initconfig.c 91 KB

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