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
42 F_log_filename_strftime = 2,
49 __attribute__((__visibility__(
"default"), used))
55 uint16_t num_pointers;
59 void *pointers[MAX_NUM_POINTERS];
63 } blobinfo = {(uint64_t)-1};
66 # define WIN32_LEAN_AND_MEAN
69 extern void PyWinFreeze_ExeInit(
void);
70 extern void PyWinFreeze_ExeTerm(
void);
72 static struct _inittab extensions[] = {
76 #if PY_MAJOR_VERSION >= 3
82 static wchar_t *log_pathw = NULL;
85 #if defined(_WIN32) && PY_VERSION_HEX < 0x03060000
86 static int supports_code_page(UINT cp) {
93 if (cp != 0 && cp != 1252 && cp != 367 && cp != 437 && cp != 850 && cp != 819) {
94 const struct _frozen *moddef;
99 PyOS_snprintf(codec,
sizeof(codec),
"encodings.cp%u", (
unsigned int)cp);
101 moddef = PyImport_FrozenModules;
102 while (moddef->name) {
103 if (strcmp(moddef->name, codec) == 0) {
119 static void set_main_dir(
char *main_dir) {
120 if (blobinfo.num_pointers >= 10) {
121 if (blobinfo.num_pointers == 10) {
122 ++blobinfo.num_pointers;
123 blobinfo.pointers[10] = NULL;
125 if (blobinfo.pointers[10] == NULL) {
126 blobinfo.pointers[10] = main_dir;
135 static int mkdir_parent(
const wchar_t *path) {
137 wchar_t buffer[4096];
138 size_t buflen = wcslen(path);
139 if (buflen + 1 >= _countof(buffer)) {
142 wcscpy_s(buffer, _countof(buffer), path);
145 while (buflen-- > 0) {
146 if (buffer[buflen] ==
'/' || buffer[buflen] ==
'\\') {
151 if (buflen == (
size_t)-1 || buflen == 0) {
156 if (CreateDirectoryW(buffer, NULL) != 0) {
162 DWORD last_error = GetLastError();
163 if (last_error == ERROR_ALREADY_EXISTS) {
168 if (last_error == ERROR_PATH_NOT_FOUND) {
170 if (mkdir_parent(buffer)) {
172 if (CreateDirectoryW(buffer, NULL) != 0) {
181 static int mkdir_parent(
const char *path) {
184 size_t buflen = strlen(path);
185 if (buflen + 1 >=
sizeof(buffer)) {
188 strcpy(buffer, path);
191 while (buflen-- > 0) {
192 if (buffer[buflen] ==
'/') {
197 if (buflen == (
size_t)-1 || buflen == 0) {
201 if (mkdir(buffer, 0755) == 0) {
207 if (errno == EEXIST) {
212 if (errno == ENOENT || errno == EACCES) {
214 if (mkdir_parent(buffer)) {
216 if (mkdir(buffer, 0755) == 0) {
232 static int setup_logging(
const char *path,
int append) {
235 wchar_t *pathw = (
wchar_t *)malloc(
sizeof(
wchar_t) * MAX_PATH);
238 if (path[0] ==
'~' && (path[1] == 0 || path[1] ==
'/' || path[1] ==
'\\')) {
243 if (!SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_PROFILE, NULL, 0, pathw))) {
247 offset = wcslen(pathw);
251 if (MultiByteToWideChar(CP_UTF8, 0, path, -1, pathw + offset,
252 (
int)(MAX_PATH - offset)) == 0) {
257 DWORD access = append ? FILE_APPEND_DATA : (GENERIC_READ | GENERIC_WRITE);
258 int creation = append ? OPEN_ALWAYS : CREATE_ALWAYS;
259 HANDLE handle = CreateFileW(pathw, access, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
260 NULL, creation, FILE_ATTRIBUTE_NORMAL, NULL);
262 if (handle == INVALID_HANDLE_VALUE) {
265 handle = CreateFileW(pathw, access, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
266 NULL, creation, FILE_ATTRIBUTE_NORMAL, NULL);
269 if (handle == INVALID_HANDLE_VALUE) {
277 SetFilePointer(handle, 0, NULL, FILE_END);
280 SetStdHandle(STD_OUTPUT_HANDLE, handle);
281 SetStdHandle(STD_ERROR_HANDLE, handle);
286 if (_fileno(stdout) < 0) {
288 _wfreopen(L
"\\\\.\\NUL", L
"w", stdout);
291 if (_fileno(stderr) < 0) {
293 _wfreopen(L
"\\\\.\\NUL", L
"w", stderr);
298 int fd = _open_osfhandle((intptr_t)handle, _O_WRONLY | _O_TEXT | _O_APPEND);
299 _dup2(fd, _fileno(stdout));
300 _dup2(fd, _fileno(stderr));
306 char buffer[PATH_MAX * 2];
308 if (path[0] ==
'~' && (path[1] == 0 || path[1] ==
'/')) {
313 const char *home_dir = getenv(
"HOME");
314 if (home_dir == NULL) {
315 home_dir = getpwuid(getuid())->pw_dir;
317 offset = strlen(home_dir);
318 assert(offset <
sizeof(buffer));
319 strncpy(buffer, home_dir,
sizeof(buffer));
323 strcpy(buffer + offset, path);
325 mode_t mode = O_CREAT | O_WRONLY | (append ? O_APPEND : O_TRUNC);
326 int fd = open(buffer, mode, 0644);
329 mkdir_parent(buffer);
330 fd = open(buffer, mode, 0644);
352 #if PY_MAJOR_VERSION >= 3
353 static int enable_line_buffering(PyObject *file) {
354 #if PY_VERSION_HEX >= 0x03070000
356 PyObject *kwargs = _PyDict_NewPresized(1);
357 PyDict_SetItemString(kwargs,
"line_buffering", Py_True);
358 PyObject *args = PyTuple_New(0);
360 PyObject *method = PyObject_GetAttrString(file,
"reconfigure");
361 if (method != NULL) {
362 PyObject *result = PyObject_Call(method, args, kwargs);
366 if (result != NULL) {
383 PyTypeObject *type = Py_TYPE(file);
384 PyMemberDef *member = type->tp_members;
386 while (member != NULL && member->name != NULL) {
387 if (strcmp(member->name,
"line_buffering") == 0) {
388 *((
char *)file + member->offset) = 1;
402 int Py_FrozenMain(
int argc,
wchar_t **argv)
404 int Py_FrozenMain(
int argc,
char **argv)
414 #if PY_MAJOR_VERSION >= 3 && !defined(WIN_UNICODE)
417 wchar_t **argv_copy = NULL;
419 wchar_t **argv_copy2 = NULL;
422 argv_copy = (
wchar_t **)alloca(
sizeof(
wchar_t *) * argc);
423 argv_copy2 = (
wchar_t **)alloca(
sizeof(
wchar_t *) * argc);
427 #if defined(MS_WINDOWS) && PY_VERSION_HEX >= 0x03040000 && PY_VERSION_HEX < 0x03060000
428 if (!supports_code_page(GetConsoleOutputCP()) ||
429 !supports_code_page(GetConsoleCP())) {
435 SetConsoleOutputCP(acp);
436 Py_SetStandardStreamEncoding(
"mbcs", NULL);
442 Py_NoUserSiteDirectory = 1;
445 if ((p = Py_GETENV(
"PYTHONINSPECT")) && *p !=
'\0')
448 if ((p = Py_GETENV(
"PYTHONUNBUFFERED")) && *p !=
'\0')
452 setbuf(stdin, (
char *)NULL);
453 setbuf(stdout, (
char *)NULL);
454 setbuf(stderr, (
char *)NULL);
457 #if PY_MAJOR_VERSION >= 3 && !defined(WIN_UNICODE)
458 oldloc = setlocale(LC_ALL, NULL);
459 setlocale(LC_ALL,
"");
460 for (i = 0; i < argc; i++) {
461 argv_copy[i] = Py_DecodeLocale(argv[i], NULL);
462 argv_copy2[i] = argv_copy[i];
464 fprintf(stderr,
"Unable to decode the command line argument #%i\n",
470 setlocale(LC_ALL, oldloc);
474 PyImport_ExtendInittab(extensions);
478 #if PY_MAJOR_VERSION >= 3 && !defined(WIN_UNICODE)
479 Py_SetProgramName(argv_copy[0]);
481 Py_SetProgramName(argv[0]);
487 PyWinFreeze_ExeInit();
490 #if defined(MS_WINDOWS) && PY_VERSION_HEX < 0x03040000
497 #if PY_MAJOR_VERSION < 3
498 if (log_pathw != NULL) {
499 PyObject *uniobj = PyUnicode_FromWideChar(log_pathw, (Py_ssize_t)wcslen(log_pathw));
500 PyObject *file = PyObject_CallFunction((PyObject*)&PyFile_Type,
"Nsi", uniobj,
"a", 0);
503 PyFile_SetEncodingAndErrors(file,
"utf-8", NULL);
505 PySys_SetObject(
"stdout", file);
506 PySys_SetObject(
"stderr", file);
507 PySys_SetObject(
"__stdout__", file);
508 PySys_SetObject(
"__stderr__", file);
511 setbuf(stdout, (
char *)NULL);
512 setbuf(stderr, (
char *)NULL);
517 if (!supports_code_page(GetConsoleOutputCP()) ||
518 !supports_code_page(GetConsoleCP())) {
523 PyObject *sys_stream;
526 SetConsoleOutputCP(acp);
528 sys_stream = PySys_GetObject(
"stdin");
529 if (sys_stream && PyFile_Check(sys_stream)) {
530 PyFile_SetEncodingAndErrors(sys_stream,
"mbcs", NULL);
532 sys_stream = PySys_GetObject(
"stdout");
533 if (sys_stream && PyFile_Check(sys_stream)) {
534 PyFile_SetEncodingAndErrors(sys_stream,
"mbcs", NULL);
536 sys_stream = PySys_GetObject(
"stderr");
537 if (sys_stream && PyFile_Check(sys_stream)) {
538 PyFile_SetEncodingAndErrors(sys_stream,
"mbcs", NULL);
543 #if defined(MS_WINDOWS) && PY_VERSION_HEX >= 0x03040000
547 PyObject *sys_stream;
548 sys_stream = PySys_GetObject(
"__stdout__");
549 if (sys_stream && !enable_line_buffering(sys_stream)) {
550 fprintf(stderr,
"Failed to enable line buffering on sys.stdout\n");
553 sys_stream = PySys_GetObject(
"__stderr__");
554 if (sys_stream && !enable_line_buffering(sys_stream)) {
555 fprintf(stderr,
"Failed to enable line buffering on sys.stderr\n");
562 fprintf(stderr,
"Python %s\n%s\n",
563 Py_GetVersion(), Py_GetCopyright());
565 #if PY_MAJOR_VERSION >= 3 && !defined(WIN_UNICODE)
566 PySys_SetArgv(argc, argv_copy);
568 PySys_SetArgv(argc, argv);
571 #ifdef MACOS_APP_BUNDLE
573 char buffer[PATH_MAX];
574 uint32_t bufsize =
sizeof(buffer);
575 if (_NSGetExecutablePath(buffer, &bufsize) != 0) {
579 char resolved[PATH_MAX];
580 if (!realpath(buffer, resolved)) {
584 const char *dir = dirname(resolved);
585 sprintf(buffer,
"%s/../Frameworks", dir);
587 PyObject *sys_path = PyList_New(1);
588 #if PY_MAJOR_VERSION >= 3
589 PyList_SET_ITEM(sys_path, 0, PyUnicode_FromString(buffer));
591 PyList_SET_ITEM(sys_path, 0, PyString_FromString(buffer));
593 PySys_SetObject(
"path", sys_path);
598 sprintf(buffer,
"%s/../Resources", dir);
599 set_main_dir(buffer);
606 n = PyImport_ImportFrozenModule(
"__main__");
608 Py_FatalError(
"__main__ not frozen");
617 if (inspect && isatty((
int)fileno(stdin)))
618 sts = PyRun_AnyFile(stdin,
"<stdin>") != 0;
622 PyWinFreeze_ExeTerm();
626 #if PY_MAJOR_VERSION >= 3 && !defined(WIN_UNICODE)
629 for (i = 0; i < argc; i++) {
630 #if PY_MAJOR_VERSION > 3 || PY_MINOR_VERSION >= 4
631 PyMem_RawFree(argv_copy2[i]);
633 PyMem_Free(argv_copy2[i]);
645 static void *map_blob(off_t offset,
size_t size) {
650 wchar_t buffer[2048];
651 GetModuleFileNameW(NULL, buffer, 2048);
652 runtime = _wfopen(buffer, L
"rb");
653 #elif defined(__FreeBSD__)
654 size_t bufsize = 4096;
656 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
658 if (sysctl(mib, 4, (
void *)buffer, &bufsize, NULL, 0) == -1) {
662 runtime = fopen(buffer,
"rb");
663 #elif defined(__APPLE__)
665 uint32_t bufsize =
sizeof(buffer);
666 if (_NSGetExecutablePath(buffer, &bufsize) != 0) {
669 runtime = fopen(buffer,
"rb");
672 ssize_t pathlen = readlink(
"/proc/self/exe", buffer,
sizeof(buffer) - 1);
674 perror(
"readlink(/proc/self/exe)");
677 buffer[pathlen] =
'\0';
678 runtime = fopen(buffer,
"rb");
682 if (blobinfo.version == 0) {
684 fseek(runtime, -8, SEEK_END);
685 end = ftell(runtime);
686 fread(&begin, 8, 1, runtime);
688 offset = (off_t)begin;
689 size = (size_t)(end - begin);
694 blob = (
void *)malloc(size);
695 assert(blob != NULL);
696 fseek(runtime, (
long)offset, SEEK_SET);
697 fread(blob, size, 1, runtime);
699 blob = (
void *)mmap(0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fileno(runtime), offset);
700 assert(blob != MAP_FAILED);
710 static void unmap_blob(
void *blob) {
715 munmap(blob, blobinfo.blob_size);
723 #if defined(_WIN32) && PY_MAJOR_VERSION >= 3
724 int wmain(
int argc,
wchar_t *argv[]) {
726 int main(
int argc,
char *argv[]) {
729 struct _frozen *moddef;
730 const char *log_filename;
736 if (argc > 1 && strncmp(argv[1],
"-psn_", 5) == 0) {
754 if (blobinfo.version == 0 || blobinfo.blob_offset != 0) {
755 void *blob = map_blob((off_t)blobinfo.blob_offset, (
size_t)blobinfo.blob_size);
756 assert(blob != NULL);
759 if (blobinfo.version > 0 && blobinfo.num_pointers > 0) {
761 assert(blobinfo.num_pointers <= MAX_NUM_POINTERS);
762 for (i = 0; i < blobinfo.num_pointers; ++i) {
766 if (i == 0 || blobinfo.pointers[i] != 0) {
767 blobinfo.pointers[i] = (
void *)((uintptr_t)blobinfo.pointers[i] + (uintptr_t)blob);
770 if (blobinfo.num_pointers >= 12) {
771 log_filename = blobinfo.pointers[11];
774 blobinfo.pointers[0] = blob;
778 moddef = blobinfo.pointers[0];
779 while (moddef->name) {
780 moddef->name = (
char *)((uintptr_t)moddef->name + (uintptr_t)blob);
781 if (moddef->code != 0) {
782 moddef->code = (
unsigned char *)((uintptr_t)moddef->code + (uintptr_t)blob);
789 if (log_filename != NULL) {
790 char log_filename_buf[4096];
791 if (blobinfo.flags & F_log_filename_strftime) {
792 log_filename_buf[0] = 0;
793 time_t now = time(NULL);
794 if (strftime(log_filename_buf,
sizeof(log_filename_buf), log_filename, localtime(&now)) > 0) {
795 log_filename = log_filename_buf;
798 setup_logging(log_filename, (blobinfo.flags & F_log_append) != 0);
802 if (blobinfo.codepage != 0) {
803 SetConsoleCP(blobinfo.codepage);
804 SetConsoleOutputCP(blobinfo.codepage);
809 PyImport_FrozenModules = blobinfo.pointers[0];
810 retval = Py_FrozenMain(argc, argv);
820 int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
wchar_t *lpCmdLine,
int nCmdShow) {
821 return wmain(__argc, __wargv);
823 #elif defined(_WIN32)
824 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
char *lpCmdLine,
int nCmdShow) {
825 return main(__argc, __argv);