import.c revision 031829d3ef22fcc0f5a6d325fee075ee11186599
1 2/* Module definition and import implementation */ 3 4#include "Python.h" 5 6#include "node.h" 7#include "token.h" 8#include "errcode.h" 9#include "marshal.h" 10#include "compile.h" 11#include "eval.h" 12#include "osdefs.h" 13#include "importdl.h" 14#ifdef macintosh 15#include "macglue.h" 16#endif 17 18#ifdef HAVE_FCNTL_H 19#include <fcntl.h> 20#endif 21 22extern time_t PyOS_GetLastModificationTime(char *, FILE *); 23 /* In getmtime.c */ 24 25/* Magic word to reject .pyc files generated by other Python versions */ 26/* Change for each incompatible change */ 27/* The value of CR and LF is incorporated so if you ever read or write 28 a .pyc file in text mode the magic number will be wrong; also, the 29 Apple MPW compiler swaps their values, botching string constants. 30 XXX That probably isn't important anymore. 31*/ 32/* XXX Perhaps the magic number should be frozen and a version field 33 added to the .pyc file header? */ 34/* New way to come up with the low 16 bits of the magic number: 35 (YEAR-1995) * 10000 + MONTH * 100 + DAY 36 where MONTH and DAY are 1-based. 37 XXX Whatever the "old way" may have been isn't documented. 38 XXX This scheme breaks in 2002, as (2002-1995)*10000 = 70000 doesn't 39 fit in 16 bits. 40 XXX Later, sometimes 1 gets added to MAGIC in order to record that 41 the Unicode -U option is in use. IMO (Tim's), that's a Bad Idea 42 (quite apart from that the -U option doesn't work so isn't used 43 anyway). 44 45 XXX MAL, 2002-02-07: I had to modify the MAGIC due to a fix of the 46 UTF-8 encoder (it previously produced invalid UTF-8 for unpaired 47 high surrogates), so I simply bumped the month value to 20 (invalid 48 month) and set the day to 1. This should be recognizable by any 49 algorithm relying on the above scheme. Perhaps we should simply 50 start counting in increments of 10 from now on ?! 51 52 Known values: 53 Python 1.5: 20121 54 Python 1.5.1: 20121 55 Python 1.5.2: 20121 56 Python 2.0: 50823 57 Python 2.0.1: 50823 58 Python 2.1: 60202 59 Python 2.1.1: 60202 60 Python 2.1.2: 60202 61 Python 2.2: 60717 62 Python 2.3a0: 62001 63*/ 64#define MAGIC (62001 | ((long)'\r'<<16) | ((long)'\n'<<24)) 65 66/* Magic word as global; note that _PyImport_Init() can change the 67 value of this global to accommodate for alterations of how the 68 compiler works which are enabled by command line switches. */ 69static long pyc_magic = MAGIC; 70 71/* See _PyImport_FixupExtension() below */ 72static PyObject *extensions = NULL; 73 74/* This table is defined in config.c: */ 75extern struct _inittab _PyImport_Inittab[]; 76 77struct _inittab *PyImport_Inittab = _PyImport_Inittab; 78 79/* these tables define the module suffixes that Python recognizes */ 80struct filedescr * _PyImport_Filetab = NULL; 81 82#ifdef RISCOS 83static const struct filedescr _PyImport_StandardFiletab[] = { 84 {"/py", "r", PY_SOURCE}, 85 {"/pyc", "rb", PY_COMPILED}, 86 {0, 0} 87}; 88#else 89static const struct filedescr _PyImport_StandardFiletab[] = { 90 {".py", "r", PY_SOURCE}, 91#ifdef MS_WIN32 92 {".pyw", "r", PY_SOURCE}, 93#endif 94 {".pyc", "rb", PY_COMPILED}, 95 {0, 0} 96}; 97#endif 98 99/* Initialize things */ 100 101void 102_PyImport_Init(void) 103{ 104 const struct filedescr *scan; 105 struct filedescr *filetab; 106 int countD = 0; 107 int countS = 0; 108 109 /* prepare _PyImport_Filetab: copy entries from 110 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab. 111 */ 112 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan) 113 ++countD; 114 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan) 115 ++countS; 116 filetab = PyMem_NEW(struct filedescr, countD + countS + 1); 117 memcpy(filetab, _PyImport_DynLoadFiletab, 118 countD * sizeof(struct filedescr)); 119 memcpy(filetab + countD, _PyImport_StandardFiletab, 120 countS * sizeof(struct filedescr)); 121 filetab[countD + countS].suffix = NULL; 122 123 _PyImport_Filetab = filetab; 124 125 if (Py_OptimizeFlag) { 126 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */ 127 for (; filetab->suffix != NULL; filetab++) { 128#ifndef RISCOS 129 if (strcmp(filetab->suffix, ".pyc") == 0) 130 filetab->suffix = ".pyo"; 131#else 132 if (strcmp(filetab->suffix, "/pyc") == 0) 133 filetab->suffix = "/pyo"; 134#endif 135 } 136 } 137 138 if (Py_UnicodeFlag) { 139 /* Fix the pyc_magic so that byte compiled code created 140 using the all-Unicode method doesn't interfere with 141 code created in normal operation mode. */ 142 pyc_magic = MAGIC + 1; 143 } 144} 145 146void 147_PyImport_Fini(void) 148{ 149 Py_XDECREF(extensions); 150 extensions = NULL; 151 PyMem_DEL(_PyImport_Filetab); 152 _PyImport_Filetab = NULL; 153} 154 155 156/* Locking primitives to prevent parallel imports of the same module 157 in different threads to return with a partially loaded module. 158 These calls are serialized by the global interpreter lock. */ 159 160#ifdef WITH_THREAD 161 162#include "pythread.h" 163 164static PyThread_type_lock import_lock = 0; 165static long import_lock_thread = -1; 166static int import_lock_level = 0; 167 168static void 169lock_import(void) 170{ 171 long me = PyThread_get_thread_ident(); 172 if (me == -1) 173 return; /* Too bad */ 174 if (import_lock == NULL) 175 import_lock = PyThread_allocate_lock(); 176 if (import_lock_thread == me) { 177 import_lock_level++; 178 return; 179 } 180 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0)) { 181 PyThreadState *tstate = PyEval_SaveThread(); 182 PyThread_acquire_lock(import_lock, 1); 183 PyEval_RestoreThread(tstate); 184 } 185 import_lock_thread = me; 186 import_lock_level = 1; 187} 188 189static void 190unlock_import(void) 191{ 192 long me = PyThread_get_thread_ident(); 193 if (me == -1) 194 return; /* Too bad */ 195 if (import_lock_thread != me) 196 Py_FatalError("unlock_import: not holding the import lock"); 197 import_lock_level--; 198 if (import_lock_level == 0) { 199 import_lock_thread = -1; 200 PyThread_release_lock(import_lock); 201 } 202} 203 204#else 205 206#define lock_import() 207#define unlock_import() 208 209#endif 210 211static PyObject * 212imp_lock_held(PyObject *self, PyObject *args) 213{ 214 if (!PyArg_ParseTuple(args, ":lock_held")) 215 return NULL; 216#ifdef WITH_THREAD 217 return PyInt_FromLong(import_lock_thread != -1); 218#else 219 return PyInt_FromLong(0); 220#endif 221} 222 223/* Helper for sys */ 224 225PyObject * 226PyImport_GetModuleDict(void) 227{ 228 PyInterpreterState *interp = PyThreadState_Get()->interp; 229 if (interp->modules == NULL) 230 Py_FatalError("PyImport_GetModuleDict: no module dictionary!"); 231 return interp->modules; 232} 233 234 235/* List of names to clear in sys */ 236static char* sys_deletes[] = { 237 "path", "argv", "ps1", "ps2", "exitfunc", 238 "exc_type", "exc_value", "exc_traceback", 239 "last_type", "last_value", "last_traceback", 240 NULL 241}; 242 243static char* sys_files[] = { 244 "stdin", "__stdin__", 245 "stdout", "__stdout__", 246 "stderr", "__stderr__", 247 NULL 248}; 249 250 251/* Un-initialize things, as good as we can */ 252 253void 254PyImport_Cleanup(void) 255{ 256 int pos, ndone; 257 char *name; 258 PyObject *key, *value, *dict; 259 PyInterpreterState *interp = PyThreadState_Get()->interp; 260 PyObject *modules = interp->modules; 261 262 if (modules == NULL) 263 return; /* Already done */ 264 265 /* Delete some special variables first. These are common 266 places where user values hide and people complain when their 267 destructors fail. Since the modules containing them are 268 deleted *last* of all, they would come too late in the normal 269 destruction order. Sigh. */ 270 271 value = PyDict_GetItemString(modules, "__builtin__"); 272 if (value != NULL && PyModule_Check(value)) { 273 dict = PyModule_GetDict(value); 274 if (Py_VerboseFlag) 275 PySys_WriteStderr("# clear __builtin__._\n"); 276 PyDict_SetItemString(dict, "_", Py_None); 277 } 278 value = PyDict_GetItemString(modules, "sys"); 279 if (value != NULL && PyModule_Check(value)) { 280 char **p; 281 PyObject *v; 282 dict = PyModule_GetDict(value); 283 for (p = sys_deletes; *p != NULL; p++) { 284 if (Py_VerboseFlag) 285 PySys_WriteStderr("# clear sys.%s\n", *p); 286 PyDict_SetItemString(dict, *p, Py_None); 287 } 288 for (p = sys_files; *p != NULL; p+=2) { 289 if (Py_VerboseFlag) 290 PySys_WriteStderr("# restore sys.%s\n", *p); 291 v = PyDict_GetItemString(dict, *(p+1)); 292 if (v == NULL) 293 v = Py_None; 294 PyDict_SetItemString(dict, *p, v); 295 } 296 } 297 298 /* First, delete __main__ */ 299 value = PyDict_GetItemString(modules, "__main__"); 300 if (value != NULL && PyModule_Check(value)) { 301 if (Py_VerboseFlag) 302 PySys_WriteStderr("# cleanup __main__\n"); 303 _PyModule_Clear(value); 304 PyDict_SetItemString(modules, "__main__", Py_None); 305 } 306 307 /* The special treatment of __builtin__ here is because even 308 when it's not referenced as a module, its dictionary is 309 referenced by almost every module's __builtins__. Since 310 deleting a module clears its dictionary (even if there are 311 references left to it), we need to delete the __builtin__ 312 module last. Likewise, we don't delete sys until the very 313 end because it is implicitly referenced (e.g. by print). 314 315 Also note that we 'delete' modules by replacing their entry 316 in the modules dict with None, rather than really deleting 317 them; this avoids a rehash of the modules dictionary and 318 also marks them as "non existent" so they won't be 319 re-imported. */ 320 321 /* Next, repeatedly delete modules with a reference count of 322 one (skipping __builtin__ and sys) and delete them */ 323 do { 324 ndone = 0; 325 pos = 0; 326 while (PyDict_Next(modules, &pos, &key, &value)) { 327 if (value->ob_refcnt != 1) 328 continue; 329 if (PyString_Check(key) && PyModule_Check(value)) { 330 name = PyString_AS_STRING(key); 331 if (strcmp(name, "__builtin__") == 0) 332 continue; 333 if (strcmp(name, "sys") == 0) 334 continue; 335 if (Py_VerboseFlag) 336 PySys_WriteStderr( 337 "# cleanup[1] %s\n", name); 338 _PyModule_Clear(value); 339 PyDict_SetItem(modules, key, Py_None); 340 ndone++; 341 } 342 } 343 } while (ndone > 0); 344 345 /* Next, delete all modules (still skipping __builtin__ and sys) */ 346 pos = 0; 347 while (PyDict_Next(modules, &pos, &key, &value)) { 348 if (PyString_Check(key) && PyModule_Check(value)) { 349 name = PyString_AS_STRING(key); 350 if (strcmp(name, "__builtin__") == 0) 351 continue; 352 if (strcmp(name, "sys") == 0) 353 continue; 354 if (Py_VerboseFlag) 355 PySys_WriteStderr("# cleanup[2] %s\n", name); 356 _PyModule_Clear(value); 357 PyDict_SetItem(modules, key, Py_None); 358 } 359 } 360 361 /* Next, delete sys and __builtin__ (in that order) */ 362 value = PyDict_GetItemString(modules, "sys"); 363 if (value != NULL && PyModule_Check(value)) { 364 if (Py_VerboseFlag) 365 PySys_WriteStderr("# cleanup sys\n"); 366 _PyModule_Clear(value); 367 PyDict_SetItemString(modules, "sys", Py_None); 368 } 369 value = PyDict_GetItemString(modules, "__builtin__"); 370 if (value != NULL && PyModule_Check(value)) { 371 if (Py_VerboseFlag) 372 PySys_WriteStderr("# cleanup __builtin__\n"); 373 _PyModule_Clear(value); 374 PyDict_SetItemString(modules, "__builtin__", Py_None); 375 } 376 377 /* Finally, clear and delete the modules directory */ 378 PyDict_Clear(modules); 379 interp->modules = NULL; 380 Py_DECREF(modules); 381} 382 383 384/* Helper for pythonrun.c -- return magic number */ 385 386long 387PyImport_GetMagicNumber(void) 388{ 389 return pyc_magic; 390} 391 392 393/* Magic for extension modules (built-in as well as dynamically 394 loaded). To prevent initializing an extension module more than 395 once, we keep a static dictionary 'extensions' keyed by module name 396 (for built-in modules) or by filename (for dynamically loaded 397 modules), containing these modules. A copy of the module's 398 dictionary is stored by calling _PyImport_FixupExtension() 399 immediately after the module initialization function succeeds. A 400 copy can be retrieved from there by calling 401 _PyImport_FindExtension(). */ 402 403PyObject * 404_PyImport_FixupExtension(char *name, char *filename) 405{ 406 PyObject *modules, *mod, *dict, *copy; 407 if (extensions == NULL) { 408 extensions = PyDict_New(); 409 if (extensions == NULL) 410 return NULL; 411 } 412 modules = PyImport_GetModuleDict(); 413 mod = PyDict_GetItemString(modules, name); 414 if (mod == NULL || !PyModule_Check(mod)) { 415 PyErr_Format(PyExc_SystemError, 416 "_PyImport_FixupExtension: module %.200s not loaded", name); 417 return NULL; 418 } 419 dict = PyModule_GetDict(mod); 420 if (dict == NULL) 421 return NULL; 422 copy = PyDict_Copy(dict); 423 if (copy == NULL) 424 return NULL; 425 PyDict_SetItemString(extensions, filename, copy); 426 Py_DECREF(copy); 427 return copy; 428} 429 430PyObject * 431_PyImport_FindExtension(char *name, char *filename) 432{ 433 PyObject *dict, *mod, *mdict; 434 if (extensions == NULL) 435 return NULL; 436 dict = PyDict_GetItemString(extensions, filename); 437 if (dict == NULL) 438 return NULL; 439 mod = PyImport_AddModule(name); 440 if (mod == NULL) 441 return NULL; 442 mdict = PyModule_GetDict(mod); 443 if (mdict == NULL) 444 return NULL; 445 if (PyDict_Update(mdict, dict)) 446 return NULL; 447 if (Py_VerboseFlag) 448 PySys_WriteStderr("import %s # previously loaded (%s)\n", 449 name, filename); 450 return mod; 451} 452 453 454/* Get the module object corresponding to a module name. 455 First check the modules dictionary if there's one there, 456 if not, create a new one and insert in in the modules dictionary. 457 Because the former action is most common, THIS DOES NOT RETURN A 458 'NEW' REFERENCE! */ 459 460PyObject * 461PyImport_AddModule(char *name) 462{ 463 PyObject *modules = PyImport_GetModuleDict(); 464 PyObject *m; 465 466 if ((m = PyDict_GetItemString(modules, name)) != NULL && 467 PyModule_Check(m)) 468 return m; 469 m = PyModule_New(name); 470 if (m == NULL) 471 return NULL; 472 if (PyDict_SetItemString(modules, name, m) != 0) { 473 Py_DECREF(m); 474 return NULL; 475 } 476 Py_DECREF(m); /* Yes, it still exists, in modules! */ 477 478 return m; 479} 480 481 482/* Execute a code object in a module and return the module object 483 WITH INCREMENTED REFERENCE COUNT */ 484 485PyObject * 486PyImport_ExecCodeModule(char *name, PyObject *co) 487{ 488 return PyImport_ExecCodeModuleEx(name, co, (char *)NULL); 489} 490 491PyObject * 492PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname) 493{ 494 PyObject *modules = PyImport_GetModuleDict(); 495 PyObject *m, *d, *v; 496 497 m = PyImport_AddModule(name); 498 if (m == NULL) 499 return NULL; 500 d = PyModule_GetDict(m); 501 if (PyDict_GetItemString(d, "__builtins__") == NULL) { 502 if (PyDict_SetItemString(d, "__builtins__", 503 PyEval_GetBuiltins()) != 0) 504 return NULL; 505 } 506 /* Remember the filename as the __file__ attribute */ 507 v = NULL; 508 if (pathname != NULL) { 509 v = PyString_FromString(pathname); 510 if (v == NULL) 511 PyErr_Clear(); 512 } 513 if (v == NULL) { 514 v = ((PyCodeObject *)co)->co_filename; 515 Py_INCREF(v); 516 } 517 if (PyDict_SetItemString(d, "__file__", v) != 0) 518 PyErr_Clear(); /* Not important enough to report */ 519 Py_DECREF(v); 520 521 v = PyEval_EvalCode((PyCodeObject *)co, d, d); 522 if (v == NULL) 523 return NULL; 524 Py_DECREF(v); 525 526 if ((m = PyDict_GetItemString(modules, name)) == NULL) { 527 PyErr_Format(PyExc_ImportError, 528 "Loaded module %.200s not found in sys.modules", 529 name); 530 return NULL; 531 } 532 533 Py_INCREF(m); 534 535 return m; 536} 537 538 539/* Given a pathname for a Python source file, fill a buffer with the 540 pathname for the corresponding compiled file. Return the pathname 541 for the compiled file, or NULL if there's no space in the buffer. 542 Doesn't set an exception. */ 543 544static char * 545make_compiled_pathname(char *pathname, char *buf, size_t buflen) 546{ 547 size_t len = strlen(pathname); 548 if (len+2 > buflen) 549 return NULL; 550 551#ifdef MS_WIN32 552 /* Treat .pyw as if it were .py. The case of ".pyw" must match 553 that used in _PyImport_StandardFiletab. */ 554 if (len >= 4 && strcmp(&pathname[len-4], ".pyw") == 0) 555 --len; /* pretend 'w' isn't there */ 556#endif 557 memcpy(buf, pathname, len); 558 buf[len] = Py_OptimizeFlag ? 'o' : 'c'; 559 buf[len+1] = '\0'; 560 561 return buf; 562} 563 564 565/* Given a pathname for a Python source file, its time of last 566 modification, and a pathname for a compiled file, check whether the 567 compiled file represents the same version of the source. If so, 568 return a FILE pointer for the compiled file, positioned just after 569 the header; if not, return NULL. 570 Doesn't set an exception. */ 571 572static FILE * 573check_compiled_module(char *pathname, long mtime, char *cpathname) 574{ 575 FILE *fp; 576 long magic; 577 long pyc_mtime; 578 579 fp = fopen(cpathname, "rb"); 580 if (fp == NULL) 581 return NULL; 582 magic = PyMarshal_ReadLongFromFile(fp); 583 if (magic != pyc_magic) { 584 if (Py_VerboseFlag) 585 PySys_WriteStderr("# %s has bad magic\n", cpathname); 586 fclose(fp); 587 return NULL; 588 } 589 pyc_mtime = PyMarshal_ReadLongFromFile(fp); 590 if (pyc_mtime != mtime) { 591 if (Py_VerboseFlag) 592 PySys_WriteStderr("# %s has bad mtime\n", cpathname); 593 fclose(fp); 594 return NULL; 595 } 596 if (Py_VerboseFlag) 597 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname); 598 return fp; 599} 600 601 602/* Read a code object from a file and check it for validity */ 603 604static PyCodeObject * 605read_compiled_module(char *cpathname, FILE *fp) 606{ 607 PyObject *co; 608 609 co = PyMarshal_ReadLastObjectFromFile(fp); 610 /* Ugly: rd_object() may return NULL with or without error */ 611 if (co == NULL || !PyCode_Check(co)) { 612 if (!PyErr_Occurred()) 613 PyErr_Format(PyExc_ImportError, 614 "Non-code object in %.200s", cpathname); 615 Py_XDECREF(co); 616 return NULL; 617 } 618 return (PyCodeObject *)co; 619} 620 621 622/* Load a module from a compiled file, execute it, and return its 623 module object WITH INCREMENTED REFERENCE COUNT */ 624 625static PyObject * 626load_compiled_module(char *name, char *cpathname, FILE *fp) 627{ 628 long magic; 629 PyCodeObject *co; 630 PyObject *m; 631 632 magic = PyMarshal_ReadLongFromFile(fp); 633 if (magic != pyc_magic) { 634 PyErr_Format(PyExc_ImportError, 635 "Bad magic number in %.200s", cpathname); 636 return NULL; 637 } 638 (void) PyMarshal_ReadLongFromFile(fp); 639 co = read_compiled_module(cpathname, fp); 640 if (co == NULL) 641 return NULL; 642 if (Py_VerboseFlag) 643 PySys_WriteStderr("import %s # precompiled from %s\n", 644 name, cpathname); 645 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname); 646 Py_DECREF(co); 647 648 return m; 649} 650 651/* Parse a source file and return the corresponding code object */ 652 653static PyCodeObject * 654parse_source_module(char *pathname, FILE *fp) 655{ 656 PyCodeObject *co; 657 node *n; 658 659 n = PyParser_SimpleParseFile(fp, pathname, Py_file_input); 660 if (n == NULL) 661 return NULL; 662 co = PyNode_Compile(n, pathname); 663 PyNode_Free(n); 664 665 return co; 666} 667 668 669/* Helper to open a bytecode file for writing in exclusive mode */ 670 671static FILE * 672open_exclusive(char *filename) 673{ 674#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC) 675 /* Use O_EXCL to avoid a race condition when another process tries to 676 write the same file. When that happens, our open() call fails, 677 which is just fine (since it's only a cache). 678 XXX If the file exists and is writable but the directory is not 679 writable, the file will never be written. Oh well. 680 */ 681 int fd; 682 (void) unlink(filename); 683 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC 684#ifdef O_BINARY 685 |O_BINARY /* necessary for Windows */ 686#endif 687 688 , 0666); 689 if (fd < 0) 690 return NULL; 691 return fdopen(fd, "wb"); 692#else 693 /* Best we can do -- on Windows this can't happen anyway */ 694 return fopen(filename, "wb"); 695#endif 696} 697 698 699/* Write a compiled module to a file, placing the time of last 700 modification of its source into the header. 701 Errors are ignored, if a write error occurs an attempt is made to 702 remove the file. */ 703 704static void 705write_compiled_module(PyCodeObject *co, char *cpathname, long mtime) 706{ 707 FILE *fp; 708 709 fp = open_exclusive(cpathname); 710 if (fp == NULL) { 711 if (Py_VerboseFlag) 712 PySys_WriteStderr( 713 "# can't create %s\n", cpathname); 714 return; 715 } 716 PyMarshal_WriteLongToFile(pyc_magic, fp); 717 /* First write a 0 for mtime */ 718 PyMarshal_WriteLongToFile(0L, fp); 719 PyMarshal_WriteObjectToFile((PyObject *)co, fp); 720 if (ferror(fp)) { 721 if (Py_VerboseFlag) 722 PySys_WriteStderr("# can't write %s\n", cpathname); 723 /* Don't keep partial file */ 724 fclose(fp); 725 (void) unlink(cpathname); 726 return; 727 } 728 /* Now write the true mtime */ 729 fseek(fp, 4L, 0); 730 PyMarshal_WriteLongToFile(mtime, fp); 731 fflush(fp); 732 fclose(fp); 733 if (Py_VerboseFlag) 734 PySys_WriteStderr("# wrote %s\n", cpathname); 735#ifdef macintosh 736 PyMac_setfiletype(cpathname, 'Pyth', 'PYC '); 737#endif 738} 739 740 741/* Load a source module from a given file and return its module 742 object WITH INCREMENTED REFERENCE COUNT. If there's a matching 743 byte-compiled file, use that instead. */ 744 745static PyObject * 746load_source_module(char *name, char *pathname, FILE *fp) 747{ 748 time_t mtime; 749 FILE *fpc; 750 char buf[MAXPATHLEN+1]; 751 char *cpathname; 752 PyCodeObject *co; 753 PyObject *m; 754 755 mtime = PyOS_GetLastModificationTime(pathname, fp); 756 if (mtime == (time_t)(-1)) 757 return NULL; 758#if SIZEOF_TIME_T > 4 759 /* Python's .pyc timestamp handling presumes that the timestamp fits 760 in 4 bytes. This will be fine until sometime in the year 2038, 761 when a 4-byte signed time_t will overflow. 762 */ 763 if (mtime >> 32) { 764 PyErr_SetString(PyExc_OverflowError, 765 "modification time overflows a 4 byte field"); 766 return NULL; 767 } 768#endif 769 cpathname = make_compiled_pathname(pathname, buf, 770 (size_t)MAXPATHLEN + 1); 771 if (cpathname != NULL && 772 (fpc = check_compiled_module(pathname, mtime, cpathname))) { 773 co = read_compiled_module(cpathname, fpc); 774 fclose(fpc); 775 if (co == NULL) 776 return NULL; 777 if (Py_VerboseFlag) 778 PySys_WriteStderr("import %s # precompiled from %s\n", 779 name, cpathname); 780 pathname = cpathname; 781 } 782 else { 783 co = parse_source_module(pathname, fp); 784 if (co == NULL) 785 return NULL; 786 if (Py_VerboseFlag) 787 PySys_WriteStderr("import %s # from %s\n", 788 name, pathname); 789 write_compiled_module(co, cpathname, mtime); 790 } 791 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname); 792 Py_DECREF(co); 793 794 return m; 795} 796 797 798/* Forward */ 799static PyObject *load_module(char *, FILE *, char *, int); 800static struct filedescr *find_module(char *, PyObject *, 801 char *, size_t, FILE **); 802static struct _frozen *find_frozen(char *name); 803 804/* Load a package and return its module object WITH INCREMENTED 805 REFERENCE COUNT */ 806 807static PyObject * 808load_package(char *name, char *pathname) 809{ 810 PyObject *m, *d, *file, *path; 811 int err; 812 char buf[MAXPATHLEN+1]; 813 FILE *fp = NULL; 814 struct filedescr *fdp; 815 816 m = PyImport_AddModule(name); 817 if (m == NULL) 818 return NULL; 819 if (Py_VerboseFlag) 820 PySys_WriteStderr("import %s # directory %s\n", 821 name, pathname); 822 d = PyModule_GetDict(m); 823 file = PyString_FromString(pathname); 824 if (file == NULL) 825 return NULL; 826 path = Py_BuildValue("[O]", file); 827 if (path == NULL) { 828 Py_DECREF(file); 829 return NULL; 830 } 831 err = PyDict_SetItemString(d, "__file__", file); 832 if (err == 0) 833 err = PyDict_SetItemString(d, "__path__", path); 834 if (err != 0) { 835 m = NULL; 836 goto cleanup; 837 } 838 buf[0] = '\0'; 839 fdp = find_module("__init__", path, buf, sizeof(buf), &fp); 840 if (fdp == NULL) { 841 if (PyErr_ExceptionMatches(PyExc_ImportError)) { 842 PyErr_Clear(); 843 } 844 else 845 m = NULL; 846 goto cleanup; 847 } 848 m = load_module(name, fp, buf, fdp->type); 849 if (fp != NULL) 850 fclose(fp); 851 cleanup: 852 Py_XDECREF(path); 853 Py_XDECREF(file); 854 return m; 855} 856 857 858/* Helper to test for built-in module */ 859 860static int 861is_builtin(char *name) 862{ 863 int i; 864 for (i = 0; PyImport_Inittab[i].name != NULL; i++) { 865 if (strcmp(name, PyImport_Inittab[i].name) == 0) { 866 if (PyImport_Inittab[i].initfunc == NULL) 867 return -1; 868 else 869 return 1; 870 } 871 } 872 return 0; 873} 874 875 876/* Search the path (default sys.path) for a module. Return the 877 corresponding filedescr struct, and (via return arguments) the 878 pathname and an open file. Return NULL if the module is not found. */ 879 880#ifdef MS_COREDLL 881extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **, 882 char *, int); 883#endif 884 885static int case_ok(char *, int, int, char *); 886static int find_init_module(char *); /* Forward */ 887 888static struct filedescr * 889find_module(char *realname, PyObject *path, char *buf, size_t buflen, 890 FILE **p_fp) 891{ 892 int i, npath; 893 size_t len, namelen; 894 struct filedescr *fdp = NULL; 895 FILE *fp = NULL; 896#ifndef RISCOS 897 struct stat statbuf; 898#endif 899 static struct filedescr fd_frozen = {"", "", PY_FROZEN}; 900 static struct filedescr fd_builtin = {"", "", C_BUILTIN}; 901 static struct filedescr fd_package = {"", "", PKG_DIRECTORY}; 902 char name[MAXPATHLEN+1]; 903#if defined(PYOS_OS2) 904 size_t saved_len; 905 size_t saved_namelen; 906 char *saved_buf = NULL; 907#endif 908 909 if (strlen(realname) > MAXPATHLEN) { 910 PyErr_SetString(PyExc_OverflowError, 911 "module name is too long"); 912 return NULL; 913 } 914 strcpy(name, realname); 915 916 if (path != NULL && PyString_Check(path)) { 917 /* The only type of submodule allowed inside a "frozen" 918 package are other frozen modules or packages. */ 919 if (PyString_Size(path) + 1 + strlen(name) >= (size_t)buflen) { 920 PyErr_SetString(PyExc_ImportError, 921 "full frozen module name too long"); 922 return NULL; 923 } 924 strcpy(buf, PyString_AsString(path)); 925 strcat(buf, "."); 926 strcat(buf, name); 927 strcpy(name, buf); 928#ifdef macintosh 929 /* Freezing on the mac works different, and the modules are 930 ** actually on sys.path. So we don't take the quick exit but 931 ** continue with the normal flow. 932 */ 933 path = NULL; 934#else 935 if (find_frozen(name) != NULL) { 936 strcpy(buf, name); 937 return &fd_frozen; 938 } 939 PyErr_Format(PyExc_ImportError, 940 "No frozen submodule named %.200s", name); 941 return NULL; 942#endif 943 } 944 if (path == NULL) { 945 if (is_builtin(name)) { 946 strcpy(buf, name); 947 return &fd_builtin; 948 } 949 if ((find_frozen(name)) != NULL) { 950 strcpy(buf, name); 951 return &fd_frozen; 952 } 953 954#ifdef MS_COREDLL 955 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen); 956 if (fp != NULL) { 957 *p_fp = fp; 958 return fdp; 959 } 960#endif 961 path = PySys_GetObject("path"); 962 } 963 if (path == NULL || !PyList_Check(path)) { 964 PyErr_SetString(PyExc_ImportError, 965 "sys.path must be a list of directory names"); 966 return NULL; 967 } 968 npath = PyList_Size(path); 969 namelen = strlen(name); 970 for (i = 0; i < npath; i++) { 971 PyObject *v = PyList_GetItem(path, i); 972 if (!PyString_Check(v)) 973 continue; 974 len = PyString_Size(v); 975 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) 976 continue; /* Too long */ 977 strcpy(buf, PyString_AsString(v)); 978 if (strlen(buf) != len) 979 continue; /* v contains '\0' */ 980#ifdef macintosh 981 /* 982 ** Speedup: each sys.path item is interned, and 983 ** FindResourceModule remembers which items refer to 984 ** folders (so we don't have to bother trying to look 985 ** into them for resources). 986 */ 987 PyString_InternInPlace(&PyList_GET_ITEM(path, i)); 988 v = PyList_GET_ITEM(path, i); 989 if (PyMac_FindResourceModule((PyStringObject *)v, name, buf)) { 990 static struct filedescr resfiledescr = 991 {"", "", PY_RESOURCE}; 992 993 return &resfiledescr; 994 } 995 if (PyMac_FindCodeResourceModule((PyStringObject *)v, name, buf)) { 996 static struct filedescr resfiledescr = 997 {"", "", PY_CODERESOURCE}; 998 999 return &resfiledescr; 1000 } 1001#endif 1002 if (len > 0 && buf[len-1] != SEP 1003#ifdef ALTSEP 1004 && buf[len-1] != ALTSEP 1005#endif 1006 ) 1007 buf[len++] = SEP; 1008 strcpy(buf+len, name); 1009 len += namelen; 1010 1011 /* Check for package import (buf holds a directory name, 1012 and there's an __init__ module in that directory */ 1013#ifdef HAVE_STAT 1014 if (stat(buf, &statbuf) == 0 && /* it exists */ 1015 S_ISDIR(statbuf.st_mode) && /* it's a directory */ 1016 find_init_module(buf) && /* it has __init__.py */ 1017 case_ok(buf, len, namelen, name)) /* and case matches */ 1018 return &fd_package; 1019#else 1020 /* XXX How are you going to test for directories? */ 1021#ifdef RISCOS 1022 if (isdir(buf) && 1023 find_init_module(buf) && 1024 case_ok(buf, len, namelen, name)) 1025 return &fd_package; 1026#endif 1027#endif 1028#ifdef macintosh 1029 fdp = PyMac_FindModuleExtension(buf, &len, name); 1030 if (fdp) { 1031#else 1032#if defined(PYOS_OS2) 1033 /* take a snapshot of the module spec for restoration 1034 * after the 8 character DLL hackery 1035 */ 1036 saved_buf = strdup(buf); 1037 saved_len = len; 1038 saved_namelen = namelen; 1039#endif /* PYOS_OS2 */ 1040 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) { 1041#if defined(PYOS_OS2) 1042 /* OS/2 limits DLLs to 8 character names (w/o extension) 1043 * so if the name is longer than that and its a 1044 * dynamically loaded module we're going to try, 1045 * truncate the name before trying 1046 */ 1047 if (strlen(realname) > 8) { 1048 /* is this an attempt to load a C extension? */ 1049 const struct filedescr *scan = _PyImport_DynLoadFiletab; 1050 while (scan->suffix != NULL) { 1051 if (strcmp(scan->suffix, fdp->suffix) == 0) 1052 break; 1053 else 1054 scan++; 1055 } 1056 if (scan->suffix != NULL) { 1057 /* yes, so truncate the name */ 1058 namelen = 8; 1059 len -= strlen(realname) - namelen; 1060 buf[len] = '\0'; 1061 } 1062 } 1063#endif /* PYOS_OS2 */ 1064 strcpy(buf+len, fdp->suffix); 1065 if (Py_VerboseFlag > 1) 1066 PySys_WriteStderr("# trying %s\n", buf); 1067#endif /* !macintosh */ 1068 fp = fopen(buf, fdp->mode); 1069 if (fp != NULL) { 1070 if (case_ok(buf, len, namelen, name)) 1071 break; 1072 else { /* continue search */ 1073 fclose(fp); 1074 fp = NULL; 1075 } 1076 } 1077#if defined(PYOS_OS2) 1078 /* restore the saved snapshot */ 1079 strcpy(buf, saved_buf); 1080 len = saved_len; 1081 namelen = saved_namelen; 1082#endif 1083 } 1084#if defined(PYOS_OS2) 1085 /* don't need/want the module name snapshot anymore */ 1086 if (saved_buf) 1087 { 1088 free(saved_buf); 1089 saved_buf = NULL; 1090 } 1091#endif 1092 if (fp != NULL) 1093 break; 1094 } 1095 if (fp == NULL) { 1096 PyErr_Format(PyExc_ImportError, 1097 "No module named %.200s", name); 1098 return NULL; 1099 } 1100 *p_fp = fp; 1101 return fdp; 1102} 1103 1104/* case_ok(char* buf, int len, int namelen, char* name) 1105 * The arguments here are tricky, best shown by example: 1106 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0 1107 * ^ ^ ^ ^ 1108 * |--------------------- buf ---------------------| 1109 * |------------------- len ------------------| 1110 * |------ name -------| 1111 * |----- namelen -----| 1112 * buf is the full path, but len only counts up to (& exclusive of) the 1113 * extension. name is the module name, also exclusive of extension. 1114 * 1115 * We've already done a successful stat() or fopen() on buf, so know that 1116 * there's some match, possibly case-insensitive. 1117 * 1118 * case_ok() is to return 1 if there's a case-sensitive match for 1119 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK 1120 * exists. 1121 * 1122 * case_ok() is used to implement case-sensitive import semantics even 1123 * on platforms with case-insensitive filesystems. It's trivial to implement 1124 * for case-sensitive filesystems. It's pretty much a cross-platform 1125 * nightmare for systems with case-insensitive filesystems. 1126 */ 1127 1128/* First we may need a pile of platform-specific header files; the sequence 1129 * of #if's here should match the sequence in the body of case_ok(). 1130 */ 1131#if defined(MS_WIN32) || defined(__CYGWIN__) 1132#include <windows.h> 1133#ifdef __CYGWIN__ 1134#include <sys/cygwin.h> 1135#endif 1136 1137#elif defined(DJGPP) 1138#include <dir.h> 1139 1140#elif defined(macintosh) 1141#include <TextUtils.h> 1142#ifdef USE_GUSI1 1143#include "TFileSpec.h" /* for Path2FSSpec() */ 1144#endif 1145 1146#elif defined(__MACH__) && defined(__APPLE__) && defined(HAVE_DIRENT_H) 1147#include <sys/types.h> 1148#include <dirent.h> 1149 1150#elif defined(PYOS_OS2) 1151#define INCL_DOS 1152#define INCL_DOSERRORS 1153#define INCL_NOPMAPI 1154#include <os2.h> 1155 1156#elif defined(RISCOS) 1157#include "oslib/osfscontrol.h" 1158#endif 1159 1160static int 1161case_ok(char *buf, int len, int namelen, char *name) 1162{ 1163/* Pick a platform-specific implementation; the sequence of #if's here should 1164 * match the sequence just above. 1165 */ 1166 1167/* MS_WIN32 || __CYGWIN__ */ 1168#if defined(MS_WIN32) || defined(__CYGWIN__) 1169 WIN32_FIND_DATA data; 1170 HANDLE h; 1171#ifdef __CYGWIN__ 1172 char tempbuf[MAX_PATH]; 1173#endif 1174 1175 if (Py_GETENV("PYTHONCASEOK") != NULL) 1176 return 1; 1177 1178#ifdef __CYGWIN__ 1179 cygwin32_conv_to_win32_path(buf, tempbuf); 1180 h = FindFirstFile(tempbuf, &data); 1181#else 1182 h = FindFirstFile(buf, &data); 1183#endif 1184 if (h == INVALID_HANDLE_VALUE) { 1185 PyErr_Format(PyExc_NameError, 1186 "Can't find file for module %.100s\n(filename %.300s)", 1187 name, buf); 1188 return 0; 1189 } 1190 FindClose(h); 1191 return strncmp(data.cFileName, name, namelen) == 0; 1192 1193/* DJGPP */ 1194#elif defined(DJGPP) 1195 struct ffblk ffblk; 1196 int done; 1197 1198 if (Py_GETENV("PYTHONCASEOK") != NULL) 1199 return 1; 1200 1201 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC); 1202 if (done) { 1203 PyErr_Format(PyExc_NameError, 1204 "Can't find file for module %.100s\n(filename %.300s)", 1205 name, buf); 1206 return 0; 1207 } 1208 return strncmp(ffblk.ff_name, name, namelen) == 0; 1209 1210/* macintosh */ 1211#elif defined(macintosh) 1212 FSSpec fss; 1213 OSErr err; 1214 1215 if (Py_GETENV("PYTHONCASEOK") != NULL) 1216 return 1; 1217 1218#ifndef USE_GUSI1 1219 err = FSMakeFSSpec(0, 0, Pstring(buf), &fss); 1220#else 1221 /* GUSI's Path2FSSpec() resolves all possible aliases nicely on 1222 the way, which is fine for all directories, but here we need 1223 the original name of the alias file (say, Dlg.ppc.slb, not 1224 toolboxmodules.ppc.slb). */ 1225 char *colon; 1226 err = Path2FSSpec(buf, &fss); 1227 if (err == noErr) { 1228 colon = strrchr(buf, ':'); /* find filename */ 1229 if (colon != NULL) 1230 err = FSMakeFSSpec(fss.vRefNum, fss.parID, 1231 Pstring(colon+1), &fss); 1232 else 1233 err = FSMakeFSSpec(fss.vRefNum, fss.parID, 1234 fss.name, &fss); 1235 } 1236#endif 1237 if (err) { 1238 PyErr_Format(PyExc_NameError, 1239 "Can't find file for module %.100s\n(filename %.300s)", 1240 name, buf); 1241 return 0; 1242 } 1243 return fss.name[0] >= namelen && 1244 strncmp(name, (char *)fss.name+1, namelen) == 0; 1245 1246/* new-fangled macintosh (macosx) */ 1247#elif defined(__MACH__) && defined(__APPLE__) && defined(HAVE_DIRENT_H) 1248 DIR *dirp; 1249 struct dirent *dp; 1250 char dirname[MAXPATHLEN + 1]; 1251 const int dirlen = len - namelen - 1; /* don't want trailing SEP */ 1252 1253 if (Py_GETENV("PYTHONCASEOK") != NULL) 1254 return 1; 1255 1256 /* Copy the dir component into dirname; substitute "." if empty */ 1257 if (dirlen <= 0) { 1258 dirname[0] = '.'; 1259 dirname[1] = '\0'; 1260 } 1261 else { 1262 assert(dirlen <= MAXPATHLEN); 1263 memcpy(dirname, buf, dirlen); 1264 dirname[dirlen] = '\0'; 1265 } 1266 /* Open the directory and search the entries for an exact match. */ 1267 dirp = opendir(dirname); 1268 if (dirp) { 1269 char *nameWithExt = buf + len - namelen; 1270 while ((dp = readdir(dirp)) != NULL) { 1271 const int thislen = 1272#ifdef _DIRENT_HAVE_D_NAMELEN 1273 dp->d_namlen; 1274#else 1275 strlen(dp->d_name); 1276#endif 1277 if (thislen >= namelen && 1278 strcmp(dp->d_name, nameWithExt) == 0) { 1279 (void)closedir(dirp); 1280 return 1; /* Found */ 1281 } 1282 } 1283 (void)closedir(dirp); 1284 } 1285 return 0 ; /* Not found */ 1286 1287/* RISC OS */ 1288#elif defined(RISCOS) 1289 char canon[MAXPATHLEN+1]; /* buffer for the canonical form of the path */ 1290 char buf2[MAXPATHLEN+2]; 1291 char *nameWithExt = buf+len-namelen; 1292 int canonlen; 1293 os_error *e; 1294 1295 if (Py_GETENV("PYTHONCASEOK") != NULL) 1296 return 1; 1297 1298 /* workaround: 1299 append wildcard, otherwise case of filename wouldn't be touched */ 1300 strcpy(buf2, buf); 1301 strcat(buf2, "*"); 1302 1303 e = xosfscontrol_canonicalise_path(buf2,canon,0,0,MAXPATHLEN+1,&canonlen); 1304 canonlen = MAXPATHLEN+1-canonlen; 1305 if (e || canonlen<=0 || canonlen>(MAXPATHLEN+1) ) 1306 return 0; 1307 if (strcmp(nameWithExt, canon+canonlen-strlen(nameWithExt))==0) 1308 return 1; /* match */ 1309 1310 return 0; 1311 1312/* OS/2 */ 1313#elif defined(PYOS_OS2) 1314 HDIR hdir = 1; 1315 ULONG srchcnt = 1; 1316 FILEFINDBUF3 ffbuf; 1317 APIRET rc; 1318 1319 if (getenv("PYTHONCASEOK") != NULL) 1320 return 1; 1321 1322 rc = DosFindFirst(buf, 1323 &hdir, 1324 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY, 1325 &ffbuf, sizeof(ffbuf), 1326 &srchcnt, 1327 FIL_STANDARD); 1328 if (rc != NO_ERROR) 1329 return 0; 1330 return strncmp(ffbuf.achName, name, namelen) == 0; 1331 1332/* assuming it's a case-sensitive filesystem, so there's nothing to do! */ 1333#else 1334 return 1; 1335 1336#endif 1337} 1338 1339 1340#ifdef HAVE_STAT 1341/* Helper to look for __init__.py or __init__.py[co] in potential package */ 1342static int 1343find_init_module(char *buf) 1344{ 1345 const size_t save_len = strlen(buf); 1346 size_t i = save_len; 1347 char *pname; /* pointer to start of __init__ */ 1348 struct stat statbuf; 1349 1350/* For calling case_ok(buf, len, namelen, name): 1351 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0 1352 * ^ ^ ^ ^ 1353 * |--------------------- buf ---------------------| 1354 * |------------------- len ------------------| 1355 * |------ name -------| 1356 * |----- namelen -----| 1357 */ 1358 if (save_len + 13 >= MAXPATHLEN) 1359 return 0; 1360 buf[i++] = SEP; 1361 pname = buf + i; 1362 strcpy(pname, "__init__.py"); 1363 if (stat(buf, &statbuf) == 0) { 1364 if (case_ok(buf, 1365 save_len + 9, /* len("/__init__") */ 1366 8, /* len("__init__") */ 1367 pname)) { 1368 buf[save_len] = '\0'; 1369 return 1; 1370 } 1371 } 1372 i += strlen(pname); 1373 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c"); 1374 if (stat(buf, &statbuf) == 0) { 1375 if (case_ok(buf, 1376 save_len + 9, /* len("/__init__") */ 1377 8, /* len("__init__") */ 1378 pname)) { 1379 buf[save_len] = '\0'; 1380 return 1; 1381 } 1382 } 1383 buf[save_len] = '\0'; 1384 return 0; 1385} 1386 1387#else 1388 1389#ifdef RISCOS 1390static int 1391find_init_module(buf) 1392 char *buf; 1393{ 1394 int save_len = strlen(buf); 1395 int i = save_len; 1396 1397 if (save_len + 13 >= MAXPATHLEN) 1398 return 0; 1399 buf[i++] = SEP; 1400 strcpy(buf+i, "__init__/py"); 1401 if (isfile(buf)) { 1402 buf[save_len] = '\0'; 1403 return 1; 1404 } 1405 1406 if (Py_OptimizeFlag) 1407 strcpy(buf+i, "o"); 1408 else 1409 strcpy(buf+i, "c"); 1410 if (isfile(buf)) { 1411 buf[save_len] = '\0'; 1412 return 1; 1413 } 1414 buf[save_len] = '\0'; 1415 return 0; 1416} 1417#endif /*RISCOS*/ 1418 1419#endif /* HAVE_STAT */ 1420 1421 1422static int init_builtin(char *); /* Forward */ 1423 1424/* Load an external module using the default search path and return 1425 its module object WITH INCREMENTED REFERENCE COUNT */ 1426 1427static PyObject * 1428load_module(char *name, FILE *fp, char *buf, int type) 1429{ 1430 PyObject *modules; 1431 PyObject *m; 1432 int err; 1433 1434 /* First check that there's an open file (if we need one) */ 1435 switch (type) { 1436 case PY_SOURCE: 1437 case PY_COMPILED: 1438 if (fp == NULL) { 1439 PyErr_Format(PyExc_ValueError, 1440 "file object required for import (type code %d)", 1441 type); 1442 return NULL; 1443 } 1444 } 1445 1446 switch (type) { 1447 1448 case PY_SOURCE: 1449 m = load_source_module(name, buf, fp); 1450 break; 1451 1452 case PY_COMPILED: 1453 m = load_compiled_module(name, buf, fp); 1454 break; 1455 1456#ifdef HAVE_DYNAMIC_LOADING 1457 case C_EXTENSION: 1458 m = _PyImport_LoadDynamicModule(name, buf, fp); 1459 break; 1460#endif 1461 1462#ifdef macintosh 1463 case PY_RESOURCE: 1464 m = PyMac_LoadResourceModule(name, buf); 1465 break; 1466 case PY_CODERESOURCE: 1467 m = PyMac_LoadCodeResourceModule(name, buf); 1468 break; 1469#endif 1470 1471 case PKG_DIRECTORY: 1472 m = load_package(name, buf); 1473 break; 1474 1475 case C_BUILTIN: 1476 case PY_FROZEN: 1477 if (buf != NULL && buf[0] != '\0') 1478 name = buf; 1479 if (type == C_BUILTIN) 1480 err = init_builtin(name); 1481 else 1482 err = PyImport_ImportFrozenModule(name); 1483 if (err < 0) 1484 return NULL; 1485 if (err == 0) { 1486 PyErr_Format(PyExc_ImportError, 1487 "Purported %s module %.200s not found", 1488 type == C_BUILTIN ? 1489 "builtin" : "frozen", 1490 name); 1491 return NULL; 1492 } 1493 modules = PyImport_GetModuleDict(); 1494 m = PyDict_GetItemString(modules, name); 1495 if (m == NULL) { 1496 PyErr_Format( 1497 PyExc_ImportError, 1498 "%s module %.200s not properly initialized", 1499 type == C_BUILTIN ? 1500 "builtin" : "frozen", 1501 name); 1502 return NULL; 1503 } 1504 Py_INCREF(m); 1505 break; 1506 1507 default: 1508 PyErr_Format(PyExc_ImportError, 1509 "Don't know how to import %.200s (type code %d)", 1510 name, type); 1511 m = NULL; 1512 1513 } 1514 1515 return m; 1516} 1517 1518 1519/* Initialize a built-in module. 1520 Return 1 for succes, 0 if the module is not found, and -1 with 1521 an exception set if the initialization failed. */ 1522 1523static int 1524init_builtin(char *name) 1525{ 1526 struct _inittab *p; 1527 1528 if (_PyImport_FindExtension(name, name) != NULL) 1529 return 1; 1530 1531 for (p = PyImport_Inittab; p->name != NULL; p++) { 1532 if (strcmp(name, p->name) == 0) { 1533 if (p->initfunc == NULL) { 1534 PyErr_Format(PyExc_ImportError, 1535 "Cannot re-init internal module %.200s", 1536 name); 1537 return -1; 1538 } 1539 if (Py_VerboseFlag) 1540 PySys_WriteStderr("import %s # builtin\n", name); 1541 (*p->initfunc)(); 1542 if (PyErr_Occurred()) 1543 return -1; 1544 if (_PyImport_FixupExtension(name, name) == NULL) 1545 return -1; 1546 return 1; 1547 } 1548 } 1549 return 0; 1550} 1551 1552 1553/* Frozen modules */ 1554 1555static struct _frozen * 1556find_frozen(char *name) 1557{ 1558 struct _frozen *p; 1559 1560 for (p = PyImport_FrozenModules; ; p++) { 1561 if (p->name == NULL) 1562 return NULL; 1563 if (strcmp(p->name, name) == 0) 1564 break; 1565 } 1566 return p; 1567} 1568 1569static PyObject * 1570get_frozen_object(char *name) 1571{ 1572 struct _frozen *p = find_frozen(name); 1573 int size; 1574 1575 if (p == NULL) { 1576 PyErr_Format(PyExc_ImportError, 1577 "No such frozen object named %.200s", 1578 name); 1579 return NULL; 1580 } 1581 if (p->code == NULL) { 1582 PyErr_Format(PyExc_ImportError, 1583 "Excluded frozen object named %.200s", 1584 name); 1585 return NULL; 1586 } 1587 size = p->size; 1588 if (size < 0) 1589 size = -size; 1590 return PyMarshal_ReadObjectFromString((char *)p->code, size); 1591} 1592 1593/* Initialize a frozen module. 1594 Return 1 for succes, 0 if the module is not found, and -1 with 1595 an exception set if the initialization failed. 1596 This function is also used from frozenmain.c */ 1597 1598int 1599PyImport_ImportFrozenModule(char *name) 1600{ 1601 struct _frozen *p = find_frozen(name); 1602 PyObject *co; 1603 PyObject *m; 1604 int ispackage; 1605 int size; 1606 1607 if (p == NULL) 1608 return 0; 1609 if (p->code == NULL) { 1610 PyErr_Format(PyExc_ImportError, 1611 "Excluded frozen object named %.200s", 1612 name); 1613 return -1; 1614 } 1615 size = p->size; 1616 ispackage = (size < 0); 1617 if (ispackage) 1618 size = -size; 1619 if (Py_VerboseFlag) 1620 PySys_WriteStderr("import %s # frozen%s\n", 1621 name, ispackage ? " package" : ""); 1622 co = PyMarshal_ReadObjectFromString((char *)p->code, size); 1623 if (co == NULL) 1624 return -1; 1625 if (!PyCode_Check(co)) { 1626 Py_DECREF(co); 1627 PyErr_Format(PyExc_TypeError, 1628 "frozen object %.200s is not a code object", 1629 name); 1630 return -1; 1631 } 1632 if (ispackage) { 1633 /* Set __path__ to the package name */ 1634 PyObject *d, *s; 1635 int err; 1636 m = PyImport_AddModule(name); 1637 if (m == NULL) 1638 return -1; 1639 d = PyModule_GetDict(m); 1640 s = PyString_InternFromString(name); 1641 if (s == NULL) 1642 return -1; 1643 err = PyDict_SetItemString(d, "__path__", s); 1644 Py_DECREF(s); 1645 if (err != 0) 1646 return err; 1647 } 1648 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>"); 1649 Py_DECREF(co); 1650 if (m == NULL) 1651 return -1; 1652 Py_DECREF(m); 1653 return 1; 1654} 1655 1656 1657/* Import a module, either built-in, frozen, or external, and return 1658 its module object WITH INCREMENTED REFERENCE COUNT */ 1659 1660PyObject * 1661PyImport_ImportModule(char *name) 1662{ 1663 PyObject *pname; 1664 PyObject *result; 1665 1666 pname = PyString_FromString(name); 1667 result = PyImport_Import(pname); 1668 Py_DECREF(pname); 1669 return result; 1670} 1671 1672/* Forward declarations for helper routines */ 1673static PyObject *get_parent(PyObject *globals, char *buf, int *p_buflen); 1674static PyObject *load_next(PyObject *mod, PyObject *altmod, 1675 char **p_name, char *buf, int *p_buflen); 1676static int mark_miss(char *name); 1677static int ensure_fromlist(PyObject *mod, PyObject *fromlist, 1678 char *buf, int buflen, int recursive); 1679static PyObject * import_submodule(PyObject *mod, char *name, char *fullname); 1680 1681/* The Magnum Opus of dotted-name import :-) */ 1682 1683static PyObject * 1684import_module_ex(char *name, PyObject *globals, PyObject *locals, 1685 PyObject *fromlist) 1686{ 1687 char buf[MAXPATHLEN+1]; 1688 int buflen = 0; 1689 PyObject *parent, *head, *next, *tail; 1690 1691 parent = get_parent(globals, buf, &buflen); 1692 if (parent == NULL) 1693 return NULL; 1694 1695 head = load_next(parent, Py_None, &name, buf, &buflen); 1696 if (head == NULL) 1697 return NULL; 1698 1699 tail = head; 1700 Py_INCREF(tail); 1701 while (name) { 1702 next = load_next(tail, tail, &name, buf, &buflen); 1703 Py_DECREF(tail); 1704 if (next == NULL) { 1705 Py_DECREF(head); 1706 return NULL; 1707 } 1708 tail = next; 1709 } 1710 1711 if (fromlist != NULL) { 1712 if (fromlist == Py_None || !PyObject_IsTrue(fromlist)) 1713 fromlist = NULL; 1714 } 1715 1716 if (fromlist == NULL) { 1717 Py_DECREF(tail); 1718 return head; 1719 } 1720 1721 Py_DECREF(head); 1722 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) { 1723 Py_DECREF(tail); 1724 return NULL; 1725 } 1726 1727 return tail; 1728} 1729 1730PyObject * 1731PyImport_ImportModuleEx(char *name, PyObject *globals, PyObject *locals, 1732 PyObject *fromlist) 1733{ 1734 PyObject *result; 1735 lock_import(); 1736 result = import_module_ex(name, globals, locals, fromlist); 1737 unlock_import(); 1738 return result; 1739} 1740 1741static PyObject * 1742get_parent(PyObject *globals, char *buf, int *p_buflen) 1743{ 1744 static PyObject *namestr = NULL; 1745 static PyObject *pathstr = NULL; 1746 PyObject *modname, *modpath, *modules, *parent; 1747 1748 if (globals == NULL || !PyDict_Check(globals)) 1749 return Py_None; 1750 1751 if (namestr == NULL) { 1752 namestr = PyString_InternFromString("__name__"); 1753 if (namestr == NULL) 1754 return NULL; 1755 } 1756 if (pathstr == NULL) { 1757 pathstr = PyString_InternFromString("__path__"); 1758 if (pathstr == NULL) 1759 return NULL; 1760 } 1761 1762 *buf = '\0'; 1763 *p_buflen = 0; 1764 modname = PyDict_GetItem(globals, namestr); 1765 if (modname == NULL || !PyString_Check(modname)) 1766 return Py_None; 1767 1768 modpath = PyDict_GetItem(globals, pathstr); 1769 if (modpath != NULL) { 1770 int len = PyString_GET_SIZE(modname); 1771 if (len > MAXPATHLEN) { 1772 PyErr_SetString(PyExc_ValueError, 1773 "Module name too long"); 1774 return NULL; 1775 } 1776 strcpy(buf, PyString_AS_STRING(modname)); 1777 *p_buflen = len; 1778 } 1779 else { 1780 char *start = PyString_AS_STRING(modname); 1781 char *lastdot = strrchr(start, '.'); 1782 size_t len; 1783 if (lastdot == NULL) 1784 return Py_None; 1785 len = lastdot - start; 1786 if (len >= MAXPATHLEN) { 1787 PyErr_SetString(PyExc_ValueError, 1788 "Module name too long"); 1789 return NULL; 1790 } 1791 strncpy(buf, start, len); 1792 buf[len] = '\0'; 1793 *p_buflen = len; 1794 } 1795 1796 modules = PyImport_GetModuleDict(); 1797 parent = PyDict_GetItemString(modules, buf); 1798 if (parent == NULL) 1799 parent = Py_None; 1800 return parent; 1801 /* We expect, but can't guarantee, if parent != None, that: 1802 - parent.__name__ == buf 1803 - parent.__dict__ is globals 1804 If this is violated... Who cares? */ 1805} 1806 1807/* altmod is either None or same as mod */ 1808static PyObject * 1809load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf, 1810 int *p_buflen) 1811{ 1812 char *name = *p_name; 1813 char *dot = strchr(name, '.'); 1814 size_t len; 1815 char *p; 1816 PyObject *result; 1817 1818 if (dot == NULL) { 1819 *p_name = NULL; 1820 len = strlen(name); 1821 } 1822 else { 1823 *p_name = dot+1; 1824 len = dot-name; 1825 } 1826 if (len == 0) { 1827 PyErr_SetString(PyExc_ValueError, 1828 "Empty module name"); 1829 return NULL; 1830 } 1831 1832 p = buf + *p_buflen; 1833 if (p != buf) 1834 *p++ = '.'; 1835 if (p+len-buf >= MAXPATHLEN) { 1836 PyErr_SetString(PyExc_ValueError, 1837 "Module name too long"); 1838 return NULL; 1839 } 1840 strncpy(p, name, len); 1841 p[len] = '\0'; 1842 *p_buflen = p+len-buf; 1843 1844 result = import_submodule(mod, p, buf); 1845 if (result == Py_None && altmod != mod) { 1846 Py_DECREF(result); 1847 /* Here, altmod must be None and mod must not be None */ 1848 result = import_submodule(altmod, p, p); 1849 if (result != NULL && result != Py_None) { 1850 if (mark_miss(buf) != 0) { 1851 Py_DECREF(result); 1852 return NULL; 1853 } 1854 strncpy(buf, name, len); 1855 buf[len] = '\0'; 1856 *p_buflen = len; 1857 } 1858 } 1859 if (result == NULL) 1860 return NULL; 1861 1862 if (result == Py_None) { 1863 Py_DECREF(result); 1864 PyErr_Format(PyExc_ImportError, 1865 "No module named %.200s", name); 1866 return NULL; 1867 } 1868 1869 return result; 1870} 1871 1872static int 1873mark_miss(char *name) 1874{ 1875 PyObject *modules = PyImport_GetModuleDict(); 1876 return PyDict_SetItemString(modules, name, Py_None); 1877} 1878 1879static int 1880ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, int buflen, 1881 int recursive) 1882{ 1883 int i; 1884 1885 if (!PyObject_HasAttrString(mod, "__path__")) 1886 return 1; 1887 1888 for (i = 0; ; i++) { 1889 PyObject *item = PySequence_GetItem(fromlist, i); 1890 int hasit; 1891 if (item == NULL) { 1892 if (PyErr_ExceptionMatches(PyExc_IndexError)) { 1893 PyErr_Clear(); 1894 return 1; 1895 } 1896 return 0; 1897 } 1898 if (!PyString_Check(item)) { 1899 PyErr_SetString(PyExc_TypeError, 1900 "Item in ``from list'' not a string"); 1901 Py_DECREF(item); 1902 return 0; 1903 } 1904 if (PyString_AS_STRING(item)[0] == '*') { 1905 PyObject *all; 1906 Py_DECREF(item); 1907 /* See if the package defines __all__ */ 1908 if (recursive) 1909 continue; /* Avoid endless recursion */ 1910 all = PyObject_GetAttrString(mod, "__all__"); 1911 if (all == NULL) 1912 PyErr_Clear(); 1913 else { 1914 if (!ensure_fromlist(mod, all, buf, buflen, 1)) 1915 return 0; 1916 Py_DECREF(all); 1917 } 1918 continue; 1919 } 1920 hasit = PyObject_HasAttr(mod, item); 1921 if (!hasit) { 1922 char *subname = PyString_AS_STRING(item); 1923 PyObject *submod; 1924 char *p; 1925 if (buflen + strlen(subname) >= MAXPATHLEN) { 1926 PyErr_SetString(PyExc_ValueError, 1927 "Module name too long"); 1928 Py_DECREF(item); 1929 return 0; 1930 } 1931 p = buf + buflen; 1932 *p++ = '.'; 1933 strcpy(p, subname); 1934 submod = import_submodule(mod, subname, buf); 1935 Py_XDECREF(submod); 1936 if (submod == NULL) { 1937 Py_DECREF(item); 1938 return 0; 1939 } 1940 } 1941 Py_DECREF(item); 1942 } 1943 1944 /* NOTREACHED */ 1945} 1946 1947static PyObject * 1948import_submodule(PyObject *mod, char *subname, char *fullname) 1949{ 1950 PyObject *modules = PyImport_GetModuleDict(); 1951 PyObject *m, *res = NULL; 1952 1953 /* Require: 1954 if mod == None: subname == fullname 1955 else: mod.__name__ + "." + subname == fullname 1956 */ 1957 1958 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) { 1959 Py_INCREF(m); 1960 } 1961 else { 1962 PyObject *path; 1963 char buf[MAXPATHLEN+1]; 1964 struct filedescr *fdp; 1965 FILE *fp = NULL; 1966 1967 if (mod == Py_None) 1968 path = NULL; 1969 else { 1970 path = PyObject_GetAttrString(mod, "__path__"); 1971 if (path == NULL) { 1972 PyErr_Clear(); 1973 Py_INCREF(Py_None); 1974 return Py_None; 1975 } 1976 } 1977 1978 buf[0] = '\0'; 1979 fdp = find_module(subname, path, buf, MAXPATHLEN+1, &fp); 1980 Py_XDECREF(path); 1981 if (fdp == NULL) { 1982 if (!PyErr_ExceptionMatches(PyExc_ImportError)) 1983 return NULL; 1984 PyErr_Clear(); 1985 Py_INCREF(Py_None); 1986 return Py_None; 1987 } 1988 m = load_module(fullname, fp, buf, fdp->type); 1989 if (fp) 1990 fclose(fp); 1991 if (mod != Py_None) { 1992 /* Irrespective of the success of this load, make a 1993 reference to it in the parent package module. 1994 A copy gets saved in the modules dictionary 1995 under the full name, so get a reference from 1996 there, if need be. (The exception is when 1997 the load failed with a SyntaxError -- then 1998 there's no trace in sys.modules. In that case, 1999 of course, do nothing extra.) */ 2000 res = m; 2001 if (res == NULL) 2002 res = PyDict_GetItemString(modules, fullname); 2003 if (res != NULL && 2004 PyObject_SetAttrString(mod, subname, res) < 0) { 2005 Py_XDECREF(m); 2006 m = NULL; 2007 } 2008 } 2009 } 2010 2011 return m; 2012} 2013 2014 2015/* Re-import a module of any kind and return its module object, WITH 2016 INCREMENTED REFERENCE COUNT */ 2017 2018PyObject * 2019PyImport_ReloadModule(PyObject *m) 2020{ 2021 PyObject *modules = PyImport_GetModuleDict(); 2022 PyObject *path = NULL; 2023 char *name, *subname; 2024 char buf[MAXPATHLEN+1]; 2025 struct filedescr *fdp; 2026 FILE *fp = NULL; 2027 2028 if (m == NULL || !PyModule_Check(m)) { 2029 PyErr_SetString(PyExc_TypeError, 2030 "reload() argument must be module"); 2031 return NULL; 2032 } 2033 name = PyModule_GetName(m); 2034 if (name == NULL) 2035 return NULL; 2036 if (m != PyDict_GetItemString(modules, name)) { 2037 PyErr_Format(PyExc_ImportError, 2038 "reload(): module %.200s not in sys.modules", 2039 name); 2040 return NULL; 2041 } 2042 subname = strrchr(name, '.'); 2043 if (subname == NULL) 2044 subname = name; 2045 else { 2046 PyObject *parentname, *parent; 2047 parentname = PyString_FromStringAndSize(name, (subname-name)); 2048 if (parentname == NULL) 2049 return NULL; 2050 parent = PyDict_GetItem(modules, parentname); 2051 Py_DECREF(parentname); 2052 if (parent == NULL) { 2053 PyErr_Format(PyExc_ImportError, 2054 "reload(): parent %.200s not in sys.modules", 2055 name); 2056 return NULL; 2057 } 2058 subname++; 2059 path = PyObject_GetAttrString(parent, "__path__"); 2060 if (path == NULL) 2061 PyErr_Clear(); 2062 } 2063 buf[0] = '\0'; 2064 fdp = find_module(subname, path, buf, MAXPATHLEN+1, &fp); 2065 Py_XDECREF(path); 2066 if (fdp == NULL) 2067 return NULL; 2068 m = load_module(name, fp, buf, fdp->type); 2069 if (fp) 2070 fclose(fp); 2071 return m; 2072} 2073 2074 2075/* Higher-level import emulator which emulates the "import" statement 2076 more accurately -- it invokes the __import__() function from the 2077 builtins of the current globals. This means that the import is 2078 done using whatever import hooks are installed in the current 2079 environment, e.g. by "rexec". 2080 A dummy list ["__doc__"] is passed as the 4th argument so that 2081 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache")) 2082 will return <module "gencache"> instead of <module "win32com">. */ 2083 2084PyObject * 2085PyImport_Import(PyObject *module_name) 2086{ 2087 static PyObject *silly_list = NULL; 2088 static PyObject *builtins_str = NULL; 2089 static PyObject *import_str = NULL; 2090 PyObject *globals = NULL; 2091 PyObject *import = NULL; 2092 PyObject *builtins = NULL; 2093 PyObject *r = NULL; 2094 2095 /* Initialize constant string objects */ 2096 if (silly_list == NULL) { 2097 import_str = PyString_InternFromString("__import__"); 2098 if (import_str == NULL) 2099 return NULL; 2100 builtins_str = PyString_InternFromString("__builtins__"); 2101 if (builtins_str == NULL) 2102 return NULL; 2103 silly_list = Py_BuildValue("[s]", "__doc__"); 2104 if (silly_list == NULL) 2105 return NULL; 2106 } 2107 2108 /* Get the builtins from current globals */ 2109 globals = PyEval_GetGlobals(); 2110 if (globals != NULL) { 2111 Py_INCREF(globals); 2112 builtins = PyObject_GetItem(globals, builtins_str); 2113 if (builtins == NULL) 2114 goto err; 2115 } 2116 else { 2117 /* No globals -- use standard builtins, and fake globals */ 2118 PyErr_Clear(); 2119 2120 builtins = PyImport_ImportModuleEx("__builtin__", 2121 NULL, NULL, NULL); 2122 if (builtins == NULL) 2123 return NULL; 2124 globals = Py_BuildValue("{OO}", builtins_str, builtins); 2125 if (globals == NULL) 2126 goto err; 2127 } 2128 2129 /* Get the __import__ function from the builtins */ 2130 if (PyDict_Check(builtins)) { 2131 import = PyObject_GetItem(builtins, import_str); 2132 if (import == NULL) 2133 PyErr_SetObject(PyExc_KeyError, import_str); 2134 } 2135 else 2136 import = PyObject_GetAttr(builtins, import_str); 2137 if (import == NULL) 2138 goto err; 2139 2140 /* Call the _import__ function with the proper argument list */ 2141 r = PyObject_CallFunction(import, "OOOO", 2142 module_name, globals, globals, silly_list); 2143 2144 err: 2145 Py_XDECREF(globals); 2146 Py_XDECREF(builtins); 2147 Py_XDECREF(import); 2148 2149 return r; 2150} 2151 2152 2153/* Module 'imp' provides Python access to the primitives used for 2154 importing modules. 2155*/ 2156 2157static PyObject * 2158imp_get_magic(PyObject *self, PyObject *args) 2159{ 2160 char buf[4]; 2161 2162 if (!PyArg_ParseTuple(args, ":get_magic")) 2163 return NULL; 2164 buf[0] = (char) ((pyc_magic >> 0) & 0xff); 2165 buf[1] = (char) ((pyc_magic >> 8) & 0xff); 2166 buf[2] = (char) ((pyc_magic >> 16) & 0xff); 2167 buf[3] = (char) ((pyc_magic >> 24) & 0xff); 2168 2169 return PyString_FromStringAndSize(buf, 4); 2170} 2171 2172static PyObject * 2173imp_get_suffixes(PyObject *self, PyObject *args) 2174{ 2175 PyObject *list; 2176 struct filedescr *fdp; 2177 2178 if (!PyArg_ParseTuple(args, ":get_suffixes")) 2179 return NULL; 2180 list = PyList_New(0); 2181 if (list == NULL) 2182 return NULL; 2183 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) { 2184 PyObject *item = Py_BuildValue("ssi", 2185 fdp->suffix, fdp->mode, fdp->type); 2186 if (item == NULL) { 2187 Py_DECREF(list); 2188 return NULL; 2189 } 2190 if (PyList_Append(list, item) < 0) { 2191 Py_DECREF(list); 2192 Py_DECREF(item); 2193 return NULL; 2194 } 2195 Py_DECREF(item); 2196 } 2197 return list; 2198} 2199 2200static PyObject * 2201call_find_module(char *name, PyObject *path) 2202{ 2203 extern int fclose(FILE *); 2204 PyObject *fob, *ret; 2205 struct filedescr *fdp; 2206 char pathname[MAXPATHLEN+1]; 2207 FILE *fp = NULL; 2208 2209 pathname[0] = '\0'; 2210 if (path == Py_None) 2211 path = NULL; 2212 fdp = find_module(name, path, pathname, MAXPATHLEN+1, &fp); 2213 if (fdp == NULL) 2214 return NULL; 2215 if (fp != NULL) { 2216 fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose); 2217 if (fob == NULL) { 2218 fclose(fp); 2219 return NULL; 2220 } 2221 } 2222 else { 2223 fob = Py_None; 2224 Py_INCREF(fob); 2225 } 2226 ret = Py_BuildValue("Os(ssi)", 2227 fob, pathname, fdp->suffix, fdp->mode, fdp->type); 2228 Py_DECREF(fob); 2229 return ret; 2230} 2231 2232static PyObject * 2233imp_find_module(PyObject *self, PyObject *args) 2234{ 2235 char *name; 2236 PyObject *path = NULL; 2237 if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path)) 2238 return NULL; 2239 return call_find_module(name, path); 2240} 2241 2242static PyObject * 2243imp_init_builtin(PyObject *self, PyObject *args) 2244{ 2245 char *name; 2246 int ret; 2247 PyObject *m; 2248 if (!PyArg_ParseTuple(args, "s:init_builtin", &name)) 2249 return NULL; 2250 ret = init_builtin(name); 2251 if (ret < 0) 2252 return NULL; 2253 if (ret == 0) { 2254 Py_INCREF(Py_None); 2255 return Py_None; 2256 } 2257 m = PyImport_AddModule(name); 2258 Py_XINCREF(m); 2259 return m; 2260} 2261 2262static PyObject * 2263imp_init_frozen(PyObject *self, PyObject *args) 2264{ 2265 char *name; 2266 int ret; 2267 PyObject *m; 2268 if (!PyArg_ParseTuple(args, "s:init_frozen", &name)) 2269 return NULL; 2270 ret = PyImport_ImportFrozenModule(name); 2271 if (ret < 0) 2272 return NULL; 2273 if (ret == 0) { 2274 Py_INCREF(Py_None); 2275 return Py_None; 2276 } 2277 m = PyImport_AddModule(name); 2278 Py_XINCREF(m); 2279 return m; 2280} 2281 2282static PyObject * 2283imp_get_frozen_object(PyObject *self, PyObject *args) 2284{ 2285 char *name; 2286 2287 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name)) 2288 return NULL; 2289 return get_frozen_object(name); 2290} 2291 2292static PyObject * 2293imp_is_builtin(PyObject *self, PyObject *args) 2294{ 2295 char *name; 2296 if (!PyArg_ParseTuple(args, "s:is_builtin", &name)) 2297 return NULL; 2298 return PyInt_FromLong(is_builtin(name)); 2299} 2300 2301static PyObject * 2302imp_is_frozen(PyObject *self, PyObject *args) 2303{ 2304 char *name; 2305 struct _frozen *p; 2306 if (!PyArg_ParseTuple(args, "s:is_frozen", &name)) 2307 return NULL; 2308 p = find_frozen(name); 2309 return PyInt_FromLong((long) (p == NULL ? 0 : p->size)); 2310} 2311 2312static FILE * 2313get_file(char *pathname, PyObject *fob, char *mode) 2314{ 2315 FILE *fp; 2316 if (fob == NULL) { 2317 fp = fopen(pathname, mode); 2318 if (fp == NULL) 2319 PyErr_SetFromErrno(PyExc_IOError); 2320 } 2321 else { 2322 fp = PyFile_AsFile(fob); 2323 if (fp == NULL) 2324 PyErr_SetString(PyExc_ValueError, 2325 "bad/closed file object"); 2326 } 2327 return fp; 2328} 2329 2330static PyObject * 2331imp_load_compiled(PyObject *self, PyObject *args) 2332{ 2333 char *name; 2334 char *pathname; 2335 PyObject *fob = NULL; 2336 PyObject *m; 2337 FILE *fp; 2338 if (!PyArg_ParseTuple(args, "ss|O!:load_compiled", &name, &pathname, 2339 &PyFile_Type, &fob)) 2340 return NULL; 2341 fp = get_file(pathname, fob, "rb"); 2342 if (fp == NULL) 2343 return NULL; 2344 m = load_compiled_module(name, pathname, fp); 2345 if (fob == NULL) 2346 fclose(fp); 2347 return m; 2348} 2349 2350#ifdef HAVE_DYNAMIC_LOADING 2351 2352static PyObject * 2353imp_load_dynamic(PyObject *self, PyObject *args) 2354{ 2355 char *name; 2356 char *pathname; 2357 PyObject *fob = NULL; 2358 PyObject *m; 2359 FILE *fp = NULL; 2360 if (!PyArg_ParseTuple(args, "ss|O!:load_dynamic", &name, &pathname, 2361 &PyFile_Type, &fob)) 2362 return NULL; 2363 if (fob) { 2364 fp = get_file(pathname, fob, "r"); 2365 if (fp == NULL) 2366 return NULL; 2367 } 2368 m = _PyImport_LoadDynamicModule(name, pathname, fp); 2369 return m; 2370} 2371 2372#endif /* HAVE_DYNAMIC_LOADING */ 2373 2374static PyObject * 2375imp_load_source(PyObject *self, PyObject *args) 2376{ 2377 char *name; 2378 char *pathname; 2379 PyObject *fob = NULL; 2380 PyObject *m; 2381 FILE *fp; 2382 if (!PyArg_ParseTuple(args, "ss|O!:load_source", &name, &pathname, 2383 &PyFile_Type, &fob)) 2384 return NULL; 2385 fp = get_file(pathname, fob, "r"); 2386 if (fp == NULL) 2387 return NULL; 2388 m = load_source_module(name, pathname, fp); 2389 if (fob == NULL) 2390 fclose(fp); 2391 return m; 2392} 2393 2394#ifdef macintosh 2395static PyObject * 2396imp_load_resource(PyObject *self, PyObject *args) 2397{ 2398 char *name; 2399 char *pathname; 2400 PyObject *m; 2401 2402 if (!PyArg_ParseTuple(args, "ss:load_resource", &name, &pathname)) 2403 return NULL; 2404 m = PyMac_LoadResourceModule(name, pathname); 2405 return m; 2406} 2407#endif /* macintosh */ 2408 2409static PyObject * 2410imp_load_module(PyObject *self, PyObject *args) 2411{ 2412 char *name; 2413 PyObject *fob; 2414 char *pathname; 2415 char *suffix; /* Unused */ 2416 char *mode; 2417 int type; 2418 FILE *fp; 2419 2420 if (!PyArg_ParseTuple(args, "sOs(ssi):load_module", 2421 &name, &fob, &pathname, 2422 &suffix, &mode, &type)) 2423 return NULL; 2424 if (*mode && (*mode != 'r' || strchr(mode, '+') != NULL)) { 2425 PyErr_Format(PyExc_ValueError, 2426 "invalid file open mode %.200s", mode); 2427 return NULL; 2428 } 2429 if (fob == Py_None) 2430 fp = NULL; 2431 else { 2432 if (!PyFile_Check(fob)) { 2433 PyErr_SetString(PyExc_ValueError, 2434 "load_module arg#2 should be a file or None"); 2435 return NULL; 2436 } 2437 fp = get_file(pathname, fob, mode); 2438 if (fp == NULL) 2439 return NULL; 2440 } 2441 return load_module(name, fp, pathname, type); 2442} 2443 2444static PyObject * 2445imp_load_package(PyObject *self, PyObject *args) 2446{ 2447 char *name; 2448 char *pathname; 2449 if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname)) 2450 return NULL; 2451 return load_package(name, pathname); 2452} 2453 2454static PyObject * 2455imp_new_module(PyObject *self, PyObject *args) 2456{ 2457 char *name; 2458 if (!PyArg_ParseTuple(args, "s:new_module", &name)) 2459 return NULL; 2460 return PyModule_New(name); 2461} 2462 2463/* Doc strings */ 2464 2465static char doc_imp[] = "\ 2466This module provides the components needed to build your own\n\ 2467__import__ function. Undocumented functions are obsolete.\n\ 2468"; 2469 2470static char doc_find_module[] = "\ 2471find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\ 2472Search for a module. If path is omitted or None, search for a\n\ 2473built-in, frozen or special module and continue search in sys.path.\n\ 2474The module name cannot contain '.'; to search for a submodule of a\n\ 2475package, pass the submodule name and the package's __path__.\ 2476"; 2477 2478static char doc_load_module[] = "\ 2479load_module(name, file, filename, (suffix, mode, type)) -> module\n\ 2480Load a module, given information returned by find_module().\n\ 2481The module name must include the full package name, if any.\ 2482"; 2483 2484static char doc_get_magic[] = "\ 2485get_magic() -> string\n\ 2486Return the magic number for .pyc or .pyo files.\ 2487"; 2488 2489static char doc_get_suffixes[] = "\ 2490get_suffixes() -> [(suffix, mode, type), ...]\n\ 2491Return a list of (suffix, mode, type) tuples describing the files\n\ 2492that find_module() looks for.\ 2493"; 2494 2495static char doc_new_module[] = "\ 2496new_module(name) -> module\n\ 2497Create a new module. Do not enter it in sys.modules.\n\ 2498The module name must include the full package name, if any.\ 2499"; 2500 2501static char doc_lock_held[] = "\ 2502lock_held() -> 0 or 1\n\ 2503Return 1 if the import lock is currently held.\n\ 2504On platforms without threads, return 0.\ 2505"; 2506 2507static PyMethodDef imp_methods[] = { 2508 {"find_module", imp_find_module, METH_VARARGS, doc_find_module}, 2509 {"get_magic", imp_get_magic, METH_VARARGS, doc_get_magic}, 2510 {"get_suffixes", imp_get_suffixes, METH_VARARGS, doc_get_suffixes}, 2511 {"load_module", imp_load_module, METH_VARARGS, doc_load_module}, 2512 {"new_module", imp_new_module, METH_VARARGS, doc_new_module}, 2513 {"lock_held", imp_lock_held, METH_VARARGS, doc_lock_held}, 2514 /* The rest are obsolete */ 2515 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS}, 2516 {"init_builtin", imp_init_builtin, METH_VARARGS}, 2517 {"init_frozen", imp_init_frozen, METH_VARARGS}, 2518 {"is_builtin", imp_is_builtin, METH_VARARGS}, 2519 {"is_frozen", imp_is_frozen, METH_VARARGS}, 2520 {"load_compiled", imp_load_compiled, METH_VARARGS}, 2521#ifdef HAVE_DYNAMIC_LOADING 2522 {"load_dynamic", imp_load_dynamic, METH_VARARGS}, 2523#endif 2524 {"load_package", imp_load_package, METH_VARARGS}, 2525#ifdef macintosh 2526 {"load_resource", imp_load_resource, METH_VARARGS}, 2527#endif 2528 {"load_source", imp_load_source, METH_VARARGS}, 2529 {NULL, NULL} /* sentinel */ 2530}; 2531 2532static int 2533setint(PyObject *d, char *name, int value) 2534{ 2535 PyObject *v; 2536 int err; 2537 2538 v = PyInt_FromLong((long)value); 2539 err = PyDict_SetItemString(d, name, v); 2540 Py_XDECREF(v); 2541 return err; 2542} 2543 2544void 2545initimp(void) 2546{ 2547 PyObject *m, *d; 2548 2549 m = Py_InitModule4("imp", imp_methods, doc_imp, 2550 NULL, PYTHON_API_VERSION); 2551 d = PyModule_GetDict(m); 2552 2553 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure; 2554 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure; 2555 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure; 2556 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure; 2557 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure; 2558 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure; 2559 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure; 2560 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure; 2561 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure; 2562 2563 failure: 2564 ; 2565} 2566 2567 2568/* API for embedding applications that want to add their own entries 2569 to the table of built-in modules. This should normally be called 2570 *before* Py_Initialize(). When the table resize fails, -1 is 2571 returned and the existing table is unchanged. 2572 2573 After a similar function by Just van Rossum. */ 2574 2575int 2576PyImport_ExtendInittab(struct _inittab *newtab) 2577{ 2578 static struct _inittab *our_copy = NULL; 2579 struct _inittab *p; 2580 int i, n; 2581 2582 /* Count the number of entries in both tables */ 2583 for (n = 0; newtab[n].name != NULL; n++) 2584 ; 2585 if (n == 0) 2586 return 0; /* Nothing to do */ 2587 for (i = 0; PyImport_Inittab[i].name != NULL; i++) 2588 ; 2589 2590 /* Allocate new memory for the combined table */ 2591 p = our_copy; 2592 PyMem_RESIZE(p, struct _inittab, i+n+1); 2593 if (p == NULL) 2594 return -1; 2595 2596 /* Copy the tables into the new memory */ 2597 if (our_copy != PyImport_Inittab) 2598 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab)); 2599 PyImport_Inittab = our_copy = p; 2600 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab)); 2601 2602 return 0; 2603} 2604 2605/* Shorthand to add a single entry given a name and a function */ 2606 2607int 2608PyImport_AppendInittab(char *name, void (*initfunc)(void)) 2609{ 2610 struct _inittab newtab[2]; 2611 2612 memset(newtab, '\0', sizeof newtab); 2613 2614 newtab[0].name = name; 2615 newtab[0].initfunc = initfunc; 2616 2617 return PyImport_ExtendInittab(newtab); 2618} 2619