File size: 47,441 Bytes
a4edccc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
diff --git a/Include/exports.h b/Include/exports.h
index 0c646d5beb6..62feb09ed2b 100644
--- a/Include/exports.h
+++ b/Include/exports.h
@@ -9,6 +9,7 @@
                     inside the Python core, they are private to the core.
                     If in an extension module, it may be declared with
                     external linkage depending on the platform.
+  PyMODEXPORT_FUNC: Like PyMODINIT_FUNC, but for a slots array
 
   As a number of platforms support/require "__declspec(dllimport/dllexport)",
   we support a HAVE_DECLSPEC_DLL macro to save duplication.
@@ -62,9 +63,9 @@
         /* module init functions inside the core need no external linkage */
         /* except for Cygwin to handle embedding */
 #                       if defined(__CYGWIN__)
-#                               define PyMODINIT_FUNC Py_EXPORTED_SYMBOL PyObject*
+#                               define _PyINIT_FUNC_DECLSPEC Py_EXPORTED_SYMBOL
 #                       else /* __CYGWIN__ */
-#                               define PyMODINIT_FUNC PyObject*
+#                               define _PyINIT_FUNC_DECLSPEC
 #                       endif /* __CYGWIN__ */
 #               else /* Py_BUILD_CORE */
         /* Building an extension module, or an embedded situation */
@@ -78,9 +79,9 @@
 #                       define PyAPI_DATA(RTYPE) extern Py_IMPORTED_SYMBOL RTYPE
         /* module init functions outside the core must be exported */
 #                       if defined(__cplusplus)
-#                               define PyMODINIT_FUNC extern "C" Py_EXPORTED_SYMBOL PyObject*
+#                               define _PyINIT_FUNC_DECLSPEC extern "C" Py_EXPORTED_SYMBOL
 #                       else /* __cplusplus */
-#                               define PyMODINIT_FUNC Py_EXPORTED_SYMBOL PyObject*
+#                               define _PyINIT_FUNC_DECLSPEC Py_EXPORTED_SYMBOL
 #                       endif /* __cplusplus */
 #               endif /* Py_BUILD_CORE */
 #       endif /* HAVE_DECLSPEC_DLL */
@@ -93,13 +94,15 @@
 #ifndef PyAPI_DATA
 #       define PyAPI_DATA(RTYPE) extern Py_EXPORTED_SYMBOL RTYPE
 #endif
-#ifndef PyMODINIT_FUNC
+#ifndef _PyINIT_FUNC_DECLSPEC
 #       if defined(__cplusplus)
-#               define PyMODINIT_FUNC extern "C" Py_EXPORTED_SYMBOL PyObject*
+#               define _PyINIT_FUNC_DECLSPEC extern "C" Py_EXPORTED_SYMBOL
 #       else /* __cplusplus */
-#               define PyMODINIT_FUNC Py_EXPORTED_SYMBOL PyObject*
+#               define _PyINIT_FUNC_DECLSPEC Py_EXPORTED_SYMBOL
 #       endif /* __cplusplus */
 #endif
 
+#define PyMODINIT_FUNC _PyINIT_FUNC_DECLSPEC PyObject*
+#define PyMODEXPORT_FUNC _PyINIT_FUNC_DECLSPEC PyModuleDef_Slot*
 
 #endif /* Py_EXPORTS_H */
diff --git a/Include/internal/pycore_importdl.h b/Include/internal/pycore_importdl.h
index 3ba9229cc21..12a32a5f70e 100644
--- a/Include/internal/pycore_importdl.h
+++ b/Include/internal/pycore_importdl.h
@@ -28,6 +28,11 @@ typedef enum ext_module_origin {
     _Py_ext_module_origin_DYNAMIC = 3,
 } _Py_ext_module_origin;
 
+struct hook_prefixes {
+    const char *const init_prefix;
+    const char *const export_prefix;
+};
+
 /* Input for loading an extension module. */
 struct _Py_ext_module_loader_info {
     PyObject *filename;
@@ -40,7 +45,7 @@ struct _Py_ext_module_loader_info {
      * depending on if it's builtin or not. */
     PyObject *path;
     _Py_ext_module_origin origin;
-    const char *hook_prefix;
+    const struct hook_prefixes *hook_prefixes;
     const char *newcontext;
 };
 extern void _Py_ext_module_loader_info_clear(
@@ -62,7 +67,9 @@ extern int _Py_ext_module_loader_info_init_from_spec(
     PyObject *spec);
 #endif
 
-/* The result from running an extension module's init function. */
+/* The result from running an extension module's init function.
+ * Not used for modules defined via PyModExport (slots array).
+ */
 struct _Py_ext_module_loader_result {
     PyModuleDef *def;
     PyObject *module;
@@ -89,10 +96,11 @@ extern void _Py_ext_module_loader_result_apply_error(
 
 /* The module init function. */
 typedef PyObject *(*PyModInitFunction)(void);
+typedef PyModuleDef_Slot *(*PyModExportFunction)(void);
 #ifdef HAVE_DYNAMIC_LOADING
-extern PyModInitFunction _PyImport_GetModInitFunc(
+extern int _PyImport_GetModuleExportHooks(
     struct _Py_ext_module_loader_info *info,
-    FILE *fp);
+    FILE *fp, PyModInitFunction *modinit, PyModExportFunction *modexport);
 #endif
 extern int _PyImport_RunModInitFunc(
     PyModInitFunction p0,
diff --git a/Include/internal/pycore_moduleobject.h b/Include/internal/pycore_moduleobject.h
index b170d7bce70..c34e42e826e 100644
--- a/Include/internal/pycore_moduleobject.h
+++ b/Include/internal/pycore_moduleobject.h
@@ -1,5 +1,8 @@
 #ifndef Py_INTERNAL_MODULEOBJECT_H
 #define Py_INTERNAL_MODULEOBJECT_H
+
+#include <stdbool.h>
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -16,32 +19,49 @@ extern int _PyModule_IsPossiblyShadowing(PyObject *);
 
 extern int _PyModule_IsExtension(PyObject *obj);
 
+typedef int (*_Py_modexecfunc)(PyObject *);
+
 typedef struct {
     PyObject_HEAD
     PyObject *md_dict;
-    PyModuleDef *md_def;
     void *md_state;
     PyObject *md_weaklist;
     // for logging purposes after md_dict is cleared
     PyObject *md_name;
+    bool md_token_is_def;  /* if true, `md_token` is the PyModuleDef */
 #ifdef Py_GIL_DISABLED
     void *md_gil;
 #endif
+    Py_ssize_t md_state_size;
+    traverseproc md_state_traverse;
+    inquiry md_state_clear;
+    freefunc md_state_free;
+    void *md_token;
+    _Py_modexecfunc md_exec;  /* only set if md_token_is_def is true */
 } PyModuleObject;
 
-static inline PyModuleDef* _PyModule_GetDef(PyObject *mod) {
-    assert(PyModule_Check(mod));
-    return ((PyModuleObject *)mod)->md_def;
+#define _PyModule_CAST(op) \
+    (assert(PyModule_Check(op)), _Py_CAST(PyModuleObject*, (op)))
+
+static inline PyModuleDef *_PyModule_GetDefOrNull(PyObject *arg) {
+    PyModuleObject *mod = _PyModule_CAST(arg);
+    if (mod->md_token_is_def) {
+        return (PyModuleDef *)mod->md_token;
+    }
+    return NULL;
+}
+
+static inline PyModuleDef *_PyModule_GetToken(PyObject *arg) {
+    PyModuleObject *mod = _PyModule_CAST(arg);
+    return mod->md_token;
 }
 
 static inline void* _PyModule_GetState(PyObject* mod) {
-    assert(PyModule_Check(mod));
-    return ((PyModuleObject *)mod)->md_state;
+    return _PyModule_CAST(mod)->md_state;
 }
 
 static inline PyObject* _PyModule_GetDict(PyObject *mod) {
-    assert(PyModule_Check(mod));
-    PyObject *dict = ((PyModuleObject *)mod) -> md_dict;
+    PyObject *dict = _PyModule_CAST(mod)->md_dict;
     // _PyModule_GetDict(mod) must not be used after calling module_clear(mod)
     assert(dict != NULL);
     return dict;  // borrowed reference
diff --git a/Include/moduleobject.h b/Include/moduleobject.h
index e3afac0a343..e83bc395aa4 100644
--- a/Include/moduleobject.h
+++ b/Include/moduleobject.h
@@ -83,11 +83,19 @@ struct PyModuleDef_Slot {
 #endif
 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= _Py_PACK_VERSION(3, 15)
 #  define Py_mod_abi 5
+#  define Py_mod_name 6
+#  define Py_mod_doc 7
+#  define Py_mod_state_size 8
+#  define Py_mod_methods 9
+#  define Py_mod_state_traverse 10
+#  define Py_mod_state_clear 11
+#  define Py_mod_state_free 12
+#  define Py_mod_token 13
 #endif
 
 
 #ifndef Py_LIMITED_API
-#define _Py_mod_LAST_SLOT 5
+#define _Py_mod_LAST_SLOT 13
 #endif
 
 #endif /* New in 3.5 */
@@ -109,6 +117,13 @@ struct PyModuleDef_Slot {
 PyAPI_FUNC(int) PyUnstable_Module_SetGIL(PyObject *module, void *gil);
 #endif
 
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= _Py_PACK_VERSION(3, 15)
+PyAPI_FUNC(PyObject *) PyModule_FromSlotsAndSpec(const PyModuleDef_Slot *,
+                                                 PyObject *spec);
+PyAPI_FUNC(int) PyModule_Exec(PyObject *mod);
+PyAPI_FUNC(int) PyModule_GetStateSize(PyObject *mod, Py_ssize_t *result);
+PyAPI_FUNC(int) PyModule_GetToken(PyObject *, void **result);
+#endif
 
 #ifndef _Py_OPAQUE_PYOBJECT
 struct PyModuleDef {
diff --git a/Include/object.h b/Include/object.h
index 291e4f0a7ed..f17dcba4f47 100644
--- a/Include/object.h
+++ b/Include/object.h
@@ -839,6 +839,11 @@ PyAPI_FUNC(PyObject *) PyType_GetModuleByDef(PyTypeObject *, PyModuleDef *);
 PyAPI_FUNC(int) PyType_Freeze(PyTypeObject *type);
 #endif
 
+#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= _Py_PACK_VERSION(3, 15)
+PyAPI_FUNC(PyObject *) PyType_GetModuleByToken(PyTypeObject *type,
+                                               const void *token);
+#endif
+
 #ifdef __cplusplus
 }
 #endif
diff --git a/Objects/moduleobject.c b/Objects/moduleobject.c
index 0d45c117168..9dee03bdb5e 100644
--- a/Objects/moduleobject.c
+++ b/Objects/moduleobject.c
@@ -8,7 +8,7 @@
 #include "pycore_interp.h"        // PyInterpreterState.importlib
 #include "pycore_long.h"          // _PyLong_GetOne()
 #include "pycore_modsupport.h"    // _PyModule_CreateInitialized()
-#include "pycore_moduleobject.h"  // _PyModule_GetDef()
+#include "pycore_moduleobject.h"  // _PyModule_GetDefOrNull()
 #include "pycore_object.h"        // _PyType_AllocNoTrack
 #include "pycore_pyerrors.h"      // _PyErr_FormatFromCause()
 #include "pycore_pystate.h"       // _PyInterpreterState_GET()
@@ -27,6 +27,27 @@ static PyMemberDef module_members[] = {
     {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)
@@ -44,8 +65,14 @@ _PyModule_IsExtension(PyObject *obj)
     }
     PyModuleObject *module = (PyModuleObject*)obj;
 
-    PyModuleDef *def = module->md_def;
-    return (def != NULL && def->m_methods != NULL);
+    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;
 }
 
 
@@ -146,10 +173,19 @@ new_module_notrack(PyTypeObject *mt)
     m = (PyModuleObject *)_PyType_AllocNoTrack(mt, 0);
     if (m == NULL)
         return NULL;
-    m->md_def = 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_gil = Py_MOD_GIL_USED;
+#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);
@@ -264,6 +300,17 @@ PyModule_Create2(PyModuleDef* module, int module_api_version)
     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)
 {
@@ -310,15 +357,21 @@ _PyModule_CreateInitialized(PyModuleDef* module, int module_api_version)
             return NULL;
         }
     }
-    m->md_def = module;
+    m->md_token = module;
+    m->md_token_is_def = true;
+    module_copy_members_from_deflike(m, module);
 #ifdef Py_GIL_DISABLED
     m->md_gil = Py_MOD_GIL_USED;
 #endif
     return (PyObject*)m;
 }
 
-PyObject *
-PyModule_FromDefAndSpec2(PyModuleDef* def, PyObject *spec, int module_api_version)
+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;
@@ -331,10 +384,10 @@ PyModule_FromDefAndSpec2(PyModuleDef* def, PyObject *spec, int module_api_versio
     int has_execution_slots = 0;
     const char *name;
     int ret;
+    void *token = NULL;
+    _Py_modexecfunc m_exec = NULL;
     PyInterpreterState *interp = _PyInterpreterState_GET();
 
-    PyModuleDef_Init(def);
-
     nameobj = PyObject_GetAttrString(spec, "name");
     if (nameobj == NULL) {
         return NULL;
@@ -348,7 +401,7 @@ PyModule_FromDefAndSpec2(PyModuleDef* def, PyObject *spec, int module_api_versio
         goto error;
     }
 
-    if (def->m_size < 0) {
+    if (def_like->m_size < 0) {
         PyErr_Format(
             PyExc_SystemError,
             "module %s: m_size may not be negative for multi-phase initialization",
@@ -356,7 +409,35 @@ PyModule_FromDefAndSpec2(PyModuleDef* def, PyObject *spec, int module_api_versio
         goto error;
     }
 
-    for (cur_slot = def->m_slots; cur_slot && cur_slot->slot; cur_slot++) {
+    for (cur_slot = def_like->m_slots; cur_slot && cur_slot->slot; cur_slot++) {
+        // Macro to copy a non-NULL, non-repeatable slot that's unusable with
+        // PyModuleDef. The destination must be initially NULL.
+#define COPY_COMMON_SLOT(SLOT, TYPE, DEST)                              \
+        do {                                                            \
+            if (!(TYPE)(cur_slot->value)) {                             \
+                PyErr_Format(                                           \
+                    PyExc_SystemError,                                  \
+                    "module %s: " #SLOT " must not be NULL",            \
+                    name);                                              \
+                goto error;                                             \
+            }                                                           \
+            if (original_def) {                                         \
+                PyErr_Format(                                           \
+                    PyExc_SystemError,                                  \
+                    "module %s: " #SLOT " used with PyModuleDef",       \
+                    name);                                              \
+                goto error;                                             \
+            }                                                           \
+            if (DEST) {                                                 \
+                PyErr_Format(                                           \
+                    PyExc_SystemError,                                  \
+                    "module %s has more than one " #SLOT " slot",       \
+                    name);                                              \
+                goto error;                                             \
+            }                                                           \
+            DEST = (TYPE)(cur_slot->value);                             \
+        } while (0);                                                    \
+        /////////////////////////////////////////////////////////////////
         switch (cur_slot->slot) {
             case Py_mod_create:
                 if (create) {
@@ -370,6 +451,9 @@ PyModule_FromDefAndSpec2(PyModuleDef* def, PyObject *spec, int module_api_versio
                 break;
             case Py_mod_exec:
                 has_execution_slots = 1;
+                if (!original_def) {
+                    COPY_COMMON_SLOT(Py_mod_exec, _Py_modexecfunc, m_exec);
+                }
                 break;
             case Py_mod_multiple_interpreters:
                 if (has_multiple_interpreters_slot) {
@@ -398,6 +482,35 @@ PyModule_FromDefAndSpec2(PyModuleDef* def, PyObject *spec, int module_api_versio
                     goto error;
                 }
                 break;
+            case Py_mod_name:
+                COPY_COMMON_SLOT(Py_mod_name, char*, def_like->m_name);
+                break;
+            case Py_mod_doc:
+                COPY_COMMON_SLOT(Py_mod_doc, char*, def_like->m_doc);
+                break;
+            case Py_mod_state_size:
+                COPY_COMMON_SLOT(Py_mod_state_size, Py_ssize_t,
+                                 def_like->m_size);
+                break;
+            case Py_mod_methods:
+                COPY_COMMON_SLOT(Py_mod_methods, PyMethodDef*,
+                                 def_like->m_methods);
+                break;
+            case Py_mod_state_traverse:
+                COPY_COMMON_SLOT(Py_mod_state_traverse, traverseproc,
+                                 def_like->m_traverse);
+                break;
+            case Py_mod_state_clear:
+                COPY_COMMON_SLOT(Py_mod_state_clear, inquiry,
+                                 def_like->m_clear);
+                break;
+            case Py_mod_state_free:
+                COPY_COMMON_SLOT(Py_mod_state_free, freefunc,
+                                 def_like->m_free);
+                break;
+            case Py_mod_token:
+                COPY_COMMON_SLOT(Py_mod_token, void*, token);
+                break;
             default:
                 assert(cur_slot->slot < 0 || cur_slot->slot > _Py_mod_LAST_SLOT);
                 PyErr_Format(
@@ -406,6 +519,7 @@ PyModule_FromDefAndSpec2(PyModuleDef* def, PyObject *spec, int module_api_versio
                     name, cur_slot->slot);
                 goto error;
         }
+#undef COPY_COMMON_SLOT
     }
 
     /* By default, multi-phase init modules are expected
@@ -429,7 +543,7 @@ PyModule_FromDefAndSpec2(PyModuleDef* def, PyObject *spec, int module_api_versio
     }
 
     if (create) {
-        m = create(spec, def);
+        m = create(spec, original_def);
         if (m == NULL) {
             if (!PyErr_Occurred()) {
                 PyErr_Format(
@@ -455,15 +569,27 @@ PyModule_FromDefAndSpec2(PyModuleDef* def, PyObject *spec, int module_api_versio
     }
 
     if (PyModule_Check(m)) {
-        ((PyModuleObject*)m)->md_state = NULL;
-        ((PyModuleObject*)m)->md_def = def;
+        PyModuleObject *mod = (PyModuleObject*)m;
+        mod->md_state = NULL;
+        module_copy_members_from_deflike(mod, def_like);
+        if (original_def) {
+            assert (!token);
+            mod->md_token = original_def;
+            mod->md_token_is_def = 1;
+        }
+        else {
+            mod->md_token = token;
+        }
 #ifdef Py_GIL_DISABLED
-        ((PyModuleObject*)m)->md_gil = gil_slot;
+        mod->md_gil = gil_slot;
 #else
         (void)gil_slot;
 #endif
+        mod->md_exec = m_exec;
     } else {
-        if (def->m_size > 0 || def->m_traverse || def->m_clear || def->m_free) {
+        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",
@@ -478,17 +604,25 @@ PyModule_FromDefAndSpec2(PyModuleDef* def, PyObject *spec, int module_api_versio
                 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->m_methods != NULL) {
-        ret = _add_methods_to_object(m, nameobj, def->m_methods);
+    if (def_like->m_methods != NULL) {
+        ret = _add_methods_to_object(m, nameobj, def_like->m_methods);
         if (ret != 0) {
             goto error;
         }
     }
 
-    if (def->m_doc != NULL) {
-        ret = PyModule_SetDocString(m, def->m_doc);
+    if (def_like->m_doc != NULL) {
+        ret = PyModule_SetDocString(m, def_like->m_doc);
         if (ret != 0) {
             goto error;
         }
@@ -503,6 +637,29 @@ error:
     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)
@@ -516,71 +673,94 @@ PyUnstable_Module_SetGIL(PyObject *module, void *gil)
 }
 #endif
 
-int
-PyModule_ExecDef(PyObject *module, PyModuleDef *def)
+static int
+run_exec_func(PyObject *module, int (*exec)(PyObject *))
 {
-    PyModuleDef_Slot *cur_slot;
-    const char *name;
-    int ret;
+    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;
+}
 
-    name = PyModule_GetName(module);
-    if (name == NULL) {
+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 (def->m_size >= 0) {
-        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(def->m_size);
+            md->md_state = PyMem_Malloc(md->md_state_size);
             if (!md->md_state) {
                 PyErr_NoMemory();
                 return -1;
             }
-            memset(md->md_state, 0, def->m_size);
+            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++) {
-        switch (cur_slot->slot) {
-            case Py_mod_create:
-                /* handled in PyModule_FromDefAndSpec2 */
-                break;
-            case Py_mod_exec:
-                ret = ((int (*)(PyObject *))cur_slot->value)(module);
-                if (ret != 0) {
-                    if (!PyErr_Occurred()) {
-                        PyErr_Format(
-                            PyExc_SystemError,
-                            "execution of module %s failed without setting an exception",
-                            name);
-                    }
-                    return -1;
-                }
-                if (PyErr_Occurred()) {
-                    _PyErr_FormatFromCause(
-                        PyExc_SystemError,
-                        "execution of module %s raised unreported exception",
-                        name);
-                    return -1;
-                }
-                break;
-            case Py_mod_multiple_interpreters:
-            case Py_mod_gil:
-            case Py_mod_abi:
-                /* handled in PyModule_FromDefAndSpec2 */
-                break;
-            default:
-                PyErr_Format(
-                    PyExc_SystemError,
-                    "module %s initialized with unknown slot %i",
-                    name, cur_slot->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;
@@ -624,6 +804,31 @@ PyModule_GetDict(PyObject *m)
     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)
 {
@@ -764,7 +969,7 @@ PyModule_GetDef(PyObject* m)
         PyErr_BadArgument();
         return NULL;
     }
-    return _PyModule_GetDef(m);
+    return _PyModule_GetDefOrNull(m);
 }
 
 void*
@@ -888,17 +1093,18 @@ module_dealloc(PyObject *self)
     }
     FT_CLEAR_WEAKREFS(self, m->md_weaklist);
 
+    assert_def_missing_or_redundant(m);
     /* bpo-39824: Don't call m_free() if m_size > 0 and md_state=NULL */
-    if (m->md_def && m->md_def->m_free
-        && (m->md_def->m_size <= 0 || m->md_state != NULL))
+    if (m->md_state_free && (m->md_state_size <= 0 || m->md_state != NULL))
     {
-        m->md_def->m_free(m);
+        m->md_state_free(m);
     }
 
     Py_XDECREF(m->md_dict);
     Py_XDECREF(m->md_name);
-    if (m->md_state != NULL)
+    if (m->md_state != NULL) {
         PyMem_Free(m->md_state);
+    }
     Py_TYPE(m)->tp_free((PyObject *)m);
 }
 
@@ -1206,11 +1412,11 @@ module_traverse(PyObject *self, visitproc visit, void *arg)
 {
     PyModuleObject *m = _PyModule_CAST(self);
 
+    assert_def_missing_or_redundant(m);
     /* bpo-39824: Don't call m_traverse() if m_size > 0 and md_state=NULL */
-    if (m->md_def && m->md_def->m_traverse
-        && (m->md_def->m_size <= 0 || m->md_state != NULL))
+    if (m->md_state_traverse && (m->md_state_size <= 0 || m->md_state != NULL))
     {
-        int res = m->md_def->m_traverse((PyObject*)m, visit, arg);
+        int res = m->md_state_traverse((PyObject*)m, visit, arg);
         if (res)
             return res;
     }
@@ -1224,18 +1430,19 @@ module_clear(PyObject *self)
 {
     PyModuleObject *m = _PyModule_CAST(self);
 
+    assert_def_missing_or_redundant(m);
     /* bpo-39824: Don't call m_clear() if m_size > 0 and md_state=NULL */
-    if (m->md_def && m->md_def->m_clear
-        && (m->md_def->m_size <= 0 || m->md_state != NULL))
+    if (m->md_state_clear && (m->md_state_size <= 0 || m->md_state != NULL))
     {
-        int res = m->md_def->m_clear((PyObject*)m);
+        int res = m->md_state_clear((PyObject*)m);
         if (PyErr_Occurred()) {
             PyErr_FormatUnraisable("Exception ignored in m_clear of module%s%V",
                                    m->md_name ? " " : "",
                                    m->md_name, "");
         }
-        if (res)
+        if (res) {
             return res;
+        }
     }
     Py_CLEAR(m->md_dict);
     return 0;
diff --git a/Objects/typeobject.c b/Objects/typeobject.c
index d5695015807..326f4add896 100644
--- a/Objects/typeobject.c
+++ b/Objects/typeobject.c
@@ -5764,11 +5764,11 @@ PyType_GetModuleState(PyTypeObject *type)
 }
 
 
-/* Get the module of the first superclass where the module has the
- * given PyModuleDef.
+/* Return borrowed ref to the module of the first superclass where the module
+ * has the given token.
  */
-PyObject *
-PyType_GetModuleByDef(PyTypeObject *type, PyModuleDef *def)
+static PyObject *
+borrow_module_by_token(PyTypeObject *type, const void *token)
 {
     assert(PyType_Check(type));
 
@@ -5780,7 +5780,7 @@ PyType_GetModuleByDef(PyTypeObject *type, PyModuleDef *def)
     else {
         PyHeapTypeObject *ht = (PyHeapTypeObject*)type;
         PyObject *module = ht->ht_module;
-        if (module && _PyModule_GetDef(module) == def) {
+        if (module && _PyModule_GetToken(module) == token) {
             return module;
         }
     }
@@ -5808,7 +5808,7 @@ PyType_GetModuleByDef(PyTypeObject *type, PyModuleDef *def)
 
         PyHeapTypeObject *ht = (PyHeapTypeObject*)super;
         PyObject *module = ht->ht_module;
-        if (module && _PyModule_GetDef(module) == def) {
+        if (module && _PyModule_GetToken(module) == token) {
             res = module;
             break;
         }
@@ -5826,6 +5826,18 @@ error:
     return NULL;
 }
 
+PyObject *
+PyType_GetModuleByDef(PyTypeObject *type, PyModuleDef *def)
+{
+    return borrow_module_by_token(type, def);
+}
+
+PyObject *
+PyType_GetModuleByToken(PyTypeObject *type, const void *token)
+{
+    return Py_XNewRef(borrow_module_by_token(type, token));
+}
+
 
 static PyTypeObject *
 get_base_by_token_recursive(PyObject *bases, void *token)
diff --git a/PC/python3dll.c b/PC/python3dll.c
index 05c86e6d592..99e0f05fe03 100755
--- a/PC/python3dll.c
+++ b/PC/python3dll.c
@@ -416,8 +416,10 @@ EXPORT_FUNC(PyModule_AddObjectRef)
 EXPORT_FUNC(PyModule_AddStringConstant)
 EXPORT_FUNC(PyModule_AddType)
 EXPORT_FUNC(PyModule_Create2)
+EXPORT_FUNC(PyModule_Exec)
 EXPORT_FUNC(PyModule_ExecDef)
 EXPORT_FUNC(PyModule_FromDefAndSpec2)
+EXPORT_FUNC(PyModule_FromSlotsAndSpec)
 EXPORT_FUNC(PyModule_GetDef)
 EXPORT_FUNC(PyModule_GetDict)
 EXPORT_FUNC(PyModule_GetFilename)
@@ -425,6 +427,8 @@ EXPORT_FUNC(PyModule_GetFilenameObject)
 EXPORT_FUNC(PyModule_GetName)
 EXPORT_FUNC(PyModule_GetNameObject)
 EXPORT_FUNC(PyModule_GetState)
+EXPORT_FUNC(PyModule_GetStateSize)
+EXPORT_FUNC(PyModule_GetToken)
 EXPORT_FUNC(PyModule_New)
 EXPORT_FUNC(PyModule_NewObject)
 EXPORT_FUNC(PyModule_SetDocString)
@@ -668,6 +672,7 @@ EXPORT_FUNC(PyType_GetFlags)
 EXPORT_FUNC(PyType_GetFullyQualifiedName)
 EXPORT_FUNC(PyType_GetModule)
 EXPORT_FUNC(PyType_GetModuleByDef)
+EXPORT_FUNC(PyType_GetModuleByToken)
 EXPORT_FUNC(PyType_GetModuleName)
 EXPORT_FUNC(PyType_GetModuleState)
 EXPORT_FUNC(PyType_GetName)
diff --git a/Python/import.c b/Python/import.c
index d4b574a8828..6cf4a061ca6 100644
--- a/Python/import.c
+++ b/Python/import.c
@@ -672,8 +672,8 @@ _PyImport_ClearModulesByIndex(PyInterpreterState *interp)
 
     (6). first time  (not found in _PyRuntime.imports.extensions):
        A. _imp_create_dynamic_impl() -> import_find_extension()
-       B. _imp_create_dynamic_impl() -> _PyImport_GetModInitFunc()
-       C.   _PyImport_GetModInitFunc():  load <module init func>
+       B. _imp_create_dynamic_impl() -> _PyImport_GetModuleExportHooks()
+       C.   _PyImport_GetModuleExportHooks():  load <module init func>
        D. _imp_create_dynamic_impl() -> import_run_extension()
        E.   import_run_extension() -> _PyImport_RunModInitFunc()
        F.     _PyImport_RunModInitFunc():  call <module init func>
@@ -743,16 +743,19 @@ _PyImport_ClearModulesByIndex(PyInterpreterState *interp)
        A. noop
 
 
-    ...for multi-phase init modules:
+    ...for multi-phase init modules from PyModInit_* (PyModuleDef):
 
     (6). every time:
        A. _imp_create_dynamic_impl() -> import_find_extension()  (not found)
-       B. _imp_create_dynamic_impl() -> _PyImport_GetModInitFunc()
-       C.   _PyImport_GetModInitFunc():  load <module init func>
+       B. _imp_create_dynamic_impl() -> _PyImport_GetModuleExportHooks()
+       C.   _PyImport_GetModuleExportHooks():  load <module init func>
        D. _imp_create_dynamic_impl() -> import_run_extension()
        E.   import_run_extension() -> _PyImport_RunModInitFunc()
        F.     _PyImport_RunModInitFunc():  call <module init func>
        G.   import_run_extension() -> PyModule_FromDefAndSpec()
+
+       PyModule_FromDefAndSpec():
+
        H.      PyModule_FromDefAndSpec(): gather/check moduledef slots
        I.      if there's a Py_mod_create slot:
                  1. PyModule_FromDefAndSpec():  call its function
@@ -765,10 +768,29 @@ _PyImport_ClearModulesByIndex(PyInterpreterState *interp)
     (10). every time:
        A. _imp_exec_dynamic_impl() -> exec_builtin_or_dynamic()
        B.   if mod->md_state == NULL (including if m_size == 0):
-            1. exec_builtin_or_dynamic() -> PyModule_ExecDef()
-            2.   PyModule_ExecDef():  allocate mod->md_state
+            1. exec_builtin_or_dynamic() -> PyModule_Exec()
+            2.   PyModule_Exec():  allocate mod->md_state
             3.   if there's a Py_mod_exec slot:
-                 1. PyModule_ExecDef():  call its function
+                 1. PyModule_Exec():  call its function
+
+
+    ...for multi-phase init modules from PyModExport_* (slots array):
+
+    (6). every time:
+
+       A. _imp_create_dynamic_impl() -> import_find_extension()  (not found)
+       B. _imp_create_dynamic_impl() -> _PyImport_GetModuleExportHooks()
+       C.   _PyImport_GetModuleExportHooks():  load <module export func>
+       D. _imp_create_dynamic_impl() -> import_run_modexport()
+       E.     import_run_modexport():  call <module init func>
+       F.   import_run_modexport() -> PyModule_FromSlotsAndSpec()
+       G.     PyModule_FromSlotsAndSpec(): create temporary PyModuleDef-like
+       H.       PyModule_FromSlotsAndSpec() -> PyModule_FromDefAndSpec()
+
+       (PyModule_FromDefAndSpec behaves as for PyModInit_*, above)
+
+    (10). every time: as for PyModInit_*, above
+
  */
 
 
@@ -825,25 +847,19 @@ _PyImport_SetDLOpenFlags(PyInterpreterState *interp, int new_val)
 /* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
 static int
 exec_builtin_or_dynamic(PyObject *mod) {
-    PyModuleDef *def;
     void *state;
 
     if (!PyModule_Check(mod)) {
         return 0;
     }
 
-    def = PyModule_GetDef(mod);
-    if (def == NULL) {
-        return 0;
-    }
-
     state = PyModule_GetState(mod);
     if (state) {
         /* Already initialized; skip reload */
         return 0;
     }
 
-    return PyModule_ExecDef(mod, def);
+    return PyModule_Exec(mod);
 }
 
 
@@ -1787,7 +1803,7 @@ finish_singlephase_extension(PyThreadState *tstate, PyObject *mod,
                              PyObject *name, PyObject *modules)
 {
     assert(mod != NULL && PyModule_Check(mod));
-    assert(cached->def == _PyModule_GetDef(mod));
+    assert(cached->def == _PyModule_GetDefOrNull(mod));
 
     Py_ssize_t index = _get_cached_module_index(cached);
     if (_modules_by_index_set(tstate->interp, index, mod) < 0) {
@@ -1865,8 +1881,8 @@ reload_singlephase_extension(PyThreadState *tstate,
          * due to violating interpreter isolation.
          * See the note in set_cached_m_dict().
          * Until that is solved, we leave md_def set to NULL. */
-        assert(_PyModule_GetDef(mod) == NULL
-               || _PyModule_GetDef(mod) == def);
+        assert(_PyModule_GetDefOrNull(mod) == NULL
+               || _PyModule_GetDefOrNull(mod) == def);
     }
     else {
         assert(cached->m_dict == NULL);
@@ -1953,6 +1969,43 @@ import_find_extension(PyThreadState *tstate,
     return mod;
 }
 
+static PyObject *
+import_run_modexport(PyThreadState *tstate, PyModExportFunction ex0,
+                     struct _Py_ext_module_loader_info *info,
+                     PyObject *spec)
+{
+    /* This is like import_run_extension, but avoids interpreter switching
+     * and code for for single-phase modules.
+     */
+    PyModuleDef_Slot *slots = ex0();
+    if (!slots) {
+        if (!PyErr_Occurred()) {
+            PyErr_Format(
+                PyExc_SystemError,
+                "slot export function for module %s failed without setting an exception",
+                info->name);
+        }
+        return NULL;
+    }
+    if (PyErr_Occurred()) {
+        PyErr_Format(
+            PyExc_SystemError,
+            "slot export function for module %s raised unreported exception",
+            info->name);
+    }
+    PyObject *result = PyModule_FromSlotsAndSpec(slots, spec);
+    if (!result) {
+        return NULL;
+    }
+    if (PyModule_Check(result)) {
+        PyModuleObject *mod = (PyModuleObject *)result;
+        if (mod && !mod->md_token) {
+            mod->md_token = slots;
+        }
+    }
+    return result;
+}
+
 static PyObject *
 import_run_extension(PyThreadState *tstate, PyModInitFunction p0,
                      struct _Py_ext_module_loader_info *info,
@@ -2125,7 +2178,7 @@ main_finally:
         assert_multiphase_def(def);
         assert(mod == NULL);
         /* Note that we cheat a little by not repeating the calls
-         * to _PyImport_GetModInitFunc() and _PyImport_RunModInitFunc(). */
+         * to _PyImport_GetModuleExportHooks() and _PyImport_RunModInitFunc(). */
         mod = PyModule_FromDefAndSpec(def, spec);
         if (mod == NULL) {
             goto error;
@@ -2239,8 +2292,9 @@ _PyImport_FixupBuiltin(PyThreadState *tstate, PyObject *mod, const char *name,
         return -1;
     }
 
-    PyModuleDef *def = PyModule_GetDef(mod);
+    PyModuleDef *def = _PyModule_GetDefOrNull(mod);
     if (def == NULL) {
+        assert(!PyErr_Occurred());
         PyErr_BadInternalCall();
         goto finally;
     }
@@ -2322,8 +2376,8 @@ create_builtin(PyThreadState *tstate, PyObject *name, PyObject *spec)
         assert(!_PyErr_Occurred(tstate));
         assert(cached != NULL);
         /* The module might not have md_def set in certain reload cases. */
-        assert(_PyModule_GetDef(mod) == NULL
-                || cached->def == _PyModule_GetDef(mod));
+        assert(_PyModule_GetDefOrNull(mod) == NULL
+                || cached->def == _PyModule_GetDefOrNull(mod));
         assert_singlephase(cached);
         goto finally;
     }
@@ -4653,8 +4707,8 @@ _imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
         assert(!_PyErr_Occurred(tstate));
         assert(cached != NULL);
         /* The module might not have md_def set in certain reload cases. */
-        assert(_PyModule_GetDef(mod) == NULL
-                || cached->def == _PyModule_GetDef(mod));
+        assert(_PyModule_GetDefOrNull(mod) == NULL
+                || cached->def == _PyModule_GetDefOrNull(mod));
         assert_singlephase(cached);
         goto finally;
     }
@@ -4679,7 +4733,7 @@ _imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
     }
 
     /* We would move this (and the fclose() below) into
-     * _PyImport_GetModInitFunc(), but it isn't clear if the intervening
+     * _PyImport_GetModuleExportHooks(), but it isn't clear if the intervening
      * code relies on fp still being open. */
     FILE *fp;
     if (file != NULL) {
@@ -4692,7 +4746,13 @@ _imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
         fp = NULL;
     }
 
-    PyModInitFunction p0 = _PyImport_GetModInitFunc(&info, fp);
+    PyModInitFunction p0 = NULL;
+    PyModExportFunction ex0 = NULL;
+    _PyImport_GetModuleExportHooks(&info, fp, &p0, &ex0);
+    if (ex0) {
+        mod = import_run_modexport(tstate, ex0, &info, spec);
+        goto cleanup;
+    }
     if (p0 == NULL) {
         goto finally;
     }
@@ -4714,6 +4774,7 @@ _imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
     }
 #endif
 
+cleanup:
     // XXX Shouldn't this happen in the error cases too (i.e. in "finally")?
     if (fp) {
         fclose(fp);
diff --git a/Python/importdl.c b/Python/importdl.c
index 802843fe7b9..23a55c39677 100644
--- a/Python/importdl.c
+++ b/Python/importdl.c
@@ -5,7 +5,7 @@
 #include "pycore_call.h"          // _PyObject_CallMethod()
 #include "pycore_import.h"        // _PyImport_SwapPackageContext()
 #include "pycore_importdl.h"
-#include "pycore_moduleobject.h"  // _PyModule_GetDef()
+#include "pycore_moduleobject.h"  // _PyModule_GetDefOrNull()
 #include "pycore_pyerrors.h"      // _PyErr_FormatFromCause()
 #include "pycore_runtime.h"       // _Py_ID()
 
@@ -35,8 +35,10 @@ extern dl_funcptr _PyImport_FindSharedFuncptr(const char *prefix,
 /* module info to use when loading */
 /***********************************/
 
-static const char * const ascii_only_prefix = "PyInit";
-static const char * const nonascii_prefix = "PyInitU";
+static const struct hook_prefixes ascii_only_prefixes = {
+    "PyInit", "PyModExport"};
+static const struct hook_prefixes nonascii_prefixes = {
+    "PyInitU", "PyModExportU"};
 
 /* Get the variable part of a module's export symbol name.
  * Returns a bytes instance. For non-ASCII-named modules, the name is
@@ -45,7 +47,7 @@ static const char * const nonascii_prefix = "PyInitU";
  * nonascii_prefix, as appropriate.
  */
 static PyObject *
-get_encoded_name(PyObject *name, const char **hook_prefix) {
+get_encoded_name(PyObject *name, const struct hook_prefixes **hook_prefixes) {
     PyObject *tmp;
     PyObject *encoded = NULL;
     PyObject *modname = NULL;
@@ -72,7 +74,7 @@ get_encoded_name(PyObject *name, const char **hook_prefix) {
     /* Encode to ASCII or Punycode, as needed */
     encoded = PyUnicode_AsEncodedString(name, "ascii", NULL);
     if (encoded != NULL) {
-        *hook_prefix = ascii_only_prefix;
+        *hook_prefixes = &ascii_only_prefixes;
     } else {
         if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
             PyErr_Clear();
@@ -80,7 +82,7 @@ get_encoded_name(PyObject *name, const char **hook_prefix) {
             if (encoded == NULL) {
                 goto error;
             }
-            *hook_prefix = nonascii_prefix;
+            *hook_prefixes = &nonascii_prefixes;
         } else {
             goto error;
         }
@@ -130,7 +132,7 @@ _Py_ext_module_loader_info_init(struct _Py_ext_module_loader_info *p_info,
     assert(PyUnicode_GetLength(name) > 0);
     info.name = Py_NewRef(name);
 
-    info.name_encoded = get_encoded_name(info.name, &info.hook_prefix);
+    info.name_encoded = get_encoded_name(info.name, &info.hook_prefixes);
     if (info.name_encoded == NULL) {
         _Py_ext_module_loader_info_clear(&info);
         return -1;
@@ -189,7 +191,7 @@ _Py_ext_module_loader_info_init_for_builtin(
         /* We won't need filename. */
         .path=name,
         .origin=_Py_ext_module_origin_BUILTIN,
-        .hook_prefix=ascii_only_prefix,
+        .hook_prefixes=&ascii_only_prefixes,
         .newcontext=NULL,
     };
     return 0;
@@ -377,39 +379,63 @@ _Py_ext_module_loader_result_apply_error(
 /********************************************/
 
 #ifdef HAVE_DYNAMIC_LOADING
-PyModInitFunction
-_PyImport_GetModInitFunc(struct _Py_ext_module_loader_info *info,
-                         FILE *fp)
+static dl_funcptr
+findfuncptr(const char *prefix, const char *name_buf,
+            struct _Py_ext_module_loader_info *info,
+            FILE *fp)
 {
-    const char *name_buf = PyBytes_AS_STRING(info->name_encoded);
-    dl_funcptr exportfunc;
 #ifdef MS_WINDOWS
-    exportfunc = _PyImport_FindSharedFuncptrWindows(
-            info->hook_prefix, name_buf, info->filename, fp);
+    return _PyImport_FindSharedFuncptrWindows(
+            prefix, name_buf, info->filename, fp);
 #else
-    {
-        const char *path_buf = PyBytes_AS_STRING(info->filename_encoded);
-        exportfunc = _PyImport_FindSharedFuncptr(
-                        info->hook_prefix, name_buf, path_buf, fp);
-    }
+    const char *path_buf = PyBytes_AS_STRING(info->filename_encoded);
+    return _PyImport_FindSharedFuncptr(
+            prefix, name_buf, path_buf, fp);
 #endif
+}
 
-    if (exportfunc == NULL) {
-        if (!PyErr_Occurred()) {
-            PyObject *msg;
-            msg = PyUnicode_FromFormat(
-                "dynamic module does not define "
-                "module export function (%s_%s)",
-                info->hook_prefix, name_buf);
-            if (msg != NULL) {
-                PyErr_SetImportError(msg, info->name, info->filename);
-                Py_DECREF(msg);
-            }
-        }
-        return NULL;
+int
+_PyImport_GetModuleExportHooks(
+    struct _Py_ext_module_loader_info *info,
+    FILE *fp,
+    PyModInitFunction *modinit,
+    PyModExportFunction *modexport)
+{
+    *modinit = NULL;
+    *modexport = NULL;
+
+    const char *name_buf = PyBytes_AS_STRING(info->name_encoded);
+    dl_funcptr exportfunc;
+
+    exportfunc = findfuncptr(
+        info->hook_prefixes->export_prefix,
+        name_buf, info, fp);
+    if (exportfunc) {
+        *modexport = (PyModExportFunction)exportfunc;
+        return 2;
+    }
+
+    exportfunc = findfuncptr(
+        info->hook_prefixes->init_prefix,
+        name_buf, info, fp);
+    if (exportfunc) {
+        *modinit = (PyModInitFunction)exportfunc;
+        return 1;
     }
 
-    return (PyModInitFunction)exportfunc;
+    if (!PyErr_Occurred()) {
+        PyObject *msg;
+        msg = PyUnicode_FromFormat(
+            "dynamic module does not define "
+            "module export function (%s_%s or %s_%s)",
+            info->hook_prefixes->export_prefix, name_buf,
+            info->hook_prefixes->init_prefix, name_buf);
+        if (msg != NULL) {
+            PyErr_SetImportError(msg, info->name, info->filename);
+            Py_DECREF(msg);
+        }
+    }
+    return -1;
 }
 #endif /* HAVE_DYNAMIC_LOADING */
 
@@ -477,7 +503,7 @@ _PyImport_RunModInitFunc(PyModInitFunction p0,
         res.def = (PyModuleDef *)m;
         /* Run PyModule_FromDefAndSpec() to finish loading the module. */
     }
-    else if (info->hook_prefix == nonascii_prefix) {
+    else if (info->hook_prefixes == &nonascii_prefixes) {
         /* Non-ASCII is only supported for multi-phase init. */
         res.kind = _Py_ext_module_kind_MULTIPHASE;
         /* Don't allow legacy init for non-ASCII module names. */
@@ -496,7 +522,7 @@ _PyImport_RunModInitFunc(PyModInitFunction p0,
             goto error;
         }
 
-        res.def = _PyModule_GetDef(m);
+        res.def = _PyModule_GetDefOrNull(m);
         if (res.def == NULL) {
             PyErr_Clear();
             _Py_ext_module_loader_result_set_error(