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
69extern void PyWinFreeze_ExeInit(
void);
70extern void PyWinFreeze_ExeTerm(
void);
72static struct _inittab extensions[] = {
76#if PY_MAJOR_VERSION >= 3
82static wchar_t *log_pathw = NULL;
85#if defined(_WIN32) && PY_VERSION_HEX < 0x03060000
86static 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) {
119static 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;
135static 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) {
181static 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) {
232static 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
353static 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;
402int Py_FrozenMain(
int argc,
wchar_t **argv)
404int 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;
444#if PY_VERSION_HEX >= 0x03020000
449 if ((p = Py_GETENV(
"PYTHONINSPECT")) && *p !=
'\0')
452 if ((p = Py_GETENV(
"PYTHONUNBUFFERED")) && *p !=
'\0')
456 setbuf(stdin, (
char *)NULL);
457 setbuf(stdout, (
char *)NULL);
458 setbuf(stderr, (
char *)NULL);
461#if PY_MAJOR_VERSION >= 3 && !defined(WIN_UNICODE)
462 oldloc = setlocale(LC_ALL, NULL);
463 setlocale(LC_ALL,
"");
464 for (i = 0; i < argc; i++) {
465 argv_copy[i] = Py_DecodeLocale(argv[i], NULL);
466 argv_copy2[i] = argv_copy[i];
468 fprintf(stderr,
"Unable to decode the command line argument #%i\n",
474 setlocale(LC_ALL, oldloc);
478 PyImport_ExtendInittab(extensions);
482#if PY_MAJOR_VERSION >= 3 && !defined(WIN_UNICODE)
483 Py_SetProgramName(argv_copy[0]);
485 Py_SetProgramName(argv[0]);
491 PyWinFreeze_ExeInit();
494#if defined(MS_WINDOWS) && PY_VERSION_HEX < 0x03040000
501#if PY_MAJOR_VERSION < 3
502 if (log_pathw != NULL) {
503 PyObject *uniobj = PyUnicode_FromWideChar(log_pathw, (Py_ssize_t)wcslen(log_pathw));
504 PyObject *file = PyObject_CallFunction((PyObject*)&PyFile_Type,
"Nsi", uniobj,
"a", 0);
507 PyFile_SetEncodingAndErrors(file,
"utf-8", NULL);
509 PySys_SetObject(
"stdout", file);
510 PySys_SetObject(
"stderr", file);
511 PySys_SetObject(
"__stdout__", file);
512 PySys_SetObject(
"__stderr__", file);
515 setbuf(stdout, (
char *)NULL);
516 setbuf(stderr, (
char *)NULL);
521 if (!supports_code_page(GetConsoleOutputCP()) ||
522 !supports_code_page(GetConsoleCP())) {
527 PyObject *sys_stream;
530 SetConsoleOutputCP(acp);
532 sys_stream = PySys_GetObject(
"stdin");
533 if (sys_stream && PyFile_Check(sys_stream)) {
534 PyFile_SetEncodingAndErrors(sys_stream,
"mbcs", NULL);
536 sys_stream = PySys_GetObject(
"stdout");
537 if (sys_stream && PyFile_Check(sys_stream)) {
538 PyFile_SetEncodingAndErrors(sys_stream,
"mbcs", NULL);
540 sys_stream = PySys_GetObject(
"stderr");
541 if (sys_stream && PyFile_Check(sys_stream)) {
542 PyFile_SetEncodingAndErrors(sys_stream,
"mbcs", NULL);
547#if defined(MS_WINDOWS) && PY_VERSION_HEX >= 0x03040000
551 PyObject *sys_stream;
552 sys_stream = PySys_GetObject(
"__stdout__");
553 if (sys_stream && !enable_line_buffering(sys_stream)) {
554 fprintf(stderr,
"Failed to enable line buffering on sys.stdout\n");
557 sys_stream = PySys_GetObject(
"__stderr__");
558 if (sys_stream && !enable_line_buffering(sys_stream)) {
559 fprintf(stderr,
"Failed to enable line buffering on sys.stderr\n");
566 fprintf(stderr,
"Python %s\n%s\n",
567 Py_GetVersion(), Py_GetCopyright());
569#if PY_MAJOR_VERSION >= 3 && !defined(WIN_UNICODE)
570 PySys_SetArgv(argc, argv_copy);
572 PySys_SetArgv(argc, argv);
575#ifdef MACOS_APP_BUNDLE
577 char buffer[PATH_MAX];
578 uint32_t bufsize =
sizeof(buffer);
579 if (_NSGetExecutablePath(buffer, &bufsize) != 0) {
583 char resolved[PATH_MAX];
584 if (!realpath(buffer, resolved)) {
588 const char *dir = dirname(resolved);
589 sprintf(buffer,
"%s/../Frameworks", dir);
591 PyObject *sys_path = PyList_New(1);
592 #if PY_MAJOR_VERSION >= 3
593 PyList_SET_ITEM(sys_path, 0, PyUnicode_FromString(buffer));
595 PyList_SET_ITEM(sys_path, 0, PyString_FromString(buffer));
597 PySys_SetObject(
"path", sys_path);
602 sprintf(buffer,
"%s/../Resources", dir);
603 set_main_dir(buffer);
610 n = PyImport_ImportFrozenModule(
"__main__");
612 Py_FatalError(
"__main__ not frozen");
621 if (inspect && isatty((
int)fileno(stdin)))
622 sts = PyRun_AnyFile(stdin,
"<stdin>") != 0;
626 PyWinFreeze_ExeTerm();
630#if PY_MAJOR_VERSION >= 3 && !defined(WIN_UNICODE)
633 for (i = 0; i < argc; i++) {
634#if PY_MAJOR_VERSION > 3 || PY_MINOR_VERSION >= 4
635 PyMem_RawFree(argv_copy2[i]);
637 PyMem_Free(argv_copy2[i]);
649static void *map_blob(off_t offset,
size_t size) {
654 wchar_t buffer[2048];
655 GetModuleFileNameW(NULL, buffer, 2048);
656 runtime = _wfopen(buffer, L
"rb");
657#elif defined(__FreeBSD__)
658 size_t bufsize = 4096;
660 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
662 if (sysctl(mib, 4, (
void *)buffer, &bufsize, NULL, 0) == -1) {
666 runtime = fopen(buffer,
"rb");
667#elif defined(__APPLE__)
669 uint32_t bufsize =
sizeof(buffer);
670 if (_NSGetExecutablePath(buffer, &bufsize) != 0) {
673 runtime = fopen(buffer,
"rb");
676 ssize_t pathlen = readlink(
"/proc/self/exe", buffer,
sizeof(buffer) - 1);
678 perror(
"readlink(/proc/self/exe)");
681 buffer[pathlen] =
'\0';
682 runtime = fopen(buffer,
"rb");
686 if (blobinfo.version == 0) {
688 fseek(runtime, -8, SEEK_END);
689 end = ftell(runtime);
690 fread(&begin, 8, 1, runtime);
692 offset = (off_t)begin;
693 size = (size_t)(end - begin);
698 blob = (
void *)malloc(size);
699 assert(blob != NULL);
700 fseek(runtime, (
long)offset, SEEK_SET);
701 fread(blob, size, 1, runtime);
703 blob = (
void *)mmap(0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fileno(runtime), offset);
704 assert(blob != MAP_FAILED);
714static void unmap_blob(
void *blob) {
719 munmap(blob, blobinfo.blob_size);
727#if defined(_WIN32) && PY_MAJOR_VERSION >= 3
728int wmain(
int argc,
wchar_t *argv[]) {
730int main(
int argc,
char *argv[]) {
733 struct _frozen *moddef;
734 const char *log_filename;
740 if (argc > 1 && strncmp(argv[1],
"-psn_", 5) == 0) {
758 if (blobinfo.version == 0 || blobinfo.blob_offset != 0) {
759 void *blob = map_blob((off_t)blobinfo.blob_offset, (
size_t)blobinfo.blob_size);
760 assert(blob != NULL);
763 if (blobinfo.version > 0 && blobinfo.num_pointers > 0) {
765 assert(blobinfo.num_pointers <= MAX_NUM_POINTERS);
766 for (i = 0; i < blobinfo.num_pointers; ++i) {
770 if (i == 0 || blobinfo.pointers[i] != 0) {
771 blobinfo.pointers[i] = (
void *)((uintptr_t)blobinfo.pointers[i] + (uintptr_t)blob);
774 if (blobinfo.num_pointers >= 12) {
775 log_filename = blobinfo.pointers[11];
778 blobinfo.pointers[0] = blob;
782 moddef = blobinfo.pointers[0];
783 while (moddef->name) {
784 moddef->name = (
char *)((uintptr_t)moddef->name + (uintptr_t)blob);
785 if (moddef->code != 0) {
786 moddef->code = (
unsigned char *)((uintptr_t)moddef->code + (uintptr_t)blob);
793 if (log_filename != NULL) {
794 char log_filename_buf[4096];
795 if (blobinfo.flags & F_log_filename_strftime) {
796 log_filename_buf[0] = 0;
797 time_t now = time(NULL);
798 if (strftime(log_filename_buf,
sizeof(log_filename_buf), log_filename, localtime(&now)) > 0) {
799 log_filename = log_filename_buf;
802 setup_logging(log_filename, (blobinfo.flags & F_log_append) != 0);
806 if (blobinfo.codepage != 0) {
807 SetConsoleCP(blobinfo.codepage);
808 SetConsoleOutputCP(blobinfo.codepage);
813 PyImport_FrozenModules = blobinfo.pointers[0];
814 retval = Py_FrozenMain(argc, argv);
824int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
wchar_t *lpCmdLine,
int nCmdShow) {
825 return wmain(__argc, __wargv);
828int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
char *lpCmdLine,
int nCmdShow) {
829 return main(__argc, __argv);