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