deploy-stub.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  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. if (close(fd) < 0) {
  278. perror("setup_logging: close");
  279. }
  280. return 1;
  281. #endif
  282. }
  283. /**
  284. * Sets the line_buffering property on a TextIOWrapper object.
  285. */
  286. static int enable_line_buffering(PyObject *file) {
  287. #if PY_VERSION_HEX >= 0x03070000
  288. /* Python 3.7 has a useful reconfigure() method. */
  289. PyObject *kwargs = _PyDict_NewPresized(1);
  290. PyDict_SetItemString(kwargs, "line_buffering", Py_True);
  291. PyObject *args = PyTuple_New(0);
  292. PyObject *method = PyObject_GetAttrString(file, "reconfigure");
  293. if (method != NULL) {
  294. PyObject *result = PyObject_Call(method, args, kwargs);
  295. Py_DECREF(method);
  296. Py_DECREF(kwargs);
  297. Py_DECREF(args);
  298. if (result != NULL) {
  299. Py_DECREF(result);
  300. } else {
  301. PyErr_Clear();
  302. return 0;
  303. }
  304. } else {
  305. Py_DECREF(kwargs);
  306. Py_DECREF(args);
  307. PyErr_Clear();
  308. return 0;
  309. }
  310. #else
  311. /* Older versions just don't expose a way to reconfigure(), but it's still
  312. safe to override the property; we just have to use a hack to do it,
  313. because it's officially marked "readonly". */
  314. PyTypeObject *type = Py_TYPE(file);
  315. PyMemberDef *member = type->tp_members;
  316. while (member != NULL && member->name != NULL) {
  317. if (strcmp(member->name, "line_buffering") == 0) {
  318. *((char *)file + member->offset) = 1;
  319. return 1;
  320. }
  321. ++member;
  322. }
  323. fflush(stdout);
  324. #endif
  325. return 1;
  326. }
  327. /* Main program */
  328. #ifdef WIN_UNICODE
  329. int Py_FrozenMain(int argc, wchar_t **argv)
  330. #else
  331. int Py_FrozenMain(int argc, char **argv)
  332. #endif
  333. {
  334. char *p;
  335. int n, sts = 1;
  336. int unbuffered = 0;
  337. #ifndef NDEBUG
  338. int inspect = 0;
  339. #endif
  340. #ifndef WIN_UNICODE
  341. int i;
  342. char *oldloc;
  343. wchar_t **argv_copy = NULL;
  344. /* We need a second copies, as Python might modify the first one. */
  345. wchar_t **argv_copy2 = NULL;
  346. if (argc > 0) {
  347. argv_copy = (wchar_t **)alloca(sizeof(wchar_t *) * argc);
  348. argv_copy2 = (wchar_t **)alloca(sizeof(wchar_t *) * argc);
  349. }
  350. #endif
  351. Py_FrozenFlag = 1; /* Suppress errors from getpath.c */
  352. Py_NoSiteFlag = 0;
  353. Py_NoUserSiteDirectory = 1;
  354. #if PY_VERSION_HEX >= 0x03020000
  355. if (blobinfo.flags & F_keep_docstrings) {
  356. Py_OptimizeFlag = 1;
  357. } else {
  358. Py_OptimizeFlag = 2;
  359. }
  360. #endif
  361. #ifndef NDEBUG
  362. if ((p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
  363. inspect = 1;
  364. #endif
  365. if ((p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0')
  366. unbuffered = 1;
  367. if (unbuffered) {
  368. setbuf(stdin, (char *)NULL);
  369. setbuf(stdout, (char *)NULL);
  370. setbuf(stderr, (char *)NULL);
  371. }
  372. #ifndef WIN_UNICODE
  373. oldloc = setlocale(LC_ALL, NULL);
  374. setlocale(LC_ALL, "");
  375. for (i = 0; i < argc; i++) {
  376. argv_copy[i] = Py_DecodeLocale(argv[i], NULL);
  377. argv_copy2[i] = argv_copy[i];
  378. if (!argv_copy[i]) {
  379. fprintf(stderr, "Unable to decode the command line argument #%i\n",
  380. i + 1);
  381. argc = i;
  382. goto error;
  383. }
  384. }
  385. setlocale(LC_ALL, oldloc);
  386. #endif
  387. #ifdef MS_WINDOWS
  388. PyImport_ExtendInittab(extensions);
  389. #endif /* MS_WINDOWS */
  390. if (argc >= 1) {
  391. #ifndef WIN_UNICODE
  392. Py_SetProgramName(argv_copy[0]);
  393. #else
  394. Py_SetProgramName(argv[0]);
  395. #endif
  396. }
  397. Py_Initialize();
  398. #ifdef MS_WINDOWS
  399. PyWinFreeze_ExeInit();
  400. #endif
  401. #ifdef MS_WINDOWS
  402. /* Ensure that line buffering is enabled on the output streams. */
  403. if (!unbuffered) {
  404. PyObject *sys_stream;
  405. sys_stream = PySys_GetObject("__stdout__");
  406. if (sys_stream && !enable_line_buffering(sys_stream)) {
  407. fprintf(stderr, "Failed to enable line buffering on sys.stdout\n");
  408. fflush(stderr);
  409. }
  410. sys_stream = PySys_GetObject("__stderr__");
  411. if (sys_stream && !enable_line_buffering(sys_stream)) {
  412. fprintf(stderr, "Failed to enable line buffering on sys.stderr\n");
  413. fflush(stderr);
  414. }
  415. }
  416. #endif
  417. if (Py_VerboseFlag)
  418. fprintf(stderr, "Python %s\n%s\n",
  419. Py_GetVersion(), Py_GetCopyright());
  420. #ifndef WIN_UNICODE
  421. PySys_SetArgv(argc, argv_copy);
  422. #else
  423. PySys_SetArgv(argc, argv);
  424. #endif
  425. #ifdef MACOS_APP_BUNDLE
  426. // Add the Frameworks directory to sys.path.
  427. char buffer[PATH_MAX];
  428. uint32_t bufsize = sizeof(buffer);
  429. if (_NSGetExecutablePath(buffer, &bufsize) != 0) {
  430. assert(false);
  431. return 1;
  432. }
  433. char resolved[PATH_MAX];
  434. if (!realpath(buffer, resolved)) {
  435. perror("realpath");
  436. return 1;
  437. }
  438. const char *dir = dirname(resolved);
  439. sprintf(buffer, "%s/../Frameworks", dir);
  440. PyObject *sys_path = PyList_New(1);
  441. PyList_SET_ITEM(sys_path, 0, PyUnicode_FromString(buffer));
  442. PySys_SetObject("path", sys_path);
  443. Py_DECREF(sys_path);
  444. // Now, store a path to the Resources directory into the main_dir pointer,
  445. // for ConfigPageManager to read out and assign to MAIN_DIR.
  446. sprintf(buffer, "%s/../Resources", dir);
  447. set_main_dir(buffer);
  448. // Finally, chdir to it, so that regular Python files are read from the
  449. // right location.
  450. chdir(buffer);
  451. #endif
  452. n = PyImport_ImportFrozenModule("__main__");
  453. if (n == 0)
  454. Py_FatalError("__main__ not frozen");
  455. if (n < 0) {
  456. PyErr_Print();
  457. sts = 1;
  458. }
  459. else
  460. sts = 0;
  461. #ifndef NDEBUG
  462. if (inspect && isatty((int)fileno(stdin)))
  463. sts = PyRun_AnyFile(stdin, "<stdin>") != 0;
  464. #endif
  465. #ifdef MS_WINDOWS
  466. PyWinFreeze_ExeTerm();
  467. #endif
  468. Py_Finalize();
  469. #ifndef WIN_UNICODE
  470. error:
  471. if (argv_copy2) {
  472. for (i = 0; i < argc; i++) {
  473. PyMem_RawFree(argv_copy2[i]);
  474. }
  475. }
  476. #endif
  477. return sts;
  478. }
  479. /**
  480. * Maps the binary blob at the given memory address to memory, and returns the
  481. * pointer to the beginning of it.
  482. */
  483. static void *map_blob(off_t offset, size_t size) {
  484. void *blob;
  485. FILE *runtime;
  486. #ifdef _WIN32
  487. wchar_t buffer[2048];
  488. GetModuleFileNameW(NULL, buffer, 2048);
  489. runtime = _wfopen(buffer, L"rb");
  490. #elif defined(__FreeBSD__)
  491. size_t bufsize = 4096;
  492. char buffer[4096];
  493. int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
  494. mib[3] = getpid();
  495. if (sysctl(mib, 4, (void *)buffer, &bufsize, NULL, 0) == -1) {
  496. perror("sysctl");
  497. return NULL;
  498. }
  499. runtime = fopen(buffer, "rb");
  500. #elif defined(__APPLE__)
  501. char buffer[4096];
  502. uint32_t bufsize = sizeof(buffer);
  503. if (_NSGetExecutablePath(buffer, &bufsize) != 0) {
  504. return NULL;
  505. }
  506. runtime = fopen(buffer, "rb");
  507. #else
  508. char buffer[4096];
  509. ssize_t pathlen = readlink("/proc/self/exe", buffer, sizeof(buffer) - 1);
  510. if (pathlen <= 0) {
  511. perror("readlink(/proc/self/exe)");
  512. return NULL;
  513. }
  514. buffer[pathlen] = '\0';
  515. runtime = fopen(buffer, "rb");
  516. #endif
  517. // Get offsets. In version 0, we read it from the end of the file.
  518. if (blobinfo.version == 0) {
  519. uint64_t end, begin;
  520. fseek(runtime, -8, SEEK_END);
  521. end = ftell(runtime);
  522. fread(&begin, 8, 1, runtime);
  523. offset = (off_t)begin;
  524. size = (size_t)(end - begin);
  525. }
  526. // mmap the section indicated by the offset (or malloc/fread on windows)
  527. #ifdef _WIN32
  528. blob = (void *)malloc(size);
  529. assert(blob != NULL);
  530. fseek(runtime, (long)offset, SEEK_SET);
  531. fread(blob, size, 1, runtime);
  532. #else
  533. blob = (void *)mmap(0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fileno(runtime), offset);
  534. assert(blob != MAP_FAILED);
  535. #endif
  536. fclose(runtime);
  537. return blob;
  538. }
  539. /**
  540. * The inverse of map_blob.
  541. */
  542. static void unmap_blob(void *blob) {
  543. if (blob) {
  544. #ifdef _WIN32
  545. free(blob);
  546. #else
  547. munmap(blob, blobinfo.blob_size);
  548. #endif
  549. }
  550. }
  551. /**
  552. * Main entry point to deploy-stub.
  553. */
  554. #ifdef _WIN32
  555. int wmain(int argc, wchar_t *argv[]) {
  556. #else
  557. int main(int argc, char *argv[]) {
  558. #endif
  559. int retval;
  560. ModuleDef *moddef;
  561. const char *log_filename;
  562. void *blob = NULL;
  563. log_filename = NULL;
  564. #ifdef __APPLE__
  565. // Strip a -psn_xxx argument passed in by macOS when run from an .app bundle.
  566. if (argc > 1 && strncmp(argv[1], "-psn_", 5) == 0) {
  567. argv[1] = argv[0];
  568. ++argv;
  569. --argc;
  570. }
  571. #endif
  572. /*
  573. printf("blob_offset: %d\n", (int)blobinfo.blob_offset);
  574. printf("blob_size: %d\n", (int)blobinfo.blob_size);
  575. printf("version: %d\n", (int)blobinfo.version);
  576. printf("num_pointers: %d\n", (int)blobinfo.num_pointers);
  577. printf("codepage: %d\n", (int)blobinfo.codepage);
  578. printf("flags: %d\n", (int)blobinfo.flags);
  579. printf("reserved: %d\n", (int)blobinfo.reserved);
  580. */
  581. // If we have a blob offset, we have to map the blob to memory.
  582. if (blobinfo.version == 0 || blobinfo.blob_offset != 0) {
  583. void *blob = map_blob((off_t)blobinfo.blob_offset, (size_t)blobinfo.blob_size);
  584. assert(blob != NULL);
  585. // Offset the pointers in the header using the base mmap address.
  586. if (blobinfo.version > 0 && blobinfo.num_pointers > 0) {
  587. uint32_t i;
  588. assert(blobinfo.num_pointers <= MAX_NUM_POINTERS);
  589. for (i = 0; i < blobinfo.num_pointers; ++i) {
  590. // Only offset if the pointer is non-NULL. Except for the first
  591. // pointer, which may never be NULL and usually (but not always)
  592. // points to the beginning of the blob.
  593. if (i == 0 || blobinfo.pointers[i] != 0) {
  594. blobinfo.pointers[i] = (void *)((uintptr_t)blobinfo.pointers[i] + (uintptr_t)blob);
  595. }
  596. }
  597. if (blobinfo.num_pointers >= 12) {
  598. log_filename = blobinfo.pointers[11];
  599. }
  600. } else {
  601. blobinfo.pointers[0] = blob;
  602. }
  603. // Offset the pointers in the module table using the base mmap address.
  604. moddef = blobinfo.pointers[0];
  605. #if PY_VERSION_HEX < 0x030b0000
  606. PyImport_FrozenModules = moddef;
  607. #endif
  608. while (moddef->name) {
  609. moddef->name = (char *)((uintptr_t)moddef->name + (uintptr_t)blob);
  610. if (moddef->code != 0) {
  611. moddef->code = (unsigned char *)((uintptr_t)moddef->code + (uintptr_t)blob);
  612. }
  613. //printf("MOD: %s %p %d\n", moddef->name, (void*)moddef->code, moddef->size);
  614. moddef++;
  615. }
  616. // In Python 3.11, we need to convert this to the new structure format.
  617. #if PY_VERSION_HEX >= 0x030b0000
  618. ModuleDef *moddef_end = moddef;
  619. ptrdiff_t num_modules = moddef - (ModuleDef *)blobinfo.pointers[0];
  620. struct _frozen *new_moddef = (struct _frozen *)calloc(num_modules + 1, sizeof(struct _frozen));
  621. PyImport_FrozenModules = new_moddef;
  622. for (moddef = blobinfo.pointers[0]; moddef < moddef_end; ++moddef) {
  623. new_moddef->name = moddef->name;
  624. new_moddef->code = moddef->code;
  625. new_moddef->size = moddef->size < 0 ? -(moddef->size) : moddef->size;
  626. new_moddef->is_package = moddef->size < 0;
  627. #if PY_VERSION_HEX < 0x030d0000 // 3.13
  628. new_moddef->get_code = NULL;
  629. #endif
  630. new_moddef++;
  631. }
  632. #endif
  633. } else {
  634. PyImport_FrozenModules = blobinfo.pointers[0];
  635. }
  636. if (log_filename != NULL) {
  637. char log_filename_buf[4096];
  638. if (blobinfo.flags & F_log_filename_strftime) {
  639. log_filename_buf[0] = 0;
  640. time_t now = time(NULL);
  641. if (strftime(log_filename_buf, sizeof(log_filename_buf), log_filename, localtime(&now)) > 0) {
  642. log_filename = log_filename_buf;
  643. }
  644. }
  645. setup_logging(log_filename, (blobinfo.flags & F_log_append) != 0);
  646. }
  647. #ifdef _WIN32
  648. if (blobinfo.codepage != 0) {
  649. SetConsoleCP(blobinfo.codepage);
  650. SetConsoleOutputCP(blobinfo.codepage);
  651. }
  652. #endif
  653. // Run frozen application
  654. retval = Py_FrozenMain(argc, argv);
  655. fflush(stdout);
  656. fflush(stderr);
  657. #if PY_VERSION_HEX >= 0x030b0000
  658. free((void *)PyImport_FrozenModules);
  659. PyImport_FrozenModules = NULL;
  660. #endif
  661. unmap_blob(blob);
  662. return retval;
  663. }
  664. #ifdef WIN_UNICODE
  665. int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, wchar_t *lpCmdLine, int nCmdShow) {
  666. return wmain(__argc, __wargv);
  667. }
  668. #elif defined(_WIN32)
  669. int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, char *lpCmdLine, int nCmdShow) {
  670. return main(__argc, __argv);
  671. }
  672. #endif