import.c 109 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930
  1. /* Module definition and import implementation */
  2. #include "Python.h"
  3. #include "pycore_hashtable.h" // _Py_hashtable_new_full()
  4. #include "pycore_import.h" // _PyImport_BootstrapImp()
  5. #include "pycore_initconfig.h" // _PyStatus_OK()
  6. #include "pycore_interp.h" // struct _import_runtime_state
  7. #include "pycore_namespace.h" // _PyNamespace_Type
  8. #include "pycore_object.h" // _Py_SetImmortal()
  9. #include "pycore_pyerrors.h" // _PyErr_SetString()
  10. #include "pycore_pyhash.h" // _Py_KeyedHash()
  11. #include "pycore_pylifecycle.h"
  12. #include "pycore_pymem.h" // _PyMem_SetDefaultAllocator()
  13. #include "pycore_pystate.h" // _PyInterpreterState_GET()
  14. #include "pycore_sysmodule.h" // _PySys_Audit()
  15. #include "marshal.h" // PyMarshal_ReadObjectFromString()
  16. #include "importdl.h" // _PyImport_DynLoadFiletab
  17. #include "pydtrace.h" // PyDTrace_IMPORT_FIND_LOAD_START_ENABLED()
  18. #include <stdbool.h> // bool
  19. #ifdef HAVE_FCNTL_H
  20. #include <fcntl.h>
  21. #endif
  22. #ifdef __cplusplus
  23. extern "C" {
  24. #endif
  25. /*[clinic input]
  26. module _imp
  27. [clinic start generated code]*/
  28. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=9c332475d8686284]*/
  29. #include "clinic/import.c.h"
  30. /*******************************/
  31. /* process-global import state */
  32. /*******************************/
  33. /* This table is defined in config.c: */
  34. extern struct _inittab _PyImport_Inittab[];
  35. // This is not used after Py_Initialize() is called.
  36. // (See _PyRuntimeState.imports.inittab.)
  37. struct _inittab *PyImport_Inittab = _PyImport_Inittab;
  38. // When we dynamically allocate a larger table for PyImport_ExtendInittab(),
  39. // we track the pointer here so we can deallocate it during finalization.
  40. static struct _inittab *inittab_copy = NULL;
  41. /*******************************/
  42. /* runtime-global import state */
  43. /*******************************/
  44. #define INITTAB _PyRuntime.imports.inittab
  45. #define LAST_MODULE_INDEX _PyRuntime.imports.last_module_index
  46. #define EXTENSIONS _PyRuntime.imports.extensions
  47. #define PKGCONTEXT (_PyRuntime.imports.pkgcontext)
  48. /*******************************/
  49. /* interpreter import state */
  50. /*******************************/
  51. #define MODULES(interp) \
  52. (interp)->imports.modules
  53. #define MODULES_BY_INDEX(interp) \
  54. (interp)->imports.modules_by_index
  55. #define IMPORTLIB(interp) \
  56. (interp)->imports.importlib
  57. #define OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK(interp) \
  58. (interp)->imports.override_multi_interp_extensions_check
  59. #define OVERRIDE_FROZEN_MODULES(interp) \
  60. (interp)->imports.override_frozen_modules
  61. #ifdef HAVE_DLOPEN
  62. # define DLOPENFLAGS(interp) \
  63. (interp)->imports.dlopenflags
  64. #endif
  65. #define IMPORT_FUNC(interp) \
  66. (interp)->imports.import_func
  67. #define IMPORT_LOCK(interp) \
  68. (interp)->imports.lock.mutex
  69. #define IMPORT_LOCK_THREAD(interp) \
  70. (interp)->imports.lock.thread
  71. #define IMPORT_LOCK_LEVEL(interp) \
  72. (interp)->imports.lock.level
  73. #define FIND_AND_LOAD(interp) \
  74. (interp)->imports.find_and_load
  75. /*******************/
  76. /* the import lock */
  77. /*******************/
  78. /* Locking primitives to prevent parallel imports of the same module
  79. in different threads to return with a partially loaded module.
  80. These calls are serialized by the global interpreter lock. */
  81. void
  82. _PyImport_AcquireLock(PyInterpreterState *interp)
  83. {
  84. unsigned long me = PyThread_get_thread_ident();
  85. if (me == PYTHREAD_INVALID_THREAD_ID)
  86. return; /* Too bad */
  87. if (IMPORT_LOCK(interp) == NULL) {
  88. IMPORT_LOCK(interp) = PyThread_allocate_lock();
  89. if (IMPORT_LOCK(interp) == NULL)
  90. return; /* Nothing much we can do. */
  91. }
  92. if (IMPORT_LOCK_THREAD(interp) == me) {
  93. IMPORT_LOCK_LEVEL(interp)++;
  94. return;
  95. }
  96. if (IMPORT_LOCK_THREAD(interp) != PYTHREAD_INVALID_THREAD_ID ||
  97. !PyThread_acquire_lock(IMPORT_LOCK(interp), 0))
  98. {
  99. PyThreadState *tstate = PyEval_SaveThread();
  100. PyThread_acquire_lock(IMPORT_LOCK(interp), WAIT_LOCK);
  101. PyEval_RestoreThread(tstate);
  102. }
  103. assert(IMPORT_LOCK_LEVEL(interp) == 0);
  104. IMPORT_LOCK_THREAD(interp) = me;
  105. IMPORT_LOCK_LEVEL(interp) = 1;
  106. }
  107. int
  108. _PyImport_ReleaseLock(PyInterpreterState *interp)
  109. {
  110. unsigned long me = PyThread_get_thread_ident();
  111. if (me == PYTHREAD_INVALID_THREAD_ID || IMPORT_LOCK(interp) == NULL)
  112. return 0; /* Too bad */
  113. if (IMPORT_LOCK_THREAD(interp) != me)
  114. return -1;
  115. IMPORT_LOCK_LEVEL(interp)--;
  116. assert(IMPORT_LOCK_LEVEL(interp) >= 0);
  117. if (IMPORT_LOCK_LEVEL(interp) == 0) {
  118. IMPORT_LOCK_THREAD(interp) = PYTHREAD_INVALID_THREAD_ID;
  119. PyThread_release_lock(IMPORT_LOCK(interp));
  120. }
  121. return 1;
  122. }
  123. #ifdef HAVE_FORK
  124. /* This function is called from PyOS_AfterFork_Child() to ensure that newly
  125. created child processes do not share locks with the parent.
  126. We now acquire the import lock around fork() calls but on some platforms
  127. (Solaris 9 and earlier? see isue7242) that still left us with problems. */
  128. PyStatus
  129. _PyImport_ReInitLock(PyInterpreterState *interp)
  130. {
  131. if (IMPORT_LOCK(interp) != NULL) {
  132. if (_PyThread_at_fork_reinit(&IMPORT_LOCK(interp)) < 0) {
  133. return _PyStatus_ERR("failed to create a new lock");
  134. }
  135. }
  136. if (IMPORT_LOCK_LEVEL(interp) > 1) {
  137. /* Forked as a side effect of import */
  138. unsigned long me = PyThread_get_thread_ident();
  139. PyThread_acquire_lock(IMPORT_LOCK(interp), WAIT_LOCK);
  140. IMPORT_LOCK_THREAD(interp) = me;
  141. IMPORT_LOCK_LEVEL(interp)--;
  142. } else {
  143. IMPORT_LOCK_THREAD(interp) = PYTHREAD_INVALID_THREAD_ID;
  144. IMPORT_LOCK_LEVEL(interp) = 0;
  145. }
  146. return _PyStatus_OK();
  147. }
  148. #endif
  149. /***************/
  150. /* sys.modules */
  151. /***************/
  152. PyObject *
  153. _PyImport_InitModules(PyInterpreterState *interp)
  154. {
  155. assert(MODULES(interp) == NULL);
  156. MODULES(interp) = PyDict_New();
  157. if (MODULES(interp) == NULL) {
  158. return NULL;
  159. }
  160. return MODULES(interp);
  161. }
  162. PyObject *
  163. _PyImport_GetModules(PyInterpreterState *interp)
  164. {
  165. return MODULES(interp);
  166. }
  167. void
  168. _PyImport_ClearModules(PyInterpreterState *interp)
  169. {
  170. Py_SETREF(MODULES(interp), NULL);
  171. }
  172. PyObject *
  173. PyImport_GetModuleDict(void)
  174. {
  175. PyInterpreterState *interp = _PyInterpreterState_GET();
  176. if (MODULES(interp) == NULL) {
  177. Py_FatalError("interpreter has no modules dictionary");
  178. }
  179. return MODULES(interp);
  180. }
  181. // This is only kept around for extensions that use _Py_IDENTIFIER.
  182. PyObject *
  183. _PyImport_GetModuleId(_Py_Identifier *nameid)
  184. {
  185. PyObject *name = _PyUnicode_FromId(nameid); /* borrowed */
  186. if (name == NULL) {
  187. return NULL;
  188. }
  189. return PyImport_GetModule(name);
  190. }
  191. int
  192. _PyImport_SetModule(PyObject *name, PyObject *m)
  193. {
  194. PyInterpreterState *interp = _PyInterpreterState_GET();
  195. PyObject *modules = MODULES(interp);
  196. return PyObject_SetItem(modules, name, m);
  197. }
  198. int
  199. _PyImport_SetModuleString(const char *name, PyObject *m)
  200. {
  201. PyInterpreterState *interp = _PyInterpreterState_GET();
  202. PyObject *modules = MODULES(interp);
  203. return PyMapping_SetItemString(modules, name, m);
  204. }
  205. static PyObject *
  206. import_get_module(PyThreadState *tstate, PyObject *name)
  207. {
  208. PyObject *modules = MODULES(tstate->interp);
  209. if (modules == NULL) {
  210. _PyErr_SetString(tstate, PyExc_RuntimeError,
  211. "unable to get sys.modules");
  212. return NULL;
  213. }
  214. PyObject *m;
  215. Py_INCREF(modules);
  216. if (PyDict_CheckExact(modules)) {
  217. m = PyDict_GetItemWithError(modules, name); /* borrowed */
  218. Py_XINCREF(m);
  219. }
  220. else {
  221. m = PyObject_GetItem(modules, name);
  222. if (m == NULL && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
  223. _PyErr_Clear(tstate);
  224. }
  225. }
  226. Py_DECREF(modules);
  227. return m;
  228. }
  229. static int
  230. import_ensure_initialized(PyInterpreterState *interp, PyObject *mod, PyObject *name)
  231. {
  232. PyObject *spec;
  233. /* Optimization: only call _bootstrap._lock_unlock_module() if
  234. __spec__._initializing is true.
  235. NOTE: because of this, initializing must be set *before*
  236. stuffing the new module in sys.modules.
  237. */
  238. spec = PyObject_GetAttr(mod, &_Py_ID(__spec__));
  239. int busy = _PyModuleSpec_IsInitializing(spec);
  240. Py_XDECREF(spec);
  241. if (busy) {
  242. /* Wait until module is done importing. */
  243. PyObject *value = _PyObject_CallMethodOneArg(
  244. IMPORTLIB(interp), &_Py_ID(_lock_unlock_module), name);
  245. if (value == NULL) {
  246. return -1;
  247. }
  248. Py_DECREF(value);
  249. }
  250. return 0;
  251. }
  252. static void remove_importlib_frames(PyThreadState *tstate);
  253. PyObject *
  254. PyImport_GetModule(PyObject *name)
  255. {
  256. PyThreadState *tstate = _PyThreadState_GET();
  257. PyObject *mod;
  258. mod = import_get_module(tstate, name);
  259. if (mod != NULL && mod != Py_None) {
  260. if (import_ensure_initialized(tstate->interp, mod, name) < 0) {
  261. Py_DECREF(mod);
  262. remove_importlib_frames(tstate);
  263. return NULL;
  264. }
  265. }
  266. return mod;
  267. }
  268. /* Get the module object corresponding to a module name.
  269. First check the modules dictionary if there's one there,
  270. if not, create a new one and insert it in the modules dictionary. */
  271. static PyObject *
  272. import_add_module(PyThreadState *tstate, PyObject *name)
  273. {
  274. PyObject *modules = MODULES(tstate->interp);
  275. if (modules == NULL) {
  276. _PyErr_SetString(tstate, PyExc_RuntimeError,
  277. "no import module dictionary");
  278. return NULL;
  279. }
  280. PyObject *m;
  281. if (PyDict_CheckExact(modules)) {
  282. m = Py_XNewRef(PyDict_GetItemWithError(modules, name));
  283. }
  284. else {
  285. m = PyObject_GetItem(modules, name);
  286. // For backward-compatibility we copy the behavior
  287. // of PyDict_GetItemWithError().
  288. if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
  289. _PyErr_Clear(tstate);
  290. }
  291. }
  292. if (_PyErr_Occurred(tstate)) {
  293. return NULL;
  294. }
  295. if (m != NULL && PyModule_Check(m)) {
  296. return m;
  297. }
  298. Py_XDECREF(m);
  299. m = PyModule_NewObject(name);
  300. if (m == NULL)
  301. return NULL;
  302. if (PyObject_SetItem(modules, name, m) != 0) {
  303. Py_DECREF(m);
  304. return NULL;
  305. }
  306. return m;
  307. }
  308. PyObject *
  309. PyImport_AddModuleObject(PyObject *name)
  310. {
  311. PyThreadState *tstate = _PyThreadState_GET();
  312. PyObject *mod = import_add_module(tstate, name);
  313. if (mod) {
  314. PyObject *ref = PyWeakref_NewRef(mod, NULL);
  315. Py_DECREF(mod);
  316. if (ref == NULL) {
  317. return NULL;
  318. }
  319. mod = PyWeakref_GetObject(ref);
  320. Py_DECREF(ref);
  321. }
  322. return mod; /* borrowed reference */
  323. }
  324. PyObject *
  325. PyImport_AddModule(const char *name)
  326. {
  327. PyObject *nameobj = PyUnicode_FromString(name);
  328. if (nameobj == NULL) {
  329. return NULL;
  330. }
  331. PyObject *module = PyImport_AddModuleObject(nameobj);
  332. Py_DECREF(nameobj);
  333. return module;
  334. }
  335. /* Remove name from sys.modules, if it's there.
  336. * Can be called with an exception raised.
  337. * If fail to remove name a new exception will be chained with the old
  338. * exception, otherwise the old exception is preserved.
  339. */
  340. static void
  341. remove_module(PyThreadState *tstate, PyObject *name)
  342. {
  343. PyObject *exc = _PyErr_GetRaisedException(tstate);
  344. PyObject *modules = MODULES(tstate->interp);
  345. if (PyDict_CheckExact(modules)) {
  346. PyObject *mod = _PyDict_Pop(modules, name, Py_None);
  347. Py_XDECREF(mod);
  348. }
  349. else if (PyMapping_DelItem(modules, name) < 0) {
  350. if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
  351. _PyErr_Clear(tstate);
  352. }
  353. }
  354. _PyErr_ChainExceptions1(exc);
  355. }
  356. /************************************/
  357. /* per-interpreter modules-by-index */
  358. /************************************/
  359. Py_ssize_t
  360. _PyImport_GetNextModuleIndex(void)
  361. {
  362. PyThread_acquire_lock(EXTENSIONS.mutex, WAIT_LOCK);
  363. LAST_MODULE_INDEX++;
  364. Py_ssize_t index = LAST_MODULE_INDEX;
  365. PyThread_release_lock(EXTENSIONS.mutex);
  366. return index;
  367. }
  368. static const char *
  369. _modules_by_index_check(PyInterpreterState *interp, Py_ssize_t index)
  370. {
  371. if (index == 0) {
  372. return "invalid module index";
  373. }
  374. if (MODULES_BY_INDEX(interp) == NULL) {
  375. return "Interpreters module-list not accessible.";
  376. }
  377. if (index > PyList_GET_SIZE(MODULES_BY_INDEX(interp))) {
  378. return "Module index out of bounds.";
  379. }
  380. return NULL;
  381. }
  382. static PyObject *
  383. _modules_by_index_get(PyInterpreterState *interp, PyModuleDef *def)
  384. {
  385. Py_ssize_t index = def->m_base.m_index;
  386. if (_modules_by_index_check(interp, index) != NULL) {
  387. return NULL;
  388. }
  389. PyObject *res = PyList_GET_ITEM(MODULES_BY_INDEX(interp), index);
  390. return res==Py_None ? NULL : res;
  391. }
  392. static int
  393. _modules_by_index_set(PyInterpreterState *interp,
  394. PyModuleDef *def, PyObject *module)
  395. {
  396. assert(def != NULL);
  397. assert(def->m_slots == NULL);
  398. assert(def->m_base.m_index > 0);
  399. if (MODULES_BY_INDEX(interp) == NULL) {
  400. MODULES_BY_INDEX(interp) = PyList_New(0);
  401. if (MODULES_BY_INDEX(interp) == NULL) {
  402. return -1;
  403. }
  404. }
  405. Py_ssize_t index = def->m_base.m_index;
  406. while (PyList_GET_SIZE(MODULES_BY_INDEX(interp)) <= index) {
  407. if (PyList_Append(MODULES_BY_INDEX(interp), Py_None) < 0) {
  408. return -1;
  409. }
  410. }
  411. return PyList_SetItem(MODULES_BY_INDEX(interp), index, Py_NewRef(module));
  412. }
  413. static int
  414. _modules_by_index_clear_one(PyInterpreterState *interp, PyModuleDef *def)
  415. {
  416. Py_ssize_t index = def->m_base.m_index;
  417. const char *err = _modules_by_index_check(interp, index);
  418. if (err != NULL) {
  419. Py_FatalError(err);
  420. return -1;
  421. }
  422. return PyList_SetItem(MODULES_BY_INDEX(interp), index, Py_NewRef(Py_None));
  423. }
  424. PyObject*
  425. PyState_FindModule(PyModuleDef* module)
  426. {
  427. PyInterpreterState *interp = _PyInterpreterState_GET();
  428. if (module->m_slots) {
  429. return NULL;
  430. }
  431. return _modules_by_index_get(interp, module);
  432. }
  433. /* _PyState_AddModule() has been completely removed from the C-API
  434. (and was removed from the limited API in 3.6). However, we're
  435. playing it safe and keeping it around for any stable ABI extensions
  436. built against 3.2-3.5. */
  437. int
  438. _PyState_AddModule(PyThreadState *tstate, PyObject* module, PyModuleDef* def)
  439. {
  440. if (!def) {
  441. assert(_PyErr_Occurred(tstate));
  442. return -1;
  443. }
  444. if (def->m_slots) {
  445. _PyErr_SetString(tstate,
  446. PyExc_SystemError,
  447. "PyState_AddModule called on module with slots");
  448. return -1;
  449. }
  450. return _modules_by_index_set(tstate->interp, def, module);
  451. }
  452. int
  453. PyState_AddModule(PyObject* module, PyModuleDef* def)
  454. {
  455. if (!def) {
  456. Py_FatalError("module definition is NULL");
  457. return -1;
  458. }
  459. PyThreadState *tstate = _PyThreadState_GET();
  460. if (def->m_slots) {
  461. _PyErr_SetString(tstate,
  462. PyExc_SystemError,
  463. "PyState_AddModule called on module with slots");
  464. return -1;
  465. }
  466. PyInterpreterState *interp = tstate->interp;
  467. Py_ssize_t index = def->m_base.m_index;
  468. if (MODULES_BY_INDEX(interp) &&
  469. index < PyList_GET_SIZE(MODULES_BY_INDEX(interp)) &&
  470. module == PyList_GET_ITEM(MODULES_BY_INDEX(interp), index))
  471. {
  472. _Py_FatalErrorFormat(__func__, "module %p already added", module);
  473. return -1;
  474. }
  475. return _modules_by_index_set(interp, def, module);
  476. }
  477. int
  478. PyState_RemoveModule(PyModuleDef* def)
  479. {
  480. PyThreadState *tstate = _PyThreadState_GET();
  481. if (def->m_slots) {
  482. _PyErr_SetString(tstate,
  483. PyExc_SystemError,
  484. "PyState_RemoveModule called on module with slots");
  485. return -1;
  486. }
  487. return _modules_by_index_clear_one(tstate->interp, def);
  488. }
  489. // Used by finalize_modules()
  490. void
  491. _PyImport_ClearModulesByIndex(PyInterpreterState *interp)
  492. {
  493. if (!MODULES_BY_INDEX(interp)) {
  494. return;
  495. }
  496. Py_ssize_t i;
  497. for (i = 0; i < PyList_GET_SIZE(MODULES_BY_INDEX(interp)); i++) {
  498. PyObject *m = PyList_GET_ITEM(MODULES_BY_INDEX(interp), i);
  499. if (PyModule_Check(m)) {
  500. /* cleanup the saved copy of module dicts */
  501. PyModuleDef *md = PyModule_GetDef(m);
  502. if (md) {
  503. Py_CLEAR(md->m_base.m_copy);
  504. }
  505. }
  506. }
  507. /* Setting modules_by_index to NULL could be dangerous, so we
  508. clear the list instead. */
  509. if (PyList_SetSlice(MODULES_BY_INDEX(interp),
  510. 0, PyList_GET_SIZE(MODULES_BY_INDEX(interp)),
  511. NULL)) {
  512. PyErr_WriteUnraisable(MODULES_BY_INDEX(interp));
  513. }
  514. }
  515. /*********************/
  516. /* extension modules */
  517. /*********************/
  518. /*
  519. It may help to have a big picture view of what happens
  520. when an extension is loaded. This includes when it is imported
  521. for the first time.
  522. Here's a summary, using importlib._boostrap._load() as a starting point.
  523. 1. importlib._bootstrap._load()
  524. 2. _load(): acquire import lock
  525. 3. _load() -> importlib._bootstrap._load_unlocked()
  526. 4. _load_unlocked() -> importlib._bootstrap.module_from_spec()
  527. 5. module_from_spec() -> ExtensionFileLoader.create_module()
  528. 6. create_module() -> _imp.create_dynamic()
  529. (see below)
  530. 7. module_from_spec() -> importlib._bootstrap._init_module_attrs()
  531. 8. _load_unlocked(): sys.modules[name] = module
  532. 9. _load_unlocked() -> ExtensionFileLoader.exec_module()
  533. 10. exec_module() -> _imp.exec_dynamic()
  534. (see below)
  535. 11. _load(): release import lock
  536. ...for single-phase init modules, where m_size == -1:
  537. (6). first time (not found in _PyRuntime.imports.extensions):
  538. 1. _imp_create_dynamic_impl() -> import_find_extension()
  539. 2. _imp_create_dynamic_impl() -> _PyImport_LoadDynamicModuleWithSpec()
  540. 3. _PyImport_LoadDynamicModuleWithSpec(): load <module init func>
  541. 4. _PyImport_LoadDynamicModuleWithSpec(): call <module init func>
  542. 5. <module init func> -> PyModule_Create() -> PyModule_Create2() -> PyModule_CreateInitialized()
  543. 6. PyModule_CreateInitialized() -> PyModule_New()
  544. 7. PyModule_CreateInitialized(): allocate mod->md_state
  545. 8. PyModule_CreateInitialized() -> PyModule_AddFunctions()
  546. 9. PyModule_CreateInitialized() -> PyModule_SetDocString()
  547. 10. PyModule_CreateInitialized(): set mod->md_def
  548. 11. <module init func>: initialize the module
  549. 12. _PyImport_LoadDynamicModuleWithSpec() -> _PyImport_CheckSubinterpIncompatibleExtensionAllowed()
  550. 13. _PyImport_LoadDynamicModuleWithSpec(): set def->m_base.m_init
  551. 14. _PyImport_LoadDynamicModuleWithSpec(): set __file__
  552. 15. _PyImport_LoadDynamicModuleWithSpec() -> _PyImport_FixupExtensionObject()
  553. 16. _PyImport_FixupExtensionObject(): add it to interp->imports.modules_by_index
  554. 17. _PyImport_FixupExtensionObject(): copy __dict__ into def->m_base.m_copy
  555. 18. _PyImport_FixupExtensionObject(): add it to _PyRuntime.imports.extensions
  556. (6). subsequent times (found in _PyRuntime.imports.extensions):
  557. 1. _imp_create_dynamic_impl() -> import_find_extension()
  558. 2. import_find_extension() -> import_add_module()
  559. 3. if name in sys.modules: use that module
  560. 4. else:
  561. 1. import_add_module() -> PyModule_NewObject()
  562. 2. import_add_module(): set it on sys.modules
  563. 5. import_find_extension(): copy the "m_copy" dict into __dict__
  564. 6. _imp_create_dynamic_impl() -> _PyImport_CheckSubinterpIncompatibleExtensionAllowed()
  565. (10). (every time):
  566. 1. noop
  567. ...for single-phase init modules, where m_size >= 0:
  568. (6). not main interpreter and never loaded there - every time (not found in _PyRuntime.imports.extensions):
  569. 1-16. (same as for m_size == -1)
  570. (6). main interpreter - first time (not found in _PyRuntime.imports.extensions):
  571. 1-16. (same as for m_size == -1)
  572. 17. _PyImport_FixupExtensionObject(): add it to _PyRuntime.imports.extensions
  573. (6). previously loaded in main interpreter (found in _PyRuntime.imports.extensions):
  574. 1. _imp_create_dynamic_impl() -> import_find_extension()
  575. 2. import_find_extension(): call def->m_base.m_init
  576. 3. import_find_extension(): add the module to sys.modules
  577. (10). every time:
  578. 1. noop
  579. ...for multi-phase init modules:
  580. (6). every time:
  581. 1. _imp_create_dynamic_impl() -> import_find_extension() (not found)
  582. 2. _imp_create_dynamic_impl() -> _PyImport_LoadDynamicModuleWithSpec()
  583. 3. _PyImport_LoadDynamicModuleWithSpec(): load module init func
  584. 4. _PyImport_LoadDynamicModuleWithSpec(): call module init func
  585. 5. _PyImport_LoadDynamicModuleWithSpec() -> PyModule_FromDefAndSpec()
  586. 6. PyModule_FromDefAndSpec(): gather/check moduledef slots
  587. 7. if there's a Py_mod_create slot:
  588. 1. PyModule_FromDefAndSpec(): call its function
  589. 8. else:
  590. 1. PyModule_FromDefAndSpec() -> PyModule_NewObject()
  591. 9: PyModule_FromDefAndSpec(): set mod->md_def
  592. 10. PyModule_FromDefAndSpec() -> _add_methods_to_object()
  593. 11. PyModule_FromDefAndSpec() -> PyModule_SetDocString()
  594. (10). every time:
  595. 1. _imp_exec_dynamic_impl() -> exec_builtin_or_dynamic()
  596. 2. if mod->md_state == NULL (including if m_size == 0):
  597. 1. exec_builtin_or_dynamic() -> PyModule_ExecDef()
  598. 2. PyModule_ExecDef(): allocate mod->md_state
  599. 3. if there's a Py_mod_exec slot:
  600. 1. PyModule_ExecDef(): call its function
  601. */
  602. /* Make sure name is fully qualified.
  603. This is a bit of a hack: when the shared library is loaded,
  604. the module name is "package.module", but the module calls
  605. PyModule_Create*() with just "module" for the name. The shared
  606. library loader squirrels away the true name of the module in
  607. _PyRuntime.imports.pkgcontext, and PyModule_Create*() will
  608. substitute this (if the name actually matches).
  609. */
  610. #ifdef HAVE_THREAD_LOCAL
  611. _Py_thread_local const char *pkgcontext = NULL;
  612. # undef PKGCONTEXT
  613. # define PKGCONTEXT pkgcontext
  614. #endif
  615. const char *
  616. _PyImport_ResolveNameWithPackageContext(const char *name)
  617. {
  618. #ifndef HAVE_THREAD_LOCAL
  619. PyThread_acquire_lock(EXTENSIONS.mutex, WAIT_LOCK);
  620. #endif
  621. if (PKGCONTEXT != NULL) {
  622. const char *p = strrchr(PKGCONTEXT, '.');
  623. if (p != NULL && strcmp(name, p+1) == 0) {
  624. name = PKGCONTEXT;
  625. PKGCONTEXT = NULL;
  626. }
  627. }
  628. #ifndef HAVE_THREAD_LOCAL
  629. PyThread_release_lock(EXTENSIONS.mutex);
  630. #endif
  631. return name;
  632. }
  633. const char *
  634. _PyImport_SwapPackageContext(const char *newcontext)
  635. {
  636. #ifndef HAVE_THREAD_LOCAL
  637. PyThread_acquire_lock(EXTENSIONS.mutex, WAIT_LOCK);
  638. #endif
  639. const char *oldcontext = PKGCONTEXT;
  640. PKGCONTEXT = newcontext;
  641. #ifndef HAVE_THREAD_LOCAL
  642. PyThread_release_lock(EXTENSIONS.mutex);
  643. #endif
  644. return oldcontext;
  645. }
  646. #ifdef HAVE_DLOPEN
  647. int
  648. _PyImport_GetDLOpenFlags(PyInterpreterState *interp)
  649. {
  650. return DLOPENFLAGS(interp);
  651. }
  652. void
  653. _PyImport_SetDLOpenFlags(PyInterpreterState *interp, int new_val)
  654. {
  655. DLOPENFLAGS(interp) = new_val;
  656. }
  657. #endif // HAVE_DLOPEN
  658. /* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
  659. static int
  660. exec_builtin_or_dynamic(PyObject *mod) {
  661. PyModuleDef *def;
  662. void *state;
  663. if (!PyModule_Check(mod)) {
  664. return 0;
  665. }
  666. def = PyModule_GetDef(mod);
  667. if (def == NULL) {
  668. return 0;
  669. }
  670. state = PyModule_GetState(mod);
  671. if (state) {
  672. /* Already initialized; skip reload */
  673. return 0;
  674. }
  675. return PyModule_ExecDef(mod, def);
  676. }
  677. static int clear_singlephase_extension(PyInterpreterState *interp,
  678. PyObject *name, PyObject *filename);
  679. // Currently, this is only used for testing.
  680. // (See _testinternalcapi.clear_extension().)
  681. int
  682. _PyImport_ClearExtension(PyObject *name, PyObject *filename)
  683. {
  684. PyInterpreterState *interp = _PyInterpreterState_GET();
  685. /* Clearing a module's C globals is up to the module. */
  686. if (clear_singlephase_extension(interp, name, filename) < 0) {
  687. return -1;
  688. }
  689. // In the future we'll probably also make sure the extension's
  690. // file handle (and DL handle) is closed (requires saving it).
  691. return 0;
  692. }
  693. /*******************/
  694. #if defined(__EMSCRIPTEN__) && defined(PY_CALL_TRAMPOLINE)
  695. #error #include <emscripten.h>
  696. EM_JS(PyObject*, _PyImport_InitFunc_TrampolineCall, (PyModInitFunction func), {
  697. return wasmTable.get(func)();
  698. });
  699. #endif // __EMSCRIPTEN__ && PY_CALL_TRAMPOLINE
  700. /*****************************/
  701. /* single-phase init modules */
  702. /*****************************/
  703. /*
  704. We support a number of kinds of single-phase init builtin/extension modules:
  705. * "basic"
  706. * no module state (PyModuleDef.m_size == -1)
  707. * does not support repeated init (we use PyModuleDef.m_base.m_copy)
  708. * may have process-global state
  709. * the module's def is cached in _PyRuntime.imports.extensions,
  710. by (name, filename)
  711. * "reinit"
  712. * no module state (PyModuleDef.m_size == 0)
  713. * supports repeated init (m_copy is never used)
  714. * should not have any process-global state
  715. * its def is never cached in _PyRuntime.imports.extensions
  716. (except, currently, under the main interpreter, for some reason)
  717. * "with state" (almost the same as reinit)
  718. * has module state (PyModuleDef.m_size > 0)
  719. * supports repeated init (m_copy is never used)
  720. * should not have any process-global state
  721. * its def is never cached in _PyRuntime.imports.extensions
  722. (except, currently, under the main interpreter, for some reason)
  723. There are also variants within those classes:
  724. * two or more modules share a PyModuleDef
  725. * a module's init func uses another module's PyModuleDef
  726. * a module's init func calls another's module's init func
  727. * a module's init "func" is actually a variable statically initialized
  728. to another module's init func
  729. * two or modules share "methods"
  730. * a module's init func copies another module's PyModuleDef
  731. (with a different name)
  732. * (basic-only) two or modules share process-global state
  733. In the first case, where modules share a PyModuleDef, the following
  734. notable weirdness happens:
  735. * the module's __name__ matches the def, not the requested name
  736. * the last module (with the same def) to be imported for the first time wins
  737. * returned by PyState_Find_Module() (via interp->modules_by_index)
  738. * (non-basic-only) its init func is used when re-loading any of them
  739. (via the def's m_init)
  740. * (basic-only) the copy of its __dict__ is used when re-loading any of them
  741. (via the def's m_copy)
  742. However, the following happens as expected:
  743. * a new module object (with its own __dict__) is created for each request
  744. * the module's __spec__ has the requested name
  745. * the loaded module is cached in sys.modules under the requested name
  746. * the m_index field of the shared def is not changed,
  747. so at least PyState_FindModule() will always look in the same place
  748. For "basic" modules there are other quirks:
  749. * (whether sharing a def or not) when loaded the first time,
  750. m_copy is set before _init_module_attrs() is called
  751. in importlib._bootstrap.module_from_spec(),
  752. so when the module is re-loaded, the previous value
  753. for __wpec__ (and others) is reset, possibly unexpectedly.
  754. Generally, when multiple interpreters are involved, some of the above
  755. gets even messier.
  756. */
  757. static inline void
  758. extensions_lock_acquire(void)
  759. {
  760. PyThread_acquire_lock(_PyRuntime.imports.extensions.mutex, WAIT_LOCK);
  761. }
  762. static inline void
  763. extensions_lock_release(void)
  764. {
  765. PyThread_release_lock(_PyRuntime.imports.extensions.mutex);
  766. }
  767. /* Magic for extension modules (built-in as well as dynamically
  768. loaded). To prevent initializing an extension module more than
  769. once, we keep a static dictionary 'extensions' keyed by the tuple
  770. (module name, module name) (for built-in modules) or by
  771. (filename, module name) (for dynamically loaded modules), containing these
  772. modules. A copy of the module's dictionary is stored by calling
  773. _PyImport_FixupExtensionObject() immediately after the module initialization
  774. function succeeds. A copy can be retrieved from there by calling
  775. import_find_extension().
  776. Modules which do support multiple initialization set their m_size
  777. field to a non-negative number (indicating the size of the
  778. module-specific state). They are still recorded in the extensions
  779. dictionary, to avoid loading shared libraries twice.
  780. */
  781. static void *
  782. hashtable_key_from_2_strings(PyObject *str1, PyObject *str2, const char sep)
  783. {
  784. const char *str1_data = _PyUnicode_AsUTF8NoNUL(str1);
  785. const char *str2_data = _PyUnicode_AsUTF8NoNUL(str2);
  786. if (str1_data == NULL || str2_data == NULL) {
  787. return NULL;
  788. }
  789. Py_ssize_t str1_len = strlen(str1_data);
  790. Py_ssize_t str2_len = strlen(str2_data);
  791. /* Make sure sep and the NULL byte won't cause an overflow. */
  792. assert(SIZE_MAX - str1_len - str2_len > 2);
  793. size_t size = str1_len + 1 + str2_len + 1;
  794. char *key = PyMem_RawMalloc(size);
  795. if (key == NULL) {
  796. PyErr_NoMemory();
  797. return NULL;
  798. }
  799. strncpy(key, str1_data, str1_len);
  800. key[str1_len] = sep;
  801. strncpy(key + str1_len + 1, str2_data, str2_len + 1);
  802. assert(strlen(key) == size - 1);
  803. return key;
  804. }
  805. static Py_uhash_t
  806. hashtable_hash_str(const void *key)
  807. {
  808. return _Py_HashBytes(key, strlen((const char *)key));
  809. }
  810. static int
  811. hashtable_compare_str(const void *key1, const void *key2)
  812. {
  813. return strcmp((const char *)key1, (const char *)key2) == 0;
  814. }
  815. static void
  816. hashtable_destroy_str(void *ptr)
  817. {
  818. PyMem_RawFree(ptr);
  819. }
  820. #define HTSEP ':'
  821. static PyModuleDef *
  822. _extensions_cache_get(PyObject *filename, PyObject *name)
  823. {
  824. PyModuleDef *def = NULL;
  825. void *key = NULL;
  826. extensions_lock_acquire();
  827. if (EXTENSIONS.hashtable == NULL) {
  828. goto finally;
  829. }
  830. key = hashtable_key_from_2_strings(filename, name, HTSEP);
  831. if (key == NULL) {
  832. goto finally;
  833. }
  834. _Py_hashtable_entry_t *entry = _Py_hashtable_get_entry(
  835. EXTENSIONS.hashtable, key);
  836. if (entry == NULL) {
  837. goto finally;
  838. }
  839. def = (PyModuleDef *)entry->value;
  840. finally:
  841. extensions_lock_release();
  842. if (key != NULL) {
  843. PyMem_RawFree(key);
  844. }
  845. return def;
  846. }
  847. static int
  848. _extensions_cache_set(PyObject *filename, PyObject *name, PyModuleDef *def)
  849. {
  850. int res = -1;
  851. extensions_lock_acquire();
  852. if (EXTENSIONS.hashtable == NULL) {
  853. _Py_hashtable_allocator_t alloc = {PyMem_RawMalloc, PyMem_RawFree};
  854. EXTENSIONS.hashtable = _Py_hashtable_new_full(
  855. hashtable_hash_str,
  856. hashtable_compare_str,
  857. hashtable_destroy_str, // key
  858. /* There's no need to decref the def since it's immortal. */
  859. NULL, // value
  860. &alloc
  861. );
  862. if (EXTENSIONS.hashtable == NULL) {
  863. PyErr_NoMemory();
  864. goto finally;
  865. }
  866. }
  867. void *key = hashtable_key_from_2_strings(filename, name, HTSEP);
  868. if (key == NULL) {
  869. goto finally;
  870. }
  871. int already_set = 0;
  872. _Py_hashtable_entry_t *entry = _Py_hashtable_get_entry(
  873. EXTENSIONS.hashtable, key);
  874. if (entry == NULL) {
  875. if (_Py_hashtable_set(EXTENSIONS.hashtable, key, def) < 0) {
  876. PyMem_RawFree(key);
  877. PyErr_NoMemory();
  878. goto finally;
  879. }
  880. }
  881. else {
  882. if (entry->value == NULL) {
  883. entry->value = def;
  884. }
  885. else {
  886. /* We expect it to be static, so it must be the same pointer. */
  887. assert((PyModuleDef *)entry->value == def);
  888. already_set = 1;
  889. }
  890. PyMem_RawFree(key);
  891. }
  892. if (!already_set) {
  893. /* We assume that all module defs are statically allocated
  894. and will never be freed. Otherwise, we would incref here. */
  895. _Py_SetImmortal(def);
  896. }
  897. res = 0;
  898. finally:
  899. extensions_lock_release();
  900. return res;
  901. }
  902. static void
  903. _extensions_cache_delete(PyObject *filename, PyObject *name)
  904. {
  905. void *key = NULL;
  906. extensions_lock_acquire();
  907. if (EXTENSIONS.hashtable == NULL) {
  908. /* It was never added. */
  909. goto finally;
  910. }
  911. key = hashtable_key_from_2_strings(filename, name, HTSEP);
  912. if (key == NULL) {
  913. goto finally;
  914. }
  915. _Py_hashtable_entry_t *entry = _Py_hashtable_get_entry(
  916. EXTENSIONS.hashtable, key);
  917. if (entry == NULL) {
  918. /* It was never added. */
  919. goto finally;
  920. }
  921. if (entry->value == NULL) {
  922. /* It was already removed. */
  923. goto finally;
  924. }
  925. /* If we hadn't made the stored defs immortal, we would decref here.
  926. However, this decref would be problematic if the module def were
  927. dynamically allocated, it were the last ref, and this function
  928. were called with an interpreter other than the def's owner. */
  929. assert(_Py_IsImmortal(entry->value));
  930. entry->value = NULL;
  931. finally:
  932. extensions_lock_release();
  933. if (key != NULL) {
  934. PyMem_RawFree(key);
  935. }
  936. }
  937. static void
  938. _extensions_cache_clear_all(void)
  939. {
  940. /* The runtime (i.e. main interpreter) must be finalizing,
  941. so we don't need to worry about the lock. */
  942. _Py_hashtable_destroy(EXTENSIONS.hashtable);
  943. EXTENSIONS.hashtable = NULL;
  944. }
  945. #undef HTSEP
  946. static bool
  947. check_multi_interp_extensions(PyInterpreterState *interp)
  948. {
  949. int override = OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK(interp);
  950. if (override < 0) {
  951. return false;
  952. }
  953. else if (override > 0) {
  954. return true;
  955. }
  956. else if (_PyInterpreterState_HasFeature(
  957. interp, Py_RTFLAGS_MULTI_INTERP_EXTENSIONS)) {
  958. return true;
  959. }
  960. return false;
  961. }
  962. int
  963. _PyImport_CheckSubinterpIncompatibleExtensionAllowed(const char *name)
  964. {
  965. PyInterpreterState *interp = _PyInterpreterState_Get();
  966. if (check_multi_interp_extensions(interp)) {
  967. assert(!_Py_IsMainInterpreter(interp));
  968. PyErr_Format(PyExc_ImportError,
  969. "module %s does not support loading in subinterpreters",
  970. name);
  971. return -1;
  972. }
  973. return 0;
  974. }
  975. static PyObject *
  976. get_core_module_dict(PyInterpreterState *interp,
  977. PyObject *name, PyObject *filename)
  978. {
  979. /* Only builtin modules are core. */
  980. if (filename == name) {
  981. assert(!PyErr_Occurred());
  982. if (PyUnicode_CompareWithASCIIString(name, "sys") == 0) {
  983. return interp->sysdict_copy;
  984. }
  985. assert(!PyErr_Occurred());
  986. if (PyUnicode_CompareWithASCIIString(name, "builtins") == 0) {
  987. return interp->builtins_copy;
  988. }
  989. assert(!PyErr_Occurred());
  990. }
  991. return NULL;
  992. }
  993. static inline int
  994. is_core_module(PyInterpreterState *interp, PyObject *name, PyObject *filename)
  995. {
  996. /* This might be called before the core dict copies are in place,
  997. so we can't rely on get_core_module_dict() here. */
  998. if (filename == name) {
  999. if (PyUnicode_CompareWithASCIIString(name, "sys") == 0) {
  1000. return 1;
  1001. }
  1002. if (PyUnicode_CompareWithASCIIString(name, "builtins") == 0) {
  1003. return 1;
  1004. }
  1005. }
  1006. return 0;
  1007. }
  1008. static int
  1009. fix_up_extension(PyObject *mod, PyObject *name, PyObject *filename)
  1010. {
  1011. if (mod == NULL || !PyModule_Check(mod)) {
  1012. PyErr_BadInternalCall();
  1013. return -1;
  1014. }
  1015. struct PyModuleDef *def = PyModule_GetDef(mod);
  1016. if (!def) {
  1017. PyErr_BadInternalCall();
  1018. return -1;
  1019. }
  1020. PyThreadState *tstate = _PyThreadState_GET();
  1021. if (_modules_by_index_set(tstate->interp, def, mod) < 0) {
  1022. return -1;
  1023. }
  1024. // bpo-44050: Extensions and def->m_base.m_copy can be updated
  1025. // when the extension module doesn't support sub-interpreters.
  1026. if (def->m_size == -1) {
  1027. if (!is_core_module(tstate->interp, name, filename)) {
  1028. assert(PyUnicode_CompareWithASCIIString(name, "sys") != 0);
  1029. assert(PyUnicode_CompareWithASCIIString(name, "builtins") != 0);
  1030. if (def->m_base.m_copy) {
  1031. /* Somebody already imported the module,
  1032. likely under a different name.
  1033. XXX this should really not happen. */
  1034. Py_CLEAR(def->m_base.m_copy);
  1035. }
  1036. PyObject *dict = PyModule_GetDict(mod);
  1037. if (dict == NULL) {
  1038. return -1;
  1039. }
  1040. def->m_base.m_copy = PyDict_Copy(dict);
  1041. if (def->m_base.m_copy == NULL) {
  1042. return -1;
  1043. }
  1044. }
  1045. }
  1046. // XXX Why special-case the main interpreter?
  1047. if (_Py_IsMainInterpreter(tstate->interp) || def->m_size == -1) {
  1048. if (_extensions_cache_set(filename, name, def) < 0) {
  1049. return -1;
  1050. }
  1051. }
  1052. return 0;
  1053. }
  1054. int
  1055. _PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
  1056. PyObject *filename, PyObject *modules)
  1057. {
  1058. if (PyObject_SetItem(modules, name, mod) < 0) {
  1059. return -1;
  1060. }
  1061. if (fix_up_extension(mod, name, filename) < 0) {
  1062. PyMapping_DelItem(modules, name);
  1063. return -1;
  1064. }
  1065. return 0;
  1066. }
  1067. static PyObject *
  1068. import_find_extension(PyThreadState *tstate, PyObject *name,
  1069. PyObject *filename)
  1070. {
  1071. /* Only single-phase init modules will be in the cache. */
  1072. PyModuleDef *def = _extensions_cache_get(filename, name);
  1073. if (def == NULL) {
  1074. return NULL;
  1075. }
  1076. /* It may have been successfully imported previously
  1077. in an interpreter that allows legacy modules
  1078. but is not allowed in the current interpreter. */
  1079. const char *name_buf = PyUnicode_AsUTF8(name);
  1080. assert(name_buf != NULL);
  1081. if (_PyImport_CheckSubinterpIncompatibleExtensionAllowed(name_buf) < 0) {
  1082. return NULL;
  1083. }
  1084. PyObject *mod, *mdict;
  1085. PyObject *modules = MODULES(tstate->interp);
  1086. if (def->m_size == -1) {
  1087. PyObject *m_copy = def->m_base.m_copy;
  1088. /* Module does not support repeated initialization */
  1089. if (m_copy == NULL) {
  1090. /* It might be a core module (e.g. sys & builtins),
  1091. for which we don't set m_copy. */
  1092. m_copy = get_core_module_dict(tstate->interp, name, filename);
  1093. if (m_copy == NULL) {
  1094. return NULL;
  1095. }
  1096. }
  1097. mod = import_add_module(tstate, name);
  1098. if (mod == NULL) {
  1099. return NULL;
  1100. }
  1101. mdict = PyModule_GetDict(mod);
  1102. if (mdict == NULL) {
  1103. Py_DECREF(mod);
  1104. return NULL;
  1105. }
  1106. if (PyDict_Update(mdict, m_copy)) {
  1107. Py_DECREF(mod);
  1108. return NULL;
  1109. }
  1110. }
  1111. else {
  1112. if (def->m_base.m_init == NULL)
  1113. return NULL;
  1114. mod = _PyImport_InitFunc_TrampolineCall(def->m_base.m_init);
  1115. if (mod == NULL)
  1116. return NULL;
  1117. if (PyObject_SetItem(modules, name, mod) == -1) {
  1118. Py_DECREF(mod);
  1119. return NULL;
  1120. }
  1121. }
  1122. if (_modules_by_index_set(tstate->interp, def, mod) < 0) {
  1123. PyMapping_DelItem(modules, name);
  1124. Py_DECREF(mod);
  1125. return NULL;
  1126. }
  1127. int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
  1128. if (verbose) {
  1129. PySys_FormatStderr("import %U # previously loaded (%R)\n",
  1130. name, filename);
  1131. }
  1132. return mod;
  1133. }
  1134. static int
  1135. clear_singlephase_extension(PyInterpreterState *interp,
  1136. PyObject *name, PyObject *filename)
  1137. {
  1138. PyModuleDef *def = _extensions_cache_get(filename, name);
  1139. if (def == NULL) {
  1140. if (PyErr_Occurred()) {
  1141. return -1;
  1142. }
  1143. return 0;
  1144. }
  1145. /* Clear data set when the module was initially loaded. */
  1146. def->m_base.m_init = NULL;
  1147. Py_CLEAR(def->m_base.m_copy);
  1148. // We leave m_index alone since there's no reason to reset it.
  1149. /* Clear the PyState_*Module() cache entry. */
  1150. if (_modules_by_index_check(interp, def->m_base.m_index) == NULL) {
  1151. if (_modules_by_index_clear_one(interp, def) < 0) {
  1152. return -1;
  1153. }
  1154. }
  1155. /* Clear the cached module def. */
  1156. _extensions_cache_delete(filename, name);
  1157. return 0;
  1158. }
  1159. /*******************/
  1160. /* builtin modules */
  1161. /*******************/
  1162. int
  1163. _PyImport_FixupBuiltin(PyObject *mod, const char *name, PyObject *modules)
  1164. {
  1165. int res = -1;
  1166. PyObject *nameobj;
  1167. nameobj = PyUnicode_InternFromString(name);
  1168. if (nameobj == NULL) {
  1169. return -1;
  1170. }
  1171. if (PyObject_SetItem(modules, nameobj, mod) < 0) {
  1172. goto finally;
  1173. }
  1174. if (fix_up_extension(mod, nameobj, nameobj) < 0) {
  1175. PyMapping_DelItem(modules, nameobj);
  1176. goto finally;
  1177. }
  1178. res = 0;
  1179. finally:
  1180. Py_DECREF(nameobj);
  1181. return res;
  1182. }
  1183. /* Helper to test for built-in module */
  1184. static int
  1185. is_builtin(PyObject *name)
  1186. {
  1187. int i;
  1188. struct _inittab *inittab = INITTAB;
  1189. for (i = 0; inittab[i].name != NULL; i++) {
  1190. if (_PyUnicode_EqualToASCIIString(name, inittab[i].name)) {
  1191. if (inittab[i].initfunc == NULL)
  1192. return -1;
  1193. else
  1194. return 1;
  1195. }
  1196. }
  1197. return 0;
  1198. }
  1199. static PyObject*
  1200. create_builtin(PyThreadState *tstate, PyObject *name, PyObject *spec)
  1201. {
  1202. PyObject *mod = import_find_extension(tstate, name, name);
  1203. if (mod || _PyErr_Occurred(tstate)) {
  1204. return mod;
  1205. }
  1206. PyObject *modules = MODULES(tstate->interp);
  1207. for (struct _inittab *p = INITTAB; p->name != NULL; p++) {
  1208. if (_PyUnicode_EqualToASCIIString(name, p->name)) {
  1209. if (p->initfunc == NULL) {
  1210. /* Cannot re-init internal module ("sys" or "builtins") */
  1211. mod = PyImport_AddModuleObject(name);
  1212. return Py_XNewRef(mod);
  1213. }
  1214. mod = _PyImport_InitFunc_TrampolineCall(*p->initfunc);
  1215. if (mod == NULL) {
  1216. return NULL;
  1217. }
  1218. if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
  1219. return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
  1220. }
  1221. else {
  1222. /* Remember pointer to module init function. */
  1223. PyModuleDef *def = PyModule_GetDef(mod);
  1224. if (def == NULL) {
  1225. return NULL;
  1226. }
  1227. def->m_base.m_init = p->initfunc;
  1228. if (_PyImport_FixupExtensionObject(mod, name, name,
  1229. modules) < 0) {
  1230. return NULL;
  1231. }
  1232. return mod;
  1233. }
  1234. }
  1235. }
  1236. // not found
  1237. Py_RETURN_NONE;
  1238. }
  1239. /*****************************/
  1240. /* the builtin modules table */
  1241. /*****************************/
  1242. /* API for embedding applications that want to add their own entries
  1243. to the table of built-in modules. This should normally be called
  1244. *before* Py_Initialize(). When the table resize fails, -1 is
  1245. returned and the existing table is unchanged.
  1246. After a similar function by Just van Rossum. */
  1247. int
  1248. PyImport_ExtendInittab(struct _inittab *newtab)
  1249. {
  1250. struct _inittab *p;
  1251. size_t i, n;
  1252. int res = 0;
  1253. if (INITTAB != NULL) {
  1254. Py_FatalError("PyImport_ExtendInittab() may not be called after Py_Initialize()");
  1255. }
  1256. /* Count the number of entries in both tables */
  1257. for (n = 0; newtab[n].name != NULL; n++)
  1258. ;
  1259. if (n == 0)
  1260. return 0; /* Nothing to do */
  1261. for (i = 0; PyImport_Inittab[i].name != NULL; i++)
  1262. ;
  1263. /* Force default raw memory allocator to get a known allocator to be able
  1264. to release the memory in _PyImport_Fini2() */
  1265. PyMemAllocatorEx old_alloc;
  1266. _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  1267. /* Allocate new memory for the combined table */
  1268. p = NULL;
  1269. if (i + n <= SIZE_MAX / sizeof(struct _inittab) - 1) {
  1270. size_t size = sizeof(struct _inittab) * (i + n + 1);
  1271. p = PyMem_RawRealloc(inittab_copy, size);
  1272. }
  1273. if (p == NULL) {
  1274. res = -1;
  1275. goto done;
  1276. }
  1277. /* Copy the tables into the new memory at the first call
  1278. to PyImport_ExtendInittab(). */
  1279. if (inittab_copy != PyImport_Inittab) {
  1280. memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
  1281. }
  1282. memcpy(p + i, newtab, (n + 1) * sizeof(struct _inittab));
  1283. PyImport_Inittab = inittab_copy = p;
  1284. done:
  1285. PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  1286. return res;
  1287. }
  1288. /* Shorthand to add a single entry given a name and a function */
  1289. int
  1290. PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
  1291. {
  1292. struct _inittab newtab[2];
  1293. if (INITTAB != NULL) {
  1294. Py_FatalError("PyImport_AppendInittab() may not be called after Py_Initialize()");
  1295. }
  1296. memset(newtab, '\0', sizeof newtab);
  1297. newtab[0].name = name;
  1298. newtab[0].initfunc = initfunc;
  1299. return PyImport_ExtendInittab(newtab);
  1300. }
  1301. /* the internal table */
  1302. static int
  1303. init_builtin_modules_table(void)
  1304. {
  1305. size_t size;
  1306. for (size = 0; PyImport_Inittab[size].name != NULL; size++)
  1307. ;
  1308. size++;
  1309. /* Make the copy. */
  1310. struct _inittab *copied = PyMem_RawMalloc(size * sizeof(struct _inittab));
  1311. if (copied == NULL) {
  1312. return -1;
  1313. }
  1314. memcpy(copied, PyImport_Inittab, size * sizeof(struct _inittab));
  1315. INITTAB = copied;
  1316. return 0;
  1317. }
  1318. static void
  1319. fini_builtin_modules_table(void)
  1320. {
  1321. struct _inittab *inittab = INITTAB;
  1322. INITTAB = NULL;
  1323. PyMem_RawFree(inittab);
  1324. }
  1325. PyObject *
  1326. _PyImport_GetBuiltinModuleNames(void)
  1327. {
  1328. PyObject *list = PyList_New(0);
  1329. if (list == NULL) {
  1330. return NULL;
  1331. }
  1332. struct _inittab *inittab = INITTAB;
  1333. for (Py_ssize_t i = 0; inittab[i].name != NULL; i++) {
  1334. PyObject *name = PyUnicode_FromString(inittab[i].name);
  1335. if (name == NULL) {
  1336. Py_DECREF(list);
  1337. return NULL;
  1338. }
  1339. if (PyList_Append(list, name) < 0) {
  1340. Py_DECREF(name);
  1341. Py_DECREF(list);
  1342. return NULL;
  1343. }
  1344. Py_DECREF(name);
  1345. }
  1346. return list;
  1347. }
  1348. /********************/
  1349. /* the magic number */
  1350. /********************/
  1351. /* Helper for pythonrun.c -- return magic number and tag. */
  1352. long
  1353. PyImport_GetMagicNumber(void)
  1354. {
  1355. long res;
  1356. PyInterpreterState *interp = _PyInterpreterState_GET();
  1357. PyObject *external, *pyc_magic;
  1358. external = PyObject_GetAttrString(IMPORTLIB(interp), "_bootstrap_external");
  1359. if (external == NULL)
  1360. return -1;
  1361. pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER");
  1362. Py_DECREF(external);
  1363. if (pyc_magic == NULL)
  1364. return -1;
  1365. res = PyLong_AsLong(pyc_magic);
  1366. Py_DECREF(pyc_magic);
  1367. return res;
  1368. }
  1369. extern const char * _PySys_ImplCacheTag;
  1370. const char *
  1371. PyImport_GetMagicTag(void)
  1372. {
  1373. return _PySys_ImplCacheTag;
  1374. }
  1375. /*********************************/
  1376. /* a Python module's code object */
  1377. /*********************************/
  1378. /* Execute a code object in a module and return the module object
  1379. * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
  1380. * removed from sys.modules, to avoid leaving damaged module objects
  1381. * in sys.modules. The caller may wish to restore the original
  1382. * module object (if any) in this case; PyImport_ReloadModule is an
  1383. * example.
  1384. *
  1385. * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
  1386. * interface. The other two exist primarily for backward compatibility.
  1387. */
  1388. PyObject *
  1389. PyImport_ExecCodeModule(const char *name, PyObject *co)
  1390. {
  1391. return PyImport_ExecCodeModuleWithPathnames(
  1392. name, co, (char *)NULL, (char *)NULL);
  1393. }
  1394. PyObject *
  1395. PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
  1396. {
  1397. return PyImport_ExecCodeModuleWithPathnames(
  1398. name, co, pathname, (char *)NULL);
  1399. }
  1400. PyObject *
  1401. PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
  1402. const char *pathname,
  1403. const char *cpathname)
  1404. {
  1405. PyObject *m = NULL;
  1406. PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
  1407. nameobj = PyUnicode_FromString(name);
  1408. if (nameobj == NULL)
  1409. return NULL;
  1410. if (cpathname != NULL) {
  1411. cpathobj = PyUnicode_DecodeFSDefault(cpathname);
  1412. if (cpathobj == NULL)
  1413. goto error;
  1414. }
  1415. else
  1416. cpathobj = NULL;
  1417. if (pathname != NULL) {
  1418. pathobj = PyUnicode_DecodeFSDefault(pathname);
  1419. if (pathobj == NULL)
  1420. goto error;
  1421. }
  1422. else if (cpathobj != NULL) {
  1423. PyInterpreterState *interp = _PyInterpreterState_GET();
  1424. if (interp == NULL) {
  1425. Py_FatalError("no current interpreter");
  1426. }
  1427. external= PyObject_GetAttrString(IMPORTLIB(interp),
  1428. "_bootstrap_external");
  1429. if (external != NULL) {
  1430. pathobj = _PyObject_CallMethodOneArg(
  1431. external, &_Py_ID(_get_sourcefile), cpathobj);
  1432. Py_DECREF(external);
  1433. }
  1434. if (pathobj == NULL)
  1435. PyErr_Clear();
  1436. }
  1437. else
  1438. pathobj = NULL;
  1439. m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
  1440. error:
  1441. Py_DECREF(nameobj);
  1442. Py_XDECREF(pathobj);
  1443. Py_XDECREF(cpathobj);
  1444. return m;
  1445. }
  1446. static PyObject *
  1447. module_dict_for_exec(PyThreadState *tstate, PyObject *name)
  1448. {
  1449. PyObject *m, *d;
  1450. m = import_add_module(tstate, name);
  1451. if (m == NULL)
  1452. return NULL;
  1453. /* If the module is being reloaded, we get the old module back
  1454. and re-use its dict to exec the new code. */
  1455. d = PyModule_GetDict(m);
  1456. int r = PyDict_Contains(d, &_Py_ID(__builtins__));
  1457. if (r == 0) {
  1458. r = PyDict_SetItem(d, &_Py_ID(__builtins__), PyEval_GetBuiltins());
  1459. }
  1460. if (r < 0) {
  1461. remove_module(tstate, name);
  1462. Py_DECREF(m);
  1463. return NULL;
  1464. }
  1465. Py_INCREF(d);
  1466. Py_DECREF(m);
  1467. return d;
  1468. }
  1469. static PyObject *
  1470. exec_code_in_module(PyThreadState *tstate, PyObject *name,
  1471. PyObject *module_dict, PyObject *code_object)
  1472. {
  1473. PyObject *v, *m;
  1474. v = PyEval_EvalCode(code_object, module_dict, module_dict);
  1475. if (v == NULL) {
  1476. remove_module(tstate, name);
  1477. return NULL;
  1478. }
  1479. Py_DECREF(v);
  1480. m = import_get_module(tstate, name);
  1481. if (m == NULL && !_PyErr_Occurred(tstate)) {
  1482. _PyErr_Format(tstate, PyExc_ImportError,
  1483. "Loaded module %R not found in sys.modules",
  1484. name);
  1485. }
  1486. return m;
  1487. }
  1488. PyObject*
  1489. PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
  1490. PyObject *cpathname)
  1491. {
  1492. PyThreadState *tstate = _PyThreadState_GET();
  1493. PyObject *d, *external, *res;
  1494. d = module_dict_for_exec(tstate, name);
  1495. if (d == NULL) {
  1496. return NULL;
  1497. }
  1498. if (pathname == NULL) {
  1499. pathname = ((PyCodeObject *)co)->co_filename;
  1500. }
  1501. external = PyObject_GetAttrString(IMPORTLIB(tstate->interp),
  1502. "_bootstrap_external");
  1503. if (external == NULL) {
  1504. Py_DECREF(d);
  1505. return NULL;
  1506. }
  1507. res = PyObject_CallMethodObjArgs(external, &_Py_ID(_fix_up_module),
  1508. d, name, pathname, cpathname, NULL);
  1509. Py_DECREF(external);
  1510. if (res != NULL) {
  1511. Py_DECREF(res);
  1512. res = exec_code_in_module(tstate, name, d, co);
  1513. }
  1514. Py_DECREF(d);
  1515. return res;
  1516. }
  1517. static void
  1518. update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
  1519. {
  1520. PyObject *constants, *tmp;
  1521. Py_ssize_t i, n;
  1522. if (PyUnicode_Compare(co->co_filename, oldname))
  1523. return;
  1524. Py_XSETREF(co->co_filename, Py_NewRef(newname));
  1525. constants = co->co_consts;
  1526. n = PyTuple_GET_SIZE(constants);
  1527. for (i = 0; i < n; i++) {
  1528. tmp = PyTuple_GET_ITEM(constants, i);
  1529. if (PyCode_Check(tmp))
  1530. update_code_filenames((PyCodeObject *)tmp,
  1531. oldname, newname);
  1532. }
  1533. }
  1534. static void
  1535. update_compiled_module(PyCodeObject *co, PyObject *newname)
  1536. {
  1537. PyObject *oldname;
  1538. if (PyUnicode_Compare(co->co_filename, newname) == 0)
  1539. return;
  1540. oldname = co->co_filename;
  1541. Py_INCREF(oldname);
  1542. update_code_filenames(co, oldname, newname);
  1543. Py_DECREF(oldname);
  1544. }
  1545. /******************/
  1546. /* frozen modules */
  1547. /******************/
  1548. /* Return true if the name is an alias. In that case, "alias" is set
  1549. to the original module name. If it is an alias but the original
  1550. module isn't known then "alias" is set to NULL while true is returned. */
  1551. static bool
  1552. resolve_module_alias(const char *name, const struct _module_alias *aliases,
  1553. const char **alias)
  1554. {
  1555. const struct _module_alias *entry;
  1556. for (entry = aliases; ; entry++) {
  1557. if (entry->name == NULL) {
  1558. /* It isn't an alias. */
  1559. return false;
  1560. }
  1561. if (strcmp(name, entry->name) == 0) {
  1562. if (alias != NULL) {
  1563. *alias = entry->orig;
  1564. }
  1565. return true;
  1566. }
  1567. }
  1568. }
  1569. static bool
  1570. use_frozen(void)
  1571. {
  1572. PyInterpreterState *interp = _PyInterpreterState_GET();
  1573. int override = OVERRIDE_FROZEN_MODULES(interp);
  1574. if (override > 0) {
  1575. return true;
  1576. }
  1577. else if (override < 0) {
  1578. return false;
  1579. }
  1580. else {
  1581. return interp->config.use_frozen_modules;
  1582. }
  1583. }
  1584. static PyObject *
  1585. list_frozen_module_names(void)
  1586. {
  1587. PyObject *names = PyList_New(0);
  1588. if (names == NULL) {
  1589. return NULL;
  1590. }
  1591. bool enabled = use_frozen();
  1592. const struct _frozen *p;
  1593. #define ADD_MODULE(name) \
  1594. do { \
  1595. PyObject *nameobj = PyUnicode_FromString(name); \
  1596. if (nameobj == NULL) { \
  1597. goto error; \
  1598. } \
  1599. int res = PyList_Append(names, nameobj); \
  1600. Py_DECREF(nameobj); \
  1601. if (res != 0) { \
  1602. goto error; \
  1603. } \
  1604. } while(0)
  1605. // We always use the bootstrap modules.
  1606. for (p = _PyImport_FrozenBootstrap; ; p++) {
  1607. if (p->name == NULL) {
  1608. break;
  1609. }
  1610. ADD_MODULE(p->name);
  1611. }
  1612. // Frozen stdlib modules may be disabled.
  1613. for (p = _PyImport_FrozenStdlib; ; p++) {
  1614. if (p->name == NULL) {
  1615. break;
  1616. }
  1617. if (enabled) {
  1618. ADD_MODULE(p->name);
  1619. }
  1620. }
  1621. for (p = _PyImport_FrozenTest; ; p++) {
  1622. if (p->name == NULL) {
  1623. break;
  1624. }
  1625. if (enabled) {
  1626. ADD_MODULE(p->name);
  1627. }
  1628. }
  1629. #undef ADD_MODULE
  1630. // Add any custom modules.
  1631. if (PyImport_FrozenModules != NULL) {
  1632. for (p = PyImport_FrozenModules; ; p++) {
  1633. if (p->name == NULL) {
  1634. break;
  1635. }
  1636. PyObject *nameobj = PyUnicode_FromString(p->name);
  1637. if (nameobj == NULL) {
  1638. goto error;
  1639. }
  1640. int found = PySequence_Contains(names, nameobj);
  1641. if (found < 0) {
  1642. Py_DECREF(nameobj);
  1643. goto error;
  1644. }
  1645. else if (found) {
  1646. Py_DECREF(nameobj);
  1647. }
  1648. else {
  1649. int res = PyList_Append(names, nameobj);
  1650. Py_DECREF(nameobj);
  1651. if (res != 0) {
  1652. goto error;
  1653. }
  1654. }
  1655. }
  1656. }
  1657. return names;
  1658. error:
  1659. Py_DECREF(names);
  1660. return NULL;
  1661. }
  1662. typedef enum {
  1663. FROZEN_OKAY,
  1664. FROZEN_BAD_NAME, // The given module name wasn't valid.
  1665. FROZEN_NOT_FOUND, // It wasn't in PyImport_FrozenModules.
  1666. FROZEN_DISABLED, // -X frozen_modules=off (and not essential)
  1667. FROZEN_EXCLUDED, /* The PyImport_FrozenModules entry has NULL "code"
  1668. (module is present but marked as unimportable, stops search). */
  1669. FROZEN_INVALID, /* The PyImport_FrozenModules entry is bogus
  1670. (eg. does not contain executable code). */
  1671. } frozen_status;
  1672. static inline void
  1673. set_frozen_error(frozen_status status, PyObject *modname)
  1674. {
  1675. const char *err = NULL;
  1676. switch (status) {
  1677. case FROZEN_BAD_NAME:
  1678. case FROZEN_NOT_FOUND:
  1679. err = "No such frozen object named %R";
  1680. break;
  1681. case FROZEN_DISABLED:
  1682. err = "Frozen modules are disabled and the frozen object named %R is not essential";
  1683. break;
  1684. case FROZEN_EXCLUDED:
  1685. err = "Excluded frozen object named %R";
  1686. break;
  1687. case FROZEN_INVALID:
  1688. err = "Frozen object named %R is invalid";
  1689. break;
  1690. case FROZEN_OKAY:
  1691. // There was no error.
  1692. break;
  1693. default:
  1694. Py_UNREACHABLE();
  1695. }
  1696. if (err != NULL) {
  1697. PyObject *msg = PyUnicode_FromFormat(err, modname);
  1698. if (msg == NULL) {
  1699. PyErr_Clear();
  1700. }
  1701. PyErr_SetImportError(msg, modname, NULL);
  1702. Py_XDECREF(msg);
  1703. }
  1704. }
  1705. static const struct _frozen *
  1706. look_up_frozen(const char *name)
  1707. {
  1708. const struct _frozen *p;
  1709. // We always use the bootstrap modules.
  1710. for (p = _PyImport_FrozenBootstrap; ; p++) {
  1711. if (p->name == NULL) {
  1712. // We hit the end-of-list sentinel value.
  1713. break;
  1714. }
  1715. if (strcmp(name, p->name) == 0) {
  1716. return p;
  1717. }
  1718. }
  1719. // Prefer custom modules, if any. Frozen stdlib modules can be
  1720. // disabled here by setting "code" to NULL in the array entry.
  1721. if (PyImport_FrozenModules != NULL) {
  1722. for (p = PyImport_FrozenModules; ; p++) {
  1723. if (p->name == NULL) {
  1724. break;
  1725. }
  1726. if (strcmp(name, p->name) == 0) {
  1727. return p;
  1728. }
  1729. }
  1730. }
  1731. // Frozen stdlib modules may be disabled.
  1732. if (use_frozen()) {
  1733. for (p = _PyImport_FrozenStdlib; ; p++) {
  1734. if (p->name == NULL) {
  1735. break;
  1736. }
  1737. if (strcmp(name, p->name) == 0) {
  1738. return p;
  1739. }
  1740. }
  1741. for (p = _PyImport_FrozenTest; ; p++) {
  1742. if (p->name == NULL) {
  1743. break;
  1744. }
  1745. if (strcmp(name, p->name) == 0) {
  1746. return p;
  1747. }
  1748. }
  1749. }
  1750. return NULL;
  1751. }
  1752. struct frozen_info {
  1753. PyObject *nameobj;
  1754. const char *data;
  1755. PyObject *(*get_code)(void);
  1756. Py_ssize_t size;
  1757. bool is_package;
  1758. bool is_alias;
  1759. const char *origname;
  1760. };
  1761. static frozen_status
  1762. find_frozen(PyObject *nameobj, struct frozen_info *info)
  1763. {
  1764. if (info != NULL) {
  1765. memset(info, 0, sizeof(*info));
  1766. }
  1767. if (nameobj == NULL || nameobj == Py_None) {
  1768. return FROZEN_BAD_NAME;
  1769. }
  1770. const char *name = PyUnicode_AsUTF8(nameobj);
  1771. if (name == NULL) {
  1772. // Note that this function previously used
  1773. // _PyUnicode_EqualToASCIIString(). We clear the error here
  1774. // (instead of propagating it) to match the earlier behavior
  1775. // more closely.
  1776. PyErr_Clear();
  1777. return FROZEN_BAD_NAME;
  1778. }
  1779. const struct _frozen *p = look_up_frozen(name);
  1780. if (p == NULL) {
  1781. return FROZEN_NOT_FOUND;
  1782. }
  1783. if (info != NULL) {
  1784. info->nameobj = nameobj; // borrowed
  1785. info->data = (const char *)p->code;
  1786. info->get_code = p->get_code;
  1787. info->size = p->size;
  1788. info->is_package = p->is_package;
  1789. if (p->size < 0) {
  1790. // backward compatibility with negative size values
  1791. info->size = -(p->size);
  1792. info->is_package = true;
  1793. }
  1794. info->origname = name;
  1795. info->is_alias = resolve_module_alias(name, _PyImport_FrozenAliases,
  1796. &info->origname);
  1797. }
  1798. if (p->code == NULL && p->size == 0 && p->get_code != NULL) {
  1799. /* It is only deepfrozen. */
  1800. return FROZEN_OKAY;
  1801. }
  1802. if (p->code == NULL) {
  1803. /* It is frozen but marked as un-importable. */
  1804. return FROZEN_EXCLUDED;
  1805. }
  1806. if (p->code[0] == '\0' || p->size == 0) {
  1807. /* Does not contain executable code. */
  1808. return FROZEN_INVALID;
  1809. }
  1810. return FROZEN_OKAY;
  1811. }
  1812. static PyObject *
  1813. unmarshal_frozen_code(PyInterpreterState *interp, struct frozen_info *info)
  1814. {
  1815. if (info->get_code && _Py_IsMainInterpreter(interp)) {
  1816. PyObject *code = info->get_code();
  1817. assert(code != NULL);
  1818. return code;
  1819. }
  1820. PyObject *co = PyMarshal_ReadObjectFromString(info->data, info->size);
  1821. if (co == NULL) {
  1822. /* Does not contain executable code. */
  1823. PyErr_Clear();
  1824. set_frozen_error(FROZEN_INVALID, info->nameobj);
  1825. return NULL;
  1826. }
  1827. if (!PyCode_Check(co)) {
  1828. // We stick with TypeError for backward compatibility.
  1829. PyErr_Format(PyExc_TypeError,
  1830. "frozen object %R is not a code object",
  1831. info->nameobj);
  1832. Py_DECREF(co);
  1833. return NULL;
  1834. }
  1835. return co;
  1836. }
  1837. /* Initialize a frozen module.
  1838. Return 1 for success, 0 if the module is not found, and -1 with
  1839. an exception set if the initialization failed.
  1840. This function is also used from frozenmain.c */
  1841. int
  1842. PyImport_ImportFrozenModuleObject(PyObject *name)
  1843. {
  1844. PyThreadState *tstate = _PyThreadState_GET();
  1845. PyObject *co, *m, *d = NULL;
  1846. int err;
  1847. struct frozen_info info;
  1848. frozen_status status = find_frozen(name, &info);
  1849. if (status == FROZEN_NOT_FOUND || status == FROZEN_DISABLED) {
  1850. return 0;
  1851. }
  1852. else if (status == FROZEN_BAD_NAME) {
  1853. return 0;
  1854. }
  1855. else if (status != FROZEN_OKAY) {
  1856. set_frozen_error(status, name);
  1857. return -1;
  1858. }
  1859. co = unmarshal_frozen_code(tstate->interp, &info);
  1860. if (co == NULL) {
  1861. return -1;
  1862. }
  1863. if (info.is_package) {
  1864. /* Set __path__ to the empty list */
  1865. PyObject *l;
  1866. m = import_add_module(tstate, name);
  1867. if (m == NULL)
  1868. goto err_return;
  1869. d = PyModule_GetDict(m);
  1870. l = PyList_New(0);
  1871. if (l == NULL) {
  1872. Py_DECREF(m);
  1873. goto err_return;
  1874. }
  1875. err = PyDict_SetItemString(d, "__path__", l);
  1876. Py_DECREF(l);
  1877. Py_DECREF(m);
  1878. if (err != 0)
  1879. goto err_return;
  1880. }
  1881. d = module_dict_for_exec(tstate, name);
  1882. if (d == NULL) {
  1883. goto err_return;
  1884. }
  1885. m = exec_code_in_module(tstate, name, d, co);
  1886. if (m == NULL) {
  1887. goto err_return;
  1888. }
  1889. Py_DECREF(m);
  1890. /* Set __origname__ (consumed in FrozenImporter._setup_module()). */
  1891. PyObject *origname;
  1892. if (info.origname) {
  1893. origname = PyUnicode_FromString(info.origname);
  1894. if (origname == NULL) {
  1895. goto err_return;
  1896. }
  1897. }
  1898. else {
  1899. origname = Py_NewRef(Py_None);
  1900. }
  1901. err = PyDict_SetItemString(d, "__origname__", origname);
  1902. Py_DECREF(origname);
  1903. if (err != 0) {
  1904. goto err_return;
  1905. }
  1906. Py_DECREF(d);
  1907. Py_DECREF(co);
  1908. return 1;
  1909. err_return:
  1910. Py_XDECREF(d);
  1911. Py_DECREF(co);
  1912. return -1;
  1913. }
  1914. int
  1915. PyImport_ImportFrozenModule(const char *name)
  1916. {
  1917. PyObject *nameobj;
  1918. int ret;
  1919. nameobj = PyUnicode_InternFromString(name);
  1920. if (nameobj == NULL)
  1921. return -1;
  1922. ret = PyImport_ImportFrozenModuleObject(nameobj);
  1923. Py_DECREF(nameobj);
  1924. return ret;
  1925. }
  1926. /*************/
  1927. /* importlib */
  1928. /*************/
  1929. /* Import the _imp extension by calling manually _imp.create_builtin() and
  1930. _imp.exec_builtin() since importlib is not initialized yet. Initializing
  1931. importlib requires the _imp module: this function fix the bootstrap issue.
  1932. */
  1933. static PyObject*
  1934. bootstrap_imp(PyThreadState *tstate)
  1935. {
  1936. PyObject *name = PyUnicode_FromString("_imp");
  1937. if (name == NULL) {
  1938. return NULL;
  1939. }
  1940. // Mock a ModuleSpec object just good enough for PyModule_FromDefAndSpec():
  1941. // an object with just a name attribute.
  1942. //
  1943. // _imp.__spec__ is overridden by importlib._bootstrap._instal() anyway.
  1944. PyObject *attrs = Py_BuildValue("{sO}", "name", name);
  1945. if (attrs == NULL) {
  1946. goto error;
  1947. }
  1948. PyObject *spec = _PyNamespace_New(attrs);
  1949. Py_DECREF(attrs);
  1950. if (spec == NULL) {
  1951. goto error;
  1952. }
  1953. // Create the _imp module from its definition.
  1954. PyObject *mod = create_builtin(tstate, name, spec);
  1955. Py_CLEAR(name);
  1956. Py_DECREF(spec);
  1957. if (mod == NULL) {
  1958. goto error;
  1959. }
  1960. assert(mod != Py_None); // not found
  1961. // Execute the _imp module: call imp_module_exec().
  1962. if (exec_builtin_or_dynamic(mod) < 0) {
  1963. Py_DECREF(mod);
  1964. goto error;
  1965. }
  1966. return mod;
  1967. error:
  1968. Py_XDECREF(name);
  1969. return NULL;
  1970. }
  1971. /* Global initializations. Can be undone by Py_FinalizeEx(). Don't
  1972. call this twice without an intervening Py_FinalizeEx() call. When
  1973. initializations fail, a fatal error is issued and the function does
  1974. not return. On return, the first thread and interpreter state have
  1975. been created.
  1976. Locking: you must hold the interpreter lock while calling this.
  1977. (If the lock has not yet been initialized, that's equivalent to
  1978. having the lock, but you cannot use multiple threads.)
  1979. */
  1980. static int
  1981. init_importlib(PyThreadState *tstate, PyObject *sysmod)
  1982. {
  1983. assert(!_PyErr_Occurred(tstate));
  1984. PyInterpreterState *interp = tstate->interp;
  1985. int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
  1986. // Import _importlib through its frozen version, _frozen_importlib.
  1987. if (verbose) {
  1988. PySys_FormatStderr("import _frozen_importlib # frozen\n");
  1989. }
  1990. if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
  1991. return -1;
  1992. }
  1993. PyObject *importlib = PyImport_AddModule("_frozen_importlib"); // borrowed
  1994. if (importlib == NULL) {
  1995. return -1;
  1996. }
  1997. IMPORTLIB(interp) = Py_NewRef(importlib);
  1998. // Import the _imp module
  1999. if (verbose) {
  2000. PySys_FormatStderr("import _imp # builtin\n");
  2001. }
  2002. PyObject *imp_mod = bootstrap_imp(tstate);
  2003. if (imp_mod == NULL) {
  2004. return -1;
  2005. }
  2006. if (_PyImport_SetModuleString("_imp", imp_mod) < 0) {
  2007. Py_DECREF(imp_mod);
  2008. return -1;
  2009. }
  2010. // Install importlib as the implementation of import
  2011. PyObject *value = PyObject_CallMethod(importlib, "_install",
  2012. "OO", sysmod, imp_mod);
  2013. Py_DECREF(imp_mod);
  2014. if (value == NULL) {
  2015. return -1;
  2016. }
  2017. Py_DECREF(value);
  2018. assert(!_PyErr_Occurred(tstate));
  2019. return 0;
  2020. }
  2021. static int
  2022. init_importlib_external(PyInterpreterState *interp)
  2023. {
  2024. PyObject *value;
  2025. value = PyObject_CallMethod(IMPORTLIB(interp),
  2026. "_install_external_importers", "");
  2027. if (value == NULL) {
  2028. return -1;
  2029. }
  2030. Py_DECREF(value);
  2031. value = PyImport_ImportModule("__res");
  2032. if (value == NULL) {
  2033. return -1;
  2034. }
  2035. Py_DECREF(value);
  2036. return 0;
  2037. }
  2038. PyObject *
  2039. _PyImport_GetImportlibLoader(PyInterpreterState *interp,
  2040. const char *loader_name)
  2041. {
  2042. return PyObject_GetAttrString(IMPORTLIB(interp), loader_name);
  2043. }
  2044. PyObject *
  2045. _PyImport_GetImportlibExternalLoader(PyInterpreterState *interp,
  2046. const char *loader_name)
  2047. {
  2048. PyObject *bootstrap = PyObject_GetAttrString(IMPORTLIB(interp),
  2049. "_bootstrap_external");
  2050. if (bootstrap == NULL) {
  2051. return NULL;
  2052. }
  2053. PyObject *loader_type = PyObject_GetAttrString(bootstrap, loader_name);
  2054. Py_DECREF(bootstrap);
  2055. return loader_type;
  2056. }
  2057. PyObject *
  2058. _PyImport_BlessMyLoader(PyInterpreterState *interp, PyObject *module_globals)
  2059. {
  2060. PyObject *external = PyObject_GetAttrString(IMPORTLIB(interp),
  2061. "_bootstrap_external");
  2062. if (external == NULL) {
  2063. return NULL;
  2064. }
  2065. PyObject *loader = PyObject_CallMethod(external, "_bless_my_loader",
  2066. "O", module_globals, NULL);
  2067. Py_DECREF(external);
  2068. return loader;
  2069. }
  2070. PyObject *
  2071. _PyImport_ImportlibModuleRepr(PyInterpreterState *interp, PyObject *m)
  2072. {
  2073. return PyObject_CallMethod(IMPORTLIB(interp), "_module_repr", "O", m);
  2074. }
  2075. /*******************/
  2076. /* Return a finder object for a sys.path/pkg.__path__ item 'p',
  2077. possibly by fetching it from the path_importer_cache dict. If it
  2078. wasn't yet cached, traverse path_hooks until a hook is found
  2079. that can handle the path item. Return None if no hook could;
  2080. this tells our caller that the path based finder could not find
  2081. a finder for this path item. Cache the result in
  2082. path_importer_cache. */
  2083. static PyObject *
  2084. get_path_importer(PyThreadState *tstate, PyObject *path_importer_cache,
  2085. PyObject *path_hooks, PyObject *p)
  2086. {
  2087. PyObject *importer;
  2088. Py_ssize_t j, nhooks;
  2089. if (!PyList_Check(path_hooks)) {
  2090. PyErr_SetString(PyExc_RuntimeError, "sys.path_hooks is not a list");
  2091. return NULL;
  2092. }
  2093. if (!PyDict_Check(path_importer_cache)) {
  2094. PyErr_SetString(PyExc_RuntimeError, "sys.path_importer_cache is not a dict");
  2095. return NULL;
  2096. }
  2097. nhooks = PyList_Size(path_hooks);
  2098. if (nhooks < 0)
  2099. return NULL; /* Shouldn't happen */
  2100. importer = PyDict_GetItemWithError(path_importer_cache, p);
  2101. if (importer != NULL || _PyErr_Occurred(tstate)) {
  2102. return Py_XNewRef(importer);
  2103. }
  2104. /* set path_importer_cache[p] to None to avoid recursion */
  2105. if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
  2106. return NULL;
  2107. for (j = 0; j < nhooks; j++) {
  2108. PyObject *hook = PyList_GetItem(path_hooks, j);
  2109. if (hook == NULL)
  2110. return NULL;
  2111. importer = PyObject_CallOneArg(hook, p);
  2112. if (importer != NULL)
  2113. break;
  2114. if (!_PyErr_ExceptionMatches(tstate, PyExc_ImportError)) {
  2115. return NULL;
  2116. }
  2117. _PyErr_Clear(tstate);
  2118. }
  2119. if (importer == NULL) {
  2120. Py_RETURN_NONE;
  2121. }
  2122. if (PyDict_SetItem(path_importer_cache, p, importer) < 0) {
  2123. Py_DECREF(importer);
  2124. return NULL;
  2125. }
  2126. return importer;
  2127. }
  2128. PyObject *
  2129. PyImport_GetImporter(PyObject *path)
  2130. {
  2131. PyThreadState *tstate = _PyThreadState_GET();
  2132. PyObject *path_importer_cache = PySys_GetObject("path_importer_cache");
  2133. if (path_importer_cache == NULL) {
  2134. PyErr_SetString(PyExc_RuntimeError, "lost sys.path_importer_cache");
  2135. return NULL;
  2136. }
  2137. Py_INCREF(path_importer_cache);
  2138. PyObject *path_hooks = PySys_GetObject("path_hooks");
  2139. if (path_hooks == NULL) {
  2140. PyErr_SetString(PyExc_RuntimeError, "lost sys.path_hooks");
  2141. Py_DECREF(path_importer_cache);
  2142. return NULL;
  2143. }
  2144. Py_INCREF(path_hooks);
  2145. PyObject *importer = get_path_importer(tstate, path_importer_cache, path_hooks, path);
  2146. Py_DECREF(path_hooks);
  2147. Py_DECREF(path_importer_cache);
  2148. return importer;
  2149. }
  2150. /*********************/
  2151. /* importing modules */
  2152. /*********************/
  2153. int
  2154. _PyImport_InitDefaultImportFunc(PyInterpreterState *interp)
  2155. {
  2156. // Get the __import__ function
  2157. PyObject *import_func = _PyDict_GetItemStringWithError(interp->builtins,
  2158. "__import__");
  2159. if (import_func == NULL) {
  2160. return -1;
  2161. }
  2162. IMPORT_FUNC(interp) = Py_NewRef(import_func);
  2163. return 0;
  2164. }
  2165. int
  2166. _PyImport_IsDefaultImportFunc(PyInterpreterState *interp, PyObject *func)
  2167. {
  2168. return func == IMPORT_FUNC(interp);
  2169. }
  2170. /* Import a module, either built-in, frozen, or external, and return
  2171. its module object WITH INCREMENTED REFERENCE COUNT */
  2172. PyObject *
  2173. PyImport_ImportModule(const char *name)
  2174. {
  2175. PyObject *pname;
  2176. PyObject *result;
  2177. pname = PyUnicode_FromString(name);
  2178. if (pname == NULL)
  2179. return NULL;
  2180. result = PyImport_Import(pname);
  2181. Py_DECREF(pname);
  2182. return result;
  2183. }
  2184. /* Import a module without blocking
  2185. *
  2186. * At first it tries to fetch the module from sys.modules. If the module was
  2187. * never loaded before it loads it with PyImport_ImportModule() unless another
  2188. * thread holds the import lock. In the latter case the function raises an
  2189. * ImportError instead of blocking.
  2190. *
  2191. * Returns the module object with incremented ref count.
  2192. */
  2193. PyObject *
  2194. PyImport_ImportModuleNoBlock(const char *name)
  2195. {
  2196. return PyImport_ImportModule(name);
  2197. }
  2198. /* Remove importlib frames from the traceback,
  2199. * except in Verbose mode. */
  2200. static void
  2201. remove_importlib_frames(PyThreadState *tstate)
  2202. {
  2203. const char *importlib_filename = "<frozen importlib._bootstrap>";
  2204. const char *external_filename = "<frozen importlib._bootstrap_external>";
  2205. const char *importer_filename = "library/python/runtime_py3/importer.pxi";
  2206. const char *remove_frames = "_call_with_frames_removed";
  2207. int always_trim = 0;
  2208. int in_importlib = 0;
  2209. PyObject **prev_link, **outer_link = NULL;
  2210. PyObject *base_tb = NULL;
  2211. /* Synopsis: if it's an ImportError, we trim all importlib chunks
  2212. from the traceback. We always trim chunks
  2213. which end with a call to "_call_with_frames_removed". */
  2214. PyObject *exc = _PyErr_GetRaisedException(tstate);
  2215. if (exc == NULL || _PyInterpreterState_GetConfig(tstate->interp)->verbose) {
  2216. goto done;
  2217. }
  2218. if (PyType_IsSubtype(Py_TYPE(exc), (PyTypeObject *) PyExc_ImportError)) {
  2219. always_trim = 1;
  2220. }
  2221. assert(PyExceptionInstance_Check(exc));
  2222. base_tb = PyException_GetTraceback(exc);
  2223. prev_link = &base_tb;
  2224. PyObject *tb = base_tb;
  2225. while (tb != NULL) {
  2226. assert(PyTraceBack_Check(tb));
  2227. PyTracebackObject *traceback = (PyTracebackObject *)tb;
  2228. PyObject *next = (PyObject *) traceback->tb_next;
  2229. PyFrameObject *frame = traceback->tb_frame;
  2230. PyCodeObject *code = PyFrame_GetCode(frame);
  2231. int now_in_importlib;
  2232. now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
  2233. _PyUnicode_EqualToASCIIString(code->co_filename, external_filename) ||
  2234. _PyUnicode_EqualToASCIIString(code->co_filename, importer_filename);
  2235. if (now_in_importlib && !in_importlib) {
  2236. /* This is the link to this chunk of importlib tracebacks */
  2237. outer_link = prev_link;
  2238. }
  2239. in_importlib = now_in_importlib;
  2240. if (in_importlib &&
  2241. (always_trim ||
  2242. _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
  2243. Py_XSETREF(*outer_link, Py_XNewRef(next));
  2244. prev_link = outer_link;
  2245. }
  2246. else {
  2247. prev_link = (PyObject **) &traceback->tb_next;
  2248. }
  2249. Py_DECREF(code);
  2250. tb = next;
  2251. }
  2252. if (base_tb == NULL) {
  2253. base_tb = Py_None;
  2254. Py_INCREF(Py_None);
  2255. }
  2256. PyException_SetTraceback(exc, base_tb);
  2257. done:
  2258. Py_XDECREF(base_tb);
  2259. _PyErr_SetRaisedException(tstate, exc);
  2260. }
  2261. static PyObject *
  2262. resolve_name(PyThreadState *tstate, PyObject *name, PyObject *globals, int level)
  2263. {
  2264. PyObject *abs_name;
  2265. PyObject *package = NULL;
  2266. PyObject *spec;
  2267. Py_ssize_t last_dot;
  2268. PyObject *base;
  2269. int level_up;
  2270. if (globals == NULL) {
  2271. _PyErr_SetString(tstate, PyExc_KeyError, "'__name__' not in globals");
  2272. goto error;
  2273. }
  2274. if (!PyDict_Check(globals)) {
  2275. _PyErr_SetString(tstate, PyExc_TypeError, "globals must be a dict");
  2276. goto error;
  2277. }
  2278. package = PyDict_GetItemWithError(globals, &_Py_ID(__package__));
  2279. if (package == Py_None) {
  2280. package = NULL;
  2281. }
  2282. else if (package == NULL && _PyErr_Occurred(tstate)) {
  2283. goto error;
  2284. }
  2285. spec = PyDict_GetItemWithError(globals, &_Py_ID(__spec__));
  2286. if (spec == NULL && _PyErr_Occurred(tstate)) {
  2287. goto error;
  2288. }
  2289. if (package != NULL) {
  2290. Py_INCREF(package);
  2291. if (!PyUnicode_Check(package)) {
  2292. _PyErr_SetString(tstate, PyExc_TypeError,
  2293. "package must be a string");
  2294. goto error;
  2295. }
  2296. else if (spec != NULL && spec != Py_None) {
  2297. int equal;
  2298. PyObject *parent = PyObject_GetAttr(spec, &_Py_ID(parent));
  2299. if (parent == NULL) {
  2300. goto error;
  2301. }
  2302. equal = PyObject_RichCompareBool(package, parent, Py_EQ);
  2303. Py_DECREF(parent);
  2304. if (equal < 0) {
  2305. goto error;
  2306. }
  2307. else if (equal == 0) {
  2308. if (PyErr_WarnEx(PyExc_DeprecationWarning,
  2309. "__package__ != __spec__.parent", 1) < 0) {
  2310. goto error;
  2311. }
  2312. }
  2313. }
  2314. }
  2315. else if (spec != NULL && spec != Py_None) {
  2316. package = PyObject_GetAttr(spec, &_Py_ID(parent));
  2317. if (package == NULL) {
  2318. goto error;
  2319. }
  2320. else if (!PyUnicode_Check(package)) {
  2321. _PyErr_SetString(tstate, PyExc_TypeError,
  2322. "__spec__.parent must be a string");
  2323. goto error;
  2324. }
  2325. }
  2326. else {
  2327. if (PyErr_WarnEx(PyExc_ImportWarning,
  2328. "can't resolve package from __spec__ or __package__, "
  2329. "falling back on __name__ and __path__", 1) < 0) {
  2330. goto error;
  2331. }
  2332. package = PyDict_GetItemWithError(globals, &_Py_ID(__name__));
  2333. if (package == NULL) {
  2334. if (!_PyErr_Occurred(tstate)) {
  2335. _PyErr_SetString(tstate, PyExc_KeyError,
  2336. "'__name__' not in globals");
  2337. }
  2338. goto error;
  2339. }
  2340. Py_INCREF(package);
  2341. if (!PyUnicode_Check(package)) {
  2342. _PyErr_SetString(tstate, PyExc_TypeError,
  2343. "__name__ must be a string");
  2344. goto error;
  2345. }
  2346. int haspath = PyDict_Contains(globals, &_Py_ID(__path__));
  2347. if (haspath < 0) {
  2348. goto error;
  2349. }
  2350. if (!haspath) {
  2351. Py_ssize_t dot;
  2352. if (PyUnicode_READY(package) < 0) {
  2353. goto error;
  2354. }
  2355. dot = PyUnicode_FindChar(package, '.',
  2356. 0, PyUnicode_GET_LENGTH(package), -1);
  2357. if (dot == -2) {
  2358. goto error;
  2359. }
  2360. else if (dot == -1) {
  2361. goto no_parent_error;
  2362. }
  2363. PyObject *substr = PyUnicode_Substring(package, 0, dot);
  2364. if (substr == NULL) {
  2365. goto error;
  2366. }
  2367. Py_SETREF(package, substr);
  2368. }
  2369. }
  2370. last_dot = PyUnicode_GET_LENGTH(package);
  2371. if (last_dot == 0) {
  2372. goto no_parent_error;
  2373. }
  2374. for (level_up = 1; level_up < level; level_up += 1) {
  2375. last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
  2376. if (last_dot == -2) {
  2377. goto error;
  2378. }
  2379. else if (last_dot == -1) {
  2380. _PyErr_SetString(tstate, PyExc_ImportError,
  2381. "attempted relative import beyond top-level "
  2382. "package");
  2383. goto error;
  2384. }
  2385. }
  2386. base = PyUnicode_Substring(package, 0, last_dot);
  2387. Py_DECREF(package);
  2388. if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
  2389. return base;
  2390. }
  2391. abs_name = PyUnicode_FromFormat("%U.%U", base, name);
  2392. Py_DECREF(base);
  2393. return abs_name;
  2394. no_parent_error:
  2395. _PyErr_SetString(tstate, PyExc_ImportError,
  2396. "attempted relative import "
  2397. "with no known parent package");
  2398. error:
  2399. Py_XDECREF(package);
  2400. return NULL;
  2401. }
  2402. static PyObject *
  2403. import_find_and_load(PyThreadState *tstate, PyObject *abs_name)
  2404. {
  2405. PyObject *mod = NULL;
  2406. PyInterpreterState *interp = tstate->interp;
  2407. int import_time = _PyInterpreterState_GetConfig(interp)->import_time;
  2408. #define import_level FIND_AND_LOAD(interp).import_level
  2409. #define accumulated FIND_AND_LOAD(interp).accumulated
  2410. _PyTime_t t1 = 0, accumulated_copy = accumulated;
  2411. PyObject *sys_path = PySys_GetObject("path");
  2412. PyObject *sys_meta_path = PySys_GetObject("meta_path");
  2413. PyObject *sys_path_hooks = PySys_GetObject("path_hooks");
  2414. if (_PySys_Audit(tstate, "import", "OOOOO",
  2415. abs_name, Py_None, sys_path ? sys_path : Py_None,
  2416. sys_meta_path ? sys_meta_path : Py_None,
  2417. sys_path_hooks ? sys_path_hooks : Py_None) < 0) {
  2418. return NULL;
  2419. }
  2420. /* XOptions is initialized after first some imports.
  2421. * So we can't have negative cache before completed initialization.
  2422. * Anyway, importlib._find_and_load is much slower than
  2423. * _PyDict_GetItemIdWithError().
  2424. */
  2425. if (import_time) {
  2426. #define header FIND_AND_LOAD(interp).header
  2427. if (header) {
  2428. fputs("import time: self [us] | cumulative | imported package\n",
  2429. stderr);
  2430. header = 0;
  2431. }
  2432. #undef header
  2433. import_level++;
  2434. t1 = _PyTime_GetPerfCounter();
  2435. accumulated = 0;
  2436. }
  2437. if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
  2438. PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
  2439. mod = PyObject_CallMethodObjArgs(IMPORTLIB(interp), &_Py_ID(_find_and_load),
  2440. abs_name, IMPORT_FUNC(interp), NULL);
  2441. if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
  2442. PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
  2443. mod != NULL);
  2444. if (import_time) {
  2445. _PyTime_t cum = _PyTime_GetPerfCounter() - t1;
  2446. import_level--;
  2447. fprintf(stderr, "import time: %9ld | %10ld | %*s%s\n",
  2448. (long)_PyTime_AsMicroseconds(cum - accumulated, _PyTime_ROUND_CEILING),
  2449. (long)_PyTime_AsMicroseconds(cum, _PyTime_ROUND_CEILING),
  2450. import_level*2, "", PyUnicode_AsUTF8(abs_name));
  2451. accumulated = accumulated_copy + cum;
  2452. }
  2453. return mod;
  2454. #undef import_level
  2455. #undef accumulated
  2456. }
  2457. PyObject *
  2458. PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
  2459. PyObject *locals, PyObject *fromlist,
  2460. int level)
  2461. {
  2462. PyThreadState *tstate = _PyThreadState_GET();
  2463. PyObject *abs_name = NULL;
  2464. PyObject *final_mod = NULL;
  2465. PyObject *mod = NULL;
  2466. PyObject *package = NULL;
  2467. PyInterpreterState *interp = tstate->interp;
  2468. int has_from;
  2469. if (name == NULL) {
  2470. _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
  2471. goto error;
  2472. }
  2473. /* The below code is importlib.__import__() & _gcd_import(), ported to C
  2474. for added performance. */
  2475. if (!PyUnicode_Check(name)) {
  2476. _PyErr_SetString(tstate, PyExc_TypeError,
  2477. "module name must be a string");
  2478. goto error;
  2479. }
  2480. if (PyUnicode_READY(name) < 0) {
  2481. goto error;
  2482. }
  2483. if (level < 0) {
  2484. _PyErr_SetString(tstate, PyExc_ValueError, "level must be >= 0");
  2485. goto error;
  2486. }
  2487. if (level > 0) {
  2488. abs_name = resolve_name(tstate, name, globals, level);
  2489. if (abs_name == NULL)
  2490. goto error;
  2491. }
  2492. else { /* level == 0 */
  2493. if (PyUnicode_GET_LENGTH(name) == 0) {
  2494. _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
  2495. goto error;
  2496. }
  2497. abs_name = Py_NewRef(name);
  2498. }
  2499. mod = import_get_module(tstate, abs_name);
  2500. if (mod == NULL && _PyErr_Occurred(tstate)) {
  2501. goto error;
  2502. }
  2503. if (mod != NULL && mod != Py_None) {
  2504. if (import_ensure_initialized(tstate->interp, mod, abs_name) < 0) {
  2505. goto error;
  2506. }
  2507. }
  2508. else {
  2509. Py_XDECREF(mod);
  2510. mod = import_find_and_load(tstate, abs_name);
  2511. if (mod == NULL) {
  2512. goto error;
  2513. }
  2514. }
  2515. has_from = 0;
  2516. if (fromlist != NULL && fromlist != Py_None) {
  2517. has_from = PyObject_IsTrue(fromlist);
  2518. if (has_from < 0)
  2519. goto error;
  2520. }
  2521. if (!has_from) {
  2522. Py_ssize_t len = PyUnicode_GET_LENGTH(name);
  2523. if (level == 0 || len > 0) {
  2524. Py_ssize_t dot;
  2525. dot = PyUnicode_FindChar(name, '.', 0, len, 1);
  2526. if (dot == -2) {
  2527. goto error;
  2528. }
  2529. if (dot == -1) {
  2530. /* No dot in module name, simple exit */
  2531. final_mod = Py_NewRef(mod);
  2532. goto error;
  2533. }
  2534. if (level == 0) {
  2535. PyObject *front = PyUnicode_Substring(name, 0, dot);
  2536. if (front == NULL) {
  2537. goto error;
  2538. }
  2539. final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
  2540. Py_DECREF(front);
  2541. }
  2542. else {
  2543. Py_ssize_t cut_off = len - dot;
  2544. Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
  2545. PyObject *to_return = PyUnicode_Substring(abs_name, 0,
  2546. abs_name_len - cut_off);
  2547. if (to_return == NULL) {
  2548. goto error;
  2549. }
  2550. final_mod = import_get_module(tstate, to_return);
  2551. Py_DECREF(to_return);
  2552. if (final_mod == NULL) {
  2553. if (!_PyErr_Occurred(tstate)) {
  2554. _PyErr_Format(tstate, PyExc_KeyError,
  2555. "%R not in sys.modules as expected",
  2556. to_return);
  2557. }
  2558. goto error;
  2559. }
  2560. }
  2561. }
  2562. else {
  2563. final_mod = Py_NewRef(mod);
  2564. }
  2565. }
  2566. else {
  2567. PyObject *path;
  2568. if (_PyObject_LookupAttr(mod, &_Py_ID(__path__), &path) < 0) {
  2569. goto error;
  2570. }
  2571. if (path) {
  2572. Py_DECREF(path);
  2573. final_mod = PyObject_CallMethodObjArgs(
  2574. IMPORTLIB(interp), &_Py_ID(_handle_fromlist),
  2575. mod, fromlist, IMPORT_FUNC(interp), NULL);
  2576. }
  2577. else {
  2578. final_mod = Py_NewRef(mod);
  2579. }
  2580. }
  2581. error:
  2582. Py_XDECREF(abs_name);
  2583. Py_XDECREF(mod);
  2584. Py_XDECREF(package);
  2585. if (final_mod == NULL) {
  2586. remove_importlib_frames(tstate);
  2587. }
  2588. return final_mod;
  2589. }
  2590. PyObject *
  2591. PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
  2592. PyObject *fromlist, int level)
  2593. {
  2594. PyObject *nameobj, *mod;
  2595. nameobj = PyUnicode_FromString(name);
  2596. if (nameobj == NULL)
  2597. return NULL;
  2598. mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
  2599. fromlist, level);
  2600. Py_DECREF(nameobj);
  2601. return mod;
  2602. }
  2603. /* Re-import a module of any kind and return its module object, WITH
  2604. INCREMENTED REFERENCE COUNT */
  2605. PyObject *
  2606. PyImport_ReloadModule(PyObject *m)
  2607. {
  2608. PyObject *reloaded_module = NULL;
  2609. PyObject *importlib = PyImport_GetModule(&_Py_ID(importlib));
  2610. if (importlib == NULL) {
  2611. if (PyErr_Occurred()) {
  2612. return NULL;
  2613. }
  2614. importlib = PyImport_ImportModule("importlib");
  2615. if (importlib == NULL) {
  2616. return NULL;
  2617. }
  2618. }
  2619. reloaded_module = PyObject_CallMethodOneArg(importlib, &_Py_ID(reload), m);
  2620. Py_DECREF(importlib);
  2621. return reloaded_module;
  2622. }
  2623. /* Higher-level import emulator which emulates the "import" statement
  2624. more accurately -- it invokes the __import__() function from the
  2625. builtins of the current globals. This means that the import is
  2626. done using whatever import hooks are installed in the current
  2627. environment.
  2628. A dummy list ["__doc__"] is passed as the 4th argument so that
  2629. e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
  2630. will return <module "gencache"> instead of <module "win32com">. */
  2631. PyObject *
  2632. PyImport_Import(PyObject *module_name)
  2633. {
  2634. PyThreadState *tstate = _PyThreadState_GET();
  2635. PyObject *globals = NULL;
  2636. PyObject *import = NULL;
  2637. PyObject *builtins = NULL;
  2638. PyObject *r = NULL;
  2639. PyObject *from_list = PyList_New(0);
  2640. if (from_list == NULL) {
  2641. goto err;
  2642. }
  2643. /* Get the builtins from current globals */
  2644. globals = PyEval_GetGlobals();
  2645. if (globals != NULL) {
  2646. Py_INCREF(globals);
  2647. builtins = PyObject_GetItem(globals, &_Py_ID(__builtins__));
  2648. if (builtins == NULL)
  2649. goto err;
  2650. }
  2651. else {
  2652. /* No globals -- use standard builtins, and fake globals */
  2653. builtins = PyImport_ImportModuleLevel("builtins",
  2654. NULL, NULL, NULL, 0);
  2655. if (builtins == NULL) {
  2656. goto err;
  2657. }
  2658. globals = Py_BuildValue("{OO}", &_Py_ID(__builtins__), builtins);
  2659. if (globals == NULL)
  2660. goto err;
  2661. }
  2662. /* Get the __import__ function from the builtins */
  2663. if (PyDict_Check(builtins)) {
  2664. import = PyObject_GetItem(builtins, &_Py_ID(__import__));
  2665. if (import == NULL) {
  2666. _PyErr_SetObject(tstate, PyExc_KeyError, &_Py_ID(__import__));
  2667. }
  2668. }
  2669. else
  2670. import = PyObject_GetAttr(builtins, &_Py_ID(__import__));
  2671. if (import == NULL)
  2672. goto err;
  2673. /* Call the __import__ function with the proper argument list
  2674. Always use absolute import here.
  2675. Calling for side-effect of import. */
  2676. r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
  2677. globals, from_list, 0, NULL);
  2678. if (r == NULL)
  2679. goto err;
  2680. Py_DECREF(r);
  2681. r = import_get_module(tstate, module_name);
  2682. if (r == NULL && !_PyErr_Occurred(tstate)) {
  2683. _PyErr_SetObject(tstate, PyExc_KeyError, module_name);
  2684. }
  2685. err:
  2686. Py_XDECREF(globals);
  2687. Py_XDECREF(builtins);
  2688. Py_XDECREF(import);
  2689. Py_XDECREF(from_list);
  2690. return r;
  2691. }
  2692. /*********************/
  2693. /* runtime lifecycle */
  2694. /*********************/
  2695. PyStatus
  2696. _PyImport_Init(void)
  2697. {
  2698. if (INITTAB != NULL) {
  2699. return _PyStatus_ERR("global import state already initialized");
  2700. }
  2701. PyStatus status = _PyStatus_OK();
  2702. /* Force default raw memory allocator to get a known allocator to be able
  2703. to release the memory in _PyImport_Fini() */
  2704. PyMemAllocatorEx old_alloc;
  2705. _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  2706. if (init_builtin_modules_table() != 0) {
  2707. status = PyStatus_NoMemory();
  2708. goto done;
  2709. }
  2710. done:
  2711. PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  2712. return status;
  2713. }
  2714. void
  2715. _PyImport_Fini(void)
  2716. {
  2717. /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
  2718. // XXX Should we actually leave them (mostly) intact, since we don't
  2719. // ever dlclose() the module files?
  2720. _extensions_cache_clear_all();
  2721. /* Use the same memory allocator as _PyImport_Init(). */
  2722. PyMemAllocatorEx old_alloc;
  2723. _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  2724. /* Free memory allocated by _PyImport_Init() */
  2725. fini_builtin_modules_table();
  2726. PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  2727. }
  2728. void
  2729. _PyImport_Fini2(void)
  2730. {
  2731. /* Use the same memory allocator than PyImport_ExtendInittab(). */
  2732. PyMemAllocatorEx old_alloc;
  2733. _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  2734. // Reset PyImport_Inittab
  2735. PyImport_Inittab = _PyImport_Inittab;
  2736. /* Free memory allocated by PyImport_ExtendInittab() */
  2737. PyMem_RawFree(inittab_copy);
  2738. inittab_copy = NULL;
  2739. PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  2740. }
  2741. /*************************/
  2742. /* interpreter lifecycle */
  2743. /*************************/
  2744. PyStatus
  2745. _PyImport_InitCore(PyThreadState *tstate, PyObject *sysmod, int importlib)
  2746. {
  2747. // XXX Initialize here: interp->modules and interp->import_func.
  2748. // XXX Initialize here: sys.modules and sys.meta_path.
  2749. if (importlib) {
  2750. /* This call sets up builtin and frozen import support */
  2751. if (init_importlib(tstate, sysmod) < 0) {
  2752. return _PyStatus_ERR("failed to initialize importlib");
  2753. }
  2754. }
  2755. return _PyStatus_OK();
  2756. }
  2757. /* In some corner cases it is important to be sure that the import
  2758. machinery has been initialized (or not cleaned up yet). For
  2759. example, see issue #4236 and PyModule_Create2(). */
  2760. int
  2761. _PyImport_IsInitialized(PyInterpreterState *interp)
  2762. {
  2763. if (MODULES(interp) == NULL)
  2764. return 0;
  2765. return 1;
  2766. }
  2767. /* Clear the direct per-interpreter import state, if not cleared already. */
  2768. void
  2769. _PyImport_ClearCore(PyInterpreterState *interp)
  2770. {
  2771. /* interp->modules should have been cleaned up and cleared already
  2772. by _PyImport_FiniCore(). */
  2773. Py_CLEAR(MODULES(interp));
  2774. Py_CLEAR(MODULES_BY_INDEX(interp));
  2775. Py_CLEAR(IMPORTLIB(interp));
  2776. Py_CLEAR(IMPORT_FUNC(interp));
  2777. }
  2778. void
  2779. _PyImport_FiniCore(PyInterpreterState *interp)
  2780. {
  2781. int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
  2782. if (_PySys_ClearAttrString(interp, "meta_path", verbose) < 0) {
  2783. PyErr_WriteUnraisable(NULL);
  2784. }
  2785. // XXX Pull in most of finalize_modules() in pylifecycle.c.
  2786. if (_PySys_ClearAttrString(interp, "modules", verbose) < 0) {
  2787. PyErr_WriteUnraisable(NULL);
  2788. }
  2789. if (IMPORT_LOCK(interp) != NULL) {
  2790. PyThread_free_lock(IMPORT_LOCK(interp));
  2791. IMPORT_LOCK(interp) = NULL;
  2792. }
  2793. _PyImport_ClearCore(interp);
  2794. }
  2795. // XXX Add something like _PyImport_Disable() for use early in interp fini?
  2796. /* "external" imports */
  2797. static int
  2798. init_zipimport(PyThreadState *tstate, int verbose)
  2799. {
  2800. PyObject *path_hooks = PySys_GetObject("path_hooks");
  2801. if (path_hooks == NULL) {
  2802. _PyErr_SetString(tstate, PyExc_RuntimeError,
  2803. "unable to get sys.path_hooks");
  2804. return -1;
  2805. }
  2806. if (verbose) {
  2807. PySys_WriteStderr("# installing zipimport hook\n");
  2808. }
  2809. PyObject *zipimporter = _PyImport_GetModuleAttrString("zipimport", "zipimporter");
  2810. if (zipimporter == NULL) {
  2811. _PyErr_Clear(tstate); /* No zipimporter object -- okay */
  2812. if (verbose) {
  2813. PySys_WriteStderr("# can't import zipimport.zipimporter\n");
  2814. }
  2815. }
  2816. else {
  2817. /* sys.path_hooks.insert(0, zipimporter) */
  2818. int err = PyList_Insert(path_hooks, 0, zipimporter);
  2819. Py_DECREF(zipimporter);
  2820. if (err < 0) {
  2821. return -1;
  2822. }
  2823. if (verbose) {
  2824. PySys_WriteStderr("# installed zipimport hook\n");
  2825. }
  2826. }
  2827. return 0;
  2828. }
  2829. PyStatus
  2830. _PyImport_InitExternal(PyThreadState *tstate)
  2831. {
  2832. int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
  2833. // XXX Initialize here: sys.path_hooks and sys.path_importer_cache.
  2834. if (init_importlib_external(tstate->interp) != 0) {
  2835. _PyErr_Print(tstate);
  2836. return _PyStatus_ERR("external importer setup failed");
  2837. }
  2838. if (init_zipimport(tstate, verbose) != 0) {
  2839. PyErr_Print();
  2840. return _PyStatus_ERR("initializing zipimport failed");
  2841. }
  2842. return _PyStatus_OK();
  2843. }
  2844. void
  2845. _PyImport_FiniExternal(PyInterpreterState *interp)
  2846. {
  2847. int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
  2848. // XXX Uninstall importlib metapath importers here?
  2849. if (_PySys_ClearAttrString(interp, "path_importer_cache", verbose) < 0) {
  2850. PyErr_WriteUnraisable(NULL);
  2851. }
  2852. if (_PySys_ClearAttrString(interp, "path_hooks", verbose) < 0) {
  2853. PyErr_WriteUnraisable(NULL);
  2854. }
  2855. }
  2856. /******************/
  2857. /* module helpers */
  2858. /******************/
  2859. PyObject *
  2860. _PyImport_GetModuleAttr(PyObject *modname, PyObject *attrname)
  2861. {
  2862. PyObject *mod = PyImport_Import(modname);
  2863. if (mod == NULL) {
  2864. return NULL;
  2865. }
  2866. PyObject *result = PyObject_GetAttr(mod, attrname);
  2867. Py_DECREF(mod);
  2868. return result;
  2869. }
  2870. PyObject *
  2871. _PyImport_GetModuleAttrString(const char *modname, const char *attrname)
  2872. {
  2873. PyObject *pmodname = PyUnicode_FromString(modname);
  2874. if (pmodname == NULL) {
  2875. return NULL;
  2876. }
  2877. PyObject *pattrname = PyUnicode_FromString(attrname);
  2878. if (pattrname == NULL) {
  2879. Py_DECREF(pmodname);
  2880. return NULL;
  2881. }
  2882. PyObject *result = _PyImport_GetModuleAttr(pmodname, pattrname);
  2883. Py_DECREF(pattrname);
  2884. Py_DECREF(pmodname);
  2885. return result;
  2886. }
  2887. /**************/
  2888. /* the module */
  2889. /**************/
  2890. /*[clinic input]
  2891. _imp.lock_held
  2892. Return True if the import lock is currently held, else False.
  2893. On platforms without threads, return False.
  2894. [clinic start generated code]*/
  2895. static PyObject *
  2896. _imp_lock_held_impl(PyObject *module)
  2897. /*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/
  2898. {
  2899. PyInterpreterState *interp = _PyInterpreterState_GET();
  2900. return PyBool_FromLong(
  2901. IMPORT_LOCK_THREAD(interp) != PYTHREAD_INVALID_THREAD_ID);
  2902. }
  2903. /*[clinic input]
  2904. _imp.acquire_lock
  2905. Acquires the interpreter's import lock for the current thread.
  2906. This lock should be used by import hooks to ensure thread-safety when importing
  2907. modules. On platforms without threads, this function does nothing.
  2908. [clinic start generated code]*/
  2909. static PyObject *
  2910. _imp_acquire_lock_impl(PyObject *module)
  2911. /*[clinic end generated code: output=1aff58cb0ee1b026 input=4a2d4381866d5fdc]*/
  2912. {
  2913. PyInterpreterState *interp = _PyInterpreterState_GET();
  2914. _PyImport_AcquireLock(interp);
  2915. Py_RETURN_NONE;
  2916. }
  2917. /*[clinic input]
  2918. _imp.release_lock
  2919. Release the interpreter's import lock.
  2920. On platforms without threads, this function does nothing.
  2921. [clinic start generated code]*/
  2922. static PyObject *
  2923. _imp_release_lock_impl(PyObject *module)
  2924. /*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
  2925. {
  2926. PyInterpreterState *interp = _PyInterpreterState_GET();
  2927. if (_PyImport_ReleaseLock(interp) < 0) {
  2928. PyErr_SetString(PyExc_RuntimeError,
  2929. "not holding the import lock");
  2930. return NULL;
  2931. }
  2932. Py_RETURN_NONE;
  2933. }
  2934. /*[clinic input]
  2935. _imp._fix_co_filename
  2936. code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
  2937. Code object to change.
  2938. path: unicode
  2939. File path to use.
  2940. /
  2941. Changes code.co_filename to specify the passed-in file path.
  2942. [clinic start generated code]*/
  2943. static PyObject *
  2944. _imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
  2945. PyObject *path)
  2946. /*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
  2947. {
  2948. update_compiled_module(code, path);
  2949. Py_RETURN_NONE;
  2950. }
  2951. /*[clinic input]
  2952. _imp.create_builtin
  2953. spec: object
  2954. /
  2955. Create an extension module.
  2956. [clinic start generated code]*/
  2957. static PyObject *
  2958. _imp_create_builtin(PyObject *module, PyObject *spec)
  2959. /*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
  2960. {
  2961. PyThreadState *tstate = _PyThreadState_GET();
  2962. PyObject *name = PyObject_GetAttrString(spec, "name");
  2963. if (name == NULL) {
  2964. return NULL;
  2965. }
  2966. if (!PyUnicode_Check(name)) {
  2967. PyErr_Format(PyExc_TypeError,
  2968. "name must be string, not %.200s",
  2969. Py_TYPE(name)->tp_name);
  2970. Py_DECREF(name);
  2971. return NULL;
  2972. }
  2973. PyObject *mod = create_builtin(tstate, name, spec);
  2974. Py_DECREF(name);
  2975. return mod;
  2976. }
  2977. /*[clinic input]
  2978. _imp.extension_suffixes
  2979. Returns the list of file suffixes used to identify extension modules.
  2980. [clinic start generated code]*/
  2981. static PyObject *
  2982. _imp_extension_suffixes_impl(PyObject *module)
  2983. /*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
  2984. {
  2985. PyObject *list;
  2986. list = PyList_New(0);
  2987. if (list == NULL)
  2988. return NULL;
  2989. #ifdef HAVE_DYNAMIC_LOADING
  2990. const char *suffix;
  2991. unsigned int index = 0;
  2992. while ((suffix = _PyImport_DynLoadFiletab[index])) {
  2993. PyObject *item = PyUnicode_FromString(suffix);
  2994. if (item == NULL) {
  2995. Py_DECREF(list);
  2996. return NULL;
  2997. }
  2998. if (PyList_Append(list, item) < 0) {
  2999. Py_DECREF(list);
  3000. Py_DECREF(item);
  3001. return NULL;
  3002. }
  3003. Py_DECREF(item);
  3004. index += 1;
  3005. }
  3006. #endif
  3007. return list;
  3008. }
  3009. /*[clinic input]
  3010. _imp.init_frozen
  3011. name: unicode
  3012. /
  3013. Initializes a frozen module.
  3014. [clinic start generated code]*/
  3015. static PyObject *
  3016. _imp_init_frozen_impl(PyObject *module, PyObject *name)
  3017. /*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
  3018. {
  3019. PyThreadState *tstate = _PyThreadState_GET();
  3020. int ret;
  3021. ret = PyImport_ImportFrozenModuleObject(name);
  3022. if (ret < 0)
  3023. return NULL;
  3024. if (ret == 0) {
  3025. Py_RETURN_NONE;
  3026. }
  3027. return import_add_module(tstate, name);
  3028. }
  3029. /*[clinic input]
  3030. _imp.find_frozen
  3031. name: unicode
  3032. /
  3033. *
  3034. withdata: bool = False
  3035. Return info about the corresponding frozen module (if there is one) or None.
  3036. The returned info (a 2-tuple):
  3037. * data the raw marshalled bytes
  3038. * is_package whether or not it is a package
  3039. * origname the originally frozen module's name, or None if not
  3040. a stdlib module (this will usually be the same as
  3041. the module's current name)
  3042. [clinic start generated code]*/
  3043. static PyObject *
  3044. _imp_find_frozen_impl(PyObject *module, PyObject *name, int withdata)
  3045. /*[clinic end generated code: output=8c1c3c7f925397a5 input=22a8847c201542fd]*/
  3046. {
  3047. struct frozen_info info;
  3048. frozen_status status = find_frozen(name, &info);
  3049. if (status == FROZEN_NOT_FOUND || status == FROZEN_DISABLED) {
  3050. Py_RETURN_NONE;
  3051. }
  3052. else if (status == FROZEN_BAD_NAME) {
  3053. Py_RETURN_NONE;
  3054. }
  3055. else if (status != FROZEN_OKAY) {
  3056. set_frozen_error(status, name);
  3057. return NULL;
  3058. }
  3059. PyObject *data = NULL;
  3060. if (withdata) {
  3061. data = PyMemoryView_FromMemory((char *)info.data, info.size, PyBUF_READ);
  3062. if (data == NULL) {
  3063. return NULL;
  3064. }
  3065. }
  3066. PyObject *origname = NULL;
  3067. if (info.origname != NULL && info.origname[0] != '\0') {
  3068. origname = PyUnicode_FromString(info.origname);
  3069. if (origname == NULL) {
  3070. Py_XDECREF(data);
  3071. return NULL;
  3072. }
  3073. }
  3074. PyObject *result = PyTuple_Pack(3, data ? data : Py_None,
  3075. info.is_package ? Py_True : Py_False,
  3076. origname ? origname : Py_None);
  3077. Py_XDECREF(origname);
  3078. Py_XDECREF(data);
  3079. return result;
  3080. }
  3081. /*[clinic input]
  3082. _imp.get_frozen_object
  3083. name: unicode
  3084. data as dataobj: object = None
  3085. /
  3086. Create a code object for a frozen module.
  3087. [clinic start generated code]*/
  3088. static PyObject *
  3089. _imp_get_frozen_object_impl(PyObject *module, PyObject *name,
  3090. PyObject *dataobj)
  3091. /*[clinic end generated code: output=54368a673a35e745 input=034bdb88f6460b7b]*/
  3092. {
  3093. struct frozen_info info = {0};
  3094. Py_buffer buf = {0};
  3095. if (PyObject_CheckBuffer(dataobj)) {
  3096. if (PyObject_GetBuffer(dataobj, &buf, PyBUF_SIMPLE) != 0) {
  3097. return NULL;
  3098. }
  3099. info.data = (const char *)buf.buf;
  3100. info.size = buf.len;
  3101. }
  3102. else if (dataobj != Py_None) {
  3103. _PyArg_BadArgument("get_frozen_object", "argument 2", "bytes", dataobj);
  3104. return NULL;
  3105. }
  3106. else {
  3107. frozen_status status = find_frozen(name, &info);
  3108. if (status != FROZEN_OKAY) {
  3109. set_frozen_error(status, name);
  3110. return NULL;
  3111. }
  3112. }
  3113. if (info.nameobj == NULL) {
  3114. info.nameobj = name;
  3115. }
  3116. if (info.size == 0 && info.get_code == NULL) {
  3117. /* Does not contain executable code. */
  3118. set_frozen_error(FROZEN_INVALID, name);
  3119. return NULL;
  3120. }
  3121. PyInterpreterState *interp = _PyInterpreterState_GET();
  3122. PyObject *codeobj = unmarshal_frozen_code(interp, &info);
  3123. if (dataobj != Py_None) {
  3124. PyBuffer_Release(&buf);
  3125. }
  3126. return codeobj;
  3127. }
  3128. /*[clinic input]
  3129. _imp.is_frozen_package
  3130. name: unicode
  3131. /
  3132. Returns True if the module name is of a frozen package.
  3133. [clinic start generated code]*/
  3134. static PyObject *
  3135. _imp_is_frozen_package_impl(PyObject *module, PyObject *name)
  3136. /*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
  3137. {
  3138. struct frozen_info info;
  3139. frozen_status status = find_frozen(name, &info);
  3140. if (status != FROZEN_OKAY && status != FROZEN_EXCLUDED) {
  3141. set_frozen_error(status, name);
  3142. return NULL;
  3143. }
  3144. return PyBool_FromLong(info.is_package);
  3145. }
  3146. /*[clinic input]
  3147. _imp.is_builtin
  3148. name: unicode
  3149. /
  3150. Returns True if the module name corresponds to a built-in module.
  3151. [clinic start generated code]*/
  3152. static PyObject *
  3153. _imp_is_builtin_impl(PyObject *module, PyObject *name)
  3154. /*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
  3155. {
  3156. return PyLong_FromLong(is_builtin(name));
  3157. }
  3158. /*[clinic input]
  3159. _imp.is_frozen
  3160. name: unicode
  3161. /
  3162. Returns True if the module name corresponds to a frozen module.
  3163. [clinic start generated code]*/
  3164. static PyObject *
  3165. _imp_is_frozen_impl(PyObject *module, PyObject *name)
  3166. /*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
  3167. {
  3168. struct frozen_info info;
  3169. frozen_status status = find_frozen(name, &info);
  3170. if (status != FROZEN_OKAY) {
  3171. Py_RETURN_FALSE;
  3172. }
  3173. Py_RETURN_TRUE;
  3174. }
  3175. /*[clinic input]
  3176. _imp._frozen_module_names
  3177. Returns the list of available frozen modules.
  3178. [clinic start generated code]*/
  3179. static PyObject *
  3180. _imp__frozen_module_names_impl(PyObject *module)
  3181. /*[clinic end generated code: output=80609ef6256310a8 input=76237fbfa94460d2]*/
  3182. {
  3183. return list_frozen_module_names();
  3184. }
  3185. /*[clinic input]
  3186. _imp._override_frozen_modules_for_tests
  3187. override: int
  3188. /
  3189. (internal-only) Override PyConfig.use_frozen_modules.
  3190. (-1: "off", 1: "on", 0: no override)
  3191. See frozen_modules() in Lib/test/support/import_helper.py.
  3192. [clinic start generated code]*/
  3193. static PyObject *
  3194. _imp__override_frozen_modules_for_tests_impl(PyObject *module, int override)
  3195. /*[clinic end generated code: output=36d5cb1594160811 input=8f1f95a3ef21aec3]*/
  3196. {
  3197. PyInterpreterState *interp = _PyInterpreterState_GET();
  3198. OVERRIDE_FROZEN_MODULES(interp) = override;
  3199. Py_RETURN_NONE;
  3200. }
  3201. /*[clinic input]
  3202. _imp._override_multi_interp_extensions_check
  3203. override: int
  3204. /
  3205. (internal-only) Override PyInterpreterConfig.check_multi_interp_extensions.
  3206. (-1: "never", 1: "always", 0: no override)
  3207. [clinic start generated code]*/
  3208. static PyObject *
  3209. _imp__override_multi_interp_extensions_check_impl(PyObject *module,
  3210. int override)
  3211. /*[clinic end generated code: output=3ff043af52bbf280 input=e086a2ea181f92ae]*/
  3212. {
  3213. PyInterpreterState *interp = _PyInterpreterState_GET();
  3214. if (_Py_IsMainInterpreter(interp)) {
  3215. PyErr_SetString(PyExc_RuntimeError,
  3216. "_imp._override_multi_interp_extensions_check() "
  3217. "cannot be used in the main interpreter");
  3218. return NULL;
  3219. }
  3220. int oldvalue = OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK(interp);
  3221. OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK(interp) = override;
  3222. return PyLong_FromLong(oldvalue);
  3223. }
  3224. #ifdef HAVE_DYNAMIC_LOADING
  3225. /*[clinic input]
  3226. _imp.create_dynamic
  3227. spec: object
  3228. file: object = NULL
  3229. /
  3230. Create an extension module.
  3231. [clinic start generated code]*/
  3232. static PyObject *
  3233. _imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
  3234. /*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
  3235. {
  3236. PyObject *mod, *name, *path;
  3237. FILE *fp;
  3238. name = PyObject_GetAttrString(spec, "name");
  3239. if (name == NULL) {
  3240. return NULL;
  3241. }
  3242. path = PyObject_GetAttrString(spec, "origin");
  3243. if (path == NULL) {
  3244. Py_DECREF(name);
  3245. return NULL;
  3246. }
  3247. PyThreadState *tstate = _PyThreadState_GET();
  3248. mod = import_find_extension(tstate, name, path);
  3249. if (mod != NULL || _PyErr_Occurred(tstate)) {
  3250. assert(mod == NULL || !_PyErr_Occurred(tstate));
  3251. goto finally;
  3252. }
  3253. if (file != NULL) {
  3254. fp = _Py_fopen_obj(path, "r");
  3255. if (fp == NULL) {
  3256. goto finally;
  3257. }
  3258. }
  3259. else
  3260. fp = NULL;
  3261. mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp);
  3262. if (fp)
  3263. fclose(fp);
  3264. finally:
  3265. Py_DECREF(name);
  3266. Py_DECREF(path);
  3267. return mod;
  3268. }
  3269. /*[clinic input]
  3270. _imp.exec_dynamic -> int
  3271. mod: object
  3272. /
  3273. Initialize an extension module.
  3274. [clinic start generated code]*/
  3275. static int
  3276. _imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
  3277. /*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
  3278. {
  3279. return exec_builtin_or_dynamic(mod);
  3280. }
  3281. #endif /* HAVE_DYNAMIC_LOADING */
  3282. /*[clinic input]
  3283. _imp.exec_builtin -> int
  3284. mod: object
  3285. /
  3286. Initialize a built-in module.
  3287. [clinic start generated code]*/
  3288. static int
  3289. _imp_exec_builtin_impl(PyObject *module, PyObject *mod)
  3290. /*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
  3291. {
  3292. return exec_builtin_or_dynamic(mod);
  3293. }
  3294. /*[clinic input]
  3295. _imp.source_hash
  3296. key: long
  3297. source: Py_buffer
  3298. [clinic start generated code]*/
  3299. static PyObject *
  3300. _imp_source_hash_impl(PyObject *module, long key, Py_buffer *source)
  3301. /*[clinic end generated code: output=edb292448cf399ea input=9aaad1e590089789]*/
  3302. {
  3303. union {
  3304. uint64_t x;
  3305. char data[sizeof(uint64_t)];
  3306. } hash;
  3307. hash.x = _Py_KeyedHash((uint64_t)key, source->buf, source->len);
  3308. #if !PY_LITTLE_ENDIAN
  3309. // Force to little-endian. There really ought to be a succinct standard way
  3310. // to do this.
  3311. for (size_t i = 0; i < sizeof(hash.data)/2; i++) {
  3312. char tmp = hash.data[i];
  3313. hash.data[i] = hash.data[sizeof(hash.data) - i - 1];
  3314. hash.data[sizeof(hash.data) - i - 1] = tmp;
  3315. }
  3316. #endif
  3317. return PyBytes_FromStringAndSize(hash.data, sizeof(hash.data));
  3318. }
  3319. PyDoc_STRVAR(doc_imp,
  3320. "(Extremely) low-level import machinery bits as used by importlib.");
  3321. static PyMethodDef imp_methods[] = {
  3322. _IMP_EXTENSION_SUFFIXES_METHODDEF
  3323. _IMP_LOCK_HELD_METHODDEF
  3324. _IMP_ACQUIRE_LOCK_METHODDEF
  3325. _IMP_RELEASE_LOCK_METHODDEF
  3326. _IMP_FIND_FROZEN_METHODDEF
  3327. _IMP_GET_FROZEN_OBJECT_METHODDEF
  3328. _IMP_IS_FROZEN_PACKAGE_METHODDEF
  3329. _IMP_CREATE_BUILTIN_METHODDEF
  3330. _IMP_INIT_FROZEN_METHODDEF
  3331. _IMP_IS_BUILTIN_METHODDEF
  3332. _IMP_IS_FROZEN_METHODDEF
  3333. _IMP__FROZEN_MODULE_NAMES_METHODDEF
  3334. _IMP__OVERRIDE_FROZEN_MODULES_FOR_TESTS_METHODDEF
  3335. _IMP__OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK_METHODDEF
  3336. _IMP_CREATE_DYNAMIC_METHODDEF
  3337. _IMP_EXEC_DYNAMIC_METHODDEF
  3338. _IMP_EXEC_BUILTIN_METHODDEF
  3339. _IMP__FIX_CO_FILENAME_METHODDEF
  3340. _IMP_SOURCE_HASH_METHODDEF
  3341. {NULL, NULL} /* sentinel */
  3342. };
  3343. static int
  3344. imp_module_exec(PyObject *module)
  3345. {
  3346. const wchar_t *mode = _Py_GetConfig()->check_hash_pycs_mode;
  3347. PyObject *pyc_mode = PyUnicode_FromWideChar(mode, -1);
  3348. if (pyc_mode == NULL) {
  3349. return -1;
  3350. }
  3351. if (PyModule_AddObjectRef(module, "check_hash_based_pycs", pyc_mode) < 0) {
  3352. Py_DECREF(pyc_mode);
  3353. return -1;
  3354. }
  3355. Py_DECREF(pyc_mode);
  3356. return 0;
  3357. }
  3358. static PyModuleDef_Slot imp_slots[] = {
  3359. {Py_mod_exec, imp_module_exec},
  3360. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  3361. {0, NULL}
  3362. };
  3363. static struct PyModuleDef imp_module = {
  3364. PyModuleDef_HEAD_INIT,
  3365. .m_name = "_imp",
  3366. .m_doc = doc_imp,
  3367. .m_size = 0,
  3368. .m_methods = imp_methods,
  3369. .m_slots = imp_slots,
  3370. };
  3371. PyMODINIT_FUNC
  3372. PyInit__imp(void)
  3373. {
  3374. return PyModuleDef_Init(&imp_module);
  3375. }
  3376. #ifdef __cplusplus
  3377. }
  3378. #endif