-
-
Notifications
You must be signed in to change notification settings - Fork 34.2k
Expand file tree
/
Copy pathmoduleobject.c
More file actions
1815 lines (1665 loc) · 56.1 KB
/
moduleobject.c
File metadata and controls
1815 lines (1665 loc) · 56.1 KB
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 object implementation */
#include "Python.h"
#include "pycore_call.h" // _PyObject_CallNoArgs()
#include "pycore_ceval.h" // _PyEval_EnableGILTransient()
#include "pycore_dict.h" // _PyDict_EnablePerThreadRefcounting()
#include "pycore_fileutils.h" // _Py_wgetcwd
#include "pycore_import.h" // _PyImport_GetNextModuleIndex()
#include "pycore_interp.h" // PyInterpreterState.importlib
#include "pycore_lazyimportobject.h" // _PyLazyImportObject_Check()
#include "pycore_long.h" // _PyLong_GetOne()
#include "pycore_modsupport.h" // _PyModule_CreateInitialized()
#include "pycore_moduleobject.h" // _PyModule_GetDefOrNull()
#include "pycore_object.h" // _PyType_AllocNoTrack
#include "pycore_pyerrors.h" // _PyErr_FormatFromCause()
#include "pycore_pystate.h" // _PyInterpreterState_GET()
#include "pycore_unicodeobject.h" // _PyUnicode_EqualToASCIIString()
#include "pycore_weakref.h" // FT_CLEAR_WEAKREFS()
#include "osdefs.h" // MAXPATHLEN
#define _PyModule_CAST(op) \
(assert(PyModule_Check(op)), _Py_CAST(PyModuleObject*, (op)))
static PyMemberDef module_members[] = {
{"__dict__", _Py_T_OBJECT, offsetof(PyModuleObject, md_dict), Py_READONLY},
{0}
};
static void
assert_def_missing_or_redundant(PyModuleObject *m)
{
/* We copy all relevant info into the module object.
* Modules created using a def keep a reference to that (statically
* allocated) def; the info there should match what we have in the module.
*/
#ifndef NDEBUG
if (m->md_token_is_def) {
PyModuleDef *def = (PyModuleDef *)m->md_token;
assert(def);
#define DO_ASSERT(F) assert (def->m_ ## F == m->md_state_ ## F);
DO_ASSERT(size);
DO_ASSERT(traverse);
DO_ASSERT(clear);
DO_ASSERT(free);
#undef DO_ASSERT
}
#endif // NDEBUG
}
PyTypeObject PyModuleDef_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"moduledef", /* tp_name */
sizeof(PyModuleDef), /* tp_basicsize */
0, /* tp_itemsize */
};
int
_PyModule_IsExtension(PyObject *obj)
{
if (!PyModule_Check(obj)) {
return 0;
}
PyModuleObject *module = (PyModuleObject*)obj;
if (module->md_exec) {
return 1;
}
if (module->md_token_is_def) {
PyModuleDef *def = (PyModuleDef *)module->md_token;
return (module->md_token_is_def && def->m_methods != NULL);
}
return 0;
}
PyObject*
PyModuleDef_Init(PyModuleDef* def)
{
#ifdef Py_GIL_DISABLED
// Check that this def does not come from a non-free-threading ABI.
//
// This is meant as a "sanity check"; users should never rely on it.
// In particular, if we run out of ob_flags bits, or otherwise need to
// change some of the internals, this check can go away. Still, it
// would be nice to keep it for the free-threading transition.
//
// A PyModuleDef must be initialized with PyModuleDef_HEAD_INIT,
// which (via PyObject_HEAD_INIT) sets _Py_STATICALLY_ALLOCATED_FLAG
// and not _Py_LEGACY_ABI_CHECK_FLAG. For PyModuleDef, these flags never
// change.
// This means that the lower nibble of a valid PyModuleDef's ob_flags is
// always `_10_` (in binary; `_` is don't care).
//
// So, a check for these bits won't reject valid PyModuleDef.
// Rejecting incompatible extensions is slightly less important; here's
// how that works:
//
// In the pre-free-threading stable ABI, PyModuleDef_HEAD_INIT is big
// enough to overlap with free-threading ABI's ob_flags, is all zeros
// except for the refcount field.
// The refcount field can be:
// - 1 (3.11 and below)
// - UINT_MAX >> 2 (32-bit 3.12 & 3.13)
// - UINT_MAX (64-bit 3.12 & 3.13)
// - 7L << 28 (3.14)
//
// This means that the lower nibble of *any byte* in PyModuleDef_HEAD_INIT
// is not `_10_` -- it can be:
// - 0b0000
// - 0b0001
// - 0b0011 (from UINT_MAX >> 2)
// - 0b0111 (from 7L << 28)
// - 0b1111 (e.g. from UINT_MAX)
// (The values may change at runtime as the PyModuleDef is used, but
// PyModuleDef_Init is required before using the def as a Python object,
// so we check at least once with the initial values.
uint16_t flags = ((PyObject*)def)->ob_flags;
uint16_t bits = _Py_STATICALLY_ALLOCATED_FLAG | _Py_LEGACY_ABI_CHECK_FLAG;
if ((flags & bits) != _Py_STATICALLY_ALLOCATED_FLAG) {
const char *message = "invalid PyModuleDef, extension possibly "
"compiled for non-free-threaded Python";
// Write the error as unraisable: if the extension tries calling
// any API, it's likely to segfault and lose the exception.
PyErr_SetString(PyExc_SystemError, message);
PyErr_WriteUnraisable(NULL);
// But also raise the exception normally -- this is technically
// a recoverable state.
PyErr_SetString(PyExc_SystemError, message);
return NULL;
}
#endif
assert(PyModuleDef_Type.tp_flags & Py_TPFLAGS_READY);
if (def->m_base.m_index == 0) {
Py_SET_REFCNT(def, 1);
Py_SET_TYPE(def, &PyModuleDef_Type);
def->m_base.m_index = _PyImport_GetNextModuleIndex();
}
return (PyObject*)def;
}
static int
module_init_dict(PyModuleObject *mod, PyObject *md_dict,
PyObject *name, PyObject *doc)
{
assert(md_dict != NULL);
if (doc == NULL)
doc = Py_None;
if (PyDict_SetItem(md_dict, &_Py_ID(__name__), name) != 0)
return -1;
if (PyDict_SetItem(md_dict, &_Py_ID(__doc__), doc) != 0)
return -1;
if (PyDict_SetItem(md_dict, &_Py_ID(__package__), Py_None) != 0)
return -1;
if (PyDict_SetItem(md_dict, &_Py_ID(__loader__), Py_None) != 0)
return -1;
if (PyDict_SetItem(md_dict, &_Py_ID(__spec__), Py_None) != 0)
return -1;
if (PyUnicode_CheckExact(name)) {
Py_XSETREF(mod->md_name, Py_NewRef(name));
}
return 0;
}
static PyModuleObject *
new_module_notrack(PyTypeObject *mt)
{
PyModuleObject *m;
m = (PyModuleObject *)_PyType_AllocNoTrack(mt, 0);
if (m == NULL)
return NULL;
m->md_state = NULL;
m->md_weaklist = NULL;
m->md_name = NULL;
m->md_token_is_def = false;
#ifdef Py_GIL_DISABLED
m->md_requires_gil = true;
#endif
m->md_state_size = 0;
m->md_state_traverse = NULL;
m->md_state_clear = NULL;
m->md_state_free = NULL;
m->md_exec = NULL;
m->md_token = NULL;
m->md_dict = PyDict_New();
if (m->md_dict == NULL) {
Py_DECREF(m);
return NULL;
}
return m;
}
/* Module dict watcher callback.
* When a module dictionary is modified, we need to clear the keys version
* to invalidate any cached lookups that depend on the dictionary structure.
*/
static int
module_dict_watcher(PyDict_WatchEvent event, PyObject *dict,
PyObject *key, PyObject *new_value)
{
assert(PyDict_Check(dict));
// Only if a new lazy object shows up do we need to clear the dictionary. If
// this is adding a new key then the version will be reset anyway.
if (event == PyDict_EVENT_MODIFIED &&
new_value != NULL &&
PyLazyImport_CheckExact(new_value)) {
_PyDict_ClearKeysVersionLockHeld(dict);
}
return 0;
}
int
_PyModule_InitModuleDictWatcher(PyInterpreterState *interp)
{
// This is a reserved watcher for CPython so there's no need to check for non-NULL.
assert(interp->dict_state.watchers[MODULE_WATCHER_ID] == NULL);
interp->dict_state.watchers[MODULE_WATCHER_ID] = &module_dict_watcher;
return 0;
}
static void
track_module(PyModuleObject *m)
{
_PyDict_EnablePerThreadRefcounting(m->md_dict);
_PyObject_SetDeferredRefcount((PyObject *)m);
PyDict_Watch(MODULE_WATCHER_ID, m->md_dict);
PyObject_GC_Track(m);
}
static PyObject *
new_module(PyTypeObject *mt, PyObject *args, PyObject *kws)
{
PyModuleObject *m = new_module_notrack(mt);
if (m != NULL) {
track_module(m);
}
return (PyObject *)m;
}
PyObject *
PyModule_NewObject(PyObject *name)
{
PyModuleObject *m = new_module_notrack(&PyModule_Type);
if (m == NULL)
return NULL;
if (module_init_dict(m, m->md_dict, name, NULL) != 0)
goto fail;
track_module(m);
return (PyObject *)m;
fail:
Py_DECREF(m);
return NULL;
}
PyObject *
PyModule_New(const char *name)
{
PyObject *nameobj, *module;
nameobj = PyUnicode_FromString(name);
if (nameobj == NULL)
return NULL;
module = PyModule_NewObject(nameobj);
Py_DECREF(nameobj);
return module;
}
/* Check API/ABI version
* Issues a warning on mismatch, which is usually not fatal.
* Returns 0 if an exception is raised.
*/
static int
check_api_version(const char *name, int module_api_version)
{
if (module_api_version != PYTHON_API_VERSION && module_api_version != PYTHON_ABI_VERSION) {
int err;
err = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
"Python C API version mismatch for module %.100s: "
"This Python has API version %d, module %.100s has version %d.",
name,
PYTHON_API_VERSION, name, module_api_version);
if (err)
return 0;
}
return 1;
}
static int
_add_methods_to_object(PyObject *module, PyObject *name, PyMethodDef *functions)
{
PyObject *func;
PyMethodDef *fdef;
for (fdef = functions; fdef->ml_name != NULL; fdef++) {
if ((fdef->ml_flags & METH_CLASS) ||
(fdef->ml_flags & METH_STATIC)) {
PyErr_SetString(PyExc_ValueError,
"module functions cannot set"
" METH_CLASS or METH_STATIC");
return -1;
}
func = PyCFunction_NewEx(fdef, (PyObject*)module, name);
if (func == NULL) {
return -1;
}
_PyObject_SetDeferredRefcount(func);
if (PyObject_SetAttrString(module, fdef->ml_name, func) != 0) {
Py_DECREF(func);
return -1;
}
Py_DECREF(func);
}
return 0;
}
PyObject *
PyModule_Create2(PyModuleDef* module, int module_api_version)
{
if (!_PyImport_IsInitialized(_PyInterpreterState_GET())) {
PyErr_SetString(PyExc_SystemError,
"Python import machinery not initialized");
return NULL;
}
return _PyModule_CreateInitialized(module, module_api_version);
}
static void
module_copy_members_from_deflike(
PyModuleObject *md,
PyModuleDef *def_like /* not necessarily a valid Python object */)
{
md->md_state_size = def_like->m_size;
md->md_state_traverse = def_like->m_traverse;
md->md_state_clear = def_like->m_clear;
md->md_state_free = def_like->m_free;
}
PyObject *
_PyModule_CreateInitialized(PyModuleDef* module, int module_api_version)
{
const char* name;
PyModuleObject *m;
if (!PyModuleDef_Init(module))
return NULL;
name = module->m_name;
if (!check_api_version(name, module_api_version)) {
return NULL;
}
if (module->m_slots) {
PyErr_Format(
PyExc_SystemError,
"module %s: PyModule_Create is incompatible with m_slots", name);
return NULL;
}
name = _PyImport_ResolveNameWithPackageContext(name);
m = (PyModuleObject*)PyModule_New(name);
if (m == NULL)
return NULL;
if (module->m_size > 0) {
m->md_state = PyMem_Malloc(module->m_size);
if (!m->md_state) {
PyErr_NoMemory();
Py_DECREF(m);
return NULL;
}
memset(m->md_state, 0, module->m_size);
}
if (module->m_methods != NULL) {
if (PyModule_AddFunctions((PyObject *) m, module->m_methods) != 0) {
Py_DECREF(m);
return NULL;
}
}
if (module->m_doc != NULL) {
if (PyModule_SetDocString((PyObject *) m, module->m_doc) != 0) {
Py_DECREF(m);
return NULL;
}
}
m->md_token = module;
m->md_token_is_def = true;
module_copy_members_from_deflike(m, module);
#ifdef Py_GIL_DISABLED
m->md_requires_gil = true;
#endif
return (PyObject*)m;
}
static PyObject *
module_from_def_and_spec(
PyModuleDef* def_like, /* not necessarily a valid Python object */
PyObject *spec,
int module_api_version,
PyModuleDef* original_def /* NULL if not defined by a def */)
{
PyModuleDef_Slot* cur_slot;
PyObject *(*create)(PyObject *, PyModuleDef*) = NULL;
PyObject *nameobj;
PyObject *m = NULL;
int has_multiple_interpreters_slot = 0;
void *multiple_interpreters = (void *)0;
int has_gil_slot = 0;
bool requires_gil = true;
int has_execution_slots = 0;
const char *name;
int ret;
void *token = NULL;
_Py_modexecfunc m_exec = NULL;
PyInterpreterState *interp = _PyInterpreterState_GET();
nameobj = PyObject_GetAttrString(spec, "name");
if (nameobj == NULL) {
return NULL;
}
name = PyUnicode_AsUTF8(nameobj);
if (name == NULL) {
goto error;
}
if (!check_api_version(name, module_api_version)) {
goto error;
}
if (def_like->m_size < 0) {
PyErr_Format(
PyExc_SystemError,
"module %s: m_size may not be negative for multi-phase initialization",
name);
goto error;
}
bool seen_m_name_slot = false;
bool seen_m_doc_slot = false;
bool seen_m_size_slot = false;
bool seen_m_methods_slot = false;
bool seen_m_traverse_slot = false;
bool seen_m_clear_slot = false;
bool seen_m_free_slot = false;
for (cur_slot = def_like->m_slots; cur_slot && cur_slot->slot; cur_slot++) {
// Macro to copy a non-NULL, non-repeatable slot.
#define COPY_NONNULL_SLOT(SLOTNAME, TYPE, DEST) \
do { \
if (!(TYPE)(cur_slot->value)) { \
PyErr_Format( \
PyExc_SystemError, \
"module %s: %s must not be NULL", \
name, SLOTNAME); \
goto error; \
} \
DEST = (TYPE)(cur_slot->value); \
} while (0); \
/////////////////////////////////////////////////////////////////
// Macro to copy a non-NULL, non-repeatable slot to def_like.
#define COPY_DEF_SLOT(SLOTNAME, TYPE, MEMBER) \
do { \
if (seen_ ## MEMBER ## _slot) { \
PyErr_Format( \
PyExc_SystemError, \
"module %s has more than one %s slot", \
name, SLOTNAME); \
goto error; \
} \
seen_ ## MEMBER ## _slot = true; \
if (original_def) { \
TYPE orig_value = (TYPE)original_def->MEMBER; \
TYPE new_value = (TYPE)cur_slot->value; \
if (orig_value != new_value) { \
PyErr_Format( \
PyExc_SystemError, \
"module %s: %s conflicts with " \
"PyModuleDef." #MEMBER, \
name, SLOTNAME); \
goto error; \
} \
} \
COPY_NONNULL_SLOT(SLOTNAME, TYPE, (def_like->MEMBER)) \
} while (0); \
/////////////////////////////////////////////////////////////////
// Macro to copy a non-NULL, non-repeatable slot without a
// corresponding PyModuleDef member.
// DEST must be initially NULL (so we don't need a seen_* flag).
#define COPY_NONDEF_SLOT(SLOTNAME, TYPE, DEST) \
do { \
if (DEST) { \
PyErr_Format( \
PyExc_SystemError, \
"module %s has more than one %s slot", \
name, SLOTNAME); \
goto error; \
} \
COPY_NONNULL_SLOT(SLOTNAME, TYPE, DEST) \
} while (0); \
/////////////////////////////////////////////////////////////////
// Define the whole common case
#define DEF_SLOT_CASE(SLOT, TYPE, MEMBER) \
case SLOT: \
COPY_DEF_SLOT(#SLOT, TYPE, MEMBER); \
break; \
/////////////////////////////////////////////////////////////////
switch (cur_slot->slot) {
case Py_mod_create:
if (create) {
PyErr_Format(
PyExc_SystemError,
"module %s has multiple create slots",
name);
goto error;
}
create = cur_slot->value;
break;
case Py_mod_exec:
has_execution_slots = 1;
if (!original_def) {
COPY_NONDEF_SLOT("Py_mod_exec", _Py_modexecfunc, m_exec);
}
break;
case Py_mod_multiple_interpreters:
if (has_multiple_interpreters_slot) {
PyErr_Format(
PyExc_SystemError,
"module %s has more than one 'multiple interpreters' "
"slots",
name);
goto error;
}
multiple_interpreters = cur_slot->value;
has_multiple_interpreters_slot = 1;
break;
case Py_mod_gil:
if (has_gil_slot) {
PyErr_Format(
PyExc_SystemError,
"module %s has more than one 'gil' slot",
name);
goto error;
}
requires_gil = (cur_slot->value != Py_MOD_GIL_NOT_USED);
has_gil_slot = 1;
break;
case Py_mod_abi:
if (PyABIInfo_Check((PyABIInfo *)cur_slot->value, name) < 0) {
goto error;
}
break;
DEF_SLOT_CASE(Py_mod_name, char*, m_name)
DEF_SLOT_CASE(Py_mod_doc, char*, m_doc)
DEF_SLOT_CASE(Py_mod_state_size, Py_ssize_t, m_size)
DEF_SLOT_CASE(Py_mod_methods, PyMethodDef*, m_methods)
DEF_SLOT_CASE(Py_mod_state_traverse, traverseproc, m_traverse)
DEF_SLOT_CASE(Py_mod_state_clear, inquiry, m_clear)
DEF_SLOT_CASE(Py_mod_state_free, freefunc, m_free)
case Py_mod_token:
if (original_def && original_def != cur_slot->value) {
PyErr_Format(
PyExc_SystemError,
"module %s: arbitrary Py_mod_token not "
"allowed with PyModuleDef",
name);
goto error;
}
COPY_NONDEF_SLOT("Py_mod_token", void*, token);
break;
default:
assert(cur_slot->slot < 0 || cur_slot->slot > _Py_mod_LAST_SLOT);
PyErr_Format(
PyExc_SystemError,
"module %s uses unknown slot ID %i",
name, cur_slot->slot);
goto error;
}
#undef DEF_SLOT_CASE
#undef COPY_DEF_SLOT
#undef COPY_NONDEF_SLOT
#undef COPY_NONNULL_SLOT
}
#ifdef Py_GIL_DISABLED
// For modules created directly from slots (not from a def), we enable
// the GIL here (pairing `_PyEval_EnableGILTransient` with
// an immediate `_PyImport_EnableGILAndWarn`).
// For modules created from a def, the caller is responsible for this.
if (!original_def && requires_gil) {
PyThreadState *tstate = _PyThreadState_GET();
if (_PyEval_EnableGILTransient(tstate) < 0) {
goto error;
}
if (_PyImport_EnableGILAndWarn(tstate, nameobj) < 0) {
goto error;
}
}
#endif
/* By default, multi-phase init modules are expected
to work under multiple interpreters. */
if (!has_multiple_interpreters_slot) {
multiple_interpreters = Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED;
}
if (multiple_interpreters == Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED) {
if (!_Py_IsMainInterpreter(interp)
&& _PyImport_CheckSubinterpIncompatibleExtensionAllowed(name) < 0)
{
goto error;
}
}
else if (multiple_interpreters != Py_MOD_PER_INTERPRETER_GIL_SUPPORTED
&& interp->ceval.own_gil
&& !_Py_IsMainInterpreter(interp)
&& _PyImport_CheckSubinterpIncompatibleExtensionAllowed(name) < 0)
{
goto error;
}
if (create) {
m = create(spec, original_def);
if (m == NULL) {
if (!PyErr_Occurred()) {
PyErr_Format(
PyExc_SystemError,
"creation of module %s failed without setting an exception",
name);
}
goto error;
} else {
if (PyErr_Occurred()) {
_PyErr_FormatFromCause(
PyExc_SystemError,
"creation of module %s raised unreported exception",
name);
goto error;
}
}
} else {
m = PyModule_NewObject(nameobj);
if (m == NULL) {
goto error;
}
}
if (PyModule_Check(m)) {
PyModuleObject *mod = (PyModuleObject*)m;
mod->md_state = NULL;
module_copy_members_from_deflike(mod, def_like);
if (original_def) {
assert (!token || token == original_def);
mod->md_token = original_def;
mod->md_token_is_def = 1;
}
else {
mod->md_token = token;
}
#ifdef Py_GIL_DISABLED
mod->md_requires_gil = requires_gil;
#else
(void)requires_gil;
#endif
mod->md_exec = m_exec;
} else {
if (def_like->m_size > 0 || def_like->m_traverse || def_like->m_clear
|| def_like->m_free)
{
PyErr_Format(
PyExc_SystemError,
"module %s is not a module object, but requests module state",
name);
goto error;
}
if (has_execution_slots) {
PyErr_Format(
PyExc_SystemError,
"module %s specifies execution slots, but did not create "
"a ModuleType instance",
name);
goto error;
}
if (token) {
PyErr_Format(
PyExc_SystemError,
"module %s specifies a token, but did not create "
"a ModuleType instance",
name);
goto error;
}
}
if (def_like->m_methods != NULL) {
ret = _add_methods_to_object(m, nameobj, def_like->m_methods);
if (ret != 0) {
goto error;
}
}
if (def_like->m_doc != NULL) {
ret = PyModule_SetDocString(m, def_like->m_doc);
if (ret != 0) {
goto error;
}
}
Py_DECREF(nameobj);
return m;
error:
Py_DECREF(nameobj);
Py_XDECREF(m);
return NULL;
}
PyObject *
PyModule_FromDefAndSpec2(PyModuleDef* def, PyObject *spec, int module_api_version)
{
PyModuleDef_Init(def);
return module_from_def_and_spec(def, spec, module_api_version, def);
}
PyObject *
PyModule_FromSlotsAndSpec(const PyModuleDef_Slot *slots, PyObject *spec)
{
if (!slots) {
PyErr_SetString(
PyExc_SystemError,
"PyModule_FromSlotsAndSpec called with NULL slots");
return NULL;
}
// Fill in enough of a PyModuleDef to pass to common machinery
PyModuleDef def_like = {.m_slots = (PyModuleDef_Slot *)slots};
return module_from_def_and_spec(&def_like, spec, PYTHON_API_VERSION,
NULL);
}
#ifdef Py_GIL_DISABLED
int
PyUnstable_Module_SetGIL(PyObject *module, void *gil)
{
bool requires_gil = (gil != Py_MOD_GIL_NOT_USED);
if (!PyModule_Check(module)) {
PyErr_BadInternalCall();
return -1;
}
((PyModuleObject *)module)->md_requires_gil = requires_gil;
return 0;
}
#endif
static int
run_exec_func(PyObject *module, int (*exec)(PyObject *))
{
int ret = exec(module);
if (ret != 0) {
if (!PyErr_Occurred()) {
PyErr_Format(
PyExc_SystemError,
"execution of %R failed without setting an exception",
module);
}
return -1;
}
if (PyErr_Occurred()) {
_PyErr_FormatFromCause(
PyExc_SystemError,
"execution of module %R raised unreported exception",
module);
return -1;
}
return 0;
}
static int
alloc_state(PyObject *module)
{
if (!PyModule_Check(module)) {
PyErr_Format(PyExc_TypeError, "expected module, got %T", module);
return -1;
}
PyModuleObject *md = (PyModuleObject*)module;
if (md->md_state_size >= 0) {
if (md->md_state == NULL) {
/* Always set a state pointer; this serves as a marker to skip
* multiple initialization (importlib.reload() is no-op) */
md->md_state = PyMem_Malloc(md->md_state_size);
if (!md->md_state) {
PyErr_NoMemory();
return -1;
}
memset(md->md_state, 0, md->md_state_size);
}
}
return 0;
}
int
PyModule_Exec(PyObject *module)
{
if (alloc_state(module) < 0) {
return -1;
}
PyModuleObject *md = (PyModuleObject*)module;
if (md->md_exec) {
assert(!md->md_token_is_def);
return run_exec_func(module, md->md_exec);
}
PyModuleDef *def = _PyModule_GetDefOrNull(module);
if (def) {
return PyModule_ExecDef(module, def);
}
return 0;
}
int
PyModule_ExecDef(PyObject *module, PyModuleDef *def)
{
PyModuleDef_Slot *cur_slot;
if (alloc_state(module) < 0) {
return -1;
}
assert(PyModule_Check(module));
if (def->m_slots == NULL) {
return 0;
}
for (cur_slot = def->m_slots; cur_slot && cur_slot->slot; cur_slot++) {
if (cur_slot->slot == Py_mod_exec) {
int (*func)(PyObject *) = cur_slot->value;
if (run_exec_func(module, func) < 0) {
return -1;
}
continue;
}
}
return 0;
}
int
PyModule_AddFunctions(PyObject *m, PyMethodDef *functions)
{
int res;
PyObject *name = PyModule_GetNameObject(m);
if (name == NULL) {
return -1;
}
res = _add_methods_to_object(m, name, functions);
Py_DECREF(name);
return res;
}
int
PyModule_SetDocString(PyObject *m, const char *doc)
{
PyObject *v;
v = PyUnicode_FromString(doc);
if (v == NULL || PyObject_SetAttr(m, &_Py_ID(__doc__), v) != 0) {
Py_XDECREF(v);
return -1;
}
Py_DECREF(v);
return 0;
}
PyObject *
PyModule_GetDict(PyObject *m)
{
if (!PyModule_Check(m)) {
PyErr_BadInternalCall();
return NULL;
}
return _PyModule_GetDict(m); // borrowed reference
}
int
PyModule_GetStateSize(PyObject *m, Py_ssize_t *size_p)
{
*size_p = -1;
if (!PyModule_Check(m)) {
PyErr_Format(PyExc_TypeError, "expected module, got %T", m);
return -1;
}
PyModuleObject *mod = (PyModuleObject *)m;
*size_p = mod->md_state_size;
return 0;
}
int
PyModule_GetToken(PyObject *m, void **token_p)
{
*token_p = NULL;
if (!PyModule_Check(m)) {
PyErr_Format(PyExc_TypeError, "expected module, got %T", m);
return -1;
}
*token_p = _PyModule_GetToken(m);
return 0;
}
PyObject*
PyModule_GetNameObject(PyObject *mod)
{
if (!PyModule_Check(mod)) {
PyErr_BadArgument();
return NULL;
}
PyObject *dict = ((PyModuleObject *)mod)->md_dict; // borrowed reference
if (dict == NULL || !PyDict_Check(dict)) {
goto error;
}
PyObject *name;
if (PyDict_GetItemRef(dict, &_Py_ID(__name__), &name) <= 0) {
// error or not found
goto error;
}
if (!PyUnicode_Check(name)) {
Py_DECREF(name);
goto error;
}
return name;
error:
if (!PyErr_Occurred()) {
PyErr_SetString(PyExc_SystemError, "nameless module");
}
return NULL;
}
const char *
PyModule_GetName(PyObject *m)
{
PyObject *name = PyModule_GetNameObject(m);
if (name == NULL) {
return NULL;
}
assert(Py_REFCNT(name) >= 2);
Py_DECREF(name); /* module dict has still a reference */
return PyUnicode_AsUTF8(name);
}
PyObject*
_PyModule_GetFilenameObject(PyObject *mod)
{
// We return None to indicate "not found" or "bogus".
if (!PyModule_Check(mod)) {
PyErr_BadArgument();
return NULL;
}
PyObject *dict = ((PyModuleObject *)mod)->md_dict; // borrowed reference
if (dict == NULL) {
// The module has been tampered with.
Py_RETURN_NONE;
}
PyObject *fileobj;
int res = PyDict_GetItemRef(dict, &_Py_ID(__file__), &fileobj);
if (res < 0) {
return NULL;
}
if (res == 0) {
// __file__ isn't set. There are several reasons why this might
// be so, most of them valid reasons. If it's the __main__
// module then we're running the REPL or with -c. Otherwise
// it's a namespace package or other module with a loader that
// isn't disk-based. It could also be that a user created
// a module manually but without manually setting __file__.
Py_RETURN_NONE;
}
if (!PyUnicode_Check(fileobj)) {
Py_DECREF(fileobj);
Py_RETURN_NONE;
}
return fileobj;
}
PyObject*
PyModule_GetFilenameObject(PyObject *mod)
{
PyObject *fileobj = _PyModule_GetFilenameObject(mod);
if (fileobj == NULL) {
return NULL;
}
if (fileobj == Py_None) {
PyErr_SetString(PyExc_SystemError, "module filename missing");
return NULL;
}