102 Dalmatians: Puppies to the Rescue
Decompilation Source Reference | GitLab repository
Loading...
Searching...
No Matches
startup.c
Go to the documentation of this file.
1/* Recovered game implementation; original addresses identify provenance. */
11
12enum
13{
16};
17
18// Original pcdogs.exe: no direct counterpart (decomp helper)
19// Initializes the CRT, prepares process arguments and environment, invokes WinMain, and terminates with its result. The explicit startup context preserves the parent SEH frame, and the normal path does not return.
20void CRT_InitializeAndRunWinMain(int32_t *startup_frame)
21{
22 uint32_t windows_version_bits = GetVersion();
23 int32_t minor_version = (windows_version_bits >> 8) & 0xff;
24
25 g_windowsVersionMinor = minor_version;
26
27 uint32_t major_version = (uint32_t)(uint8_t)windows_version_bits;
28
29 g_windowsVersionMajor = major_version;
30 g_windowsVersionCombined = (major_version << 8) + minor_version;
31 g_crtStartupFlags = windows_version_bits >> 0x10;
32
33 if (!_heap_init(0))
34 {
36 /* no return */
37 }
38
39 startup_frame[-1] = 0;
40 _ioinit();
41 g_commandLine = GetCommandLineA();
44 _setenvp();
45 _cinit();
46 STARTUPINFOA startup_info;
47 startup_info.dwFlags = 0;
48 GetStartupInfoA(&startup_info);
49
50 char *command_line_tail = CRT_SkipProgramNameInCmdLine();
51 int show_window = startup_info.dwFlags & STARTF_USESHOWWINDOW ? startup_info.wShowWindow : SW_SHOWDEFAULT;
52 int32_t win_main_result = Game_WinMain(g_crtGetModuleHandleAPtr(NULL), NULL, command_line_tail, show_window);
53
54 CRT_exit(win_main_result);
55 /* no return */
56}
57
58// Original pcdogs.exe: 0x443780
59// Returns immediately without changing program state.
61{
62 return;
63}
64
65// Original pcdogs.exe: 0x446325
66// Appends a termination callback to the CRT callback table, growing the table when necessary. It returns the callback on success and NULL on allocation failure.
68{
69 uint32_t allocated_bytes = CRT_msize(g_atexitHandlerBase);
71 CRT_ExitCallback *next_handler_slot = g_atexitHandlerNext;
72
73 if (allocated_bytes < (next_handler_slot - handler_base + 1) * sizeof(*next_handler_slot))
74 {
75 uint32_t size = CRT_msize(handler_base) + CRT_EXIT_TABLE_GROWTH_BYTES;
76 CRT_ExitCallback *resized_handlers = CRT_realloc(g_atexitHandlerBase, size);
77
78 if (!resized_handlers)
79 return NULL;
80
81 /* Reload after a possible new-handler registration. Realloc may have
82 freed the old block, so preserve its byte displacement as integer
83 addresses rather than subtracting pointers into that old object. */
84 uintptr_t used_bytes = (uintptr_t)g_atexitHandlerNext - (uintptr_t)g_atexitHandlerBase;
85
86 g_atexitHandlerBase = resized_handlers;
87 next_handler_slot = resized_handlers + used_bytes / sizeof(*resized_handlers);
88 g_atexitHandlerNext = next_handler_slot;
89 }
90
91 *next_handler_slot = callback;
93
94 return callback;
95}
96
97// Original pcdogs.exe: 0x446392
98// Registers a termination callback and returns zero on success or -1 on failure.
100{
101 return CRT_onexit(callback) ? 0 : -1;
102}
103
104// Original pcdogs.exe: 0x4463a4
105// Allocates and initializes the CRT termination-callback table. Allocation failure terminates through the CRT fatal-error path.
107{
109
110 g_atexitHandlerBase = handler_allocation;
111
112 if (!handler_allocation)
113 {
115 /* no return */
116 }
117
118 *handler_allocation = NULL;
120}
121
122// Original pcdogs.exe: 0x446bf5
123// Runs optional floating-point initialization and then the configured C and C++ initializer ranges.
132
133// Original pcdogs.exe: 0x446c22
134// Performs full CRT termination, including registered exit callbacks, and terminates the process without returning.
135void CRT_exit(int32_t status)
136{
137 _doexit(status, 0, 0);
138 __builtin_unreachable();
139}
140
141// Original pcdogs.exe: 0x446c33
142// Performs quick CRT termination and terminates the process without returning. Registered exit callbacks and pre-terminators are skipped, while terminators still run.
143void CRT_exit_immediate(int32_t status)
144{
145 _doexit(status, 1, 0);
146 __builtin_unreachable();
147}
148
149// Original pcdogs.exe: 0x446c44
150// Coordinates CRT termination with recursion protection, reverse-order exit callbacks, and initializer-table cleanup. The quick-exit and return-to-caller flags select which callbacks run and whether the process is terminated.
151void _doexit(int32_t status, int32_t quick_exit, int32_t return_to_caller)
152{
153 if (g_crtExitInProgress == 1)
154 {
155 TerminateProcess(GetCurrentProcess(), status);
156 /* no return */
157 }
158
159 g_crtExitCode = 1;
160 g_crtExitProcessing = (uint8_t)return_to_caller;
161
162 if (!quick_exit)
163 {
164 CRT_ExitCallback *handler_cursor = g_atexitHandlerNext;
165
166 if (g_atexitHandlerBase && handler_cursor > g_atexitHandlerBase)
167 {
168 do
169 {
170 CRT_ExitCallback exit_callback = *--handler_cursor;
171
172 if (exit_callback)
173 exit_callback();
174 } while (handler_cursor > g_atexitHandlerBase);
175 }
176
178 }
179
181
182 if (return_to_caller)
183 return;
184
186 ExitProcess(status);
187 /* no return */
188}
189
190// Original pcdogs.exe: 0x446cdd
191// Calls each non-NULL initializer in the half-open pointer range.
192void CRT_initterm(void (**first)(), void (**last)())
193{
194 for (void (**initializer_slot)() = first; initializer_slot < last; initializer_slot = &initializer_slot[1])
195 {
196 void (*initializer)(void) = *initializer_slot;
197
198 if (initializer)
199 initializer();
200 }
201}
202
203// Original pcdogs.exe: 0x446ef7
204// Writes the selected CRT fatal-error message, including the configured banner, and invokes the configured termination callback with status 255. This path does not return.
205void __amsg_exit(int32_t runtime_error)
206{
209
210 _NMSG_WRITE(runtime_error);
212 __builtin_unreachable();
213}
214
215// Original pcdogs.exe: 0x446f1c
216// Writes the CRT fatal-error banner and message and terminates the process with status 255.
217void CRT_fast_error_exit(int32_t runtime_error)
218{
221
222 _NMSG_WRITE(runtime_error);
223 ExitProcess(CRT_FATAL_EXIT_STATUS);
224 /* no return */
225}
226
227// Original pcdogs.exe: 0x449bde
228// Skips the quoted or unquoted program name and following whitespace in a command line while respecting multibyte characters.
230{
231 if (!g_crtInitialized)
233
234 char *cursor = g_commandLine;
235 if (*cursor == '"')
236 {
237 ++cursor;
238 while (*cursor && *cursor != '"')
239 {
240 if (CRT_ismbblead((uint8_t)*cursor))
241 ++cursor;
242 ++cursor;
243 }
244 if (*cursor == '"')
245 ++cursor;
246 }
247 else
248 {
249 while ((uint8_t)*cursor > ' ')
250 ++cursor;
251 }
252
253 while (*cursor && (uint8_t)*cursor <= ' ')
254 ++cursor;
255 return cursor;
256}
257
258// Original pcdogs.exe: 0x449c36
259// Builds a NULL-terminated array of copied environment strings, skipping entries that begin with an equals sign. On completion it frees the original flat environment block and records the initialized state.
261{
262 if (!g_crtInitialized)
264
265 size_t count = 0;
266 for (const char *entry = g_environmentBlock; *entry; entry += _strlen(entry) + 1)
267 {
268 if (*entry != '=')
269 ++count;
270 }
271
272 char **slot = CRT_malloc((count + 1) * sizeof(*slot));
273 g_environ = slot;
274 if (!slot)
276
277 const char *entry = g_environmentBlock;
278 while (*entry)
279 {
280 size_t size = _strlen(entry) + 1;
281 if (*entry != '=')
282 {
283 *slot = CRT_malloc(size);
284 if (!*slot)
286 CRT_strcpy(*slot++, entry);
287 }
288 entry += size;
289 }
290
292 g_environmentBlock = NULL;
293 *slot = NULL;
295}
296
297// Original pcdogs.exe: 0x449cef
298// Sizes and allocates a combined argument-pointer and string block, parses the command line, and installs the program-name, argc, and argv globals.
299int32_t CRT_setargv()
300{
301 int32_t argc_out;
302 int32_t char_count_out;
303
304 if (!g_crtInitialized)
306
307 GetModuleFileNameA(NULL, g_crtCommandLineBuffer, sizeof(g_crtCommandLineBuffer));
309 char *command_line = *g_commandLine ? g_commandLine : g_crtCommandLineBuffer;
310 _parse_cmdline(command_line, NULL, NULL, &argc_out, &char_count_out);
311
312 char **argv = CRT_malloc(char_count_out + argc_out * sizeof(*argv));
313 if (!argv)
315 char *arg_buffer = (char *)(argv + argc_out);
316 _parse_cmdline(command_line, argv, arg_buffer, &argc_out, &char_count_out);
317
318 int32_t result = argc_out - 1;
319
320 g_argv = argv;
321 g_argc = result;
322
323 return result;
324}
325
326// Original pcdogs.exe: 0x449d88
327// Counts argv slots (including the NULL sentinel) and packed string bytes.
328// Either output buffer can be omitted.
329void _parse_cmdline(char *command_line, char **argv, char *arg_buffer, int32_t *argc_out, int32_t *char_count_out)
330{
331 char *input = command_line;
332 char *output = arg_buffer;
333 *char_count_out = 0;
334 *argc_out = 1;
335 if (argv)
336 *argv++ = output;
337
338 if (*input == '"')
339 {
340 ++input;
341 while (*input && *input != '"')
342 {
343 if (g_crtMultibyteClassTable[1 + (uint8_t)*input] & CRT_MBC_LEAD)
344 {
345 // The quoted program name's sizing pass counts the lead byte
346 // twice and examines its trail byte on the next iteration.
347 ++*char_count_out;
348 if (output)
349 *output++ = *input++;
350 }
351 ++*char_count_out;
352 if (output)
353 *output++ = *input;
354 ++input;
355 }
356 if (*input == '"')
357 ++input;
358 if (output)
359 *output++ = '\0';
360 ++*char_count_out;
361 }
362 else
363 {
364 for (;;)
365 {
366 char character = *input++;
367 if (output)
368 *output++ = character;
369 ++*char_count_out;
370
371 if (g_crtMultibyteClassTable[1 + (uint8_t)character] & CRT_MBC_LEAD)
372 {
373 if (output)
374 *output++ = *input;
375 ++input;
376 ++*char_count_out;
377 }
378 if (character == '\0')
379 {
380 --input;
381 break;
382 }
383 if (character == ' ' || character == '\t')
384 {
385 if (output)
386 output[-1] = '\0';
387 break;
388 }
389 }
390 }
391
392 bool in_quotes = false;
393 for (;;)
394 {
395 while (*input == ' ' || *input == '\t')
396 ++input;
397 if (!*input)
398 break;
399 if (argv)
400 *argv++ = output;
401 ++*argc_out;
402
403 for (;;)
404 {
405 unsigned int backslashes = 0;
406 while (*input == '\\')
407 {
408 ++input;
409 ++backslashes;
410 }
411
412 bool copy_character = true;
413 if (*input == '"')
414 {
415 if ((backslashes & 1) == 0)
416 {
417 if (in_quotes && input[1] == '"')
418 ++input;
419 else
420 copy_character = false;
421 in_quotes = !in_quotes;
422 }
423 backslashes /= 2;
424 }
425
426 while (backslashes > 0)
427 {
428 if (output)
429 *output++ = '\\';
430 ++*char_count_out;
431 --backslashes;
432 }
433
434 if (!*input || (!in_quotes && (*input == ' ' || *input == '\t')))
435 break;
436 if (copy_character)
437 {
438 if (g_crtMultibyteClassTable[1 + (uint8_t)*input] & CRT_MBC_LEAD)
439 {
440 if (output)
441 *output++ = *input;
442 ++input;
443 ++*char_count_out;
444 }
445 if (output)
446 *output++ = *input;
447 ++*char_count_out;
448 }
449 ++input;
450 }
451
452 if (output)
453 *output++ = '\0';
454 ++*char_count_out;
455 }
456
457 if (argv)
458 *argv = NULL;
459 ++*argc_out;
460}
461
462// Original pcdogs.exe: 0x449f3c
463// Copies the process environment into CRT-owned ANSI storage, preferring the wide Windows environment API and converting when available. The corresponding Windows environment block is freed after copying.
465{
466 WCHAR *wide = NULL;
467 char *ansi = NULL;
468
469 switch (g_crtEnvStringsMode)
470 {
472 wide = GetEnvironmentStringsW();
473 if (wide)
475 else
476 {
477 ansi = GetEnvironmentStrings();
478 if (!ansi)
479 return NULL;
481 }
482 break;
483 case CRT_API_WIDE:
484 wide = GetEnvironmentStringsW();
485 if (!wide)
486 return NULL;
487 break;
488 case CRT_API_ANSI:
489 ansi = GetEnvironmentStrings();
490 if (!ansi)
491 return NULL;
492 break;
493 default:
494 return NULL;
495 }
496
497 if (ansi)
498 {
499 const char *end = ansi;
500 while (*end)
501 {
502 while (*end)
503 ++end;
504 ++end;
505 }
506 size_t bytes = (size_t)(end - ansi) + 1;
507 char *copy = CRT_malloc(bytes);
508 if (copy)
509 CRT_MoveBytesOverlapSafe(copy, ansi, bytes);
510 FreeEnvironmentStringsA(ansi);
511 return copy;
512 }
513
514 const WCHAR *end = wide;
515 while (*end)
516 {
517 while (*end)
518 ++end;
519 ++end;
520 }
521 int characters = (int)(end - wide) + 1;
522 int bytes = WideCharToMultiByte(CP_ACP, 0, wide, characters, NULL, 0, NULL, NULL);
523 char *copy = NULL;
524 if (bytes)
525 {
526 copy = CRT_malloc(bytes);
527 if (copy && !WideCharToMultiByte(CP_ACP, 0, wide, characters, copy, bytes, NULL, NULL))
528 {
529 CRT_free(copy);
530 copy = NULL;
531 }
532 }
533 FreeEnvironmentStringsW(wide);
534 return copy;
535}
536
537// Original pcdogs.exe: 0x44a150
538// Writes the configured runtime-error banner and invokes the optional banner callback when present.
540{
541 int32_t application_type = g_crtAppType;
542
543 if (application_type == CRT_APPLICATION_CONSOLE || (!application_type && g_crtConsoleMode == CRT_APPLICATION_CONSOLE))
544 {
546
549
551 }
552}
553
554// Original pcdogs.exe: 0x44a189
555// Finds a runtime-error message and displays it through standard error or a message box according to the CRT error-output mode.
556void _NMSG_WRITE(int32_t runtime_error_id)
557{
558 const uint32_t error_id = (uint32_t)runtime_error_id;
559 const struct CRT_RuntimeErrorEntry *error_entry = g_crtRuntimeErrors;
560 while (error_entry < g_crtRuntimeErrors + 18 && error_entry->error_id != error_id)
561 ++error_entry;
562 if (error_entry->error_id != error_id)
563 return;
564
565 int32_t application_type = g_crtAppType;
566
567 if (application_type == CRT_APPLICATION_CONSOLE || (!application_type && g_crtConsoleMode == CRT_APPLICATION_CONSOLE))
568 {
569 DWORD written;
570 DWORD length = _strlen(error_entry->message);
571 WriteFile(GetStdHandle(STD_ERROR_HANDLE), error_entry->message, length, &written, NULL);
572 }
573 else if (error_id != CRT_RUNTIME_NEWLINE)
574 {
575 char program_path[MAX_PATH];
576
577 if (!GetModuleFileNameA(NULL, program_path, sizeof(program_path)))
578 CRT_strcpy(program_path, "<program name unknown>");
579
580 char *display_path = program_path;
581
582 if (_strlen(program_path) + 1 > 0x3c)
583 {
584 display_path = program_path + _strlen(program_path) - 59;
585 _strncpy(display_path, "...", 3);
586 }
587
588 char text[160];
589
590 CRT_strcpy(text, "Runtime Error!\n\nProgram: ");
591 CRT_strcat(text, display_path);
592 CRT_strcat(text, "\n\n");
593 CRT_strcat(text, error_entry->message);
594 CRT_ShowMessageBoxA(text, "Microsoft Visual C++ Runtime Library", (MB_OK | MB_ICONHAND | MB_TASKMODAL | MB_SETFOREGROUND));
595 }
596}
597
598// Original pcdogs.exe: 0x44bbba
599// Loads the required user-interface entry points on demand, selects the active popup window when available, and displays the requested message box.
600int32_t CRT_ShowMessageBoxA(LPCSTR lp_text, LPCSTR lp_caption, UINT u_type)
601{
602 HWND owner_window = NULL;
603
604 if (!g_pMessageBoxA)
605 {
606 HMODULE h_module = LoadLibraryA("user32.dll");
607 if (!h_module)
608 return 0;
609
610 g_pMessageBoxA = (void *)GetProcAddress(h_module, "MessageBoxA");
611 if (!g_pMessageBoxA)
612 return 0;
613
614 g_pGetActiveWindow = (void *)GetProcAddress(h_module, "GetActiveWindow");
615 g_pGetLastActivePopup = (void *)GetProcAddress(h_module, "GetLastActivePopup");
616 }
617
618 HWND(__stdcall * get_active_window)() = g_pGetActiveWindow;
619
620 if (get_active_window)
621 {
622 owner_window = get_active_window();
623
624 if (owner_window)
625 {
626 HWND(__stdcall * get_last_active_popup)(HWND) = g_pGetLastActivePopup;
627
628 if (get_last_active_popup)
629 owner_window = get_last_active_popup(owner_window);
630 }
631 }
632
633 return g_pMessageBoxA(owner_window, lp_text, lp_caption, u_type);
634}
#define g_pGetLastActivePopup
#define g_crtGetModuleHandleAPtr
#define g_pMessageBoxA
int32_t Game_WinMain(HINSTANCE h_instance, HINSTANCE h_prev_instance, LPSTR lp_cmd_line, int32_t n_cmd_show)
Definition application.c:22
#define g_pGetActiveWindow
Definition globals.h:204
#define CRT_FATAL_EXIT_STATUS
Definition constants.h:309
@ CRT_API_UNSELECTED
Definition constants.h:115
@ CRT_API_WIDE
Definition constants.h:116
@ CRT_API_ANSI
Definition constants.h:117
#define CRT_MBC_LEAD
Definition constants.h:62
@ CRT_RUNTIME_EXIT_TABLE
Definition constants.h:259
@ CRT_RUNTIME_ARGUMENT_SPACE
Definition constants.h:257
@ CRT_RUNTIME_HEAP_INIT
Definition constants.h:262
@ CRT_RUNTIME_BANNER
Definition constants.h:264
@ CRT_RUNTIME_ENVIRONMENT_SPACE
Definition constants.h:258
@ CRT_RUNTIME_NEWLINE
Definition constants.h:263
@ CRT_APPLICATION_CONSOLE
Definition constants.h:239
uint32_t CRT_msize(void *ptr)
Definition heap.c:184
int32_t _heap_init(int32_t mt_flag)
Definition heap.c:203
void * CRT_malloc(uint32_t size)
Definition heap.c:16
void * CRT_realloc(void *ptr, uint32_t size)
Definition heap.c:65
void(*)() CRT_onexit(void(*callback)())
Definition functions.h:44
char * CRT_strcat(char *dest, char const *src)
Definition strings.c:172
void CRT_free(void *ptr)
Definition heap.c:164
void __initmbctable()
Definition locale.c:608
char * _strncpy(char *dest, char const *src, uint32_t count)
Definition strings.c:237
char * CRT_MoveBytesOverlapSafe(char *dest, char const *src, uint32_t count)
Definition strings.c:134
uint32_t _strlen(char const *str)
Definition strings.c:225
void _ioinit()
int32_t CRT_ismbblead(uint32_t character)
Definition locale.c:302
char * CRT_strcpy(char *dest, char const *src)
Definition strings.c:158
#define g_crtPreTerminators
Definition globals.h:331
#define g_crtExitProcessing
Definition globals.h:175
#define g_crtStartupFlags
Definition globals.h:172
#define g_crtEnvStringsMode
Definition globals.h:211
#define g_crtCommandLineBuffer
Definition globals.h:208
#define g_pCRT_ErrorHandler
Definition globals.h:94
#define g_crtExitCode
Definition globals.h:178
#define g_crtFloatingPointInitializer
Definition globals.h:91
#define g_crtMultibyteClassTable
Definition globals.h:268
#define g_crtConsoleMode
Definition globals.h:97
#define g_crtAppType
Definition globals.h:187
#define g_crtSubsystemInitializers
Definition globals.h:329
#define g_CRT_EnvironmentBlock
Definition globals.h:295
#define g_crtTerminators
Definition globals.h:332
#define g_crtApplicationInitializers
Definition globals.h:330
#define g_crtInitialized
Definition globals.h:298
#define g_crtExitInProgress
Definition globals.h:181
#define g_crtRuntimeErrors
Definition globals.h:338
#define g_crtRuntimeErrorBannerCallback
Definition globals.h:214
char * __crtGetEnvironmentStringsA()
Definition startup.c:464
int32_t CRT_atexit(CRT_ExitCallback callback)
Definition startup.c:99
void _parse_cmdline(char *command_line, char **argv, char *arg_buffer, int32_t *argc_out, int32_t *char_count_out)
Definition startup.c:329
void Runtime_NoOp()
Definition startup.c:60
void _doexit(int32_t status, int32_t quick_exit, int32_t return_to_caller)
Definition startup.c:151
void _cinit()
Definition startup.c:124
void CRT_InitializeAndRunWinMain(int32_t *startup_frame)
Definition startup.c:20
void __amsg_exit(int32_t runtime_error)
Definition startup.c:205
void CRT_exit_immediate(int32_t status)
Definition startup.c:143
void _atexit_init()
Definition startup.c:106
int32_t CRT_ShowMessageBoxA(LPCSTR lp_text, LPCSTR lp_caption, UINT u_type)
Definition startup.c:600
void CRT_initterm(void(**first)(), void(**last)())
Definition startup.c:192
void CRT_exit(int32_t status)
Definition startup.c:135
@ CRT_EXIT_TABLE_GROWTH_BYTES
Definition startup.c:15
@ CRT_EXIT_TABLE_INITIAL_BYTES
Definition startup.c:14
int32_t CRT_setargv()
Definition startup.c:299
void CRT_WriteRuntimeErrorBanner()
Definition startup.c:539
void CRT_fast_error_exit(int32_t runtime_error)
Definition startup.c:217
char * CRT_SkipProgramNameInCmdLine()
Definition startup.c:229
void _setenvp()
Definition startup.c:260
void _NMSG_WRITE(int32_t runtime_error_id)
Definition startup.c:556
uint32_t error_id
Definition types.h:316
#define g_windowsVersionMinor
Definition values.h:510
#define g_windowsVersionCombined
Definition values.h:504
#define g_environmentBlock
Definition values.h:525
void(* CRT_ExitCallback)(void)
Definition values.h:878
#define g_atexitHandlerNext
Definition values.h:881
#define g_environ
Definition values.h:519
#define g_argv
Definition values.h:516
#define g_windowsVersionMajor
Definition values.h:507
#define g_atexitHandlerBase
Definition values.h:884
#define g_argc
Definition values.h:513
#define g_commandLine
Definition values.h:876
#define g_pgmptr
Definition values.h:522
@ STD_ERROR_HANDLE
Definition win32_file.h:32
#define MB_SETFOREGROUND
#define MB_ICONHAND
#define MB_TASKMODAL
@ SW_SHOWDEFAULT
#define MB_OK