deploy-stub.c 19 KB

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