pylifecycle.c 89 KB

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