import.c revision e8c27bb3eabe0550f4ddaf652bd8ebda23876d4e
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#include <sys/types.h> 59#include <sys/stat.h> 60 61#if defined(PYCC_VACPP) 62/* VisualAge C/C++ Failed to Define MountType Field in sys/stat.h */ 63#define S_IFMT (S_IFDIR|S_IFCHR|S_IFREG) 64#endif 65 66#ifndef S_ISDIR 67#define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR) 68#endif 69 70#endif 71 72 73extern long PyOS_GetLastModificationTime(); /* In getmtime.c */ 74 75/* Magic word to reject .pyc files generated by other Python versions */ 76/* Change for each incompatible change */ 77/* The value of CR and LF is incorporated so if you ever read or write 78 a .pyc file in text mode the magic number will be wrong; also, the 79 Apple MPW compiler swaps their values, botching string constants */ 80/* XXX Perhaps the magic number should be frozen and a version field 81 added to the .pyc file header? */ 82/* New way to come up with the magic number: (YEAR-1995), MONTH, DAY */ 83#define MAGIC (20121 | ((long)'\r'<<16) | ((long)'\n'<<24)) 84 85/* See _PyImport_FixupExtension() below */ 86static PyObject *extensions = NULL; 87 88/* This table is defined in config.c: */ 89extern struct _inittab _PyImport_Inittab[]; 90 91struct _inittab *PyImport_Inittab = _PyImport_Inittab; 92 93/* Initialize things */ 94 95void 96_PyImport_Init() 97{ 98 if (Py_OptimizeFlag) { 99 /* Replace ".pyc" with ".pyo" in import_filetab */ 100 struct filedescr *p; 101 for (p = _PyImport_Filetab; p->suffix != NULL; p++) { 102 if (strcmp(p->suffix, ".pyc") == 0) 103 p->suffix = ".pyo"; 104 } 105 } 106} 107 108void 109_PyImport_Fini() 110{ 111 Py_XDECREF(extensions); 112 extensions = NULL; 113} 114 115 116/* Helper for sys */ 117 118PyObject * 119PyImport_GetModuleDict() 120{ 121 PyInterpreterState *interp = PyThreadState_Get()->interp; 122 if (interp->modules == NULL) 123 Py_FatalError("PyImport_GetModuleDict: no module dictionary!"); 124 return interp->modules; 125} 126 127 128/* Helper for PyImport_Cleanup */ 129 130static void 131clear_carefully(d) 132 PyObject *d; 133{ 134 /* To make the execution order of destructors for global 135 objects a bit more predictable, we first zap all objects 136 whose name starts with a single underscore, before we clear 137 the entire dictionary. We zap them by replacing them with 138 None, rather than deleting them from the dictionary, to 139 avoid rehashing the dictionary (to some extent). */ 140 141 int pos; 142 PyObject *key, *value; 143 144 pos = 0; 145 while (PyDict_Next(d, &pos, &key, &value)) { 146 if (value != Py_None && PyString_Check(key)) { 147 char *s = PyString_AsString(key); 148 if (s[0] == '_' && s[1] != '_') 149 PyDict_SetItem(d, key, Py_None); 150 } 151 } 152 153 PyDict_Clear(d); 154} 155 156/* Un-initialize things, as good as we can */ 157 158void 159PyImport_Cleanup() 160{ 161 PyInterpreterState *interp = PyThreadState_Get()->interp; 162 PyObject *tmp = interp->modules; 163 if (tmp != NULL) { 164 int pos; 165 PyObject *key, *value; 166 interp->modules = NULL; 167 pos = 0; 168 while (PyDict_Next(tmp, &pos, &key, &value)) { 169 if (PyModule_Check(value)) { 170 PyObject *d = PyModule_GetDict(value); 171 clear_carefully(d); 172 } 173 } 174 PyDict_Clear(tmp); 175 Py_DECREF(tmp); 176 } 177} 178 179 180/* Helper for pythonrun.c -- return magic number */ 181 182long 183PyImport_GetMagicNumber() 184{ 185 return MAGIC; 186} 187 188 189/* Magic for extension modules (built-in as well as dynamically 190 loaded). To prevent initializing an extension module more than 191 once, we keep a static dictionary 'extensions' keyed by module name 192 (for built-in modules) or by filename (for dynamically loaded 193 modules), containing these modules. A copy od the module's 194 dictionary is stored by calling _PyImport_FixupExtension() 195 immediately after the module initialization function succeeds. A 196 copy can be retrieved from there by calling 197 _PyImport_FindExtension(). */ 198 199PyObject * 200_PyImport_FixupExtension(name, filename) 201 char *name; 202 char *filename; 203{ 204 PyObject *modules, *mod, *dict, *copy; 205 if (extensions == NULL) { 206 extensions = PyDict_New(); 207 if (extensions == NULL) 208 return NULL; 209 } 210 modules = PyImport_GetModuleDict(); 211 mod = PyDict_GetItemString(modules, name); 212 if (mod == NULL || !PyModule_Check(mod)) { 213 PyErr_Format(PyExc_SystemError, 214 "_PyImport_FixupExtension: module %.200s not loaded", name); 215 return NULL; 216 } 217 dict = PyModule_GetDict(mod); 218 if (dict == NULL) 219 return NULL; 220 copy = PyObject_CallMethod(dict, "copy", ""); 221 if (copy == NULL) 222 return NULL; 223 PyDict_SetItemString(extensions, filename, copy); 224 Py_DECREF(copy); 225 return copy; 226} 227 228PyObject * 229_PyImport_FindExtension(name, filename) 230 char *name; 231 char *filename; 232{ 233 PyObject *dict, *mod, *mdict, *result; 234 if (extensions == NULL) 235 return NULL; 236 dict = PyDict_GetItemString(extensions, filename); 237 if (dict == NULL) 238 return NULL; 239 mod = PyImport_AddModule(name); 240 if (mod == NULL) 241 return NULL; 242 mdict = PyModule_GetDict(mod); 243 if (mdict == NULL) 244 return NULL; 245 result = PyObject_CallMethod(mdict, "update", "O", dict); 246 if (result == NULL) 247 return NULL; 248 Py_DECREF(result); 249 if (Py_VerboseFlag) 250 fprintf(stderr, "import %s # previously loaded (%s)\n", 251 name, filename); 252 return mod; 253} 254 255 256/* Get the module object corresponding to a module name. 257 First check the modules dictionary if there's one there, 258 if not, create a new one and insert in in the modules dictionary. 259 Because the former action is most common, THIS DOES NOT RETURN A 260 'NEW' REFERENCE! */ 261 262PyObject * 263PyImport_AddModule(name) 264 char *name; 265{ 266 PyObject *modules = PyImport_GetModuleDict(); 267 PyObject *m; 268 269 if ((m = PyDict_GetItemString(modules, name)) != NULL && 270 PyModule_Check(m)) 271 return m; 272 m = PyModule_New(name); 273 if (m == NULL) 274 return NULL; 275 if (PyDict_SetItemString(modules, name, m) != 0) { 276 Py_DECREF(m); 277 return NULL; 278 } 279 Py_DECREF(m); /* Yes, it still exists, in modules! */ 280 281 return m; 282} 283 284 285/* Execute a code object in a module and return the module object 286 WITH INCREMENTED REFERENCE COUNT */ 287 288PyObject * 289PyImport_ExecCodeModule(name, co) 290 char *name; 291 PyObject *co; 292{ 293 PyObject *modules = PyImport_GetModuleDict(); 294 PyObject *m, *d, *v; 295 296 m = PyImport_AddModule(name); 297 if (m == NULL) 298 return NULL; 299 d = PyModule_GetDict(m); 300 if (PyDict_GetItemString(d, "__builtins__") == NULL) { 301 if (PyDict_SetItemString(d, "__builtins__", 302 PyEval_GetBuiltins()) != 0) 303 return NULL; 304 } 305 /* Remember the filename as the __file__ attribute */ 306 if (PyDict_SetItemString(d, "__file__", 307 ((PyCodeObject *)co)->co_filename) != 0) 308 PyErr_Clear(); /* Not important enough to report */ 309 v = PyEval_EvalCode((PyCodeObject *)co, d, d); 310 if (v == NULL) 311 return NULL; 312 Py_DECREF(v); 313 314 if ((m = PyDict_GetItemString(modules, name)) == NULL) { 315 PyErr_Format(PyExc_ImportError, 316 "Loaded module %.200s not found in sys.modules", 317 name); 318 return NULL; 319 } 320 321 Py_INCREF(m); 322 323 return m; 324} 325 326 327/* Given a pathname for a Python source file, fill a buffer with the 328 pathname for the corresponding compiled file. Return the pathname 329 for the compiled file, or NULL if there's no space in the buffer. 330 Doesn't set an exception. */ 331 332static char * 333make_compiled_pathname(pathname, buf, buflen) 334 char *pathname; 335 char *buf; 336 int buflen; 337{ 338 int len; 339 340 len = strlen(pathname); 341 if (len+2 > buflen) 342 return NULL; 343 strcpy(buf, pathname); 344 strcpy(buf+len, Py_OptimizeFlag ? "o" : "c"); 345 346 return buf; 347} 348 349 350/* Given a pathname for a Python source file, its time of last 351 modification, and a pathname for a compiled file, check whether the 352 compiled file represents the same version of the source. If so, 353 return a FILE pointer for the compiled file, positioned just after 354 the header; if not, return NULL. 355 Doesn't set an exception. */ 356 357static FILE * 358check_compiled_module(pathname, mtime, cpathname) 359 char *pathname; 360 long mtime; 361 char *cpathname; 362{ 363 FILE *fp; 364 long magic; 365 long pyc_mtime; 366 367 fp = fopen(cpathname, "rb"); 368 if (fp == NULL) 369 return NULL; 370 magic = PyMarshal_ReadLongFromFile(fp); 371 if (magic != MAGIC) { 372 if (Py_VerboseFlag) 373 fprintf(stderr, "# %s has bad magic\n", cpathname); 374 fclose(fp); 375 return NULL; 376 } 377 pyc_mtime = PyMarshal_ReadLongFromFile(fp); 378 if (pyc_mtime != mtime) { 379 if (Py_VerboseFlag) 380 fprintf(stderr, "# %s has bad mtime\n", cpathname); 381 fclose(fp); 382 return NULL; 383 } 384 if (Py_VerboseFlag) 385 fprintf(stderr, "# %s matches %s\n", cpathname, pathname); 386 return fp; 387} 388 389 390/* Read a code object from a file and check it for validity */ 391 392static PyCodeObject * 393read_compiled_module(cpathname, fp) 394 char *cpathname; 395 FILE *fp; 396{ 397 PyObject *co; 398 399 co = PyMarshal_ReadObjectFromFile(fp); 400 /* Ugly: rd_object() may return NULL with or without error */ 401 if (co == NULL || !PyCode_Check(co)) { 402 if (!PyErr_Occurred()) 403 PyErr_Format(PyExc_ImportError, 404 "Non-code object in %.200s", cpathname); 405 Py_XDECREF(co); 406 return NULL; 407 } 408 return (PyCodeObject *)co; 409} 410 411 412/* Load a module from a compiled file, execute it, and return its 413 module object WITH INCREMENTED REFERENCE COUNT */ 414 415static PyObject * 416load_compiled_module(name, cpathname, fp) 417 char *name; 418 char *cpathname; 419 FILE *fp; 420{ 421 long magic; 422 PyCodeObject *co; 423 PyObject *m; 424 425 magic = PyMarshal_ReadLongFromFile(fp); 426 if (magic != MAGIC) { 427 PyErr_Format(PyExc_ImportError, 428 "Bad magic number in %.200s", cpathname); 429 return NULL; 430 } 431 (void) PyMarshal_ReadLongFromFile(fp); 432 co = read_compiled_module(cpathname, fp); 433 if (co == NULL) 434 return NULL; 435 if (Py_VerboseFlag) 436 fprintf(stderr, "import %s # precompiled from %s\n", 437 name, cpathname); 438 m = PyImport_ExecCodeModule(name, (PyObject *)co); 439 Py_DECREF(co); 440 441 return m; 442} 443 444/* Parse a source file and return the corresponding code object */ 445 446static PyCodeObject * 447parse_source_module(pathname, fp) 448 char *pathname; 449 FILE *fp; 450{ 451 PyCodeObject *co; 452 node *n; 453 454 n = PyParser_SimpleParseFile(fp, pathname, Py_file_input); 455 if (n == NULL) 456 return NULL; 457 co = PyNode_Compile(n, pathname); 458 PyNode_Free(n); 459 460 return co; 461} 462 463 464/* Write a compiled module to a file, placing the time of last 465 modification of its source into the header. 466 Errors are ignored, if a write error occurs an attempt is made to 467 remove the file. */ 468 469static void 470write_compiled_module(co, cpathname, mtime) 471 PyCodeObject *co; 472 char *cpathname; 473 long mtime; 474{ 475 FILE *fp; 476 477 fp = fopen(cpathname, "wb"); 478 if (fp == NULL) { 479 if (Py_VerboseFlag) 480 fprintf(stderr, 481 "# can't create %s\n", cpathname); 482 return; 483 } 484 PyMarshal_WriteLongToFile(MAGIC, fp); 485 /* First write a 0 for mtime */ 486 PyMarshal_WriteLongToFile(0L, fp); 487 PyMarshal_WriteObjectToFile((PyObject *)co, fp); 488 if (ferror(fp)) { 489 if (Py_VerboseFlag) 490 fprintf(stderr, "# can't write %s\n", cpathname); 491 /* Don't keep partial file */ 492 fclose(fp); 493 (void) unlink(cpathname); 494 return; 495 } 496 /* Now write the true mtime */ 497 fseek(fp, 4L, 0); 498 PyMarshal_WriteLongToFile(mtime, fp); 499 fflush(fp); 500 fclose(fp); 501 if (Py_VerboseFlag) 502 fprintf(stderr, "# wrote %s\n", cpathname); 503#ifdef macintosh 504 setfiletype(cpathname, 'Pyth', 'PYC '); 505#endif 506} 507 508 509/* Load a source module from a given file and return its module 510 object WITH INCREMENTED REFERENCE COUNT. If there's a matching 511 byte-compiled file, use that instead. */ 512 513static PyObject * 514load_source_module(name, pathname, fp) 515 char *name; 516 char *pathname; 517 FILE *fp; 518{ 519 long mtime; 520 FILE *fpc; 521 char buf[MAXPATHLEN+1]; 522 char *cpathname; 523 PyCodeObject *co; 524 PyObject *m; 525 526 mtime = PyOS_GetLastModificationTime(pathname, fp); 527 cpathname = make_compiled_pathname(pathname, buf, MAXPATHLEN+1); 528 if (cpathname != NULL && 529 (fpc = check_compiled_module(pathname, mtime, cpathname))) { 530 co = read_compiled_module(cpathname, fpc); 531 fclose(fpc); 532 if (co == NULL) 533 return NULL; 534 if (Py_VerboseFlag) 535 fprintf(stderr, "import %s # precompiled from %s\n", 536 name, cpathname); 537 } 538 else { 539 co = parse_source_module(pathname, fp); 540 if (co == NULL) 541 return NULL; 542 if (Py_VerboseFlag) 543 fprintf(stderr, "import %s # from %s\n", 544 name, pathname); 545 write_compiled_module(co, cpathname, mtime); 546 } 547 m = PyImport_ExecCodeModule(name, (PyObject *)co); 548 Py_DECREF(co); 549 550 return m; 551} 552 553 554/* Forward */ 555static PyObject *load_module Py_PROTO((char *, FILE *, char *, int)); 556static struct filedescr *find_module Py_PROTO((char *, PyObject *, 557 char *, int, FILE **)); 558static struct _frozen *find_frozen Py_PROTO((char *name)); 559 560/* Load a package and return its module object WITH INCREMENTED 561 REFERENCE COUNT */ 562 563static PyObject * 564load_package(name, pathname) 565 char *name; 566 char *pathname; 567{ 568 PyObject *m, *d, *file, *path; 569 int err; 570 char buf[MAXPATHLEN+1]; 571 FILE *fp = NULL; 572 struct filedescr *fdp; 573 574 m = PyImport_AddModule(name); 575 if (m == NULL) 576 return NULL; 577 if (Py_VerboseFlag) 578 fprintf(stderr, "import %s # directory %s\n", 579 name, pathname); 580 d = PyModule_GetDict(m); 581 file = PyString_FromString(pathname); 582 if (file == NULL) 583 return NULL; 584 path = Py_BuildValue("[O]", file); 585 if (path == NULL) { 586 Py_DECREF(file); 587 return NULL; 588 } 589 err = PyDict_SetItemString(d, "__file__", file); 590 if (err == 0) 591 err = PyDict_SetItemString(d, "__path__", path); 592 if (err != 0) { 593 m = NULL; 594 goto cleanup; 595 } 596 buf[0] = '\0'; 597 fdp = find_module("__init__", path, buf, sizeof(buf), &fp); 598 if (fdp == NULL) { 599 if (PyErr_ExceptionMatches(PyExc_ImportError)) { 600 PyErr_Clear(); 601 } 602 else 603 m = NULL; 604 goto cleanup; 605 } 606 m = load_module(name, fp, buf, fdp->type); 607 if (fp != NULL) 608 fclose(fp); 609 cleanup: 610 Py_XINCREF(m); 611 Py_XDECREF(path); 612 Py_XDECREF(file); 613 return m; 614} 615 616 617/* Helper to test for built-in module */ 618 619static int 620is_builtin(name) 621 char *name; 622{ 623 int i; 624 for (i = 0; PyImport_Inittab[i].name != NULL; i++) { 625 if (strcmp(name, PyImport_Inittab[i].name) == 0) { 626 if (PyImport_Inittab[i].initfunc == NULL) 627 return -1; 628 else 629 return 1; 630 } 631 } 632 return 0; 633} 634 635 636/* Search the path (default sys.path) for a module. Return the 637 corresponding filedescr struct, and (via return arguments) the 638 pathname and an open file. Return NULL if the module is not found. */ 639 640#ifdef MS_COREDLL 641extern FILE *PyWin_FindRegisteredModule(); 642#endif 643 644static int find_init_module Py_PROTO((char *)); /* Forward */ 645 646static struct filedescr * 647find_module(name, path, buf, buflen, p_fp) 648 char *name; 649 PyObject *path; 650 /* Output parameters: */ 651 char *buf; 652 int buflen; 653 FILE **p_fp; 654{ 655 int i, npath, len, namelen; 656 struct filedescr *fdp = NULL; 657 FILE *fp = NULL; 658 struct stat statbuf; 659 660 if (path == NULL) { 661 if (is_builtin(name)) { 662 static struct filedescr fd = {"", "", C_BUILTIN}; 663 return &fd; 664 } 665 if (find_frozen(name) != NULL) { 666 static struct filedescr fd = {"", "", PY_FROZEN}; 667 return &fd; 668 } 669 670#ifdef MS_COREDLL 671 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen); 672 if (fp != NULL) { 673 *p_fp = fp; 674 return fdp; 675 } 676#endif 677 } 678 679 680 if (path == NULL) 681 path = PySys_GetObject("path"); 682 if (path == NULL || !PyList_Check(path)) { 683 PyErr_SetString(PyExc_ImportError, 684 "sys.path must be a list of directory names"); 685 return NULL; 686 } 687 npath = PyList_Size(path); 688 namelen = strlen(name); 689 for (i = 0; i < npath; i++) { 690 PyObject *v = PyList_GetItem(path, i); 691 if (!PyString_Check(v)) 692 continue; 693 len = PyString_Size(v); 694 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) 695 continue; /* Too long */ 696 strcpy(buf, PyString_AsString(v)); 697 if ((int)strlen(buf) != len) 698 continue; /* v contains '\0' */ 699#ifdef macintosh 700#ifdef INTERN_STRINGS 701 /* 702 ** Speedup: each sys.path item is interned, and 703 ** FindResourceModule remembers which items refer to 704 ** folders (so we don't have to bother trying to look 705 ** into them for resources). 706 */ 707 PyString_InternInPlace(&PyList_GET_ITEM(path, i)); 708 v = PyList_GET_ITEM(path, i); 709#endif 710 if (PyMac_FindResourceModule((PyStringObject *)v, name, buf)) { 711 static struct filedescr resfiledescr = 712 {"", "", PY_RESOURCE}; 713 714 return &resfiledescr; 715 } 716#endif 717 if (len > 0 && buf[len-1] != SEP 718#ifdef ALTSEP 719 && buf[len-1] != ALTSEP 720#endif 721 ) 722 buf[len++] = SEP; 723#ifdef IMPORT_8x3_NAMES 724 /* see if we are searching in directory dos-8x3 */ 725 if (len > 7 && !strncmp(buf + len - 8, "dos-8x3", 7)){ 726 int j; 727 char ch; /* limit name to 8 lower-case characters */ 728 for (j = 0; (ch = name[j]) && j < 8; j++) 729 if (isupper(ch)) 730 buf[len++] = tolower(ch); 731 else 732 buf[len++] = ch; 733 } 734 else /* Not in dos-8x3, use the full name */ 735#endif 736 { 737 strcpy(buf+len, name); 738 len += namelen; 739 } 740#ifdef HAVE_STAT 741 if (stat(buf, &statbuf) == 0) { 742 static struct filedescr fd = {"", "", PKG_DIRECTORY}; 743 if (S_ISDIR(statbuf.st_mode)) { 744 if (find_init_module(buf)) 745 return &fd; 746 } 747 } 748#else 749 /* XXX How are you going to test for directories? */ 750#endif 751#ifdef macintosh 752 fdp = PyMac_FindModuleExtension(buf, &len, name); 753 if (fdp) 754 fp = fopen(buf, fdp->mode); 755#else 756 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) { 757 strcpy(buf+len, fdp->suffix); 758 if (Py_VerboseFlag > 1) 759 fprintf(stderr, "# trying %s\n", buf); 760 fp = fopen(buf, fdp->mode); 761 if (fp != NULL) 762 break; 763 } 764#endif /* !macintosh */ 765 if (fp != NULL) 766 break; 767 } 768 if (fp == NULL) { 769 PyErr_Format(PyExc_ImportError, 770 "No module named %.200s", name); 771 return NULL; 772 } 773 774 *p_fp = fp; 775 return fdp; 776} 777 778#ifdef HAVE_STAT 779/* Helper to look for __init__.py or __init__.py[co] in potential package */ 780static int 781find_init_module(buf) 782 char *buf; 783{ 784 int save_len = strlen(buf); 785 int i = save_len; 786 struct stat statbuf; 787 788 if (save_len + 13 >= MAXPATHLEN) 789 return 0; 790 buf[i++] = SEP; 791 strcpy(buf+i, "__init__.py"); 792 if (stat(buf, &statbuf) == 0) { 793 buf[save_len] = '\0'; 794 return 1; 795 } 796 i += strlen(buf+i); 797 if (Py_OptimizeFlag) 798 strcpy(buf+i, "o"); 799 else 800 strcpy(buf+i, "c"); 801 if (stat(buf, &statbuf) == 0) { 802 buf[save_len] = '\0'; 803 return 1; 804 } 805 buf[save_len] = '\0'; 806 return 0; 807} 808#endif /* HAVE_STAT */ 809 810 811static int init_builtin Py_PROTO((char *)); /* Forward */ 812 813/* Load an external module using the default search path and return 814 its module object WITH INCREMENTED REFERENCE COUNT */ 815 816static PyObject * 817load_module(name, fp, buf, type) 818 char *name; 819 FILE *fp; 820 char *buf; 821 int type; 822{ 823 PyObject *modules; 824 PyObject *m; 825 int err; 826 827 /* First check that there's an open file (if we need one) */ 828 switch (type) { 829 case PY_SOURCE: 830 case PY_COMPILED: 831 if (fp == NULL) { 832 PyErr_Format(PyExc_ValueError, 833 "file object required for import (type code %d)", 834 type); 835 return NULL; 836 } 837 } 838 839 switch (type) { 840 841 case PY_SOURCE: 842 m = load_source_module(name, buf, fp); 843 break; 844 845 case PY_COMPILED: 846 m = load_compiled_module(name, buf, fp); 847 break; 848 849 case C_EXTENSION: 850 m = _PyImport_LoadDynamicModule(name, buf, fp); 851 break; 852 853#ifdef macintosh 854 case PY_RESOURCE: 855 m = PyMac_LoadResourceModule(name, buf); 856 break; 857#endif 858 859 case PKG_DIRECTORY: 860 m = load_package(name, buf); 861 break; 862 863 case C_BUILTIN: 864 case PY_FROZEN: 865 if (type == C_BUILTIN) 866 err = init_builtin(name); 867 else 868 err = PyImport_ImportFrozenModule(name); 869 if (err < 0) 870 return NULL; 871 if (err == 0) { 872 PyErr_Format(PyExc_ImportError, 873 "Purported %s module %.200s not found", 874 type == C_BUILTIN ? 875 "builtin" : "frozen", 876 name); 877 return NULL; 878 } 879 modules = PyImport_GetModuleDict(); 880 m = PyDict_GetItemString(modules, name); 881 if (m == NULL) { 882 PyErr_Format( 883 PyExc_ImportError, 884 "%s module %.200s not properly initialized", 885 type == C_BUILTIN ? 886 "builtin" : "frozen", 887 name); 888 return NULL; 889 } 890 Py_INCREF(m); 891 break; 892 893 default: 894 PyErr_Format(PyExc_ImportError, 895 "Don't know how to import %.200s (type code %d)", 896 name, type); 897 m = NULL; 898 899 } 900 901 return m; 902} 903 904 905/* Initialize a built-in module. 906 Return 1 for succes, 0 if the module is not found, and -1 with 907 an exception set if the initialization failed. */ 908 909static int 910init_builtin(name) 911 char *name; 912{ 913 struct _inittab *p; 914 PyObject *mod; 915 916 if ((mod = _PyImport_FindExtension(name, name)) != NULL) 917 return 1; 918 919 for (p = PyImport_Inittab; p->name != NULL; p++) { 920 if (strcmp(name, p->name) == 0) { 921 if (p->initfunc == NULL) { 922 PyErr_Format(PyExc_ImportError, 923 "Cannot re-init internal module %.200s", 924 name); 925 return -1; 926 } 927 if (Py_VerboseFlag) 928 fprintf(stderr, "import %s # builtin\n", name); 929 (*p->initfunc)(); 930 if (PyErr_Occurred()) 931 return -1; 932 if (_PyImport_FixupExtension(name, name) == NULL) 933 return -1; 934 return 1; 935 } 936 } 937 return 0; 938} 939 940 941/* Frozen modules */ 942 943static struct _frozen * 944find_frozen(name) 945 char *name; 946{ 947 struct _frozen *p; 948 949 for (p = PyImport_FrozenModules; ; p++) { 950 if (p->name == NULL) 951 return NULL; 952 if (strcmp(p->name, name) == 0) 953 break; 954 } 955 return p; 956} 957 958static PyObject * 959get_frozen_object(name) 960 char *name; 961{ 962 struct _frozen *p = find_frozen(name); 963 964 if (p == NULL) { 965 PyErr_Format(PyExc_ImportError, 966 "No such frozen object named %.200s", 967 name); 968 return NULL; 969 } 970 return PyMarshal_ReadObjectFromString((char *)p->code, p->size); 971} 972 973/* Initialize a frozen module. 974 Return 1 for succes, 0 if the module is not found, and -1 with 975 an exception set if the initialization failed. 976 This function is also used from frozenmain.c */ 977 978int 979PyImport_ImportFrozenModule(name) 980 char *name; 981{ 982 struct _frozen *p = find_frozen(name); 983 PyObject *co; 984 PyObject *m; 985 986 if (p == NULL) 987 return 0; 988 if (Py_VerboseFlag) 989 fprintf(stderr, "import %s # frozen\n", name); 990 co = PyMarshal_ReadObjectFromString((char *)p->code, p->size); 991 if (co == NULL) 992 return -1; 993 if (!PyCode_Check(co)) { 994 Py_DECREF(co); 995 PyErr_Format(PyExc_TypeError, 996 "frozen object %.200s is not a code object", 997 name); 998 return -1; 999 } 1000 m = PyImport_ExecCodeModule(name, co); 1001 Py_DECREF(co); 1002 if (m == NULL) 1003 return -1; 1004 Py_DECREF(m); 1005 return 1; 1006} 1007 1008 1009/* Import a module, either built-in, frozen, or external, and return 1010 its module object WITH INCREMENTED REFERENCE COUNT */ 1011 1012PyObject * 1013PyImport_ImportModule(name) 1014 char *name; 1015{ 1016 static PyObject *fromlist = NULL; 1017 if (fromlist == NULL && strchr(name, '.') != NULL) { 1018 fromlist = Py_BuildValue("[s]", "*"); 1019 if (fromlist == NULL) 1020 return NULL; 1021 } 1022 return PyImport_ImportModuleEx(name, NULL, NULL, fromlist); 1023} 1024 1025/* Forward declarations for helper routines */ 1026static PyObject *get_parent Py_PROTO((PyObject *globals, 1027 char *buf, int *p_buflen)); 1028static PyObject *load_next Py_PROTO((PyObject *mod, PyObject *altmod, 1029 char **p_name, char *buf, int *p_buflen)); 1030static int mark_miss Py_PROTO((char *name)); 1031static int ensure_fromlist Py_PROTO((PyObject *mod, PyObject *fromlist, 1032 char *buf, int buflen, int recursive)); 1033static PyObject * import_submodule Py_PROTO((PyObject *mod, 1034 char *name, char *fullname)); 1035 1036/* The Magnum Opus of dotted-name import :-) */ 1037 1038/* XXX TO DO: 1039 - Remember misses in package directories so package submodules 1040 that all import the same toplevel module don't keep hitting on the 1041 package directory first 1042*/ 1043 1044PyObject * 1045PyImport_ImportModuleEx(name, globals, locals, fromlist) 1046 char *name; 1047 PyObject *globals; 1048 PyObject *locals; 1049 PyObject *fromlist; 1050{ 1051 char buf[MAXPATHLEN+1]; 1052 int buflen = 0; 1053 PyObject *parent, *head, *next, *tail; 1054 1055 parent = get_parent(globals, buf, &buflen); 1056 if (parent == NULL) 1057 return NULL; 1058 1059 head = load_next(parent, Py_None, &name, buf, &buflen); 1060 if (head == NULL) 1061 return NULL; 1062 1063 tail = head; 1064 Py_INCREF(tail); 1065 while (name) { 1066 next = load_next(tail, tail, &name, buf, &buflen); 1067 Py_DECREF(tail); 1068 if (next == NULL) { 1069 Py_DECREF(head); 1070 return NULL; 1071 } 1072 tail = next; 1073 } 1074 1075 if (fromlist != NULL) { 1076 if (fromlist == Py_None || !PyObject_IsTrue(fromlist)) 1077 fromlist = NULL; 1078 } 1079 1080 if (fromlist == NULL) { 1081 Py_DECREF(tail); 1082 return head; 1083 } 1084 1085 Py_DECREF(head); 1086 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) { 1087 Py_DECREF(tail); 1088 return NULL; 1089 } 1090 1091 return tail; 1092} 1093 1094static PyObject * 1095get_parent(globals, buf, p_buflen) 1096 PyObject *globals; 1097 char *buf; 1098 int *p_buflen; 1099{ 1100 static PyObject *namestr = NULL; 1101 static PyObject *pathstr = NULL; 1102 PyObject *modname, *modpath, *modules, *parent; 1103 1104 if (globals == NULL || !PyDict_Check(globals)) 1105 return Py_None; 1106 1107 if (namestr == NULL) { 1108 namestr = PyString_InternFromString("__name__"); 1109 if (namestr == NULL) 1110 return NULL; 1111 } 1112 if (pathstr == NULL) { 1113 pathstr = PyString_InternFromString("__path__"); 1114 if (pathstr == NULL) 1115 return NULL; 1116 } 1117 1118 *buf = '\0'; 1119 *p_buflen = 0; 1120 modname = PyDict_GetItem(globals, namestr); 1121 if (modname == NULL || !PyString_Check(modname)) 1122 return Py_None; 1123 1124 modpath = PyDict_GetItem(globals, pathstr); 1125 if (modpath != NULL) { 1126 int len = PyString_GET_SIZE(modname); 1127 if (len > MAXPATHLEN) { 1128 PyErr_SetString(PyExc_ValueError, 1129 "Module name too long"); 1130 return NULL; 1131 } 1132 strcpy(buf, PyString_AS_STRING(modname)); 1133 *p_buflen = len; 1134 } 1135 else { 1136 char *start = PyString_AS_STRING(modname); 1137 char *lastdot = strrchr(start, '.'); 1138 int len; 1139 if (lastdot == NULL) 1140 return Py_None; 1141 len = lastdot - start; 1142 if (len >= MAXPATHLEN) { 1143 PyErr_SetString(PyExc_ValueError, 1144 "Module name too long"); 1145 return NULL; 1146 } 1147 strncpy(buf, start, len); 1148 buf[len] = '\0'; 1149 *p_buflen = len; 1150 } 1151 1152 modules = PyImport_GetModuleDict(); 1153 parent = PyDict_GetItemString(modules, buf); 1154 if (parent == NULL) 1155 parent = Py_None; 1156 return parent; 1157 /* We expect, but can't guarantee, if parent != None, that: 1158 - parent.__name__ == buf 1159 - parent.__dict__ is globals 1160 If this is violated... Who cares? */ 1161} 1162 1163static PyObject * 1164load_next(mod, altmod, p_name, buf, p_buflen) 1165 PyObject *mod; 1166 PyObject *altmod; /* Either None or same as mod */ 1167 char **p_name; 1168 char *buf; 1169 int *p_buflen; 1170{ 1171 char *name = *p_name; 1172 char *dot = strchr(name, '.'); 1173 int len; 1174 char *p; 1175 PyObject *result; 1176 1177 if (dot == NULL) { 1178 *p_name = NULL; 1179 len = strlen(name); 1180 } 1181 else { 1182 *p_name = dot+1; 1183 len = dot-name; 1184 } 1185 1186 p = buf + *p_buflen; 1187 if (p != buf) 1188 *p++ = '.'; 1189 if (p+len-buf >= MAXPATHLEN) { 1190 PyErr_SetString(PyExc_ValueError, 1191 "Module name too long"); 1192 return NULL; 1193 } 1194 strncpy(p, name, len); 1195 p[len] = '\0'; 1196 *p_buflen = p+len-buf; 1197 1198 result = import_submodule(mod, p, buf); 1199 if (result == Py_None && altmod != mod) { 1200 Py_DECREF(result); 1201 /* Here, altmod must be None and mod must not be None */ 1202 result = import_submodule(altmod, p, p); 1203 if (result != NULL && result != Py_None) { 1204 if (mark_miss(buf) != 0) { 1205 Py_DECREF(result); 1206 return NULL; 1207 } 1208 strncpy(buf, name, len); 1209 buf[len] = '\0'; 1210 *p_buflen = len; 1211 } 1212 } 1213 if (result == NULL) 1214 return NULL; 1215 1216 if (result == Py_None) { 1217 Py_DECREF(result); 1218 PyErr_Format(PyExc_ImportError, 1219 "No module named %.200s", name); 1220 return NULL; 1221 } 1222 1223 return result; 1224} 1225 1226static int 1227mark_miss(name) 1228 char *name; 1229{ 1230 PyObject *modules = PyImport_GetModuleDict(); 1231 return PyDict_SetItemString(modules, name, Py_None); 1232} 1233 1234static int 1235ensure_fromlist(mod, fromlist, buf, buflen, recursive) 1236 PyObject *mod; 1237 PyObject *fromlist; 1238 char *buf; 1239 int buflen; 1240 int recursive; 1241{ 1242 int i; 1243 1244 if (!PyObject_HasAttrString(mod, "__path__")) 1245 return 1; 1246 1247 for (i = 0; ; i++) { 1248 PyObject *item = PySequence_GetItem(fromlist, i); 1249 int hasit; 1250 if (item == NULL) { 1251 if (PyErr_ExceptionMatches(PyExc_IndexError)) { 1252 PyErr_Clear(); 1253 return 1; 1254 } 1255 return 0; 1256 } 1257 if (!PyString_Check(item)) { 1258 PyErr_SetString(PyExc_TypeError, 1259 "Item in ``from list'' not a string"); 1260 Py_DECREF(item); 1261 return 0; 1262 } 1263 if (PyString_AS_STRING(item)[0] == '*') { 1264 PyObject *all; 1265 Py_DECREF(item); 1266 /* See if the package defines __all__ */ 1267 if (recursive) 1268 continue; /* Avoid endless recursion */ 1269 all = PyObject_GetAttrString(mod, "__all__"); 1270 if (all == NULL) 1271 PyErr_Clear(); 1272 else { 1273 if (!ensure_fromlist(mod, all, buf, buflen, 1)) 1274 return 0; 1275 Py_DECREF(all); 1276 } 1277 continue; 1278 } 1279 hasit = PyObject_HasAttr(mod, item); 1280 if (!hasit) { 1281 char *subname = PyString_AS_STRING(item); 1282 PyObject *submod; 1283 char *p; 1284 if (buflen + strlen(subname) >= MAXPATHLEN) { 1285 PyErr_SetString(PyExc_ValueError, 1286 "Module name too long"); 1287 Py_DECREF(item); 1288 return 0; 1289 } 1290 p = buf + buflen; 1291 *p++ = '.'; 1292 strcpy(p, subname); 1293 submod = import_submodule(mod, subname, buf); 1294 Py_XDECREF(submod); 1295 if (submod == NULL) { 1296 Py_DECREF(item); 1297 return 0; 1298 } 1299 } 1300 Py_DECREF(item); 1301 } 1302 1303 /* NOTREACHED */ 1304} 1305 1306static PyObject * 1307import_submodule(mod, subname, fullname) 1308 PyObject *mod; /* May be None */ 1309 char *subname; 1310 char *fullname; 1311{ 1312 PyObject *modules = PyImport_GetModuleDict(); 1313 PyObject *m; 1314 1315 /* Require: 1316 if mod == None: subname == fullname 1317 else: mod.__name__ + "." + subname == fullname 1318 */ 1319 1320 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) { 1321 Py_INCREF(m); 1322 } 1323 else { 1324 PyObject *path; 1325 char buf[MAXPATHLEN+1]; 1326 struct filedescr *fdp; 1327 FILE *fp = NULL; 1328 1329 path = PyObject_GetAttrString(mod, "__path__"); 1330 if (path == NULL) 1331 PyErr_Clear(); 1332 1333 buf[0] = '\0'; 1334 fdp = find_module(subname, path, 1335 buf, MAXPATHLEN+1, &fp); 1336 if (fdp == NULL) { 1337 if (!PyErr_ExceptionMatches(PyExc_ImportError)) 1338 return NULL; 1339 PyErr_Clear(); 1340 Py_INCREF(Py_None); 1341 return Py_None; 1342 } 1343 m = load_module(fullname, fp, buf, fdp->type); 1344 if (fp) 1345 fclose(fp); 1346 if (m != NULL && mod != Py_None) { 1347 if (PyObject_SetAttrString(mod, subname, m) < 0) { 1348 Py_DECREF(m); 1349 m = NULL; 1350 } 1351 } 1352 } 1353 1354 return m; 1355} 1356 1357 1358/* Re-import a module of any kind and return its module object, WITH 1359 INCREMENTED REFERENCE COUNT */ 1360 1361PyObject * 1362PyImport_ReloadModule(m) 1363 PyObject *m; 1364{ 1365 PyObject *modules = PyImport_GetModuleDict(); 1366 PyObject *path = NULL; 1367 char *name, *subname; 1368 char buf[MAXPATHLEN+1]; 1369 struct filedescr *fdp; 1370 FILE *fp = NULL; 1371 1372 if (m == NULL || !PyModule_Check(m)) { 1373 PyErr_SetString(PyExc_TypeError, 1374 "reload() argument must be module"); 1375 return NULL; 1376 } 1377 name = PyModule_GetName(m); 1378 if (name == NULL) 1379 return NULL; 1380 if (m != PyDict_GetItemString(modules, name)) { 1381 PyErr_Format(PyExc_ImportError, 1382 "reload(): module %.200s not in sys.modules", 1383 name); 1384 return NULL; 1385 } 1386 subname = strrchr(name, '.'); 1387 if (subname == NULL) 1388 subname = name; 1389 else { 1390 PyObject *parentname, *parent; 1391 parentname = PyString_FromStringAndSize(name, (subname-name)); 1392 if (parentname == NULL) 1393 return NULL; 1394 parent = PyDict_GetItem(modules, parentname); 1395 if (parent == NULL) { 1396 PyErr_Format(PyExc_ImportError, 1397 "reload(): parent %.200s not in sys.modules", 1398 name); 1399 return NULL; 1400 } 1401 subname++; 1402 path = PyObject_GetAttrString(parent, "__path__"); 1403 if (path == NULL) 1404 PyErr_Clear(); 1405 } 1406 buf[0] = '\0'; 1407 fdp = find_module(subname, path, buf, MAXPATHLEN+1, &fp); 1408 Py_XDECREF(path); 1409 if (fdp == NULL) 1410 return NULL; 1411 m = load_module(name, fp, buf, fdp->type); 1412 if (fp) 1413 fclose(fp); 1414 return m; 1415} 1416 1417 1418/* Higher-level import emulator which emulates the "import" statement 1419 more accurately -- it invokes the __import__() function from the 1420 builtins of the current globals. This means that the import is 1421 done using whatever import hooks are installed in the current 1422 environment, e.g. by "ni" or "rexec". */ 1423 1424PyObject * 1425PyImport_Import(module_name) 1426 PyObject *module_name; 1427{ 1428 static PyObject *silly_list = NULL; 1429 static PyObject *builtins_str = NULL; 1430 static PyObject *import_str = NULL; 1431 static PyObject *standard_builtins = NULL; 1432 PyObject *globals = NULL; 1433 PyObject *import = NULL; 1434 PyObject *builtins = NULL; 1435 PyObject *r = NULL; 1436 1437 /* Initialize constant string objects */ 1438 if (silly_list == NULL) { 1439 import_str = PyString_InternFromString("__import__"); 1440 if (import_str == NULL) 1441 return NULL; 1442 builtins_str = PyString_InternFromString("__builtins__"); 1443 if (builtins_str == NULL) 1444 return NULL; 1445 silly_list = Py_BuildValue("[s]", "__doc__"); 1446 if (silly_list == NULL) 1447 return NULL; 1448 } 1449 1450 /* Get the builtins from current globals */ 1451 globals = PyEval_GetGlobals(); 1452 if(globals != NULL) { 1453 builtins = PyObject_GetItem(globals, builtins_str); 1454 if (builtins == NULL) 1455 goto err; 1456 } 1457 else { 1458 /* No globals -- use standard builtins, and fake globals */ 1459 PyErr_Clear(); 1460 1461 if (standard_builtins == NULL) { 1462 standard_builtins = 1463 PyImport_ImportModule("__builtin__"); 1464 if (standard_builtins == NULL) 1465 return NULL; 1466 } 1467 1468 builtins = standard_builtins; 1469 Py_INCREF(builtins); 1470 globals = Py_BuildValue("{OO}", builtins_str, builtins); 1471 if (globals == NULL) 1472 goto err; 1473 } 1474 1475 /* Get the __import__ function from the builtins */ 1476 if (PyDict_Check(builtins)) 1477 import=PyObject_GetItem(builtins, import_str); 1478 else 1479 import=PyObject_GetAttr(builtins, import_str); 1480 if (import == NULL) 1481 goto err; 1482 1483 /* Call the _import__ function with the proper argument list */ 1484 r = PyObject_CallFunction(import, "OOOO", 1485 module_name, globals, globals, silly_list); 1486 1487 err: 1488 Py_XDECREF(globals); 1489 Py_XDECREF(builtins); 1490 Py_XDECREF(import); 1491 1492 return r; 1493} 1494 1495 1496/* Module 'imp' provides Python access to the primitives used for 1497 importing modules. 1498*/ 1499 1500static PyObject * 1501imp_get_magic(self, args) 1502 PyObject *self; 1503 PyObject *args; 1504{ 1505 char buf[4]; 1506 1507 if (!PyArg_ParseTuple(args, "")) 1508 return NULL; 1509 buf[0] = (char) ((MAGIC >> 0) & 0xff); 1510 buf[1] = (char) ((MAGIC >> 8) & 0xff); 1511 buf[2] = (char) ((MAGIC >> 16) & 0xff); 1512 buf[3] = (char) ((MAGIC >> 24) & 0xff); 1513 1514 return PyString_FromStringAndSize(buf, 4); 1515} 1516 1517static PyObject * 1518imp_get_suffixes(self, args) 1519 PyObject *self; 1520 PyObject *args; 1521{ 1522 PyObject *list; 1523 struct filedescr *fdp; 1524 1525 if (!PyArg_ParseTuple(args, "")) 1526 return NULL; 1527 list = PyList_New(0); 1528 if (list == NULL) 1529 return NULL; 1530 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) { 1531 PyObject *item = Py_BuildValue("ssi", 1532 fdp->suffix, fdp->mode, fdp->type); 1533 if (item == NULL) { 1534 Py_DECREF(list); 1535 return NULL; 1536 } 1537 if (PyList_Append(list, item) < 0) { 1538 Py_DECREF(list); 1539 Py_DECREF(item); 1540 return NULL; 1541 } 1542 Py_DECREF(item); 1543 } 1544 return list; 1545} 1546 1547static PyObject * 1548call_find_module(name, path) 1549 char *name; 1550 PyObject *path; /* list or None or NULL */ 1551{ 1552 extern int fclose Py_PROTO((FILE *)); 1553 PyObject *fob, *ret; 1554 struct filedescr *fdp; 1555 char pathname[MAXPATHLEN+1]; 1556 FILE *fp = NULL; 1557 1558 pathname[0] = '\0'; 1559 if (path == Py_None) 1560 path = NULL; 1561 fdp = find_module(name, path, pathname, MAXPATHLEN+1, &fp); 1562 if (fdp == NULL) 1563 return NULL; 1564 if (fp != NULL) { 1565 fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose); 1566 if (fob == NULL) { 1567 fclose(fp); 1568 return NULL; 1569 } 1570 } 1571 else { 1572 fob = Py_None; 1573 Py_INCREF(fob); 1574 } 1575 ret = Py_BuildValue("Os(ssi)", 1576 fob, pathname, fdp->suffix, fdp->mode, fdp->type); 1577 Py_DECREF(fob); 1578 return ret; 1579} 1580 1581static PyObject * 1582imp_find_module(self, args) 1583 PyObject *self; 1584 PyObject *args; 1585{ 1586 char *name; 1587 PyObject *path = NULL; 1588 if (!PyArg_ParseTuple(args, "s|O", &name, &path)) 1589 return NULL; 1590 return call_find_module(name, path); 1591} 1592 1593static PyObject * 1594imp_init_builtin(self, args) 1595 PyObject *self; 1596 PyObject *args; 1597{ 1598 char *name; 1599 int ret; 1600 PyObject *m; 1601 if (!PyArg_ParseTuple(args, "s", &name)) 1602 return NULL; 1603 ret = init_builtin(name); 1604 if (ret < 0) 1605 return NULL; 1606 if (ret == 0) { 1607 Py_INCREF(Py_None); 1608 return Py_None; 1609 } 1610 m = PyImport_AddModule(name); 1611 Py_XINCREF(m); 1612 return m; 1613} 1614 1615static PyObject * 1616imp_init_frozen(self, args) 1617 PyObject *self; 1618 PyObject *args; 1619{ 1620 char *name; 1621 int ret; 1622 PyObject *m; 1623 if (!PyArg_ParseTuple(args, "s", &name)) 1624 return NULL; 1625 ret = PyImport_ImportFrozenModule(name); 1626 if (ret < 0) 1627 return NULL; 1628 if (ret == 0) { 1629 Py_INCREF(Py_None); 1630 return Py_None; 1631 } 1632 m = PyImport_AddModule(name); 1633 Py_XINCREF(m); 1634 return m; 1635} 1636 1637static PyObject * 1638imp_get_frozen_object(self, args) 1639 PyObject *self; 1640 PyObject *args; 1641{ 1642 char *name; 1643 1644 if (!PyArg_ParseTuple(args, "s", &name)) 1645 return NULL; 1646 return get_frozen_object(name); 1647} 1648 1649static PyObject * 1650imp_is_builtin(self, args) 1651 PyObject *self; 1652 PyObject *args; 1653{ 1654 char *name; 1655 if (!PyArg_ParseTuple(args, "s", &name)) 1656 return NULL; 1657 return PyInt_FromLong(is_builtin(name)); 1658} 1659 1660static PyObject * 1661imp_is_frozen(self, args) 1662 PyObject *self; 1663 PyObject *args; 1664{ 1665 char *name; 1666 if (!PyArg_ParseTuple(args, "s", &name)) 1667 return NULL; 1668 return PyInt_FromLong(find_frozen(name) != NULL); 1669} 1670 1671static FILE * 1672get_file(pathname, fob, mode) 1673 char *pathname; 1674 PyObject *fob; 1675 char *mode; 1676{ 1677 FILE *fp; 1678 if (fob == NULL) { 1679 fp = fopen(pathname, mode); 1680 if (fp == NULL) 1681 PyErr_SetFromErrno(PyExc_IOError); 1682 } 1683 else { 1684 fp = PyFile_AsFile(fob); 1685 if (fp == NULL) 1686 PyErr_SetString(PyExc_ValueError, 1687 "bad/closed file object"); 1688 } 1689 return fp; 1690} 1691 1692static PyObject * 1693imp_load_compiled(self, args) 1694 PyObject *self; 1695 PyObject *args; 1696{ 1697 char *name; 1698 char *pathname; 1699 PyObject *fob = NULL; 1700 PyObject *m; 1701 FILE *fp; 1702 if (!PyArg_ParseTuple(args, "ss|O!", &name, &pathname, 1703 &PyFile_Type, &fob)) 1704 return NULL; 1705 fp = get_file(pathname, fob, "rb"); 1706 if (fp == NULL) 1707 return NULL; 1708 m = load_compiled_module(name, pathname, fp); 1709 if (fob == NULL) 1710 fclose(fp); 1711 return m; 1712} 1713 1714static PyObject * 1715imp_load_dynamic(self, args) 1716 PyObject *self; 1717 PyObject *args; 1718{ 1719 char *name; 1720 char *pathname; 1721 PyObject *fob = NULL; 1722 PyObject *m; 1723 FILE *fp = NULL; 1724 if (!PyArg_ParseTuple(args, "ss|O!", &name, &pathname, 1725 &PyFile_Type, &fob)) 1726 return NULL; 1727 if (fob) { 1728 fp = get_file(pathname, fob, "r"); 1729 if (fp == NULL) 1730 return NULL; 1731 } 1732 m = _PyImport_LoadDynamicModule(name, pathname, fp); 1733 return m; 1734} 1735 1736static PyObject * 1737imp_load_source(self, args) 1738 PyObject *self; 1739 PyObject *args; 1740{ 1741 char *name; 1742 char *pathname; 1743 PyObject *fob = NULL; 1744 PyObject *m; 1745 FILE *fp; 1746 if (!PyArg_ParseTuple(args, "ss|O!", &name, &pathname, 1747 &PyFile_Type, &fob)) 1748 return NULL; 1749 fp = get_file(pathname, fob, "r"); 1750 if (fp == NULL) 1751 return NULL; 1752 m = load_source_module(name, pathname, fp); 1753 if (fob == NULL) 1754 fclose(fp); 1755 return m; 1756} 1757 1758#ifdef macintosh 1759static PyObject * 1760imp_load_resource(self, args) 1761 PyObject *self; 1762 PyObject *args; 1763{ 1764 char *name; 1765 char *pathname; 1766 PyObject *m; 1767 1768 if (!PyArg_ParseTuple(args, "ss", &name, &pathname)) 1769 return NULL; 1770 m = PyMac_LoadResourceModule(name, pathname); 1771 return m; 1772} 1773#endif /* macintosh */ 1774 1775static PyObject * 1776imp_load_module(self, args) 1777 PyObject *self; 1778 PyObject *args; 1779{ 1780 char *name; 1781 PyObject *fob; 1782 char *pathname; 1783 char *suffix; /* Unused */ 1784 char *mode; 1785 int type; 1786 FILE *fp; 1787 1788 if (!PyArg_ParseTuple(args, "sOs(ssi)", 1789 &name, &fob, &pathname, 1790 &suffix, &mode, &type)) 1791 return NULL; 1792 if (*mode && (*mode != 'r' || strchr(mode, '+') != NULL)) { 1793 PyErr_Format(PyExc_ValueError, 1794 "invalid file open mode %.200s", mode); 1795 return NULL; 1796 } 1797 if (fob == Py_None) 1798 fp = NULL; 1799 else { 1800 if (!PyFile_Check(fob)) { 1801 PyErr_SetString(PyExc_ValueError, 1802 "load_module arg#2 should be a file or None"); 1803 return NULL; 1804 } 1805 fp = get_file(pathname, fob, mode); 1806 if (fp == NULL) 1807 return NULL; 1808 } 1809 return load_module(name, fp, pathname, type); 1810} 1811 1812static PyObject * 1813imp_load_package(self, args) 1814 PyObject *self; 1815 PyObject *args; 1816{ 1817 char *name; 1818 char *pathname; 1819 if (!PyArg_ParseTuple(args, "ss", &name, &pathname)) 1820 return NULL; 1821 return load_package(name, pathname); 1822} 1823 1824static PyObject * 1825imp_new_module(self, args) 1826 PyObject *self; 1827 PyObject *args; 1828{ 1829 char *name; 1830 if (!PyArg_ParseTuple(args, "s", &name)) 1831 return NULL; 1832 return PyModule_New(name); 1833} 1834 1835/* Doc strings */ 1836 1837static char doc_imp[] = "\ 1838This module provides the components needed to build your own\n\ 1839__import__ function. Undocumented functions are obsolete.\n\ 1840"; 1841 1842static char doc_find_module[] = "\ 1843find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\ 1844Search for a module. If path is omitted or None, search for a\n\ 1845built-in, frozen or special module and continue search in sys.path.\n\ 1846The module name cannot contain '.'; to search for a submodule of a\n\ 1847package, pass the submodule name and the package's __path__.\ 1848"; 1849 1850static char doc_load_module[] = "\ 1851load_module(name, file, filename, (suffix, mode, type)) -> module\n\ 1852Load a module, given information returned by find_module().\n\ 1853The module name must include the full package name, if any.\ 1854"; 1855 1856static char doc_get_magic[] = "\ 1857get_magic() -> string\n\ 1858Return the magic number for .pyc or .pyo files.\ 1859"; 1860 1861static char doc_get_suffixes[] = "\ 1862get_suffixes() -> [(suffix, mode, type), ...]\n\ 1863Return a list of (suffix, mode, type) tuples describing the files\n\ 1864that find_module() looks for.\ 1865"; 1866 1867static char doc_new_module[] = "\ 1868new_module(name) -> module\n\ 1869Create a new module. Do not enter it in sys.modules.\n\ 1870The module name must include the full package name, if any.\ 1871"; 1872 1873static PyMethodDef imp_methods[] = { 1874 {"find_module", imp_find_module, 1, doc_find_module}, 1875 {"get_magic", imp_get_magic, 1, doc_get_magic}, 1876 {"get_suffixes", imp_get_suffixes, 1, doc_get_suffixes}, 1877 {"load_module", imp_load_module, 1, doc_load_module}, 1878 {"new_module", imp_new_module, 1, doc_new_module}, 1879 /* The rest are obsolete */ 1880 {"get_frozen_object", imp_get_frozen_object, 1}, 1881 {"init_builtin", imp_init_builtin, 1}, 1882 {"init_frozen", imp_init_frozen, 1}, 1883 {"is_builtin", imp_is_builtin, 1}, 1884 {"is_frozen", imp_is_frozen, 1}, 1885 {"load_compiled", imp_load_compiled, 1}, 1886 {"load_dynamic", imp_load_dynamic, 1}, 1887 {"load_package", imp_load_package, 1}, 1888#ifdef macintosh 1889 {"load_resource", imp_load_resource, 1}, 1890#endif 1891 {"load_source", imp_load_source, 1}, 1892 {NULL, NULL} /* sentinel */ 1893}; 1894 1895int 1896setint(d, name, value) 1897 PyObject *d; 1898 char *name; 1899 int value; 1900{ 1901 PyObject *v; 1902 int err; 1903 1904 v = PyInt_FromLong((long)value); 1905 err = PyDict_SetItemString(d, name, v); 1906 Py_XDECREF(v); 1907 return err; 1908} 1909 1910void 1911initimp() 1912{ 1913 PyObject *m, *d; 1914 1915 m = Py_InitModule4("imp", imp_methods, doc_imp, 1916 NULL, PYTHON_API_VERSION); 1917 d = PyModule_GetDict(m); 1918 1919 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure; 1920 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure; 1921 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure; 1922 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure; 1923 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure; 1924 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure; 1925 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure; 1926 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure; 1927 1928 failure: 1929 ; 1930} 1931