import.c revision 741689d5f3570a2e56bf166e6dfc6417749b0790
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 52extern long PyOS_GetLastModificationTime(); /* In getmtime.c */ 53 54/* Magic word to reject .pyc files generated by other Python versions */ 55/* Change for each incompatible change */ 56/* The value of CR and LF is incorporated so if you ever read or write 57 a .pyc file in text mode the magic number will be wrong; also, the 58 Apple MPW compiler swaps their values, botching string constants */ 59/* XXX Perhaps the magic number should be frozen and a version field 60 added to the .pyc file header? */ 61/* New way to come up with the magic number: (YEAR-1995), MONTH, DAY */ 62#define MAGIC (20121 | ((long)'\r'<<16) | ((long)'\n'<<24)) 63 64/* See _PyImport_FixupExtension() below */ 65static PyObject *extensions = NULL; 66 67 68/* Initialize things */ 69 70void 71_PyImport_Init() 72{ 73 if (Py_OptimizeFlag) { 74 /* Replace ".pyc" with ".pyo" in import_filetab */ 75 struct filedescr *p; 76 for (p = _PyImport_Filetab; p->suffix != NULL; p++) { 77 if (strcmp(p->suffix, ".pyc") == 0) 78 p->suffix = ".pyo"; 79 } 80 } 81} 82 83void 84_PyImport_Fini() 85{ 86 Py_XDECREF(extensions); 87 extensions = NULL; 88} 89 90 91/* Helper for sys */ 92 93PyObject * 94PyImport_GetModuleDict() 95{ 96 PyInterpreterState *interp = PyThreadState_Get()->interp; 97 if (interp->modules == NULL) 98 Py_FatalError("PyImport_GetModuleDict: no module dictionary!"); 99 return interp->modules; 100} 101 102 103/* Helper for PyImport_Cleanup */ 104 105static void 106clear_carefully(d) 107 PyObject *d; 108{ 109 /* To make the execution order of destructors for global 110 objects a bit more predictable, we first zap all objects 111 whose name starts with a single underscore, before we clear 112 the entire dictionary. We zap them by replacing them with 113 None, rather than deleting them from the dictionary, to 114 avoid rehashing the dictionary (to some extent). */ 115 116 int pos; 117 PyObject *key, *value; 118 119 pos = 0; 120 while (PyDict_Next(d, &pos, &key, &value)) { 121 if (value != Py_None && PyString_Check(key)) { 122 char *s = PyString_AsString(key); 123 if (s[0] == '_' && s[1] != '_') 124 PyDict_SetItem(d, key, Py_None); 125 } 126 } 127 128 PyDict_Clear(d); 129} 130 131/* Un-initialize things, as good as we can */ 132 133void 134PyImport_Cleanup() 135{ 136 PyInterpreterState *interp = PyThreadState_Get()->interp; 137 PyObject *tmp = interp->modules; 138 if (tmp != NULL) { 139 int pos; 140 PyObject *key, *value; 141 interp->modules = NULL; 142 pos = 0; 143 while (PyDict_Next(tmp, &pos, &key, &value)) { 144 if (PyModule_Check(value)) { 145 PyObject *d = PyModule_GetDict(value); 146 clear_carefully(d); 147 } 148 } 149 PyDict_Clear(tmp); 150 Py_DECREF(tmp); 151 } 152} 153 154 155/* Helper for pythonrun.c -- return magic number */ 156 157long 158PyImport_GetMagicNumber() 159{ 160 return MAGIC; 161} 162 163 164/* Magic for extension modules (built-in as well as dynamically 165 loaded). To prevent initializing an extension module more than 166 once, we keep a static dictionary 'extensions' keyed by module name 167 (for built-in modules) or by filename (for dynamically loaded 168 modules), containing these modules. A copy od the module's 169 dictionary is stored by calling _PyImport_FixupExtension() 170 immediately after the module initialization function succeeds. A 171 copy can be retrieved from there by calling 172 _PyImport_FindExtension(). */ 173 174PyObject * 175_PyImport_FixupExtension(name, filename) 176 char *name; 177 char *filename; 178{ 179 PyObject *modules, *mod, *dict, *copy; 180 if (extensions == NULL) { 181 extensions = PyDict_New(); 182 if (extensions == NULL) 183 return NULL; 184 } 185 modules = PyImport_GetModuleDict(); 186 mod = PyDict_GetItemString(modules, name); 187 if (mod == NULL || !PyModule_Check(mod)) { 188 PyErr_SetString(PyExc_SystemError, 189 "_PyImport_FixupExtension: module not loaded"); 190 return NULL; 191 } 192 dict = PyModule_GetDict(mod); 193 if (dict == NULL) 194 return NULL; 195 copy = PyObject_CallMethod(dict, "copy", ""); 196 if (copy == NULL) 197 return NULL; 198 PyDict_SetItemString(extensions, filename, copy); 199 Py_DECREF(copy); 200 return copy; 201} 202 203PyObject * 204_PyImport_FindExtension(name, filename) 205 char *name; 206 char *filename; 207{ 208 PyObject *dict, *mod, *mdict, *result; 209 if (extensions == NULL) 210 return NULL; 211 dict = PyDict_GetItemString(extensions, filename); 212 if (dict == NULL) 213 return NULL; 214 mod = PyImport_AddModule(name); 215 if (mod == NULL) 216 return NULL; 217 mdict = PyModule_GetDict(mod); 218 if (mdict == NULL) 219 return NULL; 220 result = PyObject_CallMethod(mdict, "update", "O", dict); 221 if (result == NULL) 222 return NULL; 223 Py_DECREF(result); 224 if (Py_VerboseFlag) 225 fprintf(stderr, "import %s # previously loaded (%s)\n", 226 name, filename); 227 return mod; 228} 229 230 231/* Get the module object corresponding to a module name. 232 First check the modules dictionary if there's one there, 233 if not, create a new one and insert in in the modules dictionary. 234 Because the former action is most common, THIS DOES NOT RETURN A 235 'NEW' REFERENCE! */ 236 237PyObject * 238PyImport_AddModule(name) 239 char *name; 240{ 241 PyObject *modules = PyImport_GetModuleDict(); 242 PyObject *m; 243 244 if ((m = PyDict_GetItemString(modules, name)) != NULL && 245 PyModule_Check(m)) 246 return m; 247 m = PyModule_New(name); 248 if (m == NULL) 249 return NULL; 250 if (PyDict_SetItemString(modules, name, m) != 0) { 251 Py_DECREF(m); 252 return NULL; 253 } 254 Py_DECREF(m); /* Yes, it still exists, in modules! */ 255 256 return m; 257} 258 259 260/* Execute a code object in a module and return the module object 261 WITH INCREMENTED REFERENCE COUNT */ 262 263PyObject * 264PyImport_ExecCodeModule(name, co) 265 char *name; 266 PyObject *co; 267{ 268 PyObject *modules = PyImport_GetModuleDict(); 269 PyObject *m, *d, *v; 270 271 m = PyImport_AddModule(name); 272 if (m == NULL) 273 return NULL; 274 d = PyModule_GetDict(m); 275 if (PyDict_GetItemString(d, "__builtins__") == NULL) { 276 if (PyDict_SetItemString(d, "__builtins__", 277 PyEval_GetBuiltins()) != 0) 278 return NULL; 279 } 280 /* Remember the filename as the __file__ attribute */ 281 if (PyDict_SetItemString(d, "__file__", 282 ((PyCodeObject *)co)->co_filename) != 0) 283 PyErr_Clear(); /* Not important enough to report */ 284 v = PyEval_EvalCode((PyCodeObject *)co, d, d); /* XXX owner? */ 285 if (v == NULL) 286 return NULL; 287 Py_DECREF(v); 288 289 if ((m = PyDict_GetItemString(modules, name)) == NULL) { 290 PyErr_SetString(PyExc_SystemError, 291 "loaded module not found in sys.modules"); 292 return NULL; 293 } 294 295 Py_INCREF(m); 296 297 return m; 298} 299 300 301/* Given a pathname for a Python source file, fill a buffer with the 302 pathname for the corresponding compiled file. Return the pathname 303 for the compiled file, or NULL if there's no space in the buffer. 304 Doesn't set an exception. */ 305 306static char * 307make_compiled_pathname(pathname, buf, buflen) 308 char *pathname; 309 char *buf; 310 int buflen; 311{ 312 int len; 313 314 len = strlen(pathname); 315 if (len+2 > buflen) 316 return NULL; 317 strcpy(buf, pathname); 318 strcpy(buf+len, Py_OptimizeFlag ? "o" : "c"); 319 320 return buf; 321} 322 323 324/* Given a pathname for a Python source file, its time of last 325 modification, and a pathname for a compiled file, check whether the 326 compiled file represents the same version of the source. If so, 327 return a FILE pointer for the compiled file, positioned just after 328 the header; if not, return NULL. 329 Doesn't set an exception. */ 330 331static FILE * 332check_compiled_module(pathname, mtime, cpathname) 333 char *pathname; 334 long mtime; 335 char *cpathname; 336{ 337 FILE *fp; 338 long magic; 339 long pyc_mtime; 340 341 fp = fopen(cpathname, "rb"); 342 if (fp == NULL) 343 return NULL; 344 magic = PyMarshal_ReadLongFromFile(fp); 345 if (magic != MAGIC) { 346 if (Py_VerboseFlag) 347 fprintf(stderr, "# %s has bad magic\n", cpathname); 348 fclose(fp); 349 return NULL; 350 } 351 pyc_mtime = PyMarshal_ReadLongFromFile(fp); 352 if (pyc_mtime != mtime) { 353 if (Py_VerboseFlag) 354 fprintf(stderr, "# %s has bad mtime\n", cpathname); 355 fclose(fp); 356 return NULL; 357 } 358 if (Py_VerboseFlag) 359 fprintf(stderr, "# %s matches %s\n", cpathname, pathname); 360 return fp; 361} 362 363 364/* Read a code object from a file and check it for validity */ 365 366static PyCodeObject * 367read_compiled_module(fp) 368 FILE *fp; 369{ 370 PyObject *co; 371 372 co = PyMarshal_ReadObjectFromFile(fp); 373 /* Ugly: rd_object() may return NULL with or without error */ 374 if (co == NULL || !PyCode_Check(co)) { 375 if (!PyErr_Occurred()) 376 PyErr_SetString(PyExc_ImportError, 377 "Non-code object in .pyc file"); 378 Py_XDECREF(co); 379 return NULL; 380 } 381 return (PyCodeObject *)co; 382} 383 384 385/* Load a module from a compiled file, execute it, and return its 386 module object WITH INCREMENTED REFERENCE COUNT */ 387 388static PyObject * 389load_compiled_module(name, cpathname, fp) 390 char *name; 391 char *cpathname; 392 FILE *fp; 393{ 394 long magic; 395 PyCodeObject *co; 396 PyObject *m; 397 398 magic = PyMarshal_ReadLongFromFile(fp); 399 if (magic != MAGIC) { 400 PyErr_SetString(PyExc_ImportError, 401 "Bad magic number in .pyc file"); 402 return NULL; 403 } 404 (void) PyMarshal_ReadLongFromFile(fp); 405 co = read_compiled_module(fp); 406 if (co == NULL) 407 return NULL; 408 if (Py_VerboseFlag) 409 fprintf(stderr, "import %s # precompiled from %s\n", 410 name, cpathname); 411 m = PyImport_ExecCodeModule(name, (PyObject *)co); 412 Py_DECREF(co); 413 414 return m; 415} 416 417/* Parse a source file and return the corresponding code object */ 418 419static PyCodeObject * 420parse_source_module(pathname, fp) 421 char *pathname; 422 FILE *fp; 423{ 424 PyCodeObject *co; 425 node *n; 426 427 n = PyParser_SimpleParseFile(fp, pathname, Py_file_input); 428 if (n == NULL) 429 return NULL; 430 co = PyNode_Compile(n, pathname); 431 PyNode_Free(n); 432 433 return co; 434} 435 436 437/* Write a compiled module to a file, placing the time of last 438 modification of its source into the header. 439 Errors are ignored, if a write error occurs an attempt is made to 440 remove the file. */ 441 442static void 443write_compiled_module(co, cpathname, mtime) 444 PyCodeObject *co; 445 char *cpathname; 446 long mtime; 447{ 448 FILE *fp; 449 450 fp = fopen(cpathname, "wb"); 451 if (fp == NULL) { 452 if (Py_VerboseFlag) 453 fprintf(stderr, 454 "# can't create %s\n", cpathname); 455 return; 456 } 457 PyMarshal_WriteLongToFile(MAGIC, fp); 458 /* First write a 0 for mtime */ 459 PyMarshal_WriteLongToFile(0L, fp); 460 PyMarshal_WriteObjectToFile((PyObject *)co, fp); 461 if (ferror(fp)) { 462 if (Py_VerboseFlag) 463 fprintf(stderr, "# can't write %s\n", cpathname); 464 /* Don't keep partial file */ 465 fclose(fp); 466 (void) unlink(cpathname); 467 return; 468 } 469 /* Now write the true mtime */ 470 fseek(fp, 4L, 0); 471 PyMarshal_WriteLongToFile(mtime, fp); 472 fflush(fp); 473 fclose(fp); 474 if (Py_VerboseFlag) 475 fprintf(stderr, "# wrote %s\n", cpathname); 476#ifdef macintosh 477 setfiletype(cpathname, 'Pyth', 'PYC '); 478#endif 479} 480 481 482/* Load a source module from a given file and return its module 483 object WITH INCREMENTED REFERENCE COUNT. If there's a matching 484 byte-compiled file, use that instead. */ 485 486static PyObject * 487load_source_module(name, pathname, fp) 488 char *name; 489 char *pathname; 490 FILE *fp; 491{ 492 long mtime; 493 FILE *fpc; 494 char buf[MAXPATHLEN+1]; 495 char *cpathname; 496 PyCodeObject *co; 497 PyObject *m; 498 499 mtime = PyOS_GetLastModificationTime(pathname); 500 cpathname = make_compiled_pathname(pathname, buf, MAXPATHLEN+1); 501 if (cpathname != NULL && 502 (fpc = check_compiled_module(pathname, mtime, cpathname))) { 503 co = read_compiled_module(fpc); 504 fclose(fpc); 505 if (co == NULL) 506 return NULL; 507 if (Py_VerboseFlag) 508 fprintf(stderr, "import %s # precompiled from %s\n", 509 name, cpathname); 510 } 511 else { 512 co = parse_source_module(pathname, fp); 513 if (co == NULL) 514 return NULL; 515 if (Py_VerboseFlag) 516 fprintf(stderr, "import %s # from %s\n", 517 name, pathname); 518 write_compiled_module(co, cpathname, mtime); 519 } 520 m = PyImport_ExecCodeModule(name, (PyObject *)co); 521 Py_DECREF(co); 522 523 return m; 524} 525 526 527/* Search the path (default sys.path) for a module. Return the 528 corresponding filedescr struct, and (via return arguments) the 529 pathname and an open file. Return NULL if the module is not found. */ 530 531static struct filedescr * 532find_module(name, path, buf, buflen, p_fp) 533 char *name; 534 PyObject *path; 535 /* Output parameters: */ 536 char *buf; 537 int buflen; 538 FILE **p_fp; 539{ 540 int i, npath, len, namelen; 541 struct filedescr *fdp = NULL; 542 FILE *fp = NULL; 543 544#ifdef MS_COREDLL 545 extern FILE *PyWin_FindRegisteredModule(); 546 if ((fp=PyWin_FindRegisteredModule(name, &fdp, buf, buflen))!=NULL) { 547 *p_fp = fp; 548 return fdp; 549 } 550#endif 551 552 553 if (path == NULL) 554 path = PySys_GetObject("path"); 555 if (path == NULL || !PyList_Check(path)) { 556 PyErr_SetString(PyExc_ImportError, 557 "sys.path must be a list of directory names"); 558 return NULL; 559 } 560 npath = PyList_Size(path); 561 namelen = strlen(name); 562 for (i = 0; i < npath; i++) { 563 PyObject *v = PyList_GetItem(path, i); 564 if (!PyString_Check(v)) 565 continue; 566 len = PyString_Size(v); 567 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) 568 continue; /* Too long */ 569 strcpy(buf, PyString_AsString(v)); 570 if ((int)strlen(buf) != len) 571 continue; /* v contains '\0' */ 572#ifdef macintosh 573#ifdef INTERN_STRINGS 574 /* 575 ** Speedup: each sys.path item is interned, and 576 ** FindResourceModule remembers which items refer to 577 ** folders (so we don't have to bother trying to look 578 ** into them for resources). 579 */ 580 PyString_InternInPlace(&PyList_GET_ITEM(path, i)); 581 v = PyList_GET_ITEM(path, i); 582#endif 583 if ( PyMac_FindResourceModule((PyStringObject *)v, name, buf) ) { 584 static struct filedescr resfiledescr = 585 {"", "", PY_RESOURCE}; 586 587 return &resfiledescr; 588 } 589#endif 590 if (len > 0 && buf[len-1] != SEP) 591 buf[len++] = SEP; 592#ifdef macintosh 593 fdp = PyMac_FindModuleExtension(buf, &len, name); 594 if ( fdp ) 595 fp = fopen(buf, fdp->mode); 596#else 597#ifdef IMPORT_8x3_NAMES 598 /* see if we are searching in directory dos_8x3 */ 599 if (len > 7 && !strncmp(buf + len - 8, "dos_8x3", 7)){ 600 int j; 601 char ch; /* limit name to 8 lower-case characters */ 602 for (j = 0; (ch = name[j]) && j < 8; j++) 603 if (isupper(ch)) 604 buf[len++] = tolower(ch); 605 else 606 buf[len++] = ch; 607 } 608 else /* Not in dos_8x3, use the full name */ 609#endif 610 { 611 strcpy(buf+len, name); 612 len += namelen; 613 } 614 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) { 615 strcpy(buf+len, fdp->suffix); 616 if (Py_VerboseFlag > 1) 617 fprintf(stderr, "# trying %s\n", buf); 618 fp = fopen(buf, fdp->mode); 619 if (fp != NULL) 620 break; 621 } 622#endif /* !macintosh */ 623 if (fp != NULL) 624 break; 625 } 626 if (fp == NULL) { 627 char buf[256]; 628 sprintf(buf, "No module named %.200s", name); 629 PyErr_SetString(PyExc_ImportError, buf); 630 return NULL; 631 } 632 633 *p_fp = fp; 634 return fdp; 635} 636 637 638/* Load an external module using the default search path and return 639 its module object WITH INCREMENTED REFERENCE COUNT */ 640 641static PyObject * 642load_module(name) 643 char *name; 644{ 645 char buf[MAXPATHLEN+1]; 646 struct filedescr *fdp; 647 FILE *fp = NULL; 648 PyObject *m; 649 650 fdp = find_module(name, (PyObject *)NULL, buf, MAXPATHLEN+1, &fp); 651 if (fdp == NULL) 652 return NULL; 653 654 switch (fdp->type) { 655 656 case PY_SOURCE: 657 m = load_source_module(name, buf, fp); 658 break; 659 660 case PY_COMPILED: 661 m = load_compiled_module(name, buf, fp); 662 break; 663 664 case C_EXTENSION: 665 m = _PyImport_LoadDynamicModule(name, buf, fp); 666 break; 667 668#ifdef macintosh 669 case PY_RESOURCE: 670 m = PyMac_LoadResourceModule(name, buf); 671 break; 672#endif 673 674 default: 675 PyErr_SetString(PyExc_SystemError, 676 "find_module returned unexpected result"); 677 m = NULL; 678 679 } 680 if ( fp ) 681 fclose(fp); 682 683 return m; 684} 685 686 687/* Initialize a built-in module. 688 Return 1 for succes, 0 if the module is not found, and -1 with 689 an exception set if the initialization failed. */ 690 691static int 692init_builtin(name) 693 char *name; 694{ 695 PyInterpreterState *interp = PyThreadState_Get()->interp; 696 struct _inittab *p; 697 PyObject *mod; 698 699 if ((mod = _PyImport_FindExtension(name, name)) != NULL) 700 return 1; 701 702 for (p = _PyImport_Inittab; p->name != NULL; p++) { 703 if (strcmp(name, p->name) == 0) { 704 if (p->initfunc == NULL) { 705 PyErr_SetString(PyExc_ImportError, 706 "Cannot re-init internal module"); 707 return -1; 708 } 709 if (Py_VerboseFlag) 710 fprintf(stderr, "import %s # builtin\n", name); 711 (*p->initfunc)(); 712 if (PyErr_Occurred()) 713 return -1; 714 if (_PyImport_FixupExtension(name, name) == NULL) 715 return -1; 716 return 1; 717 } 718 } 719 return 0; 720} 721 722 723/* Frozen modules */ 724 725static struct _frozen * 726find_frozen(name) 727 char *name; 728{ 729 struct _frozen *p; 730 731 for (p = PyImport_FrozenModules; ; p++) { 732 if (p->name == NULL) 733 return NULL; 734 if (strcmp(p->name, name) == 0) 735 break; 736 } 737 return p; 738} 739 740static PyObject * 741get_frozen_object(name) 742 char *name; 743{ 744 struct _frozen *p = find_frozen(name); 745 746 if (p == NULL) { 747 PyErr_SetString(PyExc_ImportError, "No such frozen object"); 748 return NULL; 749 } 750 return PyMarshal_ReadObjectFromString((char *)p->code, p->size); 751} 752 753/* Initialize a frozen module. 754 Return 1 for succes, 0 if the module is not found, and -1 with 755 an exception set if the initialization failed. 756 This function is also used from frozenmain.c */ 757 758int 759PyImport_ImportFrozenModule(name) 760 char *name; 761{ 762 struct _frozen *p = find_frozen(name); 763 PyObject *co; 764 PyObject *m; 765 766 if (p == NULL) 767 return 0; 768 if (Py_VerboseFlag) 769 fprintf(stderr, "import %s # frozen\n", name); 770 co = PyMarshal_ReadObjectFromString((char *)p->code, p->size); 771 if (co == NULL) 772 return -1; 773 if (!PyCode_Check(co)) { 774 Py_DECREF(co); 775 PyErr_SetString(PyExc_TypeError, 776 "frozen object is not a code object"); 777 return -1; 778 } 779 m = PyImport_ExecCodeModule(name, co); 780 Py_DECREF(co); 781 if (m == NULL) 782 return -1; 783 Py_DECREF(m); 784 return 1; 785} 786 787 788/* Import a module, either built-in, frozen, or external, and return 789 its module object WITH INCREMENTED REFERENCE COUNT */ 790 791PyObject * 792PyImport_ImportModule(name) 793 char *name; 794{ 795 PyObject *modules = PyImport_GetModuleDict(); 796 PyObject *m; 797 798 if ((m = PyDict_GetItemString(modules, name)) != NULL) { 799 Py_INCREF(m); 800 } 801 else { 802 int i; 803 if ((i = init_builtin(name)) || 804 (i = PyImport_ImportFrozenModule(name))) { 805 if (i < 0) 806 return NULL; 807 if ((m = PyDict_GetItemString(modules, 808 name)) == NULL) { 809 if (PyErr_Occurred() == NULL) 810 PyErr_SetString(PyExc_SystemError, 811 "built-in module not initialized properly"); 812 } 813 else 814 Py_INCREF(m); 815 } 816 else 817 m = load_module(name); 818 } 819 820 return m; 821} 822 823 824/* Re-import a module of any kind and return its module object, WITH 825 INCREMENTED REFERENCE COUNT */ 826 827PyObject * 828PyImport_ReloadModule(m) 829 PyObject *m; 830{ 831 PyObject *modules = PyImport_GetModuleDict(); 832 char *name; 833 int i; 834 835 if (m == NULL || !PyModule_Check(m)) { 836 PyErr_SetString(PyExc_TypeError, 837 "reload() argument must be module"); 838 return NULL; 839 } 840 name = PyModule_GetName(m); 841 if (name == NULL) 842 return NULL; 843 if (m != PyDict_GetItemString(modules, name)) { 844 PyErr_SetString(PyExc_ImportError, 845 "reload() module not in sys.modules"); 846 return NULL; 847 } 848 /* Check for built-in and frozen modules */ 849 if ((i = init_builtin(name)) || 850 (i = PyImport_ImportFrozenModule(name))) { 851 if (i < 0) 852 return NULL; 853 Py_INCREF(m); 854 } 855 else 856 m = load_module(name); 857 return m; 858} 859 860 861/* Module 'imp' provides Python access to the primitives used for 862 importing modules. 863*/ 864 865static PyObject * 866imp_get_magic(self, args) 867 PyObject *self; 868 PyObject *args; 869{ 870 char buf[4]; 871 872 if (!PyArg_ParseTuple(args, "")) 873 return NULL; 874 buf[0] = (char) ((MAGIC >> 0) & 0xff); 875 buf[1] = (char) ((MAGIC >> 8) & 0xff); 876 buf[2] = (char) ((MAGIC >> 16) & 0xff); 877 buf[3] = (char) ((MAGIC >> 24) & 0xff); 878 879 return PyString_FromStringAndSize(buf, 4); 880} 881 882static PyObject * 883imp_get_suffixes(self, args) 884 PyObject *self; 885 PyObject *args; 886{ 887 PyObject *list; 888 struct filedescr *fdp; 889 890 if (!PyArg_ParseTuple(args, "")) 891 return NULL; 892 list = PyList_New(0); 893 if (list == NULL) 894 return NULL; 895 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) { 896 PyObject *item = Py_BuildValue("ssi", 897 fdp->suffix, fdp->mode, fdp->type); 898 if (item == NULL) { 899 Py_DECREF(list); 900 return NULL; 901 } 902 if (PyList_Append(list, item) < 0) { 903 Py_DECREF(list); 904 Py_DECREF(item); 905 return NULL; 906 } 907 Py_DECREF(item); 908 } 909 return list; 910} 911 912static PyObject * 913imp_find_module(self, args) 914 PyObject *self; 915 PyObject *args; 916{ 917 extern int fclose Py_PROTO((FILE *)); 918 char *name; 919 PyObject *path = NULL; 920 PyObject *fob, *ret; 921 struct filedescr *fdp; 922 char pathname[MAXPATHLEN+1]; 923 FILE *fp; 924 if (!PyArg_ParseTuple(args, "s|O!", &name, &PyList_Type, &path)) 925 return NULL; 926 fdp = find_module(name, path, pathname, MAXPATHLEN+1, &fp); 927 if (fdp == NULL) 928 return NULL; 929 fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose); 930 if (fob == NULL) { 931 fclose(fp); 932 return NULL; 933 } 934 ret = Py_BuildValue("Os(ssi)", 935 fob, pathname, fdp->suffix, fdp->mode, fdp->type); 936 Py_DECREF(fob); 937 return ret; 938} 939 940static PyObject * 941imp_init_builtin(self, args) 942 PyObject *self; 943 PyObject *args; 944{ 945 char *name; 946 int ret; 947 PyObject *m; 948 if (!PyArg_ParseTuple(args, "s", &name)) 949 return NULL; 950 ret = init_builtin(name); 951 if (ret < 0) 952 return NULL; 953 if (ret == 0) { 954 Py_INCREF(Py_None); 955 return Py_None; 956 } 957 m = PyImport_AddModule(name); 958 Py_XINCREF(m); 959 return m; 960} 961 962static PyObject * 963imp_init_frozen(self, args) 964 PyObject *self; 965 PyObject *args; 966{ 967 char *name; 968 int ret; 969 PyObject *m; 970 if (!PyArg_ParseTuple(args, "s", &name)) 971 return NULL; 972 ret = PyImport_ImportFrozenModule(name); 973 if (ret < 0) 974 return NULL; 975 if (ret == 0) { 976 Py_INCREF(Py_None); 977 return Py_None; 978 } 979 m = PyImport_AddModule(name); 980 Py_XINCREF(m); 981 return m; 982} 983 984static PyObject * 985imp_get_frozen_object(self, args) 986 PyObject *self; 987 PyObject *args; 988{ 989 char *name; 990 991 if (!PyArg_ParseTuple(args, "s", &name)) 992 return NULL; 993 return get_frozen_object(name); 994} 995 996static PyObject * 997imp_is_builtin(self, args) 998 PyObject *self; 999 PyObject *args; 1000{ 1001 int i; 1002 char *name; 1003 if (!PyArg_ParseTuple(args, "s", &name)) 1004 return NULL; 1005 for (i = 0; _PyImport_Inittab[i].name != NULL; i++) { 1006 if (strcmp(name, _PyImport_Inittab[i].name) == 0) { 1007 if (_PyImport_Inittab[i].initfunc == NULL) 1008 return PyInt_FromLong(-1); 1009 else 1010 return PyInt_FromLong(1); 1011 } 1012 } 1013 return PyInt_FromLong(0); 1014} 1015 1016static PyObject * 1017imp_is_frozen(self, args) 1018 PyObject *self; 1019 PyObject *args; 1020{ 1021 struct _frozen *p; 1022 char *name; 1023 if (!PyArg_ParseTuple(args, "s", &name)) 1024 return NULL; 1025 for (p = PyImport_FrozenModules; ; p++) { 1026 if (p->name == NULL) 1027 break; 1028 if (strcmp(p->name, name) == 0) 1029 return PyInt_FromLong(1); 1030 } 1031 return PyInt_FromLong(0); 1032} 1033 1034static FILE * 1035get_file(pathname, fob, mode) 1036 char *pathname; 1037 PyObject *fob; 1038 char *mode; 1039{ 1040 FILE *fp; 1041 if (fob == NULL) { 1042 fp = fopen(pathname, mode); 1043 if (fp == NULL) 1044 PyErr_SetFromErrno(PyExc_IOError); 1045 } 1046 else { 1047 fp = PyFile_AsFile(fob); 1048 if (fp == NULL) 1049 PyErr_SetString(PyExc_ValueError, 1050 "bad/closed file object"); 1051 } 1052 return fp; 1053} 1054 1055static PyObject * 1056imp_load_compiled(self, args) 1057 PyObject *self; 1058 PyObject *args; 1059{ 1060 char *name; 1061 char *pathname; 1062 PyObject *fob = NULL; 1063 PyObject *m; 1064 FILE *fp; 1065 if (!PyArg_ParseTuple(args, "ssO!", &name, &pathname, 1066 &PyFile_Type, &fob)) 1067 return NULL; 1068 fp = get_file(pathname, fob, "rb"); 1069 if (fp == NULL) 1070 return NULL; 1071 m = load_compiled_module(name, pathname, fp); 1072 return m; 1073} 1074 1075static PyObject * 1076imp_load_dynamic(self, args) 1077 PyObject *self; 1078 PyObject *args; 1079{ 1080 char *name; 1081 char *pathname; 1082 PyObject *fob = NULL; 1083 PyObject *m; 1084 FILE *fp = NULL; 1085 if (!PyArg_ParseTuple(args, "ss|O!", &name, &pathname, 1086 &PyFile_Type, &fob)) 1087 return NULL; 1088 if (fob) 1089 fp = get_file(pathname, fob, "r"); 1090 m = _PyImport_LoadDynamicModule(name, pathname, fp); 1091 return m; 1092} 1093 1094static PyObject * 1095imp_load_source(self, args) 1096 PyObject *self; 1097 PyObject *args; 1098{ 1099 char *name; 1100 char *pathname; 1101 PyObject *fob = NULL; 1102 PyObject *m; 1103 FILE *fp; 1104 if (!PyArg_ParseTuple(args, "ssO!", &name, &pathname, 1105 &PyFile_Type, &fob)) 1106 return NULL; 1107 fp = get_file(pathname, fob, "r"); 1108 if (fp == NULL) 1109 return NULL; 1110 m = load_source_module(name, pathname, fp); 1111 return m; 1112} 1113 1114#ifdef macintosh 1115static PyObject * 1116imp_load_resource(self, args) 1117 PyObject *self; 1118 PyObject *args; 1119{ 1120 char *name; 1121 char *pathname; 1122 PyObject *m; 1123 1124 if (!PyArg_ParseTuple(args, "ss", &name, &pathname)) 1125 return NULL; 1126 m = PyMac_LoadResourceModule(name, pathname); 1127 return m; 1128} 1129#endif /* macintosh */ 1130 1131static PyObject * 1132imp_new_module(self, args) 1133 PyObject *self; 1134 PyObject *args; 1135{ 1136 char *name; 1137 if (!PyArg_ParseTuple(args, "s", &name)) 1138 return NULL; 1139 return PyModule_New(name); 1140} 1141 1142static PyMethodDef imp_methods[] = { 1143 {"get_frozen_object", imp_get_frozen_object, 1}, 1144 {"get_magic", imp_get_magic, 1}, 1145 {"get_suffixes", imp_get_suffixes, 1}, 1146 {"find_module", imp_find_module, 1}, 1147 {"init_builtin", imp_init_builtin, 1}, 1148 {"init_frozen", imp_init_frozen, 1}, 1149 {"is_builtin", imp_is_builtin, 1}, 1150 {"is_frozen", imp_is_frozen, 1}, 1151 {"load_compiled", imp_load_compiled, 1}, 1152 {"load_dynamic", imp_load_dynamic, 1}, 1153 {"load_source", imp_load_source, 1}, 1154 {"new_module", imp_new_module, 1}, 1155#ifdef macintosh 1156 {"load_resource", imp_load_resource, 1}, 1157#endif 1158 {NULL, NULL} /* sentinel */ 1159}; 1160 1161void 1162initimp() 1163{ 1164 PyObject *m, *d, *v; 1165 1166 m = Py_InitModule("imp", imp_methods); 1167 d = PyModule_GetDict(m); 1168 1169 v = PyInt_FromLong(SEARCH_ERROR); 1170 PyDict_SetItemString(d, "SEARCH_ERROR", v); 1171 Py_XDECREF(v); 1172 1173 v = PyInt_FromLong(PY_SOURCE); 1174 PyDict_SetItemString(d, "PY_SOURCE", v); 1175 Py_XDECREF(v); 1176 1177 v = PyInt_FromLong(PY_COMPILED); 1178 PyDict_SetItemString(d, "PY_COMPILED", v); 1179 Py_XDECREF(v); 1180 1181 v = PyInt_FromLong(C_EXTENSION); 1182 PyDict_SetItemString(d, "C_EXTENSION", v); 1183 Py_XDECREF(v); 1184 1185#ifdef macintosh 1186 v = PyInt_FromLong(PY_RESOURCE); 1187 PyDict_SetItemString(d, "PY_RESOURCE", v); 1188 Py_XDECREF(v); 1189#endif 1190 1191 1192 if (PyErr_Occurred()) 1193 Py_FatalError("imp module initialization failed"); 1194} 1195