-
-
Notifications
You must be signed in to change notification settings - Fork 30.7k
/
import.c
2180 lines (1889 loc) · 59.5 KB
/
import.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Module definition and import implementation */
#include "Python.h"
#include "Python-ast.h"
#undef Yield /* undefine macro conflicting with winbase.h */
#include "errcode.h"
#include "marshal.h"
#include "code.h"
#include "frameobject.h"
#include "osdefs.h"
#include "importdl.h"
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
#define CACHEDIR "__pycache__"
/* See _PyImport_FixupExtensionObject() below */
static PyObject *extensions = NULL;
/* This table is defined in config.c: */
extern struct _inittab _PyImport_Inittab[];
struct _inittab *PyImport_Inittab = _PyImport_Inittab;
static PyObject *initstr = NULL;
/*[clinic input]
module _imp
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=9c332475d8686284]*/
#include "clinic/import.c.h"
/*[python input]
class fs_unicode_converter(CConverter):
type = 'PyObject *'
converter = 'PyUnicode_FSDecoder'
[python start generated code]*/
/*[python end generated code: output=da39a3ee5e6b4b0d input=9d6786230166006e]*/
/* Initialize things */
void
_PyImport_Init(void)
{
PyInterpreterState *interp = PyThreadState_Get()->interp;
initstr = PyUnicode_InternFromString("__init__");
if (initstr == NULL)
Py_FatalError("Can't initialize import variables");
interp->builtins_copy = PyDict_Copy(interp->builtins);
if (interp->builtins_copy == NULL)
Py_FatalError("Can't backup builtins dict");
}
void
_PyImportHooks_Init(void)
{
PyObject *v, *path_hooks = NULL;
int err = 0;
/* adding sys.path_hooks and sys.path_importer_cache */
v = PyList_New(0);
if (v == NULL)
goto error;
err = PySys_SetObject("meta_path", v);
Py_DECREF(v);
if (err)
goto error;
v = PyDict_New();
if (v == NULL)
goto error;
err = PySys_SetObject("path_importer_cache", v);
Py_DECREF(v);
if (err)
goto error;
path_hooks = PyList_New(0);
if (path_hooks == NULL)
goto error;
err = PySys_SetObject("path_hooks", path_hooks);
if (err) {
error:
PyErr_Print();
Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
"or path_importer_cache failed");
}
Py_DECREF(path_hooks);
}
void
_PyImportZip_Init(void)
{
PyObject *path_hooks, *zimpimport;
int err = 0;
path_hooks = PySys_GetObject("path_hooks");
if (path_hooks == NULL) {
PyErr_SetString(PyExc_RuntimeError, "unable to get sys.path_hooks");
goto error;
}
if (Py_VerboseFlag)
PySys_WriteStderr("# installing zipimport hook\n");
zimpimport = PyImport_ImportModule("zipimport");
if (zimpimport == NULL) {
PyErr_Clear(); /* No zip import module -- okay */
if (Py_VerboseFlag)
PySys_WriteStderr("# can't import zipimport\n");
}
else {
_Py_IDENTIFIER(zipimporter);
PyObject *zipimporter = _PyObject_GetAttrId(zimpimport,
&PyId_zipimporter);
Py_DECREF(zimpimport);
if (zipimporter == NULL) {
PyErr_Clear(); /* No zipimporter object -- okay */
if (Py_VerboseFlag)
PySys_WriteStderr(
"# can't import zipimport.zipimporter\n");
}
else {
/* sys.path_hooks.insert(0, zipimporter) */
err = PyList_Insert(path_hooks, 0, zipimporter);
Py_DECREF(zipimporter);
if (err < 0) {
goto error;
}
if (Py_VerboseFlag)
PySys_WriteStderr(
"# installed zipimport hook\n");
}
}
return;
error:
PyErr_Print();
Py_FatalError("initializing zipimport failed");
}
/* Locking primitives to prevent parallel imports of the same module
in different threads to return with a partially loaded module.
These calls are serialized by the global interpreter lock. */
#ifdef WITH_THREAD
#include "pythread.h"
static PyThread_type_lock import_lock = 0;
static long import_lock_thread = -1;
static int import_lock_level = 0;
void
_PyImport_AcquireLock(void)
{
long me = PyThread_get_thread_ident();
if (me == -1)
return; /* Too bad */
if (import_lock == NULL) {
import_lock = PyThread_allocate_lock();
if (import_lock == NULL)
return; /* Nothing much we can do. */
}
if (import_lock_thread == me) {
import_lock_level++;
return;
}
if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
{
PyThreadState *tstate = PyEval_SaveThread();
PyThread_acquire_lock(import_lock, 1);
PyEval_RestoreThread(tstate);
}
assert(import_lock_level == 0);
import_lock_thread = me;
import_lock_level = 1;
}
int
_PyImport_ReleaseLock(void)
{
long me = PyThread_get_thread_ident();
if (me == -1 || import_lock == NULL)
return 0; /* Too bad */
if (import_lock_thread != me)
return -1;
import_lock_level--;
assert(import_lock_level >= 0);
if (import_lock_level == 0) {
import_lock_thread = -1;
PyThread_release_lock(import_lock);
}
return 1;
}
/* This function is called from PyOS_AfterFork to ensure that newly
created child processes do not share locks with the parent.
We now acquire the import lock around fork() calls but on some platforms
(Solaris 9 and earlier? see isue7242) that still left us with problems. */
void
_PyImport_ReInitLock(void)
{
if (import_lock != NULL) {
import_lock = PyThread_allocate_lock();
if (import_lock == NULL) {
Py_FatalError("PyImport_ReInitLock failed to create a new lock");
}
}
if (import_lock_level > 1) {
/* Forked as a side effect of import */
long me = PyThread_get_thread_ident();
/* The following could fail if the lock is already held, but forking as
a side-effect of an import is a) rare, b) nuts, and c) difficult to
do thanks to the lock only being held when doing individual module
locks per import. */
PyThread_acquire_lock(import_lock, NOWAIT_LOCK);
import_lock_thread = me;
import_lock_level--;
} else {
import_lock_thread = -1;
import_lock_level = 0;
}
}
#endif
/*[clinic input]
_imp.lock_held
Return True if the import lock is currently held, else False.
On platforms without threads, return False.
[clinic start generated code]*/
static PyObject *
_imp_lock_held_impl(PyModuleDef *module)
/*[clinic end generated code: output=d7a8cc3a5169081a input=9b088f9b217d9bdf]*/
{
#ifdef WITH_THREAD
return PyBool_FromLong(import_lock_thread != -1);
#else
return PyBool_FromLong(0);
#endif
}
/*[clinic input]
_imp.acquire_lock
Acquires the interpreter's import lock for the current thread.
This lock should be used by import hooks to ensure thread-safety when importing
modules. On platforms without threads, this function does nothing.
[clinic start generated code]*/
static PyObject *
_imp_acquire_lock_impl(PyModuleDef *module)
/*[clinic end generated code: output=cc143b1d16422cae input=4a2d4381866d5fdc]*/
{
#ifdef WITH_THREAD
_PyImport_AcquireLock();
#endif
Py_INCREF(Py_None);
return Py_None;
}
/*[clinic input]
_imp.release_lock
Release the interpreter's import lock.
On platforms without threads, this function does nothing.
[clinic start generated code]*/
static PyObject *
_imp_release_lock_impl(PyModuleDef *module)
/*[clinic end generated code: output=74d28e38ebe2b224 input=934fb11516dd778b]*/
{
#ifdef WITH_THREAD
if (_PyImport_ReleaseLock() < 0) {
PyErr_SetString(PyExc_RuntimeError,
"not holding the import lock");
return NULL;
}
#endif
Py_INCREF(Py_None);
return Py_None;
}
void
_PyImport_Fini(void)
{
Py_CLEAR(extensions);
#ifdef WITH_THREAD
if (import_lock != NULL) {
PyThread_free_lock(import_lock);
import_lock = NULL;
}
#endif
}
/* Helper for sys */
PyObject *
PyImport_GetModuleDict(void)
{
PyInterpreterState *interp = PyThreadState_GET()->interp;
if (interp->modules == NULL)
Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
return interp->modules;
}
/* List of names to clear in sys */
static char* sys_deletes[] = {
"path", "argv", "ps1", "ps2",
"last_type", "last_value", "last_traceback",
"path_hooks", "path_importer_cache", "meta_path",
"__interactivehook__",
/* misc stuff */
"flags", "float_info",
NULL
};
static char* sys_files[] = {
"stdin", "__stdin__",
"stdout", "__stdout__",
"stderr", "__stderr__",
NULL
};
/* Un-initialize things, as good as we can */
void
PyImport_Cleanup(void)
{
Py_ssize_t pos;
PyObject *key, *value, *dict;
PyInterpreterState *interp = PyThreadState_GET()->interp;
PyObject *modules = interp->modules;
PyObject *weaklist = NULL;
char **p;
if (modules == NULL)
return; /* Already done */
/* Delete some special variables first. These are common
places where user values hide and people complain when their
destructors fail. Since the modules containing them are
deleted *last* of all, they would come too late in the normal
destruction order. Sigh. */
/* XXX Perhaps these precautions are obsolete. Who knows? */
if (Py_VerboseFlag)
PySys_WriteStderr("# clear builtins._\n");
PyDict_SetItemString(interp->builtins, "_", Py_None);
for (p = sys_deletes; *p != NULL; p++) {
if (Py_VerboseFlag)
PySys_WriteStderr("# clear sys.%s\n", *p);
PyDict_SetItemString(interp->sysdict, *p, Py_None);
}
for (p = sys_files; *p != NULL; p+=2) {
if (Py_VerboseFlag)
PySys_WriteStderr("# restore sys.%s\n", *p);
value = PyDict_GetItemString(interp->sysdict, *(p+1));
if (value == NULL)
value = Py_None;
PyDict_SetItemString(interp->sysdict, *p, value);
}
/* We prepare a list which will receive (name, weakref) tuples of
modules when they are removed from sys.modules. The name is used
for diagnosis messages (in verbose mode), while the weakref helps
detect those modules which have been held alive. */
weaklist = PyList_New(0);
if (weaklist == NULL)
PyErr_Clear();
#define STORE_MODULE_WEAKREF(name, mod) \
if (weaklist != NULL) { \
PyObject *wr = PyWeakref_NewRef(mod, NULL); \
if (name && wr) { \
PyObject *tup = PyTuple_Pack(2, name, wr); \
PyList_Append(weaklist, tup); \
Py_XDECREF(tup); \
} \
Py_XDECREF(wr); \
if (PyErr_Occurred()) \
PyErr_Clear(); \
}
/* Remove all modules from sys.modules, hoping that garbage collection
can reclaim most of them. */
pos = 0;
while (PyDict_Next(modules, &pos, &key, &value)) {
if (PyModule_Check(value)) {
if (Py_VerboseFlag && PyUnicode_Check(key))
PySys_FormatStderr("# cleanup[2] removing %U\n", key);
STORE_MODULE_WEAKREF(key, value);
PyDict_SetItem(modules, key, Py_None);
}
}
/* Clear the modules dict. */
PyDict_Clear(modules);
/* Restore the original builtins dict, to ensure that any
user data gets cleared. */
dict = PyDict_Copy(interp->builtins);
if (dict == NULL)
PyErr_Clear();
PyDict_Clear(interp->builtins);
if (PyDict_Update(interp->builtins, interp->builtins_copy))
PyErr_Clear();
Py_XDECREF(dict);
/* Clear module dict copies stored in the interpreter state */
_PyState_ClearModules();
/* Collect references */
_PyGC_CollectNoFail();
/* Dump GC stats before it's too late, since it uses the warnings
machinery. */
_PyGC_DumpShutdownStats();
/* Now, if there are any modules left alive, clear their globals to
minimize potential leaks. All C extension modules actually end
up here, since they are kept alive in the interpreter state.
The special treatment of "builtins" here is because even
when it's not referenced as a module, its dictionary is
referenced by almost every module's __builtins__. Since
deleting a module clears its dictionary (even if there are
references left to it), we need to delete the "builtins"
module last. Likewise, we don't delete sys until the very
end because it is implicitly referenced (e.g. by print). */
if (weaklist != NULL) {
Py_ssize_t i, n;
n = PyList_GET_SIZE(weaklist);
for (i = 0; i < n; i++) {
PyObject *tup = PyList_GET_ITEM(weaklist, i);
PyObject *name = PyTuple_GET_ITEM(tup, 0);
PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
if (mod == Py_None)
continue;
assert(PyModule_Check(mod));
dict = PyModule_GetDict(mod);
if (dict == interp->builtins || dict == interp->sysdict)
continue;
Py_INCREF(mod);
if (Py_VerboseFlag && PyUnicode_Check(name))
PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
_PyModule_Clear(mod);
Py_DECREF(mod);
}
Py_DECREF(weaklist);
}
/* Next, delete sys and builtins (in that order) */
if (Py_VerboseFlag)
PySys_FormatStderr("# cleanup[3] wiping sys\n");
_PyModule_ClearDict(interp->sysdict);
if (Py_VerboseFlag)
PySys_FormatStderr("# cleanup[3] wiping builtins\n");
_PyModule_ClearDict(interp->builtins);
/* Clear and delete the modules directory. Actual modules will
still be there only if imported during the execution of some
destructor. */
interp->modules = NULL;
Py_DECREF(modules);
/* Once more */
_PyGC_CollectNoFail();
#undef STORE_MODULE_WEAKREF
}
/* Helper for pythonrun.c -- return magic number and tag. */
long
PyImport_GetMagicNumber(void)
{
long res;
PyInterpreterState *interp = PyThreadState_Get()->interp;
PyObject *external, *pyc_magic;
external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
if (external == NULL)
return -1;
pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER");
Py_DECREF(external);
if (pyc_magic == NULL)
return -1;
res = PyLong_AsLong(pyc_magic);
Py_DECREF(pyc_magic);
return res;
}
extern const char * _PySys_ImplCacheTag;
const char *
PyImport_GetMagicTag(void)
{
return _PySys_ImplCacheTag;
}
/* Magic for extension modules (built-in as well as dynamically
loaded). To prevent initializing an extension module more than
once, we keep a static dictionary 'extensions' keyed by the tuple
(module name, module name) (for built-in modules) or by
(filename, module name) (for dynamically loaded modules), containing these
modules. A copy of the module's dictionary is stored by calling
_PyImport_FixupExtensionObject() immediately after the module initialization
function succeeds. A copy can be retrieved from there by calling
_PyImport_FindExtensionObject().
Modules which do support multiple initialization set their m_size
field to a non-negative number (indicating the size of the
module-specific state). They are still recorded in the extensions
dictionary, to avoid loading shared libraries twice.
*/
int
_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
PyObject *filename)
{
PyObject *modules, *dict, *key;
struct PyModuleDef *def;
int res;
if (extensions == NULL) {
extensions = PyDict_New();
if (extensions == NULL)
return -1;
}
if (mod == NULL || !PyModule_Check(mod)) {
PyErr_BadInternalCall();
return -1;
}
def = PyModule_GetDef(mod);
if (!def) {
PyErr_BadInternalCall();
return -1;
}
modules = PyImport_GetModuleDict();
if (PyDict_SetItem(modules, name, mod) < 0)
return -1;
if (_PyState_AddModule(mod, def) < 0) {
PyDict_DelItem(modules, name);
return -1;
}
if (def->m_size == -1) {
if (def->m_base.m_copy) {
/* Somebody already imported the module,
likely under a different name.
XXX this should really not happen. */
Py_CLEAR(def->m_base.m_copy);
}
dict = PyModule_GetDict(mod);
if (dict == NULL)
return -1;
def->m_base.m_copy = PyDict_Copy(dict);
if (def->m_base.m_copy == NULL)
return -1;
}
key = PyTuple_Pack(2, filename, name);
if (key == NULL)
return -1;
res = PyDict_SetItem(extensions, key, (PyObject *)def);
Py_DECREF(key);
if (res < 0)
return -1;
return 0;
}
int
_PyImport_FixupBuiltin(PyObject *mod, const char *name)
{
int res;
PyObject *nameobj;
nameobj = PyUnicode_InternFromString(name);
if (nameobj == NULL)
return -1;
res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj);
Py_DECREF(nameobj);
return res;
}
PyObject *
_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
{
PyObject *mod, *mdict, *key;
PyModuleDef* def;
if (extensions == NULL)
return NULL;
key = PyTuple_Pack(2, filename, name);
if (key == NULL)
return NULL;
def = (PyModuleDef *)PyDict_GetItem(extensions, key);
Py_DECREF(key);
if (def == NULL)
return NULL;
if (def->m_size == -1) {
/* Module does not support repeated initialization */
if (def->m_base.m_copy == NULL)
return NULL;
mod = PyImport_AddModuleObject(name);
if (mod == NULL)
return NULL;
mdict = PyModule_GetDict(mod);
if (mdict == NULL)
return NULL;
if (PyDict_Update(mdict, def->m_base.m_copy))
return NULL;
}
else {
if (def->m_base.m_init == NULL)
return NULL;
mod = def->m_base.m_init();
if (mod == NULL)
return NULL;
if (PyDict_SetItem(PyImport_GetModuleDict(), name, mod) == -1) {
Py_DECREF(mod);
return NULL;
}
Py_DECREF(mod);
}
if (_PyState_AddModule(mod, def) < 0) {
PyDict_DelItem(PyImport_GetModuleDict(), name);
Py_DECREF(mod);
return NULL;
}
if (Py_VerboseFlag)
PySys_FormatStderr("import %U # previously loaded (%R)\n",
name, filename);
return mod;
}
PyObject *
_PyImport_FindBuiltin(const char *name)
{
PyObject *res, *nameobj;
nameobj = PyUnicode_InternFromString(name);
if (nameobj == NULL)
return NULL;
res = _PyImport_FindExtensionObject(nameobj, nameobj);
Py_DECREF(nameobj);
return res;
}
/* Get the module object corresponding to a module name.
First check the modules dictionary if there's one there,
if not, create a new one and insert it in the modules dictionary.
Because the former action is most common, THIS DOES NOT RETURN A
'NEW' REFERENCE! */
PyObject *
PyImport_AddModuleObject(PyObject *name)
{
PyObject *modules = PyImport_GetModuleDict();
PyObject *m;
if ((m = PyDict_GetItem(modules, name)) != NULL &&
PyModule_Check(m))
return m;
m = PyModule_NewObject(name);
if (m == NULL)
return NULL;
if (PyDict_SetItem(modules, name, m) != 0) {
Py_DECREF(m);
return NULL;
}
Py_DECREF(m); /* Yes, it still exists, in modules! */
return m;
}
PyObject *
PyImport_AddModule(const char *name)
{
PyObject *nameobj, *module;
nameobj = PyUnicode_FromString(name);
if (nameobj == NULL)
return NULL;
module = PyImport_AddModuleObject(nameobj);
Py_DECREF(nameobj);
return module;
}
/* Remove name from sys.modules, if it's there. */
static void
remove_module(PyObject *name)
{
PyObject *modules = PyImport_GetModuleDict();
if (PyDict_GetItem(modules, name) == NULL)
return;
if (PyDict_DelItem(modules, name) < 0)
Py_FatalError("import: deleting existing key in"
"sys.modules failed");
}
/* Execute a code object in a module and return the module object
* WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
* removed from sys.modules, to avoid leaving damaged module objects
* in sys.modules. The caller may wish to restore the original
* module object (if any) in this case; PyImport_ReloadModule is an
* example.
*
* Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
* interface. The other two exist primarily for backward compatibility.
*/
PyObject *
PyImport_ExecCodeModule(const char *name, PyObject *co)
{
return PyImport_ExecCodeModuleWithPathnames(
name, co, (char *)NULL, (char *)NULL);
}
PyObject *
PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
{
return PyImport_ExecCodeModuleWithPathnames(
name, co, pathname, (char *)NULL);
}
PyObject *
PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
const char *pathname,
const char *cpathname)
{
PyObject *m = NULL;
PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
nameobj = PyUnicode_FromString(name);
if (nameobj == NULL)
return NULL;
if (cpathname != NULL) {
cpathobj = PyUnicode_DecodeFSDefault(cpathname);
if (cpathobj == NULL)
goto error;
}
else
cpathobj = NULL;
if (pathname != NULL) {
pathobj = PyUnicode_DecodeFSDefault(pathname);
if (pathobj == NULL)
goto error;
}
else if (cpathobj != NULL) {
PyInterpreterState *interp = PyThreadState_GET()->interp;
_Py_IDENTIFIER(_get_sourcefile);
if (interp == NULL) {
Py_FatalError("PyImport_ExecCodeModuleWithPathnames: "
"no interpreter!");
}
external= PyObject_GetAttrString(interp->importlib,
"_bootstrap_external");
if (external != NULL) {
pathobj = _PyObject_CallMethodIdObjArgs(external,
&PyId__get_sourcefile, cpathobj,
NULL);
Py_DECREF(external);
}
if (pathobj == NULL)
PyErr_Clear();
}
else
pathobj = NULL;
m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
error:
Py_DECREF(nameobj);
Py_XDECREF(pathobj);
Py_XDECREF(cpathobj);
return m;
}
static PyObject *
module_dict_for_exec(PyObject *name)
{
PyObject *m, *d = NULL;
m = PyImport_AddModuleObject(name);
if (m == NULL)
return NULL;
/* If the module is being reloaded, we get the old module back
and re-use its dict to exec the new code. */
d = PyModule_GetDict(m);
if (PyDict_GetItemString(d, "__builtins__") == NULL) {
if (PyDict_SetItemString(d, "__builtins__",
PyEval_GetBuiltins()) != 0) {
remove_module(name);
return NULL;
}
}
return d; /* Return a borrowed reference. */
}
static PyObject *
exec_code_in_module(PyObject *name, PyObject *module_dict, PyObject *code_object)
{
PyObject *modules = PyImport_GetModuleDict();
PyObject *v, *m;
v = PyEval_EvalCode(code_object, module_dict, module_dict);
if (v == NULL) {
remove_module(name);
return NULL;
}
Py_DECREF(v);
if ((m = PyDict_GetItem(modules, name)) == NULL) {
PyErr_Format(PyExc_ImportError,
"Loaded module %R not found in sys.modules",
name);
return NULL;
}
Py_INCREF(m);
return m;
}
PyObject*
PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
PyObject *cpathname)
{
PyObject *d, *external, *res;
PyInterpreterState *interp = PyThreadState_GET()->interp;
_Py_IDENTIFIER(_fix_up_module);
d = module_dict_for_exec(name);
if (d == NULL) {
return NULL;
}
if (pathname == NULL) {
pathname = ((PyCodeObject *)co)->co_filename;
}
external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
if (external == NULL)
return NULL;
res = _PyObject_CallMethodIdObjArgs(external,
&PyId__fix_up_module,
d, name, pathname, cpathname, NULL);
Py_DECREF(external);
if (res != NULL) {
Py_DECREF(res);
res = exec_code_in_module(name, d, co);
}
return res;
}
static void
update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
{
PyObject *constants, *tmp;
Py_ssize_t i, n;
if (PyUnicode_Compare(co->co_filename, oldname))
return;
tmp = co->co_filename;
co->co_filename = newname;
Py_INCREF(co->co_filename);
Py_DECREF(tmp);
constants = co->co_consts;
n = PyTuple_GET_SIZE(constants);
for (i = 0; i < n; i++) {
tmp = PyTuple_GET_ITEM(constants, i);
if (PyCode_Check(tmp))
update_code_filenames((PyCodeObject *)tmp,
oldname, newname);
}
}
static void
update_compiled_module(PyCodeObject *co, PyObject *newname)
{
PyObject *oldname;
if (PyUnicode_Compare(co->co_filename, newname) == 0)
return;
oldname = co->co_filename;
Py_INCREF(oldname);
update_code_filenames(co, oldname, newname);
Py_DECREF(oldname);
}
/*[clinic input]
_imp._fix_co_filename
code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
Code object to change.
path: unicode
File path to use.
/
Changes code.co_filename to specify the passed-in file path.
[clinic start generated code]*/
static PyObject *
_imp__fix_co_filename_impl(PyModuleDef *module, PyCodeObject *code,
PyObject *path)
/*[clinic end generated code: output=f4db56aac0a1327f input=895ba50e78b82f05]*/
{
update_compiled_module(code, path);
Py_RETURN_NONE;
}
/* Forward */
static const struct _frozen * find_frozen(PyObject *);
/* Helper to test for built-in module */
static int
is_builtin(PyObject *name)
{
int i, cmp;
for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
cmp = PyUnicode_CompareWithASCIIString(name, PyImport_Inittab[i].name);
if (cmp == 0) {
if (PyImport_Inittab[i].initfunc == NULL)
return -1;
else
return 1;
}
}
return 0;
}
/* Return an importer object for a sys.path/pkg.__path__ item 'p',
possibly by fetching it from the path_importer_cache dict. If it
wasn't yet cached, traverse path_hooks until a hook is found
that can handle the path item. Return None if no hook could;
this tells our caller it should fall back to the builtin
import mechanism. Cache the result in path_importer_cache.
Returns a borrowed reference. */
static PyObject *
get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
PyObject *p)
{
PyObject *importer;
Py_ssize_t j, nhooks;
/* These conditions are the caller's responsibility: */
assert(PyList_Check(path_hooks));
assert(PyDict_Check(path_importer_cache));
nhooks = PyList_Size(path_hooks);
if (nhooks < 0)
return NULL; /* Shouldn't happen */
importer = PyDict_GetItem(path_importer_cache, p);
if (importer != NULL)
return importer;
/* set path_importer_cache[p] to None to avoid recursion */
if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
return NULL;
for (j = 0; j < nhooks; j++) {
PyObject *hook = PyList_GetItem(path_hooks, j);
if (hook == NULL)
return NULL;
importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
if (importer != NULL)
break;
if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
return NULL;
}