blob: b1d6591b87181819ff72c06c967a6600c133ae42 [file] [log] [blame]
Jack Jansen1e2260f1998-07-13 13:37:12 +00001/***********************************************************
2Copyright 1991-1997 by Stichting Mathematisch Centrum, Amsterdam,
3The Netherlands.
4
5 All Rights Reserved
6
7Permission to use, copy, modify, and distribute this software and its
8documentation for any purpose and without fee is hereby granted,
9provided that the above copyright notice appear in all copies and that
10both that copyright notice and this permission notice appear in
11supporting documentation, and that the names of Stichting Mathematisch
12Centrum or CWI not be used in advertising or publicity pertaining to
13distribution of the software without specific, written prior permission.
14
15STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
16THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
17FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
18FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
19WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
20ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
21OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
22
23******************************************************************/
24
25
26#include "Python.h"
27
28#include "macglue.h"
29#include "marshal.h"
30#include "import.h"
31#include "importdl.h"
32
33#include "pythonresources.h"
34
35#include <Types.h>
36#include <Files.h>
37#include <Resources.h>
38#if 0
39#include <OSUtils.h> /* for Set(Current)A5 */
40#include <StandardFile.h>
41#include <Memory.h>
42#include <Windows.h>
43#include <Traps.h>
44#include <Processes.h>
45#include <Fonts.h>
46#include <Menus.h>
47#include <TextUtils.h>
48#endif
49#include <CodeFragments.h>
50
Jack Jansen2d1306b2000-04-07 09:10:49 +000051#ifdef USE_GUSI1
Jack Jansen48a9c361998-09-07 11:36:17 +000052#include "TFileSpec.h" /* for Path2FSSpec() */
53#endif
54
Jack Jansen1e2260f1998-07-13 13:37:12 +000055typedef void (*dl_funcptr)();
56#define FUNCNAME_PATTERN "init%.200s"
57
58/*
59** findnamedresource - Common code for the various *ResourceModule functions.
60** Check whether a file contains a resource of the correct name and type, and
61** optionally return the value in it.
62*/
63static int
64findnamedresource(
65 PyStringObject *obj,
66 char *module,
67 char *filename,
68 OSType restype,
69 StringPtr dataptr)
70{
71 FSSpec fss;
72 FInfo finfo;
73 short oldrh, filerh;
74 int ok;
75 Handle h;
76
77#ifdef INTERN_STRINGS
78 /*
79 ** If we have interning find_module takes care of interning all
80 ** sys.path components. We then keep a record of all sys.path
81 ** components for which GetFInfo has failed (usually because the
82 ** component in question is a folder), and we don't try opening these
83 ** as resource files again.
84 */
85#define MAXPATHCOMPONENTS 32
86 static PyStringObject *not_a_file[MAXPATHCOMPONENTS];
87 static int max_not_a_file = 0;
88 int i;
89
90 if (obj && obj->ob_sinterned ) {
91 for( i=0; i< max_not_a_file; i++ )
92 if ( obj == not_a_file[i] )
93 return 0;
94 }
95#endif /* INTERN_STRINGS */
96
97 if ( strcmp(filename, PyMac_ApplicationPath) == 0 ) {
98 /*
99 ** Special case: the application itself. Use a shortcut to
100 ** forestall opening and closing the application numerous times
101 ** (which is dead slow when running from CDROM)
102 */
103 oldrh = CurResFile();
104 UseResFile(PyMac_AppRefNum);
105 filerh = -1;
106 } else {
Jack Jansen2d1306b2000-04-07 09:10:49 +0000107#ifdef USE_GUSI1
Jack Jansen48a9c361998-09-07 11:36:17 +0000108 if ( Path2FSSpec(filename, &fss) != noErr ||
109#else
Jack Jansen1e2260f1998-07-13 13:37:12 +0000110 if ( FSMakeFSSpec(0, 0, Pstring(filename), &fss) != noErr ||
Jack Jansen48a9c361998-09-07 11:36:17 +0000111#endif
Jack Jansen1e2260f1998-07-13 13:37:12 +0000112 FSpGetFInfo(&fss, &finfo) != noErr ) {
113#ifdef INTERN_STRINGS
114 if ( obj && max_not_a_file < MAXPATHCOMPONENTS && obj->ob_sinterned )
115 not_a_file[max_not_a_file++] = obj;
116#endif /* INTERN_STRINGS */
117 /* doesn't exist or is folder */
118 return 0;
119 }
120 oldrh = CurResFile();
121 filerh = FSpOpenResFile(&fss, fsRdPerm);
122 if ( filerh == -1 )
123 return 0;
124 UseResFile(filerh);
125 }
126 if ( dataptr == NULL )
127 SetResLoad(0);
128 h = Get1NamedResource(restype, Pstring(module));
129 SetResLoad(1);
130 ok = (h != NULL);
131 if ( ok && dataptr != NULL ) {
132 HLock(h);
Jack Jansen017e0ff1998-07-31 09:34:47 +0000133 /* XXXX Unsafe if resource not correctly formatted! */
134#ifdef __CFM68K__
135 /* for cfm68k we take the second pstring */
136 *dataptr = *((*h)+(**h)+1);
137 memcpy(dataptr+1, (*h)+(**h)+2, (int)*dataptr);
138#else
139 /* for ppc we take the first pstring */
Jack Jansen1e2260f1998-07-13 13:37:12 +0000140 *dataptr = **h;
141 memcpy(dataptr+1, (*h)+1, (int)*dataptr);
Jack Jansen017e0ff1998-07-31 09:34:47 +0000142#endif
Jack Jansen1e2260f1998-07-13 13:37:12 +0000143 HUnlock(h);
144 }
145 if ( filerh != -1 )
146 CloseResFile(filerh);
147 UseResFile(oldrh);
148 return ok;
149}
150
151/*
152** Returns true if the argument has a resource fork, and it contains
153** a 'PYC ' resource of the correct name
154*/
155int
156PyMac_FindResourceModule(obj, module, filename)
157PyStringObject *obj;
158char *module;
159char *filename;
160{
161 int ok;
162
163 ok = findnamedresource(obj, module, filename, 'PYC ', (StringPtr)0);
164 return ok;
165}
166
167/*
168** Returns true if the argument has a resource fork, and it contains
169** a 'PYD ' resource of the correct name
170*/
171int
172PyMac_FindCodeResourceModule(obj, module, filename)
173PyStringObject *obj;
174char *module;
175char *filename;
176{
177 int ok;
178
179 ok = findnamedresource(obj, module, filename, 'PYD ', (StringPtr)0);
180 return ok;
181}
182
183
184/*
185** Load the specified module from a code resource
186*/
187PyObject *
188PyMac_LoadCodeResourceModule(name, pathname)
189 char *name;
190 char *pathname;
191{
Jack Jansen017e0ff1998-07-31 09:34:47 +0000192 PyObject *m, *d, *s;
Jack Jansen1e2260f1998-07-13 13:37:12 +0000193 char funcname[258];
194 char *lastdot, *shortname, *packagecontext;
195 dl_funcptr p = NULL;
196 Str255 fragmentname;
197 CFragConnectionID connID;
198 Ptr mainAddr;
199 Str255 errMessage;
200 OSErr err;
201 char buf[512];
202 Ptr symAddr;
203 CFragSymbolClass class;
204
205 if ((m = _PyImport_FindExtension(name, name)) != NULL) {
206 Py_INCREF(m);
207 return m;
208 }
209 lastdot = strrchr(name, '.');
210 if (lastdot == NULL) {
211 packagecontext = NULL;
212 shortname = name;
213 }
214 else {
215 packagecontext = name;
216 shortname = lastdot+1;
217 }
218 sprintf(funcname, FUNCNAME_PATTERN, shortname);
219 if( !findnamedresource((PyStringObject *)0, shortname, pathname, 'PYD ', fragmentname)) {
220 PyErr_SetString(PyExc_ImportError, "PYD resource not found");
221 return NULL;
222 }
223
224 /* Load the fragment
225 (or return the connID if it is already loaded */
226 err = GetSharedLibrary(fragmentname, kCompiledCFragArch,
227 kLoadCFrag, &connID, &mainAddr,
228 errMessage);
229 if ( err ) {
230 sprintf(buf, "%.*s: %.200s",
231 errMessage[0], errMessage+1,
232 PyMac_StrError(err));
233 PyErr_SetString(PyExc_ImportError, buf);
234 return NULL;
235 }
236 /* Locate the address of the correct init function */
237 err = FindSymbol(connID, Pstring(funcname), &symAddr, &class);
238 if ( err ) {
239 sprintf(buf, "%s: %.200s",
240 funcname, PyMac_StrError(err));
241 PyErr_SetString(PyExc_ImportError, buf);
242 return NULL;
243 }
244 p = (dl_funcptr)symAddr;
245 if (p == NULL) {
246 PyErr_Format(PyExc_ImportError,
247 "dynamic module does not define init function (%.200s)",
248 funcname);
249 return NULL;
250 }
251 _Py_PackageContext = packagecontext;
252 (*p)();
253 _Py_PackageContext = NULL;
254 if (PyErr_Occurred())
255 return NULL;
256 if (_PyImport_FixupExtension(name, name) == NULL)
257 return NULL;
258
259 m = PyDict_GetItemString(PyImport_GetModuleDict(), name);
260 if (m == NULL) {
261 PyErr_SetString(PyExc_SystemError,
262 "dynamic module not initialized properly");
263 return NULL;
264 }
Jack Jansen017e0ff1998-07-31 09:34:47 +0000265#if 1
Jack Jansen1e2260f1998-07-13 13:37:12 +0000266 /* Remember the filename as the __file__ attribute */
267 d = PyModule_GetDict(m);
268 s = PyString_FromString(pathname);
269 if (s == NULL || PyDict_SetItemString(d, "__file__", s) != 0)
270 PyErr_Clear(); /* Not important enough to report */
271 Py_XDECREF(s);
272#endif
273 if (Py_VerboseFlag)
Jack Jansendeff89c1998-10-12 20:53:15 +0000274 PySys_WriteStderr("import %s # pyd fragment %#s loaded from %s\n",
Jack Jansen1e2260f1998-07-13 13:37:12 +0000275 name, fragmentname, pathname);
276 Py_INCREF(m);
277 return m;
278}
279
280/*
281** Load the specified module from a resource
282*/
283PyObject *
284PyMac_LoadResourceModule(module, filename)
285char *module;
286char *filename;
287{
288 FSSpec fss;
289 FInfo finfo;
290 short oldrh, filerh;
291 Handle h;
292 OSErr err;
293 PyObject *m, *co;
294 long num, size;
295
296 if ( strcmp(filename, PyMac_ApplicationPath) == 0 ) {
297 /*
298 ** Special case: the application itself. Use a shortcut to
299 ** forestall opening and closing the application numerous times
300 ** (which is dead slow when running from CDROM)
301 */
302 oldrh = CurResFile();
303 UseResFile(PyMac_AppRefNum);
304 filerh = -1;
305 } else {
Jack Jansen2d1306b2000-04-07 09:10:49 +0000306#ifdef USE_GUSI1
Jack Jansen48a9c361998-09-07 11:36:17 +0000307 if ( (err=Path2FSSpec(filename, &fss)) != noErr ||
308 FSpGetFInfo(&fss, &finfo) != noErr )
309#else
Jack Jansen1e2260f1998-07-13 13:37:12 +0000310 if ( (err=FSMakeFSSpec(0, 0, Pstring(filename), &fss)) != noErr )
Jack Jansen48a9c361998-09-07 11:36:17 +0000311#endif
Jack Jansen1e2260f1998-07-13 13:37:12 +0000312 goto error;
313 if ( (err=FSpGetFInfo(&fss, &finfo)) != noErr )
314 goto error;
315 oldrh = CurResFile();
316 filerh = FSpOpenResFile(&fss, fsRdPerm);
317 if ( filerh == -1 ) {
318 err = ResError();
319 goto error;
320 }
321 UseResFile(filerh);
322 }
323 h = Get1NamedResource('PYC ', Pstring(module));
324 if ( h == NULL ) {
325 err = ResError();
326 goto error;
327 }
328 HLock(h);
329 /*
330 ** XXXX The next few lines are intimately tied to the format of pyc
331 ** files. I'm not sure whether this code should be here or in import.c -- Jack
332 */
333 size = GetHandleSize(h);
334 if ( size < 8 ) {
335 PyErr_SetString(PyExc_ImportError, "Resource too small");
336 co = NULL;
337 } else {
338 num = (*h)[0] & 0xff;
339 num = num | (((*h)[1] & 0xff) << 8);
340 num = num | (((*h)[2] & 0xff) << 16);
341 num = num | (((*h)[3] & 0xff) << 24);
342 if ( num != PyImport_GetMagicNumber() ) {
343 PyErr_SetString(PyExc_ImportError, "Bad MAGIC in resource");
344 co = NULL;
345 } else {
346 co = PyMarshal_ReadObjectFromString((*h)+8, size-8);
Jack Jansenb93f5211998-08-18 12:23:11 +0000347 /*
348 ** Normally, byte 4-7 are the time stamp, but that is not used
349 ** for 'PYC ' resources. We abuse byte 4 as a flag to indicate
350 ** that it is a package rather than an ordinary module.
351 ** See also py_resource.py. (jvr)
352 */
353 if ((*h)[4] & 0xff) {
354 /* it's a package */
355 /* Set __path__ to the package name */
356 PyObject *d, *s;
357 int err;
358
359 m = PyImport_AddModule(module);
360 if (m == NULL) {
361 co = NULL;
362 goto packageerror;
363 }
364 d = PyModule_GetDict(m);
365 s = PyString_InternFromString(module);
366 if (s == NULL) {
367 co = NULL;
368 goto packageerror;
369 }
370 err = PyDict_SetItemString(d, "__path__", s);
371 Py_DECREF(s);
372 if (err != 0) {
373 co = NULL;
374 goto packageerror;
375 }
376 }
Jack Jansen1e2260f1998-07-13 13:37:12 +0000377 }
378 }
Jack Jansenb93f5211998-08-18 12:23:11 +0000379packageerror:
Jack Jansen1e2260f1998-07-13 13:37:12 +0000380 HUnlock(h);
381 if ( filerh != -1 )
382 CloseResFile(filerh);
Jack Jansenadd8b242001-02-21 15:48:19 +0000383 else
384 ReleaseResource(h);
Jack Jansen1e2260f1998-07-13 13:37:12 +0000385 UseResFile(oldrh);
386 if ( co ) {
Jack Jansenb93f5211998-08-18 12:23:11 +0000387 m = PyImport_ExecCodeModuleEx(module, co, "<pyc resource>");
Jack Jansen1e2260f1998-07-13 13:37:12 +0000388 Py_DECREF(co);
389 } else {
390 m = NULL;
391 }
392 if (Py_VerboseFlag)
Jack Jansendeff89c1998-10-12 20:53:15 +0000393 PySys_WriteStderr("import %s # pyc resource from %s\n",
Jack Jansen1e2260f1998-07-13 13:37:12 +0000394 module, filename);
395 return m;
396error:
397 {
398 char buf[512];
399
400 sprintf(buf, "%s: %s", filename, PyMac_StrError(err));
401 PyErr_SetString(PyExc_ImportError, buf);
402 return NULL;
403 }
404}
405
406/*
407** Look for a module in a single folder. Upon entry buf and len
408** point to the folder to search, upon exit they refer to the full
409** pathname of the module found (if any).
410*/
411struct filedescr *
Jack Jansenfe38d292000-07-03 23:53:40 +0000412PyMac_FindModuleExtension(char *buf, size_t *lenp, char *module)
Jack Jansen1e2260f1998-07-13 13:37:12 +0000413{
414 struct filedescr *fdp;
415 unsigned char fnbuf[64];
416 int modnamelen = strlen(module);
417 FSSpec fss;
Jack Jansen9ae898b2000-07-11 21:16:03 +0000418#ifdef USE_GUSI1
Jack Jansen48a9c361998-09-07 11:36:17 +0000419 FInfo finfo;
Jack Jansen9ae898b2000-07-11 21:16:03 +0000420#endif
Jack Jansen1e2260f1998-07-13 13:37:12 +0000421 short refnum;
422 long dirid;
423
424 /*
425 ** Copy the module name to the buffer (already :-terminated)
426 ** We also copy the first suffix, if this matches immedeately we're
427 ** lucky and return immedeately.
428 */
429 if ( !_PyImport_Filetab[0].suffix )
430 return 0;
431
432#if 0
433 /* Pre 1.5a4 */
434 strcpy(buf+*lenp, module);
435 strcpy(buf+*lenp+modnamelen, _PyImport_Filetab[0].suffix);
436#else
437 strcpy(buf+*lenp, _PyImport_Filetab[0].suffix);
438#endif
Jack Jansen2d1306b2000-04-07 09:10:49 +0000439#ifdef USE_GUSI1
Jack Jansen48a9c361998-09-07 11:36:17 +0000440 if ( Path2FSSpec(buf, &fss) == noErr &&
441 FSpGetFInfo(&fss, &finfo) == noErr)
442 return _PyImport_Filetab;
443#else
Jack Jansen1e2260f1998-07-13 13:37:12 +0000444 if ( FSMakeFSSpec(0, 0, Pstring(buf), &fss) == noErr )
445 return _PyImport_Filetab;
Jack Jansen48a9c361998-09-07 11:36:17 +0000446#endif
Jack Jansen1e2260f1998-07-13 13:37:12 +0000447 /*
448 ** We cannot check for fnfErr (unfortunately), it can mean either that
449 ** the file doesn't exist (fine, we try others) or the path leading to it.
450 */
451 refnum = fss.vRefNum;
452 dirid = fss.parID;
453 if ( refnum == 0 || dirid == 0 ) /* Fail on nonexistent dir */
454 return 0;
455 /*
456 ** We now have the folder parameters. Setup the field for the filename
457 */
458 if ( modnamelen > 54 ) return 0; /* Leave room for extension */
459 strcpy((char *)fnbuf+1, module);
460
461 for( fdp = _PyImport_Filetab+1; fdp->suffix; fdp++ ) {
462 strcpy((char *)fnbuf+1+modnamelen, fdp->suffix);
463 fnbuf[0] = strlen((char *)fnbuf+1);
464 if (Py_VerboseFlag > 1)
Jack Jansendeff89c1998-10-12 20:53:15 +0000465 PySys_WriteStderr("# trying %s%s\n", buf, fdp->suffix);
Jack Jansen1e2260f1998-07-13 13:37:12 +0000466 if ( FSMakeFSSpec(refnum, dirid, fnbuf, &fss) == noErr ) {
467 /* Found it. */
468#if 0
469 strcpy(buf+*lenp+modnamelen, fdp->suffix);
470#else
471 strcpy(buf+*lenp, fdp->suffix);
472#endif
473 *lenp = strlen(buf);
474 return fdp;
475 }
476 }
477 return 0;
478}