Panda3D
Loading...
Searching...
No Matches
deploy-stub.c
1/* Python interpreter main program for frozen scripts */
2
3#include "Python.h"
4#ifdef _WIN32
5# include "malloc.h"
6# include <Shlobj.h>
7#else
8# include <sys/mman.h>
9# include <pwd.h>
10#endif
11
12#ifdef __FreeBSD__
13# include <sys/sysctl.h>
14#endif
15
16#ifdef __APPLE__
17# include <mach-o/dyld.h>
18# include <libgen.h>
19#endif
20
21#include <stdio.h>
22#include <stdint.h>
23#include <fcntl.h>
24
25#if PY_MAJOR_VERSION >= 3
26# include <locale.h>
27
28# if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION < 5
29# define Py_DecodeLocale _Py_char2wchar
30# endif
31
32# include "structmember.h"
33#endif
34
35/* Leave room for future expansion. We only read pointer 0, but there are
36 other pointers that are being read by configPageManager.cxx. */
37#define MAX_NUM_POINTERS 24
38
39/* Stored in the flags field of the blobinfo structure below. */
40enum Flags {
41 F_log_append = 1,
42 F_log_filename_strftime = 2,
43 F_keep_docstrings = 4,
44};
45
46/* Define an exposed symbol where we store the offset to the module data. */
47#ifdef _MSC_VER
48__declspec(dllexport)
49#else
50__attribute__((__visibility__("default"), used))
51#endif
52volatile struct {
53 uint64_t blob_offset;
54 uint64_t blob_size;
55 uint16_t version;
56 uint16_t num_pointers;
57 uint16_t codepage;
58 uint16_t flags;
59 uint64_t reserved;
60 void *pointers[MAX_NUM_POINTERS];
61
62 // The reason we initialize it to -1 is because otherwise, smart linkers may
63 // end up putting it in the .bss section for zero-initialized data.
64} blobinfo = {(uint64_t)-1};
65
66
67#ifdef _WIN32
68// These placeholders can have their names changed by deploy-stub.
69__declspec(dllexport) DWORD SymbolPlaceholder___________________ = 0x00000001;
70__declspec(dllexport) DWORD SymbolPlaceholder__ = 0x00000001;
71#endif
72
73#ifdef MS_WINDOWS
74# define WIN32_LEAN_AND_MEAN
75# include <windows.h>
76
77extern void PyWinFreeze_ExeInit(void);
78extern void PyWinFreeze_ExeTerm(void);
79
80static struct _inittab extensions[] = {
81 {0, 0},
82};
83
84#if PY_MAJOR_VERSION >= 3
85# define WIN_UNICODE
86#endif
87#endif
88
89#ifdef _WIN32
90static wchar_t *log_pathw = NULL;
91#endif
92
93#if PY_VERSION_HEX >= 0x030b0000
94typedef struct {
95 const char *name;
96 const unsigned char *code;
97 int size;
98} ModuleDef;
99#else
100typedef struct _frozen ModuleDef;
101#endif
102
103#if defined(_WIN32) && PY_VERSION_HEX < 0x03060000
104static int supports_code_page(UINT cp) {
105 if (cp == 0) {
106 cp = GetACP();
107 }
108
109 /* Shortcut, because we know that these encodings are bundled by default--
110 * see FreezeTool.py and Python's encodings/aliases.py */
111 if (cp != 0 && cp != 1252 && cp != 367 && cp != 437 && cp != 850 && cp != 819) {
112 const struct _frozen *moddef;
113 char codec[100];
114
115 /* Check if the codec was frozen into the program. We can't check this
116 * using _PyCodec_Lookup, since Python hasn't been initialized yet. */
117 PyOS_snprintf(codec, sizeof(codec), "encodings.cp%u", (unsigned int)cp);
118
119 moddef = PyImport_FrozenModules;
120 while (moddef->name) {
121 if (strcmp(moddef->name, codec) == 0) {
122 return 1;
123 }
124 ++moddef;
125 }
126 return 0;
127 }
128
129 return 1;
130}
131#endif
132
133/**
134 * Sets the main_dir field of the blobinfo structure, but only if it wasn't
135 * already set.
136 */
137static void set_main_dir(char *main_dir) {
138 if (blobinfo.num_pointers >= 10) {
139 if (blobinfo.num_pointers == 10) {
140 ++blobinfo.num_pointers;
141 blobinfo.pointers[10] = NULL;
142 }
143 if (blobinfo.pointers[10] == NULL) {
144 blobinfo.pointers[10] = main_dir;
145 }
146 }
147}
148
149/**
150 * Creates the parent directories of the given path. Returns 1 on success.
151 */
152#ifdef _WIN32
153static int mkdir_parent(const wchar_t *path) {
154 // Copy the path to a temporary buffer.
155 wchar_t buffer[4096];
156 size_t buflen = wcslen(path);
157 if (buflen + 1 >= _countof(buffer)) {
158 return 0;
159 }
160 wcscpy_s(buffer, _countof(buffer), path);
161
162 // Seek back to find the last path separator.
163 while (buflen-- > 0) {
164 if (buffer[buflen] == '/' || buffer[buflen] == '\\') {
165 buffer[buflen] = 0;
166 break;
167 }
168 }
169 if (buflen == (size_t)-1 || buflen == 0) {
170 // There was no path separator, or this was the root directory.
171 return 0;
172 }
173
174 if (CreateDirectoryW(buffer, NULL) != 0) {
175 // Success!
176 return 1;
177 }
178
179 // Failed.
180 DWORD last_error = GetLastError();
181 if (last_error == ERROR_ALREADY_EXISTS) {
182 // Not really an error: the directory is already there.
183 return 1;
184 }
185
186 if (last_error == ERROR_PATH_NOT_FOUND) {
187 // We need to make the parent directory first.
188 if (mkdir_parent(buffer)) {
189 // Parent successfully created. Try again to make the child.
190 if (CreateDirectoryW(buffer, NULL) != 0) {
191 // Got it!
192 return 1;
193 }
194 }
195 }
196 return 0;
197}
198#else
199static int mkdir_parent(const char *path) {
200 // Copy the path to a temporary buffer.
201 char buffer[4096];
202 size_t buflen = strlen(path);
203 if (buflen + 1 >= sizeof(buffer)) {
204 return 0;
205 }
206 strcpy(buffer, path);
207
208 // Seek back to find the last path separator.
209 while (buflen-- > 0) {
210 if (buffer[buflen] == '/') {
211 buffer[buflen] = 0;
212 break;
213 }
214 }
215 if (buflen == (size_t)-1 || buflen == 0) {
216 // There was no path separator, or this was the root directory.
217 return 0;
218 }
219 if (mkdir(buffer, 0755) == 0) {
220 // Success!
221 return 1;
222 }
223
224 // Failed.
225 if (errno == EEXIST) {
226 // Not really an error: the directory is already there.
227 return 1;
228 }
229
230 if (errno == ENOENT || errno == EACCES) {
231 // We need to make the parent directory first.
232 if (mkdir_parent(buffer)) {
233 // Parent successfully created. Try again to make the child.
234 if (mkdir(buffer, 0755) == 0) {
235 // Got it!
236 return 1;
237 }
238 }
239 }
240 return 0;
241}
242#endif
243
244/**
245 * Redirects the output streams to point to the log file with the given path.
246 *
247 * @param path specifies the location of log file, may start with ~
248 * @param append should be nonzero if it should not truncate the log file.
249 */
250static int setup_logging(const char *path, int append) {
251#ifdef _WIN32
252 // Does it start with a tilde? Perform tilde expansion if so.
253 wchar_t *pathw = (wchar_t *)malloc(sizeof(wchar_t) * MAX_PATH);
254 pathw[0] = 0;
255 size_t offset = 0;
256 if (path[0] == '~' && (path[1] == 0 || path[1] == '/' || path[1] == '\\')) {
257 // Strip off the tilde.
258 ++path;
259
260 // Get the home directory path for the current user.
261 if (!SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_PROFILE, NULL, 0, pathw))) {
262 free(pathw);
263 return 0;
264 }
265 offset = wcslen(pathw);
266 }
267
268 // We need to convert the rest of the path from UTF-8 to UTF-16.
269 if (MultiByteToWideChar(CP_UTF8, 0, path, -1, pathw + offset,
270 (int)(MAX_PATH - offset)) == 0) {
271 free(pathw);
272 return 0;
273 }
274
275 DWORD access = append ? FILE_APPEND_DATA : (GENERIC_READ | GENERIC_WRITE);
276 int creation = append ? OPEN_ALWAYS : CREATE_ALWAYS;
277 HANDLE handle = CreateFileW(pathw, access, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
278 NULL, creation, FILE_ATTRIBUTE_NORMAL, NULL);
279
280 if (handle == INVALID_HANDLE_VALUE) {
281 // Make the parent directories first.
282 mkdir_parent(pathw);
283 handle = CreateFileW(pathw, access, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
284 NULL, creation, FILE_ATTRIBUTE_NORMAL, NULL);
285 }
286
287 if (handle == INVALID_HANDLE_VALUE) {
288 free(pathw);
289 return 0;
290 }
291
292 log_pathw = pathw;
293
294 if (append) {
295 SetFilePointer(handle, 0, NULL, FILE_END);
296 }
297
298 SetStdHandle(STD_OUTPUT_HANDLE, handle);
299 SetStdHandle(STD_ERROR_HANDLE, handle);
300
301 // If we are running under the UCRT in a GUI application, we can't be sure
302 // that we have valid fds for stdout and stderr, so we have to set them up.
303 // One way to do this is to reopen them to something silly (like NUL).
304 if (_fileno(stdout) < 0) {
305 _close(1);
306 _wfreopen(L"\\\\.\\NUL", L"w", stdout);
307 }
308
309 if (_fileno(stderr) < 0) {
310 _close(2);
311 _wfreopen(L"\\\\.\\NUL", L"w", stderr);
312 }
313
314 // Now replace the stdout and stderr file descriptors with one pointing to
315 // our desired handle.
316 int fd = _open_osfhandle((intptr_t)handle, _O_WRONLY | _O_TEXT | _O_APPEND);
317 _dup2(fd, _fileno(stdout));
318 _dup2(fd, _fileno(stderr));
319 _close(fd);
320
321 return 1;
322#else
323 // Does it start with a tilde? Perform tilde expansion if so.
324 char buffer[PATH_MAX * 2];
325 size_t offset = 0;
326 if (path[0] == '~' && (path[1] == 0 || path[1] == '/')) {
327 // Strip off the tilde.
328 ++path;
329
330 // Get the home directory path for the current user.
331 const char *home_dir = getenv("HOME");
332 if (home_dir == NULL) {
333 home_dir = getpwuid(getuid())->pw_dir;
334 }
335 offset = strlen(home_dir);
336 assert(offset < sizeof(buffer));
337 strncpy(buffer, home_dir, sizeof(buffer));
338 }
339
340 // Copy over the rest of the path.
341 strcpy(buffer + offset, path);
342
343 mode_t mode = O_CREAT | O_WRONLY | (append ? O_APPEND : O_TRUNC);
344 int fd = open(buffer, mode, 0644);
345 if (fd == -1) {
346 // Make the parent directories first.
347 mkdir_parent(buffer);
348 fd = open(buffer, mode, 0644);
349 }
350
351 if (fd == -1) {
352 perror(buffer);
353 return 0;
354 }
355
356 fflush(stdout);
357 fflush(stderr);
358
359 dup2(fd, 1);
360 dup2(fd, 2);
361
362 close(fd);
363 return 1;
364#endif
365}
366
367/**
368 * Sets the line_buffering property on a TextIOWrapper object.
369 */
370#if PY_MAJOR_VERSION >= 3
371static int enable_line_buffering(PyObject *file) {
372#if PY_VERSION_HEX >= 0x03070000
373 /* Python 3.7 has a useful reconfigure() method. */
374 PyObject *kwargs = _PyDict_NewPresized(1);
375 PyDict_SetItemString(kwargs, "line_buffering", Py_True);
376 PyObject *args = PyTuple_New(0);
377
378 PyObject *method = PyObject_GetAttrString(file, "reconfigure");
379 if (method != NULL) {
380 PyObject *result = PyObject_Call(method, args, kwargs);
381 Py_DECREF(method);
382 Py_DECREF(kwargs);
383 Py_DECREF(args);
384 if (result != NULL) {
385 Py_DECREF(result);
386 } else {
387 PyErr_Clear();
388 return 0;
389 }
390 } else {
391 Py_DECREF(kwargs);
392 Py_DECREF(args);
393 PyErr_Clear();
394 return 0;
395 }
396#else
397 /* Older versions just don't expose a way to reconfigure(), but it's still
398 safe to override the property; we just have to use a hack to do it,
399 because it's officially marked "readonly". */
400
401 PyTypeObject *type = Py_TYPE(file);
402 PyMemberDef *member = type->tp_members;
403
404 while (member != NULL && member->name != NULL) {
405 if (strcmp(member->name, "line_buffering") == 0) {
406 *((char *)file + member->offset) = 1;
407 return 1;
408 }
409 ++member;
410 }
411 fflush(stdout);
412#endif
413 return 1;
414}
415#endif
416
417/* Main program */
418
419#ifdef WIN_UNICODE
420int Py_FrozenMain(int argc, wchar_t **argv)
421#else
422int Py_FrozenMain(int argc, char **argv)
423#endif
424{
425 char *p;
426 int n, sts = 1;
427 int unbuffered = 0;
428#ifndef NDEBUG
429 int inspect = 0;
430#endif
431
432#if PY_MAJOR_VERSION >= 3 && !defined(WIN_UNICODE)
433 int i;
434 char *oldloc;
435 wchar_t **argv_copy = NULL;
436 /* We need a second copies, as Python might modify the first one. */
437 wchar_t **argv_copy2 = NULL;
438
439 if (argc > 0) {
440 argv_copy = (wchar_t **)alloca(sizeof(wchar_t *) * argc);
441 argv_copy2 = (wchar_t **)alloca(sizeof(wchar_t *) * argc);
442 }
443#endif
444
445#if defined(MS_WINDOWS) && PY_VERSION_HEX >= 0x03040000 && PY_VERSION_HEX < 0x03060000
446 if (!supports_code_page(GetConsoleOutputCP()) ||
447 !supports_code_page(GetConsoleCP())) {
448 /* Revert to the active codepage, and tell Python to use the 'mbcs'
449 * encoding (which always uses the active codepage). In 99% of cases,
450 * this will be the same thing anyway. */
451 UINT acp = GetACP();
452 SetConsoleCP(acp);
453 SetConsoleOutputCP(acp);
454 Py_SetStandardStreamEncoding("mbcs", NULL);
455 }
456#endif
457
458 Py_FrozenFlag = 1; /* Suppress errors from getpath.c */
459 Py_NoSiteFlag = 0;
460 Py_NoUserSiteDirectory = 1;
461
462#if PY_VERSION_HEX >= 0x03020000
463 if (blobinfo.flags & F_keep_docstrings) {
464 Py_OptimizeFlag = 1;
465 } else {
466 Py_OptimizeFlag = 2;
467 }
468#endif
469
470#ifndef NDEBUG
471 if ((p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
472 inspect = 1;
473#endif
474 if ((p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0')
475 unbuffered = 1;
476
477 if (unbuffered) {
478 setbuf(stdin, (char *)NULL);
479 setbuf(stdout, (char *)NULL);
480 setbuf(stderr, (char *)NULL);
481 }
482
483#if PY_MAJOR_VERSION >= 3 && !defined(WIN_UNICODE)
484 oldloc = setlocale(LC_ALL, NULL);
485 setlocale(LC_ALL, "");
486 for (i = 0; i < argc; i++) {
487 argv_copy[i] = Py_DecodeLocale(argv[i], NULL);
488 argv_copy2[i] = argv_copy[i];
489 if (!argv_copy[i]) {
490 fprintf(stderr, "Unable to decode the command line argument #%i\n",
491 i + 1);
492 argc = i;
493 goto error;
494 }
495 }
496 setlocale(LC_ALL, oldloc);
497#endif
498
499#ifdef MS_WINDOWS
500 PyImport_ExtendInittab(extensions);
501#endif /* MS_WINDOWS */
502
503 if (argc >= 1) {
504#if PY_MAJOR_VERSION >= 3 && !defined(WIN_UNICODE)
505 Py_SetProgramName(argv_copy[0]);
506#else
507 Py_SetProgramName(argv[0]);
508#endif
509 }
510
511 Py_Initialize();
512#ifdef MS_WINDOWS
513 PyWinFreeze_ExeInit();
514#endif
515
516#if defined(MS_WINDOWS) && PY_VERSION_HEX < 0x03040000
517 /* We can't rely on our overriding of the standard I/O to work on older
518 * versions of Python, since they are compiled with an incompatible CRT.
519 * The best solution I've found was to just replace sys.stdout/stderr with
520 * the log file reopened in append mode (which requires not locking it for
521 * write, and also passing in _O_APPEND above, and disabling buffering).
522 * It's not the most elegant solution, but it's better than crashing. */
523#if PY_MAJOR_VERSION < 3
524 if (log_pathw != NULL) {
525 PyObject *uniobj = PyUnicode_FromWideChar(log_pathw, (Py_ssize_t)wcslen(log_pathw));
526 PyObject *file = PyObject_CallFunction((PyObject*)&PyFile_Type, "Nsi", uniobj, "a", 0);
527
528 if (file != NULL) {
529 PyFile_SetEncodingAndErrors(file, "utf-8", NULL);
530
531 PySys_SetObject("stdout", file);
532 PySys_SetObject("stderr", file);
533 PySys_SetObject("__stdout__", file);
534 PySys_SetObject("__stderr__", file);
535
536 /* Be sure to disable buffering, otherwise we'll get overlap */
537 setbuf(stdout, (char *)NULL);
538 setbuf(stderr, (char *)NULL);
539 }
540 }
541 else
542#endif
543 if (!supports_code_page(GetConsoleOutputCP()) ||
544 !supports_code_page(GetConsoleCP())) {
545 /* Same hack as before except for Python 2.7, which doesn't seem to have
546 * a way to set the encoding ahead of time, and setting PYTHONIOENCODING
547 * doesn't seem to work. Fortunately, Python 2.7 doesn't usually start
548 * causing codec errors until the first print statement. */
549 PyObject *sys_stream;
550 UINT acp = GetACP();
551 SetConsoleCP(acp);
552 SetConsoleOutputCP(acp);
553
554 sys_stream = PySys_GetObject("stdin");
555 if (sys_stream && PyFile_Check(sys_stream)) {
556 PyFile_SetEncodingAndErrors(sys_stream, "mbcs", NULL);
557 }
558 sys_stream = PySys_GetObject("stdout");
559 if (sys_stream && PyFile_Check(sys_stream)) {
560 PyFile_SetEncodingAndErrors(sys_stream, "mbcs", NULL);
561 }
562 sys_stream = PySys_GetObject("stderr");
563 if (sys_stream && PyFile_Check(sys_stream)) {
564 PyFile_SetEncodingAndErrors(sys_stream, "mbcs", NULL);
565 }
566 }
567#endif
568
569#if defined(MS_WINDOWS) && PY_VERSION_HEX >= 0x03040000
570 /* Ensure that line buffering is enabled on the output streams. */
571 if (!unbuffered) {
572 /* Python 3.7 has a useful reconfigure() method. */
573 PyObject *sys_stream;
574 sys_stream = PySys_GetObject("__stdout__");
575 if (sys_stream && !enable_line_buffering(sys_stream)) {
576 fprintf(stderr, "Failed to enable line buffering on sys.stdout\n");
577 fflush(stderr);
578 }
579 sys_stream = PySys_GetObject("__stderr__");
580 if (sys_stream && !enable_line_buffering(sys_stream)) {
581 fprintf(stderr, "Failed to enable line buffering on sys.stderr\n");
582 fflush(stderr);
583 }
584 }
585#endif
586
587 if (Py_VerboseFlag)
588 fprintf(stderr, "Python %s\n%s\n",
589 Py_GetVersion(), Py_GetCopyright());
590
591#if PY_MAJOR_VERSION >= 3 && !defined(WIN_UNICODE)
592 PySys_SetArgv(argc, argv_copy);
593#else
594 PySys_SetArgv(argc, argv);
595#endif
596
597#ifdef MACOS_APP_BUNDLE
598 // Add the Frameworks directory to sys.path.
599 char buffer[PATH_MAX];
600 uint32_t bufsize = sizeof(buffer);
601 if (_NSGetExecutablePath(buffer, &bufsize) != 0) {
602 assert(false);
603 return 1;
604 }
605 char resolved[PATH_MAX];
606 if (!realpath(buffer, resolved)) {
607 perror("realpath");
608 return 1;
609 }
610 const char *dir = dirname(resolved);
611 sprintf(buffer, "%s/../Frameworks", dir);
612
613 PyObject *sys_path = PyList_New(1);
614 #if PY_MAJOR_VERSION >= 3
615 PyList_SET_ITEM(sys_path, 0, PyUnicode_FromString(buffer));
616 #else
617 PyList_SET_ITEM(sys_path, 0, PyString_FromString(buffer));
618 #endif
619 PySys_SetObject("path", sys_path);
620 Py_DECREF(sys_path);
621
622 // Now, store a path to the Resources directory into the main_dir pointer,
623 // for ConfigPageManager to read out and assign to MAIN_DIR.
624 sprintf(buffer, "%s/../Resources", dir);
625 set_main_dir(buffer);
626
627 // Finally, chdir to it, so that regular Python files are read from the
628 // right location.
629 chdir(buffer);
630#endif
631
632 n = PyImport_ImportFrozenModule("__main__");
633 if (n == 0)
634 Py_FatalError("__main__ not frozen");
635 if (n < 0) {
636 PyErr_Print();
637 sts = 1;
638 }
639 else
640 sts = 0;
641
642#ifndef NDEBUG
643 if (inspect && isatty((int)fileno(stdin)))
644 sts = PyRun_AnyFile(stdin, "<stdin>") != 0;
645#endif
646
647#ifdef MS_WINDOWS
648 PyWinFreeze_ExeTerm();
649#endif
650 Py_Finalize();
651
652#if PY_MAJOR_VERSION >= 3 && !defined(WIN_UNICODE)
653error:
654 if (argv_copy2) {
655 for (i = 0; i < argc; i++) {
656#if PY_MAJOR_VERSION > 3 || PY_MINOR_VERSION >= 4
657 PyMem_RawFree(argv_copy2[i]);
658#else
659 PyMem_Free(argv_copy2[i]);
660#endif
661 }
662 }
663#endif
664 return sts;
665}
666
667/**
668 * Maps the binary blob at the given memory address to memory, and returns the
669 * pointer to the beginning of it.
670 */
671static void *map_blob(off_t offset, size_t size) {
672 void *blob;
673 FILE *runtime;
674
675#ifdef _WIN32
676 wchar_t buffer[2048];
677 GetModuleFileNameW(NULL, buffer, 2048);
678 runtime = _wfopen(buffer, L"rb");
679#elif defined(__FreeBSD__)
680 size_t bufsize = 4096;
681 char buffer[4096];
682 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
683 mib[3] = getpid();
684 if (sysctl(mib, 4, (void *)buffer, &bufsize, NULL, 0) == -1) {
685 perror("sysctl");
686 return NULL;
687 }
688 runtime = fopen(buffer, "rb");
689#elif defined(__APPLE__)
690 char buffer[4096];
691 uint32_t bufsize = sizeof(buffer);
692 if (_NSGetExecutablePath(buffer, &bufsize) != 0) {
693 return NULL;
694 }
695 runtime = fopen(buffer, "rb");
696#else
697 char buffer[4096];
698 ssize_t pathlen = readlink("/proc/self/exe", buffer, sizeof(buffer) - 1);
699 if (pathlen <= 0) {
700 perror("readlink(/proc/self/exe)");
701 return NULL;
702 }
703 buffer[pathlen] = '\0';
704 runtime = fopen(buffer, "rb");
705#endif
706
707 // Get offsets. In version 0, we read it from the end of the file.
708 if (blobinfo.version == 0) {
709 uint64_t end, begin;
710 fseek(runtime, -8, SEEK_END);
711 end = ftell(runtime);
712 fread(&begin, 8, 1, runtime);
713
714 offset = (off_t)begin;
715 size = (size_t)(end - begin);
716 }
717
718 // mmap the section indicated by the offset (or malloc/fread on windows)
719#ifdef _WIN32
720 blob = (void *)malloc(size);
721 assert(blob != NULL);
722 fseek(runtime, (long)offset, SEEK_SET);
723 fread(blob, size, 1, runtime);
724#else
725 blob = (void *)mmap(0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fileno(runtime), offset);
726 assert(blob != MAP_FAILED);
727#endif
728
729 fclose(runtime);
730 return blob;
731}
732
733/**
734 * The inverse of map_blob.
735 */
736static void unmap_blob(void *blob) {
737 if (blob) {
738#ifdef _WIN32
739 free(blob);
740#else
741 munmap(blob, blobinfo.blob_size);
742#endif
743 }
744}
745
746/**
747 * Main entry point to deploy-stub.
748 */
749#if defined(_WIN32) && PY_MAJOR_VERSION >= 3
750int wmain(int argc, wchar_t *argv[]) {
751#else
752int main(int argc, char *argv[]) {
753#endif
754 int retval;
755 ModuleDef *moddef;
756 const char *log_filename;
757 void *blob = NULL;
758 log_filename = NULL;
759
760#ifdef __APPLE__
761 // Strip a -psn_xxx argument passed in by macOS when run from an .app bundle.
762 if (argc > 1 && strncmp(argv[1], "-psn_", 5) == 0) {
763 argv[1] = argv[0];
764 ++argv;
765 --argc;
766 }
767#endif
768
769 /*
770 printf("blob_offset: %d\n", (int)blobinfo.blob_offset);
771 printf("blob_size: %d\n", (int)blobinfo.blob_size);
772 printf("version: %d\n", (int)blobinfo.version);
773 printf("num_pointers: %d\n", (int)blobinfo.num_pointers);
774 printf("codepage: %d\n", (int)blobinfo.codepage);
775 printf("flags: %d\n", (int)blobinfo.flags);
776 printf("reserved: %d\n", (int)blobinfo.reserved);
777 */
778
779 // If we have a blob offset, we have to map the blob to memory.
780 if (blobinfo.version == 0 || blobinfo.blob_offset != 0) {
781 void *blob = map_blob((off_t)blobinfo.blob_offset, (size_t)blobinfo.blob_size);
782 assert(blob != NULL);
783
784 // Offset the pointers in the header using the base mmap address.
785 if (blobinfo.version > 0 && blobinfo.num_pointers > 0) {
786 uint32_t i;
787 assert(blobinfo.num_pointers <= MAX_NUM_POINTERS);
788 for (i = 0; i < blobinfo.num_pointers; ++i) {
789 // Only offset if the pointer is non-NULL. Except for the first
790 // pointer, which may never be NULL and usually (but not always)
791 // points to the beginning of the blob.
792 if (i == 0 || blobinfo.pointers[i] != 0) {
793 blobinfo.pointers[i] = (void *)((uintptr_t)blobinfo.pointers[i] + (uintptr_t)blob);
794 }
795 }
796 if (blobinfo.num_pointers >= 12) {
797 log_filename = blobinfo.pointers[11];
798 }
799 } else {
800 blobinfo.pointers[0] = blob;
801 }
802
803 // Offset the pointers in the module table using the base mmap address.
804 moddef = blobinfo.pointers[0];
805#if PY_VERSION_HEX < 0x030b0000
806 PyImport_FrozenModules = moddef;
807#endif
808 while (moddef->name) {
809 moddef->name = (char *)((uintptr_t)moddef->name + (uintptr_t)blob);
810 if (moddef->code != 0) {
811 moddef->code = (unsigned char *)((uintptr_t)moddef->code + (uintptr_t)blob);
812 }
813 //printf("MOD: %s %p %d\n", moddef->name, (void*)moddef->code, moddef->size);
814 moddef++;
815 }
816
817 // In Python 3.11, we need to convert this to the new structure format.
818#if PY_VERSION_HEX >= 0x030b0000
819 ModuleDef *moddef_end = moddef;
820 ptrdiff_t num_modules = moddef - (ModuleDef *)blobinfo.pointers[0];
821 struct _frozen *new_moddef = (struct _frozen *)calloc(num_modules + 1, sizeof(struct _frozen));
822 PyImport_FrozenModules = new_moddef;
823 for (moddef = blobinfo.pointers[0]; moddef < moddef_end; ++moddef) {
824 new_moddef->name = moddef->name;
825 new_moddef->code = moddef->code;
826 new_moddef->size = moddef->size < 0 ? -(moddef->size) : moddef->size;
827 new_moddef->is_package = moddef->size < 0;
828 new_moddef->get_code = NULL;
829 new_moddef++;
830 }
831#endif
832 } else {
833 PyImport_FrozenModules = blobinfo.pointers[0];
834 }
835
836 if (log_filename != NULL) {
837 char log_filename_buf[4096];
838 if (blobinfo.flags & F_log_filename_strftime) {
839 log_filename_buf[0] = 0;
840 time_t now = time(NULL);
841 if (strftime(log_filename_buf, sizeof(log_filename_buf), log_filename, localtime(&now)) > 0) {
842 log_filename = log_filename_buf;
843 }
844 }
845 setup_logging(log_filename, (blobinfo.flags & F_log_append) != 0);
846 }
847
848#ifdef _WIN32
849 if (blobinfo.codepage != 0) {
850 SetConsoleCP(blobinfo.codepage);
851 SetConsoleOutputCP(blobinfo.codepage);
852 }
853#endif
854
855 // Run frozen application
856 retval = Py_FrozenMain(argc, argv);
857
858 fflush(stdout);
859 fflush(stderr);
860
861#if PY_VERSION_HEX >= 0x030b0000
862 free((void *)PyImport_FrozenModules);
863 PyImport_FrozenModules = NULL;
864#endif
865
866 unmap_blob(blob);
867 return retval;
868}
869
870#ifdef WIN_UNICODE
871int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, wchar_t *lpCmdLine, int nCmdShow) {
872 return wmain(__argc, __wargv);
873}
874#elif defined(_WIN32)
875int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, char *lpCmdLine, int nCmdShow) {
876 return main(__argc, __argv);
877}
878#endif