13 # include <sys/sysctl.h>
17 # include <mach-o/dyld.h>
25 #if PY_MAJOR_VERSION >= 3
28 # if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION < 5
29 # define Py_DecodeLocale _Py_char2wchar
32 # include "structmember.h"
37 #define MAX_NUM_POINTERS 24
48 __attribute__((__visibility__(
"default"), used))
54 uint16_t num_pointers;
58 void *pointers[MAX_NUM_POINTERS];
62 } blobinfo = {(uint64_t)-1};
65 # define WIN32_LEAN_AND_MEAN
68 extern void PyWinFreeze_ExeInit(
void);
69 extern void PyWinFreeze_ExeTerm(
void);
71 static struct _inittab extensions[] = {
75 #if PY_MAJOR_VERSION >= 3
81 static wchar_t *log_pathw = NULL;
84 #if defined(_WIN32) && PY_VERSION_HEX < 0x03060000
85 static int supports_code_page(UINT cp) {
92 if (cp != 0 && cp != 1252 && cp != 367 && cp != 437 && cp != 850 && cp != 819) {
93 const struct _frozen *moddef;
98 PyOS_snprintf(codec,
sizeof(codec),
"encodings.cp%u", (
unsigned int)cp);
100 moddef = PyImport_FrozenModules;
101 while (moddef->name) {
102 if (strcmp(moddef->name, codec) == 0) {
118 static void set_main_dir(
char *main_dir) {
119 if (blobinfo.num_pointers >= 10) {
120 if (blobinfo.num_pointers == 10) {
121 ++blobinfo.num_pointers;
122 blobinfo.pointers[10] = NULL;
124 if (blobinfo.pointers[10] == NULL) {
125 blobinfo.pointers[10] = main_dir;
134 static int mkdir_parent(
const wchar_t *path) {
136 wchar_t buffer[4096];
137 size_t buflen = wcslen(path);
138 if (buflen + 1 >= _countof(buffer)) {
141 wcscpy_s(buffer, _countof(buffer), path);
144 while (buflen-- > 0) {
145 if (buffer[buflen] ==
'/' || buffer[buflen] ==
'\\') {
150 if (buflen == (
size_t)-1 || buflen == 0) {
155 if (CreateDirectoryW(buffer, NULL) != 0) {
161 DWORD last_error = GetLastError();
162 if (last_error == ERROR_ALREADY_EXISTS) {
167 if (last_error == ERROR_PATH_NOT_FOUND) {
169 if (mkdir_parent(buffer)) {
171 if (CreateDirectoryW(buffer, NULL) != 0) {
180 static int mkdir_parent(
const char *path) {
183 size_t buflen = strlen(path);
184 if (buflen + 1 >=
sizeof(buffer)) {
187 strcpy(buffer, path);
190 while (buflen-- > 0) {
191 if (buffer[buflen] ==
'/') {
196 if (buflen == (
size_t)-1 || buflen == 0) {
200 if (mkdir(buffer, 0755) == 0) {
206 if (errno == EEXIST) {
211 if (errno == ENOENT || errno == EACCES) {
213 if (mkdir_parent(buffer)) {
215 if (mkdir(buffer, 0755) == 0) {
231 static int setup_logging(
const char *path,
int append) {
234 wchar_t *pathw = (
wchar_t *)malloc(
sizeof(
wchar_t) * MAX_PATH);
237 if (path[0] ==
'~' && (path[1] == 0 || path[1] ==
'/' || path[1] ==
'\\')) {
242 if (!SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_PROFILE, NULL, 0, pathw))) {
246 offset = wcslen(pathw);
250 if (MultiByteToWideChar(CP_UTF8, 0, path, -1, pathw + offset,
251 (
int)(MAX_PATH - offset)) == 0) {
256 DWORD access = append ? FILE_APPEND_DATA : (GENERIC_READ | GENERIC_WRITE);
257 int creation = append ? OPEN_ALWAYS : CREATE_ALWAYS;
258 HANDLE handle = CreateFileW(pathw, access, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
259 NULL, creation, FILE_ATTRIBUTE_NORMAL, NULL);
261 if (handle == INVALID_HANDLE_VALUE) {
264 handle = CreateFileW(pathw, access, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
265 NULL, creation, FILE_ATTRIBUTE_NORMAL, NULL);
268 if (handle == INVALID_HANDLE_VALUE) {
276 SetFilePointer(handle, 0, NULL, FILE_END);
279 SetStdHandle(STD_OUTPUT_HANDLE, handle);
280 SetStdHandle(STD_ERROR_HANDLE, handle);
285 if (_fileno(stdout) < 0) {
287 _wfreopen(L
"\\\\.\\NUL", L
"w", stdout);
290 if (_fileno(stderr) < 0) {
292 _wfreopen(L
"\\\\.\\NUL", L
"w", stderr);
297 int fd = _open_osfhandle((intptr_t)handle, _O_WRONLY | _O_TEXT | _O_APPEND);
298 _dup2(fd, _fileno(stdout));
299 _dup2(fd, _fileno(stderr));
305 char buffer[PATH_MAX * 2];
307 if (path[0] ==
'~' && (path[1] == 0 || path[1] ==
'/')) {
312 const char *home_dir = getenv(
"HOME");
313 if (home_dir == NULL) {
314 home_dir = getpwuid(getuid())->pw_dir;
316 offset = strlen(home_dir);
317 assert(offset <
sizeof(buffer));
318 strncpy(buffer, home_dir,
sizeof(buffer));
322 strcpy(buffer + offset, path);
324 mode_t mode = O_CREAT | O_WRONLY | (append ? O_APPEND : O_TRUNC);
325 int fd = open(buffer, mode, 0644);
328 mkdir_parent(buffer);
329 fd = open(buffer, mode, 0644);
351 #if PY_MAJOR_VERSION >= 3
352 static int enable_line_buffering(PyObject *file) {
353 #if PY_VERSION_HEX >= 0x03070000
355 PyObject *kwargs = _PyDict_NewPresized(1);
356 PyDict_SetItemString(kwargs,
"line_buffering", Py_True);
357 PyObject *args = PyTuple_New(0);
359 PyObject *method = PyObject_GetAttrString(file,
"reconfigure");
360 if (method != NULL) {
361 PyObject *result = PyObject_Call(method, args, kwargs);
363 if (result != NULL) {
377 PyTypeObject *type = Py_TYPE(file);
378 PyMemberDef *member = type->tp_members;
380 while (member != NULL && member->name != NULL) {
381 if (strcmp(member->name,
"line_buffering") == 0) {
382 *((
char *)file + member->offset) = 1;
396 int Py_FrozenMain(
int argc,
wchar_t **argv)
398 int Py_FrozenMain(
int argc,
char **argv)
408 #if PY_MAJOR_VERSION >= 3 && !defined(WIN_UNICODE)
411 wchar_t **argv_copy = NULL;
413 wchar_t **argv_copy2 = NULL;
416 argv_copy = (
wchar_t **)alloca(
sizeof(
wchar_t *) * argc);
417 argv_copy2 = (
wchar_t **)alloca(
sizeof(
wchar_t *) * argc);
421 #if defined(MS_WINDOWS) && PY_VERSION_HEX >= 0x03040000 && PY_VERSION_HEX < 0x03060000
422 if (!supports_code_page(GetConsoleOutputCP()) ||
423 !supports_code_page(GetConsoleCP())) {
429 SetConsoleOutputCP(acp);
430 Py_SetStandardStreamEncoding(
"mbcs", NULL);
436 Py_NoUserSiteDirectory = 1;
439 if ((p = Py_GETENV(
"PYTHONINSPECT")) && *p !=
'\0')
442 if ((p = Py_GETENV(
"PYTHONUNBUFFERED")) && *p !=
'\0')
446 setbuf(stdin, (
char *)NULL);
447 setbuf(stdout, (
char *)NULL);
448 setbuf(stderr, (
char *)NULL);
451 #if PY_MAJOR_VERSION >= 3 && !defined(WIN_UNICODE)
452 oldloc = setlocale(LC_ALL, NULL);
453 setlocale(LC_ALL,
"");
454 for (i = 0; i < argc; i++) {
455 argv_copy[i] = Py_DecodeLocale(argv[i], NULL);
456 argv_copy2[i] = argv_copy[i];
458 fprintf(stderr,
"Unable to decode the command line argument #%i\n",
464 setlocale(LC_ALL, oldloc);
468 PyImport_ExtendInittab(extensions);
472 #if PY_MAJOR_VERSION >= 3 && !defined(WIN_UNICODE)
473 Py_SetProgramName(argv_copy[0]);
475 Py_SetProgramName(argv[0]);
481 PyWinFreeze_ExeInit();
484 #if defined(MS_WINDOWS) && PY_VERSION_HEX < 0x03040000
491 #if PY_MAJOR_VERSION < 3
492 if (log_pathw != NULL) {
493 PyObject *uniobj = PyUnicode_FromWideChar(log_pathw, (Py_ssize_t)wcslen(log_pathw));
494 PyObject *file = PyObject_CallFunction((PyObject*)&PyFile_Type,
"Nsi", uniobj,
"a", 0);
497 PyFile_SetEncodingAndErrors(file,
"utf-8", NULL);
499 PySys_SetObject(
"stdout", file);
500 PySys_SetObject(
"stderr", file);
501 PySys_SetObject(
"__stdout__", file);
502 PySys_SetObject(
"__stderr__", file);
505 setbuf(stdout, (
char *)NULL);
506 setbuf(stderr, (
char *)NULL);
511 if (!supports_code_page(GetConsoleOutputCP()) ||
512 !supports_code_page(GetConsoleCP())) {
517 PyObject *sys_stream;
520 SetConsoleOutputCP(acp);
522 sys_stream = PySys_GetObject(
"stdin");
523 if (sys_stream && PyFile_Check(sys_stream)) {
524 PyFile_SetEncodingAndErrors(sys_stream,
"mbcs", NULL);
526 sys_stream = PySys_GetObject(
"stdout");
527 if (sys_stream && PyFile_Check(sys_stream)) {
528 PyFile_SetEncodingAndErrors(sys_stream,
"mbcs", NULL);
530 sys_stream = PySys_GetObject(
"stderr");
531 if (sys_stream && PyFile_Check(sys_stream)) {
532 PyFile_SetEncodingAndErrors(sys_stream,
"mbcs", NULL);
537 #if defined(MS_WINDOWS) && PY_VERSION_HEX >= 0x03040000
541 PyObject *sys_stream;
542 sys_stream = PySys_GetObject(
"__stdout__");
543 if (sys_stream && !enable_line_buffering(sys_stream)) {
544 fprintf(stderr,
"Failed to enable line buffering on sys.stdout\n");
547 sys_stream = PySys_GetObject(
"__stderr__");
548 if (sys_stream && !enable_line_buffering(sys_stream)) {
549 fprintf(stderr,
"Failed to enable line buffering on sys.stderr\n");
556 fprintf(stderr,
"Python %s\n%s\n",
557 Py_GetVersion(), Py_GetCopyright());
559 #if PY_MAJOR_VERSION >= 3 && !defined(WIN_UNICODE)
560 PySys_SetArgv(argc, argv_copy);
562 PySys_SetArgv(argc, argv);
565 #ifdef MACOS_APP_BUNDLE
567 char buffer[PATH_MAX];
568 uint32_t bufsize =
sizeof(buffer);
569 if (_NSGetExecutablePath(buffer, &bufsize) != 0) {
573 char resolved[PATH_MAX];
574 if (!realpath(buffer, resolved)) {
578 const char *dir = dirname(resolved);
579 sprintf(buffer,
"%s/../Frameworks", dir);
581 PyObject *sys_path = PyList_New(1);
582 #if PY_MAJOR_VERSION >= 3
583 PyList_SET_ITEM(sys_path, 0, PyUnicode_FromString(buffer));
585 PyList_SET_ITEM(sys_path, 0, PyString_FromString(buffer));
587 PySys_SetObject(
"path", sys_path);
592 sprintf(buffer,
"%s/../Resources", dir);
593 set_main_dir(buffer);
600 n = PyImport_ImportFrozenModule(
"__main__");
602 Py_FatalError(
"__main__ not frozen");
611 if (inspect && isatty((
int)fileno(stdin)))
612 sts = PyRun_AnyFile(stdin,
"<stdin>") != 0;
616 PyWinFreeze_ExeTerm();
620 #if PY_MAJOR_VERSION >= 3 && !defined(WIN_UNICODE)
623 for (i = 0; i < argc; i++) {
624 #if PY_MAJOR_VERSION > 3 || PY_MINOR_VERSION >= 4
625 PyMem_RawFree(argv_copy2[i]);
627 PyMem_Free(argv_copy2[i]);
639 static void *map_blob(off_t offset,
size_t size) {
644 wchar_t buffer[2048];
645 GetModuleFileNameW(NULL, buffer, 2048);
646 runtime = _wfopen(buffer, L
"rb");
647 #elif defined(__FreeBSD__)
648 size_t bufsize = 4096;
650 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
652 if (sysctl(mib, 4, (
void *)buffer, &bufsize, NULL, 0) == -1) {
656 runtime = fopen(buffer,
"rb");
657 #elif defined(__APPLE__)
659 uint32_t bufsize =
sizeof(buffer);
660 if (_NSGetExecutablePath(buffer, &bufsize) != 0) {
663 runtime = fopen(buffer,
"rb");
666 ssize_t pathlen = readlink(
"/proc/self/exe", buffer,
sizeof(buffer) - 1);
668 perror(
"readlink(/proc/self/exe)");
671 buffer[pathlen] =
'\0';
672 runtime = fopen(buffer,
"rb");
676 if (blobinfo.version == 0) {
678 fseek(runtime, -8, SEEK_END);
679 end = ftell(runtime);
680 fread(&begin, 8, 1, runtime);
682 offset = (off_t)begin;
683 size = (size_t)(end - begin);
688 blob = (
void *)malloc(size);
689 assert(blob != NULL);
690 fseek(runtime, (
long)offset, SEEK_SET);
691 fread(blob, size, 1, runtime);
693 blob = (
void *)mmap(0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fileno(runtime), offset);
694 assert(blob != MAP_FAILED);
704 static void unmap_blob(
void *blob) {
709 munmap(blob, blobinfo.blob_size);
717 #if defined(_WIN32) && PY_MAJOR_VERSION >= 3
718 int wmain(
int argc,
wchar_t *argv[]) {
720 int main(
int argc,
char *argv[]) {
723 struct _frozen *moddef;
724 const char *log_filename;
730 if (argc > 1 && strncmp(argv[1],
"-psn_", 5) == 0) {
748 if (blobinfo.version == 0 || blobinfo.blob_offset != 0) {
749 void *blob = map_blob((off_t)blobinfo.blob_offset, (
size_t)blobinfo.blob_size);
750 assert(blob != NULL);
753 if (blobinfo.version > 0 && blobinfo.num_pointers > 0) {
755 assert(blobinfo.num_pointers <= MAX_NUM_POINTERS);
756 for (i = 0; i < blobinfo.num_pointers; ++i) {
760 if (i == 0 || blobinfo.pointers[i] != 0) {
761 blobinfo.pointers[i] = (
void *)((uintptr_t)blobinfo.pointers[i] + (uintptr_t)blob);
764 if (blobinfo.num_pointers >= 12) {
765 log_filename = blobinfo.pointers[11];
768 blobinfo.pointers[0] = blob;
772 moddef = blobinfo.pointers[0];
773 while (moddef->name) {
774 moddef->name = (
char *)((uintptr_t)moddef->name + (uintptr_t)blob);
775 if (moddef->code != 0) {
776 moddef->code = (
unsigned char *)((uintptr_t)moddef->code + (uintptr_t)blob);
783 if (log_filename != NULL) {
784 setup_logging(log_filename, (blobinfo.flags & F_log_append) != 0);
788 if (blobinfo.codepage != 0) {
789 SetConsoleCP(blobinfo.codepage);
790 SetConsoleOutputCP(blobinfo.codepage);
795 PyImport_FrozenModules = blobinfo.pointers[0];
796 retval = Py_FrozenMain(argc, argv);
806 int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
wchar_t *lpCmdLine,
int nCmdShow) {
807 return wmain(__argc, __wargv);
809 #elif defined(_WIN32)
810 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
char *lpCmdLine,
int nCmdShow) {
811 return main(__argc, __argv);