pylifecycle.c 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188
  1. /* Python interpreter top-level routines, including init/exit */
  2. #include "Python.h"
  3. #include "pycore_ceval.h" // _PyEval_FiniGIL()
  4. #include "pycore_context.h" // _PyContext_Init()
  5. #include "pycore_exceptions.h" // _PyExc_InitTypes()
  6. #include "pycore_dict.h" // _PyDict_Fini()
  7. #include "pycore_fileutils.h" // _Py_ResetForceASCII()
  8. #include "pycore_floatobject.h" // _PyFloat_InitTypes()
  9. #include "pycore_genobject.h" // _PyAsyncGen_Fini()
  10. #include "pycore_global_objects_fini_generated.h" // "_PyStaticObjects_CheckRefcnt()
  11. #include "pycore_import.h" // _PyImport_BootstrapImp()
  12. #include "pycore_initconfig.h" // _PyStatus_OK()
  13. #include "pycore_list.h" // _PyList_Fini()
  14. #include "pycore_long.h" // _PyLong_InitTypes()
  15. #include "pycore_object.h" // _PyDebug_PrintTotalRefs()
  16. #include "pycore_pathconfig.h" // _PyConfig_WritePathConfig()
  17. #include "pycore_pyerrors.h" // _PyErr_Occurred()
  18. #include "pycore_pylifecycle.h" // _PyErr_Print()
  19. #include "pycore_pymem.h" // _PyObject_DebugMallocStats()
  20. #include "pycore_pystate.h" // _PyThreadState_GET()
  21. #include "pycore_runtime.h" // _Py_ID()
  22. #include "pycore_runtime_init.h" // _PyRuntimeState_INIT
  23. #include "pycore_sliceobject.h" // _PySlice_Fini()
  24. #include "pycore_sysmodule.h" // _PySys_ClearAuditHooks()
  25. #include "pycore_traceback.h" // _Py_DumpTracebackThreads()
  26. #include "pycore_typeobject.h" // _PyTypes_InitTypes()
  27. #include "pycore_typevarobject.h" // _Py_clear_generic_types()
  28. #include "pycore_unicodeobject.h" // _PyUnicode_InitTypes()
  29. #include "opcode.h"
  30. #include <locale.h> // setlocale()
  31. #include <stdlib.h> // getenv()
  32. #if defined(__APPLE__)
  33. #include <mach-o/loader.h>
  34. #endif
  35. #ifdef HAVE_SIGNAL_H
  36. # include <signal.h> // SIG_IGN
  37. #endif
  38. #ifdef HAVE_LANGINFO_H
  39. # include <langinfo.h> // nl_langinfo(CODESET)
  40. #endif
  41. #ifdef HAVE_FCNTL_H
  42. # include <fcntl.h> // F_GETFD
  43. #endif
  44. #ifdef MS_WINDOWS
  45. # undef BYTE
  46. #endif
  47. #define PUTS(fd, str) _Py_write_noraise(fd, str, (int)strlen(str))
  48. #ifdef __cplusplus
  49. extern "C" {
  50. #endif
  51. /* Forward declarations */
  52. static PyStatus add_main_module(PyInterpreterState *interp);
  53. static PyStatus init_import_site(void);
  54. static PyStatus init_set_builtins_open(void);
  55. static PyStatus init_sys_streams(PyThreadState *tstate);
  56. static void wait_for_thread_shutdown(PyThreadState *tstate);
  57. static void call_ll_exitfuncs(_PyRuntimeState *runtime);
  58. /* The following places the `_PyRuntime` structure in a location that can be
  59. * found without any external information. This is meant to ease access to the
  60. * interpreter state for various runtime debugging tools, but is *not* an
  61. * officially supported feature */
  62. /* Suppress deprecation warning for PyBytesObject.ob_shash */
  63. _Py_COMP_DIAG_PUSH
  64. _Py_COMP_DIAG_IGNORE_DEPR_DECLS
  65. #if defined(MS_WINDOWS)
  66. #pragma section("PyRuntime", read, write)
  67. __declspec(allocate("PyRuntime"))
  68. #elif defined(__APPLE__)
  69. __attribute__((
  70. section(SEG_DATA ",PyRuntime")
  71. ))
  72. #endif
  73. _PyRuntimeState _PyRuntime
  74. #if defined(__linux__) && (defined(__GNUC__) || defined(__clang__))
  75. __attribute__ ((section (".PyRuntime")))
  76. #endif
  77. = _PyRuntimeState_INIT(_PyRuntime);
  78. _Py_COMP_DIAG_POP
  79. static int runtime_initialized = 0;
  80. PyStatus
  81. _PyRuntime_Initialize(void)
  82. {
  83. /* XXX We only initialize once in the process, which aligns with
  84. the static initialization of the former globals now found in
  85. _PyRuntime. However, _PyRuntime *should* be initialized with
  86. every Py_Initialize() call, but doing so breaks the runtime.
  87. This is because the runtime state is not properly finalized
  88. currently. */
  89. if (runtime_initialized) {
  90. return _PyStatus_OK();
  91. }
  92. runtime_initialized = 1;
  93. return _PyRuntimeState_Init(&_PyRuntime);
  94. }
  95. void
  96. _PyRuntime_Finalize(void)
  97. {
  98. _PyRuntimeState_Fini(&_PyRuntime);
  99. runtime_initialized = 0;
  100. }
  101. int
  102. _Py_IsFinalizing(void)
  103. {
  104. return _PyRuntimeState_GetFinalizing(&_PyRuntime) != NULL;
  105. }
  106. /* Hack to force loading of object files */
  107. int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
  108. PyOS_mystrnicmp; /* Python/pystrcmp.o */
  109. /* APIs to access the initialization flags
  110. *
  111. * Can be called prior to Py_Initialize.
  112. */
  113. int
  114. _Py_IsCoreInitialized(void)
  115. {
  116. return _PyRuntime.core_initialized;
  117. }
  118. int
  119. Py_IsInitialized(void)
  120. {
  121. return _PyRuntime.initialized;
  122. }
  123. /* Helper functions to better handle the legacy C locale
  124. *
  125. * The legacy C locale assumes ASCII as the default text encoding, which
  126. * causes problems not only for the CPython runtime, but also other
  127. * components like GNU readline.
  128. *
  129. * Accordingly, when the CLI detects it, it attempts to coerce it to a
  130. * more capable UTF-8 based alternative as follows:
  131. *
  132. * if (_Py_LegacyLocaleDetected()) {
  133. * _Py_CoerceLegacyLocale();
  134. * }
  135. *
  136. * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
  137. *
  138. * Locale coercion also impacts the default error handler for the standard
  139. * streams: while the usual default is "strict", the default for the legacy
  140. * C locale and for any of the coercion target locales is "surrogateescape".
  141. */
  142. int
  143. _Py_LegacyLocaleDetected(int warn)
  144. {
  145. #ifndef MS_WINDOWS
  146. if (!warn) {
  147. const char *locale_override = getenv("LC_ALL");
  148. if (locale_override != NULL && *locale_override != '\0') {
  149. /* Don't coerce C locale if the LC_ALL environment variable
  150. is set */
  151. return 0;
  152. }
  153. }
  154. /* On non-Windows systems, the C locale is considered a legacy locale */
  155. /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
  156. * the POSIX locale as a simple alias for the C locale, so
  157. * we may also want to check for that explicitly.
  158. */
  159. const char *ctype_loc = setlocale(LC_CTYPE, NULL);
  160. return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
  161. #else
  162. /* Windows uses code pages instead of locales, so no locale is legacy */
  163. return 0;
  164. #endif
  165. }
  166. #ifndef MS_WINDOWS
  167. static const char *_C_LOCALE_WARNING =
  168. "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
  169. "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
  170. "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
  171. "locales is recommended.\n";
  172. static void
  173. emit_stderr_warning_for_legacy_locale(_PyRuntimeState *runtime)
  174. {
  175. const PyPreConfig *preconfig = &runtime->preconfig;
  176. if (preconfig->coerce_c_locale_warn && _Py_LegacyLocaleDetected(1)) {
  177. PySys_FormatStderr("%s", _C_LOCALE_WARNING);
  178. }
  179. }
  180. #endif /* !defined(MS_WINDOWS) */
  181. typedef struct _CandidateLocale {
  182. const char *locale_name; /* The locale to try as a coercion target */
  183. } _LocaleCoercionTarget;
  184. static _LocaleCoercionTarget _TARGET_LOCALES[] = {
  185. {"C.UTF-8"},
  186. {"C.utf8"},
  187. {"UTF-8"},
  188. {NULL}
  189. };
  190. int
  191. _Py_IsLocaleCoercionTarget(const char *ctype_loc)
  192. {
  193. const _LocaleCoercionTarget *target = NULL;
  194. for (target = _TARGET_LOCALES; target->locale_name; target++) {
  195. if (strcmp(ctype_loc, target->locale_name) == 0) {
  196. return 1;
  197. }
  198. }
  199. return 0;
  200. }
  201. #ifdef PY_COERCE_C_LOCALE
  202. static const char C_LOCALE_COERCION_WARNING[] =
  203. "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
  204. "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
  205. static int
  206. _coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
  207. {
  208. const char *newloc = target->locale_name;
  209. /* Reset locale back to currently configured defaults */
  210. _Py_SetLocaleFromEnv(LC_ALL);
  211. /* Set the relevant locale environment variable */
  212. if (setenv("LC_CTYPE", newloc, 1)) {
  213. fprintf(stderr,
  214. "Error setting LC_CTYPE, skipping C locale coercion\n");
  215. return 0;
  216. }
  217. if (warn) {
  218. fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
  219. }
  220. /* Reconfigure with the overridden environment variables */
  221. _Py_SetLocaleFromEnv(LC_ALL);
  222. return 1;
  223. }
  224. #endif
  225. int
  226. _Py_CoerceLegacyLocale(int warn)
  227. {
  228. int coerced = 0;
  229. #ifdef PY_COERCE_C_LOCALE
  230. char *oldloc = NULL;
  231. oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
  232. if (oldloc == NULL) {
  233. return coerced;
  234. }
  235. const char *locale_override = getenv("LC_ALL");
  236. if (locale_override == NULL || *locale_override == '\0') {
  237. /* LC_ALL is also not set (or is set to an empty string) */
  238. const _LocaleCoercionTarget *target = NULL;
  239. for (target = _TARGET_LOCALES; target->locale_name; target++) {
  240. const char *new_locale = setlocale(LC_CTYPE,
  241. target->locale_name);
  242. if (new_locale != NULL) {
  243. #if !defined(_Py_FORCE_UTF8_LOCALE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
  244. /* Also ensure that nl_langinfo works in this locale */
  245. char *codeset = nl_langinfo(CODESET);
  246. if (!codeset || *codeset == '\0') {
  247. /* CODESET is not set or empty, so skip coercion */
  248. new_locale = NULL;
  249. _Py_SetLocaleFromEnv(LC_CTYPE);
  250. continue;
  251. }
  252. #endif
  253. /* Successfully configured locale, so make it the default */
  254. coerced = _coerce_default_locale_settings(warn, target);
  255. goto done;
  256. }
  257. }
  258. }
  259. /* No C locale warning here, as Py_Initialize will emit one later */
  260. setlocale(LC_CTYPE, oldloc);
  261. done:
  262. PyMem_RawFree(oldloc);
  263. #endif
  264. return coerced;
  265. }
  266. /* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
  267. * isolate the idiosyncrasies of different libc implementations. It reads the
  268. * appropriate environment variable and uses its value to select the locale for
  269. * 'category'. */
  270. char *
  271. _Py_SetLocaleFromEnv(int category)
  272. {
  273. char *res;
  274. #ifdef __ANDROID__
  275. const char *locale;
  276. const char **pvar;
  277. #ifdef PY_COERCE_C_LOCALE
  278. const char *coerce_c_locale;
  279. #endif
  280. const char *utf8_locale = "C.UTF-8";
  281. const char *env_var_set[] = {
  282. "LC_ALL",
  283. "LC_CTYPE",
  284. "LANG",
  285. NULL,
  286. };
  287. /* Android setlocale(category, "") doesn't check the environment variables
  288. * and incorrectly sets the "C" locale at API 24 and older APIs. We only
  289. * check the environment variables listed in env_var_set. */
  290. for (pvar=env_var_set; *pvar; pvar++) {
  291. locale = getenv(*pvar);
  292. if (locale != NULL && *locale != '\0') {
  293. if (strcmp(locale, utf8_locale) == 0 ||
  294. strcmp(locale, "en_US.UTF-8") == 0) {
  295. return setlocale(category, utf8_locale);
  296. }
  297. return setlocale(category, "C");
  298. }
  299. }
  300. /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
  301. * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
  302. * Quote from POSIX section "8.2 Internationalization Variables":
  303. * "4. If the LANG environment variable is not set or is set to the empty
  304. * string, the implementation-defined default locale shall be used." */
  305. #ifdef PY_COERCE_C_LOCALE
  306. coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
  307. if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
  308. /* Some other ported code may check the environment variables (e.g. in
  309. * extension modules), so we make sure that they match the locale
  310. * configuration */
  311. if (setenv("LC_CTYPE", utf8_locale, 1)) {
  312. fprintf(stderr, "Warning: failed setting the LC_CTYPE "
  313. "environment variable to %s\n", utf8_locale);
  314. }
  315. }
  316. #endif
  317. res = setlocale(category, utf8_locale);
  318. #else /* !defined(__ANDROID__) */
  319. res = setlocale(category, "");
  320. #endif
  321. _Py_ResetForceASCII();
  322. return res;
  323. }
  324. static int
  325. interpreter_update_config(PyThreadState *tstate, int only_update_path_config)
  326. {
  327. const PyConfig *config = &tstate->interp->config;
  328. if (!only_update_path_config) {
  329. PyStatus status = _PyConfig_Write(config, tstate->interp->runtime);
  330. if (_PyStatus_EXCEPTION(status)) {
  331. _PyErr_SetFromPyStatus(status);
  332. return -1;
  333. }
  334. }
  335. if (_Py_IsMainInterpreter(tstate->interp)) {
  336. PyStatus status = _PyPathConfig_UpdateGlobal(config);
  337. if (_PyStatus_EXCEPTION(status)) {
  338. _PyErr_SetFromPyStatus(status);
  339. return -1;
  340. }
  341. }
  342. tstate->interp->long_state.max_str_digits = config->int_max_str_digits;
  343. // Update the sys module for the new configuration
  344. if (_PySys_UpdateConfig(tstate) < 0) {
  345. return -1;
  346. }
  347. return 0;
  348. }
  349. int
  350. _PyInterpreterState_SetConfig(const PyConfig *src_config)
  351. {
  352. PyThreadState *tstate = _PyThreadState_GET();
  353. int res = -1;
  354. PyConfig config;
  355. PyConfig_InitPythonConfig(&config);
  356. PyStatus status = _PyConfig_Copy(&config, src_config);
  357. if (_PyStatus_EXCEPTION(status)) {
  358. _PyErr_SetFromPyStatus(status);
  359. goto done;
  360. }
  361. status = _PyConfig_Read(&config, 1);
  362. if (_PyStatus_EXCEPTION(status)) {
  363. _PyErr_SetFromPyStatus(status);
  364. goto done;
  365. }
  366. status = _PyConfig_Copy(&tstate->interp->config, &config);
  367. if (_PyStatus_EXCEPTION(status)) {
  368. _PyErr_SetFromPyStatus(status);
  369. goto done;
  370. }
  371. res = interpreter_update_config(tstate, 0);
  372. done:
  373. PyConfig_Clear(&config);
  374. return res;
  375. }
  376. /* Global initializations. Can be undone by Py_Finalize(). Don't
  377. call this twice without an intervening Py_Finalize() call.
  378. Every call to Py_InitializeFromConfig, Py_Initialize or Py_InitializeEx
  379. must have a corresponding call to Py_Finalize.
  380. Locking: you must hold the interpreter lock while calling these APIs.
  381. (If the lock has not yet been initialized, that's equivalent to
  382. having the lock, but you cannot use multiple threads.)
  383. */
  384. static PyStatus
  385. pyinit_core_reconfigure(_PyRuntimeState *runtime,
  386. PyThreadState **tstate_p,
  387. const PyConfig *config)
  388. {
  389. PyStatus status;
  390. PyThreadState *tstate = _PyThreadState_GET();
  391. if (!tstate) {
  392. return _PyStatus_ERR("failed to read thread state");
  393. }
  394. *tstate_p = tstate;
  395. PyInterpreterState *interp = tstate->interp;
  396. if (interp == NULL) {
  397. return _PyStatus_ERR("can't make main interpreter");
  398. }
  399. status = _PyConfig_Write(config, runtime);
  400. if (_PyStatus_EXCEPTION(status)) {
  401. return status;
  402. }
  403. status = _PyConfig_Copy(&interp->config, config);
  404. if (_PyStatus_EXCEPTION(status)) {
  405. return status;
  406. }
  407. config = _PyInterpreterState_GetConfig(interp);
  408. if (config->_install_importlib) {
  409. status = _PyPathConfig_UpdateGlobal(config);
  410. if (_PyStatus_EXCEPTION(status)) {
  411. return status;
  412. }
  413. }
  414. return _PyStatus_OK();
  415. }
  416. static PyStatus
  417. pycore_init_runtime(_PyRuntimeState *runtime,
  418. const PyConfig *config)
  419. {
  420. if (runtime->initialized) {
  421. return _PyStatus_ERR("main interpreter already initialized");
  422. }
  423. PyStatus status = _PyConfig_Write(config, runtime);
  424. if (_PyStatus_EXCEPTION(status)) {
  425. return status;
  426. }
  427. /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
  428. * threads behave a little more gracefully at interpreter shutdown.
  429. * We clobber it here so the new interpreter can start with a clean
  430. * slate.
  431. *
  432. * However, this may still lead to misbehaviour if there are daemon
  433. * threads still hanging around from a previous Py_Initialize/Finalize
  434. * pair :(
  435. */
  436. _PyRuntimeState_SetFinalizing(runtime, NULL);
  437. _Py_InitVersion();
  438. status = _Py_HashRandomization_Init(config);
  439. if (_PyStatus_EXCEPTION(status)) {
  440. return status;
  441. }
  442. status = _PyTime_Init();
  443. if (_PyStatus_EXCEPTION(status)) {
  444. return status;
  445. }
  446. status = _PyImport_Init();
  447. if (_PyStatus_EXCEPTION(status)) {
  448. return status;
  449. }
  450. status = _PyInterpreterState_Enable(runtime);
  451. if (_PyStatus_EXCEPTION(status)) {
  452. return status;
  453. }
  454. return _PyStatus_OK();
  455. }
  456. static PyStatus
  457. init_interp_settings(PyInterpreterState *interp,
  458. const PyInterpreterConfig *config)
  459. {
  460. assert(interp->feature_flags == 0);
  461. if (config->use_main_obmalloc) {
  462. interp->feature_flags |= Py_RTFLAGS_USE_MAIN_OBMALLOC;
  463. }
  464. else if (!config->check_multi_interp_extensions) {
  465. /* The reason: PyModuleDef.m_base.m_copy leaks objects between
  466. interpreters. */
  467. return _PyStatus_ERR("per-interpreter obmalloc does not support "
  468. "single-phase init extension modules");
  469. }
  470. if (config->allow_fork) {
  471. interp->feature_flags |= Py_RTFLAGS_FORK;
  472. }
  473. if (config->allow_exec) {
  474. interp->feature_flags |= Py_RTFLAGS_EXEC;
  475. }
  476. // Note that fork+exec is always allowed.
  477. if (config->allow_threads) {
  478. interp->feature_flags |= Py_RTFLAGS_THREADS;
  479. }
  480. if (config->allow_daemon_threads) {
  481. interp->feature_flags |= Py_RTFLAGS_DAEMON_THREADS;
  482. }
  483. if (config->check_multi_interp_extensions) {
  484. interp->feature_flags |= Py_RTFLAGS_MULTI_INTERP_EXTENSIONS;
  485. }
  486. /* We check "gil" in init_interp_create_gil(). */
  487. return _PyStatus_OK();
  488. }
  489. static PyStatus
  490. init_interp_create_gil(PyThreadState *tstate, int gil)
  491. {
  492. PyStatus status;
  493. /* finalize_interp_delete() comment explains why _PyEval_FiniGIL() is
  494. only called here. */
  495. // XXX This is broken with a per-interpreter GIL.
  496. _PyEval_FiniGIL(tstate->interp);
  497. /* Auto-thread-state API */
  498. status = _PyGILState_SetTstate(tstate);
  499. if (_PyStatus_EXCEPTION(status)) {
  500. return status;
  501. }
  502. int own_gil;
  503. switch (gil) {
  504. case PyInterpreterConfig_DEFAULT_GIL: own_gil = 0; break;
  505. case PyInterpreterConfig_SHARED_GIL: own_gil = 0; break;
  506. case PyInterpreterConfig_OWN_GIL: own_gil = 1; break;
  507. default:
  508. return _PyStatus_ERR("invalid interpreter config 'gil' value");
  509. }
  510. /* Create the GIL and take it */
  511. status = _PyEval_InitGIL(tstate, own_gil);
  512. if (_PyStatus_EXCEPTION(status)) {
  513. return status;
  514. }
  515. return _PyStatus_OK();
  516. }
  517. static PyStatus
  518. pycore_create_interpreter(_PyRuntimeState *runtime,
  519. const PyConfig *src_config,
  520. PyThreadState **tstate_p)
  521. {
  522. PyStatus status;
  523. PyInterpreterState *interp = PyInterpreterState_New();
  524. if (interp == NULL) {
  525. return _PyStatus_ERR("can't make main interpreter");
  526. }
  527. assert(_Py_IsMainInterpreter(interp));
  528. status = _PyConfig_Copy(&interp->config, src_config);
  529. if (_PyStatus_EXCEPTION(status)) {
  530. return status;
  531. }
  532. /* Auto-thread-state API */
  533. status = _PyGILState_Init(interp);
  534. if (_PyStatus_EXCEPTION(status)) {
  535. return status;
  536. }
  537. PyInterpreterConfig config = _PyInterpreterConfig_LEGACY_INIT;
  538. // The main interpreter always has its own GIL.
  539. config.gil = PyInterpreterConfig_OWN_GIL;
  540. status = init_interp_settings(interp, &config);
  541. if (_PyStatus_EXCEPTION(status)) {
  542. return status;
  543. }
  544. // This could be done in init_interpreter() (in pystate.c) if it
  545. // didn't depend on interp->feature_flags being set already.
  546. _PyObject_InitState(interp);
  547. PyThreadState *tstate = _PyThreadState_New(interp);
  548. if (tstate == NULL) {
  549. return _PyStatus_ERR("can't make first thread");
  550. }
  551. _PyThreadState_Bind(tstate);
  552. // XXX For now we do this before the GIL is created.
  553. (void) _PyThreadState_SwapNoGIL(tstate);
  554. status = init_interp_create_gil(tstate, config.gil);
  555. if (_PyStatus_EXCEPTION(status)) {
  556. return status;
  557. }
  558. *tstate_p = tstate;
  559. return _PyStatus_OK();
  560. }
  561. static PyStatus
  562. pycore_init_global_objects(PyInterpreterState *interp)
  563. {
  564. PyStatus status;
  565. _PyFloat_InitState(interp);
  566. status = _PyUnicode_InitGlobalObjects(interp);
  567. if (_PyStatus_EXCEPTION(status)) {
  568. return status;
  569. }
  570. _PyUnicode_InitState(interp);
  571. return _PyStatus_OK();
  572. }
  573. static PyStatus
  574. pycore_init_types(PyInterpreterState *interp)
  575. {
  576. PyStatus status;
  577. status = _PyTypes_InitTypes(interp);
  578. if (_PyStatus_EXCEPTION(status)) {
  579. return status;
  580. }
  581. status = _PyLong_InitTypes(interp);
  582. if (_PyStatus_EXCEPTION(status)) {
  583. return status;
  584. }
  585. status = _PyUnicode_InitTypes(interp);
  586. if (_PyStatus_EXCEPTION(status)) {
  587. return status;
  588. }
  589. status = _PyFloat_InitTypes(interp);
  590. if (_PyStatus_EXCEPTION(status)) {
  591. return status;
  592. }
  593. if (_PyExc_InitTypes(interp) < 0) {
  594. return _PyStatus_ERR("failed to initialize an exception type");
  595. }
  596. status = _PyExc_InitGlobalObjects(interp);
  597. if (_PyStatus_EXCEPTION(status)) {
  598. return status;
  599. }
  600. status = _PyExc_InitState(interp);
  601. if (_PyStatus_EXCEPTION(status)) {
  602. return status;
  603. }
  604. status = _PyErr_InitTypes(interp);
  605. if (_PyStatus_EXCEPTION(status)) {
  606. return status;
  607. }
  608. status = _PyContext_Init(interp);
  609. if (_PyStatus_EXCEPTION(status)) {
  610. return status;
  611. }
  612. return _PyStatus_OK();
  613. }
  614. static const uint8_t INTERPRETER_TRAMPOLINE_INSTRUCTIONS[] = {
  615. /* Put a NOP at the start, so that the IP points into
  616. * the code, rather than before it */
  617. NOP, 0,
  618. INTERPRETER_EXIT, 0,
  619. /* RESUME at end makes sure that the frame appears incomplete */
  620. RESUME, 0
  621. };
  622. static const _PyShimCodeDef INTERPRETER_TRAMPOLINE_CODEDEF = {
  623. INTERPRETER_TRAMPOLINE_INSTRUCTIONS,
  624. sizeof(INTERPRETER_TRAMPOLINE_INSTRUCTIONS),
  625. 1,
  626. "<interpreter trampoline>"
  627. };
  628. static PyStatus
  629. pycore_init_builtins(PyThreadState *tstate)
  630. {
  631. PyInterpreterState *interp = tstate->interp;
  632. PyObject *bimod = _PyBuiltin_Init(interp);
  633. if (bimod == NULL) {
  634. goto error;
  635. }
  636. PyObject *modules = _PyImport_GetModules(interp);
  637. if (_PyImport_FixupBuiltin(bimod, "builtins", modules) < 0) {
  638. goto error;
  639. }
  640. PyObject *builtins_dict = PyModule_GetDict(bimod);
  641. if (builtins_dict == NULL) {
  642. goto error;
  643. }
  644. interp->builtins = Py_NewRef(builtins_dict);
  645. PyObject *isinstance = PyDict_GetItem(builtins_dict, &_Py_ID(isinstance));
  646. assert(isinstance);
  647. interp->callable_cache.isinstance = isinstance;
  648. PyObject *len = PyDict_GetItem(builtins_dict, &_Py_ID(len));
  649. assert(len);
  650. interp->callable_cache.len = len;
  651. PyObject *list_append = _PyType_Lookup(&PyList_Type, &_Py_ID(append));
  652. assert(list_append);
  653. interp->callable_cache.list_append = list_append;
  654. PyObject *object__getattribute__ = _PyType_Lookup(&PyBaseObject_Type, &_Py_ID(__getattribute__));
  655. assert(object__getattribute__);
  656. interp->callable_cache.object__getattribute__ = object__getattribute__;
  657. interp->interpreter_trampoline = _Py_MakeShimCode(&INTERPRETER_TRAMPOLINE_CODEDEF);
  658. if (interp->interpreter_trampoline == NULL) {
  659. return _PyStatus_ERR("failed to create interpreter trampoline.");
  660. }
  661. if (_PyBuiltins_AddExceptions(bimod) < 0) {
  662. return _PyStatus_ERR("failed to add exceptions to builtins");
  663. }
  664. interp->builtins_copy = PyDict_Copy(interp->builtins);
  665. if (interp->builtins_copy == NULL) {
  666. goto error;
  667. }
  668. Py_DECREF(bimod);
  669. if (_PyImport_InitDefaultImportFunc(interp) < 0) {
  670. goto error;
  671. }
  672. assert(!_PyErr_Occurred(tstate));
  673. return _PyStatus_OK();
  674. error:
  675. Py_XDECREF(bimod);
  676. return _PyStatus_ERR("can't initialize builtins module");
  677. }
  678. static PyStatus
  679. pycore_interp_init(PyThreadState *tstate)
  680. {
  681. PyInterpreterState *interp = tstate->interp;
  682. PyStatus status;
  683. PyObject *sysmod = NULL;
  684. // Create singletons before the first PyType_Ready() call, since
  685. // PyType_Ready() uses singletons like the Unicode empty string (tp_doc)
  686. // and the empty tuple singletons (tp_bases).
  687. status = pycore_init_global_objects(interp);
  688. if (_PyStatus_EXCEPTION(status)) {
  689. return status;
  690. }
  691. // The GC must be initialized before the first GC collection.
  692. status = _PyGC_Init(interp);
  693. if (_PyStatus_EXCEPTION(status)) {
  694. return status;
  695. }
  696. // Intern strings in deep-frozen modules first so that others
  697. // can use it instead of creating a heap allocated string.
  698. if (_Py_Deepfreeze_Init() < 0) {
  699. return _PyStatus_ERR("failed to initialize deep-frozen modules");
  700. }
  701. // Per-interpreter interned string dict is created after deep-frozen
  702. // modules have interned the global strings.
  703. status = _PyUnicode_InitInternDict(interp);
  704. if (_PyStatus_EXCEPTION(status)) {
  705. return status;
  706. }
  707. status = pycore_init_types(interp);
  708. if (_PyStatus_EXCEPTION(status)) {
  709. goto done;
  710. }
  711. if (_PyWarnings_InitState(interp) < 0) {
  712. return _PyStatus_ERR("can't initialize warnings");
  713. }
  714. status = _PyAtExit_Init(interp);
  715. if (_PyStatus_EXCEPTION(status)) {
  716. return status;
  717. }
  718. status = _PySys_Create(tstate, &sysmod);
  719. if (_PyStatus_EXCEPTION(status)) {
  720. goto done;
  721. }
  722. status = pycore_init_builtins(tstate);
  723. if (_PyStatus_EXCEPTION(status)) {
  724. goto done;
  725. }
  726. const PyConfig *config = _PyInterpreterState_GetConfig(interp);
  727. status = _PyImport_InitCore(tstate, sysmod, config->_install_importlib);
  728. if (_PyStatus_EXCEPTION(status)) {
  729. goto done;
  730. }
  731. done:
  732. /* sys.modules['sys'] contains a strong reference to the module */
  733. Py_XDECREF(sysmod);
  734. return status;
  735. }
  736. static PyStatus
  737. pyinit_config(_PyRuntimeState *runtime,
  738. PyThreadState **tstate_p,
  739. const PyConfig *config)
  740. {
  741. PyStatus status = pycore_init_runtime(runtime, config);
  742. if (_PyStatus_EXCEPTION(status)) {
  743. return status;
  744. }
  745. PyThreadState *tstate;
  746. status = pycore_create_interpreter(runtime, config, &tstate);
  747. if (_PyStatus_EXCEPTION(status)) {
  748. return status;
  749. }
  750. *tstate_p = tstate;
  751. status = pycore_interp_init(tstate);
  752. if (_PyStatus_EXCEPTION(status)) {
  753. return status;
  754. }
  755. /* Only when we get here is the runtime core fully initialized */
  756. runtime->core_initialized = 1;
  757. return _PyStatus_OK();
  758. }
  759. PyStatus
  760. _Py_PreInitializeFromPyArgv(const PyPreConfig *src_config, const _PyArgv *args)
  761. {
  762. PyStatus status;
  763. if (src_config == NULL) {
  764. return _PyStatus_ERR("preinitialization config is NULL");
  765. }
  766. status = _PyRuntime_Initialize();
  767. if (_PyStatus_EXCEPTION(status)) {
  768. return status;
  769. }
  770. _PyRuntimeState *runtime = &_PyRuntime;
  771. if (runtime->preinitialized) {
  772. /* If it's already configured: ignored the new configuration */
  773. return _PyStatus_OK();
  774. }
  775. /* Note: preinitialized remains 1 on error, it is only set to 0
  776. at exit on success. */
  777. runtime->preinitializing = 1;
  778. PyPreConfig config;
  779. status = _PyPreConfig_InitFromPreConfig(&config, src_config);
  780. if (_PyStatus_EXCEPTION(status)) {
  781. return status;
  782. }
  783. status = _PyPreConfig_Read(&config, args);
  784. if (_PyStatus_EXCEPTION(status)) {
  785. return status;
  786. }
  787. status = _PyPreConfig_Write(&config);
  788. if (_PyStatus_EXCEPTION(status)) {
  789. return status;
  790. }
  791. runtime->preinitializing = 0;
  792. runtime->preinitialized = 1;
  793. return _PyStatus_OK();
  794. }
  795. PyStatus
  796. Py_PreInitializeFromBytesArgs(const PyPreConfig *src_config, Py_ssize_t argc, char **argv)
  797. {
  798. _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
  799. return _Py_PreInitializeFromPyArgv(src_config, &args);
  800. }
  801. PyStatus
  802. Py_PreInitializeFromArgs(const PyPreConfig *src_config, Py_ssize_t argc, wchar_t **argv)
  803. {
  804. _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
  805. return _Py_PreInitializeFromPyArgv(src_config, &args);
  806. }
  807. PyStatus
  808. Py_PreInitialize(const PyPreConfig *src_config)
  809. {
  810. return _Py_PreInitializeFromPyArgv(src_config, NULL);
  811. }
  812. PyStatus
  813. _Py_PreInitializeFromConfig(const PyConfig *config,
  814. const _PyArgv *args)
  815. {
  816. assert(config != NULL);
  817. PyStatus status = _PyRuntime_Initialize();
  818. if (_PyStatus_EXCEPTION(status)) {
  819. return status;
  820. }
  821. _PyRuntimeState *runtime = &_PyRuntime;
  822. if (runtime->preinitialized) {
  823. /* Already initialized: do nothing */
  824. return _PyStatus_OK();
  825. }
  826. PyPreConfig preconfig;
  827. _PyPreConfig_InitFromConfig(&preconfig, config);
  828. if (!config->parse_argv) {
  829. return Py_PreInitialize(&preconfig);
  830. }
  831. else if (args == NULL) {
  832. _PyArgv config_args = {
  833. .use_bytes_argv = 0,
  834. .argc = config->argv.length,
  835. .wchar_argv = config->argv.items};
  836. return _Py_PreInitializeFromPyArgv(&preconfig, &config_args);
  837. }
  838. else {
  839. return _Py_PreInitializeFromPyArgv(&preconfig, args);
  840. }
  841. }
  842. /* Begin interpreter initialization
  843. *
  844. * On return, the first thread and interpreter state have been created,
  845. * but the compiler, signal handling, multithreading and
  846. * multiple interpreter support, and codec infrastructure are not yet
  847. * available.
  848. *
  849. * The import system will support builtin and frozen modules only.
  850. * The only supported io is writing to sys.stderr
  851. *
  852. * If any operation invoked by this function fails, a fatal error is
  853. * issued and the function does not return.
  854. *
  855. * Any code invoked from this function should *not* assume it has access
  856. * to the Python C API (unless the API is explicitly listed as being
  857. * safe to call without calling Py_Initialize first)
  858. */
  859. static PyStatus
  860. pyinit_core(_PyRuntimeState *runtime,
  861. const PyConfig *src_config,
  862. PyThreadState **tstate_p)
  863. {
  864. PyStatus status;
  865. status = _Py_PreInitializeFromConfig(src_config, NULL);
  866. if (_PyStatus_EXCEPTION(status)) {
  867. return status;
  868. }
  869. PyConfig config;
  870. PyConfig_InitPythonConfig(&config);
  871. status = _PyConfig_Copy(&config, src_config);
  872. if (_PyStatus_EXCEPTION(status)) {
  873. goto done;
  874. }
  875. // Read the configuration, but don't compute the path configuration
  876. // (it is computed in the main init).
  877. status = _PyConfig_Read(&config, 0);
  878. if (_PyStatus_EXCEPTION(status)) {
  879. goto done;
  880. }
  881. if (!runtime->core_initialized) {
  882. status = pyinit_config(runtime, tstate_p, &config);
  883. }
  884. else {
  885. status = pyinit_core_reconfigure(runtime, tstate_p, &config);
  886. }
  887. if (_PyStatus_EXCEPTION(status)) {
  888. goto done;
  889. }
  890. done:
  891. PyConfig_Clear(&config);
  892. return status;
  893. }
  894. /* Py_Initialize() has already been called: update the main interpreter
  895. configuration. Example of bpo-34008: Py_Main() called after
  896. Py_Initialize(). */
  897. static PyStatus
  898. pyinit_main_reconfigure(PyThreadState *tstate)
  899. {
  900. if (interpreter_update_config(tstate, 0) < 0) {
  901. return _PyStatus_ERR("fail to reconfigure Python");
  902. }
  903. return _PyStatus_OK();
  904. }
  905. static PyStatus
  906. init_interp_main(PyThreadState *tstate)
  907. {
  908. assert(!_PyErr_Occurred(tstate));
  909. PyStatus status;
  910. int is_main_interp = _Py_IsMainInterpreter(tstate->interp);
  911. PyInterpreterState *interp = tstate->interp;
  912. const PyConfig *config = _PyInterpreterState_GetConfig(interp);
  913. if (!config->_install_importlib) {
  914. /* Special mode for freeze_importlib: run with no import system
  915. *
  916. * This means anything which needs support from extension modules
  917. * or pure Python code in the standard library won't work.
  918. */
  919. if (is_main_interp) {
  920. interp->runtime->initialized = 1;
  921. }
  922. return _PyStatus_OK();
  923. }
  924. // Initialize the import-related configuration.
  925. status = _PyConfig_InitImportConfig(&interp->config);
  926. if (_PyStatus_EXCEPTION(status)) {
  927. return status;
  928. }
  929. if (interpreter_update_config(tstate, 1) < 0) {
  930. return _PyStatus_ERR("failed to update the Python config");
  931. }
  932. status = _PyImport_InitExternal(tstate);
  933. if (_PyStatus_EXCEPTION(status)) {
  934. return status;
  935. }
  936. if (is_main_interp) {
  937. /* initialize the faulthandler module */
  938. status = _PyFaulthandler_Init(config->faulthandler);
  939. if (_PyStatus_EXCEPTION(status)) {
  940. return status;
  941. }
  942. }
  943. status = _PyUnicode_InitEncodings(tstate);
  944. if (_PyStatus_EXCEPTION(status)) {
  945. return status;
  946. }
  947. if (is_main_interp) {
  948. if (_PySignal_Init(config->install_signal_handlers) < 0) {
  949. return _PyStatus_ERR("can't initialize signals");
  950. }
  951. if (config->tracemalloc) {
  952. if (_PyTraceMalloc_Start(config->tracemalloc) < 0) {
  953. return _PyStatus_ERR("can't start tracemalloc");
  954. }
  955. }
  956. #ifdef PY_HAVE_PERF_TRAMPOLINE
  957. if (config->perf_profiling) {
  958. if (_PyPerfTrampoline_SetCallbacks(&_Py_perfmap_callbacks) < 0 ||
  959. _PyPerfTrampoline_Init(config->perf_profiling) < 0) {
  960. return _PyStatus_ERR("can't initialize the perf trampoline");
  961. }
  962. }
  963. #endif
  964. }
  965. status = init_sys_streams(tstate);
  966. if (_PyStatus_EXCEPTION(status)) {
  967. return status;
  968. }
  969. status = init_set_builtins_open();
  970. if (_PyStatus_EXCEPTION(status)) {
  971. return status;
  972. }
  973. status = add_main_module(interp);
  974. if (_PyStatus_EXCEPTION(status)) {
  975. return status;
  976. }
  977. if (is_main_interp) {
  978. /* Initialize warnings. */
  979. PyObject *warnoptions = PySys_GetObject("warnoptions");
  980. if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
  981. {
  982. PyObject *warnings_module = PyImport_ImportModule("warnings");
  983. if (warnings_module == NULL) {
  984. fprintf(stderr, "'import warnings' failed; traceback:\n");
  985. _PyErr_Print(tstate);
  986. }
  987. Py_XDECREF(warnings_module);
  988. }
  989. interp->runtime->initialized = 1;
  990. }
  991. if (config->site_import) {
  992. status = init_import_site();
  993. if (_PyStatus_EXCEPTION(status)) {
  994. return status;
  995. }
  996. }
  997. if (is_main_interp) {
  998. #ifndef MS_WINDOWS
  999. emit_stderr_warning_for_legacy_locale(interp->runtime);
  1000. #endif
  1001. }
  1002. if (!is_main_interp) {
  1003. // The main interpreter is handled in Py_Main(), for now.
  1004. wchar_t *sys_path_0 = interp->runtime->sys_path_0;
  1005. if (sys_path_0 != NULL) {
  1006. PyObject *path0 = PyUnicode_FromWideChar(sys_path_0, -1);
  1007. if (path0 == NULL) {
  1008. return _PyStatus_ERR("can't initialize sys.path[0]");
  1009. }
  1010. PyObject *sysdict = interp->sysdict;
  1011. if (sysdict == NULL) {
  1012. Py_DECREF(path0);
  1013. return _PyStatus_ERR("can't initialize sys.path[0]");
  1014. }
  1015. PyObject *sys_path = PyDict_GetItemWithError(sysdict, &_Py_ID(path));
  1016. if (sys_path == NULL) {
  1017. Py_DECREF(path0);
  1018. return _PyStatus_ERR("can't initialize sys.path[0]");
  1019. }
  1020. int res = PyList_Insert(sys_path, 0, path0);
  1021. Py_DECREF(path0);
  1022. if (res) {
  1023. return _PyStatus_ERR("can't initialize sys.path[0]");
  1024. }
  1025. }
  1026. }
  1027. assert(!_PyErr_Occurred(tstate));
  1028. return _PyStatus_OK();
  1029. }
  1030. /* Update interpreter state based on supplied configuration settings
  1031. *
  1032. * After calling this function, most of the restrictions on the interpreter
  1033. * are lifted. The only remaining incomplete settings are those related
  1034. * to the main module (sys.argv[0], __main__ metadata)
  1035. *
  1036. * Calling this when the interpreter is not initializing, is already
  1037. * initialized or without a valid current thread state is a fatal error.
  1038. * Other errors should be reported as normal Python exceptions with a
  1039. * non-zero return code.
  1040. */
  1041. static PyStatus
  1042. pyinit_main(PyThreadState *tstate)
  1043. {
  1044. PyInterpreterState *interp = tstate->interp;
  1045. if (!interp->runtime->core_initialized) {
  1046. return _PyStatus_ERR("runtime core not initialized");
  1047. }
  1048. if (interp->runtime->initialized) {
  1049. return pyinit_main_reconfigure(tstate);
  1050. }
  1051. PyStatus status = init_interp_main(tstate);
  1052. if (_PyStatus_EXCEPTION(status)) {
  1053. return status;
  1054. }
  1055. return _PyStatus_OK();
  1056. }
  1057. PyStatus
  1058. Py_InitializeFromConfig(const PyConfig *config)
  1059. {
  1060. if (config == NULL) {
  1061. return _PyStatus_ERR("initialization config is NULL");
  1062. }
  1063. PyStatus status;
  1064. status = _PyRuntime_Initialize();
  1065. if (_PyStatus_EXCEPTION(status)) {
  1066. return status;
  1067. }
  1068. _PyRuntimeState *runtime = &_PyRuntime;
  1069. PyThreadState *tstate = NULL;
  1070. status = pyinit_core(runtime, config, &tstate);
  1071. if (_PyStatus_EXCEPTION(status)) {
  1072. return status;
  1073. }
  1074. config = _PyInterpreterState_GetConfig(tstate->interp);
  1075. if (config->_init_main) {
  1076. status = pyinit_main(tstate);
  1077. if (_PyStatus_EXCEPTION(status)) {
  1078. return status;
  1079. }
  1080. }
  1081. return _PyStatus_OK();
  1082. }
  1083. void
  1084. Py_InitializeEx(int install_sigs)
  1085. {
  1086. PyStatus status;
  1087. status = _PyRuntime_Initialize();
  1088. if (_PyStatus_EXCEPTION(status)) {
  1089. Py_ExitStatusException(status);
  1090. }
  1091. _PyRuntimeState *runtime = &_PyRuntime;
  1092. if (runtime->initialized) {
  1093. /* bpo-33932: Calling Py_Initialize() twice does nothing. */
  1094. return;
  1095. }
  1096. PyConfig config;
  1097. _PyConfig_InitCompatConfig(&config);
  1098. config.install_signal_handlers = install_sigs;
  1099. status = Py_InitializeFromConfig(&config);
  1100. PyConfig_Clear(&config);
  1101. if (_PyStatus_EXCEPTION(status)) {
  1102. Py_ExitStatusException(status);
  1103. }
  1104. }
  1105. void
  1106. Py_Initialize(void)
  1107. {
  1108. Py_InitializeEx(1);
  1109. }
  1110. PyStatus
  1111. _Py_InitializeMain(void)
  1112. {
  1113. PyStatus status = _PyRuntime_Initialize();
  1114. if (_PyStatus_EXCEPTION(status)) {
  1115. return status;
  1116. }
  1117. PyThreadState *tstate = _PyThreadState_GET();
  1118. return pyinit_main(tstate);
  1119. }
  1120. static void
  1121. finalize_modules_delete_special(PyThreadState *tstate, int verbose)
  1122. {
  1123. // List of names to clear in sys
  1124. static const char * const sys_deletes[] = {
  1125. "path", "argv", "ps1", "ps2", "last_exc",
  1126. "last_type", "last_value", "last_traceback",
  1127. "__interactivehook__",
  1128. // path_hooks and path_importer_cache are cleared
  1129. // by _PyImport_FiniExternal().
  1130. // XXX Clear meta_path in _PyImport_FiniCore().
  1131. "meta_path",
  1132. NULL
  1133. };
  1134. static const char * const sys_files[] = {
  1135. "stdin", "__stdin__",
  1136. "stdout", "__stdout__",
  1137. "stderr", "__stderr__",
  1138. NULL
  1139. };
  1140. PyInterpreterState *interp = tstate->interp;
  1141. if (verbose) {
  1142. PySys_WriteStderr("# clear builtins._\n");
  1143. }
  1144. if (PyDict_SetItemString(interp->builtins, "_", Py_None) < 0) {
  1145. PyErr_WriteUnraisable(NULL);
  1146. }
  1147. const char * const *p;
  1148. for (p = sys_deletes; *p != NULL; p++) {
  1149. if (_PySys_ClearAttrString(interp, *p, verbose) < 0) {
  1150. PyErr_WriteUnraisable(NULL);
  1151. }
  1152. }
  1153. for (p = sys_files; *p != NULL; p+=2) {
  1154. const char *name = p[0];
  1155. const char *orig_name = p[1];
  1156. if (verbose) {
  1157. PySys_WriteStderr("# restore sys.%s\n", name);
  1158. }
  1159. PyObject *value = _PyDict_GetItemStringWithError(interp->sysdict,
  1160. orig_name);
  1161. if (value == NULL) {
  1162. if (_PyErr_Occurred(tstate)) {
  1163. PyErr_WriteUnraisable(NULL);
  1164. }
  1165. value = Py_None;
  1166. }
  1167. if (PyDict_SetItemString(interp->sysdict, name, value) < 0) {
  1168. PyErr_WriteUnraisable(NULL);
  1169. }
  1170. }
  1171. }
  1172. static PyObject*
  1173. finalize_remove_modules(PyObject *modules, int verbose)
  1174. {
  1175. PyObject *weaklist = PyList_New(0);
  1176. if (weaklist == NULL) {
  1177. PyErr_WriteUnraisable(NULL);
  1178. }
  1179. #define STORE_MODULE_WEAKREF(name, mod) \
  1180. if (weaklist != NULL) { \
  1181. PyObject *wr = PyWeakref_NewRef(mod, NULL); \
  1182. if (wr) { \
  1183. PyObject *tup = PyTuple_Pack(2, name, wr); \
  1184. if (!tup || PyList_Append(weaklist, tup) < 0) { \
  1185. PyErr_WriteUnraisable(NULL); \
  1186. } \
  1187. Py_XDECREF(tup); \
  1188. Py_DECREF(wr); \
  1189. } \
  1190. else { \
  1191. PyErr_WriteUnraisable(NULL); \
  1192. } \
  1193. }
  1194. #define CLEAR_MODULE(name, mod) \
  1195. if (PyModule_Check(mod)) { \
  1196. if (verbose && PyUnicode_Check(name)) { \
  1197. PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
  1198. } \
  1199. STORE_MODULE_WEAKREF(name, mod); \
  1200. if (PyObject_SetItem(modules, name, Py_None) < 0) { \
  1201. PyErr_WriteUnraisable(NULL); \
  1202. } \
  1203. }
  1204. if (PyDict_CheckExact(modules)) {
  1205. Py_ssize_t pos = 0;
  1206. PyObject *key, *value;
  1207. while (PyDict_Next(modules, &pos, &key, &value)) {
  1208. CLEAR_MODULE(key, value);
  1209. }
  1210. }
  1211. else {
  1212. PyObject *iterator = PyObject_GetIter(modules);
  1213. if (iterator == NULL) {
  1214. PyErr_WriteUnraisable(NULL);
  1215. }
  1216. else {
  1217. PyObject *key;
  1218. while ((key = PyIter_Next(iterator))) {
  1219. PyObject *value = PyObject_GetItem(modules, key);
  1220. if (value == NULL) {
  1221. PyErr_WriteUnraisable(NULL);
  1222. continue;
  1223. }
  1224. CLEAR_MODULE(key, value);
  1225. Py_DECREF(value);
  1226. Py_DECREF(key);
  1227. }
  1228. if (PyErr_Occurred()) {
  1229. PyErr_WriteUnraisable(NULL);
  1230. }
  1231. Py_DECREF(iterator);
  1232. }
  1233. }
  1234. #undef CLEAR_MODULE
  1235. #undef STORE_MODULE_WEAKREF
  1236. return weaklist;
  1237. }
  1238. static void
  1239. finalize_clear_modules_dict(PyObject *modules)
  1240. {
  1241. if (PyDict_CheckExact(modules)) {
  1242. PyDict_Clear(modules);
  1243. }
  1244. else {
  1245. if (PyObject_CallMethodNoArgs(modules, &_Py_ID(clear)) == NULL) {
  1246. PyErr_WriteUnraisable(NULL);
  1247. }
  1248. }
  1249. }
  1250. static void
  1251. finalize_restore_builtins(PyThreadState *tstate)
  1252. {
  1253. PyInterpreterState *interp = tstate->interp;
  1254. PyObject *dict = PyDict_Copy(interp->builtins);
  1255. if (dict == NULL) {
  1256. PyErr_WriteUnraisable(NULL);
  1257. }
  1258. PyDict_Clear(interp->builtins);
  1259. if (PyDict_Update(interp->builtins, interp->builtins_copy)) {
  1260. PyErr_WriteUnraisable(NULL);
  1261. }
  1262. Py_XDECREF(dict);
  1263. }
  1264. static void
  1265. finalize_modules_clear_weaklist(PyInterpreterState *interp,
  1266. PyObject *weaklist, int verbose)
  1267. {
  1268. // First clear modules imported later
  1269. for (Py_ssize_t i = PyList_GET_SIZE(weaklist) - 1; i >= 0; i--) {
  1270. PyObject *tup = PyList_GET_ITEM(weaklist, i);
  1271. PyObject *name = PyTuple_GET_ITEM(tup, 0);
  1272. PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
  1273. if (mod == Py_None) {
  1274. continue;
  1275. }
  1276. assert(PyModule_Check(mod));
  1277. PyObject *dict = PyModule_GetDict(mod);
  1278. if (dict == interp->builtins || dict == interp->sysdict) {
  1279. continue;
  1280. }
  1281. Py_INCREF(mod);
  1282. if (verbose && PyUnicode_Check(name)) {
  1283. PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
  1284. }
  1285. _PyModule_Clear(mod);
  1286. Py_DECREF(mod);
  1287. }
  1288. }
  1289. static void
  1290. finalize_clear_sys_builtins_dict(PyInterpreterState *interp, int verbose)
  1291. {
  1292. // Clear sys dict
  1293. if (verbose) {
  1294. PySys_FormatStderr("# cleanup[3] wiping sys\n");
  1295. }
  1296. _PyModule_ClearDict(interp->sysdict);
  1297. // Clear builtins dict
  1298. if (verbose) {
  1299. PySys_FormatStderr("# cleanup[3] wiping builtins\n");
  1300. }
  1301. _PyModule_ClearDict(interp->builtins);
  1302. }
  1303. /* Clear modules, as good as we can */
  1304. // XXX Move most of this to import.c.
  1305. static void
  1306. finalize_modules(PyThreadState *tstate)
  1307. {
  1308. PyInterpreterState *interp = tstate->interp;
  1309. PyObject *modules = _PyImport_GetModules(interp);
  1310. if (modules == NULL) {
  1311. // Already done
  1312. return;
  1313. }
  1314. int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
  1315. // Delete some special builtins._ and sys attributes first. These are
  1316. // common places where user values hide and people complain when their
  1317. // destructors fail. Since the modules containing them are
  1318. // deleted *last* of all, they would come too late in the normal
  1319. // destruction order. Sigh.
  1320. //
  1321. // XXX Perhaps these precautions are obsolete. Who knows?
  1322. finalize_modules_delete_special(tstate, verbose);
  1323. // Remove all modules from sys.modules, hoping that garbage collection
  1324. // can reclaim most of them: set all sys.modules values to None.
  1325. //
  1326. // We prepare a list which will receive (name, weakref) tuples of
  1327. // modules when they are removed from sys.modules. The name is used
  1328. // for diagnosis messages (in verbose mode), while the weakref helps
  1329. // detect those modules which have been held alive.
  1330. PyObject *weaklist = finalize_remove_modules(modules, verbose);
  1331. // Clear the modules dict
  1332. finalize_clear_modules_dict(modules);
  1333. // Restore the original builtins dict, to ensure that any
  1334. // user data gets cleared.
  1335. finalize_restore_builtins(tstate);
  1336. // Collect garbage
  1337. _PyGC_CollectNoFail(tstate);
  1338. // Dump GC stats before it's too late, since it uses the warnings
  1339. // machinery.
  1340. _PyGC_DumpShutdownStats(interp);
  1341. if (weaklist != NULL) {
  1342. // Now, if there are any modules left alive, clear their globals to
  1343. // minimize potential leaks. All C extension modules actually end
  1344. // up here, since they are kept alive in the interpreter state.
  1345. //
  1346. // The special treatment of "builtins" here is because even
  1347. // when it's not referenced as a module, its dictionary is
  1348. // referenced by almost every module's __builtins__. Since
  1349. // deleting a module clears its dictionary (even if there are
  1350. // references left to it), we need to delete the "builtins"
  1351. // module last. Likewise, we don't delete sys until the very
  1352. // end because it is implicitly referenced (e.g. by print).
  1353. //
  1354. // Since dict is ordered in CPython 3.6+, modules are saved in
  1355. // importing order. First clear modules imported later.
  1356. finalize_modules_clear_weaklist(interp, weaklist, verbose);
  1357. Py_DECREF(weaklist);
  1358. }
  1359. // Clear sys and builtins modules dict
  1360. finalize_clear_sys_builtins_dict(interp, verbose);
  1361. // Clear module dict copies stored in the interpreter state:
  1362. // clear PyInterpreterState.modules_by_index and
  1363. // clear PyModuleDef.m_base.m_copy (of extensions not using the multi-phase
  1364. // initialization API)
  1365. _PyImport_ClearModulesByIndex(interp);
  1366. // Clear and delete the modules directory. Actual modules will
  1367. // still be there only if imported during the execution of some
  1368. // destructor.
  1369. _PyImport_ClearModules(interp);
  1370. // Collect garbage once more
  1371. _PyGC_CollectNoFail(tstate);
  1372. }
  1373. /* Flush stdout and stderr */
  1374. static int
  1375. file_is_closed(PyObject *fobj)
  1376. {
  1377. int r;
  1378. PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
  1379. if (tmp == NULL) {
  1380. PyErr_Clear();
  1381. return 0;
  1382. }
  1383. r = PyObject_IsTrue(tmp);
  1384. Py_DECREF(tmp);
  1385. if (r < 0)
  1386. PyErr_Clear();
  1387. return r > 0;
  1388. }
  1389. static int
  1390. flush_std_files(void)
  1391. {
  1392. PyThreadState *tstate = _PyThreadState_GET();
  1393. PyObject *fout = _PySys_GetAttr(tstate, &_Py_ID(stdout));
  1394. PyObject *ferr = _PySys_GetAttr(tstate, &_Py_ID(stderr));
  1395. PyObject *tmp;
  1396. int status = 0;
  1397. if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
  1398. tmp = PyObject_CallMethodNoArgs(fout, &_Py_ID(flush));
  1399. if (tmp == NULL) {
  1400. PyErr_WriteUnraisable(fout);
  1401. status = -1;
  1402. }
  1403. else
  1404. Py_DECREF(tmp);
  1405. }
  1406. if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
  1407. tmp = PyObject_CallMethodNoArgs(ferr, &_Py_ID(flush));
  1408. if (tmp == NULL) {
  1409. PyErr_Clear();
  1410. status = -1;
  1411. }
  1412. else
  1413. Py_DECREF(tmp);
  1414. }
  1415. return status;
  1416. }
  1417. /* Undo the effect of Py_Initialize().
  1418. Beware: if multiple interpreter and/or thread states exist, these
  1419. are not wiped out; only the current thread and interpreter state
  1420. are deleted. But since everything else is deleted, those other
  1421. interpreter and thread states should no longer be used.
  1422. (XXX We should do better, e.g. wipe out all interpreters and
  1423. threads.)
  1424. Locking: as above.
  1425. */
  1426. static void
  1427. finalize_interp_types(PyInterpreterState *interp)
  1428. {
  1429. _PyUnicode_FiniTypes(interp);
  1430. _PySys_FiniTypes(interp);
  1431. _PyExc_Fini(interp);
  1432. _PyAsyncGen_Fini(interp);
  1433. _PyContext_Fini(interp);
  1434. _PyFloat_FiniType(interp);
  1435. _PyLong_FiniTypes(interp);
  1436. _PyThread_FiniType(interp);
  1437. // XXX fini collections module static types (_PyStaticType_Dealloc())
  1438. // XXX fini IO module static types (_PyStaticType_Dealloc())
  1439. _PyErr_FiniTypes(interp);
  1440. _PyTypes_FiniTypes(interp);
  1441. _PyTypes_Fini(interp);
  1442. // Call _PyUnicode_ClearInterned() before _PyDict_Fini() since it uses
  1443. // a dict internally.
  1444. _PyUnicode_ClearInterned(interp);
  1445. _PyDict_Fini(interp);
  1446. _PyList_Fini(interp);
  1447. _PyTuple_Fini(interp);
  1448. _PySlice_Fini(interp);
  1449. _PyUnicode_Fini(interp);
  1450. _PyFloat_Fini(interp);
  1451. #ifdef Py_DEBUG
  1452. _PyStaticObjects_CheckRefcnt(interp);
  1453. #endif
  1454. }
  1455. static void
  1456. finalize_interp_clear(PyThreadState *tstate)
  1457. {
  1458. int is_main_interp = _Py_IsMainInterpreter(tstate->interp);
  1459. _PyExc_ClearExceptionGroupType(tstate->interp);
  1460. _Py_clear_generic_types(tstate->interp);
  1461. /* Clear interpreter state and all thread states */
  1462. _PyInterpreterState_Clear(tstate);
  1463. /* Clear all loghooks */
  1464. /* Both _PySys_Audit function and users still need PyObject, such as tuple.
  1465. Call _PySys_ClearAuditHooks when PyObject available. */
  1466. if (is_main_interp) {
  1467. _PySys_ClearAuditHooks(tstate);
  1468. }
  1469. if (is_main_interp) {
  1470. _Py_HashRandomization_Fini();
  1471. _PyArg_Fini();
  1472. _Py_ClearFileSystemEncoding();
  1473. _Py_Deepfreeze_Fini();
  1474. _PyPerfTrampoline_Fini();
  1475. _PyPerfTrampoline_FreeArenas();
  1476. }
  1477. finalize_interp_types(tstate->interp);
  1478. }
  1479. static void
  1480. finalize_interp_delete(PyInterpreterState *interp)
  1481. {
  1482. /* Cleanup auto-thread-state */
  1483. _PyGILState_Fini(interp);
  1484. /* We can't call _PyEval_FiniGIL() here because destroying the GIL lock can
  1485. fail when it is being awaited by another running daemon thread (see
  1486. bpo-9901). Instead pycore_create_interpreter() destroys the previously
  1487. created GIL, which ensures that Py_Initialize / Py_FinalizeEx can be
  1488. called multiple times. */
  1489. PyInterpreterState_Delete(interp);
  1490. }
  1491. int
  1492. Py_FinalizeEx(void)
  1493. {
  1494. int status = 0;
  1495. _PyRuntimeState *runtime = &_PyRuntime;
  1496. if (!runtime->initialized) {
  1497. return status;
  1498. }
  1499. /* Get current thread state and interpreter pointer */
  1500. PyThreadState *tstate = _PyThreadState_GET();
  1501. // XXX assert(_Py_IsMainInterpreter(tstate->interp));
  1502. // XXX assert(_Py_IsMainThread());
  1503. // Block some operations.
  1504. tstate->interp->finalizing = 1;
  1505. // Wrap up existing "threading"-module-created, non-daemon threads.
  1506. wait_for_thread_shutdown(tstate);
  1507. // Make any remaining pending calls.
  1508. _Py_FinishPendingCalls(tstate);
  1509. /* The interpreter is still entirely intact at this point, and the
  1510. * exit funcs may be relying on that. In particular, if some thread
  1511. * or exit func is still waiting to do an import, the import machinery
  1512. * expects Py_IsInitialized() to return true. So don't say the
  1513. * runtime is uninitialized until after the exit funcs have run.
  1514. * Note that Threading.py uses an exit func to do a join on all the
  1515. * threads created thru it, so this also protects pending imports in
  1516. * the threads created via Threading.
  1517. */
  1518. _PyAtExit_Call(tstate->interp);
  1519. /* Copy the core config, PyInterpreterState_Delete() free
  1520. the core config memory */
  1521. #ifdef Py_REF_DEBUG
  1522. int show_ref_count = tstate->interp->config.show_ref_count;
  1523. #endif
  1524. #ifdef Py_TRACE_REFS
  1525. int dump_refs = tstate->interp->config.dump_refs;
  1526. wchar_t *dump_refs_file = tstate->interp->config.dump_refs_file;
  1527. #endif
  1528. #ifdef WITH_PYMALLOC
  1529. int malloc_stats = tstate->interp->config.malloc_stats;
  1530. #endif
  1531. /* Remaining daemon threads will automatically exit
  1532. when they attempt to take the GIL (ex: PyEval_RestoreThread()). */
  1533. _PyInterpreterState_SetFinalizing(tstate->interp, tstate);
  1534. _PyRuntimeState_SetFinalizing(runtime, tstate);
  1535. runtime->initialized = 0;
  1536. runtime->core_initialized = 0;
  1537. // XXX Call something like _PyImport_Disable() here?
  1538. /* Destroy the state of all threads of the interpreter, except of the
  1539. current thread. In practice, only daemon threads should still be alive,
  1540. except if wait_for_thread_shutdown() has been cancelled by CTRL+C.
  1541. Clear frames of other threads to call objects destructors. Destructors
  1542. will be called in the current Python thread. Since
  1543. _PyRuntimeState_SetFinalizing() has been called, no other Python thread
  1544. can take the GIL at this point: if they try, they will exit
  1545. immediately. */
  1546. _PyThreadState_DeleteExcept(tstate);
  1547. /* At this point no Python code should be running at all.
  1548. The only thread state left should be the main thread of the main
  1549. interpreter (AKA tstate), in which this code is running right now.
  1550. There may be other OS threads running but none of them will have
  1551. thread states associated with them, nor will be able to create
  1552. new thread states.
  1553. Thus tstate is the only possible thread state from here on out.
  1554. It may still be used during finalization to run Python code as
  1555. needed or provide runtime state (e.g. sys.modules) but that will
  1556. happen sparingly. Furthermore, the order of finalization aims
  1557. to not need a thread (or interpreter) state as soon as possible.
  1558. */
  1559. // XXX Make sure we are preventing the creating of any new thread states
  1560. // (or interpreters).
  1561. /* Flush sys.stdout and sys.stderr */
  1562. if (flush_std_files() < 0) {
  1563. status = -1;
  1564. }
  1565. /* Disable signal handling */
  1566. _PySignal_Fini();
  1567. /* Collect garbage. This may call finalizers; it's nice to call these
  1568. * before all modules are destroyed.
  1569. * XXX If a __del__ or weakref callback is triggered here, and tries to
  1570. * XXX import a module, bad things can happen, because Python no
  1571. * XXX longer believes it's initialized.
  1572. * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
  1573. * XXX is easy to provoke that way. I've also seen, e.g.,
  1574. * XXX Exception exceptions.ImportError: 'No module named sha'
  1575. * XXX in <function callback at 0x008F5718> ignored
  1576. * XXX but I'm unclear on exactly how that one happens. In any case,
  1577. * XXX I haven't seen a real-life report of either of these.
  1578. */
  1579. PyGC_Collect();
  1580. /* Destroy all modules */
  1581. _PyImport_FiniExternal(tstate->interp);
  1582. finalize_modules(tstate);
  1583. /* Print debug stats if any */
  1584. _PyEval_Fini();
  1585. /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
  1586. if (flush_std_files() < 0) {
  1587. status = -1;
  1588. }
  1589. /* Collect final garbage. This disposes of cycles created by
  1590. * class definitions, for example.
  1591. * XXX This is disabled because it caused too many problems. If
  1592. * XXX a __del__ or weakref callback triggers here, Python code has
  1593. * XXX a hard time running, because even the sys module has been
  1594. * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
  1595. * XXX One symptom is a sequence of information-free messages
  1596. * XXX coming from threads (if a __del__ or callback is invoked,
  1597. * XXX other threads can execute too, and any exception they encounter
  1598. * XXX triggers a comedy of errors as subsystem after subsystem
  1599. * XXX fails to find what it *expects* to find in sys to help report
  1600. * XXX the exception and consequent unexpected failures). I've also
  1601. * XXX seen segfaults then, after adding print statements to the
  1602. * XXX Python code getting called.
  1603. */
  1604. #if 0
  1605. _PyGC_CollectIfEnabled();
  1606. #endif
  1607. /* Disable tracemalloc after all Python objects have been destroyed,
  1608. so it is possible to use tracemalloc in objects destructor. */
  1609. _PyTraceMalloc_Fini();
  1610. /* Finalize any remaining import state */
  1611. // XXX Move these up to where finalize_modules() is currently.
  1612. _PyImport_FiniCore(tstate->interp);
  1613. _PyImport_Fini();
  1614. /* unload faulthandler module */
  1615. _PyFaulthandler_Fini();
  1616. /* dump hash stats */
  1617. _PyHash_Fini();
  1618. #ifdef Py_TRACE_REFS
  1619. /* Display all objects still alive -- this can invoke arbitrary
  1620. * __repr__ overrides, so requires a mostly-intact interpreter.
  1621. * Alas, a lot of stuff may still be alive now that will be cleaned
  1622. * up later.
  1623. */
  1624. FILE *dump_refs_fp = NULL;
  1625. if (dump_refs_file != NULL) {
  1626. dump_refs_fp = _Py_wfopen(dump_refs_file, L"w");
  1627. if (dump_refs_fp == NULL) {
  1628. fprintf(stderr, "PYTHONDUMPREFSFILE: cannot create file: %ls\n", dump_refs_file);
  1629. }
  1630. }
  1631. if (dump_refs) {
  1632. _Py_PrintReferences(tstate->interp, stderr);
  1633. }
  1634. if (dump_refs_fp != NULL) {
  1635. _Py_PrintReferences(tstate->interp, dump_refs_fp);
  1636. }
  1637. #endif /* Py_TRACE_REFS */
  1638. /* At this point there's almost no other Python code that will run,
  1639. nor interpreter state needed. The only possibility is the
  1640. finalizers of the objects stored on tstate (and tstate->interp),
  1641. which are triggered via finalize_interp_clear().
  1642. For now we operate as though none of those finalizers actually
  1643. need an operational thread state or interpreter. In reality,
  1644. those finalizers may rely on some part of tstate or
  1645. tstate->interp, and/or may raise exceptions
  1646. or otherwise fail.
  1647. */
  1648. // XXX Do this sooner during finalization.
  1649. // XXX Ensure finalizer errors are handled properly.
  1650. finalize_interp_clear(tstate);
  1651. #ifdef WITH_PYMALLOC
  1652. if (malloc_stats) {
  1653. _PyObject_DebugMallocStats(stderr);
  1654. }
  1655. #endif
  1656. finalize_interp_delete(tstate->interp);
  1657. #ifdef Py_REF_DEBUG
  1658. if (show_ref_count) {
  1659. _PyDebug_PrintTotalRefs();
  1660. }
  1661. _Py_FinalizeRefTotal(runtime);
  1662. #endif
  1663. _Py_FinalizeAllocatedBlocks(runtime);
  1664. #ifdef Py_TRACE_REFS
  1665. /* Display addresses (& refcnts) of all objects still alive.
  1666. * An address can be used to find the repr of the object, printed
  1667. * above by _Py_PrintReferences.
  1668. */
  1669. if (dump_refs) {
  1670. _Py_PrintReferenceAddresses(tstate->interp, stderr);
  1671. }
  1672. if (dump_refs_fp != NULL) {
  1673. _Py_PrintReferenceAddresses(tstate->interp, dump_refs_fp);
  1674. fclose(dump_refs_fp);
  1675. }
  1676. #endif /* Py_TRACE_REFS */
  1677. call_ll_exitfuncs(runtime);
  1678. _PyRuntime_Finalize();
  1679. return status;
  1680. }
  1681. void
  1682. Py_Finalize(void)
  1683. {
  1684. Py_FinalizeEx();
  1685. }
  1686. /* Create and initialize a new interpreter and thread, and return the
  1687. new thread. This requires that Py_Initialize() has been called
  1688. first.
  1689. Unsuccessful initialization yields a NULL pointer. Note that *no*
  1690. exception information is available even in this case -- the
  1691. exception information is held in the thread, and there is no
  1692. thread.
  1693. Locking: as above.
  1694. */
  1695. static PyStatus
  1696. new_interpreter(PyThreadState **tstate_p, const PyInterpreterConfig *config)
  1697. {
  1698. PyStatus status;
  1699. status = _PyRuntime_Initialize();
  1700. if (_PyStatus_EXCEPTION(status)) {
  1701. return status;
  1702. }
  1703. _PyRuntimeState *runtime = &_PyRuntime;
  1704. if (!runtime->initialized) {
  1705. return _PyStatus_ERR("Py_Initialize must be called first");
  1706. }
  1707. /* Issue #10915, #15751: The GIL API doesn't work with multiple
  1708. interpreters: disable PyGILState_Check(). */
  1709. runtime->gilstate.check_enabled = 0;
  1710. PyInterpreterState *interp = PyInterpreterState_New();
  1711. if (interp == NULL) {
  1712. *tstate_p = NULL;
  1713. return _PyStatus_OK();
  1714. }
  1715. PyThreadState *tstate = _PyThreadState_New(interp);
  1716. if (tstate == NULL) {
  1717. PyInterpreterState_Delete(interp);
  1718. *tstate_p = NULL;
  1719. return _PyStatus_OK();
  1720. }
  1721. _PyThreadState_Bind(tstate);
  1722. // XXX For now we do this before the GIL is created.
  1723. PyThreadState *save_tstate = _PyThreadState_SwapNoGIL(tstate);
  1724. int has_gil = 0;
  1725. /* From this point until the init_interp_create_gil() call,
  1726. we must not do anything that requires that the GIL be held
  1727. (or otherwise exist). That applies whether or not the new
  1728. interpreter has its own GIL (e.g. the main interpreter). */
  1729. /* Copy the current interpreter config into the new interpreter */
  1730. const PyConfig *src_config;
  1731. if (save_tstate != NULL) {
  1732. // XXX Might new_interpreter() have been called without the GIL held?
  1733. _PyEval_ReleaseLock(save_tstate->interp, save_tstate);
  1734. src_config = _PyInterpreterState_GetConfig(save_tstate->interp);
  1735. }
  1736. else
  1737. {
  1738. /* No current thread state, copy from the main interpreter */
  1739. PyInterpreterState *main_interp = _PyInterpreterState_Main();
  1740. src_config = _PyInterpreterState_GetConfig(main_interp);
  1741. }
  1742. /* This does not require that the GIL be held. */
  1743. status = _PyConfig_Copy(&interp->config, src_config);
  1744. if (_PyStatus_EXCEPTION(status)) {
  1745. goto error;
  1746. }
  1747. /* This does not require that the GIL be held. */
  1748. status = init_interp_settings(interp, config);
  1749. if (_PyStatus_EXCEPTION(status)) {
  1750. goto error;
  1751. }
  1752. // This could be done in init_interpreter() (in pystate.c) if it
  1753. // didn't depend on interp->feature_flags being set already.
  1754. _PyObject_InitState(interp);
  1755. status = init_interp_create_gil(tstate, config->gil);
  1756. if (_PyStatus_EXCEPTION(status)) {
  1757. goto error;
  1758. }
  1759. has_gil = 1;
  1760. /* No objects have been created yet. */
  1761. status = pycore_interp_init(tstate);
  1762. if (_PyStatus_EXCEPTION(status)) {
  1763. goto error;
  1764. }
  1765. status = init_interp_main(tstate);
  1766. if (_PyStatus_EXCEPTION(status)) {
  1767. goto error;
  1768. }
  1769. *tstate_p = tstate;
  1770. return _PyStatus_OK();
  1771. error:
  1772. *tstate_p = NULL;
  1773. /* Oops, it didn't work. Undo it all. */
  1774. PyErr_PrintEx(0);
  1775. if (has_gil) {
  1776. PyThreadState_Swap(save_tstate);
  1777. }
  1778. else {
  1779. _PyThreadState_SwapNoGIL(save_tstate);
  1780. }
  1781. PyThreadState_Clear(tstate);
  1782. PyThreadState_Delete(tstate);
  1783. PyInterpreterState_Delete(interp);
  1784. return status;
  1785. }
  1786. PyStatus
  1787. Py_NewInterpreterFromConfig(PyThreadState **tstate_p,
  1788. const PyInterpreterConfig *config)
  1789. {
  1790. return new_interpreter(tstate_p, config);
  1791. }
  1792. PyThreadState *
  1793. Py_NewInterpreter(void)
  1794. {
  1795. PyThreadState *tstate = NULL;
  1796. const PyInterpreterConfig config = _PyInterpreterConfig_LEGACY_INIT;
  1797. PyStatus status = new_interpreter(&tstate, &config);
  1798. if (_PyStatus_EXCEPTION(status)) {
  1799. Py_ExitStatusException(status);
  1800. }
  1801. return tstate;
  1802. }
  1803. /* Delete an interpreter and its last thread. This requires that the
  1804. given thread state is current, that the thread has no remaining
  1805. frames, and that it is its interpreter's only remaining thread.
  1806. It is a fatal error to violate these constraints.
  1807. (Py_FinalizeEx() doesn't have these constraints -- it zaps
  1808. everything, regardless.)
  1809. Locking: as above.
  1810. */
  1811. void
  1812. Py_EndInterpreter(PyThreadState *tstate)
  1813. {
  1814. PyInterpreterState *interp = tstate->interp;
  1815. if (tstate != _PyThreadState_GET()) {
  1816. Py_FatalError("thread is not current");
  1817. }
  1818. if (tstate->cframe->current_frame != NULL) {
  1819. Py_FatalError("thread still has a frame");
  1820. }
  1821. interp->finalizing = 1;
  1822. // Wrap up existing "threading"-module-created, non-daemon threads.
  1823. wait_for_thread_shutdown(tstate);
  1824. // Make any remaining pending calls.
  1825. _Py_FinishPendingCalls(tstate);
  1826. _PyAtExit_Call(tstate->interp);
  1827. if (tstate != interp->threads.head || tstate->next != NULL) {
  1828. Py_FatalError("not the last thread");
  1829. }
  1830. /* Remaining daemon threads will automatically exit
  1831. when they attempt to take the GIL (ex: PyEval_RestoreThread()). */
  1832. _PyInterpreterState_SetFinalizing(interp, tstate);
  1833. // XXX Call something like _PyImport_Disable() here?
  1834. _PyImport_FiniExternal(tstate->interp);
  1835. finalize_modules(tstate);
  1836. _PyImport_FiniCore(tstate->interp);
  1837. finalize_interp_clear(tstate);
  1838. finalize_interp_delete(tstate->interp);
  1839. }
  1840. int
  1841. _Py_IsInterpreterFinalizing(PyInterpreterState *interp)
  1842. {
  1843. /* We check the runtime first since, in a daemon thread,
  1844. interp might be dangling pointer. */
  1845. PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(&_PyRuntime);
  1846. if (finalizing == NULL) {
  1847. finalizing = _PyInterpreterState_GetFinalizing(interp);
  1848. }
  1849. return finalizing != NULL;
  1850. }
  1851. /* Add the __main__ module */
  1852. static PyStatus
  1853. add_main_module(PyInterpreterState *interp)
  1854. {
  1855. PyObject *m, *d, *loader, *ann_dict;
  1856. m = PyImport_AddModule("__main__");
  1857. if (m == NULL)
  1858. return _PyStatus_ERR("can't create __main__ module");
  1859. d = PyModule_GetDict(m);
  1860. ann_dict = PyDict_New();
  1861. if ((ann_dict == NULL) ||
  1862. (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
  1863. return _PyStatus_ERR("Failed to initialize __main__.__annotations__");
  1864. }
  1865. Py_DECREF(ann_dict);
  1866. if (_PyDict_GetItemStringWithError(d, "__builtins__") == NULL) {
  1867. if (PyErr_Occurred()) {
  1868. return _PyStatus_ERR("Failed to test __main__.__builtins__");
  1869. }
  1870. PyObject *bimod = PyImport_ImportModule("builtins");
  1871. if (bimod == NULL) {
  1872. return _PyStatus_ERR("Failed to retrieve builtins module");
  1873. }
  1874. if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
  1875. return _PyStatus_ERR("Failed to initialize __main__.__builtins__");
  1876. }
  1877. Py_DECREF(bimod);
  1878. }
  1879. /* Main is a little special - BuiltinImporter is the most appropriate
  1880. * initial setting for its __loader__ attribute. A more suitable value
  1881. * will be set if __main__ gets further initialized later in the startup
  1882. * process.
  1883. */
  1884. loader = _PyDict_GetItemStringWithError(d, "__loader__");
  1885. if (loader == NULL || loader == Py_None) {
  1886. if (PyErr_Occurred()) {
  1887. return _PyStatus_ERR("Failed to test __main__.__loader__");
  1888. }
  1889. PyObject *loader = _PyImport_GetImportlibLoader(interp,
  1890. "BuiltinImporter");
  1891. if (loader == NULL) {
  1892. return _PyStatus_ERR("Failed to retrieve BuiltinImporter");
  1893. }
  1894. if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
  1895. return _PyStatus_ERR("Failed to initialize __main__.__loader__");
  1896. }
  1897. Py_DECREF(loader);
  1898. }
  1899. return _PyStatus_OK();
  1900. }
  1901. /* Import the site module (not into __main__ though) */
  1902. static PyStatus
  1903. init_import_site(void)
  1904. {
  1905. PyObject *m;
  1906. m = PyImport_ImportModule("site");
  1907. if (m == NULL) {
  1908. return _PyStatus_ERR("Failed to import the site module");
  1909. }
  1910. Py_DECREF(m);
  1911. return _PyStatus_OK();
  1912. }
  1913. /* Check if a file descriptor is valid or not.
  1914. Return 0 if the file descriptor is invalid, return non-zero otherwise. */
  1915. static int
  1916. is_valid_fd(int fd)
  1917. {
  1918. /* dup() is faster than fstat(): fstat() can require input/output operations,
  1919. whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
  1920. startup. Problem: dup() doesn't check if the file descriptor is valid on
  1921. some platforms.
  1922. fcntl(fd, F_GETFD) is even faster, because it only checks the process table.
  1923. It is preferred over dup() when available, since it cannot fail with the
  1924. "too many open files" error (EMFILE).
  1925. bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
  1926. side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
  1927. EBADF. FreeBSD has similar issue (bpo-32849).
  1928. Only use dup() on Linux where dup() is enough to detect invalid FD
  1929. (bpo-32849).
  1930. */
  1931. if (fd < 0) {
  1932. return 0;
  1933. }
  1934. #if defined(F_GETFD) && ( \
  1935. defined(__linux__) || \
  1936. defined(__APPLE__) || \
  1937. defined(__wasm__))
  1938. return fcntl(fd, F_GETFD) >= 0;
  1939. #elif defined(__linux__)
  1940. int fd2 = dup(fd);
  1941. if (fd2 >= 0) {
  1942. close(fd2);
  1943. }
  1944. return (fd2 >= 0);
  1945. #elif defined(MS_WINDOWS)
  1946. HANDLE hfile;
  1947. _Py_BEGIN_SUPPRESS_IPH
  1948. hfile = (HANDLE)_get_osfhandle(fd);
  1949. _Py_END_SUPPRESS_IPH
  1950. return (hfile != INVALID_HANDLE_VALUE
  1951. && GetFileType(hfile) != FILE_TYPE_UNKNOWN);
  1952. #else
  1953. struct stat st;
  1954. return (fstat(fd, &st) == 0);
  1955. #endif
  1956. }
  1957. /* returns Py_None if the fd is not valid */
  1958. static PyObject*
  1959. create_stdio(const PyConfig *config, PyObject* io,
  1960. int fd, int write_mode, const char* name,
  1961. const wchar_t* encoding, const wchar_t* errors)
  1962. {
  1963. PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
  1964. const char* mode;
  1965. const char* newline;
  1966. PyObject *line_buffering, *write_through;
  1967. int buffering, isatty;
  1968. const int buffered_stdio = config->buffered_stdio;
  1969. if (!is_valid_fd(fd))
  1970. Py_RETURN_NONE;
  1971. /* stdin is always opened in buffered mode, first because it shouldn't
  1972. make a difference in common use cases, second because TextIOWrapper
  1973. depends on the presence of a read1() method which only exists on
  1974. buffered streams.
  1975. */
  1976. if (!buffered_stdio && write_mode)
  1977. buffering = 0;
  1978. else
  1979. buffering = -1;
  1980. if (write_mode)
  1981. mode = "wb";
  1982. else
  1983. mode = "rb";
  1984. buf = _PyObject_CallMethod(io, &_Py_ID(open), "isiOOOO",
  1985. fd, mode, buffering,
  1986. Py_None, Py_None, /* encoding, errors */
  1987. Py_None, Py_False); /* newline, closefd */
  1988. if (buf == NULL)
  1989. goto error;
  1990. if (buffering) {
  1991. raw = PyObject_GetAttr(buf, &_Py_ID(raw));
  1992. if (raw == NULL)
  1993. goto error;
  1994. }
  1995. else {
  1996. raw = Py_NewRef(buf);
  1997. }
  1998. #ifdef HAVE_WINDOWS_CONSOLE_IO
  1999. /* Windows console IO is always UTF-8 encoded */
  2000. PyTypeObject *winconsoleio_type = (PyTypeObject *)_PyImport_GetModuleAttr(
  2001. &_Py_ID(_io), &_Py_ID(_WindowsConsoleIO));
  2002. if (winconsoleio_type == NULL) {
  2003. goto error;
  2004. }
  2005. int is_subclass = PyObject_TypeCheck(raw, winconsoleio_type);
  2006. Py_DECREF(winconsoleio_type);
  2007. if (is_subclass) {
  2008. encoding = L"utf-8";
  2009. }
  2010. #endif
  2011. text = PyUnicode_FromString(name);
  2012. if (text == NULL || PyObject_SetAttr(raw, &_Py_ID(name), text) < 0)
  2013. goto error;
  2014. res = PyObject_CallMethodNoArgs(raw, &_Py_ID(isatty));
  2015. if (res == NULL)
  2016. goto error;
  2017. isatty = PyObject_IsTrue(res);
  2018. Py_DECREF(res);
  2019. if (isatty == -1)
  2020. goto error;
  2021. if (!buffered_stdio)
  2022. write_through = Py_True;
  2023. else
  2024. write_through = Py_False;
  2025. if (buffered_stdio && (isatty || fd == fileno(stderr)))
  2026. line_buffering = Py_True;
  2027. else
  2028. line_buffering = Py_False;
  2029. Py_CLEAR(raw);
  2030. Py_CLEAR(text);
  2031. #ifdef MS_WINDOWS
  2032. /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
  2033. newlines to "\n".
  2034. sys.stdout and sys.stderr: translate "\n" to "\r\n". */
  2035. newline = NULL;
  2036. #else
  2037. /* sys.stdin: split lines at "\n".
  2038. sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
  2039. newline = "\n";
  2040. #endif
  2041. PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
  2042. if (encoding_str == NULL) {
  2043. Py_CLEAR(buf);
  2044. goto error;
  2045. }
  2046. PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
  2047. if (errors_str == NULL) {
  2048. Py_CLEAR(buf);
  2049. Py_CLEAR(encoding_str);
  2050. goto error;
  2051. }
  2052. stream = _PyObject_CallMethod(io, &_Py_ID(TextIOWrapper), "OOOsOO",
  2053. buf, encoding_str, errors_str,
  2054. newline, line_buffering, write_through);
  2055. Py_CLEAR(buf);
  2056. Py_CLEAR(encoding_str);
  2057. Py_CLEAR(errors_str);
  2058. if (stream == NULL)
  2059. goto error;
  2060. if (write_mode)
  2061. mode = "w";
  2062. else
  2063. mode = "r";
  2064. text = PyUnicode_FromString(mode);
  2065. if (!text || PyObject_SetAttr(stream, &_Py_ID(mode), text) < 0)
  2066. goto error;
  2067. Py_CLEAR(text);
  2068. return stream;
  2069. error:
  2070. Py_XDECREF(buf);
  2071. Py_XDECREF(stream);
  2072. Py_XDECREF(text);
  2073. Py_XDECREF(raw);
  2074. if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
  2075. /* Issue #24891: the file descriptor was closed after the first
  2076. is_valid_fd() check was called. Ignore the OSError and set the
  2077. stream to None. */
  2078. PyErr_Clear();
  2079. Py_RETURN_NONE;
  2080. }
  2081. return NULL;
  2082. }
  2083. /* Set builtins.open to io.open */
  2084. static PyStatus
  2085. init_set_builtins_open(void)
  2086. {
  2087. PyObject *wrapper;
  2088. PyObject *bimod = NULL;
  2089. PyStatus res = _PyStatus_OK();
  2090. if (!(bimod = PyImport_ImportModule("builtins"))) {
  2091. goto error;
  2092. }
  2093. if (!(wrapper = _PyImport_GetModuleAttrString("io", "open"))) {
  2094. goto error;
  2095. }
  2096. /* Set builtins.open */
  2097. if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
  2098. Py_DECREF(wrapper);
  2099. goto error;
  2100. }
  2101. Py_DECREF(wrapper);
  2102. goto done;
  2103. error:
  2104. res = _PyStatus_ERR("can't initialize io.open");
  2105. done:
  2106. Py_XDECREF(bimod);
  2107. return res;
  2108. }
  2109. /* Create sys.stdin, sys.stdout and sys.stderr */
  2110. static PyStatus
  2111. init_sys_streams(PyThreadState *tstate)
  2112. {
  2113. PyObject *iomod = NULL;
  2114. PyObject *std = NULL;
  2115. int fd;
  2116. PyObject * encoding_attr;
  2117. PyStatus res = _PyStatus_OK();
  2118. const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
  2119. /* Check that stdin is not a directory
  2120. Using shell redirection, you can redirect stdin to a directory,
  2121. crashing the Python interpreter. Catch this common mistake here
  2122. and output a useful error message. Note that under MS Windows,
  2123. the shell already prevents that. */
  2124. #ifndef MS_WINDOWS
  2125. struct _Py_stat_struct sb;
  2126. if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
  2127. S_ISDIR(sb.st_mode)) {
  2128. return _PyStatus_ERR("<stdin> is a directory, cannot continue");
  2129. }
  2130. #endif
  2131. if (!(iomod = PyImport_ImportModule("io"))) {
  2132. goto error;
  2133. }
  2134. /* Set sys.stdin */
  2135. fd = fileno(stdin);
  2136. /* Under some conditions stdin, stdout and stderr may not be connected
  2137. * and fileno() may point to an invalid file descriptor. For example
  2138. * GUI apps don't have valid standard streams by default.
  2139. */
  2140. std = create_stdio(config, iomod, fd, 0, "<stdin>",
  2141. config->stdio_encoding,
  2142. config->stdio_errors);
  2143. if (std == NULL)
  2144. goto error;
  2145. PySys_SetObject("__stdin__", std);
  2146. _PySys_SetAttr(&_Py_ID(stdin), std);
  2147. Py_DECREF(std);
  2148. /* Set sys.stdout */
  2149. fd = fileno(stdout);
  2150. std = create_stdio(config, iomod, fd, 1, "<stdout>",
  2151. config->stdio_encoding,
  2152. config->stdio_errors);
  2153. if (std == NULL)
  2154. goto error;
  2155. PySys_SetObject("__stdout__", std);
  2156. _PySys_SetAttr(&_Py_ID(stdout), std);
  2157. Py_DECREF(std);
  2158. #if 1 /* Disable this if you have trouble debugging bootstrap stuff */
  2159. /* Set sys.stderr, replaces the preliminary stderr */
  2160. fd = fileno(stderr);
  2161. std = create_stdio(config, iomod, fd, 1, "<stderr>",
  2162. config->stdio_encoding,
  2163. L"backslashreplace");
  2164. if (std == NULL)
  2165. goto error;
  2166. /* Same as hack above, pre-import stderr's codec to avoid recursion
  2167. when import.c tries to write to stderr in verbose mode. */
  2168. encoding_attr = PyObject_GetAttrString(std, "encoding");
  2169. if (encoding_attr != NULL) {
  2170. const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
  2171. if (std_encoding != NULL) {
  2172. PyObject *codec_info = _PyCodec_Lookup(std_encoding);
  2173. Py_XDECREF(codec_info);
  2174. }
  2175. Py_DECREF(encoding_attr);
  2176. }
  2177. _PyErr_Clear(tstate); /* Not a fatal error if codec isn't available */
  2178. if (PySys_SetObject("__stderr__", std) < 0) {
  2179. Py_DECREF(std);
  2180. goto error;
  2181. }
  2182. if (_PySys_SetAttr(&_Py_ID(stderr), std) < 0) {
  2183. Py_DECREF(std);
  2184. goto error;
  2185. }
  2186. Py_DECREF(std);
  2187. #endif
  2188. goto done;
  2189. error:
  2190. res = _PyStatus_ERR("can't initialize sys standard streams");
  2191. done:
  2192. _Py_ClearStandardStreamEncoding();
  2193. Py_XDECREF(iomod);
  2194. return res;
  2195. }
  2196. static void
  2197. _Py_FatalError_DumpTracebacks(int fd, PyInterpreterState *interp,
  2198. PyThreadState *tstate)
  2199. {
  2200. PUTS(fd, "\n");
  2201. /* display the current Python stack */
  2202. _Py_DumpTracebackThreads(fd, interp, tstate);
  2203. }
  2204. /* Print the current exception (if an exception is set) with its traceback,
  2205. or display the current Python stack.
  2206. Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
  2207. called on catastrophic cases.
  2208. Return 1 if the traceback was displayed, 0 otherwise. */
  2209. static int
  2210. _Py_FatalError_PrintExc(PyThreadState *tstate)
  2211. {
  2212. PyObject *exc = _PyErr_GetRaisedException(tstate);
  2213. if (exc == NULL) {
  2214. /* No current exception */
  2215. return 0;
  2216. }
  2217. PyObject *ferr = _PySys_GetAttr(tstate, &_Py_ID(stderr));
  2218. if (ferr == NULL || ferr == Py_None) {
  2219. /* sys.stderr is not set yet or set to None,
  2220. no need to try to display the exception */
  2221. Py_DECREF(exc);
  2222. return 0;
  2223. }
  2224. PyErr_DisplayException(exc);
  2225. PyObject *tb = PyException_GetTraceback(exc);
  2226. int has_tb = (tb != NULL) && (tb != Py_None);
  2227. Py_XDECREF(tb);
  2228. Py_DECREF(exc);
  2229. /* sys.stderr may be buffered: call sys.stderr.flush() */
  2230. PyObject *res = PyObject_CallMethodNoArgs(ferr, &_Py_ID(flush));
  2231. if (res == NULL) {
  2232. _PyErr_Clear(tstate);
  2233. }
  2234. else {
  2235. Py_DECREF(res);
  2236. }
  2237. return has_tb;
  2238. }
  2239. /* Print fatal error message and abort */
  2240. #ifdef MS_WINDOWS
  2241. static void
  2242. fatal_output_debug(const char *msg)
  2243. {
  2244. /* buffer of 256 bytes allocated on the stack */
  2245. WCHAR buffer[256 / sizeof(WCHAR)];
  2246. size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
  2247. size_t msglen;
  2248. OutputDebugStringW(L"Fatal Python error: ");
  2249. msglen = strlen(msg);
  2250. while (msglen) {
  2251. size_t i;
  2252. if (buflen > msglen) {
  2253. buflen = msglen;
  2254. }
  2255. /* Convert the message to wchar_t. This uses a simple one-to-one
  2256. conversion, assuming that the this error message actually uses
  2257. ASCII only. If this ceases to be true, we will have to convert. */
  2258. for (i=0; i < buflen; ++i) {
  2259. buffer[i] = msg[i];
  2260. }
  2261. buffer[i] = L'\0';
  2262. OutputDebugStringW(buffer);
  2263. msg += buflen;
  2264. msglen -= buflen;
  2265. }
  2266. OutputDebugStringW(L"\n");
  2267. }
  2268. #endif
  2269. static void
  2270. fatal_error_dump_runtime(int fd, _PyRuntimeState *runtime)
  2271. {
  2272. PUTS(fd, "Python runtime state: ");
  2273. PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(runtime);
  2274. if (finalizing) {
  2275. PUTS(fd, "finalizing (tstate=0x");
  2276. _Py_DumpHexadecimal(fd, (uintptr_t)finalizing, sizeof(finalizing) * 2);
  2277. PUTS(fd, ")");
  2278. }
  2279. else if (runtime->initialized) {
  2280. PUTS(fd, "initialized");
  2281. }
  2282. else if (runtime->core_initialized) {
  2283. PUTS(fd, "core initialized");
  2284. }
  2285. else if (runtime->preinitialized) {
  2286. PUTS(fd, "preinitialized");
  2287. }
  2288. else if (runtime->preinitializing) {
  2289. PUTS(fd, "preinitializing");
  2290. }
  2291. else {
  2292. PUTS(fd, "unknown");
  2293. }
  2294. PUTS(fd, "\n");
  2295. }
  2296. static inline void _Py_NO_RETURN
  2297. fatal_error_exit(int status)
  2298. {
  2299. if (status < 0) {
  2300. #if defined(MS_WINDOWS) && defined(_DEBUG)
  2301. DebugBreak();
  2302. #endif
  2303. abort();
  2304. }
  2305. else {
  2306. exit(status);
  2307. }
  2308. }
  2309. // Dump the list of extension modules of sys.modules, excluding stdlib modules
  2310. // (sys.stdlib_module_names), into fd file descriptor.
  2311. //
  2312. // This function is called by a signal handler in faulthandler: avoid memory
  2313. // allocations and keep the implementation simple. For example, the list is not
  2314. // sorted on purpose.
  2315. void
  2316. _Py_DumpExtensionModules(int fd, PyInterpreterState *interp)
  2317. {
  2318. if (interp == NULL) {
  2319. return;
  2320. }
  2321. PyObject *modules = _PyImport_GetModules(interp);
  2322. if (modules == NULL || !PyDict_Check(modules)) {
  2323. return;
  2324. }
  2325. Py_ssize_t pos;
  2326. PyObject *key, *value;
  2327. // Avoid PyDict_GetItemString() which calls PyUnicode_FromString(),
  2328. // memory cannot be allocated on the heap in a signal handler.
  2329. // Iterate on the dict instead.
  2330. PyObject *stdlib_module_names = NULL;
  2331. if (interp->sysdict != NULL) {
  2332. pos = 0;
  2333. while (PyDict_Next(interp->sysdict, &pos, &key, &value)) {
  2334. if (PyUnicode_Check(key)
  2335. && PyUnicode_CompareWithASCIIString(key, "stdlib_module_names") == 0) {
  2336. stdlib_module_names = value;
  2337. break;
  2338. }
  2339. }
  2340. }
  2341. // If we failed to get sys.stdlib_module_names or it's not a frozenset,
  2342. // don't exclude stdlib modules.
  2343. if (stdlib_module_names != NULL && !PyFrozenSet_Check(stdlib_module_names)) {
  2344. stdlib_module_names = NULL;
  2345. }
  2346. // List extensions
  2347. int header = 1;
  2348. Py_ssize_t count = 0;
  2349. pos = 0;
  2350. while (PyDict_Next(modules, &pos, &key, &value)) {
  2351. if (!PyUnicode_Check(key)) {
  2352. continue;
  2353. }
  2354. if (!_PyModule_IsExtension(value)) {
  2355. continue;
  2356. }
  2357. // Use the module name from the sys.modules key,
  2358. // don't attempt to get the module object name.
  2359. if (stdlib_module_names != NULL) {
  2360. int is_stdlib_ext = 0;
  2361. Py_ssize_t i = 0;
  2362. PyObject *item;
  2363. Py_hash_t hash;
  2364. while (_PySet_NextEntry(stdlib_module_names, &i, &item, &hash)) {
  2365. if (PyUnicode_Check(item)
  2366. && PyUnicode_Compare(key, item) == 0)
  2367. {
  2368. is_stdlib_ext = 1;
  2369. break;
  2370. }
  2371. }
  2372. if (is_stdlib_ext) {
  2373. // Ignore stdlib extension
  2374. continue;
  2375. }
  2376. }
  2377. if (header) {
  2378. PUTS(fd, "\nExtension modules: ");
  2379. header = 0;
  2380. }
  2381. else {
  2382. PUTS(fd, ", ");
  2383. }
  2384. _Py_DumpASCII(fd, key);
  2385. count++;
  2386. }
  2387. if (count) {
  2388. PUTS(fd, " (total: ");
  2389. _Py_DumpDecimal(fd, count);
  2390. PUTS(fd, ")");
  2391. PUTS(fd, "\n");
  2392. }
  2393. }
  2394. static void _Py_NO_RETURN
  2395. fatal_error(int fd, int header, const char *prefix, const char *msg,
  2396. int status)
  2397. {
  2398. static int reentrant = 0;
  2399. if (reentrant) {
  2400. /* Py_FatalError() caused a second fatal error.
  2401. Example: flush_std_files() raises a recursion error. */
  2402. fatal_error_exit(status);
  2403. }
  2404. reentrant = 1;
  2405. if (header) {
  2406. PUTS(fd, "Fatal Python error: ");
  2407. if (prefix) {
  2408. PUTS(fd, prefix);
  2409. PUTS(fd, ": ");
  2410. }
  2411. if (msg) {
  2412. PUTS(fd, msg);
  2413. }
  2414. else {
  2415. PUTS(fd, "<message not set>");
  2416. }
  2417. PUTS(fd, "\n");
  2418. }
  2419. _PyRuntimeState *runtime = &_PyRuntime;
  2420. fatal_error_dump_runtime(fd, runtime);
  2421. /* Check if the current thread has a Python thread state
  2422. and holds the GIL.
  2423. tss_tstate is NULL if Py_FatalError() is called from a C thread which
  2424. has no Python thread state.
  2425. tss_tstate != tstate if the current Python thread does not hold the GIL.
  2426. */
  2427. PyThreadState *tstate = _PyThreadState_GET();
  2428. PyInterpreterState *interp = NULL;
  2429. PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
  2430. if (tstate != NULL) {
  2431. interp = tstate->interp;
  2432. }
  2433. else if (tss_tstate != NULL) {
  2434. interp = tss_tstate->interp;
  2435. }
  2436. int has_tstate_and_gil = (tss_tstate != NULL && tss_tstate == tstate);
  2437. if (has_tstate_and_gil) {
  2438. /* If an exception is set, print the exception with its traceback */
  2439. if (!_Py_FatalError_PrintExc(tss_tstate)) {
  2440. /* No exception is set, or an exception is set without traceback */
  2441. _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
  2442. }
  2443. }
  2444. else {
  2445. _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
  2446. }
  2447. _Py_DumpExtensionModules(fd, interp);
  2448. /* The main purpose of faulthandler is to display the traceback.
  2449. This function already did its best to display a traceback.
  2450. Disable faulthandler to prevent writing a second traceback
  2451. on abort(). */
  2452. _PyFaulthandler_Fini();
  2453. /* Check if the current Python thread hold the GIL */
  2454. if (has_tstate_and_gil) {
  2455. /* Flush sys.stdout and sys.stderr */
  2456. flush_std_files();
  2457. }
  2458. #ifdef MS_WINDOWS
  2459. fatal_output_debug(msg);
  2460. #endif /* MS_WINDOWS */
  2461. fatal_error_exit(status);
  2462. }
  2463. #undef Py_FatalError
  2464. void _Py_NO_RETURN
  2465. Py_FatalError(const char *msg)
  2466. {
  2467. fatal_error(fileno(stderr), 1, NULL, msg, -1);
  2468. }
  2469. void _Py_NO_RETURN
  2470. _Py_FatalErrorFunc(const char *func, const char *msg)
  2471. {
  2472. fatal_error(fileno(stderr), 1, func, msg, -1);
  2473. }
  2474. void _Py_NO_RETURN
  2475. _Py_FatalErrorFormat(const char *func, const char *format, ...)
  2476. {
  2477. static int reentrant = 0;
  2478. if (reentrant) {
  2479. /* _Py_FatalErrorFormat() caused a second fatal error */
  2480. fatal_error_exit(-1);
  2481. }
  2482. reentrant = 1;
  2483. FILE *stream = stderr;
  2484. const int fd = fileno(stream);
  2485. PUTS(fd, "Fatal Python error: ");
  2486. if (func) {
  2487. PUTS(fd, func);
  2488. PUTS(fd, ": ");
  2489. }
  2490. va_list vargs;
  2491. va_start(vargs, format);
  2492. vfprintf(stream, format, vargs);
  2493. va_end(vargs);
  2494. fputs("\n", stream);
  2495. fflush(stream);
  2496. fatal_error(fd, 0, NULL, NULL, -1);
  2497. }
  2498. void _Py_NO_RETURN
  2499. _Py_FatalRefcountErrorFunc(const char *func, const char *msg)
  2500. {
  2501. _Py_FatalErrorFormat(func,
  2502. "%s: bug likely caused by a refcount error "
  2503. "in a C extension",
  2504. msg);
  2505. }
  2506. void _Py_NO_RETURN
  2507. Py_ExitStatusException(PyStatus status)
  2508. {
  2509. if (_PyStatus_IS_EXIT(status)) {
  2510. exit(status.exitcode);
  2511. }
  2512. else if (_PyStatus_IS_ERROR(status)) {
  2513. fatal_error(fileno(stderr), 1, status.func, status.err_msg, 1);
  2514. }
  2515. else {
  2516. Py_FatalError("Py_ExitStatusException() must not be called on success");
  2517. }
  2518. }
  2519. /* Wait until threading._shutdown completes, provided
  2520. the threading module was imported in the first place.
  2521. The shutdown routine will wait until all non-daemon
  2522. "threading" threads have completed. */
  2523. static void
  2524. wait_for_thread_shutdown(PyThreadState *tstate)
  2525. {
  2526. PyObject *result;
  2527. PyObject *threading = PyImport_GetModule(&_Py_ID(threading));
  2528. if (threading == NULL) {
  2529. if (_PyErr_Occurred(tstate)) {
  2530. PyErr_WriteUnraisable(NULL);
  2531. }
  2532. /* else: threading not imported */
  2533. return;
  2534. }
  2535. result = PyObject_CallMethodNoArgs(threading, &_Py_ID(_shutdown));
  2536. if (result == NULL) {
  2537. PyErr_WriteUnraisable(threading);
  2538. }
  2539. else {
  2540. Py_DECREF(result);
  2541. }
  2542. Py_DECREF(threading);
  2543. }
  2544. int Py_AtExit(void (*func)(void))
  2545. {
  2546. struct _atexit_runtime_state *state = &_PyRuntime.atexit;
  2547. PyThread_acquire_lock(state->mutex, WAIT_LOCK);
  2548. if (state->ncallbacks >= NEXITFUNCS) {
  2549. PyThread_release_lock(state->mutex);
  2550. return -1;
  2551. }
  2552. state->callbacks[state->ncallbacks++] = func;
  2553. PyThread_release_lock(state->mutex);
  2554. return 0;
  2555. }
  2556. static void
  2557. call_ll_exitfuncs(_PyRuntimeState *runtime)
  2558. {
  2559. atexit_callbackfunc exitfunc;
  2560. struct _atexit_runtime_state *state = &runtime->atexit;
  2561. PyThread_acquire_lock(state->mutex, WAIT_LOCK);
  2562. while (state->ncallbacks > 0) {
  2563. /* pop last function from the list */
  2564. state->ncallbacks--;
  2565. exitfunc = state->callbacks[state->ncallbacks];
  2566. state->callbacks[state->ncallbacks] = NULL;
  2567. PyThread_release_lock(state->mutex);
  2568. exitfunc();
  2569. PyThread_acquire_lock(state->mutex, WAIT_LOCK);
  2570. }
  2571. PyThread_release_lock(state->mutex);
  2572. fflush(stdout);
  2573. fflush(stderr);
  2574. }
  2575. void _Py_NO_RETURN
  2576. Py_Exit(int sts)
  2577. {
  2578. if (Py_FinalizeEx() < 0) {
  2579. sts = 120;
  2580. }
  2581. exit(sts);
  2582. }
  2583. /*
  2584. * The file descriptor fd is considered ``interactive'' if either
  2585. * a) isatty(fd) is TRUE, or
  2586. * b) the -i flag was given, and the filename associated with
  2587. * the descriptor is NULL or "<stdin>" or "???".
  2588. */
  2589. int
  2590. Py_FdIsInteractive(FILE *fp, const char *filename)
  2591. {
  2592. if (isatty(fileno(fp))) {
  2593. return 1;
  2594. }
  2595. if (!_Py_GetConfig()->interactive) {
  2596. return 0;
  2597. }
  2598. return ((filename == NULL)
  2599. || (strcmp(filename, "<stdin>") == 0)
  2600. || (strcmp(filename, "???") == 0));
  2601. }
  2602. int
  2603. _Py_FdIsInteractive(FILE *fp, PyObject *filename)
  2604. {
  2605. if (isatty(fileno(fp))) {
  2606. return 1;
  2607. }
  2608. if (!_Py_GetConfig()->interactive) {
  2609. return 0;
  2610. }
  2611. return ((filename == NULL)
  2612. || (PyUnicode_CompareWithASCIIString(filename, "<stdin>") == 0)
  2613. || (PyUnicode_CompareWithASCIIString(filename, "???") == 0));
  2614. }
  2615. /* Wrappers around sigaction() or signal(). */
  2616. PyOS_sighandler_t
  2617. PyOS_getsig(int sig)
  2618. {
  2619. #ifdef HAVE_SIGACTION
  2620. struct sigaction context;
  2621. if (sigaction(sig, NULL, &context) == -1)
  2622. return SIG_ERR;
  2623. return context.sa_handler;
  2624. #else
  2625. PyOS_sighandler_t handler;
  2626. /* Special signal handling for the secure CRT in Visual Studio 2005 */
  2627. #if defined(_MSC_VER) && _MSC_VER >= 1400
  2628. switch (sig) {
  2629. /* Only these signals are valid */
  2630. case SIGINT:
  2631. case SIGILL:
  2632. case SIGFPE:
  2633. case SIGSEGV:
  2634. case SIGTERM:
  2635. case SIGBREAK:
  2636. case SIGABRT:
  2637. break;
  2638. /* Don't call signal() with other values or it will assert */
  2639. default:
  2640. return SIG_ERR;
  2641. }
  2642. #endif /* _MSC_VER && _MSC_VER >= 1400 */
  2643. handler = signal(sig, SIG_IGN);
  2644. if (handler != SIG_ERR)
  2645. signal(sig, handler);
  2646. return handler;
  2647. #endif
  2648. }
  2649. /*
  2650. * All of the code in this function must only use async-signal-safe functions,
  2651. * listed at `man 7 signal` or
  2652. * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
  2653. */
  2654. PyOS_sighandler_t
  2655. PyOS_setsig(int sig, PyOS_sighandler_t handler)
  2656. {
  2657. #ifdef HAVE_SIGACTION
  2658. /* Some code in Modules/signalmodule.c depends on sigaction() being
  2659. * used here if HAVE_SIGACTION is defined. Fix that if this code
  2660. * changes to invalidate that assumption.
  2661. */
  2662. struct sigaction context, ocontext;
  2663. context.sa_handler = handler;
  2664. sigemptyset(&context.sa_mask);
  2665. /* Using SA_ONSTACK is friendlier to other C/C++/Golang-VM code that
  2666. * extension module or embedding code may use where tiny thread stacks
  2667. * are used. https://bugs.python.org/issue43390 */
  2668. context.sa_flags = SA_ONSTACK;
  2669. if (sigaction(sig, &context, &ocontext) == -1)
  2670. return SIG_ERR;
  2671. return ocontext.sa_handler;
  2672. #else
  2673. PyOS_sighandler_t oldhandler;
  2674. oldhandler = signal(sig, handler);
  2675. #ifdef HAVE_SIGINTERRUPT
  2676. siginterrupt(sig, 1);
  2677. #endif
  2678. return oldhandler;
  2679. #endif
  2680. }
  2681. #ifdef __cplusplus
  2682. }
  2683. #endif