void TK_AddProgramIncludePath(char *progname) { if(NumIncludePaths < MAX_INCLUDE_PATHS) { #ifdef _WIN32 #ifdef _MSC_VER #if _MSC_VER >= 1300 if (_get_pgmptr(&progname) != 0) { return; } #else progname = _pgmptr; #endif #else char progbuff[1024]; GetModuleFileName(0, progbuff, sizeof(progbuff)); progbuff[sizeof(progbuff)-1] = '\0'; progname = progbuff; #endif #else char progbuff[PATH_MAX]; if (realpath(progname, progbuff) != NULL) { progname = progbuff; } #endif strcpy(IncludePaths[NumIncludePaths], progname); if(MS_StripFilename(IncludePaths[NumIncludePaths])) { MS_Message(MSG_DEBUG, "Program include path is %d: \"%s\"\n", NumIncludePaths, IncludePaths[NumIncludePaths]); NumIncludePaths++; } } }
static void InstallService() { SC_HANDLE hSCManager; int status; RemoveService(); hSCManager = OpenSCManager(NULL,NULL,SC_MANAGER_CREATE_SERVICE); if (hSCManager) { SC_HANDLE hService; char *pgm; char *cmd; static const char* multi_opt="--multi"; static const char* server_opt="--server"; static const char* data_opt=""; char *opts = GetMulti() ? (GetContextSwitching() ? "--multi" : "--server") : ""; SERVICE_DESCRIPTION sd; LPTSTR description=(LPTSTR)malloc(4096); if (GetMulti()) { if (GetContextSwitching()) { opts=multi_opt; wsprintf(description,TEXT("MDSplus data service listening on port %s.\nPermits multiple connections each with own tdi and tree context\n"), GetPortname()); } else { opts=server_opt; wsprintf(description,TEXT("MDSplus data service listening on port %s.\nPermits multiple connections with shared tdi and tree context\n"), GetPortname()); } } else { opts=data_opt; wsprintf(description,TEXT("MDSplus data service listening on port %s.\nEach connections will spawn a private server.\n"), GetPortname()); } sd.lpDescription=description; _get_pgmptr(&pgm); cmd = (char *)malloc(strlen(pgm)+strlen(GetPortname())+strlen(GetHostfile())+100); sprintf(cmd,"%s --port=%s --hostfile=\"%s\" %s",pgm,GetPortname(),GetHostfile(),opts); hService = CreateService(hSCManager, ServiceName(1), ServiceName(0), SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, cmd, NULL, NULL, NULL, NULL, NULL); if (hService == NULL) status = GetLastError(); else { ChangeServiceConfig2(hService,SERVICE_CONFIG_DESCRIPTION,&sd); if (GetMulti()) { SERVICE_FAILURE_ACTIONS sfa; SC_ACTION actions[] = {{SC_ACTION_RESTART,5000}}; sfa.dwResetPeriod = INFINITE; sfa.lpRebootMsg = NULL; sfa.lpCommand = NULL; sfa.cActions = 1; sfa.lpsaActions=actions; status = ChangeServiceConfig2(hService,SERVICE_CONFIG_FAILURE_ACTIONS, &sfa); status = GetLastError(); } } free(description); free(cmd); if (hService) CloseServiceHandle(hService); CloseServiceHandle(hSCManager); } }
/* Get current user’s home directory */ static char *BarSettingsGetHome () { char* exec = NULL; char* delimiter = NULL; _get_pgmptr (&exec); delimiter = strrchr (exec, '\\'); if (delimiter) return strndup (exec, delimiter - exec); else return NULL; }
int main() { char* pgmptr = nullptr; auto errcode = _get_pgmptr(&pgmptr); // pgmptr is now empty string, errcode 0 std::cout << "pgmptr: \"" << pgmptr << "\" (error code: " << errcode << ")\n"; char modulename[MAX_PATH]; GetModuleFileNameA(nullptr, modulename, MAX_PATH); // modulename is correct std::cout << "GetModuleFileName: \"" << modulename << "\"\n"; std::system("pause"); return 0; }
static int SpawnWorker(SOCKET sock) { int status; STARTUPINFO startupinfo; PROCESS_INFORMATION pinfo; char cmd[1024]; SECURITY_ATTRIBUTES sc_atts; char *pgm,*lslash; _get_pgmptr(&pgm); lslash=strrchr(pgm,'\\'); sc_atts.nLength=sizeof(sc_atts); sc_atts.bInheritHandle=TRUE; sc_atts.lpSecurityDescriptor=NULL; sprintf(cmd,"%.*s\\mdsip.exe --port=%s --hostfile=\"%s\" --compression=%d --sockethandle=%d:%d",lslash-pgm,pgm, GetPortname(),GetHostfile(),GetMaxCompressionLevel(),_getpid(),sock); memset(&startupinfo,0,sizeof(startupinfo)); startupinfo.cb = sizeof(startupinfo); status = CreateProcess(NULL,cmd,NULL,NULL,FALSE,0,NULL,NULL,&startupinfo, &pinfo); printf("CreateProcess returned %d with cmd=%s\n",status,cmd); fflush(stdout); CloseHandle(pinfo.hProcess); CloseHandle(pinfo.hThread); return pinfo.dwProcessId; }
void DoMain (HINSTANCE hInstance) { LONG WinWidth, WinHeight; int height, width, x, y; RECT cRect; TIMECAPS tc; DEVMODE displaysettings; try { #ifdef _MSC_VER _set_new_handler (NewFailure); #endif Args = new DArgs(__argc, __argv); // Load Win32 modules Kernel32Module.Load({"kernel32.dll"}); Shell32Module.Load({"shell32.dll"}); User32Module.Load({"user32.dll"}); // Under XP, get our session ID so we can know when the user changes/locks sessions. // Since we need to remain binary compatible with older versions of Windows, we // need to extract the ProcessIdToSessionId function from kernel32.dll manually. HMODULE kernel = GetModuleHandle ("kernel32.dll"); if (Args->CheckParm("-stdout")) { // As a GUI application, we don't normally get a console when we start. // If we were run from the shell and are on XP+, we can attach to its // console. Otherwise, we can create a new one. If we already have a // stdout handle, then we have been redirected and should just use that // handle instead of creating a console window. StdOut = GetStdHandle(STD_OUTPUT_HANDLE); if (StdOut != NULL) { // It seems that running from a shell always creates a std output // for us, even if it doesn't go anywhere. (Running from Explorer // does not.) If we can get file information for this handle, it's // a file or pipe, so use it. Otherwise, pretend it wasn't there // and find a console to use instead. BY_HANDLE_FILE_INFORMATION info; if (!GetFileInformationByHandle(StdOut, &info)) { StdOut = NULL; } } if (StdOut == NULL) { // AttachConsole was introduced with Windows XP. (OTOH, since we // have to share the console with the shell, I'm not sure if it's // a good idea to actually attach to it.) typedef BOOL (WINAPI *ac)(DWORD); ac attach_console = kernel != NULL ? (ac)GetProcAddress(kernel, "AttachConsole") : NULL; if (attach_console != NULL && attach_console(ATTACH_PARENT_PROCESS)) { StdOut = GetStdHandle(STD_OUTPUT_HANDLE); DWORD foo; WriteFile(StdOut, "\n", 1, &foo, NULL); AttachedStdOut = true; } if (StdOut == NULL && AllocConsole()) { StdOut = GetStdHandle(STD_OUTPUT_HANDLE); } FancyStdOut = true; } } // Set the timer to be as accurate as possible if (timeGetDevCaps (&tc, sizeof(tc)) != TIMERR_NOERROR) TimerPeriod = 1; // Assume minimum resolution of 1 ms else TimerPeriod = tc.wPeriodMin; timeBeginPeriod (TimerPeriod); /* killough 1/98: This fixes some problems with exit handling during abnormal situations. The old code called I_Quit() to end program, while now I_Quit() is installed as an exit handler and exit() is called to exit, either normally or abnormally. */ atexit (call_terms); atterm (I_Quit); // Figure out what directory the program resides in. char *program; #ifdef _MSC_VER if (_get_pgmptr(&program) != 0) { I_FatalError("Could not determine program location."); } #else char progbuff[1024]; GetModuleFileName(0, progbuff, sizeof(progbuff)); progbuff[1023] = '\0'; program = progbuff; #endif progdir = program; program = progdir.LockBuffer(); *(strrchr(program, '\\') + 1) = '\0'; FixPathSeperator(program); progdir.Truncate((long)strlen(program)); progdir.UnlockBuffer(); HDC screenDC = GetDC(0); int dpi = GetDeviceCaps(screenDC, LOGPIXELSX); ReleaseDC(0, screenDC); width = (512 * dpi + 96 / 2) / 96; height = (384 * dpi + 96 / 2) / 96; // Many Windows structures that specify their size do so with the first // element. DEVMODE is not one of those structures. memset (&displaysettings, 0, sizeof(displaysettings)); displaysettings.dmSize = sizeof(displaysettings); EnumDisplaySettings (NULL, ENUM_CURRENT_SETTINGS, &displaysettings); x = (displaysettings.dmPelsWidth - width) / 2; y = (displaysettings.dmPelsHeight - height) / 2; if (Args->CheckParm ("-0")) { x = y = 0; } WNDCLASS WndClass; WndClass.style = 0; WndClass.lpfnWndProc = LConProc; WndClass.cbClsExtra = 0; WndClass.cbWndExtra = 0; WndClass.hInstance = hInstance; WndClass.hIcon = LoadIcon (hInstance, MAKEINTRESOURCE(IDI_ICON1)); WndClass.hCursor = LoadCursor (NULL, IDC_ARROW); WndClass.hbrBackground = NULL; WndClass.lpszMenuName = NULL; WndClass.lpszClassName = (LPCTSTR)WinClassName; /* register this new class with Windows */ if (!RegisterClass((LPWNDCLASS)&WndClass)) I_FatalError ("Could not register window class"); /* create window */ char caption[100]; mysnprintf(caption, countof(caption), "" GAMESIG " %s " X64 " (%s)", GetVersionString(), GetGitTime()); Window = CreateWindowEx( WS_EX_APPWINDOW, (LPCTSTR)WinClassName, (LPCTSTR)caption, WS_OVERLAPPEDWINDOW | WS_VISIBLE | WS_CLIPCHILDREN, x, y, width, height, (HWND) NULL, (HMENU) NULL, hInstance, NULL); if (!Window) I_FatalError ("Could not open window"); if (kernel != NULL) { typedef BOOL (WINAPI *pts)(DWORD, DWORD *); pts pidsid = (pts)GetProcAddress (kernel, "ProcessIdToSessionId"); if (pidsid != 0) { if (!pidsid (GetCurrentProcessId(), &SessionID)) { SessionID = 0; } hwtsapi32 = LoadLibraryA ("wtsapi32.dll"); if (hwtsapi32 != 0) { FARPROC reg = GetProcAddress (hwtsapi32, "WTSRegisterSessionNotification"); if (reg == 0 || !((BOOL(WINAPI *)(HWND, DWORD))reg) (Window, NOTIFY_FOR_THIS_SESSION)) { FreeLibrary (hwtsapi32); hwtsapi32 = 0; } else { atterm (UnWTS); } } } } GetClientRect (Window, &cRect); WinWidth = cRect.right; WinHeight = cRect.bottom; CoInitialize (NULL); atterm (UnCOM); C_InitConsole (((WinWidth / 8) + 2) * 8, (WinHeight / 12) * 8, false); I_DetectOS (); D_DoomMain (); } catch (class CNoRunExit &) { I_ShutdownGraphics(); if (!batchrun) { if (FancyStdOut && !AttachedStdOut) { // Outputting to a new console window: Wait for a keypress before quitting. DWORD bytes; HANDLE stdinput = GetStdHandle(STD_INPUT_HANDLE); ShowWindow(Window, SW_HIDE); WriteFile(StdOut, "Press any key to exit...", 24, &bytes, NULL); FlushConsoleInputBuffer(stdinput); SetConsoleMode(stdinput, 0); ReadConsole(stdinput, &bytes, 1, &bytes, NULL); } else if (StdOut == NULL) { ShowErrorPane(NULL); } } exit(0); } catch (class CDoomError &error) { I_ShutdownGraphics (); RestoreConView (); I_FlushBufferedConsoleStuff(); if (error.GetMessage ()) { if (!batchrun) { ShowErrorPane(error.GetMessage()); } else { Printf("%s\n", error.GetMessage()); } } exit (-1); } }
int main (int argument_count, char* argument_list[]) { struct tsdef_def_error_list def_errors; char* program_directory; char* program_path; int error; errno_t std_error; signal(SIGINT, NullSignalHandler); printf( "\n" "Launching Trigger Script Interpreter\n" "------------------------------------\n" ); TSUtil_InitializePathCollection(&tsi_search_paths); error = TSUtil_AppendPath(".", &tsi_search_paths); if(error != TSUTIL_ERROR_NONE) { printf("\nAn unexpected error has occurred and the interpretter must now exit\n"); goto append_path_failed; } TSDef_InitializeModule(&tsi_module); tsi_unit_invocation = NULL; tsi_set_variables = NULL; tsi_flags = 0; error = ProcessCommandLine(argument_count, argument_list); if(error < 0) goto process_command_line_failed; else if(error > 0) goto exit_gracefully; if(tsi_unit_invocation == NULL) { printf("\nNo function was specified, please invoke the interpretter with a function to be executed\n"); goto no_unit_specified; } #ifdef PLATFORM_WIN32 std_error = _get_pgmptr(&program_path); if(std_error != 0) goto get_program_path_failed; program_directory = strdup(program_path); if(program_directory == NULL) { printf("\nAn unexpected error has occurred and the interpretter must now exit\n"); goto allocate_program_directory_failed; } program_path = strrchr(program_directory, '\\'); if(program_path != NULL) *program_path = 0; #else #error "Unsupported platform" #endif error = TSI_RegisterFFI(program_directory, &tsi_module); free(program_directory); if(error != TSI_ERROR_NONE) { printf("\nAn unexpected error has occurred and the interpretter must now exit\n"); goto register_ffi_failed; } printf("\n"); TSDef_InitializeDefErrorList(&def_errors); printf("Compiling trigger script...\n"); error = TSUtil_CompileUnit( tsi_unit_invocation, 0, &tsi_search_paths, TSI_SOURCE_EXTENSION, &NotifyLookup, &def_errors, &tsi_module ); if(error != TSDEF_ERROR_NONE) { if(error == TSUTIL_ERROR_COMPILATION_ERROR || error == TSUTIL_ERROR_COMPILATION_WARNING) TSI_ReportDefErrors(&def_errors); else printf("An unexpected error has while trying to parse the unit\n"); if(error != TSUTIL_ERROR_COMPILATION_WARNING) goto compilation_failed; } TSDef_DestroyDefErrorList(&def_errors); printf("Compilation successful\n"); if(!(tsi_flags&TSI_FLAG_COMPILE_ONLY)) { printf("\n"); if(error == TSUTIL_ERROR_COMPILATION_WARNING) { int pressed_char; printf("Warnings were encountered, run anyways? (y/n)> "); do { pressed_char = getch(); pressed_char = tolower(pressed_char); if(isalpha(pressed_char)) putchar(pressed_char); }while(pressed_char != 'y' && pressed_char != 'n'); printf("\n"); if(pressed_char == 'y') error = TSUTIL_ERROR_NONE; } if(error == TSUTIL_ERROR_NONE) { struct tsint_controller_data controller; struct tsint_execif_data execif; controller.function = &TSI_Controller; controller.user_data = NULL; execif.execif = &tsi_execif; execif.user_data = NULL; printf("Executing trigger script...\n"); error = TSInt_AllocAbortSignal(&abort_signal); if(error != TSINT_ERROR_NONE) { printf("\nAn unexpected error has occurred and the interpretter must now exit\n"); goto alloc_abort_signal_failed; } signal(SIGINT, AbortSignalHandler); error = TSInt_InterpretModule( &tsi_module, NULL, NULL, &controller, &execif, abort_signal ); if(error != TSINT_ERROR_NONE) printf("Trigger script halted due to exception\n"); signal(SIGINT, NullSignalHandler); TSInt_FreeAbortSignal(abort_signal); } } exit_gracefully: DestroyVariables(); TSDef_DestroyModule(&tsi_module); TSUtil_DestroyPathCollection(&tsi_search_paths); return 0; compilation_failed: TSDef_DestroyDefErrorList(&def_errors); alloc_abort_signal_failed: register_ffi_failed: allocate_program_directory_failed: get_program_path_failed: process_command_line_failed: DestroyVariables(); no_unit_specified: TSDef_DestroyModule(&tsi_module); append_path_failed: TSUtil_DestroyPathCollection(&tsi_search_paths); return -1; }