pylifecycle.c 90 KB

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