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