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,
43 F_keep_docstrings = 4,
50__attribute__((__visibility__(
"default"), used))
56 uint16_t num_pointers;
60 void *pointers[MAX_NUM_POINTERS];
64} blobinfo = {(uint64_t)-1};
69__declspec(dllexport) DWORD SymbolPlaceholder___________________ = 0x00000001;
70__declspec(dllexport) DWORD SymbolPlaceholder__ = 0x00000001;
74# define WIN32_LEAN_AND_MEAN
77extern void PyWinFreeze_ExeInit(
void);
78extern void PyWinFreeze_ExeTerm(
void);
80static struct _inittab extensions[] = {
84#if PY_MAJOR_VERSION >= 3
90static wchar_t *log_pathw = NULL;
93#if PY_VERSION_HEX >= 0x030b0000
96 const unsigned char *code;
100typedef struct _frozen ModuleDef;
103#if defined(_WIN32) && PY_VERSION_HEX < 0x03060000
104static int supports_code_page(UINT cp) {
111 if (cp != 0 && cp != 1252 && cp != 367 && cp != 437 && cp != 850 && cp != 819) {
112 const struct _frozen *moddef;
117 PyOS_snprintf(codec,
sizeof(codec),
"encodings.cp%u", (
unsigned int)cp);
119 moddef = PyImport_FrozenModules;
120 while (moddef->name) {
121 if (strcmp(moddef->name, codec) == 0) {
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;
143 if (blobinfo.pointers[10] == NULL) {
144 blobinfo.pointers[10] = main_dir;
153static int mkdir_parent(
const wchar_t *path) {
155 wchar_t buffer[4096];
156 size_t buflen = wcslen(path);
157 if (buflen + 1 >= _countof(buffer)) {
160 wcscpy_s(buffer, _countof(buffer), path);
163 while (buflen-- > 0) {
164 if (buffer[buflen] ==
'/' || buffer[buflen] ==
'\\') {
169 if (buflen == (
size_t)-1 || buflen == 0) {
174 if (CreateDirectoryW(buffer, NULL) != 0) {
180 DWORD last_error = GetLastError();
181 if (last_error == ERROR_ALREADY_EXISTS) {
186 if (last_error == ERROR_PATH_NOT_FOUND) {
188 if (mkdir_parent(buffer)) {
190 if (CreateDirectoryW(buffer, NULL) != 0) {
199static int mkdir_parent(
const char *path) {
202 size_t buflen = strlen(path);
203 if (buflen + 1 >=
sizeof(buffer)) {
206 strcpy(buffer, path);
209 while (buflen-- > 0) {
210 if (buffer[buflen] ==
'/') {
215 if (buflen == (
size_t)-1 || buflen == 0) {
219 if (mkdir(buffer, 0755) == 0) {
225 if (errno == EEXIST) {
230 if (errno == ENOENT || errno == EACCES) {
232 if (mkdir_parent(buffer)) {
234 if (mkdir(buffer, 0755) == 0) {
250static int setup_logging(
const char *path,
int append) {
253 wchar_t *pathw = (
wchar_t *)malloc(
sizeof(
wchar_t) * MAX_PATH);
256 if (path[0] ==
'~' && (path[1] == 0 || path[1] ==
'/' || path[1] ==
'\\')) {
261 if (!SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_PROFILE, NULL, 0, pathw))) {
265 offset = wcslen(pathw);
269 if (MultiByteToWideChar(CP_UTF8, 0, path, -1, pathw + offset,
270 (
int)(MAX_PATH - offset)) == 0) {
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);
280 if (handle == INVALID_HANDLE_VALUE) {
283 handle = CreateFileW(pathw, access, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
284 NULL, creation, FILE_ATTRIBUTE_NORMAL, NULL);
287 if (handle == INVALID_HANDLE_VALUE) {
295 SetFilePointer(handle, 0, NULL, FILE_END);
298 SetStdHandle(STD_OUTPUT_HANDLE, handle);
299 SetStdHandle(STD_ERROR_HANDLE, handle);
304 if (_fileno(stdout) < 0) {
306 _wfreopen(L
"\\\\.\\NUL", L
"w", stdout);
309 if (_fileno(stderr) < 0) {
311 _wfreopen(L
"\\\\.\\NUL", L
"w", stderr);
316 int fd = _open_osfhandle((intptr_t)handle, _O_WRONLY | _O_TEXT | _O_APPEND);
317 _dup2(fd, _fileno(stdout));
318 _dup2(fd, _fileno(stderr));
324 char buffer[PATH_MAX * 2];
326 if (path[0] ==
'~' && (path[1] == 0 || path[1] ==
'/')) {
331 const char *home_dir = getenv(
"HOME");
332 if (home_dir == NULL) {
333 home_dir = getpwuid(getuid())->pw_dir;
335 offset = strlen(home_dir);
336 assert(offset <
sizeof(buffer));
337 strncpy(buffer, home_dir,
sizeof(buffer));
341 strcpy(buffer + offset, path);
343 mode_t mode = O_CREAT | O_WRONLY | (append ? O_APPEND : O_TRUNC);
344 int fd = open(buffer, mode, 0644);
347 mkdir_parent(buffer);
348 fd = open(buffer, mode, 0644);
370#if PY_MAJOR_VERSION >= 3
371static int enable_line_buffering(PyObject *file) {
372#if PY_VERSION_HEX >= 0x03070000
374 PyObject *kwargs = _PyDict_NewPresized(1);
375 PyDict_SetItemString(kwargs,
"line_buffering", Py_True);
376 PyObject *args = PyTuple_New(0);
378 PyObject *method = PyObject_GetAttrString(file,
"reconfigure");
379 if (method != NULL) {
380 PyObject *result = PyObject_Call(method, args, kwargs);
384 if (result != NULL) {
401 PyTypeObject *type = Py_TYPE(file);
402 PyMemberDef *member = type->tp_members;
404 while (member != NULL && member->name != NULL) {
405 if (strcmp(member->name,
"line_buffering") == 0) {
406 *((
char *)file + member->offset) = 1;
420int Py_FrozenMain(
int argc,
wchar_t **argv)
422int Py_FrozenMain(
int argc,
char **argv)
432#if PY_MAJOR_VERSION >= 3 && !defined(WIN_UNICODE)
435 wchar_t **argv_copy = NULL;
437 wchar_t **argv_copy2 = NULL;
440 argv_copy = (
wchar_t **)alloca(
sizeof(
wchar_t *) * argc);
441 argv_copy2 = (
wchar_t **)alloca(
sizeof(
wchar_t *) * argc);
445#if defined(MS_WINDOWS) && PY_VERSION_HEX >= 0x03040000 && PY_VERSION_HEX < 0x03060000
446 if (!supports_code_page(GetConsoleOutputCP()) ||
447 !supports_code_page(GetConsoleCP())) {
453 SetConsoleOutputCP(acp);
454 Py_SetStandardStreamEncoding(
"mbcs", NULL);
460 Py_NoUserSiteDirectory = 1;
462#if PY_VERSION_HEX >= 0x03020000
463 if (blobinfo.flags & F_keep_docstrings) {
471 if ((p = Py_GETENV(
"PYTHONINSPECT")) && *p !=
'\0')
474 if ((p = Py_GETENV(
"PYTHONUNBUFFERED")) && *p !=
'\0')
478 setbuf(stdin, (
char *)NULL);
479 setbuf(stdout, (
char *)NULL);
480 setbuf(stderr, (
char *)NULL);
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];
490 fprintf(stderr,
"Unable to decode the command line argument #%i\n",
496 setlocale(LC_ALL, oldloc);
500 PyImport_ExtendInittab(extensions);
504#if PY_MAJOR_VERSION >= 3 && !defined(WIN_UNICODE)
505 Py_SetProgramName(argv_copy[0]);
507 Py_SetProgramName(argv[0]);
513 PyWinFreeze_ExeInit();
516#if defined(MS_WINDOWS) && PY_VERSION_HEX < 0x03040000
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);
529 PyFile_SetEncodingAndErrors(file,
"utf-8", NULL);
531 PySys_SetObject(
"stdout", file);
532 PySys_SetObject(
"stderr", file);
533 PySys_SetObject(
"__stdout__", file);
534 PySys_SetObject(
"__stderr__", file);
537 setbuf(stdout, (
char *)NULL);
538 setbuf(stderr, (
char *)NULL);
543 if (!supports_code_page(GetConsoleOutputCP()) ||
544 !supports_code_page(GetConsoleCP())) {
549 PyObject *sys_stream;
552 SetConsoleOutputCP(acp);
554 sys_stream = PySys_GetObject(
"stdin");
555 if (sys_stream && PyFile_Check(sys_stream)) {
556 PyFile_SetEncodingAndErrors(sys_stream,
"mbcs", NULL);
558 sys_stream = PySys_GetObject(
"stdout");
559 if (sys_stream && PyFile_Check(sys_stream)) {
560 PyFile_SetEncodingAndErrors(sys_stream,
"mbcs", NULL);
562 sys_stream = PySys_GetObject(
"stderr");
563 if (sys_stream && PyFile_Check(sys_stream)) {
564 PyFile_SetEncodingAndErrors(sys_stream,
"mbcs", NULL);
569#if defined(MS_WINDOWS) && PY_VERSION_HEX >= 0x03040000
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");
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");
588 fprintf(stderr,
"Python %s\n%s\n",
589 Py_GetVersion(), Py_GetCopyright());
591#if PY_MAJOR_VERSION >= 3 && !defined(WIN_UNICODE)
592 PySys_SetArgv(argc, argv_copy);
594 PySys_SetArgv(argc, argv);
597#ifdef MACOS_APP_BUNDLE
599 char buffer[PATH_MAX];
600 uint32_t bufsize =
sizeof(buffer);
601 if (_NSGetExecutablePath(buffer, &bufsize) != 0) {
605 char resolved[PATH_MAX];
606 if (!realpath(buffer, resolved)) {
610 const char *dir = dirname(resolved);
611 sprintf(buffer,
"%s/../Frameworks", dir);
613 PyObject *sys_path = PyList_New(1);
614 #if PY_MAJOR_VERSION >= 3
615 PyList_SET_ITEM(sys_path, 0, PyUnicode_FromString(buffer));
617 PyList_SET_ITEM(sys_path, 0, PyString_FromString(buffer));
619 PySys_SetObject(
"path", sys_path);
624 sprintf(buffer,
"%s/../Resources", dir);
625 set_main_dir(buffer);
632 n = PyImport_ImportFrozenModule(
"__main__");
634 Py_FatalError(
"__main__ not frozen");
643 if (inspect && isatty((
int)fileno(stdin)))
644 sts = PyRun_AnyFile(stdin,
"<stdin>") != 0;
648 PyWinFreeze_ExeTerm();
652#if PY_MAJOR_VERSION >= 3 && !defined(WIN_UNICODE)
655 for (i = 0; i < argc; i++) {
656#if PY_MAJOR_VERSION > 3 || PY_MINOR_VERSION >= 4
657 PyMem_RawFree(argv_copy2[i]);
659 PyMem_Free(argv_copy2[i]);
671static void *map_blob(off_t offset,
size_t size) {
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;
682 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
684 if (sysctl(mib, 4, (
void *)buffer, &bufsize, NULL, 0) == -1) {
688 runtime = fopen(buffer,
"rb");
689#elif defined(__APPLE__)
691 uint32_t bufsize =
sizeof(buffer);
692 if (_NSGetExecutablePath(buffer, &bufsize) != 0) {
695 runtime = fopen(buffer,
"rb");
698 ssize_t pathlen = readlink(
"/proc/self/exe", buffer,
sizeof(buffer) - 1);
700 perror(
"readlink(/proc/self/exe)");
703 buffer[pathlen] =
'\0';
704 runtime = fopen(buffer,
"rb");
708 if (blobinfo.version == 0) {
710 fseek(runtime, -8, SEEK_END);
711 end = ftell(runtime);
712 fread(&begin, 8, 1, runtime);
714 offset = (off_t)begin;
715 size = (size_t)(end - begin);
720 blob = (
void *)malloc(size);
721 assert(blob != NULL);
722 fseek(runtime, (
long)offset, SEEK_SET);
723 fread(blob, size, 1, runtime);
725 blob = (
void *)mmap(0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fileno(runtime), offset);
726 assert(blob != MAP_FAILED);
736static void unmap_blob(
void *blob) {
741 munmap(blob, blobinfo.blob_size);
749#if defined(_WIN32) && PY_MAJOR_VERSION >= 3
750int wmain(
int argc,
wchar_t *argv[]) {
752int main(
int argc,
char *argv[]) {
756 const char *log_filename;
762 if (argc > 1 && strncmp(argv[1],
"-psn_", 5) == 0) {
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);
785 if (blobinfo.version > 0 && blobinfo.num_pointers > 0) {
787 assert(blobinfo.num_pointers <= MAX_NUM_POINTERS);
788 for (i = 0; i < blobinfo.num_pointers; ++i) {
792 if (i == 0 || blobinfo.pointers[i] != 0) {
793 blobinfo.pointers[i] = (
void *)((uintptr_t)blobinfo.pointers[i] + (uintptr_t)blob);
796 if (blobinfo.num_pointers >= 12) {
797 log_filename = blobinfo.pointers[11];
800 blobinfo.pointers[0] = blob;
804 moddef = blobinfo.pointers[0];
805#if PY_VERSION_HEX < 0x030b0000
806 PyImport_FrozenModules = moddef;
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);
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;
833 PyImport_FrozenModules = blobinfo.pointers[0];
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;
845 setup_logging(log_filename, (blobinfo.flags & F_log_append) != 0);
849 if (blobinfo.codepage != 0) {
850 SetConsoleCP(blobinfo.codepage);
851 SetConsoleOutputCP(blobinfo.codepage);
856 retval = Py_FrozenMain(argc, argv);
861#if PY_VERSION_HEX >= 0x030b0000
862 free((
void *)PyImport_FrozenModules);
863 PyImport_FrozenModules = NULL;
871int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
wchar_t *lpCmdLine,
int nCmdShow) {
872 return wmain(__argc, __wargv);
875int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
char *lpCmdLine,
int nCmdShow) {
876 return main(__argc, __argv);