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