コード例 #1
0
ファイル: ch.c プロジェクト: hsteinhaus/ChibiOS
/**
 * @brief   Initializes the kernel.
 * @details Initializes the kernel structures, the current instructions flow
 *          becomes the idle thread upon return. The idle thread must not
 *          invoke any kernel primitive able to change state to not runnable.
 * @note    This function assumes that the @p nil global variable has been
 *          zeroed by the runtime environment. If this is not the case then
 *          make sure to clear it before calling this function.
 *
 * @special
 */
void chSysInit(void) {
  thread_t *tp;
  const thread_config_t *tcp;

#if CH_DBG_SYSTEM_STATE_CHECK == TRUE
  nil.isr_cnt  = (cnt_t)0;
  nil.lock_cnt = (cnt_t)0;
#endif

  /* System initialization hook.*/
  CH_CFG_SYSTEM_INIT_HOOK();

  /* Iterates through the list of defined threads.*/
  tp = &nil.threads[0];
  tcp = nil_thd_configs;
  while (tp < &nil.threads[CH_CFG_NUM_THREADS]) {
#if CH_DBG_ENABLE_STACK_CHECK
    tp->stklimit  = (stkalign_t *)tcp->wbase;
#endif

    /* Port dependent thread initialization.*/
    PORT_SETUP_CONTEXT(tp, tcp->wbase, tcp->wend, tcp->funcp, tcp->arg);

    /* Initialization hook.*/
    CH_CFG_THREAD_EXT_INIT_HOOK(tp);

    tp++;
    tcp++;
  }

#if CH_DBG_ENABLE_STACK_CHECK
  /* The idle thread is a special case because its stack is set up by the
     runtime environment.*/
  tp->stklimit  = THD_IDLE_BASE;
#endif

  /* Interrupts partially enabled. It is equivalent to entering the
     kernel critical zone.*/
  chSysSuspend();
#if CH_DBG_SYSTEM_STATE_CHECK == TRUE
  nil.lock_cnt = (cnt_t)1;
#endif

  /* Heap initialization, if enabled.*/
#if CH_CFG_USE_HEAP == TRUE
  _heap_init();
#endif

  /* Port layer initialization last because it depend on some of the
     initializations performed before.*/
  port_init();

  /* Runs the highest priority thread, the current one becomes the idle
     thread.*/
  nil.current = nil.next = nil.threads;
  port_switch(nil.current, tp);
  chSysUnlock();
}
コード例 #2
0
ファイル: chsys.c プロジェクト: Tambralinga/ChibiOS
/**
 * @brief   ChibiOS/RT initialization.
 * @details After executing this function the current instructions stream
 *          becomes the main thread.
 * @pre     Interrupts must disabled before invoking this function.
 * @post    The main thread is created with priority @p NORMALPRIO and
 *          interrupts are enabled.
 *
 * @special
 */
void chSysInit(void) {
#if CH_DBG_ENABLE_STACK_CHECK == TRUE
  extern stkalign_t __main_thread_stack_base__;
#endif

  port_init();
  _scheduler_init();
  _vt_init();
#if CH_CFG_USE_TM == TRUE
  _tm_init();
#endif
#if CH_CFG_USE_MEMCORE == TRUE
  _core_init();
#endif
#if CH_CFG_USE_HEAP == TRUE
  _heap_init();
#endif
#if CH_DBG_STATISTICS == TRUE
  _stats_init();
#endif
#if CH_DBG_ENABLE_TRACE == TRUE
  _dbg_trace_init();
#endif

#if CH_CFG_NO_IDLE_THREAD == FALSE
  /* Now this instructions flow becomes the main thread.*/
  setcurrp(_thread_init(&ch.mainthread, NORMALPRIO));
#else
  /* Now this instructions flow becomes the idle thread.*/
  setcurrp(_thread_init(&ch.mainthread, IDLEPRIO));
#endif

  currp->p_state = CH_STATE_CURRENT;
#if CH_DBG_ENABLE_STACK_CHECK == TRUE
  /* This is a special case because the main thread thread_t structure is not
     adjacent to its stack area.*/
  currp->p_stklimit = &__main_thread_stack_base__;
#endif
  chSysEnable();

  /* Note, &ch_debug points to the string "main" if the registry is
     active, else the parameter is ignored.*/
  chRegSetThreadName((const char *)&ch_debug);

#if CH_CFG_NO_IDLE_THREAD == FALSE
  /* This thread has the lowest priority in the system, its role is just to
     serve interrupts in its context while keeping the lowest energy saving
     mode compatible with the system status.*/
  (void) chThdCreateStatic(ch.idle_thread_wa, sizeof(ch.idle_thread_wa),
                           IDLEPRIO, (tfunc_t)_idle_thread, NULL);
#endif
}
コード例 #3
0
ファイル: chsys.c プロジェクト: 12019/libraries
/**
 * @brief   ChibiOS/RT initialization.
 * @details After executing this function the current instructions stream
 *          becomes the main thread.
 * @pre     Interrupts must be still disabled when @p chSysInit() is invoked
 *          and are internally enabled.
 * @post    The main thread is created with priority @p NORMALPRIO.
 * @note    This function has special, architecture-dependent, requirements,
 *          see the notes into the various port reference manuals.
 *
 * @special
 */
void chSysInit(void) {
  static Thread mainthread;
#if CH_DBG_ENABLE_STACK_CHECK
  extern stkalign_t __main_thread_stack_base__;
#endif

  port_init();
  _scheduler_init();
  _vt_init();
#if CH_USE_MEMCORE
  _core_init();
#endif
#if CH_USE_HEAP
  _heap_init();
#endif
#if CH_DBG_ENABLE_TRACE
  _trace_init();
#endif

  /* Now this instructions flow becomes the main thread.*/
  setcurrp(_thread_init(&mainthread, NORMALPRIO));
  currp->p_state = THD_STATE_CURRENT;
#if CH_DBG_ENABLE_STACK_CHECK
  /* This is a special case because the main thread Thread structure is not
     adjacent to its stack area.*/
  currp->p_stklimit = &__main_thread_stack_base__;
#endif
  chSysEnable();

  chRegSetThreadName("main");

#if !CH_NO_IDLE_THREAD
  /* This thread has the lowest priority in the system, its role is just to
     serve interrupts in its context while keeping the lowest energy saving
     mode compatible with the system status.*/
  chThdCreateStatic(_idle_thread_wa, sizeof(_idle_thread_wa), IDLEPRIO,
                    (tfunc_t)_idle_thread, NULL);
#endif
}
コード例 #4
0
BOOL __cdecl
__CRTDLL_INIT(
        HANDLE  hDllHandle,
        DWORD   dwReason,
        LPVOID  lpreserved
        )
{
        BOOL term_all = FALSE;

        if ( dwReason == DLL_PROCESS_ATTACH ) {
            if ( !_heap_init() )    /* initialize heap */
                /*
                 * The heap cannot be initialized, return failure to the
                 * loader.
                 */
                return FALSE;

            if(!_mtinit())          /* initialize multi-thread */
            {
                /*
                 * If the DLL load is going to fail, we must clean up
                 * all resources that have already been allocated.
                 */
                _heap_term();       /* heap is now invalid! */

                return FALSE;       /* fail DLL load on failure */
            }

            if (_ioinit() < 0)
            {
                _mtterm();          /* free TLS index, call _mtdeletelocks() */
                _heap_term();       /* heap is now invalid! */
                return FALSE;       /* fail DLL load on failure */
            }

            _wcmdln = GetCommandLineW();

#if !defined(_CRT_APP) || defined(_KERNELX)
            _aenvptr = (char *)__crtGetEnvironmentStringsA();
            _acmdln = GetCommandLineA();
#else /* !defined(_CRT_APP) || defined(_KERNELX) */
            // We cannot call GetCommandLineA in the App CRT:
            if (!__copy_to_char(_wcmdln, &_acmdln))
            {
                _acmdln = NULL;
            }
#endif /* !defined(_CRT_APP) || defined(_KERNELX) */

#if !defined(_CRT_APP) || defined(_KERNELX)
#ifdef _MBCS
            /*
             * Initialize multibyte ctype table. Always done since it is
             * needed for processing the environment strings.
             */
            __initmbctable();
#endif  /* _MBCS */

            if (_setenvp() < 0 ||   /* get environ info */
                _cinit(FALSE) != 0)  /* do C data initialize */
            {
                term_all = TRUE;
            }
#else  /* !defined(_CRT_APP) || defined(_KERNELX) */
            if (_cinit(FALSE) != 0)  /* do C data initialize */
            {
                term_all = TRUE;
            }
#endif  /* !defined(_CRT_APP) || defined(_KERNELX) */

            if (term_all)
            {
#if defined(_CRT_APP) && !defined(_KERNELX)
                _free_crt(_acmdln);
                _acmdln = NULL;
#endif
                _ioterm();          /* shut down lowio */
                _mtterm();          /* free TLS index, call _mtdeletelocks() */
                _heap_term();       /* heap is now invalid! */
                return FALSE;       /* fail DLL load on failure */
            }

            /*
             * Increment flag indicating process attach notification
             * has been received.
             */
            proc_attached++;

        }
        else if ( dwReason == DLL_PROCESS_DETACH ) {
            /*
             * if a client process is detaching, make sure minimal
             * runtime termination is performed and clean up our
             * 'locks' (i.e., delete critical sections).
             */
            if ( proc_attached > 0 ) {
                proc_attached--;
                __try {

                    /*
                     * Any basic clean-up done here may also need
                     * to be done below if Process Attach is partly
                     * processed and then a failure is encountered.
                     */

                    if ( _C_Termination_Done == FALSE )
                        _cexit();

                    __crtdll_callstaticterminators();

                    /* Free all allocated CRT memory */
                    __freeCrtMemory();

#ifdef _DEBUG
                    /* Dump all memory leaks */
                    if (_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) & _CRTDBG_LEAK_CHECK_DF)
                    {
                        _CrtSetDumpClient(NULL);
                        _CrtDumpMemoryLeaks();
                    }
#endif  /* _DEBUG */

                    /*
                     * What remains is to clean up the system resources we have
                     * used (handles, critical sections, memory,...,etc.). This
                     * needs to be done if the whole process is NOT terminating.
                     */

                    /* If dwReason is DLL_PROCESS_DETACH, lpreserved is NULL
                     * if FreeLibrary has been called or the DLL load failed
                     * and non-NULL if the process is terminating.
                     */
                    if ( lpreserved == NULL )
                    {
#if defined(_CRT_APP) && !defined(_KERNELX)
                        _free_crt(_acmdln);
                        _acmdln = NULL;
#endif
                        /*
                         * The process is NOT terminating so we must clean up...
                         */
                        _ioterm();

                        /* free TLS index, call _mtdeletelocks() */
                        _mtterm();

                        /* This should be the last thing the C run-time does */
                        _heap_term();   /* heap is now invalid! */
                    }

                }
                __finally {
                    /* we shouldn't really have to care about this, because
                       letting an exception escape from DllMain(DLL_PROCESS_DETACH) should
                       result in process termination. Unfortunately, Windows up to Win7 as of now
                       just silently swallows the exception.

                       I have considered all kinds of tricks, but decided to leave it up to OS
                       folks to fix this.

                       For the time being just remove our FLS callback during phase 2 unwind
                       that would otherwise be left pointing to unmapped address space.
                       */
                     if ( lpreserved == NULL && __flsindex != FLS_OUT_OF_INDEXES )
                         _mtterm();
                }
            }
            else
                /* no prior process attach, just return */
                return FALSE;
コード例 #5
0
ファイル: chsys.c プロジェクト: Babody/ChibiOS
/**
 * @brief   ChibiOS/RT initialization.
 * @details After executing this function the current instructions stream
 *          becomes the main thread.
 * @pre     Interrupts must disabled before invoking this function.
 * @post    The main thread is created with priority @p NORMALPRIO and
 *          interrupts are enabled.
 *
 * @special
 */
void chSysInit(void) {
  extern stkalign_t __main_thread_stack_base__;

  _scheduler_init();
  _vt_init();

#if CH_DBG_SYSTEM_STATE_CHECK == TRUE
  ch.dbg.isr_cnt  = (cnt_t)0;
  ch.dbg.lock_cnt = (cnt_t)0;
#endif
#if CH_CFG_USE_TM == TRUE
  _tm_init();
#endif
#if CH_CFG_USE_MEMCORE == TRUE
  _core_init();
#endif
#if CH_CFG_USE_HEAP == TRUE
  _heap_init();
#endif
#if CH_DBG_STATISTICS == TRUE
  _stats_init();
#endif
#if CH_DBG_TRACE_MASK != CH_DBG_TRACE_MASK_NONE
  _dbg_trace_init();
#endif

#if CH_CFG_NO_IDLE_THREAD == FALSE
  /* Now this instructions flow becomes the main thread.*/
#if CH_CFG_USE_REGISTRY == TRUE
  currp = _thread_init(&ch.mainthread, (const char *)&ch_debug, NORMALPRIO);
#else
  currp = _thread_init(&ch.mainthread, "main", NORMALPRIO);
#endif
#else
  /* Now this instructions flow becomes the idle thread.*/
  currp = _thread_init(&ch.mainthread, "idle", IDLEPRIO);
#endif

  /* Setting up the base address of the static main thread stack.*/
  currp->stklimit = &__main_thread_stack_base__;

  /* Setting up the caller as current thread.*/
  currp->state = CH_STATE_CURRENT;

  /* Port layer initialization last because it depend on some of the
     initializations performed before.*/
  port_init();

#if CH_DBG_STATISTICS == TRUE
  /* Starting measurement for this thread.*/
  chTMStartMeasurementX(&currp->stats);
#endif

  /* It is alive now.*/
  chSysEnable();

#if CH_CFG_NO_IDLE_THREAD == FALSE
  {
    static const thread_descriptor_t idle_descriptor = {
      "idle",
      THD_WORKING_AREA_BASE(ch_idle_thread_wa),
      THD_WORKING_AREA_END(ch_idle_thread_wa),
      IDLEPRIO,
      _idle_thread,
      NULL
    };

    /* This thread has the lowest priority in the system, its role is just to
       serve interrupts in its context while keeping the lowest energy saving
       mode compatible with the system status.*/
    (void) chThdCreate(&idle_descriptor);
  }
#endif
}
コード例 #6
0
ファイル: crt0.c プロジェクト: mysticTot/learn_c
int
__tmainCRTStartup(
    void
) {
    unsigned int osplatform = 0;
    unsigned int winver = 0;
    unsigned int winmajor = 0;
    unsigned int winminor = 0;
    unsigned int osver = 0;
    int initret;
    int mainret = 0;
    OSVERSIONINFOA* posvi;
    int managedapp;
#ifdef _WINMAIN_
    _TUCHAR* lpszCommandLine;
    STARTUPINFO StartupInfo;

    __try {
        /*
        Note: MSDN specifically notes that GetStartupInfo returns no error, and throws unspecified SEH if it fails, so
        the very general exception handler below is appropriate
        */
        GetStartupInfo(&StartupInfo);
    } __except (EXCEPTION_EXECUTE_HANDLER) {
        return 255;
    }

#endif  /* _WINMAIN_ */
    /*
     * Dynamically allocate the OSVERSIONINFOA buffer, so we avoid
     * triggering the /GS buffer overrun detection.  That can't be
     * used here, since the guard cookie isn't available until we
     * initialize it from here!
     */
    posvi = (OSVERSIONINFOA*)HeapAlloc(GetProcessHeap(), 0, sizeof(OSVERSIONINFOA));

    if (!posvi) {
        fast_error_exit(_RT_HEAP);
        return 255;
    }

    /*
     * Get the full Win32 version
     */
    posvi->dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);

    if (!GetVersionExA(posvi)) {
        HeapFree(GetProcessHeap(), 0, posvi);
        return 255;
    }

    osplatform = posvi->dwPlatformId;
    winmajor = posvi->dwMajorVersion;
    winminor = posvi->dwMinorVersion;
    /*
     * The somewhat bizarre calculations of _osver and _winver are
     * required for backward compatibility (used to use GetVersion)
     */
    osver = (posvi->dwBuildNumber) & 0x07fff;
    HeapFree(GetProcessHeap(), 0, posvi);

    if (osplatform != VER_PLATFORM_WIN32_NT) {
        osver |= 0x08000;
    }

    winver = (winmajor << 8) + winminor;
    _set_osplatform(osplatform);
    _set_winver(winver);
    _set_winmajor(winmajor);
    _set_winminor(winminor);
    _set_osver(osver);
    /*
     * Determine if this is a managed application
     */
    managedapp = check_managed_app();

    if (!_heap_init(1)) {               /* initialize heap */
        fast_error_exit(_RT_HEAPINIT);    /* write message and die */
    }

    if (!_mtinit()) {                   /* initialize multi-thread */
        fast_error_exit(_RT_THREAD);    /* write message and die */
    }

    /* Enable buffer count checking if linking against static lib */
    _CrtSetCheckCount(TRUE);
    /*
     * Initialize the Runtime Checks stuff
     */
#ifdef _RTC
    _RTC_Initialize();
#endif  /* _RTC */
    /*
     * Guard the remainder of the initialization code and the call
     * to user's main, or WinMain, function in a __try/__except
     * statement.
     */

    __try {
        if (_ioinit() < 0) {            /* initialize lowio */
            _amsg_exit(_RT_LOWIOINIT);
        }

        /* get wide cmd line info */
        _tcmdln = (_TSCHAR*)GetCommandLineT();
        /* get wide environ info */
        _tenvptr = (_TSCHAR*)GetEnvironmentStringsT();

        if (_tsetargv() < 0) {
            _amsg_exit(_RT_SPACEARG);
        }

        if (_tsetenvp() < 0) {
            _amsg_exit(_RT_SPACEENV);
        }

        initret = _cinit(TRUE);                  /* do C data initialize */

        if (initret != 0) {
            _amsg_exit(initret);
        }

#ifdef _WINMAIN_
        lpszCommandLine = _twincmdln();
        mainret = _tWinMain((HINSTANCE)&__ImageBase,
                            NULL,
                            lpszCommandLine,
                            StartupInfo.dwFlags & STARTF_USESHOWWINDOW
                            ? StartupInfo.wShowWindow
                            : SW_SHOWDEFAULT
                           );
#else  /* _WINMAIN_ */
        _tinitenv = _tenviron;
        mainret = _tmain(__argc, _targv, _tenviron);
#endif  /* _WINMAIN_ */

        if (!managedapp) {
            exit(mainret);
        }

        _cexit();
    } __except (_XcptFilter(GetExceptionCode(), GetExceptionInformation())) {
        /*
         * Should never reach here
         */
        mainret = GetExceptionCode();

        if (!managedapp) {
            _exit(mainret);
        }

        _c_exit();
    } /* end of try - except */

    return mainret;
}
コード例 #7
0
ファイル: dllcrt0.c プロジェクト: mysticTot/learn_c
BOOL WINAPI _CRT_INIT(
    HANDLE  hDllHandle,
    DWORD   dwReason,
    LPVOID  lpreserved
) {
    unsigned int osplatform = 0;
    unsigned int winver = 0;
    unsigned int winmajor = 0;
    unsigned int winminor = 0;
    unsigned int osver = 0;

    /*
     * Start-up code only gets executed when the process is initialized
     */

    if (dwReason == DLL_PROCESS_ATTACH) {
        /*
         * Dynamically allocate the OSVERSIONINFOA buffer, so we avoid
         * triggering the /GS buffer overrun detection.  That can't be
         * used here, since the guard cookie isn't available until we
         * initialize it from here!
         */
        OSVERSIONINFOA* posvi =
            (OSVERSIONINFOA*)HeapAlloc(GetProcessHeap(), 0, sizeof(OSVERSIONINFOA));

        if (!posvi) {
            return FALSE;
        }

        /*
         * Get the full Win32 version
         */
        posvi->dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);

        if (!GetVersionExA(posvi)) {
            HeapFree(GetProcessHeap(), 0, posvi);
            return FALSE;
        }

        osplatform = posvi->dwPlatformId;
        winmajor = posvi->dwMajorVersion;
        winminor = posvi->dwMinorVersion;
        /*
         * The somewhat bizarre calculations of _osver and _winver are
         * required for backward compatibility (used to use GetVersion)
         */
        osver = (posvi->dwBuildNumber) & 0x07fff;
        HeapFree(GetProcessHeap(), 0, posvi);

        if (osplatform != VER_PLATFORM_WIN32_NT) {
            osver |= 0x08000;
        }

        winver = (winmajor << 8) + winminor;
        _set_osplatform(osplatform);
        _set_winver(winver);
        _set_winmajor(winmajor);
        _set_winminor(winminor);
        _set_osver(osver);

        if (!_heap_init(1)) {   /* initialize heap */
            return FALSE;    /* fail to load DLL */
        }

        if (!_mtinit()) {       /* initialize multi-thread */
            _heap_term();       /* heap is now invalid! */
            return FALSE;       /* fail to load DLL */
        }

        /*
         * Initialize the Runtime Checks stuff
         */
#ifdef _RTC
        _RTC_Initialize();
#endif  /* _RTC */
        _acmdln = (char*)GetCommandLineA();
        _aenvptr = (char*)__crtGetEnvironmentStringsA();

        if (_ioinit() < 0) {    /* initialize lowio */
            _mtterm();          /* free TLS index, call _mtdeletelocks() */
            _heap_term();       /* heap is now invalid! */
            return FALSE;       /* fail to load DLL */
        }

        if (_setargv() < 0 ||   /* get cmd line info */
                _setenvp() < 0 ||   /* get environ info */
                _cinit(FALSE) != 0) { /* do C data initialize, but don't init floating point */
            _ioterm();          /* shut down lowio */
            _mtterm();          /* free TLS index, call _mtdeletelocks() */
            _heap_term();       /* heap is now invalid! */
            return FALSE;       /* fail to load DLL */
        }

        /* Enable buffer count checking if linking against static lib */
        _CrtSetCheckCount(TRUE);
        /*
         * increment flag to indicate process attach notification
         * has been received
         */
        __proc_attached++;
    } else if (dwReason == DLL_PROCESS_DETACH) {
        if (__proc_attached > 0) {
            __proc_attached--;

            /*
             * Any basic clean-up code that goes here must be duplicated
             * below in _DllMainCRTStartup for the case where the user's
             * DllMain() routine fails on a Process Attach notification.
             * This does not include calling user C++ destructors, etc.
             */

            if (_C_Termination_Done == FALSE) {
                _cexit();
            }

#ifdef _DEBUG

            /* Dump all memory leaks */
            if (_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) & _CRTDBG_LEAK_CHECK_DF) {
                _CrtDumpMemoryLeaks();
            }

#endif  /* _DEBUG */
            /*
             * What remains is to clean up the system resources we have
             * used (handles, critical sections, memory,...,etc.). This
             * needs to be done if the whole process is NOT terminating.
             */
#ifndef _DEBUG

            if (lpreserved == NULL) {
#endif  /* _DEBUG */
                /*
                 * The process is NOT terminating so we must clean up...
                 */
                /* Shut down lowio */
                _ioterm();
                _mtterm();
                /* This should be the last thing the C run-time does */
                _heap_term();   /* heap is now invalid! */
#ifndef _DEBUG
            }

#endif  /* _DEBUG */
        } else
            /* no prior process attach, just return */
        {
            return FALSE;
        }
    } else if (dwReason == DLL_THREAD_ATTACH) {
        _ptiddata ptd;
        /* Initialize FlsGetValue function pointer */
        __set_flsgetvalue();

        if (((ptd = _calloc_crt(1, sizeof(struct _tiddata))) != NULL)) {
            if (FLS_SETVALUE(__flsindex, (LPVOID)ptd)) {
                /*
                 * Initialize of per-thread data
                 */
                _initptd(ptd, NULL);
                ptd->_tid = GetCurrentThreadId();
                ptd->_thandle = (uintptr_t)(-1);
            } else {
                _free_crt(ptd);
                return FALSE;
            }
        } else {
            return FALSE;
        }
    } else if (dwReason == DLL_THREAD_DETACH) {
        _freeptd(NULL);         /* free up per-thread CRT data */
    }

    return TRUE ;
}