[r738]: trunk / py2exe / source / start.c Maximize Restore History

Download this file

start.c    522 lines (467 with data), 13.9 kB

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
/*
* Copyright (c) 2000-2013 Thomas Heller, Mark Hammond
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
* $Id: start.c 738 2013-09-07 10:11:45Z theller $
*
*/
/*
#include <Python.h>
#include <marshal.h>
#include <compile.h>
#include <eval.h>
*/
#include "Python-dynload.h"
#include <stdio.h>
#include <windows.h>
#include "MyLoadLibrary.h"
#if defined(MS_WINDOWS) || defined(__CYGWIN__)
#include <fcntl.h>
#endif
struct scriptinfo {
int tag;
int optimize;
int unbuffered;
int data_bytes;
char zippath[0];
};
extern void SystemError(int error, char *msg);
int run_script(void);
void fini(void);
char *pScript;
char *pZipBaseName;
int numScriptBytes;
char modulename[_MAX_PATH + _MAX_FNAME + _MAX_EXT]; // from GetModuleName()
char dirname[_MAX_PATH]; // directory part of GetModuleName()
char libdirname[_MAX_PATH]; // library directory - probably same as above.
char libfilename[_MAX_PATH + _MAX_FNAME + _MAX_EXT]; // library filename
struct scriptinfo *p_script_info;
/*
static int dprintf(char *fmt, ...)
{
char Buffer[4096];
va_list marker;
int result;
va_start(marker, fmt);
result = vsprintf(Buffer, fmt, marker);
OutputDebugString(Buffer);
return result;
}
*/
BOOL calc_dirname(HMODULE hmod)
{
int is_special;
char *modulename_start;
char *cp;
// get module filename
if (!GetModuleFileName(hmod, modulename, sizeof(modulename))) {
SystemError(GetLastError(), "Retrieving module name");
return FALSE;
}
// get directory of modulename. Note that in some cases
// (eg, ISAPI), GetModuleFileName may return a leading "\\?\"
// (which is a special format you can pass to the Unicode API
// to avoid MAX_PATH limitations). Python currently can't understand
// such names, and as it uses the ANSI API, neither does Windows!
// So fix that up here.
is_special = strlen(modulename) > 4 &&
strncmp(modulename, "\\\\?\\", 4)==0;
modulename_start = is_special ? modulename + 4 : modulename;
strcpy(dirname, modulename_start);
cp = strrchr(dirname, '\\');
*cp = '\0';
return TRUE;
}
BOOL _LocateScript(HMODULE hmod)
{
HRSRC hrsrc = FindResource(hmod, MAKEINTRESOURCE(1), "PYTHONSCRIPT");
HGLOBAL hgbl;
if (!dirname[0])
calc_dirname(hmod);
// load the script resource
if (!hrsrc) {
SystemError(GetLastError(), "Could not locate script resource:");
return FALSE;
}
hgbl = LoadResource(hmod, hrsrc);
if (!hgbl) {
SystemError(GetLastError(), "Could not load script resource:");
return FALSE;
}
p_script_info = (struct scriptinfo *)pScript = LockResource(hgbl);
if (!pScript) {
SystemError(GetLastError(), "Could not lock script resource:");
return FALSE;
}
// validate script resource
numScriptBytes = p_script_info->data_bytes;
pScript += sizeof(struct scriptinfo);
if (p_script_info->tag != 0x78563412) {
SystemError (0, "Bug: Invalid script resource");
return FALSE;
}
// let pScript point to the start of the python script resource
pScript += strlen(p_script_info->zippath) + 1;
// get full pathname of the 'library.zip' file
if(p_script_info->zippath[0]) {
snprintf(libfilename, sizeof(libfilename),
"%s\\%s", dirname, p_script_info->zippath);
} else {
GetModuleFileName(hmod, libfilename, sizeof(libfilename));
}
return TRUE; // success
}
static char *MapExistingFile(char *pathname, DWORD *psize)
{
HANDLE hFile, hFileMapping;
DWORD nSizeLow, nSizeHigh;
char *data;
hFile = CreateFile(pathname,
GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
return NULL;
nSizeLow = GetFileSize(hFile, &nSizeHigh);
hFileMapping = CreateFileMapping(hFile,
NULL, PAGE_READONLY, 0, 0, NULL);
CloseHandle(hFile);
if (hFileMapping == INVALID_HANDLE_VALUE)
return NULL;
data = MapViewOfFile(hFileMapping,
FILE_MAP_READ, 0, 0, 0);
CloseHandle(hFileMapping);
if (psize)
*psize = nSizeLow;
return data;
}
BOOL _LoadPythonDLL(HMODULE hmod)
{
HRSRC hrsrc;
char *pBaseAddress;
int size;
if (!dirname[0])
calc_dirname(hmod);
// Try to locate pythonxy.dll as resource in the exe
hrsrc = FindResource(hmod, MAKEINTRESOURCE(1), PYTHONDLL);
if (hrsrc) {
HGLOBAL hgbl = LoadResource(hmod, hrsrc);
if (!_load_python(PYTHONDLL, LockResource(hgbl))) {
SystemError(GetLastError(), "Could not load python dll");
return FALSE;
}
// dprintf("Loaded pythondll as RESOURCE\n");
return TRUE;
}
// try to load pythonxy.dll as bytes at the start of the zipfile
pBaseAddress = MapExistingFile(libfilename, &size);
if (pBaseAddress) {
int res = 0;
if (0 == strncmp(pBaseAddress, "<pythondll>", 11))
res = _load_python(PYTHONDLL, pBaseAddress + 11 + sizeof(int));
UnmapViewOfFile(pBaseAddress);
if (res) {
// dprintf("Loaded pythondll as <pythondll> from %s\n", libfilename);
return TRUE;
}
}
// try to load pythonxy.dll from the file system
{
char buffer[_MAX_PATH + _MAX_FNAME + _MAX_EXT];
snprintf(buffer, sizeof(buffer), "%s\\%s", dirname, PYTHONDLL);
if (!_load_python(buffer, NULL)) {
SystemError(GetLastError(), "LoadLibrary(pythondll) failed");
SystemError(0, buffer);
return FALSE;
}
// dprintf("Loaded pythondll from file %s\n", buffer);
}
return TRUE;
}
void _Import_Zlib(char *pdata)
{
HMODULE hlib;
hlib = MyLoadLibrary("zlib.pyd", pdata, NULL);
if (hlib) {
void (*proc)(void);
proc = (void(*)(void))MyGetProcAddress(hlib, "initzlib");
if (proc)
proc();
}
}
void _TryLoadZlib(HMODULE hmod)
{
char *pBaseAddress;
char *pdata;
HRSRC hrsrc;
// Try to locate pythonxy.dll as resource in the exe
hrsrc = FindResource(hmod, MAKEINTRESOURCE(1), "ZLIB.PYD");
if (hrsrc) {
HGLOBAL hglb = LoadResource(hmod, hrsrc);
if (hglb) {
_Import_Zlib(LockResource(hglb));
}
return;
}
// try to load zlib.pyd from the file system
{
HMODULE hlib;
char buffer[_MAX_PATH + _MAX_FNAME + _MAX_EXT];
snprintf(buffer, sizeof(buffer), "%s\\%s", dirname, "zlib.pyd");
hlib = LoadLibrary(buffer);
if(hlib) {
void (*proc)(void);
proc = (void(*)(void))GetProcAddress(hlib, "initzlib");
if(proc) {
proc();
return;
}
}
}
// try to load zlib.pyd as bytes at the start of the zipfile
pdata = pBaseAddress = MapExistingFile(libfilename, NULL);
if (pBaseAddress) {
if (0 == strncmp(pBaseAddress, "<pythondll>", 11)) {
pdata += 11;
pdata += *(int *)pdata + sizeof(int);
}
if (0 == strncmp(pdata, "<zlib.pyd>", 10)) {
pdata += 10 + sizeof(int);
_Import_Zlib(pdata);
}
UnmapViewOfFile(pBaseAddress);
}
}
static void calc_path()
{
/* If the zip path has any path component, then build our Python
home directory from that.
*/
char *fname;
size_t lib_dir_len;
pZipBaseName = libfilename + strlen(libfilename);
/* let pZipBaseName point to the basename of the zippath */
while (pZipBaseName > libfilename && \
*(pZipBaseName-1) != '\\')
pZipBaseName--;
/* length of lib director name */
lib_dir_len = pZipBaseName-libfilename; /* incl. tail slash */
if (lib_dir_len) {
char *p = libdirname;
strncpy(p, libfilename, lib_dir_len-1);
p += lib_dir_len-1;
*p++ = '\0';
} else {
libdirname[0] = '\0';
}
/* Fully-qualify it */
GetFullPathName(libdirname, sizeof(libdirname), libdirname, &fname);
}
// Set the Python path before initialization
static int set_path_early()
{
char *ppath;
Py_SetPythonHome(libdirname);
/* Let Python calculate its initial path, according to the
builtin rules */
ppath = Py_GetPath();
// printf("Initial path: %s\n", ppath);
/* We know that Py_GetPath points to writeable memory,
so we copy our own path into it.
*/
if (strlen(ppath) <= strlen(libdirname) + strlen(pZipBaseName) + 1) {
/* Um. Not enough space. What now? */
SystemError(0, "Not enough space for new sys.path");
return -1;
}
strcpy(ppath, libdirname);
strcat(ppath, "\\");
strcat(ppath, pZipBaseName);
return 0;
}
// Set the Python path after initialization
static int set_path_late()
{
size_t buflen = strlen(libdirname) + strlen(pZipBaseName) + 2;
char *ppath = (char *)malloc(buflen);
PyObject *syspath, *newEntry;
if (!ppath) {
SystemError(ERROR_NOT_ENOUGH_MEMORY, "no mem for late sys.path");
return -1;
}
strcpy(ppath, libdirname);
strcat(ppath, "\\");
strcat(ppath, pZipBaseName);
syspath = PySys_GetObject("path");
newEntry = PyString_FromString(ppath);
if (newEntry) {
PyList_Append(syspath, newEntry);
Py_DECREF(newEntry);
}
free(ppath);
return 0;
}
/*
* returns an error code if initialization fails
*/
int init_with_instance(HMODULE hmod, char *frozen)
{
int rc;
if (!_LocateScript(hmod))
return 255;
if (!_LoadPythonDLL(hmod))
return 255;
if (p_script_info->unbuffered) {
#if defined(MS_WINDOWS) || defined(__CYGWIN__)
_setmode(fileno(stdin), O_BINARY);
_setmode(fileno(stdout), O_BINARY);
#endif
#ifdef HAVE_SETVBUF
setvbuf(stdin, (char *)NULL, _IONBF, BUFSIZ);
setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
setvbuf(stderr, (char *)NULL, _IONBF, BUFSIZ);
#else /* !HAVE_SETVBUF */
setbuf(stdin, (char *)NULL);
setbuf(stdout, (char *)NULL);
setbuf(stderr, (char *)NULL);
#endif /* !HAVE_SETVBUF */
}
if (getenv("PY2EXE_VERBOSE"))
Py_VerboseFlag = atoi(getenv("PY2EXE_VERBOSE"));
else
Py_VerboseFlag = 0;
Py_IgnoreEnvironmentFlag = 1;
Py_NoSiteFlag = 1;
Py_OptimizeFlag = p_script_info->optimize;
Py_SetProgramName(modulename);
calc_path();
if (!Py_IsInitialized()) {
// First time round and the usual case - set sys.path
// statically.
rc = set_path_early();
if (rc != 0)
return rc;
// printf("Path before Py_Initialize(): %s\n", Py_GetPath());
Py_Initialize();
// printf("Path after Py_Initialize(): %s\n", PyString_AsString(PyObject_Str(PySys_GetObject("path"))));
} else {
// Python already initialized. This likely means there are
// 2 py2exe based apps in the same process (eg, 2 COM objects
// in a single host, 2 ISAPI filters in the same site, ...)
// Until we get a better answer, add what we need to sys.path
rc = set_path_late();
if (rc != 0)
return rc;
}
/* Set sys.frozen so apps that care can tell.
If the caller did pass NULL, sys.frozen will be set zo True.
If a string is passed this is used as the frozen attribute.
run.c passes "console_exe", run_w.c passes "windows_exe",
run_dll.c passes "dll"
This falls apart when you consider that in some cases, a single
process may end up with two py2exe generated apps - but still, we
reset frozen to the correct 'current' value for the newly
initializing app.
*/
if (frozen == NULL)
PySys_SetObject("frozen", PyBool_FromLong(1));
else {
PyObject *o = PyString_FromString(frozen);
if (o) {
PySys_SetObject("frozen", o);
Py_DECREF(o);
}
}
// If zlib is builtin to pythonxx.dll, we don't need to take any
// special action (and worse, if it so happens an old version of
// the app built with python 2.4 is installed, we might attempt to
// load that python24 pyd, causing death...)
#ifndef PYZLIB_BUILTIN
_TryLoadZlib(hmod);
#endif
return 0;
}
int init(char *frozen)
{
return init_with_instance(NULL, frozen);
}
void fini(void)
{
/* The standard Python 2.3 does also allow this: Set PYTHONINSPECT
in the script and examine it afterwards
*/
if (getenv("PYTHONINSPECT") && Py_FdIsInteractive(stdin, "<stdin>"))
PyRun_InteractiveLoop(stdin, "<stdin>");
/* Clean up */
Py_Finalize();
}
int start (int argc, char **argv)
{
int rc;
PyObject *new_path;
PySys_SetArgv(argc, argv);
// PySys_SetArgv munged the path - specifically, it added the
// directory of argv[0] at the start of sys.path.
// Create a new list object for the path, and rely on our
// implementation knowledge of set_path above, which writes into
// the static Py_GetPath() buffer (Note: Py_GetPath() does *not*
// return the current sys.path value - its just a static buffer
// holding the initial Python paths)
new_path = PyList_New(1);
if (new_path) {
PyObject *entry = PyString_FromString(Py_GetPath());
if (entry && (0==PyList_SetItem(new_path, 0, entry)))
PySys_SetObject("path", new_path);
Py_DECREF(new_path);
}
rc = run_script();
fini();
return rc;
}
int run_script(void)
{
int rc = 0;
/* load the code objects to execute */
PyObject *m=NULL, *d=NULL, *seq=NULL;
/* We execute then in the context of '__main__' */
m = PyImport_AddModule("__main__");
if (m) d = PyModule_GetDict(m);
if (d) seq = PyMarshal_ReadObjectFromString(pScript, numScriptBytes);
if (seq) {
Py_ssize_t i, max = PySequence_Length(seq);
for (i=0;i<max;i++) {
PyObject *sub = PySequence_GetItem(seq, i);
if (sub /*&& PyCode_Check(sub) */) {
PyObject *discard = PyEval_EvalCode((PyCodeObject *)sub,
d, d);
if (!discard) {
PyErr_Print();
rc = 255;
}
Py_XDECREF(discard);
/* keep going even if we fail */
}
Py_XDECREF(sub);
}
}
return rc;
}