// Initialize the platforms that the jumper jumps on void GameScene::initPlatforms(void) { // CCLog("initPlatforms"); isPowerPicked = false; currentPlatformTag = kPlatformsStartTag; while(currentPlatformTag < kPlatformsStartTag + kNumPlatforms) { initPlatform(); currentPlatformTag++; } resetPlatforms(); }
// Initialize the platforms that the bird jumps on void GameScene::initPlatforms(void) { CCLog("initPlatforms"); currentPlatformTag = kPlatformsStartTag; while(currentPlatformTag < kPlatformsStartTag + kNumPlatforms) { initPlatform(); currentPlatformTag++; } resetPlatforms(); }
platform_s* createPlatform(room_s* r, vect3Di_s orig, vect3Di_s dest, bool BAF) { if(!r)return NULL; int i; for(i=0;i<NUMPLATFORMS;i++) { if(!platform[i].used) { initPlatform(&platform[i],r,orig,dest,i,BAF); return &platform[i]; } } return NULL; }
int main(int argc, char **argv) { initPlatform(); initConfig(); std::vector<Common::UString> args; Common::Platform::getParameters(argc, argv, args); Common::UString target; int code; if (!parseCommandline(args, target, code)) return code; // Check the requested target if (target.empty() || !ConfigMan.hasGame(target)) { Common::UString path = ConfigMan.getString("path"); if (path.empty()) { if (ConfigMan.getBool("listdebug", false)) { listDebug(); return 0; } error("Neither an existing target, nor a path specified"); } bool useExisting = false; if (target.empty()) { target = ConfigMan.findGame(path); if (!target.empty()) { warning("No target specified, but found a target with a matching path"); useExisting = true; } } target = ConfigMan.createGame(path, target); if (target.empty()) error("Failed creating a new config target for the game"); if (!useExisting) warning("Creating a new target for this game"); } if (!ConfigMan.setGame(target) || !ConfigMan.isInGame()) error("No target \"%s\" in the config file", target.c_str()); /* Open the log file. * * NOTE: A log is opened by default, unless the logfile config value * is set to an empty string or nologfile is set to true. */ Common::UString logFile = DebugMan.getDefaultLogFile(); if (ConfigMan.hasKey("logfile")) logFile = ConfigMan.getString("logfile"); if (ConfigMan.getBool("nologfile", false)) logFile.clear(); if (!logFile.empty()) if (!DebugMan.openLogFile(logFile)) warning("Failed to open log file \"%s\" for writing", logFile.c_str()); DebugMan.logCommandLine(args); status("Target \"%s\"", target.c_str()); Common::UString dirArg = ConfigMan.getString("path"); if (dirArg.empty()) error("Target \"%s\" is missing a path", target.c_str()); Common::UString baseDir; try { baseDir = Common::FilePath::canonicalize(dirArg); } catch (...) { error("Invalid path \"%s\"", dirArg.c_str()); } if (!Common::FilePath::isDirectory(baseDir) && !Common::FilePath::isRegularFile(baseDir)) error("No such file or directory \"%s\"", baseDir.c_str()); Engines::GameThread *gameThread = new Engines::GameThread; try { // Enable requested debug channels initDebug(); // Initialize all necessary subsystems init(); // Probe and create the game engine gameThread->init(baseDir); if (ConfigMan.getBool("listdebug", false)) { // List debug channels listDebug(); } else { // Run the game gameThread->run(); EventMan.runMainLoop(); } } catch (...) { EventMan.raiseFatalError(); Common::exceptionDispatcherError(); } if (EventMan.fatalErrorRaised()) std::exit(1); status("Shutting down"); try { delete gameThread; } catch (...) { } try { // Configs changed, we should save them if (ConfigMan.changed()) { // But don't clobber a broken save if (!configFileIsBroken) ConfigMan.save(); } } catch (...) { Common::exceptionDispatcherError(); } deinit(); return 0; }
int goahead_main(int argc, char **argv) { char *argp, *home, *documents, *endpoints, *endpoint, *route, *auth, *tok, *lspec; int argind; #if WINDOWS if (windowsInit() < 0) { return 0; } #endif route = "/nand/route.txt"; auth = "/nand/auth.txt"; for (argind = 1; argind < argc; argind++) { argp = argv[argind]; if (*argp != '-') { break; } else if (smatch(argp, "--auth") || smatch(argp, "-a")) { auth = argv[++argind]; #if ME_UNIX_LIKE && !MACOSX } else if (smatch(argp, "--background") || smatch(argp, "-b")) { websSetBackground(1); #endif } else if (smatch(argp, "--debugger") || smatch(argp, "-d") || smatch(argp, "-D")) { websSetDebug(1); } else if (smatch(argp, "--home")) { if (argind >= argc) usage(); home = argv[++argind]; if (chdir(home) < 0) { error("Can't change directory to %s", home); exit(-1); } } else if (smatch(argp, "--log") || smatch(argp, "-l")) { if (argind >= argc) usage(); logSetPath(argv[++argind]); } else if (smatch(argp, "--verbose") || smatch(argp, "-v")) { logSetPath("stdout:2"); } else if (smatch(argp, "--route") || smatch(argp, "-r")) { route = argv[++argind]; } else if (smatch(argp, "--version") || smatch(argp, "-V")) { printf("%s\n", ME_VERSION); exit(0); } else if (*argp == '-' && isdigit((uchar) argp[1])) { lspec = sfmt("stdout:%s", &argp[1]); logSetPath(lspec); wfree(lspec); } else { usage(); } } documents = ME_GOAHEAD_DOCUMENTS; if (argc > argind) { documents = argv[argind++]; } initPlatform(); if (websOpen(documents, route) < 0) { error("Can't initialize server. Exiting."); return -1; } if (websLoad(auth) < 0) { error("Can't load %s", auth); return -1; } logHeader(); if (argind < argc) { while (argind < argc) { endpoint = argv[argind++]; if (websListen(endpoint) < 0) { return -1; } } } else { endpoints = sclone(ME_GOAHEAD_LISTEN); for (endpoint = stok(endpoints, ", \t", &tok); endpoint; endpoint = stok(NULL, ", \t,", &tok)) { #if !ME_COM_SSL if (strstr(endpoint, "https")) continue; #endif if (websListen(endpoint) < 0) { return -1; } } wfree(endpoints); } #if ME_ROM && KEEP /* If not using a route/auth config files, then manually create the routes like this: If custom matching is required, use websSetRouteMatch. If authentication is required, use websSetRouteAuth. */ websAddRoute("/", "file", 0); #endif #if ME_UNIX_LIKE && !MACOSX /* Service events till terminated */ if (websGetBackground()) { if (daemon(0, 0) < 0) { error("Can't run as daemon"); return -1; } } #endif websServiceEvents(&finished); logmsg(1, "Instructed to exit"); websClose(); #if WINDOWS windowsClose(); #endif return 0; }
int HK_CALL main(int argc, const char** argv) { // // Do platform specific initialization // #if !defined(HK_PLATFORM_WIN32) extern void initPlatform(); initPlatform(); #endif // // Initialize the base system including our memory system // hkPoolMemory* memoryManager = new hkPoolMemory(); hkThreadMemory* threadMemory = new hkThreadMemory(memoryManager); hkBaseSystem::init( memoryManager, threadMemory, errorReport ); memoryManager->removeReference(); // We now initialize the stack area to 100k (fast temporary memory to be used by the engine). char* stackBuffer; { int stackSize = 0x100000; stackBuffer = hkAllocate<char>( stackSize, HK_MEMORY_CLASS_BASE); hkThreadMemory::getInstance().setStackArea( stackBuffer, stackSize); } { // // Initialize the multi-threading classes, hkJobQueue, and hkJobThreadPool // // They can be used for all Havok multithreading tasks. In this exmaple we only show how to use // them for physics, but you can reference other multithreading demos in the demo framework // to see how to multithread other products. The model of usage is the same as for physics. // The hkThreadpool has a specified number of threads that can run Havok jobs. These can work // alongside the main thread to perform any Havok multi-threadable computations. // The model for running Havok tasks in Spus and in auxilary threads is identical. It is encapsulated in the // class hkJobThreadPool. On PLAYSTATION(R)3 we initialize the SPU version of this class, which is simply a SPURS taskset. // On other multi-threaded platforms we initialize the CPU version of this class, hkCpuJobThreadPool, which creates a pool of threads // that run in exactly the same way. On the PLAYSTATION(R)3 we could also create a hkCpuJobThreadPool. However, it is only // necessary (and advisable) to use one Havok PPU thread for maximum efficiency. In this case we simply use this main thread // for this purpose, and so do not create a hkCpuJobThreadPool. hkJobThreadPool* threadPool; // We can cap the number of threads used - here we use the maximum for whatever multithreaded platform we are running on. This variable is // set in the following code sections. int totalNumThreadsUsed; #if defined HK_PLATFORM_PS3_PPU hkSpuJobThreadPoolCinfo threadPoolCinfo; extern CellSpurs* initSpurs(); HK_CELL_SPURS* spurs = initSpurs(); hkSpuUtil* spuUtil = new hkSpuUtil( spurs ); spuUtil->attachHelperThreadToSpurs(); threadPoolCinfo.m_spuUtil = spuUtil; threadPoolCinfo.m_numSpus = 6; // Use all 6 SPUs for this example totalNumThreadsUsed = 1; // only use one CPU thread for PS3. // This line enables timers collection, by allocating 200 Kb per thread. If you leave this at its default (0), // timer collection will not be enabled. threadPoolCinfo.m_perSpuMontiorBufferSize = 200000; threadPool = new hkSpuJobThreadPool( threadPoolCinfo ); spuUtil->removeReference(); #else // Get the number of physical threads available on the system hkHardwareInfo hwInfo; hkGetHardwareInfo(hwInfo); totalNumThreadsUsed = hwInfo.m_numThreads; // We use one less than this for our thread pool, because we must also use this thread for our simulation hkCpuJobThreadPoolCinfo threadPoolCinfo; threadPoolCinfo.m_numThreads = totalNumThreadsUsed - 1; // This line enables timers collection, by allocating 200 Kb per thread. If you leave this at its default (0), // timer collection will not be enabled. threadPoolCinfo.m_timerBufferPerThreadAllocation = 200000; threadPool = new hkCpuJobThreadPool( threadPoolCinfo ); #endif // We also need to create a Job queue. This job queue will be used by all Havok modules to run multithreaded work. // Here we only use it for physics. hkJobQueueCinfo info; info.m_jobQueueHwSetup.m_numCpuThreads = totalNumThreadsUsed; hkJobQueue* jobQueue = new hkJobQueue(info); // // Enable monitors for this thread. // // Monitors have been enabled for thread pool threads already (see above comment). hkMonitorStream::getInstance().resize(200000); // // <PHYSICS-ONLY>: Create the physics world. // At this point you would initialize any other Havok modules you are using. // hkpWorld* physicsWorld; { // The world cinfo contains global simulation parameters, including gravity, solver settings etc. hkpWorldCinfo worldInfo; // Set the simulation type of the world to multi-threaded. worldInfo.m_simulationType = hkpWorldCinfo::SIMULATION_TYPE_MULTITHREADED; // Flag objects that fall "out of the world" to be automatically removed - just necessary for this physics scene worldInfo.m_broadPhaseBorderBehaviour = hkpWorldCinfo::BROADPHASE_BORDER_REMOVE_ENTITY; physicsWorld = new hkpWorld(worldInfo); // Disable deactivation, so that you can view timers in the VDB. This should not be done in your game. physicsWorld->m_wantDeactivation = false; // When the simulation type is SIMULATION_TYPE_MULTITHREADED, in the debug build, the sdk performs checks // to make sure only one thread is modifying the world at once to prevent multithreaded bugs. Each thread // must call markForRead / markForWrite before it modifies the world to enable these checks. physicsWorld->markForWrite(); // Register all collision agents, even though only box - box will be used in this particular example. // It's important to register collision agents before adding any entities to the world. hkpAgentRegisterUtil::registerAllAgents( physicsWorld->getCollisionDispatcher() ); // We need to register all modules we will be running multi-threaded with the job queue physicsWorld->registerWithJobQueue( jobQueue ); // Create all the physics rigid bodies setupPhysics( physicsWorld ); } // // Initialize the VDB // hkArray<hkProcessContext*> contexts; // <PHYSICS-ONLY>: Register physics specific visual debugger processes // By default the VDB will show debug points and lines, however some products such as physics and cloth have additional viewers // that can show geometries etc and can be enabled and disabled by the VDB app. hkpPhysicsContext* context; { // The visual debugger so we can connect remotely to the simulation // The context must exist beyond the use of the VDB instance, and you can make // whatever contexts you like for your own viewer types. context = new hkpPhysicsContext(); hkpPhysicsContext::registerAllPhysicsProcesses(); // all the physics viewers context->addWorld(physicsWorld); // add the physics world so the viewers can see it contexts.pushBack(context); // Now we have finished modifying the world, release our write marker. physicsWorld->unmarkForWrite(); } hkVisualDebugger* vdb = new hkVisualDebugger(contexts); vdb->serve(); // // Simulate the world for 1 minute. // // Take fixed time steps of 1/60th of a second. // This works well if your game runs solidly at 60Hz. If your game runs at 30Hz // you can take either 2 60Hz steps or 1 30Hz step. Note that at lower frequencies (i.e. 30 Hz) // more bullet through paper issues appear, and constraints will not be as stiff. // If you run at variable frame rate, or are likely to drop frames, you can consider // running your physics for a variable number of steps based on the system clock (i.e. last frame time). // Please refer to the user guide section on time stepping for a full treatment of this issue. // A stopwatch for waiting until the real time has passed hkStopwatch stopWatch; stopWatch.start(); hkReal lastTime = stopWatch.getElapsedSeconds(); hkReal timestep = 1.f / 60.f; int numSteps = int(60.f / timestep); for ( int i = 0; i < numSteps; ++i ) { // <PHYSICS-ONLY>: // Step the physics world. This single call steps using this thread and all threads // in the threadPool. For other products you add jobs, call process all jobs and wait for completion. // See the multithreading chapter in the user guide for details { physicsWorld->stepMultithreaded( jobQueue, threadPool, timestep ); } // Step the visual debugger. We first synchronize the timer data context->syncTimers( threadPool ); vdb->step(); // Clear accumulated timer data in this thread and all slave threads hkMonitorStream::getInstance().reset(); threadPool->clearTimerData(); // <PHYSICS-ONLY>: Display the sphereRigidBody position to the console every second if (i % 60 == 0) { hkVector4 pos = g_ball->getPosition(); printf("[%f,%f,%f]\n", pos(0), pos(1), pos(2)); } // Pause until the actual time has passed while (stopWatch.getElapsedSeconds() < lastTime + timestep); lastTime += timestep; // Step the graphics display (none in this demo). } // // Clean up physics and graphics // // <PHYSICS-ONLY>: cleanup physics { physicsWorld->markForWrite(); physicsWorld->removeReference(); } vdb->removeReference(); // Contexts are not reference counted at the base class level by the VDB as // they are just interfaces really. So only delete the context after you have // finished using the VDB. context->removeReference(); delete jobQueue; // // Clean up the thread pool // threadPool->removeReference(); #if defined HK_PLATFORM_PS3_PPU extern void quitSpurs( CellSpurs* spurs ); quitSpurs( spurs ); #endif } // Deallocate stack area threadMemory->setStackArea(0, 0); hkDeallocate(stackBuffer); threadMemory->removeReference(); // Quit base system hkBaseSystem::quit(); return 0; }
MAIN(goahead, int argc, char **argv, char **envp) { char *argp, *auth, *home, *documents, *endpoints, *endpoint, *route, *tok; int argind; route = "route.txt"; auth = "auth.txt"; for (argind = 1; argind < argc; argind++) { argp = argv[argind]; if (*argp != '-') { break; } else if (smatch(argp, "--auth") || smatch(argp, "-a")) { if (argind >= argc) usage(); auth = argv[++argind]; } else if (smatch(argp, "--background") || smatch(argp, "-b")) { websSetBackground(1); } else if (smatch(argp, "--debugger") || smatch(argp, "-d") || smatch(argp, "-D")) { websSetDebug(1); } else if (smatch(argp, "--home")) { if (argind >= argc) usage(); home = argv[++argind]; if (chdir(home) < 0) { error("Can't change directory to %s", home); exit(-1); } } else if (smatch(argp, "--log") || smatch(argp, "-l")) { if (argind >= argc) usage(); logSetPath(argv[++argind]); } else if (smatch(argp, "--verbose") || smatch(argp, "-v")) { logSetPath("stdout:2"); } else if (smatch(argp, "--route") || smatch(argp, "-r")) { route = argv[++argind]; } else if (smatch(argp, "--version") || smatch(argp, "-V")) { printf("%s: %s-%s\n", BIT_PRODUCT, BIT_VERSION, BIT_BUILD_NUMBER); exit(0); } else { usage(); } } documents = BIT_GOAHEAD_DOCUMENTS; if (argc > argind) { documents = argv[argind++]; } initPlatform(); if (websOpen(documents, route) < 0) { error("Can't initialize server. Exiting."); return -1; } logHeader(); if (websLoad(auth) < 0) { error("Can't load %s", auth); return -1; } if (argind < argc) { while (argind < argc) { endpoint = argv[argind++]; if (websListen(endpoint) < 0) { return -1; } } } else { endpoints = sclone(BIT_GOAHEAD_LISTEN); for (endpoint = stok(endpoints, ", \t", &tok); endpoint; endpoint = stok(NULL, ", \t,", &tok)) { if (websListen(endpoint) < 0) { return -1; } } wfree(endpoints); } websDefineHandler("test", testHandler, 0, 0); websAddRoute("/test", "test", 0); #if BIT_GOAHEAD_LEGACY websUrlHandlerDefine("/legacy/", 0, 0, legacyTest, 0); #endif #if BIT_GOAHEAD_JAVASCRIPT websDefineJst("aspTest", aspTest); websDefineJst("bigTest", bigTest); #endif websDefineAction("test", actionTest); websDefineAction("sessionTest", sessionTest); websDefineAction("showTest", showTest); #if BIT_GOAHEAD_UPLOAD websDefineAction("uploadTest", uploadTest); #endif #if BIT_UNIX_LIKE /* Service events till terminated */ if (websGetBackground()) { if (daemon(0, 0) < 0) { error("Can't run as daemon"); return -1; } } #endif websServiceEvents(&finished); trace(1, "Instructed to exit\n"); websClose(); return 0; }
void boot(int biosdev) { zeroBSS(); mallocInit(0, 0, 0, mallocError); #if MUST_ENABLE_A20 // Enable A20 gate before accessing memory above 1 MB. if (fastEnableA20() != 0) { enableA20(); // Fast enable failed. Try legacy method. } #endif bool haveCABootPlist = false; bool quietBootMode = true; void *fileLoadBuffer = (void *)kLoadAddr; char bootFile[256]; char rootUUID[37]; char * kernelFlags = NULL; const char * val; int length = 0; int kernelFlagsLength = 0; bootFile[0] = '\0'; rootUUID[0] = '\0'; #if PRE_LINKED_KERNEL_SUPPORT bool mayUseKernelCache = false; long flags, cachetime; #endif initPlatform(biosdev); // Passing on the boot drive. #if DEBUG_STATE_ENABLED // Don't switch graphics mode / show boot logo when DEBUG is set to 1. printf("\ngArchCPUType (CPU): %s\n", (gArchCPUType == CPU_TYPE_X86_64) ? "x86_64" : "i386"); sleep(3); // Silent sleep. #else showBootLogo(); #endif // A bit ugly maybe, but this will be changed sometime soon. while (readKeyboardStatus()) { int key = (bgetc() & 0xff); if ((key |= 0x20) == 'r') { gPlatform.BootRecoveryHD = true; } } initPartitionChain(); #define loadCABootPlist() loadSystemConfig(&bootInfo->bootConfig) // Loading: /Library/Preferences/SystemConfiguration/com.apple.Boot.plist // TODO: Check if everything works <i>without</i> having this plist. if (loadCABootPlist() == STATE_SUCCESS) { _BOOT_DEBUG_DUMP("com.apple.Boot.plist located.\n"); // Load successful. Change state accordantly. haveCABootPlist = true; // Checked <i>before</i> calling key functions. // Check the value of <key>Kernel Flags</key> for stuff we are interested in. // Note: We need to know about: arch= and the boot flags: -s, -v, -f and -x if (getValueForKey(kKernelFlagsKey, &val, &kernelFlagsLength, &bootInfo->bootConfig)) { // "Kernel Flags" key found. Check length to see if we have anything to work with. if (kernelFlagsLength) { kernelFlagsLength++; // Yes. Allocate memory for it and copy the kernel flags into it. kernelFlags = malloc(kernelFlagsLength); strlcpy(kernelFlags, val, kernelFlagsLength); // Is 'arch=<i386/x86_64>' specified as kernel flag? if (getValueForBootKey(kernelFlags, "arch", &val, &length)) // && len >= 4) { gArchCPUType = (strncmp(val, "x86_64", 6) == 0) ? CPU_TYPE_X86_64 : CPU_TYPE_I386; _BOOT_DEBUG_DUMP("gArchCPUType (c.a.B.plist): %s\n", (gArchCPUType == CPU_TYPE_X86_64) ? "x86_64" : "i386"); } // Check for -v (verbose) and -s (single user mode) flags. gVerboseMode = getValueForBootKey(kernelFlags, kVerboseModeFlag, &val, &length) || getValueForBootKey(kernelFlags, kSingleUserModeFlag, &val, &length); if (gVerboseMode) { #if DEBUG_BOOT == false setVideoMode(VGA_TEXT_MODE); #endif } // Check for -x (safe) and -f (flush cache) flags. if (getValueForBootKey(kernelFlags, kSafeModeFlag, &val, &length) || getValueForBootKey(kernelFlags, kIgnoreCachesFlag, &val, &length)) { gBootMode = kBootModeSafe; } // Is 'boot-uuid=<value>' specified as kernel flag? if (getValueForBootKey(kernelFlags, kBootUUIDKey, &val, &length) && length == 36) { _BOOT_DEBUG_DUMP("Target boot-uuid=<%s>\n", val); // Yes. Copy its value into rootUUID. strlcpy(rootUUID, val, 37); } /* else { strlcpy(rootUUID, "3453E0E5-017B-38AD-A0AA-D0BBD8565D6", 37); _BOOT_DEBUG_DUMP("Target boot-uuid=<%s>\n", rootUUID); } */ } } #if PRE_LINKED_KERNEL_SUPPORT /* Look for 'Kernel Cache' key. */ if (getValueForKey(kKernelCacheKey, &val, &length, &bootInfo->bootConfig)) { _BOOT_DEBUG_DUMP("Kernel Cache set to: %s\n", val); // Key found. Check if the given filepath/name exists. if (length && GetFileInfo(NULL, val, &flags, &cachetime) == 0) { // File located. Init kernelCacheFile so that we can use it as boot file. gPlatform.KernelCachePath = strdup(val); // Set flag to inform the load process to skip parts of the code. gPlatform.KernelCacheSpecified = true; _BOOT_DEBUG_DUMP("kernelcache file found.\n"); } _BOOT_DEBUG_ELSE_DUMP("Error: kernelcache file not found.\n"); } // _BOOT_DEBUG_ELSE_DUMP("No 'Kernel Cache' key given.\n"); #endif /* Enable touching of a single BIOS device by setting 'Scan Single Drive' to yes. if (getBoolForKey(kScanSingleDriveKey, &gScanSingleDrive, &bootInfo->bootConfig) && gScanSingleDrive) { gScanSingleDrive = true; } */ } else { _BOOT_DEBUG_DUMP("No com.apple.Boot.plist found.\n"); } // Was a target drive (per UUID) specified in com.apple.Boot.plist? if (rootUUID[0] == '\0') { _BOOT_DEBUG_DUMP("No UUID specified in com.apple.Boot.plist\n"); // No, so are we booting from a System Volume? if (gPlatform.BootVolume->flags & kBVFlagSystemVolume) { _BOOT_DEBUG_DUMP("Booting from a System Volume, getting UUID.\n"); // Yes, then let's get the UUID. if (HFSGetUUID(gPlatform.BootVolume, rootUUID) == STATE_SUCCESS) { _BOOT_DEBUG_DUMP("Success [%s]\n", rootUUID); } } else // Booting from USB-stick or SDboot media. { _BOOT_DEBUG_DUMP("Booting from a Non System Volume, getting UUID.\n"); // Get target System Volume and UUID in one go. BVRef rootVolume = getTargetRootVolume(rootUUID); if (rootVolume) { _BOOT_DEBUG_DUMP("Success [%s]\n", rootUUID); gPlatform.RootVolume = rootVolume; } } // This should never happen, but just to be sure. if (rootUUID[0] == '\0') { _BOOT_DEBUG_DUMP("Failed to get UUID for System Volume.\n"); if (!gVerboseMode) { // Force verbose mode when we didn't find a UUID, so // that people see what is going on in times of trouble. gVerboseMode = true; } } } /* * At this stage we know exactly what boot mode we're in, and which disk to boot from * any of which may or may not have been set/changed (in com.apple.Boot.plist) into a * non-default system setting and thus is this the place to update our EFI tree. */ updateEFITree(rootUUID); if (haveCABootPlist) // Check boolean before doing more time consuming tasks. { if (getBoolForKey(kQuietBootKey, &quietBootMode, &bootInfo->bootConfig) && !quietBootMode) { gBootMode = kBootModeNormal; // Reversed from: gBootMode |= kBootModeQuiet; } } // Parse args, load and start kernel. while (1) { // Initialize globals. sysConfigValid = 0; gErrors = 0; int retStatus = -1; getAndProcessBootArguments(kernelFlags); // Initialize bootFile (defaults to: mach_kernel). strcpy(bootFile, bootInfo->bootFile); #if PRE_LINKED_KERNEL_SUPPORT _BOOT_DEBUG_DUMP("gBootMode = %d\n", gBootMode); // Preliminary checks to prevent us from doing useless things. mayUseKernelCache = ((gBootMode & kBootModeSafe) == 0); _BOOT_DEBUG_DUMP("mayUseKernelCache = %s\n", mayUseKernelCache ? "true" : "false"); /* * A pre-linked kernel, or kernelcache, requires you to have all essential kexts for your * configuration, including FakeSMC.kext in: /System/Library/Extensions/ * Not in /Extra/Extensions/ because this directory will be ignored, completely when a * pre-linked kernel or kernelcache is used! * * Note: Not following this word of advise will render your system incapable of booting! */ if (mayUseKernelCache == false) { _BOOT_DEBUG_DUMP("Warning: kernelcache will be ignored!\n"); // True when 'Kernel Cache' is set in com.apple.Boot.plist if (gPlatform.KernelCacheSpecified == true) { sprintf(bootFile, "%s", bootInfo->bootFile); } } else { // True when 'Kernel Cache' is set in com.apple.Boot.plist if (gPlatform.KernelCacheSpecified == true) { _BOOT_DEBUG_DUMP("kernelcache: %s\n", gPlatform.KernelCachePath); /* * Starting with Lion, we can take a shortcut by simply pointing * the 'bootFile' to the kernel cache and we are done. */ sprintf(bootFile, "%s", gPlatform.KernelCachePath); } /* * We might have been fired up from a USB thumbdrive (kickstart boot) and * thus we have to check the kernel cache path first (might not be there). */ else if (GetFileInfo(NULL, gPlatform.KernelCachePath, &flags, &cachetime) == 0) { #if ((MAKE_TARGET_OS & LION) == LION) // Also for Mountain Lion, which has bit 2 set like Lion. _BOOT_DEBUG_DUMP("Checking for kernelcache...\n"); if (GetFileInfo(gPlatform.KernelCachePath, (char *)kKernelCache, &flags, &cachetime) == 0) { sprintf(bootFile, "%s/%s", gPlatform.KernelCachePath, kKernelCache); _BOOT_DEBUG_DUMP("Kernelcache located.\n"); } _BOOT_DEBUG_ELSE_DUMP("Failed to locate the kernelcache. Will load: %s!\n", bootInfo->bootFile); } _BOOT_DEBUG_ELSE_DUMP("Failed to locate the kernelcache (directory)!\n"); } #else // Not for (Mountain) Lion, go easy with the Snow Leopard. static char preLinkedKernelPath[128]; static char adler32Key[PLATFORM_NAME_LEN + ROOT_PATH_LEN]; unsigned long adler32 = 0; preLinkedKernelPath[0] = '\0'; _BOOT_DEBUG_DUMP("Checking for pre-linked kernel...\n"); // Zero out platform info (name and kernel root path). bzero(adler32Key, sizeof(adler32Key)); // Construct key for the pre-linked kernel checksum (generated by adler32). sprintf(adler32Key, gPlatform.ModelID); sprintf(adler32Key + PLATFORM_NAME_LEN, "%s", BOOT_DEVICE_PATH); sprintf(adler32Key + (PLATFORM_NAME_LEN + 38), "%s", bootInfo->bootFile); adler32 = Adler32((unsigned char *)adler32Key, sizeof(adler32Key)); _BOOT_DEBUG_DUMP("adler32: %08X\n", adler32); // Create path to pre-linked kernel. sprintf(preLinkedKernelPath, "%s/%s_%s.%08lX", gPlatform.KernelCachePath, kKernelCache, ((gArchCPUType == CPU_TYPE_X86_64) ? "x86_64" : "i386"), adler32); // Check if this file exists. if ((GetFileInfo(NULL, preLinkedKernelPath, &flags, &cachetime) == 0) && ((flags & kFileTypeMask) == kFileTypeFlat)) { _BOOT_DEBUG_DUMP("Pre-linked kernel cache located!\nLoading pre-linked kernel: %s\n", preLinkedKernelPath); // Returns -1 on error, or the actual filesize. if (LoadFile((const char *)preLinkedKernelPath)) { retStatus = 1; fileLoadBuffer = (void *)kLoadAddr; bootFile[0] = 0; } _BOOT_DEBUG_ELSE_DUMP("Failed to load the pre-linked kernel. Will load: %s!\n", bootInfo->bootFile); } _BOOT_DEBUG_ELSE_DUMP("Failed to locate the pre-linked kernel!\n"); } _BOOT_DEBUG_ELSE_DUMP("Failed to locate the cache directory!\n"); }
MAIN(goahead, int argc, char **argv, char **envp) { char *argp, *auth, *home, *documents, *endpoints, *endpoint, *route, *tok, *lspec; int argind, duration; route = "route.txt"; auth = "auth.txt"; duration = 0; for (argind = 1; argind < argc; argind++) { argp = argv[argind]; if (*argp != '-') { break; } else if (smatch(argp, "--auth") || smatch(argp, "-a")) { if (argind >= argc) usage(); auth = argv[++argind]; #if ME_UNIX_LIKE && !MACOSX } else if (smatch(argp, "--background") || smatch(argp, "-b")) { websSetBackground(1); #endif } else if (smatch(argp, "--debugger") || smatch(argp, "-d") || smatch(argp, "-D")) { websSetDebug(1); } else if (smatch(argp, "--duration")) { if (argind >= argc) usage(); duration = atoi(argv[++argind]); } else if (smatch(argp, "--home")) { if (argind >= argc) usage(); home = argv[++argind]; if (chdir(home) < 0) { error("Cannot change directory to %s", home); exit(-1); } } else if (smatch(argp, "--log") || smatch(argp, "-l")) { if (argind >= argc) usage(); logSetPath(argv[++argind]); } else if (smatch(argp, "--verbose") || smatch(argp, "-v")) { logSetPath("stdout:2"); } else if (smatch(argp, "--route") || smatch(argp, "-r")) { route = argv[++argind]; } else if (smatch(argp, "--version") || smatch(argp, "-V")) { printf("%s\n", ME_VERSION); exit(0); } else if (*argp == '-' && isdigit((uchar) argp[1])) { lspec = sfmt("stdout:%s", &argp[1]); logSetPath(lspec); wfree(lspec); } else { usage(); } } documents = ME_GOAHEAD_DOCUMENTS; if (argc > argind) { documents = argv[argind++]; } initPlatform(); if (websOpen(documents, route) < 0) { error("Cannot initialize server. Exiting."); return -1; } logHeader(); if (websLoad(auth) < 0) { error("Cannot load %s", auth); return -1; } if (argind < argc) { while (argind < argc) { endpoint = argv[argind++]; if (websListen(endpoint) < 0) { return -1; } } } else { endpoints = sclone(ME_GOAHEAD_LISTEN); for (endpoint = stok(endpoints, ", \t", &tok); endpoint; endpoint = stok(NULL, ", \t,", &tok)) { if (websListen(endpoint) < 0) { return -1; } } wfree(endpoints); } websDefineHandler("test", testHandler, 0, 0, 0); websAddRoute("/test", "test", 0); #if ME_GOAHEAD_LEGACY websUrlHandlerDefine("/legacy/", 0, 0, legacyTest, 0); #endif #if ME_GOAHEAD_JAVASCRIPT websDefineJst("aspTest", aspTest); websDefineJst("bigTest", bigTest); #endif websDefineAction("test", actionTest); websDefineAction("sessionTest", sessionTest); websDefineAction("showTest", showTest); #if ME_GOAHEAD_UPLOAD && !ME_ROM websDefineAction("uploadTest", uploadTest); #endif #if ME_UNIX_LIKE && !MACOSX /* Service events till terminated */ if (websGetBackground()) { if (daemon(0, 0) < 0) { error("Cannot run as daemon"); return -1; } } #endif if (duration) { printf("Running for %d secs\n", duration); websStartEvent(duration * 1000, (WebsEventProc) exitProc, 0); } websServiceEvents(&finished); logmsg(1, "Instructed to exit\n"); websClose(); return 0; }
//---------------------------------------------------------- // System initialization //---------------------------------------------------------- static inline void initSystem(void) { bool success; (void)success; // disable interrupts: disabled on msp430 by default, but other systems might need this DISABLE_INTS(); // stop the watchdog: GCC disables it by default, but other compilers might not be so helpful watchdogStop(); // TODO: init dynamic memory // platformMemInit(); // basic, platform-specific initialization: timers, platform-specific drivers (?) initPlatform(); // start energy accounting (as soon as timers are initialized) energyConsumerOn(ENERGY_CONSUMER_MCU); #ifdef USE_PRINT // init printing to serial (makes sense only after clock has been calibrated) if (printInit != NULL) printInit(); #endif INIT_PRINTF("starting MansOS...\n"); #ifdef USE_LEDS INIT_PRINTF("init LED(s)...\n"); ledsInit(); #endif #ifdef USE_BEEPER beeperInit(); #endif #ifdef RAMTEXT_START if ((MemoryAddress_t)&_end > RAMTEXT_START) { // Panic right aways on RAM overflow. // In case this happens, you might want to increase the address // specified by CONST_RAMTEXT_START in config file assertionFailed("Overflow between .data and .ramtext sections", __FILE__, __LINE__); } #endif #ifdef USE_ADC if (adcInit != NULL) { INIT_PRINTF("init ADC...\n"); adcInit(); } #endif #ifdef USE_RANDOM INIT_PRINTF("init RNG...\n"); randomInit(); #endif #if USE_ALARMS INIT_PRINTF("init alarms...\n"); initAlarms(); #endif #ifdef USE_RADIO INIT_PRINTF("init radio...\n"); radioInit(); #endif #ifdef USE_ADDRESSING INIT_PRINTF("init communication stack...\n"); networkingInit(); #endif #ifdef USE_EXT_FLASH INIT_PRINTF("init external flash...\n"); extFlashInit(); #endif #ifdef USE_SDCARD INIT_PRINTF("init SD card...\n"); sdcardInit(); #endif #ifdef USE_EEPROM INIT_PRINTF("init EEPROM...\n"); eepromInit(); #endif #ifdef USE_ISL29003 INIT_PRINTF("init ISL light sensor...\n"); success = islInit(); if (!success) { INIT_PRINTF("ISL init failed!\n"); } #endif #ifdef USE_ADS1115 INIT_PRINTF("init ADS111x ADC converter chip...\n"); adsInit(); #endif #if USE_ADS8638 INIT_PRINTF("init ADS8638 ADC converter chip...\n"); ads8638Init(); #endif #if USE_ADS8328 INIT_PRINTF("init ADS8328 ADC converter chip...\n"); ads8328Init(); #endif #if USE_AD5258 INIT_PRINTF("init AD5258 digital potentiometer...\n"); ad5258Init(); #endif #if USE_DAC7718 INIT_PRINTF("init DAC7718 DAC converter chip...\n"); dac7718Init(); #endif #if USE_ISL1219 INIT_PRINTF("init ISL1219 real-time clock chip...\n"); isl1219Init(); #endif #ifdef USE_HUMIDITY INIT_PRINTF("init humidity sensor...\n"); humidityInit(); #endif #ifdef USE_ACCEL INIT_PRINTF("init accelerometer...\n"); accelInit(); #endif #ifdef USE_TIMESYNC INIT_PRINTF("init base station time sync...\n"); timesyncInit(); #endif #ifdef USE_SMP INIT_PRINTF("init SSMP...\n"); smpInit(); #endif #ifdef USE_REPROGRAMMING INIT_PRINTF("init reprogramming...\n"); bootParamsInit(); #endif #ifdef USE_DCO_RECALIBRATION extern void dcoRecalibrationInit(void); INIT_PRINTF("init DCO recalibration...\n"); dcoRecalibrationInit(); #endif #ifdef USE_FS INIT_PRINTF("init file system...\n"); fsInit(); #endif #ifdef USE_FATFS INIT_PRINTF("init FAT file system...\n"); fatFsInit(); INIT_PRINTF("init POSIX-like file routines...\n"); posixStdioInit(); #endif #ifdef USE_WMP INIT_PRINTF("init WMP...\n"); wmpInit(); #endif #ifdef USE_SEAL_NET INIT_PRINTF("init SEAL networking...\n"); sealNetInit(); #endif INIT_PRINTF("starting the application...\n"); }