initconfig.c 90 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180
  1. #include "Python.h"
  2. #include "pycore_fileutils.h" // _Py_HasFileSystemDefaultEncodeErrors
  3. #include "pycore_getopt.h" // _PyOS_GetOpt()
  4. #include "pycore_initconfig.h" // _PyStatus_OK()
  5. #include "pycore_interp.h" // _PyInterpreterState.runtime
  6. #include "pycore_long.h" // _PY_LONG_MAX_STR_DIGITS_THRESHOLD
  7. #include "pycore_pathconfig.h" // _Py_path_config
  8. #include "pycore_pyerrors.h" // _PyErr_GetRaisedException()
  9. #include "pycore_pylifecycle.h" // _Py_PreInitializeFromConfig()
  10. #include "pycore_pymem.h" // _PyMem_SetDefaultAllocator()
  11. #include "pycore_pystate.h" // _PyThreadState_GET()
  12. #include "osdefs.h" // DELIM
  13. #include <locale.h> // setlocale()
  14. #include <stdlib.h> // getenv()
  15. #if defined(MS_WINDOWS) || defined(__CYGWIN__)
  16. # ifdef HAVE_IO_H
  17. # include <io.h>
  18. # endif
  19. # ifdef HAVE_FCNTL_H
  20. # include <fcntl.h> // O_BINARY
  21. # endif
  22. #endif
  23. /* --- Command line options --------------------------------------- */
  24. /* Short usage message (with %s for argv0) */
  25. static const char usage_line[] =
  26. "usage: %ls [option] ... [-c cmd | -m mod | file | -] [arg] ...\n";
  27. /* Long help message */
  28. /* Lines sorted by option name; keep in sync with usage_envvars* below */
  29. static const char usage_help[] = "\
  30. Options (and corresponding environment variables):\n\
  31. -b : issue warnings about converting bytes/bytearray to str and comparing\n\
  32. bytes/bytearray with str or bytes with int. (-bb: issue errors)\n\
  33. -B : don't write .pyc files on import; also PYTHONDONTWRITEBYTECODE=x\n\
  34. -c cmd : program passed in as string (terminates option list)\n\
  35. -d : turn on parser debugging output (for experts only, only works on\n\
  36. debug builds); also PYTHONDEBUG=x\n\
  37. -E : ignore PYTHON* environment variables (such as PYTHONPATH)\n\
  38. -h : print this help message and exit (also -? or --help)\n\
  39. -i : inspect interactively after running script; forces a prompt even\n\
  40. if stdin does not appear to be a terminal; also PYTHONINSPECT=x\n\
  41. -I : isolate Python from the user's environment (implies -E and -s)\n\
  42. -m mod : run library module as a script (terminates option list)\n\
  43. -O : remove assert and __debug__-dependent statements; add .opt-1 before\n\
  44. .pyc extension; also PYTHONOPTIMIZE=x\n\
  45. -OO : do -O changes and also discard docstrings; add .opt-2 before\n\
  46. .pyc extension\n\
  47. -P : don't prepend a potentially unsafe path to sys.path; also\n\
  48. PYTHONSAFEPATH\n\
  49. -q : don't print version and copyright messages on interactive startup\n\
  50. -s : don't add user site directory to sys.path; also PYTHONNOUSERSITE=x\n\
  51. -S : don't imply 'import site' on initialization\n\
  52. -u : force the stdout and stderr streams to be unbuffered;\n\
  53. this option has no effect on stdin; also PYTHONUNBUFFERED=x\n\
  54. -v : verbose (trace import statements); also PYTHONVERBOSE=x\n\
  55. can be supplied multiple times to increase verbosity\n\
  56. -V : print the Python version number and exit (also --version)\n\
  57. when given twice, print more information about the build\n\
  58. -W arg : warning control; arg is action:message:category:module:lineno\n\
  59. also PYTHONWARNINGS=arg\n\
  60. -x : skip first line of source, allowing use of non-Unix forms of #!cmd\n\
  61. -X opt : set implementation-specific option\n\
  62. --check-hash-based-pycs always|default|never:\n\
  63. control how Python invalidates hash-based .pyc files\n\
  64. --help-env: print help about Python environment variables and exit\n\
  65. --help-xoptions: print help about implementation-specific -X options and exit\n\
  66. --help-all: print complete help information and exit\n\
  67. \n\
  68. Arguments:\n\
  69. file : program read from script file\n\
  70. - : program read from stdin (default; interactive mode if a tty)\n\
  71. arg ...: arguments passed to program in sys.argv[1:]\n\
  72. ";
  73. static const char usage_xoptions[] = "\
  74. The following implementation-specific options are available:\n\
  75. -X dev : enable Python Development Mode; also PYTHONDEVMODE\n\
  76. -X faulthandler: dump the Python traceback on fatal errors;\n\
  77. also PYTHONFAULTHANDLER\n\
  78. -X frozen_modules=[on|off]: whether to use frozen modules; the default is \"on\"\n\
  79. for installed Python and \"off\" for a local build\n\
  80. -X importtime: show how long each import takes; also PYTHONPROFILEIMPORTTIME\n\
  81. -X int_max_str_digits=N: limit the size of int<->str conversions;\n\
  82. 0 disables the limit; also PYTHONINTMAXSTRDIGITS\n\
  83. -X no_debug_ranges: don't include extra location information in code objects;\n\
  84. also PYTHONNODEBUGRANGES\n\
  85. -X perf: support the Linux \"perf\" profiler; also PYTHONPERFSUPPORT=1\n\
  86. "
  87. #ifdef Py_DEBUG
  88. "-X presite=MOD: import this module before site; also PYTHON_PRESITE\n"
  89. #endif
  90. "\
  91. -X pycache_prefix=PATH: write .pyc files to a parallel tree instead of to the\n\
  92. code tree; also PYTHONPYCACHEPREFIX\n\
  93. "
  94. #ifdef Py_STATS
  95. "-X pystats: enable pystats collection at startup; also PYTHONSTATS\n"
  96. #endif
  97. "\
  98. -X showrefcount: output the total reference count and number of used\n\
  99. memory blocks when the program finishes or after each statement in\n\
  100. the interactive interpreter; only works on debug builds\n\
  101. -X tracemalloc[=N]: trace Python memory allocations; N sets a traceback limit\n\
  102. of N frames (default: 1); also PYTHONTRACEMALLOC=N\n\
  103. -X utf8[=0|1]: enable (1) or disable (0) UTF-8 mode; also PYTHONUTF8\n\
  104. -X warn_default_encoding: enable opt-in EncodingWarning for 'encoding=None';\n\
  105. also PYTHONWARNDEFAULTENCODING\
  106. ";
  107. /* Envvars that don't have equivalent command-line options are listed first */
  108. static const char usage_envvars[] =
  109. "Environment variables that change behavior:\n"
  110. "PYTHONSTARTUP : file executed on interactive startup (no default)\n"
  111. "PYTHONPATH : '%lc'-separated list of directories prefixed to the\n"
  112. " default module search path. The result is sys.path.\n"
  113. "PYTHONHOME : alternate <prefix> directory (or <prefix>%lc<exec_prefix>).\n"
  114. " The default module search path uses %s.\n"
  115. "PYTHONPLATLIBDIR: override sys.platlibdir\n"
  116. "PYTHONCASEOK : ignore case in 'import' statements (Windows)\n"
  117. "PYTHONIOENCODING: encoding[:errors] used for stdin/stdout/stderr\n"
  118. "PYTHONHASHSEED : if this variable is set to 'random', a random value is used\n"
  119. " to seed the hashes of str and bytes objects. It can also be\n"
  120. " set to an integer in the range [0,4294967295] to get hash\n"
  121. " values with a predictable seed.\n"
  122. "PYTHONMALLOC : set the Python memory allocators and/or install debug hooks\n"
  123. " on Python memory allocators. Use PYTHONMALLOC=debug to\n"
  124. " install debug hooks.\n"
  125. "PYTHONCOERCECLOCALE: if this variable is set to 0, it disables the locale\n"
  126. " coercion behavior. Use PYTHONCOERCECLOCALE=warn to request\n"
  127. " display of locale coercion and locale compatibility warnings\n"
  128. " on stderr.\n"
  129. "PYTHONBREAKPOINT: if this variable is set to 0, it disables the default\n"
  130. " debugger. It can be set to the callable of your debugger of\n"
  131. " choice.\n"
  132. "\n"
  133. "These variables have equivalent command-line options (see --help for details):\n"
  134. "PYTHONDEBUG : enable parser debug mode (-d)\n"
  135. "PYTHONDEVMODE : enable Python Development Mode (-X dev)\n"
  136. "PYTHONDONTWRITEBYTECODE: don't write .pyc files (-B)\n"
  137. "PYTHONFAULTHANDLER: dump the Python traceback on fatal errors (-X faulthandler)\n"
  138. "PYTHONINSPECT : inspect interactively after running script (-i)\n"
  139. "PYTHONINTMAXSTRDIGITS: limit the size of int<->str conversions;\n"
  140. " 0 disables the limit (-X int_max_str_digits=N)\n"
  141. "PYTHONNODEBUGRANGES: don't include extra location information in code objects\n"
  142. " (-X no_debug_ranges)\n"
  143. "PYTHONNOUSERSITE: disable user site directory (-s)\n"
  144. "PYTHONOPTIMIZE : enable level 1 optimizations (-O)\n"
  145. "PYTHONPERFSUPPORT: support the Linux \"perf\" profiler (-X perf)\n"
  146. "PYTHONPROFILEIMPORTTIME: show how long each import takes (-X importtime)\n"
  147. "PYTHONPYCACHEPREFIX: root directory for bytecode cache (pyc) files\n"
  148. " (-X pycache_prefix)\n"
  149. "PYTHONSAFEPATH : don't prepend a potentially unsafe path to sys.path.\n"
  150. "PYTHONTRACEMALLOC: trace Python memory allocations (-X tracemalloc)\n"
  151. "PYTHONUNBUFFERED: disable stdout/stderr buffering (-u)\n"
  152. "PYTHONUTF8 : control the UTF-8 mode (-X utf8)\n"
  153. "PYTHONVERBOSE : trace import statements (-v)\n"
  154. "PYTHONWARNDEFAULTENCODING: enable opt-in EncodingWarning for 'encoding=None'\n"
  155. " (-X warn_default_encoding)\n"
  156. "PYTHONWARNINGS : warning control (-W)\n"
  157. ;
  158. #if defined(MS_WINDOWS)
  159. # define PYTHONHOMEHELP "<prefix>\\python{major}{minor}"
  160. #else
  161. # define PYTHONHOMEHELP "<prefix>/lib/pythonX.X"
  162. #endif
  163. /* --- Global configuration variables ----------------------------- */
  164. /* UTF-8 mode (PEP 540): if equals to 1, use the UTF-8 encoding, and change
  165. stdin and stdout error handler to "surrogateescape". */
  166. int Py_UTF8Mode = 0;
  167. int Py_DebugFlag = 0; /* Needed by parser.c */
  168. int Py_VerboseFlag = 0; /* Needed by import.c */
  169. int Py_QuietFlag = 0; /* Needed by sysmodule.c */
  170. int Py_InteractiveFlag = 0; /* Previously, was used by Py_FdIsInteractive() */
  171. int Py_InspectFlag = 0; /* Needed to determine whether to exit at SystemExit */
  172. int Py_OptimizeFlag = 0; /* Needed by compile.c */
  173. int Py_NoSiteFlag = 0; /* Suppress 'import site' */
  174. int Py_BytesWarningFlag = 0; /* Warn on str(bytes) and str(buffer) */
  175. int Py_FrozenFlag = 1; /* Needed by getpath.c */
  176. int Py_IgnoreEnvironmentFlag = 0; /* e.g. PYTHONPATH, PYTHONHOME */
  177. int Py_DontWriteBytecodeFlag = 0; /* Suppress writing bytecode files (*.pyc) */
  178. int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
  179. int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
  180. int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
  181. int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
  182. #ifdef MS_WINDOWS
  183. int Py_LegacyWindowsFSEncodingFlag = 0; /* Uses mbcs instead of utf-8 */
  184. int Py_LegacyWindowsStdioFlag = 0; /* Uses FileIO instead of WindowsConsoleIO */
  185. #endif
  186. static PyObject *
  187. _Py_GetGlobalVariablesAsDict(void)
  188. {
  189. _Py_COMP_DIAG_PUSH
  190. _Py_COMP_DIAG_IGNORE_DEPR_DECLS
  191. PyObject *dict, *obj;
  192. dict = PyDict_New();
  193. if (dict == NULL) {
  194. return NULL;
  195. }
  196. #define SET_ITEM(KEY, EXPR) \
  197. do { \
  198. obj = (EXPR); \
  199. if (obj == NULL) { \
  200. return NULL; \
  201. } \
  202. int res = PyDict_SetItemString(dict, (KEY), obj); \
  203. Py_DECREF(obj); \
  204. if (res < 0) { \
  205. goto fail; \
  206. } \
  207. } while (0)
  208. #define SET_ITEM_INT(VAR) \
  209. SET_ITEM(#VAR, PyLong_FromLong(VAR))
  210. #define FROM_STRING(STR) \
  211. ((STR != NULL) ? \
  212. PyUnicode_FromString(STR) \
  213. : Py_NewRef(Py_None))
  214. #define SET_ITEM_STR(VAR) \
  215. SET_ITEM(#VAR, FROM_STRING(VAR))
  216. SET_ITEM_STR(Py_FileSystemDefaultEncoding);
  217. SET_ITEM_INT(Py_HasFileSystemDefaultEncoding);
  218. SET_ITEM_STR(Py_FileSystemDefaultEncodeErrors);
  219. SET_ITEM_INT(_Py_HasFileSystemDefaultEncodeErrors);
  220. SET_ITEM_INT(Py_UTF8Mode);
  221. SET_ITEM_INT(Py_DebugFlag);
  222. SET_ITEM_INT(Py_VerboseFlag);
  223. SET_ITEM_INT(Py_QuietFlag);
  224. SET_ITEM_INT(Py_InteractiveFlag);
  225. SET_ITEM_INT(Py_InspectFlag);
  226. SET_ITEM_INT(Py_OptimizeFlag);
  227. SET_ITEM_INT(Py_NoSiteFlag);
  228. SET_ITEM_INT(Py_BytesWarningFlag);
  229. SET_ITEM_INT(Py_FrozenFlag);
  230. SET_ITEM_INT(Py_IgnoreEnvironmentFlag);
  231. SET_ITEM_INT(Py_DontWriteBytecodeFlag);
  232. SET_ITEM_INT(Py_NoUserSiteDirectory);
  233. SET_ITEM_INT(Py_UnbufferedStdioFlag);
  234. SET_ITEM_INT(Py_HashRandomizationFlag);
  235. SET_ITEM_INT(Py_IsolatedFlag);
  236. #ifdef MS_WINDOWS
  237. SET_ITEM_INT(Py_LegacyWindowsFSEncodingFlag);
  238. SET_ITEM_INT(Py_LegacyWindowsStdioFlag);
  239. #endif
  240. return dict;
  241. fail:
  242. Py_DECREF(dict);
  243. return NULL;
  244. #undef FROM_STRING
  245. #undef SET_ITEM
  246. #undef SET_ITEM_INT
  247. #undef SET_ITEM_STR
  248. _Py_COMP_DIAG_POP
  249. }
  250. char*
  251. Py_GETENV(const char *name)
  252. {
  253. _Py_COMP_DIAG_PUSH
  254. _Py_COMP_DIAG_IGNORE_DEPR_DECLS
  255. if (Py_IgnoreEnvironmentFlag) {
  256. return NULL;
  257. }
  258. return getenv(name);
  259. _Py_COMP_DIAG_POP
  260. }
  261. /* --- PyStatus ----------------------------------------------- */
  262. PyStatus PyStatus_Ok(void)
  263. { return _PyStatus_OK(); }
  264. PyStatus PyStatus_Error(const char *err_msg)
  265. {
  266. assert(err_msg != NULL);
  267. return (PyStatus){._type = _PyStatus_TYPE_ERROR,
  268. .err_msg = err_msg};
  269. }
  270. PyStatus PyStatus_NoMemory(void)
  271. { return PyStatus_Error("memory allocation failed"); }
  272. PyStatus PyStatus_Exit(int exitcode)
  273. { return _PyStatus_EXIT(exitcode); }
  274. int PyStatus_IsError(PyStatus status)
  275. { return _PyStatus_IS_ERROR(status); }
  276. int PyStatus_IsExit(PyStatus status)
  277. { return _PyStatus_IS_EXIT(status); }
  278. int PyStatus_Exception(PyStatus status)
  279. { return _PyStatus_EXCEPTION(status); }
  280. PyObject*
  281. _PyErr_SetFromPyStatus(PyStatus status)
  282. {
  283. if (!_PyStatus_IS_ERROR(status)) {
  284. PyErr_Format(PyExc_SystemError,
  285. "%s() expects an error PyStatus",
  286. _PyStatus_GET_FUNC());
  287. }
  288. else if (status.func) {
  289. PyErr_Format(PyExc_ValueError, "%s: %s", status.func, status.err_msg);
  290. }
  291. else {
  292. PyErr_Format(PyExc_ValueError, "%s", status.err_msg);
  293. }
  294. return NULL;
  295. }
  296. /* --- PyWideStringList ------------------------------------------------ */
  297. #ifndef NDEBUG
  298. int
  299. _PyWideStringList_CheckConsistency(const PyWideStringList *list)
  300. {
  301. assert(list->length >= 0);
  302. if (list->length != 0) {
  303. assert(list->items != NULL);
  304. }
  305. for (Py_ssize_t i = 0; i < list->length; i++) {
  306. assert(list->items[i] != NULL);
  307. }
  308. return 1;
  309. }
  310. #endif /* Py_DEBUG */
  311. void
  312. _PyWideStringList_Clear(PyWideStringList *list)
  313. {
  314. assert(_PyWideStringList_CheckConsistency(list));
  315. for (Py_ssize_t i=0; i < list->length; i++) {
  316. PyMem_RawFree(list->items[i]);
  317. }
  318. PyMem_RawFree(list->items);
  319. list->length = 0;
  320. list->items = NULL;
  321. }
  322. int
  323. _PyWideStringList_Copy(PyWideStringList *list, const PyWideStringList *list2)
  324. {
  325. assert(_PyWideStringList_CheckConsistency(list));
  326. assert(_PyWideStringList_CheckConsistency(list2));
  327. if (list2->length == 0) {
  328. _PyWideStringList_Clear(list);
  329. return 0;
  330. }
  331. PyWideStringList copy = _PyWideStringList_INIT;
  332. size_t size = list2->length * sizeof(list2->items[0]);
  333. copy.items = PyMem_RawMalloc(size);
  334. if (copy.items == NULL) {
  335. return -1;
  336. }
  337. for (Py_ssize_t i=0; i < list2->length; i++) {
  338. wchar_t *item = _PyMem_RawWcsdup(list2->items[i]);
  339. if (item == NULL) {
  340. _PyWideStringList_Clear(&copy);
  341. return -1;
  342. }
  343. copy.items[i] = item;
  344. copy.length = i + 1;
  345. }
  346. _PyWideStringList_Clear(list);
  347. *list = copy;
  348. return 0;
  349. }
  350. PyStatus
  351. PyWideStringList_Insert(PyWideStringList *list,
  352. Py_ssize_t index, const wchar_t *item)
  353. {
  354. Py_ssize_t len = list->length;
  355. if (len == PY_SSIZE_T_MAX) {
  356. /* length+1 would overflow */
  357. return _PyStatus_NO_MEMORY();
  358. }
  359. if (index < 0) {
  360. return _PyStatus_ERR("PyWideStringList_Insert index must be >= 0");
  361. }
  362. if (index > len) {
  363. index = len;
  364. }
  365. wchar_t *item2 = _PyMem_RawWcsdup(item);
  366. if (item2 == NULL) {
  367. return _PyStatus_NO_MEMORY();
  368. }
  369. size_t size = (len + 1) * sizeof(list->items[0]);
  370. wchar_t **items2 = (wchar_t **)PyMem_RawRealloc(list->items, size);
  371. if (items2 == NULL) {
  372. PyMem_RawFree(item2);
  373. return _PyStatus_NO_MEMORY();
  374. }
  375. if (index < len) {
  376. memmove(&items2[index + 1],
  377. &items2[index],
  378. (len - index) * sizeof(items2[0]));
  379. }
  380. items2[index] = item2;
  381. list->items = items2;
  382. list->length++;
  383. return _PyStatus_OK();
  384. }
  385. PyStatus
  386. PyWideStringList_Append(PyWideStringList *list, const wchar_t *item)
  387. {
  388. return PyWideStringList_Insert(list, list->length, item);
  389. }
  390. PyStatus
  391. _PyWideStringList_Extend(PyWideStringList *list, const PyWideStringList *list2)
  392. {
  393. for (Py_ssize_t i = 0; i < list2->length; i++) {
  394. PyStatus status = PyWideStringList_Append(list, list2->items[i]);
  395. if (_PyStatus_EXCEPTION(status)) {
  396. return status;
  397. }
  398. }
  399. return _PyStatus_OK();
  400. }
  401. static int
  402. _PyWideStringList_Find(PyWideStringList *list, const wchar_t *item)
  403. {
  404. for (Py_ssize_t i = 0; i < list->length; i++) {
  405. if (wcscmp(list->items[i], item) == 0) {
  406. return 1;
  407. }
  408. }
  409. return 0;
  410. }
  411. PyObject*
  412. _PyWideStringList_AsList(const PyWideStringList *list)
  413. {
  414. assert(_PyWideStringList_CheckConsistency(list));
  415. PyObject *pylist = PyList_New(list->length);
  416. if (pylist == NULL) {
  417. return NULL;
  418. }
  419. for (Py_ssize_t i = 0; i < list->length; i++) {
  420. PyObject *item = PyUnicode_FromWideChar(list->items[i], -1);
  421. if (item == NULL) {
  422. Py_DECREF(pylist);
  423. return NULL;
  424. }
  425. PyList_SET_ITEM(pylist, i, item);
  426. }
  427. return pylist;
  428. }
  429. /* --- Py_SetStandardStreamEncoding() ----------------------------- */
  430. /* Helper to allow an embedding application to override the normal
  431. * mechanism that attempts to figure out an appropriate IO encoding
  432. */
  433. static char *_Py_StandardStreamEncoding = NULL;
  434. static char *_Py_StandardStreamErrors = NULL;
  435. int
  436. Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
  437. {
  438. if (Py_IsInitialized()) {
  439. /* This is too late to have any effect */
  440. return -1;
  441. }
  442. int res = 0;
  443. /* Py_SetStandardStreamEncoding() can be called before Py_Initialize(),
  444. but Py_Initialize() can change the allocator. Use a known allocator
  445. to be able to release the memory later. */
  446. PyMemAllocatorEx old_alloc;
  447. _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  448. /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
  449. * initialised yet.
  450. *
  451. * However, the raw memory allocators are initialised appropriately
  452. * as C static variables, so _PyMem_RawStrdup is OK even though
  453. * Py_Initialize hasn't been called yet.
  454. */
  455. if (encoding) {
  456. PyMem_RawFree(_Py_StandardStreamEncoding);
  457. _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
  458. if (!_Py_StandardStreamEncoding) {
  459. res = -2;
  460. goto done;
  461. }
  462. }
  463. if (errors) {
  464. PyMem_RawFree(_Py_StandardStreamErrors);
  465. _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
  466. if (!_Py_StandardStreamErrors) {
  467. PyMem_RawFree(_Py_StandardStreamEncoding);
  468. _Py_StandardStreamEncoding = NULL;
  469. res = -3;
  470. goto done;
  471. }
  472. }
  473. #ifdef MS_WINDOWS
  474. if (_Py_StandardStreamEncoding) {
  475. _Py_COMP_DIAG_PUSH
  476. _Py_COMP_DIAG_IGNORE_DEPR_DECLS
  477. /* Overriding the stream encoding implies legacy streams */
  478. Py_LegacyWindowsStdioFlag = 1;
  479. _Py_COMP_DIAG_POP
  480. }
  481. #endif
  482. done:
  483. PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  484. return res;
  485. }
  486. void
  487. _Py_ClearStandardStreamEncoding(void)
  488. {
  489. /* Use the same allocator than Py_SetStandardStreamEncoding() */
  490. PyMemAllocatorEx old_alloc;
  491. _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  492. /* We won't need them anymore. */
  493. if (_Py_StandardStreamEncoding) {
  494. PyMem_RawFree(_Py_StandardStreamEncoding);
  495. _Py_StandardStreamEncoding = NULL;
  496. }
  497. if (_Py_StandardStreamErrors) {
  498. PyMem_RawFree(_Py_StandardStreamErrors);
  499. _Py_StandardStreamErrors = NULL;
  500. }
  501. PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  502. }
  503. /* --- Py_GetArgcArgv() ------------------------------------------- */
  504. void
  505. _Py_ClearArgcArgv(void)
  506. {
  507. PyMemAllocatorEx old_alloc;
  508. _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  509. _PyWideStringList_Clear(&_PyRuntime.orig_argv);
  510. PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  511. }
  512. static int
  513. _Py_SetArgcArgv(Py_ssize_t argc, wchar_t * const *argv)
  514. {
  515. const PyWideStringList argv_list = {.length = argc, .items = (wchar_t **)argv};
  516. int res;
  517. PyMemAllocatorEx old_alloc;
  518. _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  519. // XXX _PyRuntime.orig_argv only gets cleared by Py_Main(),
  520. // so it it currently leaks for embedders.
  521. res = _PyWideStringList_Copy(&_PyRuntime.orig_argv, &argv_list);
  522. PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  523. return res;
  524. }
  525. // _PyConfig_Write() calls _Py_SetArgcArgv() with PyConfig.orig_argv.
  526. void
  527. Py_GetArgcArgv(int *argc, wchar_t ***argv)
  528. {
  529. *argc = (int)_PyRuntime.orig_argv.length;
  530. *argv = _PyRuntime.orig_argv.items;
  531. }
  532. /* --- PyConfig ---------------------------------------------- */
  533. #define MAX_HASH_SEED 4294967295UL
  534. #ifndef NDEBUG
  535. static int
  536. config_check_consistency(const PyConfig *config)
  537. {
  538. /* Check config consistency */
  539. assert(config->isolated >= 0);
  540. assert(config->use_environment >= 0);
  541. assert(config->dev_mode >= 0);
  542. assert(config->install_signal_handlers >= 0);
  543. assert(config->use_hash_seed >= 0);
  544. assert(config->hash_seed <= MAX_HASH_SEED);
  545. assert(config->faulthandler >= 0);
  546. assert(config->tracemalloc >= 0);
  547. assert(config->import_time >= 0);
  548. assert(config->code_debug_ranges >= 0);
  549. assert(config->show_ref_count >= 0);
  550. assert(config->dump_refs >= 0);
  551. assert(config->malloc_stats >= 0);
  552. assert(config->site_import >= 0);
  553. assert(config->bytes_warning >= 0);
  554. assert(config->warn_default_encoding >= 0);
  555. assert(config->inspect >= 0);
  556. assert(config->interactive >= 0);
  557. assert(config->optimization_level >= 0);
  558. assert(config->parser_debug >= 0);
  559. assert(config->write_bytecode >= 0);
  560. assert(config->verbose >= 0);
  561. assert(config->quiet >= 0);
  562. assert(config->user_site_directory >= 0);
  563. assert(config->parse_argv >= 0);
  564. assert(config->configure_c_stdio >= 0);
  565. assert(config->buffered_stdio >= 0);
  566. assert(_PyWideStringList_CheckConsistency(&config->orig_argv));
  567. assert(_PyWideStringList_CheckConsistency(&config->argv));
  568. /* sys.argv must be non-empty: empty argv is replaced with [''] */
  569. assert(config->argv.length >= 1);
  570. assert(_PyWideStringList_CheckConsistency(&config->xoptions));
  571. assert(_PyWideStringList_CheckConsistency(&config->warnoptions));
  572. assert(_PyWideStringList_CheckConsistency(&config->module_search_paths));
  573. assert(config->module_search_paths_set >= 0);
  574. assert(config->filesystem_encoding != NULL);
  575. assert(config->filesystem_errors != NULL);
  576. assert(config->stdio_encoding != NULL);
  577. assert(config->stdio_errors != NULL);
  578. #ifdef MS_WINDOWS
  579. assert(config->legacy_windows_stdio >= 0);
  580. #endif
  581. /* -c and -m options are exclusive */
  582. assert(!(config->run_command != NULL && config->run_module != NULL));
  583. assert(config->check_hash_pycs_mode != NULL);
  584. assert(config->_install_importlib >= 0);
  585. assert(config->pathconfig_warnings >= 0);
  586. assert(config->_is_python_build >= 0);
  587. assert(config->safe_path >= 0);
  588. assert(config->int_max_str_digits >= 0);
  589. // config->use_frozen_modules is initialized later
  590. // by _PyConfig_InitImportConfig().
  591. return 1;
  592. }
  593. #endif
  594. /* Free memory allocated in config, but don't clear all attributes */
  595. void
  596. PyConfig_Clear(PyConfig *config)
  597. {
  598. #define CLEAR(ATTR) \
  599. do { \
  600. PyMem_RawFree(ATTR); \
  601. ATTR = NULL; \
  602. } while (0)
  603. CLEAR(config->pycache_prefix);
  604. CLEAR(config->pythonpath_env);
  605. CLEAR(config->home);
  606. CLEAR(config->program_name);
  607. _PyWideStringList_Clear(&config->argv);
  608. _PyWideStringList_Clear(&config->warnoptions);
  609. _PyWideStringList_Clear(&config->xoptions);
  610. _PyWideStringList_Clear(&config->module_search_paths);
  611. config->module_search_paths_set = 0;
  612. CLEAR(config->stdlib_dir);
  613. CLEAR(config->executable);
  614. CLEAR(config->base_executable);
  615. CLEAR(config->prefix);
  616. CLEAR(config->base_prefix);
  617. CLEAR(config->exec_prefix);
  618. CLEAR(config->base_exec_prefix);
  619. CLEAR(config->platlibdir);
  620. CLEAR(config->filesystem_encoding);
  621. CLEAR(config->filesystem_errors);
  622. CLEAR(config->stdio_encoding);
  623. CLEAR(config->stdio_errors);
  624. CLEAR(config->run_command);
  625. CLEAR(config->run_module);
  626. CLEAR(config->run_filename);
  627. CLEAR(config->check_hash_pycs_mode);
  628. _PyWideStringList_Clear(&config->orig_argv);
  629. #undef CLEAR
  630. }
  631. void
  632. _PyConfig_InitCompatConfig(PyConfig *config)
  633. {
  634. memset(config, 0, sizeof(*config));
  635. config->_config_init = (int)_PyConfig_INIT_COMPAT;
  636. config->isolated = -1;
  637. config->use_environment = -1;
  638. config->dev_mode = -1;
  639. config->install_signal_handlers = 1;
  640. config->use_hash_seed = -1;
  641. config->faulthandler = -1;
  642. config->tracemalloc = -1;
  643. config->perf_profiling = -1;
  644. config->module_search_paths_set = 0;
  645. config->parse_argv = 0;
  646. config->site_import = -1;
  647. config->bytes_warning = -1;
  648. config->warn_default_encoding = 0;
  649. config->inspect = -1;
  650. config->interactive = -1;
  651. config->optimization_level = -1;
  652. config->parser_debug= -1;
  653. config->write_bytecode = -1;
  654. config->verbose = -1;
  655. config->quiet = -1;
  656. config->user_site_directory = -1;
  657. config->configure_c_stdio = 0;
  658. config->buffered_stdio = -1;
  659. config->_install_importlib = 1;
  660. config->check_hash_pycs_mode = NULL;
  661. config->pathconfig_warnings = -1;
  662. config->_init_main = 1;
  663. #ifdef MS_WINDOWS
  664. config->legacy_windows_stdio = -1;
  665. #endif
  666. #ifdef Py_DEBUG
  667. config->use_frozen_modules = 0;
  668. #else
  669. config->use_frozen_modules = 1;
  670. #endif
  671. config->safe_path = 0;
  672. config->int_max_str_digits = -1;
  673. config->_is_python_build = 0;
  674. config->code_debug_ranges = 1;
  675. }
  676. static void
  677. config_init_defaults(PyConfig *config)
  678. {
  679. _PyConfig_InitCompatConfig(config);
  680. config->isolated = 0;
  681. config->use_environment = 1;
  682. config->site_import = 1;
  683. config->bytes_warning = 0;
  684. config->inspect = 0;
  685. config->interactive = 0;
  686. config->optimization_level = 0;
  687. config->parser_debug= 0;
  688. config->write_bytecode = 1;
  689. config->verbose = 0;
  690. config->quiet = 0;
  691. config->user_site_directory = 1;
  692. config->buffered_stdio = 1;
  693. config->pathconfig_warnings = 1;
  694. #ifdef MS_WINDOWS
  695. config->legacy_windows_stdio = 0;
  696. #endif
  697. }
  698. void
  699. PyConfig_InitPythonConfig(PyConfig *config)
  700. {
  701. config_init_defaults(config);
  702. config->_config_init = (int)_PyConfig_INIT_PYTHON;
  703. config->configure_c_stdio = 1;
  704. config->parse_argv = 1;
  705. }
  706. void
  707. PyConfig_InitIsolatedConfig(PyConfig *config)
  708. {
  709. config_init_defaults(config);
  710. config->_config_init = (int)_PyConfig_INIT_ISOLATED;
  711. config->isolated = 1;
  712. config->use_environment = 0;
  713. config->user_site_directory = 0;
  714. config->dev_mode = 0;
  715. config->install_signal_handlers = 0;
  716. config->use_hash_seed = 0;
  717. config->faulthandler = 0;
  718. config->tracemalloc = 0;
  719. config->perf_profiling = 0;
  720. config->int_max_str_digits = _PY_LONG_DEFAULT_MAX_STR_DIGITS;
  721. config->safe_path = 1;
  722. config->pathconfig_warnings = 0;
  723. #ifdef MS_WINDOWS
  724. config->legacy_windows_stdio = 0;
  725. #endif
  726. }
  727. /* Copy str into *config_str (duplicate the string) */
  728. PyStatus
  729. PyConfig_SetString(PyConfig *config, wchar_t **config_str, const wchar_t *str)
  730. {
  731. PyStatus status = _Py_PreInitializeFromConfig(config, NULL);
  732. if (_PyStatus_EXCEPTION(status)) {
  733. return status;
  734. }
  735. wchar_t *str2;
  736. if (str != NULL) {
  737. str2 = _PyMem_RawWcsdup(str);
  738. if (str2 == NULL) {
  739. return _PyStatus_NO_MEMORY();
  740. }
  741. }
  742. else {
  743. str2 = NULL;
  744. }
  745. PyMem_RawFree(*config_str);
  746. *config_str = str2;
  747. return _PyStatus_OK();
  748. }
  749. static PyStatus
  750. config_set_bytes_string(PyConfig *config, wchar_t **config_str,
  751. const char *str, const char *decode_err_msg)
  752. {
  753. PyStatus status = _Py_PreInitializeFromConfig(config, NULL);
  754. if (_PyStatus_EXCEPTION(status)) {
  755. return status;
  756. }
  757. wchar_t *str2;
  758. if (str != NULL) {
  759. size_t len;
  760. str2 = Py_DecodeLocale(str, &len);
  761. if (str2 == NULL) {
  762. if (len == (size_t)-2) {
  763. return _PyStatus_ERR(decode_err_msg);
  764. }
  765. else {
  766. return _PyStatus_NO_MEMORY();
  767. }
  768. }
  769. }
  770. else {
  771. str2 = NULL;
  772. }
  773. PyMem_RawFree(*config_str);
  774. *config_str = str2;
  775. return _PyStatus_OK();
  776. }
  777. #define CONFIG_SET_BYTES_STR(config, config_str, str, NAME) \
  778. config_set_bytes_string(config, config_str, str, "cannot decode " NAME)
  779. /* Decode str using Py_DecodeLocale() and set the result into *config_str.
  780. Pre-initialize Python if needed to ensure that encodings are properly
  781. configured. */
  782. PyStatus
  783. PyConfig_SetBytesString(PyConfig *config, wchar_t **config_str,
  784. const char *str)
  785. {
  786. return CONFIG_SET_BYTES_STR(config, config_str, str, "string");
  787. }
  788. PyStatus
  789. _PyConfig_Copy(PyConfig *config, const PyConfig *config2)
  790. {
  791. PyStatus status;
  792. PyConfig_Clear(config);
  793. #define COPY_ATTR(ATTR) config->ATTR = config2->ATTR
  794. #define COPY_WSTR_ATTR(ATTR) \
  795. do { \
  796. status = PyConfig_SetString(config, &config->ATTR, config2->ATTR); \
  797. if (_PyStatus_EXCEPTION(status)) { \
  798. return status; \
  799. } \
  800. } while (0)
  801. #define COPY_WSTRLIST(LIST) \
  802. do { \
  803. if (_PyWideStringList_Copy(&config->LIST, &config2->LIST) < 0) { \
  804. return _PyStatus_NO_MEMORY(); \
  805. } \
  806. } while (0)
  807. COPY_ATTR(_config_init);
  808. COPY_ATTR(isolated);
  809. COPY_ATTR(use_environment);
  810. COPY_ATTR(dev_mode);
  811. COPY_ATTR(install_signal_handlers);
  812. COPY_ATTR(use_hash_seed);
  813. COPY_ATTR(hash_seed);
  814. COPY_ATTR(_install_importlib);
  815. COPY_ATTR(faulthandler);
  816. COPY_ATTR(tracemalloc);
  817. COPY_ATTR(perf_profiling);
  818. COPY_ATTR(import_time);
  819. COPY_ATTR(code_debug_ranges);
  820. COPY_ATTR(show_ref_count);
  821. COPY_ATTR(dump_refs);
  822. COPY_ATTR(dump_refs_file);
  823. COPY_ATTR(malloc_stats);
  824. COPY_WSTR_ATTR(pycache_prefix);
  825. COPY_WSTR_ATTR(pythonpath_env);
  826. COPY_WSTR_ATTR(home);
  827. COPY_WSTR_ATTR(program_name);
  828. COPY_ATTR(parse_argv);
  829. COPY_WSTRLIST(argv);
  830. COPY_WSTRLIST(warnoptions);
  831. COPY_WSTRLIST(xoptions);
  832. COPY_WSTRLIST(module_search_paths);
  833. COPY_ATTR(module_search_paths_set);
  834. COPY_WSTR_ATTR(stdlib_dir);
  835. COPY_WSTR_ATTR(executable);
  836. COPY_WSTR_ATTR(base_executable);
  837. COPY_WSTR_ATTR(prefix);
  838. COPY_WSTR_ATTR(base_prefix);
  839. COPY_WSTR_ATTR(exec_prefix);
  840. COPY_WSTR_ATTR(base_exec_prefix);
  841. COPY_WSTR_ATTR(platlibdir);
  842. COPY_ATTR(site_import);
  843. COPY_ATTR(bytes_warning);
  844. COPY_ATTR(warn_default_encoding);
  845. COPY_ATTR(inspect);
  846. COPY_ATTR(interactive);
  847. COPY_ATTR(optimization_level);
  848. COPY_ATTR(parser_debug);
  849. COPY_ATTR(write_bytecode);
  850. COPY_ATTR(verbose);
  851. COPY_ATTR(quiet);
  852. COPY_ATTR(user_site_directory);
  853. COPY_ATTR(configure_c_stdio);
  854. COPY_ATTR(buffered_stdio);
  855. COPY_WSTR_ATTR(filesystem_encoding);
  856. COPY_WSTR_ATTR(filesystem_errors);
  857. COPY_WSTR_ATTR(stdio_encoding);
  858. COPY_WSTR_ATTR(stdio_errors);
  859. #ifdef MS_WINDOWS
  860. COPY_ATTR(legacy_windows_stdio);
  861. #endif
  862. COPY_ATTR(skip_source_first_line);
  863. COPY_WSTR_ATTR(run_command);
  864. COPY_WSTR_ATTR(run_module);
  865. COPY_WSTR_ATTR(run_filename);
  866. COPY_WSTR_ATTR(check_hash_pycs_mode);
  867. COPY_ATTR(pathconfig_warnings);
  868. COPY_ATTR(_init_main);
  869. COPY_ATTR(use_frozen_modules);
  870. COPY_ATTR(safe_path);
  871. COPY_WSTRLIST(orig_argv);
  872. COPY_ATTR(_is_python_build);
  873. COPY_ATTR(int_max_str_digits);
  874. #undef COPY_ATTR
  875. #undef COPY_WSTR_ATTR
  876. #undef COPY_WSTRLIST
  877. return _PyStatus_OK();
  878. }
  879. PyObject *
  880. _PyConfig_AsDict(const PyConfig *config)
  881. {
  882. PyObject *dict = PyDict_New();
  883. if (dict == NULL) {
  884. return NULL;
  885. }
  886. #define SET_ITEM(KEY, EXPR) \
  887. do { \
  888. PyObject *obj = (EXPR); \
  889. if (obj == NULL) { \
  890. goto fail; \
  891. } \
  892. int res = PyDict_SetItemString(dict, (KEY), obj); \
  893. Py_DECREF(obj); \
  894. if (res < 0) { \
  895. goto fail; \
  896. } \
  897. } while (0)
  898. #define SET_ITEM_INT(ATTR) \
  899. SET_ITEM(#ATTR, PyLong_FromLong(config->ATTR))
  900. #define SET_ITEM_UINT(ATTR) \
  901. SET_ITEM(#ATTR, PyLong_FromUnsignedLong(config->ATTR))
  902. #define FROM_WSTRING(STR) \
  903. ((STR != NULL) ? \
  904. PyUnicode_FromWideChar(STR, -1) \
  905. : Py_NewRef(Py_None))
  906. #define SET_ITEM_WSTR(ATTR) \
  907. SET_ITEM(#ATTR, FROM_WSTRING(config->ATTR))
  908. #define SET_ITEM_WSTRLIST(LIST) \
  909. SET_ITEM(#LIST, _PyWideStringList_AsList(&config->LIST))
  910. SET_ITEM_INT(_config_init);
  911. SET_ITEM_INT(isolated);
  912. SET_ITEM_INT(use_environment);
  913. SET_ITEM_INT(dev_mode);
  914. SET_ITEM_INT(install_signal_handlers);
  915. SET_ITEM_INT(use_hash_seed);
  916. SET_ITEM_UINT(hash_seed);
  917. SET_ITEM_INT(faulthandler);
  918. SET_ITEM_INT(tracemalloc);
  919. SET_ITEM_INT(perf_profiling);
  920. SET_ITEM_INT(import_time);
  921. SET_ITEM_INT(code_debug_ranges);
  922. SET_ITEM_INT(show_ref_count);
  923. SET_ITEM_INT(dump_refs);
  924. SET_ITEM_INT(malloc_stats);
  925. SET_ITEM_WSTR(filesystem_encoding);
  926. SET_ITEM_WSTR(filesystem_errors);
  927. SET_ITEM_WSTR(pycache_prefix);
  928. SET_ITEM_WSTR(program_name);
  929. SET_ITEM_INT(parse_argv);
  930. SET_ITEM_WSTRLIST(argv);
  931. SET_ITEM_WSTRLIST(xoptions);
  932. SET_ITEM_WSTRLIST(warnoptions);
  933. SET_ITEM_WSTR(pythonpath_env);
  934. SET_ITEM_WSTR(home);
  935. SET_ITEM_INT(module_search_paths_set);
  936. SET_ITEM_WSTRLIST(module_search_paths);
  937. SET_ITEM_WSTR(stdlib_dir);
  938. SET_ITEM_WSTR(executable);
  939. SET_ITEM_WSTR(base_executable);
  940. SET_ITEM_WSTR(prefix);
  941. SET_ITEM_WSTR(base_prefix);
  942. SET_ITEM_WSTR(exec_prefix);
  943. SET_ITEM_WSTR(base_exec_prefix);
  944. SET_ITEM_WSTR(platlibdir);
  945. SET_ITEM_INT(site_import);
  946. SET_ITEM_INT(bytes_warning);
  947. SET_ITEM_INT(warn_default_encoding);
  948. SET_ITEM_INT(inspect);
  949. SET_ITEM_INT(interactive);
  950. SET_ITEM_INT(optimization_level);
  951. SET_ITEM_INT(parser_debug);
  952. SET_ITEM_INT(write_bytecode);
  953. SET_ITEM_INT(verbose);
  954. SET_ITEM_INT(quiet);
  955. SET_ITEM_INT(user_site_directory);
  956. SET_ITEM_INT(configure_c_stdio);
  957. SET_ITEM_INT(buffered_stdio);
  958. SET_ITEM_WSTR(stdio_encoding);
  959. SET_ITEM_WSTR(stdio_errors);
  960. #ifdef MS_WINDOWS
  961. SET_ITEM_INT(legacy_windows_stdio);
  962. #endif
  963. SET_ITEM_INT(skip_source_first_line);
  964. SET_ITEM_WSTR(run_command);
  965. SET_ITEM_WSTR(run_module);
  966. SET_ITEM_WSTR(run_filename);
  967. SET_ITEM_INT(_install_importlib);
  968. SET_ITEM_WSTR(check_hash_pycs_mode);
  969. SET_ITEM_INT(pathconfig_warnings);
  970. SET_ITEM_INT(_init_main);
  971. SET_ITEM_WSTRLIST(orig_argv);
  972. SET_ITEM_INT(use_frozen_modules);
  973. SET_ITEM_INT(safe_path);
  974. SET_ITEM_INT(_is_python_build);
  975. SET_ITEM_INT(int_max_str_digits);
  976. return dict;
  977. fail:
  978. Py_DECREF(dict);
  979. return NULL;
  980. #undef FROM_WSTRING
  981. #undef SET_ITEM
  982. #undef SET_ITEM_INT
  983. #undef SET_ITEM_UINT
  984. #undef SET_ITEM_WSTR
  985. #undef SET_ITEM_WSTRLIST
  986. }
  987. static PyObject*
  988. config_dict_get(PyObject *dict, const char *name)
  989. {
  990. PyObject *item = _PyDict_GetItemStringWithError(dict, name);
  991. if (item == NULL && !PyErr_Occurred()) {
  992. PyErr_Format(PyExc_ValueError, "missing config key: %s", name);
  993. return NULL;
  994. }
  995. return item;
  996. }
  997. static void
  998. config_dict_invalid_value(const char *name)
  999. {
  1000. PyErr_Format(PyExc_ValueError, "invalid config value: %s", name);
  1001. }
  1002. static void
  1003. config_dict_invalid_type(const char *name)
  1004. {
  1005. PyErr_Format(PyExc_TypeError, "invalid config type: %s", name);
  1006. }
  1007. static int
  1008. config_dict_get_int(PyObject *dict, const char *name, int *result)
  1009. {
  1010. PyObject *item = config_dict_get(dict, name);
  1011. if (item == NULL) {
  1012. return -1;
  1013. }
  1014. int value = _PyLong_AsInt(item);
  1015. if (value == -1 && PyErr_Occurred()) {
  1016. if (PyErr_ExceptionMatches(PyExc_TypeError)) {
  1017. config_dict_invalid_type(name);
  1018. }
  1019. else if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
  1020. config_dict_invalid_value(name);
  1021. }
  1022. return -1;
  1023. }
  1024. *result = value;
  1025. return 0;
  1026. }
  1027. static int
  1028. config_dict_get_ulong(PyObject *dict, const char *name, unsigned long *result)
  1029. {
  1030. PyObject *item = config_dict_get(dict, name);
  1031. if (item == NULL) {
  1032. return -1;
  1033. }
  1034. unsigned long value = PyLong_AsUnsignedLong(item);
  1035. if (value == (unsigned long)-1 && PyErr_Occurred()) {
  1036. if (PyErr_ExceptionMatches(PyExc_TypeError)) {
  1037. config_dict_invalid_type(name);
  1038. }
  1039. else if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
  1040. config_dict_invalid_value(name);
  1041. }
  1042. return -1;
  1043. }
  1044. *result = value;
  1045. return 0;
  1046. }
  1047. static int
  1048. config_dict_get_wstr(PyObject *dict, const char *name, PyConfig *config,
  1049. wchar_t **result)
  1050. {
  1051. PyObject *item = config_dict_get(dict, name);
  1052. if (item == NULL) {
  1053. return -1;
  1054. }
  1055. PyStatus status;
  1056. if (item == Py_None) {
  1057. status = PyConfig_SetString(config, result, NULL);
  1058. }
  1059. else if (!PyUnicode_Check(item)) {
  1060. config_dict_invalid_type(name);
  1061. return -1;
  1062. }
  1063. else {
  1064. wchar_t *wstr = PyUnicode_AsWideCharString(item, NULL);
  1065. if (wstr == NULL) {
  1066. return -1;
  1067. }
  1068. status = PyConfig_SetString(config, result, wstr);
  1069. PyMem_Free(wstr);
  1070. }
  1071. if (_PyStatus_EXCEPTION(status)) {
  1072. PyErr_NoMemory();
  1073. return -1;
  1074. }
  1075. return 0;
  1076. }
  1077. static int
  1078. config_dict_get_wstrlist(PyObject *dict, const char *name, PyConfig *config,
  1079. PyWideStringList *result)
  1080. {
  1081. PyObject *list = config_dict_get(dict, name);
  1082. if (list == NULL) {
  1083. return -1;
  1084. }
  1085. if (!PyList_CheckExact(list)) {
  1086. config_dict_invalid_type(name);
  1087. return -1;
  1088. }
  1089. PyWideStringList wstrlist = _PyWideStringList_INIT;
  1090. for (Py_ssize_t i=0; i < PyList_GET_SIZE(list); i++) {
  1091. PyObject *item = PyList_GET_ITEM(list, i);
  1092. if (item == Py_None) {
  1093. config_dict_invalid_value(name);
  1094. goto error;
  1095. }
  1096. else if (!PyUnicode_Check(item)) {
  1097. config_dict_invalid_type(name);
  1098. goto error;
  1099. }
  1100. wchar_t *wstr = PyUnicode_AsWideCharString(item, NULL);
  1101. if (wstr == NULL) {
  1102. goto error;
  1103. }
  1104. PyStatus status = PyWideStringList_Append(&wstrlist, wstr);
  1105. PyMem_Free(wstr);
  1106. if (_PyStatus_EXCEPTION(status)) {
  1107. PyErr_NoMemory();
  1108. goto error;
  1109. }
  1110. }
  1111. if (_PyWideStringList_Copy(result, &wstrlist) < 0) {
  1112. PyErr_NoMemory();
  1113. goto error;
  1114. }
  1115. _PyWideStringList_Clear(&wstrlist);
  1116. return 0;
  1117. error:
  1118. _PyWideStringList_Clear(&wstrlist);
  1119. return -1;
  1120. }
  1121. int
  1122. _PyConfig_FromDict(PyConfig *config, PyObject *dict)
  1123. {
  1124. if (!PyDict_Check(dict)) {
  1125. PyErr_SetString(PyExc_TypeError, "dict expected");
  1126. return -1;
  1127. }
  1128. #define CHECK_VALUE(NAME, TEST) \
  1129. if (!(TEST)) { \
  1130. config_dict_invalid_value(NAME); \
  1131. return -1; \
  1132. }
  1133. #define GET_UINT(KEY) \
  1134. do { \
  1135. if (config_dict_get_int(dict, #KEY, &config->KEY) < 0) { \
  1136. return -1; \
  1137. } \
  1138. CHECK_VALUE(#KEY, config->KEY >= 0); \
  1139. } while (0)
  1140. #define GET_INT(KEY) \
  1141. do { \
  1142. if (config_dict_get_int(dict, #KEY, &config->KEY) < 0) { \
  1143. return -1; \
  1144. } \
  1145. } while (0)
  1146. #define GET_WSTR(KEY) \
  1147. do { \
  1148. if (config_dict_get_wstr(dict, #KEY, config, &config->KEY) < 0) { \
  1149. return -1; \
  1150. } \
  1151. CHECK_VALUE(#KEY, config->KEY != NULL); \
  1152. } while (0)
  1153. #define GET_WSTR_OPT(KEY) \
  1154. do { \
  1155. if (config_dict_get_wstr(dict, #KEY, config, &config->KEY) < 0) { \
  1156. return -1; \
  1157. } \
  1158. } while (0)
  1159. #define GET_WSTRLIST(KEY) \
  1160. do { \
  1161. if (config_dict_get_wstrlist(dict, #KEY, config, &config->KEY) < 0) { \
  1162. return -1; \
  1163. } \
  1164. } while (0)
  1165. GET_UINT(_config_init);
  1166. CHECK_VALUE("_config_init",
  1167. config->_config_init == _PyConfig_INIT_COMPAT
  1168. || config->_config_init == _PyConfig_INIT_PYTHON
  1169. || config->_config_init == _PyConfig_INIT_ISOLATED);
  1170. GET_UINT(isolated);
  1171. GET_UINT(use_environment);
  1172. GET_UINT(dev_mode);
  1173. GET_UINT(install_signal_handlers);
  1174. GET_UINT(use_hash_seed);
  1175. if (config_dict_get_ulong(dict, "hash_seed", &config->hash_seed) < 0) {
  1176. return -1;
  1177. }
  1178. CHECK_VALUE("hash_seed", config->hash_seed <= MAX_HASH_SEED);
  1179. GET_UINT(faulthandler);
  1180. GET_UINT(tracemalloc);
  1181. GET_UINT(perf_profiling);
  1182. GET_UINT(import_time);
  1183. GET_UINT(code_debug_ranges);
  1184. GET_UINT(show_ref_count);
  1185. GET_UINT(dump_refs);
  1186. GET_UINT(malloc_stats);
  1187. GET_WSTR(filesystem_encoding);
  1188. GET_WSTR(filesystem_errors);
  1189. GET_WSTR_OPT(pycache_prefix);
  1190. GET_UINT(parse_argv);
  1191. GET_WSTRLIST(orig_argv);
  1192. GET_WSTRLIST(argv);
  1193. GET_WSTRLIST(xoptions);
  1194. GET_WSTRLIST(warnoptions);
  1195. GET_UINT(site_import);
  1196. GET_UINT(bytes_warning);
  1197. GET_UINT(warn_default_encoding);
  1198. GET_UINT(inspect);
  1199. GET_UINT(interactive);
  1200. GET_UINT(optimization_level);
  1201. GET_UINT(parser_debug);
  1202. GET_UINT(write_bytecode);
  1203. GET_UINT(verbose);
  1204. GET_UINT(quiet);
  1205. GET_UINT(user_site_directory);
  1206. GET_UINT(configure_c_stdio);
  1207. GET_UINT(buffered_stdio);
  1208. GET_WSTR(stdio_encoding);
  1209. GET_WSTR(stdio_errors);
  1210. #ifdef MS_WINDOWS
  1211. GET_UINT(legacy_windows_stdio);
  1212. #endif
  1213. GET_WSTR(check_hash_pycs_mode);
  1214. GET_UINT(pathconfig_warnings);
  1215. GET_WSTR(program_name);
  1216. GET_WSTR_OPT(pythonpath_env);
  1217. GET_WSTR_OPT(home);
  1218. GET_WSTR(platlibdir);
  1219. // Path configuration output
  1220. GET_UINT(module_search_paths_set);
  1221. GET_WSTRLIST(module_search_paths);
  1222. GET_WSTR_OPT(stdlib_dir);
  1223. GET_WSTR_OPT(executable);
  1224. GET_WSTR_OPT(base_executable);
  1225. GET_WSTR_OPT(prefix);
  1226. GET_WSTR_OPT(base_prefix);
  1227. GET_WSTR_OPT(exec_prefix);
  1228. GET_WSTR_OPT(base_exec_prefix);
  1229. GET_UINT(skip_source_first_line);
  1230. GET_WSTR_OPT(run_command);
  1231. GET_WSTR_OPT(run_module);
  1232. GET_WSTR_OPT(run_filename);
  1233. GET_UINT(_install_importlib);
  1234. GET_UINT(_init_main);
  1235. GET_UINT(use_frozen_modules);
  1236. GET_UINT(safe_path);
  1237. GET_UINT(_is_python_build);
  1238. GET_INT(int_max_str_digits);
  1239. #undef CHECK_VALUE
  1240. #undef GET_UINT
  1241. #undef GET_INT
  1242. #undef GET_WSTR
  1243. #undef GET_WSTR_OPT
  1244. return 0;
  1245. }
  1246. static const char*
  1247. config_get_env(const PyConfig *config, const char *name)
  1248. {
  1249. return _Py_GetEnv(config->use_environment, name);
  1250. }
  1251. /* Get a copy of the environment variable as wchar_t*.
  1252. Return 0 on success, but *dest can be NULL.
  1253. Return -1 on memory allocation failure. Return -2 on decoding error. */
  1254. static PyStatus
  1255. config_get_env_dup(PyConfig *config,
  1256. wchar_t **dest,
  1257. wchar_t *wname, char *name,
  1258. const char *decode_err_msg)
  1259. {
  1260. assert(*dest == NULL);
  1261. assert(config->use_environment >= 0);
  1262. if (!config->use_environment) {
  1263. *dest = NULL;
  1264. return _PyStatus_OK();
  1265. }
  1266. #ifdef MS_WINDOWS
  1267. const wchar_t *var = _wgetenv(wname);
  1268. if (!var || var[0] == '\0') {
  1269. *dest = NULL;
  1270. return _PyStatus_OK();
  1271. }
  1272. return PyConfig_SetString(config, dest, var);
  1273. #else
  1274. const char *var = getenv(name);
  1275. if (!var || var[0] == '\0') {
  1276. *dest = NULL;
  1277. return _PyStatus_OK();
  1278. }
  1279. return config_set_bytes_string(config, dest, var, decode_err_msg);
  1280. #endif
  1281. }
  1282. #define CONFIG_GET_ENV_DUP(CONFIG, DEST, WNAME, NAME) \
  1283. config_get_env_dup(CONFIG, DEST, WNAME, NAME, "cannot decode " NAME)
  1284. static void
  1285. config_get_global_vars(PyConfig *config)
  1286. {
  1287. _Py_COMP_DIAG_PUSH
  1288. _Py_COMP_DIAG_IGNORE_DEPR_DECLS
  1289. if (config->_config_init != _PyConfig_INIT_COMPAT) {
  1290. /* Python and Isolated configuration ignore global variables */
  1291. return;
  1292. }
  1293. #define COPY_FLAG(ATTR, VALUE) \
  1294. if (config->ATTR == -1) { \
  1295. config->ATTR = VALUE; \
  1296. }
  1297. #define COPY_NOT_FLAG(ATTR, VALUE) \
  1298. if (config->ATTR == -1) { \
  1299. config->ATTR = !(VALUE); \
  1300. }
  1301. COPY_FLAG(isolated, Py_IsolatedFlag);
  1302. COPY_NOT_FLAG(use_environment, Py_IgnoreEnvironmentFlag);
  1303. COPY_FLAG(bytes_warning, Py_BytesWarningFlag);
  1304. COPY_FLAG(inspect, Py_InspectFlag);
  1305. COPY_FLAG(interactive, Py_InteractiveFlag);
  1306. COPY_FLAG(optimization_level, Py_OptimizeFlag);
  1307. COPY_FLAG(parser_debug, Py_DebugFlag);
  1308. COPY_FLAG(verbose, Py_VerboseFlag);
  1309. COPY_FLAG(quiet, Py_QuietFlag);
  1310. #ifdef MS_WINDOWS
  1311. COPY_FLAG(legacy_windows_stdio, Py_LegacyWindowsStdioFlag);
  1312. #endif
  1313. COPY_NOT_FLAG(pathconfig_warnings, Py_FrozenFlag);
  1314. COPY_NOT_FLAG(buffered_stdio, Py_UnbufferedStdioFlag);
  1315. COPY_NOT_FLAG(site_import, Py_NoSiteFlag);
  1316. COPY_NOT_FLAG(write_bytecode, Py_DontWriteBytecodeFlag);
  1317. COPY_NOT_FLAG(user_site_directory, Py_NoUserSiteDirectory);
  1318. #undef COPY_FLAG
  1319. #undef COPY_NOT_FLAG
  1320. _Py_COMP_DIAG_POP
  1321. }
  1322. /* Set Py_xxx global configuration variables from 'config' configuration. */
  1323. static void
  1324. config_set_global_vars(const PyConfig *config)
  1325. {
  1326. _Py_COMP_DIAG_PUSH
  1327. _Py_COMP_DIAG_IGNORE_DEPR_DECLS
  1328. #define COPY_FLAG(ATTR, VAR) \
  1329. if (config->ATTR != -1) { \
  1330. VAR = config->ATTR; \
  1331. }
  1332. #define COPY_NOT_FLAG(ATTR, VAR) \
  1333. if (config->ATTR != -1) { \
  1334. VAR = !config->ATTR; \
  1335. }
  1336. COPY_FLAG(isolated, Py_IsolatedFlag);
  1337. COPY_NOT_FLAG(use_environment, Py_IgnoreEnvironmentFlag);
  1338. COPY_FLAG(bytes_warning, Py_BytesWarningFlag);
  1339. COPY_FLAG(inspect, Py_InspectFlag);
  1340. COPY_FLAG(interactive, Py_InteractiveFlag);
  1341. COPY_FLAG(optimization_level, Py_OptimizeFlag);
  1342. COPY_FLAG(parser_debug, Py_DebugFlag);
  1343. COPY_FLAG(verbose, Py_VerboseFlag);
  1344. COPY_FLAG(quiet, Py_QuietFlag);
  1345. #ifdef MS_WINDOWS
  1346. COPY_FLAG(legacy_windows_stdio, Py_LegacyWindowsStdioFlag);
  1347. #endif
  1348. COPY_NOT_FLAG(pathconfig_warnings, Py_FrozenFlag);
  1349. COPY_NOT_FLAG(buffered_stdio, Py_UnbufferedStdioFlag);
  1350. COPY_NOT_FLAG(site_import, Py_NoSiteFlag);
  1351. COPY_NOT_FLAG(write_bytecode, Py_DontWriteBytecodeFlag);
  1352. COPY_NOT_FLAG(user_site_directory, Py_NoUserSiteDirectory);
  1353. /* Random or non-zero hash seed */
  1354. Py_HashRandomizationFlag = (config->use_hash_seed == 0 ||
  1355. config->hash_seed != 0);
  1356. #undef COPY_FLAG
  1357. #undef COPY_NOT_FLAG
  1358. _Py_COMP_DIAG_POP
  1359. }
  1360. static const wchar_t*
  1361. config_get_xoption(const PyConfig *config, wchar_t *name)
  1362. {
  1363. return _Py_get_xoption(&config->xoptions, name);
  1364. }
  1365. static const wchar_t*
  1366. config_get_xoption_value(const PyConfig *config, wchar_t *name)
  1367. {
  1368. const wchar_t *xoption = config_get_xoption(config, name);
  1369. if (xoption == NULL) {
  1370. return NULL;
  1371. }
  1372. const wchar_t *sep = wcschr(xoption, L'=');
  1373. return sep ? sep + 1 : L"";
  1374. }
  1375. static PyStatus
  1376. config_init_hash_seed(PyConfig *config)
  1377. {
  1378. static_assert(sizeof(_Py_HashSecret_t) == sizeof(_Py_HashSecret.uc),
  1379. "_Py_HashSecret_t has wrong size");
  1380. const char *seed_text = config_get_env(config, "PYTHONHASHSEED");
  1381. /* Convert a text seed to a numeric one */
  1382. if (seed_text && strcmp(seed_text, "random") != 0) {
  1383. const char *endptr = seed_text;
  1384. unsigned long seed;
  1385. errno = 0;
  1386. seed = strtoul(seed_text, (char **)&endptr, 10);
  1387. if (*endptr != '\0'
  1388. || seed > MAX_HASH_SEED
  1389. || (errno == ERANGE && seed == ULONG_MAX))
  1390. {
  1391. return _PyStatus_ERR("PYTHONHASHSEED must be \"random\" "
  1392. "or an integer in range [0; 4294967295]");
  1393. }
  1394. /* Use a specific hash */
  1395. config->use_hash_seed = 1;
  1396. config->hash_seed = seed;
  1397. }
  1398. else {
  1399. /* Use a random hash */
  1400. config->use_hash_seed = 0;
  1401. config->hash_seed = 0;
  1402. }
  1403. return _PyStatus_OK();
  1404. }
  1405. static int
  1406. config_wstr_to_int(const wchar_t *wstr, int *result)
  1407. {
  1408. const wchar_t *endptr = wstr;
  1409. errno = 0;
  1410. long value = wcstol(wstr, (wchar_t **)&endptr, 10);
  1411. if (*endptr != '\0' || errno == ERANGE) {
  1412. return -1;
  1413. }
  1414. if (value < INT_MIN || value > INT_MAX) {
  1415. return -1;
  1416. }
  1417. *result = (int)value;
  1418. return 0;
  1419. }
  1420. static PyStatus
  1421. config_read_env_vars(PyConfig *config)
  1422. {
  1423. PyStatus status;
  1424. int use_env = config->use_environment;
  1425. /* Get environment variables */
  1426. _Py_get_env_flag(use_env, &config->parser_debug, "PYTHONDEBUG");
  1427. _Py_get_env_flag(use_env, &config->verbose, "PYTHONVERBOSE");
  1428. _Py_get_env_flag(use_env, &config->optimization_level, "PYTHONOPTIMIZE");
  1429. _Py_get_env_flag(use_env, &config->inspect, "PYTHONINSPECT");
  1430. int dont_write_bytecode = 0;
  1431. _Py_get_env_flag(use_env, &dont_write_bytecode, "PYTHONDONTWRITEBYTECODE");
  1432. if (dont_write_bytecode) {
  1433. config->write_bytecode = 0;
  1434. }
  1435. int no_user_site_directory = 0;
  1436. _Py_get_env_flag(use_env, &no_user_site_directory, "PYTHONNOUSERSITE");
  1437. if (no_user_site_directory) {
  1438. config->user_site_directory = 0;
  1439. }
  1440. int unbuffered_stdio = 0;
  1441. _Py_get_env_flag(use_env, &unbuffered_stdio, "PYTHONUNBUFFERED");
  1442. if (unbuffered_stdio) {
  1443. config->buffered_stdio = 0;
  1444. }
  1445. #ifdef MS_WINDOWS
  1446. _Py_get_env_flag(use_env, &config->legacy_windows_stdio,
  1447. "PYTHONLEGACYWINDOWSSTDIO");
  1448. #endif
  1449. if (config_get_env(config, "PYTHONDUMPREFS")) {
  1450. config->dump_refs = 1;
  1451. }
  1452. if (config_get_env(config, "PYTHONMALLOCSTATS")) {
  1453. config->malloc_stats = 1;
  1454. }
  1455. if (config->dump_refs_file == NULL) {
  1456. status = CONFIG_GET_ENV_DUP(config, &config->dump_refs_file,
  1457. L"PYTHONDUMPREFSFILE", "PYTHONDUMPREFSFILE");
  1458. if (_PyStatus_EXCEPTION(status)) {
  1459. return status;
  1460. }
  1461. }
  1462. if (config->pythonpath_env == NULL) {
  1463. status = CONFIG_GET_ENV_DUP(config, &config->pythonpath_env,
  1464. L"PYTHONPATH", "PYTHONPATH");
  1465. if (_PyStatus_EXCEPTION(status)) {
  1466. return status;
  1467. }
  1468. }
  1469. if(config->platlibdir == NULL) {
  1470. status = CONFIG_GET_ENV_DUP(config, &config->platlibdir,
  1471. L"PYTHONPLATLIBDIR", "PYTHONPLATLIBDIR");
  1472. if (_PyStatus_EXCEPTION(status)) {
  1473. return status;
  1474. }
  1475. }
  1476. if (config->use_hash_seed < 0) {
  1477. status = config_init_hash_seed(config);
  1478. if (_PyStatus_EXCEPTION(status)) {
  1479. return status;
  1480. }
  1481. }
  1482. if (config_get_env(config, "PYTHONSAFEPATH")) {
  1483. config->safe_path = 1;
  1484. }
  1485. return _PyStatus_OK();
  1486. }
  1487. static PyStatus
  1488. config_init_perf_profiling(PyConfig *config)
  1489. {
  1490. int active = 0;
  1491. const char *env = config_get_env(config, "PYTHONPERFSUPPORT");
  1492. if (env) {
  1493. if (_Py_str_to_int(env, &active) != 0) {
  1494. active = 0;
  1495. }
  1496. if (active) {
  1497. config->perf_profiling = 1;
  1498. }
  1499. }
  1500. const wchar_t *xoption = config_get_xoption(config, L"perf");
  1501. if (xoption) {
  1502. config->perf_profiling = 1;
  1503. }
  1504. return _PyStatus_OK();
  1505. }
  1506. static PyStatus
  1507. config_init_tracemalloc(PyConfig *config)
  1508. {
  1509. int nframe;
  1510. int valid;
  1511. const char *env = config_get_env(config, "PYTHONTRACEMALLOC");
  1512. if (env) {
  1513. if (!_Py_str_to_int(env, &nframe)) {
  1514. valid = (nframe >= 0);
  1515. }
  1516. else {
  1517. valid = 0;
  1518. }
  1519. if (!valid) {
  1520. return _PyStatus_ERR("PYTHONTRACEMALLOC: invalid number of frames");
  1521. }
  1522. config->tracemalloc = nframe;
  1523. }
  1524. const wchar_t *xoption = config_get_xoption(config, L"tracemalloc");
  1525. if (xoption) {
  1526. const wchar_t *sep = wcschr(xoption, L'=');
  1527. if (sep) {
  1528. if (!config_wstr_to_int(sep + 1, &nframe)) {
  1529. valid = (nframe >= 0);
  1530. }
  1531. else {
  1532. valid = 0;
  1533. }
  1534. if (!valid) {
  1535. return _PyStatus_ERR("-X tracemalloc=NFRAME: "
  1536. "invalid number of frames");
  1537. }
  1538. }
  1539. else {
  1540. /* -X tracemalloc behaves as -X tracemalloc=1 */
  1541. nframe = 1;
  1542. }
  1543. config->tracemalloc = nframe;
  1544. }
  1545. return _PyStatus_OK();
  1546. }
  1547. static PyStatus
  1548. config_init_int_max_str_digits(PyConfig *config)
  1549. {
  1550. int maxdigits;
  1551. const char *env = config_get_env(config, "PYTHONINTMAXSTRDIGITS");
  1552. if (env) {
  1553. bool valid = 0;
  1554. if (!_Py_str_to_int(env, &maxdigits)) {
  1555. valid = ((maxdigits == 0) || (maxdigits >= _PY_LONG_MAX_STR_DIGITS_THRESHOLD));
  1556. }
  1557. if (!valid) {
  1558. #define STRINGIFY(VAL) _STRINGIFY(VAL)
  1559. #define _STRINGIFY(VAL) #VAL
  1560. return _PyStatus_ERR(
  1561. "PYTHONINTMAXSTRDIGITS: invalid limit; must be >= "
  1562. STRINGIFY(_PY_LONG_MAX_STR_DIGITS_THRESHOLD)
  1563. " or 0 for unlimited.");
  1564. }
  1565. config->int_max_str_digits = maxdigits;
  1566. }
  1567. const wchar_t *xoption = config_get_xoption(config, L"int_max_str_digits");
  1568. if (xoption) {
  1569. const wchar_t *sep = wcschr(xoption, L'=');
  1570. bool valid = 0;
  1571. if (sep) {
  1572. if (!config_wstr_to_int(sep + 1, &maxdigits)) {
  1573. valid = ((maxdigits == 0) || (maxdigits >= _PY_LONG_MAX_STR_DIGITS_THRESHOLD));
  1574. }
  1575. }
  1576. if (!valid) {
  1577. return _PyStatus_ERR(
  1578. "-X int_max_str_digits: invalid limit; must be >= "
  1579. STRINGIFY(_PY_LONG_MAX_STR_DIGITS_THRESHOLD)
  1580. " or 0 for unlimited.");
  1581. #undef _STRINGIFY
  1582. #undef STRINGIFY
  1583. }
  1584. config->int_max_str_digits = maxdigits;
  1585. }
  1586. if (config->int_max_str_digits < 0) {
  1587. config->int_max_str_digits = _PY_LONG_DEFAULT_MAX_STR_DIGITS;
  1588. }
  1589. return _PyStatus_OK();
  1590. }
  1591. static PyStatus
  1592. config_init_pycache_prefix(PyConfig *config)
  1593. {
  1594. assert(config->pycache_prefix == NULL);
  1595. const wchar_t *xoption = config_get_xoption(config, L"pycache_prefix");
  1596. if (xoption) {
  1597. const wchar_t *sep = wcschr(xoption, L'=');
  1598. if (sep && wcslen(sep) > 1) {
  1599. config->pycache_prefix = _PyMem_RawWcsdup(sep + 1);
  1600. if (config->pycache_prefix == NULL) {
  1601. return _PyStatus_NO_MEMORY();
  1602. }
  1603. }
  1604. else {
  1605. // PYTHONPYCACHEPREFIX env var ignored
  1606. // if "-X pycache_prefix=" option is used
  1607. config->pycache_prefix = NULL;
  1608. }
  1609. return _PyStatus_OK();
  1610. }
  1611. return CONFIG_GET_ENV_DUP(config, &config->pycache_prefix,
  1612. L"PYTHONPYCACHEPREFIX",
  1613. "PYTHONPYCACHEPREFIX");
  1614. }
  1615. static PyStatus
  1616. config_read_complex_options(PyConfig *config)
  1617. {
  1618. /* More complex options configured by env var and -X option */
  1619. if (config->faulthandler < 0) {
  1620. if (config_get_env(config, "PYTHONFAULTHANDLER")
  1621. || config_get_xoption(config, L"faulthandler")) {
  1622. config->faulthandler = 1;
  1623. }
  1624. }
  1625. if (config_get_env(config, "PYTHONPROFILEIMPORTTIME")
  1626. || config_get_xoption(config, L"importtime")) {
  1627. config->import_time = 1;
  1628. }
  1629. if (config_get_env(config, "PYTHONNODEBUGRANGES")
  1630. || config_get_xoption(config, L"no_debug_ranges")) {
  1631. config->code_debug_ranges = 0;
  1632. }
  1633. PyStatus status;
  1634. if (config->tracemalloc < 0) {
  1635. status = config_init_tracemalloc(config);
  1636. if (_PyStatus_EXCEPTION(status)) {
  1637. return status;
  1638. }
  1639. }
  1640. if (config->perf_profiling < 0) {
  1641. status = config_init_perf_profiling(config);
  1642. if (_PyStatus_EXCEPTION(status)) {
  1643. return status;
  1644. }
  1645. }
  1646. if (config->int_max_str_digits < 0) {
  1647. status = config_init_int_max_str_digits(config);
  1648. if (_PyStatus_EXCEPTION(status)) {
  1649. return status;
  1650. }
  1651. }
  1652. if (config->pycache_prefix == NULL) {
  1653. status = config_init_pycache_prefix(config);
  1654. if (_PyStatus_EXCEPTION(status)) {
  1655. return status;
  1656. }
  1657. }
  1658. return _PyStatus_OK();
  1659. }
  1660. static const wchar_t *
  1661. config_get_stdio_errors(const PyPreConfig *preconfig)
  1662. {
  1663. if (preconfig->utf8_mode) {
  1664. /* UTF-8 Mode uses UTF-8/surrogateescape */
  1665. return L"surrogateescape";
  1666. }
  1667. #ifndef MS_WINDOWS
  1668. const char *loc = setlocale(LC_CTYPE, NULL);
  1669. if (loc != NULL) {
  1670. /* surrogateescape is the default in the legacy C and POSIX locales */
  1671. if (strcmp(loc, "C") == 0 || strcmp(loc, "POSIX") == 0) {
  1672. return L"surrogateescape";
  1673. }
  1674. #ifdef PY_COERCE_C_LOCALE
  1675. /* surrogateescape is the default in locale coercion target locales */
  1676. if (_Py_IsLocaleCoercionTarget(loc)) {
  1677. return L"surrogateescape";
  1678. }
  1679. #endif
  1680. }
  1681. return L"strict";
  1682. #else
  1683. /* On Windows, always use surrogateescape by default */
  1684. return L"surrogateescape";
  1685. #endif
  1686. }
  1687. // See also config_get_fs_encoding()
  1688. static PyStatus
  1689. config_get_locale_encoding(PyConfig *config, const PyPreConfig *preconfig,
  1690. wchar_t **locale_encoding)
  1691. {
  1692. wchar_t *encoding;
  1693. if (preconfig->utf8_mode) {
  1694. encoding = _PyMem_RawWcsdup(L"utf-8");
  1695. }
  1696. else {
  1697. encoding = _Py_GetLocaleEncoding();
  1698. }
  1699. if (encoding == NULL) {
  1700. return _PyStatus_NO_MEMORY();
  1701. }
  1702. PyStatus status = PyConfig_SetString(config, locale_encoding, encoding);
  1703. PyMem_RawFree(encoding);
  1704. return status;
  1705. }
  1706. static PyStatus
  1707. config_init_stdio_encoding(PyConfig *config,
  1708. const PyPreConfig *preconfig)
  1709. {
  1710. PyStatus status;
  1711. /* If Py_SetStandardStreamEncoding() has been called, use its
  1712. arguments if they are not NULL. */
  1713. if (config->stdio_encoding == NULL && _Py_StandardStreamEncoding != NULL) {
  1714. status = CONFIG_SET_BYTES_STR(config, &config->stdio_encoding,
  1715. _Py_StandardStreamEncoding,
  1716. "_Py_StandardStreamEncoding");
  1717. if (_PyStatus_EXCEPTION(status)) {
  1718. return status;
  1719. }
  1720. }
  1721. if (config->stdio_errors == NULL && _Py_StandardStreamErrors != NULL) {
  1722. status = CONFIG_SET_BYTES_STR(config, &config->stdio_errors,
  1723. _Py_StandardStreamErrors,
  1724. "_Py_StandardStreamErrors");
  1725. if (_PyStatus_EXCEPTION(status)) {
  1726. return status;
  1727. }
  1728. }
  1729. // Exit if encoding and errors are defined
  1730. if (config->stdio_encoding != NULL && config->stdio_errors != NULL) {
  1731. return _PyStatus_OK();
  1732. }
  1733. /* PYTHONIOENCODING environment variable */
  1734. const char *opt = config_get_env(config, "PYTHONIOENCODING");
  1735. if (opt) {
  1736. char *pythonioencoding = _PyMem_RawStrdup(opt);
  1737. if (pythonioencoding == NULL) {
  1738. return _PyStatus_NO_MEMORY();
  1739. }
  1740. char *errors = strchr(pythonioencoding, ':');
  1741. if (errors) {
  1742. *errors = '\0';
  1743. errors++;
  1744. if (!errors[0]) {
  1745. errors = NULL;
  1746. }
  1747. }
  1748. /* Does PYTHONIOENCODING contain an encoding? */
  1749. if (pythonioencoding[0]) {
  1750. if (config->stdio_encoding == NULL) {
  1751. status = CONFIG_SET_BYTES_STR(config, &config->stdio_encoding,
  1752. pythonioencoding,
  1753. "PYTHONIOENCODING environment variable");
  1754. if (_PyStatus_EXCEPTION(status)) {
  1755. PyMem_RawFree(pythonioencoding);
  1756. return status;
  1757. }
  1758. }
  1759. /* If the encoding is set but not the error handler,
  1760. use "strict" error handler by default.
  1761. PYTHONIOENCODING=latin1 behaves as
  1762. PYTHONIOENCODING=latin1:strict. */
  1763. if (!errors) {
  1764. errors = "strict";
  1765. }
  1766. }
  1767. if (config->stdio_errors == NULL && errors != NULL) {
  1768. status = CONFIG_SET_BYTES_STR(config, &config->stdio_errors,
  1769. errors,
  1770. "PYTHONIOENCODING environment variable");
  1771. if (_PyStatus_EXCEPTION(status)) {
  1772. PyMem_RawFree(pythonioencoding);
  1773. return status;
  1774. }
  1775. }
  1776. PyMem_RawFree(pythonioencoding);
  1777. }
  1778. /* Choose the default error handler based on the current locale. */
  1779. if (config->stdio_encoding == NULL) {
  1780. status = config_get_locale_encoding(config, preconfig,
  1781. &config->stdio_encoding);
  1782. if (_PyStatus_EXCEPTION(status)) {
  1783. return status;
  1784. }
  1785. }
  1786. if (config->stdio_errors == NULL) {
  1787. const wchar_t *errors = config_get_stdio_errors(preconfig);
  1788. assert(errors != NULL);
  1789. status = PyConfig_SetString(config, &config->stdio_errors, errors);
  1790. if (_PyStatus_EXCEPTION(status)) {
  1791. return status;
  1792. }
  1793. }
  1794. return _PyStatus_OK();
  1795. }
  1796. // See also config_get_locale_encoding()
  1797. static PyStatus
  1798. config_get_fs_encoding(PyConfig *config, const PyPreConfig *preconfig,
  1799. wchar_t **fs_encoding)
  1800. {
  1801. #ifdef _Py_FORCE_UTF8_FS_ENCODING
  1802. return PyConfig_SetString(config, fs_encoding, L"utf-8");
  1803. #elif defined(MS_WINDOWS)
  1804. const wchar_t *encoding;
  1805. if (preconfig->legacy_windows_fs_encoding) {
  1806. // Legacy Windows filesystem encoding: mbcs/replace
  1807. encoding = L"mbcs";
  1808. }
  1809. else {
  1810. // Windows defaults to utf-8/surrogatepass (PEP 529)
  1811. encoding = L"utf-8";
  1812. }
  1813. return PyConfig_SetString(config, fs_encoding, encoding);
  1814. #else // !MS_WINDOWS
  1815. if (preconfig->utf8_mode) {
  1816. return PyConfig_SetString(config, fs_encoding, L"utf-8");
  1817. }
  1818. if (_Py_GetForceASCII()) {
  1819. return PyConfig_SetString(config, fs_encoding, L"ascii");
  1820. }
  1821. return config_get_locale_encoding(config, preconfig, fs_encoding);
  1822. #endif // !MS_WINDOWS
  1823. }
  1824. static PyStatus
  1825. config_init_fs_encoding(PyConfig *config, const PyPreConfig *preconfig)
  1826. {
  1827. PyStatus status;
  1828. if (config->filesystem_encoding == NULL) {
  1829. status = config_get_fs_encoding(config, preconfig,
  1830. &config->filesystem_encoding);
  1831. if (_PyStatus_EXCEPTION(status)) {
  1832. return status;
  1833. }
  1834. }
  1835. if (config->filesystem_errors == NULL) {
  1836. const wchar_t *errors;
  1837. #ifdef MS_WINDOWS
  1838. if (preconfig->legacy_windows_fs_encoding) {
  1839. errors = L"replace";
  1840. }
  1841. else {
  1842. errors = L"surrogatepass";
  1843. }
  1844. #else
  1845. errors = L"surrogateescape";
  1846. #endif
  1847. status = PyConfig_SetString(config, &config->filesystem_errors, errors);
  1848. if (_PyStatus_EXCEPTION(status)) {
  1849. return status;
  1850. }
  1851. }
  1852. return _PyStatus_OK();
  1853. }
  1854. static PyStatus
  1855. config_init_import(PyConfig *config, int compute_path_config)
  1856. {
  1857. PyStatus status;
  1858. status = _PyConfig_InitPathConfig(config, compute_path_config);
  1859. if (_PyStatus_EXCEPTION(status)) {
  1860. return status;
  1861. }
  1862. /* -X frozen_modules=[on|off] */
  1863. const wchar_t *value = config_get_xoption_value(config, L"frozen_modules");
  1864. if (value == NULL) {
  1865. }
  1866. else if (wcscmp(value, L"on") == 0) {
  1867. config->use_frozen_modules = 1;
  1868. }
  1869. else if (wcscmp(value, L"off") == 0) {
  1870. config->use_frozen_modules = 0;
  1871. }
  1872. else if (wcslen(value) == 0) {
  1873. // "-X frozen_modules" and "-X frozen_modules=" both imply "on".
  1874. config->use_frozen_modules = 1;
  1875. }
  1876. else {
  1877. return PyStatus_Error("bad value for option -X frozen_modules "
  1878. "(expected \"on\" or \"off\")");
  1879. }
  1880. assert(config->use_frozen_modules >= 0);
  1881. return _PyStatus_OK();
  1882. }
  1883. PyStatus
  1884. _PyConfig_InitImportConfig(PyConfig *config)
  1885. {
  1886. return config_init_import(config, 1);
  1887. }
  1888. static PyStatus
  1889. config_read(PyConfig *config, int compute_path_config)
  1890. {
  1891. PyStatus status;
  1892. const PyPreConfig *preconfig = &_PyRuntime.preconfig;
  1893. if (config->use_environment) {
  1894. status = config_read_env_vars(config);
  1895. if (_PyStatus_EXCEPTION(status)) {
  1896. return status;
  1897. }
  1898. }
  1899. /* -X options */
  1900. if (config_get_xoption(config, L"showrefcount")) {
  1901. config->show_ref_count = 1;
  1902. }
  1903. #ifdef Py_STATS
  1904. if (config_get_xoption(config, L"pystats")) {
  1905. _py_stats = &_py_stats_struct;
  1906. }
  1907. #endif
  1908. status = config_read_complex_options(config);
  1909. if (_PyStatus_EXCEPTION(status)) {
  1910. return status;
  1911. }
  1912. if (config->_install_importlib) {
  1913. status = config_init_import(config, compute_path_config);
  1914. if (_PyStatus_EXCEPTION(status)) {
  1915. return status;
  1916. }
  1917. }
  1918. /* default values */
  1919. if (config->dev_mode) {
  1920. if (config->faulthandler < 0) {
  1921. config->faulthandler = 1;
  1922. }
  1923. }
  1924. if (config->faulthandler < 0) {
  1925. config->faulthandler = 0;
  1926. }
  1927. if (config->tracemalloc < 0) {
  1928. config->tracemalloc = 0;
  1929. }
  1930. if (config->perf_profiling < 0) {
  1931. config->perf_profiling = 0;
  1932. }
  1933. if (config->use_hash_seed < 0) {
  1934. config->use_hash_seed = 0;
  1935. config->hash_seed = 0;
  1936. }
  1937. if (config->filesystem_encoding == NULL || config->filesystem_errors == NULL) {
  1938. status = config_init_fs_encoding(config, preconfig);
  1939. if (_PyStatus_EXCEPTION(status)) {
  1940. return status;
  1941. }
  1942. }
  1943. status = config_init_stdio_encoding(config, preconfig);
  1944. if (_PyStatus_EXCEPTION(status)) {
  1945. return status;
  1946. }
  1947. if (config->argv.length < 1) {
  1948. /* Ensure at least one (empty) argument is seen */
  1949. status = PyWideStringList_Append(&config->argv, L"");
  1950. if (_PyStatus_EXCEPTION(status)) {
  1951. return status;
  1952. }
  1953. }
  1954. if (config->check_hash_pycs_mode == NULL) {
  1955. status = PyConfig_SetString(config, &config->check_hash_pycs_mode,
  1956. L"default");
  1957. if (_PyStatus_EXCEPTION(status)) {
  1958. return status;
  1959. }
  1960. }
  1961. if (config->configure_c_stdio < 0) {
  1962. config->configure_c_stdio = 1;
  1963. }
  1964. // Only parse arguments once.
  1965. if (config->parse_argv == 1) {
  1966. config->parse_argv = 2;
  1967. }
  1968. return _PyStatus_OK();
  1969. }
  1970. static void
  1971. config_init_stdio(const PyConfig *config)
  1972. {
  1973. #if defined(MS_WINDOWS) || defined(__CYGWIN__)
  1974. /* don't translate newlines (\r\n <=> \n) */
  1975. _setmode(fileno(stdin), O_BINARY);
  1976. _setmode(fileno(stdout), O_BINARY);
  1977. _setmode(fileno(stderr), O_BINARY);
  1978. #endif
  1979. if (!config->buffered_stdio) {
  1980. #ifdef HAVE_SETVBUF
  1981. setvbuf(stdin, (char *)NULL, _IONBF, BUFSIZ);
  1982. setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
  1983. setvbuf(stderr, (char *)NULL, _IONBF, BUFSIZ);
  1984. #else /* !HAVE_SETVBUF */
  1985. setbuf(stdin, (char *)NULL);
  1986. setbuf(stdout, (char *)NULL);
  1987. setbuf(stderr, (char *)NULL);
  1988. #endif /* !HAVE_SETVBUF */
  1989. }
  1990. else if (config->interactive) {
  1991. #ifdef MS_WINDOWS
  1992. /* Doesn't have to have line-buffered -- use unbuffered */
  1993. /* Any set[v]buf(stdin, ...) screws up Tkinter :-( */
  1994. setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
  1995. #else /* !MS_WINDOWS */
  1996. #ifdef HAVE_SETVBUF
  1997. setvbuf(stdin, (char *)NULL, _IOLBF, BUFSIZ);
  1998. setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ);
  1999. #endif /* HAVE_SETVBUF */
  2000. #endif /* !MS_WINDOWS */
  2001. /* Leave stderr alone - it should be unbuffered anyway. */
  2002. }
  2003. }
  2004. /* Write the configuration:
  2005. - set Py_xxx global configuration variables
  2006. - initialize C standard streams (stdin, stdout, stderr) */
  2007. PyStatus
  2008. _PyConfig_Write(const PyConfig *config, _PyRuntimeState *runtime)
  2009. {
  2010. config_set_global_vars(config);
  2011. if (config->configure_c_stdio) {
  2012. config_init_stdio(config);
  2013. }
  2014. /* Write the new pre-configuration into _PyRuntime */
  2015. PyPreConfig *preconfig = &runtime->preconfig;
  2016. preconfig->isolated = config->isolated;
  2017. preconfig->use_environment = config->use_environment;
  2018. preconfig->dev_mode = config->dev_mode;
  2019. if (_Py_SetArgcArgv(config->orig_argv.length,
  2020. config->orig_argv.items) < 0)
  2021. {
  2022. return _PyStatus_NO_MEMORY();
  2023. }
  2024. return _PyStatus_OK();
  2025. }
  2026. /* --- PyConfig command line parser -------------------------- */
  2027. static void
  2028. config_usage(int error, const wchar_t* program)
  2029. {
  2030. FILE *f = error ? stderr : stdout;
  2031. fprintf(f, usage_line, program);
  2032. if (error)
  2033. fprintf(f, "Try `python -h' for more information.\n");
  2034. else {
  2035. fputs(usage_help, f);
  2036. }
  2037. }
  2038. static void
  2039. config_envvars_usage(void)
  2040. {
  2041. printf(usage_envvars, (wint_t)DELIM, (wint_t)DELIM, PYTHONHOMEHELP);
  2042. }
  2043. static void
  2044. config_xoptions_usage(void)
  2045. {
  2046. puts(usage_xoptions);
  2047. }
  2048. static void
  2049. config_complete_usage(const wchar_t* program)
  2050. {
  2051. config_usage(0, program);
  2052. putchar('\n');
  2053. config_envvars_usage();
  2054. putchar('\n');
  2055. config_xoptions_usage();
  2056. }
  2057. /* Parse the command line arguments */
  2058. static PyStatus
  2059. config_parse_cmdline(PyConfig *config, PyWideStringList *warnoptions,
  2060. Py_ssize_t *opt_index)
  2061. {
  2062. PyStatus status;
  2063. const PyWideStringList *argv = &config->argv;
  2064. int print_version = 0;
  2065. const wchar_t* program = config->program_name;
  2066. if (!program && argv->length >= 1) {
  2067. program = argv->items[0];
  2068. }
  2069. _PyOS_ResetGetOpt();
  2070. do {
  2071. int longindex = -1;
  2072. int c = _PyOS_GetOpt(argv->length, argv->items, &longindex);
  2073. if (c == EOF) {
  2074. break;
  2075. }
  2076. if (c == 'c') {
  2077. if (config->run_command == NULL) {
  2078. /* -c is the last option; following arguments
  2079. that look like options are left for the
  2080. command to interpret. */
  2081. size_t len = wcslen(_PyOS_optarg) + 1 + 1;
  2082. wchar_t *command = PyMem_RawMalloc(sizeof(wchar_t) * len);
  2083. if (command == NULL) {
  2084. return _PyStatus_NO_MEMORY();
  2085. }
  2086. memcpy(command, _PyOS_optarg, (len - 2) * sizeof(wchar_t));
  2087. command[len - 2] = '\n';
  2088. command[len - 1] = 0;
  2089. config->run_command = command;
  2090. }
  2091. break;
  2092. }
  2093. if (c == 'm') {
  2094. /* -m is the last option; following arguments
  2095. that look like options are left for the
  2096. module to interpret. */
  2097. if (config->run_module == NULL) {
  2098. config->run_module = _PyMem_RawWcsdup(_PyOS_optarg);
  2099. if (config->run_module == NULL) {
  2100. return _PyStatus_NO_MEMORY();
  2101. }
  2102. }
  2103. break;
  2104. }
  2105. switch (c) {
  2106. // Integers represent long options, see Python/getopt.c
  2107. case 0:
  2108. // check-hash-based-pycs
  2109. if (wcscmp(_PyOS_optarg, L"always") == 0
  2110. || wcscmp(_PyOS_optarg, L"never") == 0
  2111. || wcscmp(_PyOS_optarg, L"default") == 0)
  2112. {
  2113. status = PyConfig_SetString(config, &config->check_hash_pycs_mode,
  2114. _PyOS_optarg);
  2115. if (_PyStatus_EXCEPTION(status)) {
  2116. return status;
  2117. }
  2118. } else {
  2119. fprintf(stderr, "--check-hash-based-pycs must be one of "
  2120. "'default', 'always', or 'never'\n");
  2121. config_usage(1, program);
  2122. return _PyStatus_EXIT(2);
  2123. }
  2124. break;
  2125. case 1:
  2126. // help-all
  2127. config_complete_usage(program);
  2128. return _PyStatus_EXIT(0);
  2129. case 2:
  2130. // help-env
  2131. config_envvars_usage();
  2132. return _PyStatus_EXIT(0);
  2133. case 3:
  2134. // help-xoptions
  2135. config_xoptions_usage();
  2136. return _PyStatus_EXIT(0);
  2137. case 'b':
  2138. config->bytes_warning++;
  2139. break;
  2140. case 'd':
  2141. config->parser_debug++;
  2142. break;
  2143. case 'i':
  2144. config->inspect++;
  2145. config->interactive++;
  2146. break;
  2147. case 'E':
  2148. case 'I':
  2149. case 'X':
  2150. /* option handled by _PyPreCmdline_Read() */
  2151. break;
  2152. /* case 'J': reserved for Jython */
  2153. case 'O':
  2154. config->optimization_level++;
  2155. break;
  2156. case 'P':
  2157. config->safe_path = 1;
  2158. break;
  2159. case 'B':
  2160. config->write_bytecode = 0;
  2161. break;
  2162. case 's':
  2163. config->user_site_directory = 0;
  2164. break;
  2165. case 'S':
  2166. config->site_import = 0;
  2167. break;
  2168. case 't':
  2169. /* ignored for backwards compatibility */
  2170. break;
  2171. case 'u':
  2172. config->buffered_stdio = 0;
  2173. break;
  2174. case 'v':
  2175. config->verbose++;
  2176. break;
  2177. case 'x':
  2178. config->skip_source_first_line = 1;
  2179. break;
  2180. case 'h':
  2181. case '?':
  2182. config_usage(0, program);
  2183. return _PyStatus_EXIT(0);
  2184. case 'V':
  2185. print_version++;
  2186. break;
  2187. case 'W':
  2188. status = PyWideStringList_Append(warnoptions, _PyOS_optarg);
  2189. if (_PyStatus_EXCEPTION(status)) {
  2190. return status;
  2191. }
  2192. break;
  2193. case 'q':
  2194. config->quiet++;
  2195. break;
  2196. case 'R':
  2197. config->use_hash_seed = 0;
  2198. break;
  2199. /* This space reserved for other options */
  2200. default:
  2201. /* unknown argument: parsing failed */
  2202. config_usage(1, program);
  2203. return _PyStatus_EXIT(2);
  2204. }
  2205. } while (1);
  2206. if (print_version) {
  2207. printf("Python %s\n",
  2208. (print_version >= 2) ? Py_GetVersion() : PY_VERSION);
  2209. return _PyStatus_EXIT(0);
  2210. }
  2211. if (config->run_command == NULL && config->run_module == NULL
  2212. && _PyOS_optind < argv->length
  2213. && wcscmp(argv->items[_PyOS_optind], L"-") != 0
  2214. && config->run_filename == NULL)
  2215. {
  2216. config->run_filename = _PyMem_RawWcsdup(argv->items[_PyOS_optind]);
  2217. if (config->run_filename == NULL) {
  2218. return _PyStatus_NO_MEMORY();
  2219. }
  2220. }
  2221. if (config->run_command != NULL || config->run_module != NULL) {
  2222. /* Backup _PyOS_optind */
  2223. _PyOS_optind--;
  2224. }
  2225. *opt_index = _PyOS_optind;
  2226. return _PyStatus_OK();
  2227. }
  2228. #ifdef MS_WINDOWS
  2229. # define WCSTOK wcstok_s
  2230. #else
  2231. # define WCSTOK wcstok
  2232. #endif
  2233. /* Get warning options from PYTHONWARNINGS environment variable. */
  2234. static PyStatus
  2235. config_init_env_warnoptions(PyConfig *config, PyWideStringList *warnoptions)
  2236. {
  2237. PyStatus status;
  2238. /* CONFIG_GET_ENV_DUP requires dest to be initialized to NULL */
  2239. wchar_t *env = NULL;
  2240. status = CONFIG_GET_ENV_DUP(config, &env,
  2241. L"PYTHONWARNINGS", "PYTHONWARNINGS");
  2242. if (_PyStatus_EXCEPTION(status)) {
  2243. return status;
  2244. }
  2245. /* env var is not set or is empty */
  2246. if (env == NULL) {
  2247. return _PyStatus_OK();
  2248. }
  2249. wchar_t *warning, *context = NULL;
  2250. for (warning = WCSTOK(env, L",", &context);
  2251. warning != NULL;
  2252. warning = WCSTOK(NULL, L",", &context))
  2253. {
  2254. status = PyWideStringList_Append(warnoptions, warning);
  2255. if (_PyStatus_EXCEPTION(status)) {
  2256. PyMem_RawFree(env);
  2257. return status;
  2258. }
  2259. }
  2260. PyMem_RawFree(env);
  2261. return _PyStatus_OK();
  2262. }
  2263. static PyStatus
  2264. warnoptions_append(PyConfig *config, PyWideStringList *options,
  2265. const wchar_t *option)
  2266. {
  2267. /* config_init_warnoptions() add existing config warnoptions at the end:
  2268. ensure that the new option is not already present in this list to
  2269. prevent change the options order when config_init_warnoptions() is
  2270. called twice. */
  2271. if (_PyWideStringList_Find(&config->warnoptions, option)) {
  2272. /* Already present: do nothing */
  2273. return _PyStatus_OK();
  2274. }
  2275. if (_PyWideStringList_Find(options, option)) {
  2276. /* Already present: do nothing */
  2277. return _PyStatus_OK();
  2278. }
  2279. return PyWideStringList_Append(options, option);
  2280. }
  2281. static PyStatus
  2282. warnoptions_extend(PyConfig *config, PyWideStringList *options,
  2283. const PyWideStringList *options2)
  2284. {
  2285. const Py_ssize_t len = options2->length;
  2286. wchar_t *const *items = options2->items;
  2287. for (Py_ssize_t i = 0; i < len; i++) {
  2288. PyStatus status = warnoptions_append(config, options, items[i]);
  2289. if (_PyStatus_EXCEPTION(status)) {
  2290. return status;
  2291. }
  2292. }
  2293. return _PyStatus_OK();
  2294. }
  2295. static PyStatus
  2296. config_init_warnoptions(PyConfig *config,
  2297. const PyWideStringList *cmdline_warnoptions,
  2298. const PyWideStringList *env_warnoptions,
  2299. const PyWideStringList *sys_warnoptions)
  2300. {
  2301. PyStatus status;
  2302. PyWideStringList options = _PyWideStringList_INIT;
  2303. /* Priority of warnings options, lowest to highest:
  2304. *
  2305. * - any implicit filters added by _warnings.c/warnings.py
  2306. * - PyConfig.dev_mode: "default" filter
  2307. * - PYTHONWARNINGS environment variable
  2308. * - '-W' command line options
  2309. * - PyConfig.bytes_warning ('-b' and '-bb' command line options):
  2310. * "default::BytesWarning" or "error::BytesWarning" filter
  2311. * - early PySys_AddWarnOption() calls
  2312. * - PyConfig.warnoptions
  2313. *
  2314. * PyConfig.warnoptions is copied to sys.warnoptions. Since the warnings
  2315. * module works on the basis of "the most recently added filter will be
  2316. * checked first", we add the lowest precedence entries first so that later
  2317. * entries override them.
  2318. */
  2319. if (config->dev_mode) {
  2320. status = warnoptions_append(config, &options, L"default");
  2321. if (_PyStatus_EXCEPTION(status)) {
  2322. goto error;
  2323. }
  2324. }
  2325. status = warnoptions_extend(config, &options, env_warnoptions);
  2326. if (_PyStatus_EXCEPTION(status)) {
  2327. goto error;
  2328. }
  2329. status = warnoptions_extend(config, &options, cmdline_warnoptions);
  2330. if (_PyStatus_EXCEPTION(status)) {
  2331. goto error;
  2332. }
  2333. /* If the bytes_warning_flag isn't set, bytesobject.c and bytearrayobject.c
  2334. * don't even try to emit a warning, so we skip setting the filter in that
  2335. * case.
  2336. */
  2337. if (config->bytes_warning) {
  2338. const wchar_t *filter;
  2339. if (config->bytes_warning> 1) {
  2340. filter = L"error::BytesWarning";
  2341. }
  2342. else {
  2343. filter = L"default::BytesWarning";
  2344. }
  2345. status = warnoptions_append(config, &options, filter);
  2346. if (_PyStatus_EXCEPTION(status)) {
  2347. goto error;
  2348. }
  2349. }
  2350. status = warnoptions_extend(config, &options, sys_warnoptions);
  2351. if (_PyStatus_EXCEPTION(status)) {
  2352. goto error;
  2353. }
  2354. /* Always add all PyConfig.warnoptions options */
  2355. status = _PyWideStringList_Extend(&options, &config->warnoptions);
  2356. if (_PyStatus_EXCEPTION(status)) {
  2357. goto error;
  2358. }
  2359. _PyWideStringList_Clear(&config->warnoptions);
  2360. config->warnoptions = options;
  2361. return _PyStatus_OK();
  2362. error:
  2363. _PyWideStringList_Clear(&options);
  2364. return status;
  2365. }
  2366. static PyStatus
  2367. config_update_argv(PyConfig *config, Py_ssize_t opt_index)
  2368. {
  2369. const PyWideStringList *cmdline_argv = &config->argv;
  2370. PyWideStringList config_argv = _PyWideStringList_INIT;
  2371. /* Copy argv to be able to modify it (to force -c/-m) */
  2372. if (cmdline_argv->length <= opt_index) {
  2373. /* Ensure at least one (empty) argument is seen */
  2374. PyStatus status = PyWideStringList_Append(&config_argv, L"");
  2375. if (_PyStatus_EXCEPTION(status)) {
  2376. return status;
  2377. }
  2378. }
  2379. else {
  2380. PyWideStringList slice;
  2381. slice.length = cmdline_argv->length - opt_index;
  2382. slice.items = &cmdline_argv->items[opt_index];
  2383. if (_PyWideStringList_Copy(&config_argv, &slice) < 0) {
  2384. return _PyStatus_NO_MEMORY();
  2385. }
  2386. }
  2387. assert(config_argv.length >= 1);
  2388. wchar_t *arg0 = NULL;
  2389. if (config->run_command != NULL) {
  2390. /* Force sys.argv[0] = '-c' */
  2391. arg0 = L"-c";
  2392. }
  2393. else if (config->run_module != NULL) {
  2394. /* Force sys.argv[0] = '-m'*/
  2395. arg0 = L"-m";
  2396. }
  2397. if (arg0 != NULL) {
  2398. arg0 = _PyMem_RawWcsdup(arg0);
  2399. if (arg0 == NULL) {
  2400. _PyWideStringList_Clear(&config_argv);
  2401. return _PyStatus_NO_MEMORY();
  2402. }
  2403. PyMem_RawFree(config_argv.items[0]);
  2404. config_argv.items[0] = arg0;
  2405. }
  2406. _PyWideStringList_Clear(&config->argv);
  2407. config->argv = config_argv;
  2408. return _PyStatus_OK();
  2409. }
  2410. static PyStatus
  2411. core_read_precmdline(PyConfig *config, _PyPreCmdline *precmdline)
  2412. {
  2413. PyStatus status;
  2414. if (config->parse_argv == 1) {
  2415. if (_PyWideStringList_Copy(&precmdline->argv, &config->argv) < 0) {
  2416. return _PyStatus_NO_MEMORY();
  2417. }
  2418. }
  2419. PyPreConfig preconfig;
  2420. status = _PyPreConfig_InitFromPreConfig(&preconfig, &_PyRuntime.preconfig);
  2421. if (_PyStatus_EXCEPTION(status)) {
  2422. return status;
  2423. }
  2424. _PyPreConfig_GetConfig(&preconfig, config);
  2425. status = _PyPreCmdline_Read(precmdline, &preconfig);
  2426. if (_PyStatus_EXCEPTION(status)) {
  2427. return status;
  2428. }
  2429. status = _PyPreCmdline_SetConfig(precmdline, config);
  2430. if (_PyStatus_EXCEPTION(status)) {
  2431. return status;
  2432. }
  2433. return _PyStatus_OK();
  2434. }
  2435. /* Get run_filename absolute path */
  2436. static PyStatus
  2437. config_run_filename_abspath(PyConfig *config)
  2438. {
  2439. if (!config->run_filename) {
  2440. return _PyStatus_OK();
  2441. }
  2442. #ifndef MS_WINDOWS
  2443. if (_Py_isabs(config->run_filename)) {
  2444. /* path is already absolute */
  2445. return _PyStatus_OK();
  2446. }
  2447. #endif
  2448. wchar_t *abs_filename;
  2449. if (_Py_abspath(config->run_filename, &abs_filename) < 0) {
  2450. /* failed to get the absolute path of the command line filename:
  2451. ignore the error, keep the relative path */
  2452. return _PyStatus_OK();
  2453. }
  2454. if (abs_filename == NULL) {
  2455. return _PyStatus_NO_MEMORY();
  2456. }
  2457. PyMem_RawFree(config->run_filename);
  2458. config->run_filename = abs_filename;
  2459. return _PyStatus_OK();
  2460. }
  2461. static PyStatus
  2462. config_read_cmdline(PyConfig *config)
  2463. {
  2464. PyStatus status;
  2465. PyWideStringList cmdline_warnoptions = _PyWideStringList_INIT;
  2466. PyWideStringList env_warnoptions = _PyWideStringList_INIT;
  2467. PyWideStringList sys_warnoptions = _PyWideStringList_INIT;
  2468. if (config->parse_argv < 0) {
  2469. config->parse_argv = 1;
  2470. }
  2471. if (config->parse_argv == 1) {
  2472. Py_ssize_t opt_index;
  2473. status = config_parse_cmdline(config, &cmdline_warnoptions, &opt_index);
  2474. if (_PyStatus_EXCEPTION(status)) {
  2475. goto done;
  2476. }
  2477. status = config_run_filename_abspath(config);
  2478. if (_PyStatus_EXCEPTION(status)) {
  2479. goto done;
  2480. }
  2481. status = config_update_argv(config, opt_index);
  2482. if (_PyStatus_EXCEPTION(status)) {
  2483. goto done;
  2484. }
  2485. }
  2486. else {
  2487. status = config_run_filename_abspath(config);
  2488. if (_PyStatus_EXCEPTION(status)) {
  2489. goto done;
  2490. }
  2491. }
  2492. if (config->use_environment) {
  2493. status = config_init_env_warnoptions(config, &env_warnoptions);
  2494. if (_PyStatus_EXCEPTION(status)) {
  2495. goto done;
  2496. }
  2497. }
  2498. /* Handle early PySys_AddWarnOption() calls */
  2499. status = _PySys_ReadPreinitWarnOptions(&sys_warnoptions);
  2500. if (_PyStatus_EXCEPTION(status)) {
  2501. goto done;
  2502. }
  2503. status = config_init_warnoptions(config,
  2504. &cmdline_warnoptions,
  2505. &env_warnoptions,
  2506. &sys_warnoptions);
  2507. if (_PyStatus_EXCEPTION(status)) {
  2508. goto done;
  2509. }
  2510. status = _PyStatus_OK();
  2511. done:
  2512. _PyWideStringList_Clear(&cmdline_warnoptions);
  2513. _PyWideStringList_Clear(&env_warnoptions);
  2514. _PyWideStringList_Clear(&sys_warnoptions);
  2515. return status;
  2516. }
  2517. PyStatus
  2518. _PyConfig_SetPyArgv(PyConfig *config, const _PyArgv *args)
  2519. {
  2520. PyStatus status = _Py_PreInitializeFromConfig(config, args);
  2521. if (_PyStatus_EXCEPTION(status)) {
  2522. return status;
  2523. }
  2524. return _PyArgv_AsWstrList(args, &config->argv);
  2525. }
  2526. /* Set config.argv: decode argv using Py_DecodeLocale(). Pre-initialize Python
  2527. if needed to ensure that encodings are properly configured. */
  2528. PyStatus
  2529. PyConfig_SetBytesArgv(PyConfig *config, Py_ssize_t argc, char * const *argv)
  2530. {
  2531. _PyArgv args = {
  2532. .argc = argc,
  2533. .use_bytes_argv = 1,
  2534. .bytes_argv = argv,
  2535. .wchar_argv = NULL};
  2536. return _PyConfig_SetPyArgv(config, &args);
  2537. }
  2538. PyStatus
  2539. PyConfig_SetArgv(PyConfig *config, Py_ssize_t argc, wchar_t * const *argv)
  2540. {
  2541. _PyArgv args = {
  2542. .argc = argc,
  2543. .use_bytes_argv = 0,
  2544. .bytes_argv = NULL,
  2545. .wchar_argv = argv};
  2546. return _PyConfig_SetPyArgv(config, &args);
  2547. }
  2548. PyStatus
  2549. PyConfig_SetWideStringList(PyConfig *config, PyWideStringList *list,
  2550. Py_ssize_t length, wchar_t **items)
  2551. {
  2552. PyStatus status = _Py_PreInitializeFromConfig(config, NULL);
  2553. if (_PyStatus_EXCEPTION(status)) {
  2554. return status;
  2555. }
  2556. PyWideStringList list2 = {.length = length, .items = items};
  2557. if (_PyWideStringList_Copy(list, &list2) < 0) {
  2558. return _PyStatus_NO_MEMORY();
  2559. }
  2560. return _PyStatus_OK();
  2561. }
  2562. /* Read the configuration into PyConfig from:
  2563. * Command line arguments
  2564. * Environment variables
  2565. * Py_xxx global configuration variables
  2566. The only side effects are to modify config and to call _Py_SetArgcArgv(). */
  2567. PyStatus
  2568. _PyConfig_Read(PyConfig *config, int compute_path_config)
  2569. {
  2570. PyStatus status;
  2571. status = _Py_PreInitializeFromConfig(config, NULL);
  2572. if (_PyStatus_EXCEPTION(status)) {
  2573. return status;
  2574. }
  2575. config_get_global_vars(config);
  2576. if (config->orig_argv.length == 0
  2577. && !(config->argv.length == 1
  2578. && wcscmp(config->argv.items[0], L"") == 0))
  2579. {
  2580. if (_PyWideStringList_Copy(&config->orig_argv, &config->argv) < 0) {
  2581. return _PyStatus_NO_MEMORY();
  2582. }
  2583. }
  2584. _PyPreCmdline precmdline = _PyPreCmdline_INIT;
  2585. status = core_read_precmdline(config, &precmdline);
  2586. if (_PyStatus_EXCEPTION(status)) {
  2587. goto done;
  2588. }
  2589. assert(config->isolated >= 0);
  2590. if (config->isolated) {
  2591. config->safe_path = 1;
  2592. config->use_environment = 0;
  2593. config->user_site_directory = 0;
  2594. }
  2595. status = config_read_cmdline(config);
  2596. if (_PyStatus_EXCEPTION(status)) {
  2597. goto done;
  2598. }
  2599. /* Handle early PySys_AddXOption() calls */
  2600. status = _PySys_ReadPreinitXOptions(config);
  2601. if (_PyStatus_EXCEPTION(status)) {
  2602. goto done;
  2603. }
  2604. status = config_read(config, compute_path_config);
  2605. if (_PyStatus_EXCEPTION(status)) {
  2606. goto done;
  2607. }
  2608. assert(config_check_consistency(config));
  2609. status = _PyStatus_OK();
  2610. done:
  2611. _PyPreCmdline_Clear(&precmdline);
  2612. return status;
  2613. }
  2614. PyStatus
  2615. PyConfig_Read(PyConfig *config)
  2616. {
  2617. return _PyConfig_Read(config, 0);
  2618. }
  2619. PyObject*
  2620. _Py_GetConfigsAsDict(void)
  2621. {
  2622. PyObject *result = NULL;
  2623. PyObject *dict = NULL;
  2624. result = PyDict_New();
  2625. if (result == NULL) {
  2626. goto error;
  2627. }
  2628. /* global result */
  2629. dict = _Py_GetGlobalVariablesAsDict();
  2630. if (dict == NULL) {
  2631. goto error;
  2632. }
  2633. if (PyDict_SetItemString(result, "global_config", dict) < 0) {
  2634. goto error;
  2635. }
  2636. Py_CLEAR(dict);
  2637. /* pre config */
  2638. PyInterpreterState *interp = _PyInterpreterState_GET();
  2639. const PyPreConfig *pre_config = &interp->runtime->preconfig;
  2640. dict = _PyPreConfig_AsDict(pre_config);
  2641. if (dict == NULL) {
  2642. goto error;
  2643. }
  2644. if (PyDict_SetItemString(result, "pre_config", dict) < 0) {
  2645. goto error;
  2646. }
  2647. Py_CLEAR(dict);
  2648. /* core config */
  2649. const PyConfig *config = _PyInterpreterState_GetConfig(interp);
  2650. dict = _PyConfig_AsDict(config);
  2651. if (dict == NULL) {
  2652. goto error;
  2653. }
  2654. if (PyDict_SetItemString(result, "config", dict) < 0) {
  2655. goto error;
  2656. }
  2657. Py_CLEAR(dict);
  2658. return result;
  2659. error:
  2660. Py_XDECREF(result);
  2661. Py_XDECREF(dict);
  2662. return NULL;
  2663. }
  2664. static void
  2665. init_dump_ascii_wstr(const wchar_t *str)
  2666. {
  2667. if (str == NULL) {
  2668. PySys_WriteStderr("(not set)");
  2669. return;
  2670. }
  2671. PySys_WriteStderr("'");
  2672. for (; *str != L'\0'; str++) {
  2673. unsigned int ch = (unsigned int)*str;
  2674. if (ch == L'\'') {
  2675. PySys_WriteStderr("\\'");
  2676. } else if (0x20 <= ch && ch < 0x7f) {
  2677. PySys_WriteStderr("%c", ch);
  2678. }
  2679. else if (ch <= 0xff) {
  2680. PySys_WriteStderr("\\x%02x", ch);
  2681. }
  2682. #if SIZEOF_WCHAR_T > 2
  2683. else if (ch > 0xffff) {
  2684. PySys_WriteStderr("\\U%08x", ch);
  2685. }
  2686. #endif
  2687. else {
  2688. PySys_WriteStderr("\\u%04x", ch);
  2689. }
  2690. }
  2691. PySys_WriteStderr("'");
  2692. }
  2693. /* Dump the Python path configuration into sys.stderr */
  2694. void
  2695. _Py_DumpPathConfig(PyThreadState *tstate)
  2696. {
  2697. PyObject *exc = _PyErr_GetRaisedException(tstate);
  2698. PySys_WriteStderr("Python path configuration:\n");
  2699. #define DUMP_CONFIG(NAME, FIELD) \
  2700. do { \
  2701. PySys_WriteStderr(" " NAME " = "); \
  2702. init_dump_ascii_wstr(config->FIELD); \
  2703. PySys_WriteStderr("\n"); \
  2704. } while (0)
  2705. const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
  2706. DUMP_CONFIG("PYTHONHOME", home);
  2707. DUMP_CONFIG("PYTHONPATH", pythonpath_env);
  2708. DUMP_CONFIG("program name", program_name);
  2709. PySys_WriteStderr(" isolated = %i\n", config->isolated);
  2710. PySys_WriteStderr(" environment = %i\n", config->use_environment);
  2711. PySys_WriteStderr(" user site = %i\n", config->user_site_directory);
  2712. PySys_WriteStderr(" safe_path = %i\n", config->safe_path);
  2713. PySys_WriteStderr(" import site = %i\n", config->site_import);
  2714. PySys_WriteStderr(" is in build tree = %i\n", config->_is_python_build);
  2715. DUMP_CONFIG("stdlib dir", stdlib_dir);
  2716. #undef DUMP_CONFIG
  2717. #define DUMP_SYS(NAME) \
  2718. do { \
  2719. obj = PySys_GetObject(#NAME); \
  2720. PySys_FormatStderr(" sys.%s = ", #NAME); \
  2721. if (obj != NULL) { \
  2722. PySys_FormatStderr("%A", obj); \
  2723. } \
  2724. else { \
  2725. PySys_WriteStderr("(not set)"); \
  2726. } \
  2727. PySys_FormatStderr("\n"); \
  2728. } while (0)
  2729. PyObject *obj;
  2730. DUMP_SYS(_base_executable);
  2731. DUMP_SYS(base_prefix);
  2732. DUMP_SYS(base_exec_prefix);
  2733. DUMP_SYS(platlibdir);
  2734. DUMP_SYS(executable);
  2735. DUMP_SYS(prefix);
  2736. DUMP_SYS(exec_prefix);
  2737. #undef DUMP_SYS
  2738. PyObject *sys_path = PySys_GetObject("path"); /* borrowed reference */
  2739. if (sys_path != NULL && PyList_Check(sys_path)) {
  2740. PySys_WriteStderr(" sys.path = [\n");
  2741. Py_ssize_t len = PyList_GET_SIZE(sys_path);
  2742. for (Py_ssize_t i=0; i < len; i++) {
  2743. PyObject *path = PyList_GET_ITEM(sys_path, i);
  2744. PySys_FormatStderr(" %A,\n", path);
  2745. }
  2746. PySys_WriteStderr(" ]\n");
  2747. }
  2748. _PyErr_SetRaisedException(tstate, exc);
  2749. }