bool CArgumentParser::Parse() { if(!ParseArguments()){ return false; } if(!ArgumentCheck()){ return false; } return true; }
int main(int argc, char** argv) { #ifndef RX_PREFIX #warning "No RX_PREFIX defined. Relying on RX_PREFIX @ runtime" char* RX_PREFIX = getenv("RX_PREFIX"); if(RX_PREFIX == NULL) { printf("Error: RX_PREFIX not defined, neither on compile nor on run time. Please export RX_PREFIX as the directory of the compiler executable!\n"); exit(EXIT_FAILURE); } #endif /** Check if STDLIB_R3X is given **/ char* StandardLibraryLocation = getenv("STDLIB_R3X"); if(StandardLibraryLocation!=NULL) { AddIncludeDir(StandardLibraryLocation); } ParseArguments(argc, argv); if(CompileDynamic == true) { DynamicSuffix = " -d"; } char* asmfile = ConcatenateStrings(OutputFile, ".asm"); char* ASMOutputFile = ConcatenateStrings(RX_PREFIX, ConcatenateStrings("/", asmfile)); char* TBCOutputFile = ConcatenateStrings(RX_PREFIX, "/_temp.bas"); char* GCCOptions = ConcatenateStrings("gcc -E -P -o ", ConcatenateStrings(TBCOutputFile, ConcatenateStrings(" - < ", InputFile))); char* CgenOptions = ConcatenateStrings(RX_PREFIX, ConcatenateStrings("/cgen", ConcatenateStrings(" -exe ", ConcatenateStrings("./", OutputFile)))); for(unsigned int i = 0; i < NumberOfIncludeDirs; i++) { if(IncludeDirs[i]!=NULL) { GCCOptions = ConcatenateStrings(GCCOptions, ConcatenateStrings(" -I", IncludeDirs[i])); } } char* TBCOptions = ConcatenateStrings(RX_PREFIX, ConcatenateStrings("/tbc > ", ConcatenateStrings(ASMOutputFile, ConcatenateStrings(" ", ConcatenateStrings(TBCOutputFile, DynamicSuffix))))); char* FASMOptions = ConcatenateStrings(RX_PREFIX, ConcatenateStrings("/fasm ", ConcatenateStrings(ASMOutputFile, ConcatenateStrings(" ./", OutputFile)))); /*printf("ASMOutputFile: %s\nTBCOutputFile: %s\nGCCOptions: %s\nTBCOptions: %s\nFASMOptions: %s\n", ASMOutputFile, TBCOutputFile, GCCOptions, TBCOptions, FASMOptions);*/ system(GCCOptions); system(TBCOptions); if(AsmFlag == false) { system(FASMOptions); system(CgenOptions); } else { FILE* fd = fopen(ASMOutputFile, "r+b"); fseek(fd, 0L, SEEK_END); unsigned int sz = ftell(fd); fseek(fd, 0L, SEEK_SET); char* space = calloc(sz+1, 1); fread(space, 1, sz, fd); space[sz] = 0; FILE* fp = fopen(OutputFile, "w+b"); fprintf(fp, "%s", space); fclose(fp); fclose(fd); } /**! Remove temp files **/ remove(ASMOutputFile); remove(TBCOutputFile); return 0; }
int main( int argc, char *argv[] ) { //BOOL bUseStartup, bGotCmd; BOOL bGotCmd; BLOCK bCmd; //char c; RESULTt rResult; setbuf(stdout,NULL); strcpy( GsProgramName, argv[0] ); BasicsInitialize(); GbGraphicalEnvironment = FALSE; ParseArguments( argc, argv ); ParseInit( &rResult ); bGotCmd = FALSE; bCmd = bBlockCreate(); while ( rResult.iCommand != CQUIT ) { char *line=NULL; char *cp; line = tl_getline("> "); cp = stripwhite (line); if (*cp){ gl_histadd(cp); for(; *cp; cp++) (void) bBlockAddChar( bCmd, *cp ); if ( bBlockAddChar( bCmd, '\n' ) ) { ParseBlock( bCmd, &rResult ); BlockEmpty( bCmd ); } } } while ( rResult.iCommand != CQUIT ); ParseShutdown(); LISTUNFREEDMEMORYTOLOGFILE(); exit(0); }
NETAtomicPlayer::NETAtomicPlayer(Context* context) : PlayerApp(context) { #ifdef WIN32 ParseArguments(GetCommandLineW()); #else #warning Implement Argument Parsing #endif arguments_ = GetArguments(); }
int main(int argc, char **argv) { /* Parse arguments */ if (!ParseArguments(argc, argv)) return -1; /* Print results */ if (pcFilename) printf("%s ", pcFilename); else printf("<stdin> "); printf("%g %d %d\n", dArg, iArg, iFlag); /* Return success */ return 0; }
int QueryMemberOfMain( int argc, char** ppszArgv ) { DWORD dwError = 0; dwError = ParseArguments(argc, ppszArgv); BAIL_ON_LSA_ERROR(dwError); if (gState.QueryType == LSA_QUERY_TYPE_UNDEFINED) { /* Default to querying by name */ gState.QueryType = LSA_QUERY_TYPE_BY_NAME; } if (!gState.bShowUsage) { if (!gState.dwCount) { dwError = LW_ERROR_INVALID_PARAMETER; BAIL_ON_LSA_ERROR(dwError); } dwError = QueryMemberOf(); BAIL_ON_LSA_ERROR(dwError); } error: if (gState.bShowUsage) { ShowUsage(ppszArgv[0], TRUE); } else if (dwError == LW_ERROR_INVALID_PARAMETER) { ShowUsage(ppszArgv[0], FALSE); } if (dwError) { printf("Error: %s (%x)\n", LwWin32ExtErrorToName(dwError), dwError); return 1; } else { return 0; } }
int main(int argc, char *argv[]) { ParseArguments(argc, argv);//incorrect arguments? print help & exit. Also, fill in SourceDirectoryName and DestinationDirectoryName; process flags. Vprintf("OddBackup, version %s.\nBackup '%s' to '%s'.\n", VERSION, SourceDirectoryName, DestinationDirectoryName); switch (Suspicion) { case 1: Vprintf("All attempts of shell-injections will be eliminated!\n");break; case 0: Vprintf("You'll be asked about fixing suspicious filenames.\n");break; case -1: Vprintf("You won't be disturbed with suspicious filenames. Enjoy your day!\n");break; } struct dirent * DirectoryEntryPointer; DIR * ProcessingDirPointer; PushDir(SourceDirectoryName); while (ProcessingDirectoryName = PopDir()) { if (DotsCheck(ProcessingDirectoryName))//eliminate "." and ".." entries { continue; } if (!TryDirectory(ProcessingDirectoryName)) { printf("Can't backup %s.\n", ProcessingDirectoryName); continue; } Dprintf("Processing %s\n", ProcessingDirectoryName); Vprintf("Entering %s\n", ProcessingDirectoryName); ProcessingDirPointer = opendir(ProcessingDirectoryName); CATCH_ERROR("Can't open directory"); while ((DirectoryEntryPointer = readdir(ProcessingDirPointer)) != NULL) { switch(DirectoryEntryPointer->d_type) { case DT_DIR : PushDir(AbsoluteSourceName(DirectoryEntryPointer->d_name)); break;//it's a directory - will be processed too case DT_REG : if (IsToBeBackuped(DirectoryEntryPointer->d_name))//it's a file { BackupAndGzip(DirectoryEntryPointer->d_name); }; break; default : printf("%s is neither file nor directory - can't backup.\n", DirectoryEntryPointer->d_name); } } Vprintf("Leaving %s\n", ProcessingDirectoryName); closedir(ProcessingDirPointer); free(ProcessingDirectoryName); } return 0; }
int main(int argc, char **argv) // The program's main entry point. The program does a trivial // mDNS query, looking for all AFP servers in the local domain. { int result; mStatus status; DNSQuestion question; domainname type; domainname domain; // Parse our command line arguments. This won't come back if there's an error. ParseArguments(argc, argv); // Initialise the mDNS core. status = mDNS_Init(&mDNSStorage, &PlatformStorage, gRRCache, RR_CACHE_SIZE, mDNS_Init_DontAdvertiseLocalAddresses, mDNS_Init_NoInitCallback, mDNS_Init_NoInitCallbackContext); if (status == mStatus_NoError) { // Construct and start the query. MakeDomainNameFromDNSNameString(&type, gServiceType); MakeDomainNameFromDNSNameString(&domain, gServiceDomain); status = mDNS_StartBrowse(&mDNSStorage, &question, &type, &domain, mDNSInterface_Any, mDNSfalse, BrowseCallback, NULL); // Run the platform main event loop until the user types ^C. // The BrowseCallback routine is responsible for printing // any results that we find. if (status == mStatus_NoError) { fprintf(stderr, "Hit ^C when you're bored waiting for responses.\n"); ExampleClientEventLoop(&mDNSStorage); mDNS_StopQuery(&mDNSStorage, &question); mDNS_Close(&mDNSStorage); } } if (status == mStatus_NoError) { result = 0; } else { result = 2; } if ( (result != 0) || (gMDNSPlatformPosixVerboseLevel > 0) ) { fprintf(stderr, "%s: Finished with status %d, result %d\n", gProgramName, (int)status, result); } return 0; }
double Calculator::parseFunction(std::string_view &ref) { try { std::string_view partStr = ref.substr(0, 3); if (partStr == std::string_view("sin")) { ref.remove_prefix(3); m_printStrategy->printFunctionName("sin"); return sin(ParseArguments(ref) * M_PI / 180); } else if (partStr == std::string_view("cos")) { ref.remove_prefix(3); m_printStrategy->printFunctionName("cos"); return cos(ParseArguments(ref) * M_PI / 180); } else { std::string_view partStr = ref.substr(0, 4); if (partStr == std::string_view("sqrt")) { ref.remove_prefix(4); m_printStrategy->printFunctionName("sqrt"); return sqrt(ParseArguments(ref)); } } } catch(const std::out_of_range&) { return std::numeric_limits<double>::quiet_NaN(); } return std::numeric_limits<double>::quiet_NaN(); }
int main(int argc, const char* argv[]) { ArgTypes args(ParseArguments(argc, argv)); if (std::get<2>(args) == "float") { Calculation<float>(std::get<0>(args), std::get<1>(args), std::get<3>(args), std::get<4>(args), conventionnel<float, int>); } else { Calculation<double>(std::get<0>(args), std::get<1>(args), std::get<3>(args), std::get<4>(args), conventionnel<double, int>); } return 0; }
static int DoArgs(int argc, char *argv[], char **filename) { int ShowCLHelp = 0; int DoSetRemote = 0; ARGPSTRUCT MDFNArgs[]={ {"help", _("Show help!"), &ShowCLHelp, 0, 0 }, {"remote", _("Enable remote mode."), &DoSetRemote, 0, 0 }, #ifdef NEED_CDEMU {"loadcd", _("Load and boot a CD for the specified system."), 0, &loadcd, 0x4001}, #endif {"soundrecord", _("Record sound output to the specified filename in the MS WAV format."), 0,&soundrecfn,0x4001}, {0,NULL, (int *)MDFN_Internal_Args, 0, 0}, #ifdef NETWORK {"connect", _("Connect to the remote server and start network play."), &netconnect, 0, 0 }, #endif {0,0,0,0} }; const char *usage_string = _("Usage: %s [OPTION]... [FILE]\n"); if(argc <= 1) { printf(_("No command-line arguments specified.\n\n")); printf(usage_string, argv[0]); printf(_("\tPlease refer to the documentation for option parameters and usage.\n\n")); return(0); } else { if(!ParseArguments(argc - 1, &argv[1], MDFNArgs, filename)) return(0); if(ShowCLHelp) { printf(usage_string, argv[0]); ShowArgumentsHelp(MDFNArgs); return(0); } if(*filename == NULL && loadcd == NULL) { puts(_("No game filename specified!")); return(0); } } return(1); }
int main(int argc, char **argv) { if(ParseArguments(argc, argv)) return 0; NSApplicationLoad(); if(!AXLibDisplayHasSeparateSpaces()) Fatal("Error: 'Displays have separate spaces' must be enabled!"); AXLibInit(&AXState); AXLibStartEventLoop(); if(!KwmStartDaemon()) Fatal("Error: Could not start daemon!"); OverlayLibInitialize(); DEBUG("OverlayLib initialized!"); ax_display *MainDisplay = AXLibMainDisplay(); ax_display *Display = MainDisplay; do { ax_space *PrevSpace = Display->Space; Display->Space = AXLibGetActiveSpace(Display); Display->PrevSpace = PrevSpace; Display = AXLibNextDisplay(Display); } while(Display != MainDisplay); FocusedDisplay = MainDisplay; FocusedApplication = AXLibGetFocusedApplication(); KwmInit(); KwmParseConfig(KWMPath.Config); KwmExecuteInitScript(); CreateWindowNodeTree(MainDisplay); /* TODO(koekeishiya): Probably want to defer this to run at some point where we know that * the focused application is set. This is usually the case as 'Finder' is always reported * as the active application when nothing is running. The following behaviour requries * refinement, because we will (sometimes ?) get NULL when started by launchd at login */ if(FocusedApplication && FocusedApplication->Focus) UpdateBorder(&FocusedBorder, FocusedApplication->Focus); ConfigureRunLoop(); CFRunLoopRun(); return 0; }
int main(int argc, char** argv){ ParseArguments(Arguments arguments); LoadReadsToPack(char * readsFile, uint8_t * readsPack); for(prefix = 0; prefix < 256; prefix++){ AllocMemory(); Partition(); AmericanFlagSort(); OutputBWT(); FreeMemory(); } FreeReadsPack(); return 0; }
int main(int argc, char* argv[]) { Arguments args; GlobalState state; state.num_locking_processes = 0; state.p_locking_processes = NULL; state.appHWnd = FindConsoleHandle(); kExitCode exit_code = ParseArguments(argc, argv, &args); if (exit_code == kUserNoFiles) { PrintHelp(); fprintf(stderr, "\nError: No filename(s) specified."); return (exit_code); } else if (exit_code == kUserTooManyFiles) { fprintf(stderr, "\nError: Too many filenames specified, max is 32.\n"); return (exit_code); } else if (exit_code != kSuccess) { return (exit_code); } exit_code = InterfaceStateInit(&args, &state.if_state); if (exit_code != kSuccess) { CleanupAndExit(&args, &state, exit_code); } if (args.action == kActionHelpOnly) { PrintHelp(); return (kSuccess); } do { kExitCode update_result = UpdateState(&args, &state); if (update_result == kFailEnumProc) { fprintf(stderr, "\nError: Failed to enumerate processes.\n"); return (kFailEnumProc); } else if (update_result == kSuccessNoReplacements) { dbg_printf("Success: No replacement files found.\n"); return (kSuccess); } } while (1); return (kSuccess); }
//------------------------------------------------------------- // Parses commandline arguments //------------------------------------------------------------- char *ParseArgies(int argc, char *argv[]) { static ARGPSTRUCT FCEUArgs[]={ {"-pal",&pal_setting_specified,&pal_emulation,0}, {"-dendy",0,&dendy,0}, {"-noicon",0,&status_icon,0}, {"-gg",0,&genie,0}, {"-no8lim",0,&eoptions,0x8000|EO_NOSPRLIM}, //{"-nofs",0,&eoptions,0}, {"-clipsides",0,&eoptions,0x8000|EO_CLIPSIDES}, {"-nothrottle",0,&eoptions,0x8000|EO_NOTHROTTLE}, {"-playmovie",0,&MovieToLoad,0x4001}, {"-lua",0,&LuaToLoad,0x4001}, {"-palette",0,&PaletteToLoad,0x4001}, {"-loadstate",0,&StateToLoad,0x4001}, {"-readonly",0,&replayReadOnlySetting,0}, {"-stopframe",0,&replayStopFrameSetting,0}, {"-framedisplay",0,&frame_display,0}, {"-inputdisplay",0,&input_display,0}, {"-allowUDLR",0,&allowUDLR,0}, {"-stopmovie",0,&pauseAfterPlayback,0}, {"-shutmovie",0,&closeFinishedMovie,0}, {"-bginput",0,&EnableBackgroundInput,0}, {"-turbo",0,&turbo,0}, {"-pause",0,&PauseAfterLoad,0}, {"-cfg",0,&ConfigToLoad,0x4001}, {"-avi",0,&AviToLoad,0x4001}, {"-avicapture",0,&AVICapture,0}, {"-dumpinput",0,&DumpInput,0x4001}, {"-playinput",0,&PlayInput,0x4001}, {0, 0, 0, 0}, }; if(argc <= 1) { return(0); } int used = ParseArguments(argc-1, &argv[1], FCEUArgs); return(argv[used+1]); }
INT wmain(INT argc, WCHAR **argv) { po::variables_map variables_map; printInfoStruct stPrintInfo; if (!ParseArguments(argc, argv, variables_map, stPrintInfo)) return 3; if (variables_map.count("print-objects")) { PrintObjects(); return 0; } if (variables_map.count("print-object-info")) { PrintObjectInfo(stPrintInfo); return 0; } if (QueryPerfData(stPrintInfo)) return PrintOutput(variables_map, stPrintInfo); else return 3; }
/** Embedded Boot Loader (EBL) - A simple EFI command line application for embedded devices. PcdEmbeddedAutomaticBootCommand is a complied in command line that gets executed automatically. The ; separator allows multiple commands for each command line. @param ImageHandle EFI ImageHandle for this application. @param SystemTable EFI system table @return EFI status of the application **/ EFI_STATUS EFIAPI EdkExternCmdEntry ( IN EFI_HANDLE ImageHandle, IN EFI_SYSTEM_TABLE *SystemTable ) { EFI_STATUS Status; EFI_LOADED_IMAGE_PROTOCOL *ImageInfo; UINTN Argc; CHAR8 *Argv[MAX_ARGS]; Status = gBS->HandleProtocol (ImageHandle, &gEfiLoadedImageProtocolGuid, (VOID **)&ImageInfo); if (EFI_ERROR (Status)) { Argc = 0; } else { // Looks like valid commands were passed in. ParseArguments (ImageInfo->LoadOptions, ImageInfo->LoadOptionsSize, &Argc, Argv); } return EblMain (Argc, Argv); }
/** Parse a command line and execute the commands. The ; separator allows multiple commands for each command line. Stop processing if one of the commands returns an error. @param CmdLine Command Line to process. @param MaxCmdLineSize MaxSize of the Command line @return EFI status of the Command **/ EFI_STATUS ProcessCmdLine ( IN CHAR8 *CmdLine, IN UINTN MaxCmdLineSize ) { EFI_STATUS Status; EBL_COMMAND_TABLE *Cmd; CHAR8 *Ptr; UINTN Argc; CHAR8 *Argv[MAX_ARGS]; // Parse the command line. The loop processes commands separated by ; for (Ptr = CmdLine, Status = EFI_SUCCESS; Ptr != NULL;) { Ptr = ParseArguments (Ptr, &Argc, Argv); if (Argc != 0) { Cmd = EblGetCommand (Argv[0]); if (Cmd != NULL) { // Execute the Command! Status = Cmd->Command (Argc, Argv); if (Status == EFI_ABORTED) { // exit command so lets exit break; } else if (Status == EFI_TIMEOUT) { // pause command got input so don't process any more cmd on this cmd line break; } else if (EFI_ERROR (Status)) { AsciiPrint ("%a returned %r error\n", Cmd->Name, Status); // if any command fails stop processing CmdLine break; } } else { AsciiPrint ("The command '%a' is not supported.\n", Argv[0]); } } } return Status; }
// definition of the main function int main(int argc, char **argv) // TODO: add arguments 1. input file name and 2. number of iterations { // declaration of local variables char *filename; // name of the input file, which the records have to be read from unsigned int iterations; // number of iterations, got as a program's input unsigned int records; // number of records (>= 1), to be read from the input file unsigned int i; // array indexes record_t recordset[MAX_NUMBER_OF_RECORDS]; // array of records, to be read from the input file unsigned int cumWeights[MAX_NUMBER_OF_RECORDS]; // array of cumulated record weights if(ParseArguments(argc, argv, &filename, &iterations) < 0) { return(-1); } if(ReadFile(filename, &records, recordset) < 0) { return(-1); } // initialization stuff InitializeRandomNumberGenerator(); PrepareArrayOfCumulatedRecordWeights(records, recordset, cumWeights); // loop up to the given number of iterations, // picking a random record and incrementing the related frequency for(i = 0; i < iterations; i++) { recordset[PickRandomRecordIndex(records, cumWeights)].frequency++; } // show the statistics on the stdout for(i = 0; i < records; i++) { printf( "%s:\n- prob. %3u%%, freq. %3u%%\n", recordset[i].label, 100 * recordset[i].weight / cumWeights[records - 1], 100 * recordset[i].frequency / iterations); } return 0; }
int main(int argc, char **argv) { ParseArguments(&argc, &argv); if (FLAGS_model.empty()) { tprintf("Must provide a --model!\n"); return 1; } if (FLAGS_eval_listfile.empty()) { tprintf("Must provide a --eval_listfile!\n"); return 1; } tesseract::TessdataManager mgr; if (!mgr.Init(FLAGS_model.c_str())) { tprintf("%s is not a recognition model, trying training checkpoint...\n", FLAGS_model.c_str()); if (!mgr.Init(FLAGS_traineddata.c_str())) { tprintf("Failed to load language model from %s!\n", FLAGS_traineddata.c_str()); return 1; } GenericVector<char> model_data; if (!tesseract::LoadDataFromFile(FLAGS_model.c_str(), &model_data)) { tprintf("Failed to load model from: %s\n", FLAGS_model.c_str()); return 1; } mgr.OverwriteEntry(tesseract::TESSDATA_LSTM, &model_data[0], model_data.size()); } tesseract::LSTMTester tester(static_cast<inT64>(FLAGS_max_image_MB) * 1048576); if (!tester.LoadAllEvalData(FLAGS_eval_listfile.c_str())) { tprintf("Failed to load eval data from: %s\n", FLAGS_eval_listfile.c_str()); return 1; } double errs = 0.0; STRING result = tester.RunEvalSync(0, &errs, mgr, 0); tprintf("%s\n", result.string()); return 0; } /* main */
int EnumObjectsMain( int argc, char** ppszArgv ) { DWORD dwError = 0; dwError = ParseArguments(argc, ppszArgv); BAIL_ON_LSA_ERROR(dwError); if (!gState.bShowUsage) { dwError = EnumObjects(); BAIL_ON_LSA_ERROR(dwError); } error: if (gState.bShowUsage) { ShowUsage(ppszArgv[0], TRUE); } else if (dwError == LW_ERROR_INVALID_PARAMETER) { ShowUsage(ppszArgv[0], FALSE); } if (dwError) { printf("Error: %s (%x)\n", LwWin32ExtErrorToName(dwError), dwError); return 1; } else { return 0; } }
int main(int argc, const char* argv[]) { const char* error; int return_code; OpenCL* ocl; // Attempt to parse arguments if (error = ParseArguments(argc, argv)) { PrintHeader(); printf("\nError parsing arguments: %s\n\n", error); PrintUsage(); return 1; } // Print program information if (g_PrintHeader) PrintHeader(); if (g_PrintHelp) PrintUsage(); // Some OpenCL compilers can't pick up includes in the same directory as the input filename // without explicitly telling them about it AddIncludePathForFile(g_InputFilename); LOG("\n"); if (error = OpenCL_Create(&ocl)) { printf("\nError initialising OpenCL: %s\n\n", error); return 1; } return_code = OpenCL_LoadAndCompileProgram(ocl); OpenCL_Destroy(&ocl); return return_code; }
void Urho3DPlayer::Setup() { FileSystem* filesystem = GetSubsystem<FileSystem>(); // On Android and iOS, read command line from a file as parameters can not otherwise be easily given #if defined(ANDROID) || defined(IOS) SharedPtr<File> commandFile(new File(context_, filesystem->GetProgramDir() + "Data/CommandLine.txt", FILE_READ)); String commandLine = commandFile->ReadLine(); commandFile->Close(); ParseArguments(commandLine, false); // Reparse engine startup parameters now engineParameters_ = Engine::ParseParameters(GetArguments()); #endif // Check for script file name const Vector<String>& arguments = GetArguments(); String scriptFileName; for (unsigned i = 0; i < arguments.Size(); ++i) { if (arguments[i][0] != '-') { scriptFileName_ = GetInternalPath(arguments[i]); break; } } // Show usage if not found if (scriptFileName_.Empty()) { ErrorExit("Usage: Urho3DPlayer <scriptfile> [options]\n\n" "The script file should implement the function void Start() for initializing the " "application and subscribing to all necessary events, such as the frame update.\n" #ifndef WIN32 "\nCommand line options:\n" "-x <res> Horizontal resolution\n" "-y <res> Vertical resolution\n" "-m <level> Enable hardware multisampling\n" "-v Enable vertical sync\n" "-t Enable triple buffering\n" "-w Start in windowed mode\n" "-s Enable resizing when in windowed mode\n" "-q Enable quiet mode which does not log to standard output stream\n" "-b <length> Sound buffer length in milliseconds\n" "-r <freq> Sound mixing frequency in Hz\n" "-p <paths> Resource path(s) to use, separated by semicolons\n" "-ap <paths> Autoload resource path(s) to use, seperated by semicolons\n" "-log <level> Change the log level, valid 'level' values are 'debug', 'info', 'warning', 'error'\n" "-ds <file> Dump used shader variations to a file for precaching\n" "-mq <level> Material quality level, default 2 (high)\n" "-tq <level> Texture quality level, default 2 (high)\n" "-tf <level> Texture filter mode, default 2 (trilinear)\n" "-af <level> Texture anisotropy level, default 4. Also sets anisotropic filter mode\n" "-flushgpu Flush GPU command queue each frame. Effective only on Direct3D9\n" "-borderless Borderless window mode\n" "-headless Headless mode. No application window will be created\n" "-landscape Use landscape orientations (iOS only, default)\n" "-portrait Use portrait orientations (iOS only)\n" "-prepass Use light pre-pass rendering\n" "-deferred Use deferred rendering\n" "-lqshadows Use low-quality (1-sample) shadow filtering\n" "-noshadows Disable shadow rendering\n" "-nolimit Disable frame limiter\n" "-nothreads Disable worker threads\n" "-nosound Disable sound output\n" "-noip Disable sound mixing interpolation\n" "-sm2 Force SM2.0 rendering\n" "-touch Touch emulation on desktop platform\n" #endif ); } else { // Use the script file name as the base name for the log file //engineParameters_["LogName"] = filesystem->GetAppPreferencesDir("urho3d", "logs") + GetFileNameAndExtension(scriptFileName_) + ".log"; engineParameters_["LogName"]="Urho3D.log"; } }
/* This function is the entry point for this program. Based on the command-line arguments, it invokes the suitable functions. */ int _cdecl main(int argc, char *argv[]) { // holds the return value from this function. // 0 indicates success, non-zero indicates failure. int retVal; int i; BOOL bStartupSuccessful = FALSE; WSADATA wsaData; printf("Entering main()\n"); // parse and validate the given arguments and determine if we should // continue the execution or return error. if (ParseArguments(argc, argv) == FALSE) { // error input. return a non-zero error code. retVal = 1; goto CLEANUP; } // call WSAStartup to initialize Winsock before calling any of its APIs. retVal = WSAStartup(MAKEWORD(2,2), &wsaData); if (retVal != 0) { printf("WSAStartup failed. Error = %d\n", retVal); goto CLEANUP; } // remember that the WSAStartup was successful so as to call WSACleanup // once, correspondingly. bStartupSuccessful = TRUE; for(i = 1; i <= g_ClientContext.loopCount; i++) { printf("\n\nPerforming Iteration : %d\n" "-------------------------\n",i); // create a socket that's connected to the server. g_ClientContext.sock = CreateClientSocket(); if (g_ClientContext.sock == INVALID_SOCKET) goto CLEANUP; // allocate and initialize the buffer to be sent. if (PrepareSendBuffer() == FALSE) goto CLOSE_SOCKET; // allocate and initialize a buffer for receiving. if (PrepareRecvBuffer() == FALSE) goto CLOSE_SOCKET; // perform the sends/recv according to the requested scenario. switch(g_ClientContext.scenario) { case SC_SEND_THEN_RECV : DoSendThenRecv(); break; case SC_SEND_NO_RECV : DoSendNoRecv(); break; case SC_SEND_WAIT_RECV : DoSendWaitRecv(); break; case SC_WAIT_SEND_RECV : DoWaitSendRecv(); break; case SC_IDEAL_SEND_RECV: DoIdealSendRecv(); break; default: printf("Unrecognized scenario\n"); break; } CLOSE_SOCKET: // free the send and recv buffers. FreeSendBuffer(); FreeRecvBuffer(); // close the client socket. closesocket(g_ClientContext.sock); printf("Closed socket %d. " "Total Bytes Recd = %d, " "Total Bytes Sent = %d\n", g_ClientContext.sock, g_ClientContext.nBytesRecd, g_ClientContext.sendBufSize - g_ClientContext.nBytesRemainingToBeSent); } CLEANUP: // call WSACleanup only if WSAStartup was successful. if (bStartupSuccessful) { // Inform Winsock that we are done with all the APIs. WSACleanup(); } printf("Exiting main()\n"); return retVal; }
/*---------------------------------------------------------------------------*/ int main (int argc, char **argv) { /* ** Parameters: ** argc number of command line arguments ** argv array of command line arguments ** Globals: none ** Operation: ** This program reads in a text file consisting of feature ** samples from a training page in the following format: ** ** FontName CharName NumberOfFeatureTypes(N) ** FeatureTypeName1 NumberOfFeatures(M) ** Feature1 ** ... ** FeatureM ** FeatureTypeName2 NumberOfFeatures(M) ** Feature1 ** ... ** FeatureM ** ... ** FeatureTypeNameN NumberOfFeatures(M) ** Feature1 ** ... ** FeatureM ** FontName CharName ... ** ** The result of this program is a binary inttemp file used by ** the OCR engine. ** Return: none ** Exceptions: none ** History: Fri Aug 18 08:56:17 1989, DSJ, Created. ** Mon May 18 1998, Christy Russson, Revistion started. */ char *PageName; FILE *TrainingPage; FILE *OutFile; LIST CharList; CLUSTERER *Clusterer = NULL; LIST ProtoList = NIL; LABELEDLIST CharSample; PROTOTYPE *Prototype; LIST ClassList = NIL; int Cid, Pid; PROTO Proto; PROTO_STRUCT DummyProto; BIT_VECTOR Config2; MERGE_CLASS MergeClass; INT_TEMPLATES IntTemplates; LIST pCharList, pProtoList; char Filename[MAXNAMESIZE]; tesseract::Classify classify; ParseArguments (argc, argv); if (InputUnicharsetFile == NULL) { InputUnicharsetFile = kInputUnicharsetFile; } if (OutputUnicharsetFile == NULL) { OutputUnicharsetFile = kOutputUnicharsetFile; } if (!unicharset_training.load_from_file(InputUnicharsetFile)) { fprintf(stderr, "Failed to load unicharset from file %s\n" "Building unicharset for mftraining from scratch...\n", InputUnicharsetFile); unicharset_training.clear(); // Space character needed to represent NIL classification. unicharset_training.unichar_insert(" "); } if (InputFontInfoFile != NULL) { FILE* f = fopen(InputFontInfoFile, "r"); if (f == NULL) { fprintf(stderr, "Failed to load font_properties\n"); } else { int italic, bold, fixed, serif, fraktur; while (!feof(f)) { FontInfo fontinfo; fontinfo.name = new char[1024]; fontinfo.properties = 0; if (fscanf(f, "%1024s %i %i %i %i %i\n", fontinfo.name, &italic, &bold, &fixed, &serif, &fraktur) != 6) continue; fontinfo.properties = (italic << 0) + (bold << 1) + (fixed << 2) + (serif << 3) + (fraktur << 4); if (!classify.get_fontinfo_table().contains(fontinfo)) { classify.get_fontinfo_table().push_back(fontinfo); } else { fprintf(stderr, "Font %s already defined\n", fontinfo.name); return 1; } } fclose(f); } } while ((PageName = GetNextFilename(argc, argv)) != NULL) { printf ("Reading %s ...\n", PageName); char *short_name = strrchr(PageName, '/'); if (short_name == NULL) short_name = PageName; else ++short_name; // filename is expected to be of the form [lang].[fontname].exp[num].tr // If it is, then set short_name to be the [fontname]. Otherwise it is just // the file basename with the .tr extension removed. char *font_dot = strchr(short_name, '.'); char *exp_dot = (font_dot != NULL) ? strstr(font_dot, ".exp") : NULL; if (font_dot != NULL && exp_dot != NULL && font_dot != exp_dot) { short_name = new_dup(font_dot + 1); short_name[exp_dot - font_dot - 1] = '\0'; } else { short_name = new_dup(short_name); int len = strlen(short_name); if (!strcmp(short_name + len - 3, ".tr")) short_name[len - 3] = '\0'; } int fontinfo_id; FontInfo fontinfo; fontinfo.name = short_name; fontinfo.properties = 0; // Not used to lookup in the table if (!classify.get_fontinfo_table().contains(fontinfo)) { fontinfo_id = classify.get_fontinfo_table().push_back(fontinfo); printf("%s has no defined properties.\n", short_name); } else { fontinfo_id = classify.get_fontinfo_table().get_id(fontinfo); // Update the properties field fontinfo = classify.get_fontinfo_table().get(fontinfo_id); delete[] short_name; } TrainingPage = Efopen (PageName, "r"); CharList = ReadTrainingSamples (TrainingPage); fclose (TrainingPage); //WriteTrainingSamples (Directory, CharList); pCharList = CharList; iterate(pCharList) { //Cluster CharSample = (LABELEDLIST) first_node (pCharList); // printf ("\nClustering %s ...", CharSample->Label); Clusterer = SetUpForClustering(CharSample, PROGRAM_FEATURE_TYPE); Config.MagicSamples = CharSample->SampleCount; ProtoList = ClusterSamples(Clusterer, &Config); CleanUpUnusedData(ProtoList); //Merge MergeInsignificantProtos(ProtoList, CharSample->Label, Clusterer, &Config); if (strcmp(test_ch, CharSample->Label) == 0) DisplayProtoList(test_ch, ProtoList); ProtoList = RemoveInsignificantProtos(ProtoList, ShowSignificantProtos, ShowInsignificantProtos, Clusterer->SampleSize); FreeClusterer(Clusterer); MergeClass = FindClass (ClassList, CharSample->Label); if (MergeClass == NULL) { MergeClass = NewLabeledClass (CharSample->Label); ClassList = push (ClassList, MergeClass); } Cid = AddConfigToClass(MergeClass->Class); MergeClass->Class->font_set.push_back(fontinfo_id); pProtoList = ProtoList; iterate (pProtoList) { Prototype = (PROTOTYPE *) first_node (pProtoList); // see if proto can be approximated by existing proto Pid = FindClosestExistingProto(MergeClass->Class, MergeClass->NumMerged, Prototype); if (Pid == NO_PROTO) { Pid = AddProtoToClass (MergeClass->Class); Proto = ProtoIn (MergeClass->Class, Pid); MakeNewFromOld (Proto, Prototype); MergeClass->NumMerged[Pid] = 1; } else { MakeNewFromOld (&DummyProto, Prototype); ComputeMergedProto (ProtoIn (MergeClass->Class, Pid), &DummyProto, (FLOAT32) MergeClass->NumMerged[Pid], 1.0, ProtoIn (MergeClass->Class, Pid)); MergeClass->NumMerged[Pid] ++; } Config2 = MergeClass->Class->Configurations[Cid]; AddProtoToConfig (Pid, Config2); } FreeProtoList (&ProtoList); } FreeTrainingSamples (CharList); } //WriteMergedTrainingSamples(Directory,ClassList); WriteMicrofeat(Directory, ClassList); SetUpForFloat2Int(ClassList); IntTemplates = classify.CreateIntTemplates(TrainingData, unicharset_training); strcpy (Filename, ""); if (Directory != NULL) { strcat (Filename, Directory); strcat (Filename, "/"); } strcat (Filename, "inttemp"); #ifdef __UNIX__ OutFile = Efopen (Filename, "w"); #else OutFile = Efopen (Filename, "wb"); #endif classify.WriteIntTemplates(OutFile, IntTemplates, unicharset_training); fclose (OutFile); strcpy (Filename, ""); if (Directory != NULL) { strcat (Filename, Directory); strcat (Filename, "/"); } strcat (Filename, "pffmtable"); // Now create pffmtable. WritePFFMTable(IntTemplates, Filename); // Write updated unicharset to a file. if (!unicharset_training.save_to_file(OutputUnicharsetFile)) { fprintf(stderr, "Failed to save unicharset to file %s\n", OutputUnicharsetFile); exit(1); } printf ("Done!\n"); /**/ FreeLabeledClassList (ClassList); return 0; } /* main */
/*---------------------------------------------------------------------------*/ int main ( int argc, char **argv) /* ** Parameters: ** argc number of command line arguments ** argv array of command line arguments ** Globals: none ** Operation: ** This program reads in a text file consisting of feature ** samples from a training page in the following format: ** ** FontName CharName NumberOfFeatureTypes(N) ** FeatureTypeName1 NumberOfFeatures(M) ** Feature1 ** ... ** FeatureM ** FeatureTypeName2 NumberOfFeatures(M) ** Feature1 ** ... ** FeatureM ** ... ** FeatureTypeNameN NumberOfFeatures(M) ** Feature1 ** ... ** FeatureM ** FontName CharName ... ** ** It then appends these samples into a separate file for each ** character. The name of the file is ** ** DirectoryName/FontName/CharName.FeatureTypeName ** ** The DirectoryName can be specified via a command ** line argument. If not specified, it defaults to the ** current directory. The format of the resulting files is: ** ** NumberOfFeatures(M) ** Feature1 ** ... ** FeatureM ** NumberOfFeatures(M) ** ... ** ** The output files each have a header which describes the ** type of feature which the file contains. This header is ** in the format required by the clusterer. A command line ** argument can also be used to specify that only the first ** N samples of each class should be used. ** Return: none ** Exceptions: none ** History: Fri Aug 18 08:56:17 1989, DSJ, Created. */ { char *PageName; FILE *TrainingPage; LIST CharList = NIL_LIST; CLUSTERER *Clusterer = NULL; LIST ProtoList = NIL_LIST; LIST NormProtoList = NIL_LIST; LIST pCharList; LABELEDLIST CharSample; FEATURE_DEFS_STRUCT FeatureDefs; InitFeatureDefs(&FeatureDefs); ParseArguments(argc, argv); int num_fonts = 0; while ((PageName = GetNextFilename(argc, argv)) != NULL) { printf("Reading %s ...\n", PageName); TrainingPage = Efopen(PageName, "r"); ReadTrainingSamples(FeatureDefs, PROGRAM_FEATURE_TYPE, 100, 1.0f / 64.0f, 0.0f, NULL, TrainingPage, &CharList); fclose(TrainingPage); ++num_fonts; } printf("Clustering ...\n"); // To allow an individual font to form a separate cluster, // reduce the min samples: // Config.MinSamples = 0.5 / num_fonts; pCharList = CharList; iterate(pCharList) { //Cluster CharSample = (LABELEDLIST)first_node(pCharList); Clusterer = SetUpForClustering(FeatureDefs, CharSample, PROGRAM_FEATURE_TYPE); float SavedMinSamples = Config.MinSamples; // To disable the tendency to produce a single cluster for all fonts, // make MagicSamples an impossible to achieve number: // Config.MagicSamples = CharSample->SampleCount * 10; Config.MagicSamples = CharSample->SampleCount; while (Config.MinSamples > 0.001) { ProtoList = ClusterSamples(Clusterer, &Config); if (NumberOfProtos(ProtoList, 1, 0) > 0) { break; } else { Config.MinSamples *= 0.95; printf("0 significant protos for %s." " Retrying clustering with MinSamples = %f%%\n", CharSample->Label, Config.MinSamples); } } Config.MinSamples = SavedMinSamples; AddToNormProtosList(&NormProtoList, ProtoList, CharSample->Label); } FreeTrainingSamples(CharList); if (Clusterer == NULL) // To avoid a SIGSEGV return 1; WriteNormProtos (Directory, NormProtoList, Clusterer); FreeClusterer(Clusterer); FreeProtoList(&ProtoList); FreeNormProtoList(NormProtoList); printf ("\n"); return 0; } // main
static status_t nfs4_mount(fs_volume* volume, const char* device, uint32 flags, const char* args, ino_t* _rootVnodeID) { TRACE("volume = %p, device = %s, flags = %" B_PRIu32 ", args = %s", volume, device, flags, args); status_t result; /* prepare idmapper server */ MutexLocker locker(gIdMapperLock); gIdMapper = new(std::nothrow) IdMap; if (gIdMapper == NULL) return B_NO_MEMORY; result = gIdMapper->InitStatus(); if (result != B_OK) { delete gIdMapper; gIdMapper = NULL; return result; } locker.Unlock(); AddressResolver* resolver; MountConfiguration config; char* path; result = ParseArguments(args, &resolver, &path, &config); if (result != B_OK) return result; MemoryDeleter pathDeleter(path); RPC::Server* server; result = gRPCServerManager->Acquire(&server, resolver, CreateNFS4Server); delete resolver; if (result != B_OK) return result; FileSystem* fs; result = FileSystem::Mount(&fs, server, path, volume->id, config); if (result != B_OK) { gRPCServerManager->Release(server); return result; } Inode* inode = fs->Root(); if (inode == NULL) { delete fs; gRPCServerManager->Release(server); return B_IO_ERROR; } volume->private_volume = fs; volume->ops = &gNFSv4VolumeOps; VnodeToInode* vti = new VnodeToInode(inode->ID(), fs); if (vti == NULL) { delete fs; gRPCServerManager->Release(server); return B_NO_MEMORY; } vti->Replace(inode); result = publish_vnode(volume, inode->ID(), vti, &gNFSv4VnodeOps, inode->Type(), 0); if (result != B_OK) return result; *_rootVnodeID = inode->ID(); TRACE("*_rootVnodeID = %" B_PRIi64, inode->ID()); return B_OK; }
void Urho3DPlayer::Setup() { FileSystem* filesystem = GetSubsystem<FileSystem>(); // Read command line from a file if no arguments given. This is primarily intended for mobile platforms. // Note that the command file name uses a hardcoded path that does not utilize the resource system // properly (including resource path prefix), as the resource system is not yet initialized at this point const String commandFileName = filesystem->GetProgramDir() + "Data/CommandLine.txt"; if (GetArguments().Empty() && filesystem->FileExists(commandFileName)) { SharedPtr<File> commandFile(new File(context_, commandFileName)); String commandLine = commandFile->ReadLine(); commandFile->Close(); ParseArguments(commandLine, false); // Reparse engine startup parameters now engineParameters_ = Engine::ParseParameters(GetArguments()); } // Check for script file name const Vector<String>& arguments = GetArguments(); String scriptFileName; if (arguments.Size() && arguments[0][0] != '-') scriptFileName_ = GetInternalPath(arguments[0]); // Show usage if not found if (scriptFileName_.Empty()) { ErrorExit("Usage: Urho3DPlayer <scriptfile> [options]\n\n" "The script file should implement the function void Start() for initializing the " "application and subscribing to all necessary events, such as the frame update.\n" #ifndef WIN32 "\nCommand line options:\n" "-x <res> Horizontal resolution\n" "-y <res> Vertical resolution\n" "-m <level> Enable hardware multisampling\n" "-v Enable vertical sync\n" "-t Enable triple buffering\n" "-w Start in windowed mode\n" "-s Enable resizing when in windowed mode\n" "-q Enable quiet mode which does not log to standard output stream\n" "-b <length> Sound buffer length in milliseconds\n" "-r <freq> Sound mixing frequency in Hz\n" "-p <paths> Resource path(s) to use, separated by semicolons\n" "-ap <paths> Autoload resource path(s) to use, seperated by semicolons\n" "-log <level> Change the log level, valid 'level' values are 'debug', 'info', 'warning', 'error'\n" "-ds <file> Dump used shader variations to a file for precaching\n" "-mq <level> Material quality level, default 2 (high)\n" "-tq <level> Texture quality level, default 2 (high)\n" "-tf <level> Texture filter mode, default 2 (trilinear)\n" "-af <level> Texture anisotropy level, default 4. Also sets anisotropic filter mode\n" "-gl2 Force OpenGL 2 use even if OpenGL 3 is available\n" "-flushgpu Flush GPU command queue each frame. Effective only on Direct3D\n" "-borderless Borderless window mode\n" "-headless Headless mode. No application window will be created\n" "-landscape Use landscape orientations (iOS only, default)\n" "-portrait Use portrait orientations (iOS only)\n" "-prepass Use light pre-pass rendering\n" "-deferred Use deferred rendering\n" "-renderpath <name> Use the named renderpath (must enter full resource name)\n" "-lqshadows Use low-quality (1-sample) shadow filtering\n" "-noshadows Disable shadow rendering\n" "-nolimit Disable frame limiter\n" "-nothreads Disable worker threads\n" "-nosound Disable sound output\n" "-noip Disable sound mixing interpolation\n" "-touch Touch emulation on desktop platform\n" #endif ); } else { // Use the script file name as the base name for the log file engineParameters_["LogName"] = filesystem->GetAppPreferencesDir("urho3d", "logs") + GetFileNameAndExtension(scriptFileName_) + ".log"; } // Construct a search path to find the resource prefix with two entries: // The first entry is an empty path which will be substituted with program/bin directory -- this entry is for binary when it is still in build tree // The second and third entries are possible relative paths from the installed program/bin directory to the asset directory -- these entries are for binary when it is in the Urho3D SDK installation location if (!engineParameters_.Contains("ResourcePrefixPaths")) engineParameters_["ResourcePrefixPaths"] = ";../share/Resources;../share/Urho3D/Resources"; }
/* Main entry for program */ int wmain(int argc, WCHAR *argv[]) { DWORD error = ERROR_SUCCESS; struct CommandLineOptions opts; if (argc == 1) /* i.e. no commandline arguments given */ { PrintResourceString(IDS_USAGE); return EXIT_SUCCESS; } error = ParseArguments(&opts, argc, argv); if (error != ERROR_SUCCESS) { DisplayError(error); return EXIT_FAILURE; } /* If the user wants to abort a shutdown */ if (opts.abort) { /* First, the program has to determine if the shutdown/restart is local or remote. This is done since each one requires separate privileges. */ if (opts.remote_system == NULL) EnablePrivilege(SE_SHUTDOWN_NAME, TRUE); else EnablePrivilege(SE_REMOTE_SHUTDOWN_NAME, TRUE); /* Abort the delayed system shutdown specified. */ if (!AbortSystemShutdownW(opts.remote_system)) { PrintResourceString(IDS_ERROR_ABORT); DisplayError(GetLastError()); return EXIT_FAILURE; } else { return EXIT_SUCCESS; } } /* * If the user wants to hibernate the computer. Assume * that the user wants to wake the computer up from * hibernation and it should not force it on the system. */ if (opts.hibernate) { if (IsPwrHibernateAllowed()) { EnablePrivilege(SE_SHUTDOWN_NAME, TRUE); /* The shutdown utility cannot hibernate remote systems */ if (opts.remote_system != NULL) { return EXIT_FAILURE; } if (!SetSuspendState(TRUE, FALSE, FALSE)) { PrintResourceString(IDS_ERROR_HIBERNATE); DisplayError(GetLastError()); return EXIT_FAILURE; } else { PrintResourceString(IDS_ERROR_HIBERNATE_ENABLED); return EXIT_SUCCESS; } } else { return EXIT_FAILURE; } } /* Both shutdown and restart flags cannot both be true */ if (opts.shutdown && opts.restart) { PrintResourceString(IDS_ERROR_SHUTDOWN_REBOOT); return EXIT_FAILURE; } /* Ensure that the timout amount is not too high or a negative number */ if ((opts.shutdown_delay < 0) || (opts.shutdown_delay > MAX_TIMEOUT)) { PrintResourceString(IDS_ERROR_TIMEOUT, opts.shutdown_delay); return EXIT_FAILURE; } /* If the user wants a GUI environment */ if (opts.show_gui) { if (ShutdownGuiMain(opts)) return EXIT_SUCCESS; else return EXIT_FAILURE; } if (opts.logoff && (opts.remote_system == NULL)) { /* * NOTE: Sometimes, shutdown and logoff are used together. If the logoff * flag is used by itself, then simply logoff. But if used with shutdown, * then skip logging off of the computer and eventually go to the action * for shutdown. */ if (!opts.shutdown && !opts.restart) { EnablePrivilege(SE_SHUTDOWN_NAME, TRUE); if (ExitWindowsEx(EWX_LOGOFF, opts.reason)) { return EXIT_SUCCESS; } else { PrintResourceString(IDS_ERROR_LOGOFF); DisplayError(GetLastError()); return EXIT_FAILURE; } } } /* * Since both shutting down the system and restarting calls the exact same * function, all we need to know is if we wanted to restart or shutdown. */ if (opts.shutdown || opts.restart) { /* * First, the program has to determine if the shutdown/restart is local * or remote. This is done since each one requires separate privileges. */ if (opts.remote_system == NULL) { EnablePrivilege(SE_SHUTDOWN_NAME, TRUE); } else { /* TODO: Remote shutdown is not supported yet */ // EnablePrivilege(SE_REMOTE_SHUTDOWN_NAME, TRUE); return EXIT_SUCCESS; } /** ** HACK: When InitiateSystemShutdownExW will become really implemented, ** activate this line and delete the other... ** if(!InitiateSystemShutdownExW(opts.remote_system, opts.message, opts.shutdown_delay, opts.force, opts.restart, opts.reason)) ***/ if (!ExitWindowsEx((opts.shutdown ? EWX_SHUTDOWN : EWX_REBOOT) | (opts.force ? EWX_FORCE : 0), opts.reason)) { /* * If there is an error, give the proper output depending * on whether the user wanted to shutdown or restart. */ if (opts.restart) PrintResourceString(IDS_ERROR_RESTART); else PrintResourceString(IDS_ERROR_SHUTDOWN); DisplayError(GetLastError()); return EXIT_FAILURE; } else { return EXIT_SUCCESS; } } return EXIT_SUCCESS; }
/* * Entry point. */ int main(int argc, char ** argv) { JavaVM *vm = 0; JNIEnv *env = 0; char *jarfile = 0; char *classname = 0; char *s = 0; char *main_class = NULL; jstring mainClassName; jclass mainClass; jmethodID mainID; jobjectArray mainArgs; int ret; InvocationFunctions ifn; jlong start, end; char jrepath[MAXPATHLEN], jvmpath[MAXPATHLEN]; char ** original_argv = argv; /* * Error message to print or display; by default the message will * only be displayed in a window. */ char * message = "Fatal exception occurred. Program will exit."; jboolean messageDest = JNI_FALSE; if (getenv("_JAVA_LAUNCHER_DEBUG") != 0) { _launcher_debug = JNI_TRUE; printf("----_JAVA_LAUNCHER_DEBUG----\n"); } /* * Make sure the specified version of the JRE is running. * * There are three things to note about the SelectVersion() routine: * 1) If the version running isn't correct, this routine doesn't * return (either the correct version has been exec'd or an error * was issued). * 2) Argc and Argv in this scope are *not* altered by this routine. * It is the responsibility of subsequent code to ignore the * arguments handled by this routine. * 3) As a side-effect, the variable "main_class" is guaranteed to * be set (if it should ever be set). This isn't exactly the * poster child for structured programming, but it is a small * price to pay for not processing a jar file operand twice. */ SelectVersion(argc, argv, &main_class); /* copy original argv */ { int i; original_argv = (char**)MemAlloc(sizeof(char*)*(argc+1)); for(i = 0; i < argc+1; i++) original_argv[i] = argv[i]; } CreateExecutionEnvironment(&argc, &argv, jrepath, sizeof(jrepath), jvmpath, sizeof(jvmpath), original_argv); ifn.CreateJavaVM = 0; ifn.GetDefaultJavaVMInitArgs = 0; if (_launcher_debug) start = CounterGet(); if (!LoadJavaVM(jvmpath, &ifn)) { exit(6); } if (_launcher_debug) { end = CounterGet(); printf("%ld micro seconds to LoadJavaVM\n", (long)(jint)Counter2Micros(end-start)); } #ifdef JAVA_ARGS /* javac, jar and friends. */ progname = "java"; #else /* java, oldjava, javaw and friends */ #ifdef PROGNAME progname = PROGNAME; #else progname = *argv; if ((s = strrchr(progname, FILE_SEPARATOR)) != 0) { progname = s + 1; } #endif /* PROGNAME */ #endif /* JAVA_ARGS */ ++argv; --argc; #ifdef JAVA_ARGS /* Preprocess wrapper arguments */ TranslateDashJArgs(&argc, &argv); if (!AddApplicationOptions()) { exit(1); } #endif /* Set default CLASSPATH */ if ((s = getenv("CLASSPATH")) == 0) { s = "."; } #ifndef JAVA_ARGS SetClassPath(s); #endif /* * Parse command line options; if the return value of * ParseArguments is false, the program should exit. */ if (!ParseArguments(&argc, &argv, &jarfile, &classname, &ret)) { exit(ret); } /* Override class path if -jar flag was specified */ if (jarfile != 0) { SetClassPath(jarfile); } /* set the -Dsun.java.command pseudo property */ SetJavaCommandLineProp(classname, jarfile, argc, argv); /* Set the -Dsun.java.launcher pseudo property */ SetJavaLauncherProp(); /* * Done with all command line processing and potential re-execs so * clean up the environment. */ (void)UnsetEnv(ENV_ENTRY); /* Initialize the virtual machine */ if (_launcher_debug) start = CounterGet(); if (!InitializeJVM(&vm, &env, &ifn)) { ReportErrorMessage("Could not create the Java virtual machine.", JNI_TRUE); exit(1); } if (printVersion || showVersion) { PrintJavaVersion(env); if ((*env)->ExceptionOccurred(env)) { ReportExceptionDescription(env); goto leave; } if (printVersion) { ret = 0; message = NULL; goto leave; } if (showVersion) { fprintf(stderr, "\n"); } } /* If the user specified neither a class name nor a JAR file */ if (jarfile == 0 && classname == 0) { PrintUsage(); message = NULL; goto leave; } FreeKnownVMs(); /* after last possible PrintUsage() */ if (_launcher_debug) { end = CounterGet(); printf("%ld micro seconds to InitializeJVM\n", (long)(jint)Counter2Micros(end-start)); } /* At this stage, argc/argv have the applications' arguments */ if (_launcher_debug) { int i = 0; printf("Main-Class is '%s'\n", classname ? classname : ""); printf("Apps' argc is %d\n", argc); for (; i < argc; i++) { printf(" argv[%2d] = '%s'\n", i, argv[i]); } } ret = 1; /* Get the application's main class */ if (jarfile != 0) { mainClassName = GetMainClassName(env, jarfile); if ((*env)->ExceptionOccurred(env)) { ReportExceptionDescription(env); goto leave; } if (mainClassName == NULL) { const char * format = "Failed to load Main-Class manifest " "attribute from\n%s"; message = (char*)MemAlloc((strlen(format) + strlen(jarfile)) * sizeof(char)); sprintf(message, format, jarfile); messageDest = JNI_TRUE; goto leave; } classname = (char *)(*env)->GetStringUTFChars(env, mainClassName, 0); if (classname == NULL) { ReportExceptionDescription(env); goto leave; } mainClass = LoadClass(env, classname); if(mainClass == NULL) { /* exception occured */ ReportExceptionDescription(env); message = "Could not find the main class. Program will exit."; goto leave; } (*env)->ReleaseStringUTFChars(env, mainClassName, classname); } else { mainClassName = NewPlatformString(env, classname); if (mainClassName == NULL) { const char * format = "Failed to load Main Class: %s"; message = (char *)MemAlloc((strlen(format) + strlen(classname)) * sizeof(char) ); sprintf(message, format, classname); messageDest = JNI_TRUE; goto leave; } classname = (char *)(*env)->GetStringUTFChars(env, mainClassName, 0); if (classname == NULL) { ReportExceptionDescription(env); goto leave; } mainClass = LoadClass(env, classname); if(mainClass == NULL) { /* exception occured */ ReportExceptionDescription(env); message = "Could not find the main class. Program will exit."; goto leave; } (*env)->ReleaseStringUTFChars(env, mainClassName, classname); } /* Get the application's main method */ mainID = (*env)->GetStaticMethodID(env, mainClass, "main", "([Ljava/lang/String;)V"); if (mainID == NULL) { if ((*env)->ExceptionOccurred(env)) { ReportExceptionDescription(env); } else { message = "No main method found in specified class."; messageDest = JNI_TRUE; } goto leave; } { /* Make sure the main method is public */ jint mods; jmethodID mid; jobject obj = (*env)->ToReflectedMethod(env, mainClass, mainID, JNI_TRUE); if( obj == NULL) { /* exception occurred */ ReportExceptionDescription(env); goto leave; } mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, obj), "getModifiers", "()I"); if ((*env)->ExceptionOccurred(env)) { ReportExceptionDescription(env); goto leave; } mods = (*env)->CallIntMethod(env, obj, mid); if ((mods & 1) == 0) { /* if (!Modifier.isPublic(mods)) ... */ message = "Main method not public."; messageDest = JNI_TRUE; goto leave; } } /* Build argument array */ mainArgs = NewPlatformStringArray(env, argv, argc); if (mainArgs == NULL) { ReportExceptionDescription(env); goto leave; } /* Invoke main method. */ (*env)->CallStaticVoidMethod(env, mainClass, mainID, mainArgs); if ((*env)->ExceptionOccurred(env)) { /* * Formerly, we used to call the "uncaughtException" method of * the main thread group, but this was later shown to be * unnecessary since the default definition merely printed out * the same exception stack trace as ExceptionDescribe and * could never actually be overridden by application programs. */ ReportExceptionDescription(env); goto leave; } /* * Detach the current thread so that it appears to have exited when * the application's main method exits. */ if ((*vm)->DetachCurrentThread(vm) != 0) { message = "Could not detach main thread."; messageDest = JNI_TRUE; goto leave; } ret = 0; message = NULL; leave: (*vm)->DestroyJavaVM(vm); if(message != NULL && !noExitErrorMessage) ReportErrorMessage(message, messageDest); return ret; }