sysmodule.c 107 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915
  1. /* System module */
  2. /*
  3. Various bits of information used by the interpreter are collected in
  4. module 'sys'.
  5. Function member:
  6. - exit(sts): raise SystemExit
  7. Data members:
  8. - stdin, stdout, stderr: standard file objects
  9. - modules: the table of modules (dictionary)
  10. - path: module search path (list of strings)
  11. - argv: script arguments (list of strings)
  12. - ps1, ps2: optional primary and secondary prompts (strings)
  13. */
  14. #include "Python.h"
  15. #include "pycore_call.h" // _PyObject_CallNoArgs()
  16. #include "pycore_ceval.h" // _PyEval_SetAsyncGenFinalizer()
  17. #include "pycore_frame.h" // _PyInterpreterFrame
  18. #include "pycore_initconfig.h" // _PyStatus_EXCEPTION()
  19. #include "pycore_long.h" // _PY_LONG_MAX_STR_DIGITS_THRESHOLD
  20. #include "pycore_namespace.h" // _PyNamespace_New()
  21. #include "pycore_object.h" // _PyObject_IS_GC()
  22. #include "pycore_pathconfig.h" // _PyPathConfig_ComputeSysPath0()
  23. #include "pycore_pyerrors.h" // _PyErr_GetRaisedException()
  24. #include "pycore_pylifecycle.h" // _PyErr_WriteUnraisableDefaultHook()
  25. #include "pycore_pymath.h" // _PY_SHORT_FLOAT_REPR
  26. #include "pycore_pymem.h" // _PyMem_SetDefaultAllocator()
  27. #include "pycore_pystate.h" // _PyThreadState_GET()
  28. #include "pycore_structseq.h" // _PyStructSequence_InitBuiltinWithFlags()
  29. #include "pycore_tuple.h" // _PyTuple_FromArray()
  30. #include "frameobject.h" // PyFrame_FastToLocalsWithError()
  31. #include "pydtrace.h"
  32. #include "osdefs.h" // DELIM
  33. #include "stdlib_module_names.h" // _Py_stdlib_module_names
  34. #include <locale.h>
  35. #ifdef MS_WINDOWS
  36. #define WIN32_LEAN_AND_MEAN
  37. #include <windows.h>
  38. #endif /* MS_WINDOWS */
  39. #ifdef MS_COREDLL
  40. extern void *PyWin_DLLhModule;
  41. /* A string loaded from the DLL at startup: */
  42. extern const char *PyWin_DLLVersionString;
  43. #endif
  44. #ifdef __EMSCRIPTEN__
  45. #error #include <emscripten.h>
  46. #endif
  47. #ifdef HAVE_FCNTL_H
  48. #include <fcntl.h>
  49. #endif
  50. /*[clinic input]
  51. module sys
  52. [clinic start generated code]*/
  53. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=3726b388feee8cea]*/
  54. #include "clinic/sysmodule.c.h"
  55. PyObject *
  56. _PySys_GetAttr(PyThreadState *tstate, PyObject *name)
  57. {
  58. PyObject *sd = tstate->interp->sysdict;
  59. if (sd == NULL) {
  60. return NULL;
  61. }
  62. PyObject *exc = _PyErr_GetRaisedException(tstate);
  63. /* XXX Suppress a new exception if it was raised and restore
  64. * the old one. */
  65. PyObject *value = _PyDict_GetItemWithError(sd, name);
  66. _PyErr_SetRaisedException(tstate, exc);
  67. return value;
  68. }
  69. static PyObject *
  70. _PySys_GetObject(PyInterpreterState *interp, const char *name)
  71. {
  72. PyObject *sysdict = interp->sysdict;
  73. if (sysdict == NULL) {
  74. return NULL;
  75. }
  76. return _PyDict_GetItemStringWithError(sysdict, name);
  77. }
  78. PyObject *
  79. PySys_GetObject(const char *name)
  80. {
  81. PyThreadState *tstate = _PyThreadState_GET();
  82. PyObject *exc = _PyErr_GetRaisedException(tstate);
  83. PyObject *value = _PySys_GetObject(tstate->interp, name);
  84. /* XXX Suppress a new exception if it was raised and restore
  85. * the old one. */
  86. _PyErr_SetRaisedException(tstate, exc);
  87. return value;
  88. }
  89. static int
  90. sys_set_object(PyInterpreterState *interp, PyObject *key, PyObject *v)
  91. {
  92. if (key == NULL) {
  93. return -1;
  94. }
  95. PyObject *sd = interp->sysdict;
  96. if (v == NULL) {
  97. v = _PyDict_Pop(sd, key, Py_None);
  98. if (v == NULL) {
  99. return -1;
  100. }
  101. Py_DECREF(v);
  102. return 0;
  103. }
  104. else {
  105. return PyDict_SetItem(sd, key, v);
  106. }
  107. }
  108. int
  109. _PySys_SetAttr(PyObject *key, PyObject *v)
  110. {
  111. PyInterpreterState *interp = _PyInterpreterState_GET();
  112. return sys_set_object(interp, key, v);
  113. }
  114. static int
  115. sys_set_object_str(PyInterpreterState *interp, const char *name, PyObject *v)
  116. {
  117. PyObject *key = v ? PyUnicode_InternFromString(name)
  118. : PyUnicode_FromString(name);
  119. int r = sys_set_object(interp, key, v);
  120. Py_XDECREF(key);
  121. return r;
  122. }
  123. int
  124. PySys_SetObject(const char *name, PyObject *v)
  125. {
  126. PyInterpreterState *interp = _PyInterpreterState_GET();
  127. return sys_set_object_str(interp, name, v);
  128. }
  129. int
  130. _PySys_ClearAttrString(PyInterpreterState *interp,
  131. const char *name, int verbose)
  132. {
  133. if (verbose) {
  134. PySys_WriteStderr("# clear sys.%s\n", name);
  135. }
  136. /* To play it safe, we set the attr to None instead of deleting it. */
  137. if (PyDict_SetItemString(interp->sysdict, name, Py_None) < 0) {
  138. return -1;
  139. }
  140. return 0;
  141. }
  142. static int
  143. should_audit(PyInterpreterState *interp)
  144. {
  145. /* interp must not be NULL, but test it just in case for extra safety */
  146. assert(interp != NULL);
  147. if (!interp) {
  148. return 0;
  149. }
  150. return (interp->runtime->audit_hooks.head
  151. || interp->audit_hooks
  152. || PyDTrace_AUDIT_ENABLED());
  153. }
  154. static int
  155. sys_audit_tstate(PyThreadState *ts, const char *event,
  156. const char *argFormat, va_list vargs)
  157. {
  158. /* N format is inappropriate, because you do not know
  159. whether the reference is consumed by the call.
  160. Assert rather than exception for perf reasons */
  161. assert(!argFormat || !strchr(argFormat, 'N'));
  162. if (!ts) {
  163. /* Audit hooks cannot be called with a NULL thread state */
  164. return 0;
  165. }
  166. /* The current implementation cannot be called if tstate is not
  167. the current Python thread state. */
  168. assert(ts == _PyThreadState_GET());
  169. /* Early exit when no hooks are registered */
  170. PyInterpreterState *is = ts->interp;
  171. if (!should_audit(is)) {
  172. return 0;
  173. }
  174. PyObject *eventName = NULL;
  175. PyObject *eventArgs = NULL;
  176. PyObject *hooks = NULL;
  177. PyObject *hook = NULL;
  178. int res = -1;
  179. int dtrace = PyDTrace_AUDIT_ENABLED();
  180. PyObject *exc = _PyErr_GetRaisedException(ts);
  181. /* Initialize event args now */
  182. if (argFormat && argFormat[0]) {
  183. eventArgs = _Py_VaBuildValue_SizeT(argFormat, vargs);
  184. if (eventArgs && !PyTuple_Check(eventArgs)) {
  185. PyObject *argTuple = PyTuple_Pack(1, eventArgs);
  186. Py_SETREF(eventArgs, argTuple);
  187. }
  188. }
  189. else {
  190. eventArgs = PyTuple_New(0);
  191. }
  192. if (!eventArgs) {
  193. goto exit;
  194. }
  195. /* Call global hooks
  196. *
  197. * We don't worry about any races on hooks getting added,
  198. * since that would not leave is in an inconsistent state. */
  199. _Py_AuditHookEntry *e = is->runtime->audit_hooks.head;
  200. for (; e; e = e->next) {
  201. if (e->hookCFunction(event, eventArgs, e->userData) < 0) {
  202. goto exit;
  203. }
  204. }
  205. /* Dtrace USDT point */
  206. if (dtrace) {
  207. PyDTrace_AUDIT(event, (void *)eventArgs);
  208. }
  209. /* Call interpreter hooks */
  210. if (is->audit_hooks) {
  211. eventName = PyUnicode_FromString(event);
  212. if (!eventName) {
  213. goto exit;
  214. }
  215. hooks = PyObject_GetIter(is->audit_hooks);
  216. if (!hooks) {
  217. goto exit;
  218. }
  219. /* Disallow tracing in hooks unless explicitly enabled */
  220. PyThreadState_EnterTracing(ts);
  221. while ((hook = PyIter_Next(hooks)) != NULL) {
  222. PyObject *o;
  223. int canTrace = _PyObject_LookupAttr(hook, &_Py_ID(__cantrace__), &o);
  224. if (o) {
  225. canTrace = PyObject_IsTrue(o);
  226. Py_DECREF(o);
  227. }
  228. if (canTrace < 0) {
  229. break;
  230. }
  231. if (canTrace) {
  232. PyThreadState_LeaveTracing(ts);
  233. }
  234. PyObject* args[2] = {eventName, eventArgs};
  235. o = _PyObject_FastCallTstate(ts, hook, args, 2);
  236. if (canTrace) {
  237. PyThreadState_EnterTracing(ts);
  238. }
  239. if (!o) {
  240. break;
  241. }
  242. Py_DECREF(o);
  243. Py_CLEAR(hook);
  244. }
  245. PyThreadState_LeaveTracing(ts);
  246. if (_PyErr_Occurred(ts)) {
  247. goto exit;
  248. }
  249. }
  250. res = 0;
  251. exit:
  252. Py_XDECREF(hook);
  253. Py_XDECREF(hooks);
  254. Py_XDECREF(eventName);
  255. Py_XDECREF(eventArgs);
  256. if (!res) {
  257. _PyErr_SetRaisedException(ts, exc);
  258. }
  259. else {
  260. assert(_PyErr_Occurred(ts));
  261. Py_XDECREF(exc);
  262. }
  263. return res;
  264. }
  265. int
  266. _PySys_Audit(PyThreadState *tstate, const char *event,
  267. const char *argFormat, ...)
  268. {
  269. va_list vargs;
  270. va_start(vargs, argFormat);
  271. int res = sys_audit_tstate(tstate, event, argFormat, vargs);
  272. va_end(vargs);
  273. return res;
  274. }
  275. int
  276. PySys_Audit(const char *event, const char *argFormat, ...)
  277. {
  278. PyThreadState *tstate = _PyThreadState_GET();
  279. va_list vargs;
  280. va_start(vargs, argFormat);
  281. int res = sys_audit_tstate(tstate, event, argFormat, vargs);
  282. va_end(vargs);
  283. return res;
  284. }
  285. /* We expose this function primarily for our own cleanup during
  286. * finalization. In general, it should not need to be called,
  287. * and as such the function is not exported.
  288. *
  289. * Must be finalizing to clear hooks */
  290. void
  291. _PySys_ClearAuditHooks(PyThreadState *ts)
  292. {
  293. assert(ts != NULL);
  294. if (!ts) {
  295. return;
  296. }
  297. _PyRuntimeState *runtime = ts->interp->runtime;
  298. /* The hooks are global so we have to check for runtime finalization. */
  299. PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(runtime);
  300. assert(finalizing == ts);
  301. if (finalizing != ts) {
  302. return;
  303. }
  304. const PyConfig *config = _PyInterpreterState_GetConfig(ts->interp);
  305. if (config->verbose) {
  306. PySys_WriteStderr("# clear sys.audit hooks\n");
  307. }
  308. /* Hooks can abort later hooks for this event, but cannot
  309. abort the clear operation itself. */
  310. _PySys_Audit(ts, "cpython._PySys_ClearAuditHooks", NULL);
  311. _PyErr_Clear(ts);
  312. /* We don't worry about the very unlikely race right here,
  313. * since it's entirely benign. Nothing else removes entries
  314. * from the list and adding an entry right now would not cause
  315. * any trouble. */
  316. _Py_AuditHookEntry *e = runtime->audit_hooks.head, *n;
  317. runtime->audit_hooks.head = NULL;
  318. while (e) {
  319. n = e->next;
  320. PyMem_RawFree(e);
  321. e = n;
  322. }
  323. }
  324. static void
  325. add_audit_hook_entry_unlocked(_PyRuntimeState *runtime,
  326. _Py_AuditHookEntry *entry)
  327. {
  328. if (runtime->audit_hooks.head == NULL) {
  329. runtime->audit_hooks.head = entry;
  330. }
  331. else {
  332. _Py_AuditHookEntry *last = runtime->audit_hooks.head;
  333. while (last->next) {
  334. last = last->next;
  335. }
  336. last->next = entry;
  337. }
  338. }
  339. int
  340. PySys_AddAuditHook(Py_AuditHookFunction hook, void *userData)
  341. {
  342. /* tstate can be NULL, so access directly _PyRuntime:
  343. PySys_AddAuditHook() can be called before Python is initialized. */
  344. _PyRuntimeState *runtime = &_PyRuntime;
  345. PyThreadState *tstate;
  346. if (runtime->initialized) {
  347. tstate = _PyThreadState_GET();
  348. }
  349. else {
  350. tstate = NULL;
  351. }
  352. /* Invoke existing audit hooks to allow them an opportunity to abort. */
  353. /* Cannot invoke hooks until we are initialized */
  354. if (tstate != NULL) {
  355. if (_PySys_Audit(tstate, "sys.addaudithook", NULL) < 0) {
  356. if (_PyErr_ExceptionMatches(tstate, PyExc_RuntimeError)) {
  357. /* We do not report errors derived from RuntimeError */
  358. _PyErr_Clear(tstate);
  359. return 0;
  360. }
  361. return -1;
  362. }
  363. }
  364. _Py_AuditHookEntry *e = (_Py_AuditHookEntry*)PyMem_RawMalloc(
  365. sizeof(_Py_AuditHookEntry));
  366. if (!e) {
  367. if (tstate != NULL) {
  368. _PyErr_NoMemory(tstate);
  369. }
  370. return -1;
  371. }
  372. e->next = NULL;
  373. e->hookCFunction = (Py_AuditHookFunction)hook;
  374. e->userData = userData;
  375. if (runtime->audit_hooks.mutex == NULL) {
  376. /* The runtime must not be initailized yet. */
  377. add_audit_hook_entry_unlocked(runtime, e);
  378. }
  379. else {
  380. PyThread_acquire_lock(runtime->audit_hooks.mutex, WAIT_LOCK);
  381. add_audit_hook_entry_unlocked(runtime, e);
  382. PyThread_release_lock(runtime->audit_hooks.mutex);
  383. }
  384. return 0;
  385. }
  386. /*[clinic input]
  387. sys.addaudithook
  388. hook: object
  389. Adds a new audit hook callback.
  390. [clinic start generated code]*/
  391. static PyObject *
  392. sys_addaudithook_impl(PyObject *module, PyObject *hook)
  393. /*[clinic end generated code: output=4f9c17aaeb02f44e input=0f3e191217a45e34]*/
  394. {
  395. PyThreadState *tstate = _PyThreadState_GET();
  396. /* Invoke existing audit hooks to allow them an opportunity to abort. */
  397. if (_PySys_Audit(tstate, "sys.addaudithook", NULL) < 0) {
  398. if (_PyErr_ExceptionMatches(tstate, PyExc_Exception)) {
  399. /* We do not report errors derived from Exception */
  400. _PyErr_Clear(tstate);
  401. Py_RETURN_NONE;
  402. }
  403. return NULL;
  404. }
  405. PyInterpreterState *interp = tstate->interp;
  406. if (interp->audit_hooks == NULL) {
  407. interp->audit_hooks = PyList_New(0);
  408. if (interp->audit_hooks == NULL) {
  409. return NULL;
  410. }
  411. /* Avoid having our list of hooks show up in the GC module */
  412. PyObject_GC_UnTrack(interp->audit_hooks);
  413. }
  414. if (PyList_Append(interp->audit_hooks, hook) < 0) {
  415. return NULL;
  416. }
  417. Py_RETURN_NONE;
  418. }
  419. PyDoc_STRVAR(audit_doc,
  420. "audit(event, *args)\n\
  421. \n\
  422. Passes the event to any audit hooks that are attached.");
  423. static PyObject *
  424. sys_audit(PyObject *self, PyObject *const *args, Py_ssize_t argc)
  425. {
  426. PyThreadState *tstate = _PyThreadState_GET();
  427. _Py_EnsureTstateNotNULL(tstate);
  428. if (argc == 0) {
  429. _PyErr_SetString(tstate, PyExc_TypeError,
  430. "audit() missing 1 required positional argument: "
  431. "'event'");
  432. return NULL;
  433. }
  434. if (!should_audit(tstate->interp)) {
  435. Py_RETURN_NONE;
  436. }
  437. PyObject *auditEvent = args[0];
  438. if (!auditEvent) {
  439. _PyErr_SetString(tstate, PyExc_TypeError,
  440. "expected str for argument 'event'");
  441. return NULL;
  442. }
  443. if (!PyUnicode_Check(auditEvent)) {
  444. _PyErr_Format(tstate, PyExc_TypeError,
  445. "expected str for argument 'event', not %.200s",
  446. Py_TYPE(auditEvent)->tp_name);
  447. return NULL;
  448. }
  449. const char *event = PyUnicode_AsUTF8(auditEvent);
  450. if (!event) {
  451. return NULL;
  452. }
  453. PyObject *auditArgs = _PyTuple_FromArray(args + 1, argc - 1);
  454. if (!auditArgs) {
  455. return NULL;
  456. }
  457. int res = _PySys_Audit(tstate, event, "O", auditArgs);
  458. Py_DECREF(auditArgs);
  459. if (res < 0) {
  460. return NULL;
  461. }
  462. Py_RETURN_NONE;
  463. }
  464. static PyObject *
  465. sys_breakpointhook(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
  466. {
  467. PyThreadState *tstate = _PyThreadState_GET();
  468. assert(!_PyErr_Occurred(tstate));
  469. char *envar = Py_GETENV("PYTHONBREAKPOINT");
  470. if (envar == NULL || strlen(envar) == 0) {
  471. envar = "pdb.set_trace";
  472. }
  473. else if (!strcmp(envar, "0")) {
  474. /* The breakpoint is explicitly no-op'd. */
  475. Py_RETURN_NONE;
  476. }
  477. /* According to POSIX the string returned by getenv() might be invalidated
  478. * or the string content might be overwritten by a subsequent call to
  479. * getenv(). Since importing a module can performs the getenv() calls,
  480. * we need to save a copy of envar. */
  481. envar = _PyMem_RawStrdup(envar);
  482. if (envar == NULL) {
  483. _PyErr_NoMemory(tstate);
  484. return NULL;
  485. }
  486. const char *last_dot = strrchr(envar, '.');
  487. const char *attrname = NULL;
  488. PyObject *modulepath = NULL;
  489. if (last_dot == NULL) {
  490. /* The breakpoint is a built-in, e.g. PYTHONBREAKPOINT=int */
  491. modulepath = PyUnicode_FromString("builtins");
  492. attrname = envar;
  493. }
  494. else if (last_dot != envar) {
  495. /* Split on the last dot; */
  496. modulepath = PyUnicode_FromStringAndSize(envar, last_dot - envar);
  497. attrname = last_dot + 1;
  498. }
  499. else {
  500. goto warn;
  501. }
  502. if (modulepath == NULL) {
  503. PyMem_RawFree(envar);
  504. return NULL;
  505. }
  506. PyObject *module = PyImport_Import(modulepath);
  507. Py_DECREF(modulepath);
  508. if (module == NULL) {
  509. if (_PyErr_ExceptionMatches(tstate, PyExc_ImportError)) {
  510. goto warn;
  511. }
  512. PyMem_RawFree(envar);
  513. return NULL;
  514. }
  515. PyObject *hook = PyObject_GetAttrString(module, attrname);
  516. Py_DECREF(module);
  517. if (hook == NULL) {
  518. if (_PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
  519. goto warn;
  520. }
  521. PyMem_RawFree(envar);
  522. return NULL;
  523. }
  524. PyMem_RawFree(envar);
  525. PyObject *retval = PyObject_Vectorcall(hook, args, nargs, keywords);
  526. Py_DECREF(hook);
  527. return retval;
  528. warn:
  529. /* If any of the imports went wrong, then warn and ignore. */
  530. _PyErr_Clear(tstate);
  531. int status = PyErr_WarnFormat(
  532. PyExc_RuntimeWarning, 0,
  533. "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar);
  534. PyMem_RawFree(envar);
  535. if (status < 0) {
  536. /* Printing the warning raised an exception. */
  537. return NULL;
  538. }
  539. /* The warning was (probably) issued. */
  540. Py_RETURN_NONE;
  541. }
  542. PyDoc_STRVAR(breakpointhook_doc,
  543. "breakpointhook(*args, **kws)\n"
  544. "\n"
  545. "This hook function is called by built-in breakpoint().\n"
  546. );
  547. /* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
  548. error handler. If sys.stdout has a buffer attribute, use
  549. sys.stdout.buffer.write(encoded), otherwise redecode the string and use
  550. sys.stdout.write(redecoded).
  551. Helper function for sys_displayhook(). */
  552. static int
  553. sys_displayhook_unencodable(PyObject *outf, PyObject *o)
  554. {
  555. PyObject *stdout_encoding = NULL;
  556. PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
  557. const char *stdout_encoding_str;
  558. int ret;
  559. stdout_encoding = PyObject_GetAttr(outf, &_Py_ID(encoding));
  560. if (stdout_encoding == NULL)
  561. goto error;
  562. stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
  563. if (stdout_encoding_str == NULL)
  564. goto error;
  565. repr_str = PyObject_Repr(o);
  566. if (repr_str == NULL)
  567. goto error;
  568. encoded = PyUnicode_AsEncodedString(repr_str,
  569. stdout_encoding_str,
  570. "backslashreplace");
  571. Py_DECREF(repr_str);
  572. if (encoded == NULL)
  573. goto error;
  574. if (_PyObject_LookupAttr(outf, &_Py_ID(buffer), &buffer) < 0) {
  575. Py_DECREF(encoded);
  576. goto error;
  577. }
  578. if (buffer) {
  579. result = PyObject_CallMethodOneArg(buffer, &_Py_ID(write), encoded);
  580. Py_DECREF(buffer);
  581. Py_DECREF(encoded);
  582. if (result == NULL)
  583. goto error;
  584. Py_DECREF(result);
  585. }
  586. else {
  587. escaped_str = PyUnicode_FromEncodedObject(encoded,
  588. stdout_encoding_str,
  589. "strict");
  590. Py_DECREF(encoded);
  591. if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
  592. Py_DECREF(escaped_str);
  593. goto error;
  594. }
  595. Py_DECREF(escaped_str);
  596. }
  597. ret = 0;
  598. goto finally;
  599. error:
  600. ret = -1;
  601. finally:
  602. Py_XDECREF(stdout_encoding);
  603. return ret;
  604. }
  605. /*[clinic input]
  606. sys.displayhook
  607. object as o: object
  608. /
  609. Print an object to sys.stdout and also save it in builtins._
  610. [clinic start generated code]*/
  611. static PyObject *
  612. sys_displayhook(PyObject *module, PyObject *o)
  613. /*[clinic end generated code: output=347477d006df92ed input=08ba730166d7ef72]*/
  614. {
  615. PyObject *outf;
  616. PyObject *builtins;
  617. PyThreadState *tstate = _PyThreadState_GET();
  618. builtins = PyImport_GetModule(&_Py_ID(builtins));
  619. if (builtins == NULL) {
  620. if (!_PyErr_Occurred(tstate)) {
  621. _PyErr_SetString(tstate, PyExc_RuntimeError,
  622. "lost builtins module");
  623. }
  624. return NULL;
  625. }
  626. Py_DECREF(builtins);
  627. /* Print value except if None */
  628. /* After printing, also assign to '_' */
  629. /* Before, set '_' to None to avoid recursion */
  630. if (o == Py_None) {
  631. Py_RETURN_NONE;
  632. }
  633. if (PyObject_SetAttr(builtins, &_Py_ID(_), Py_None) != 0)
  634. return NULL;
  635. outf = _PySys_GetAttr(tstate, &_Py_ID(stdout));
  636. if (outf == NULL || outf == Py_None) {
  637. _PyErr_SetString(tstate, PyExc_RuntimeError, "lost sys.stdout");
  638. return NULL;
  639. }
  640. if (PyFile_WriteObject(o, outf, 0) != 0) {
  641. if (_PyErr_ExceptionMatches(tstate, PyExc_UnicodeEncodeError)) {
  642. int err;
  643. /* repr(o) is not encodable to sys.stdout.encoding with
  644. * sys.stdout.errors error handler (which is probably 'strict') */
  645. _PyErr_Clear(tstate);
  646. err = sys_displayhook_unencodable(outf, o);
  647. if (err) {
  648. return NULL;
  649. }
  650. }
  651. else {
  652. return NULL;
  653. }
  654. }
  655. _Py_DECLARE_STR(newline, "\n");
  656. if (PyFile_WriteObject(&_Py_STR(newline), outf, Py_PRINT_RAW) != 0)
  657. return NULL;
  658. if (PyObject_SetAttr(builtins, &_Py_ID(_), o) != 0)
  659. return NULL;
  660. Py_RETURN_NONE;
  661. }
  662. /*[clinic input]
  663. sys.excepthook
  664. exctype: object
  665. value: object
  666. traceback: object
  667. /
  668. Handle an exception by displaying it with a traceback on sys.stderr.
  669. [clinic start generated code]*/
  670. static PyObject *
  671. sys_excepthook_impl(PyObject *module, PyObject *exctype, PyObject *value,
  672. PyObject *traceback)
  673. /*[clinic end generated code: output=18d99fdda21b6b5e input=ecf606fa826f19d9]*/
  674. {
  675. PyErr_Display(NULL, value, traceback);
  676. Py_RETURN_NONE;
  677. }
  678. /*[clinic input]
  679. sys.exception
  680. Return the current exception.
  681. Return the most recent exception caught by an except clause
  682. in the current stack frame or in an older stack frame, or None
  683. if no such exception exists.
  684. [clinic start generated code]*/
  685. static PyObject *
  686. sys_exception_impl(PyObject *module)
  687. /*[clinic end generated code: output=2381ee2f25953e40 input=c88fbb94b6287431]*/
  688. {
  689. _PyErr_StackItem *err_info = _PyErr_GetTopmostException(_PyThreadState_GET());
  690. if (err_info->exc_value != NULL) {
  691. return Py_NewRef(err_info->exc_value);
  692. }
  693. Py_RETURN_NONE;
  694. }
  695. /*[clinic input]
  696. sys.exc_info
  697. Return current exception information: (type, value, traceback).
  698. Return information about the most recent exception caught by an except
  699. clause in the current stack frame or in an older stack frame.
  700. [clinic start generated code]*/
  701. static PyObject *
  702. sys_exc_info_impl(PyObject *module)
  703. /*[clinic end generated code: output=3afd0940cf3a4d30 input=b5c5bf077788a3e5]*/
  704. {
  705. _PyErr_StackItem *err_info = _PyErr_GetTopmostException(_PyThreadState_GET());
  706. return _PyErr_StackItemToExcInfoTuple(err_info);
  707. }
  708. /*[clinic input]
  709. sys.unraisablehook
  710. unraisable: object
  711. /
  712. Handle an unraisable exception.
  713. The unraisable argument has the following attributes:
  714. * exc_type: Exception type.
  715. * exc_value: Exception value, can be None.
  716. * exc_traceback: Exception traceback, can be None.
  717. * err_msg: Error message, can be None.
  718. * object: Object causing the exception, can be None.
  719. [clinic start generated code]*/
  720. static PyObject *
  721. sys_unraisablehook(PyObject *module, PyObject *unraisable)
  722. /*[clinic end generated code: output=bb92838b32abaa14 input=ec3af148294af8d3]*/
  723. {
  724. return _PyErr_WriteUnraisableDefaultHook(unraisable);
  725. }
  726. /*[clinic input]
  727. sys.exit
  728. status: object = None
  729. /
  730. Exit the interpreter by raising SystemExit(status).
  731. If the status is omitted or None, it defaults to zero (i.e., success).
  732. If the status is an integer, it will be used as the system exit status.
  733. If it is another kind of object, it will be printed and the system
  734. exit status will be one (i.e., failure).
  735. [clinic start generated code]*/
  736. static PyObject *
  737. sys_exit_impl(PyObject *module, PyObject *status)
  738. /*[clinic end generated code: output=13870986c1ab2ec0 input=b86ca9497baa94f2]*/
  739. {
  740. /* Raise SystemExit so callers may catch it or clean up. */
  741. PyErr_SetObject(PyExc_SystemExit, status);
  742. return NULL;
  743. }
  744. /*[clinic input]
  745. sys.getdefaultencoding
  746. Return the current default encoding used by the Unicode implementation.
  747. [clinic start generated code]*/
  748. static PyObject *
  749. sys_getdefaultencoding_impl(PyObject *module)
  750. /*[clinic end generated code: output=256d19dfcc0711e6 input=d416856ddbef6909]*/
  751. {
  752. _Py_DECLARE_STR(utf_8, "utf-8");
  753. PyObject *ret = &_Py_STR(utf_8);
  754. return Py_NewRef(ret);
  755. }
  756. /*[clinic input]
  757. sys.getfilesystemencoding
  758. Return the encoding used to convert Unicode filenames to OS filenames.
  759. [clinic start generated code]*/
  760. static PyObject *
  761. sys_getfilesystemencoding_impl(PyObject *module)
  762. /*[clinic end generated code: output=1dc4bdbe9be44aa7 input=8475f8649b8c7d8c]*/
  763. {
  764. PyInterpreterState *interp = _PyInterpreterState_GET();
  765. const PyConfig *config = _PyInterpreterState_GetConfig(interp);
  766. return PyUnicode_FromWideChar(config->filesystem_encoding, -1);
  767. }
  768. /*[clinic input]
  769. sys.getfilesystemencodeerrors
  770. Return the error mode used Unicode to OS filename conversion.
  771. [clinic start generated code]*/
  772. static PyObject *
  773. sys_getfilesystemencodeerrors_impl(PyObject *module)
  774. /*[clinic end generated code: output=ba77b36bbf7c96f5 input=22a1e8365566f1e5]*/
  775. {
  776. PyInterpreterState *interp = _PyInterpreterState_GET();
  777. const PyConfig *config = _PyInterpreterState_GetConfig(interp);
  778. return PyUnicode_FromWideChar(config->filesystem_errors, -1);
  779. }
  780. /*[clinic input]
  781. sys.intern
  782. string as s: unicode
  783. /
  784. ``Intern'' the given string.
  785. This enters the string in the (global) table of interned strings whose
  786. purpose is to speed up dictionary lookups. Return the string itself or
  787. the previously interned string object with the same value.
  788. [clinic start generated code]*/
  789. static PyObject *
  790. sys_intern_impl(PyObject *module, PyObject *s)
  791. /*[clinic end generated code: output=be680c24f5c9e5d6 input=849483c006924e2f]*/
  792. {
  793. if (PyUnicode_CheckExact(s)) {
  794. Py_INCREF(s);
  795. PyUnicode_InternInPlace(&s);
  796. return s;
  797. }
  798. else {
  799. PyErr_Format(PyExc_TypeError,
  800. "can't intern %.400s", Py_TYPE(s)->tp_name);
  801. return NULL;
  802. }
  803. }
  804. /*
  805. * Cached interned string objects used for calling the profile and
  806. * trace functions.
  807. */
  808. static PyObject *whatstrings[8] = {
  809. &_Py_ID(call),
  810. &_Py_ID(exception),
  811. &_Py_ID(line),
  812. &_Py_ID(return),
  813. &_Py_ID(c_call),
  814. &_Py_ID(c_exception),
  815. &_Py_ID(c_return),
  816. &_Py_ID(opcode),
  817. };
  818. static PyObject *
  819. call_trampoline(PyThreadState *tstate, PyObject* callback,
  820. PyFrameObject *frame, int what, PyObject *arg)
  821. {
  822. PyObject *stack[3];
  823. stack[0] = (PyObject *)frame;
  824. stack[1] = whatstrings[what];
  825. stack[2] = (arg != NULL) ? arg : Py_None;
  826. /* Discard any previous modifications the frame's fast locals */
  827. if (frame->f_fast_as_locals) {
  828. if (PyFrame_FastToLocalsWithError(frame) < 0) {
  829. return NULL;
  830. }
  831. }
  832. /* call the Python-level function */
  833. PyObject *result = _PyObject_FastCallTstate(tstate, callback, stack, 3);
  834. PyFrame_LocalsToFast(frame, 1);
  835. return result;
  836. }
  837. static int
  838. profile_trampoline(PyObject *self, PyFrameObject *frame,
  839. int what, PyObject *arg)
  840. {
  841. PyThreadState *tstate = _PyThreadState_GET();
  842. PyObject *result = call_trampoline(tstate, self, frame, what, arg);
  843. if (result == NULL) {
  844. _PyEval_SetProfile(tstate, NULL, NULL);
  845. return -1;
  846. }
  847. Py_DECREF(result);
  848. return 0;
  849. }
  850. static int
  851. trace_trampoline(PyObject *self, PyFrameObject *frame,
  852. int what, PyObject *arg)
  853. {
  854. PyObject *callback;
  855. if (what == PyTrace_CALL) {
  856. callback = self;
  857. }
  858. else {
  859. callback = frame->f_trace;
  860. }
  861. if (callback == NULL) {
  862. return 0;
  863. }
  864. PyThreadState *tstate = _PyThreadState_GET();
  865. PyObject *result = call_trampoline(tstate, callback, frame, what, arg);
  866. if (result == NULL) {
  867. _PyEval_SetTrace(tstate, NULL, NULL);
  868. Py_CLEAR(frame->f_trace);
  869. return -1;
  870. }
  871. if (result != Py_None) {
  872. Py_XSETREF(frame->f_trace, result);
  873. }
  874. else {
  875. Py_DECREF(result);
  876. }
  877. return 0;
  878. }
  879. static PyObject *
  880. sys_settrace(PyObject *self, PyObject *args)
  881. {
  882. PyThreadState *tstate = _PyThreadState_GET();
  883. if (args == Py_None) {
  884. if (_PyEval_SetTrace(tstate, NULL, NULL) < 0) {
  885. return NULL;
  886. }
  887. }
  888. else {
  889. if (_PyEval_SetTrace(tstate, trace_trampoline, args) < 0) {
  890. return NULL;
  891. }
  892. }
  893. Py_RETURN_NONE;
  894. }
  895. PyDoc_STRVAR(settrace_doc,
  896. "settrace(function)\n\
  897. \n\
  898. Set the global debug tracing function. It will be called on each\n\
  899. function call. See the debugger chapter in the library manual."
  900. );
  901. /*[clinic input]
  902. sys._settraceallthreads
  903. arg: object
  904. /
  905. Set the global debug tracing function in all running threads belonging to the current interpreter.
  906. It will be called on each function call. See the debugger chapter
  907. in the library manual.
  908. [clinic start generated code]*/
  909. static PyObject *
  910. sys__settraceallthreads(PyObject *module, PyObject *arg)
  911. /*[clinic end generated code: output=161cca30207bf3ca input=5906aa1485a50289]*/
  912. {
  913. PyObject* argument = NULL;
  914. Py_tracefunc func = NULL;
  915. if (arg != Py_None) {
  916. func = trace_trampoline;
  917. argument = arg;
  918. }
  919. PyEval_SetTraceAllThreads(func, argument);
  920. Py_RETURN_NONE;
  921. }
  922. /*[clinic input]
  923. sys.gettrace
  924. Return the global debug tracing function set with sys.settrace.
  925. See the debugger chapter in the library manual.
  926. [clinic start generated code]*/
  927. static PyObject *
  928. sys_gettrace_impl(PyObject *module)
  929. /*[clinic end generated code: output=e97e3a4d8c971b6e input=373b51bb2147f4d8]*/
  930. {
  931. PyThreadState *tstate = _PyThreadState_GET();
  932. PyObject *temp = tstate->c_traceobj;
  933. if (temp == NULL)
  934. temp = Py_None;
  935. return Py_NewRef(temp);
  936. }
  937. static PyObject *
  938. sys_setprofile(PyObject *self, PyObject *args)
  939. {
  940. PyThreadState *tstate = _PyThreadState_GET();
  941. if (args == Py_None) {
  942. if (_PyEval_SetProfile(tstate, NULL, NULL) < 0) {
  943. return NULL;
  944. }
  945. }
  946. else {
  947. if (_PyEval_SetProfile(tstate, profile_trampoline, args) < 0) {
  948. return NULL;
  949. }
  950. }
  951. Py_RETURN_NONE;
  952. }
  953. PyDoc_STRVAR(setprofile_doc,
  954. "setprofile(function)\n\
  955. \n\
  956. Set the profiling function. It will be called on each function call\n\
  957. and return. See the profiler chapter in the library manual."
  958. );
  959. /*[clinic input]
  960. sys._setprofileallthreads
  961. arg: object
  962. /
  963. Set the profiling function in all running threads belonging to the current interpreter.
  964. It will be called on each function call and return. See the profiler chapter
  965. in the library manual.
  966. [clinic start generated code]*/
  967. static PyObject *
  968. sys__setprofileallthreads(PyObject *module, PyObject *arg)
  969. /*[clinic end generated code: output=2d61319e27b309fe input=d1a356d3f4f9060a]*/
  970. {
  971. PyObject* argument = NULL;
  972. Py_tracefunc func = NULL;
  973. if (arg != Py_None) {
  974. func = profile_trampoline;
  975. argument = arg;
  976. }
  977. PyEval_SetProfileAllThreads(func, argument);
  978. Py_RETURN_NONE;
  979. }
  980. /*[clinic input]
  981. sys.getprofile
  982. Return the profiling function set with sys.setprofile.
  983. See the profiler chapter in the library manual.
  984. [clinic start generated code]*/
  985. static PyObject *
  986. sys_getprofile_impl(PyObject *module)
  987. /*[clinic end generated code: output=579b96b373448188 input=1b3209d89a32965d]*/
  988. {
  989. PyThreadState *tstate = _PyThreadState_GET();
  990. PyObject *temp = tstate->c_profileobj;
  991. if (temp == NULL)
  992. temp = Py_None;
  993. return Py_NewRef(temp);
  994. }
  995. /*[clinic input]
  996. sys.setswitchinterval
  997. interval: double
  998. /
  999. Set the ideal thread switching delay inside the Python interpreter.
  1000. The actual frequency of switching threads can be lower if the
  1001. interpreter executes long sequences of uninterruptible code
  1002. (this is implementation-specific and workload-dependent).
  1003. The parameter must represent the desired switching delay in seconds
  1004. A typical value is 0.005 (5 milliseconds).
  1005. [clinic start generated code]*/
  1006. static PyObject *
  1007. sys_setswitchinterval_impl(PyObject *module, double interval)
  1008. /*[clinic end generated code: output=65a19629e5153983 input=561b477134df91d9]*/
  1009. {
  1010. if (interval <= 0.0) {
  1011. PyErr_SetString(PyExc_ValueError,
  1012. "switch interval must be strictly positive");
  1013. return NULL;
  1014. }
  1015. _PyEval_SetSwitchInterval((unsigned long) (1e6 * interval));
  1016. Py_RETURN_NONE;
  1017. }
  1018. /*[clinic input]
  1019. sys.getswitchinterval -> double
  1020. Return the current thread switch interval; see sys.setswitchinterval().
  1021. [clinic start generated code]*/
  1022. static double
  1023. sys_getswitchinterval_impl(PyObject *module)
  1024. /*[clinic end generated code: output=a38c277c85b5096d input=bdf9d39c0ebbbb6f]*/
  1025. {
  1026. return 1e-6 * _PyEval_GetSwitchInterval();
  1027. }
  1028. /*[clinic input]
  1029. sys.setrecursionlimit
  1030. limit as new_limit: int
  1031. /
  1032. Set the maximum depth of the Python interpreter stack to n.
  1033. This limit prevents infinite recursion from causing an overflow of the C
  1034. stack and crashing Python. The highest possible limit is platform-
  1035. dependent.
  1036. [clinic start generated code]*/
  1037. static PyObject *
  1038. sys_setrecursionlimit_impl(PyObject *module, int new_limit)
  1039. /*[clinic end generated code: output=35e1c64754800ace input=b0f7a23393924af3]*/
  1040. {
  1041. PyThreadState *tstate = _PyThreadState_GET();
  1042. if (new_limit < 1) {
  1043. _PyErr_SetString(tstate, PyExc_ValueError,
  1044. "recursion limit must be greater or equal than 1");
  1045. return NULL;
  1046. }
  1047. /* Reject too low new limit if the current recursion depth is higher than
  1048. the new low-water mark. */
  1049. int depth = tstate->py_recursion_limit - tstate->py_recursion_remaining;
  1050. if (depth >= new_limit) {
  1051. _PyErr_Format(tstate, PyExc_RecursionError,
  1052. "cannot set the recursion limit to %i at "
  1053. "the recursion depth %i: the limit is too low",
  1054. new_limit, depth);
  1055. return NULL;
  1056. }
  1057. Py_SetRecursionLimit(new_limit);
  1058. Py_RETURN_NONE;
  1059. }
  1060. /*[clinic input]
  1061. sys.set_coroutine_origin_tracking_depth
  1062. depth: int
  1063. Enable or disable origin tracking for coroutine objects in this thread.
  1064. Coroutine objects will track 'depth' frames of traceback information
  1065. about where they came from, available in their cr_origin attribute.
  1066. Set a depth of 0 to disable.
  1067. [clinic start generated code]*/
  1068. static PyObject *
  1069. sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth)
  1070. /*[clinic end generated code: output=0a2123c1cc6759c5 input=a1d0a05f89d2c426]*/
  1071. {
  1072. if (_PyEval_SetCoroutineOriginTrackingDepth(depth) < 0) {
  1073. return NULL;
  1074. }
  1075. Py_RETURN_NONE;
  1076. }
  1077. /*[clinic input]
  1078. sys.get_coroutine_origin_tracking_depth -> int
  1079. Check status of origin tracking for coroutine objects in this thread.
  1080. [clinic start generated code]*/
  1081. static int
  1082. sys_get_coroutine_origin_tracking_depth_impl(PyObject *module)
  1083. /*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/
  1084. {
  1085. return _PyEval_GetCoroutineOriginTrackingDepth();
  1086. }
  1087. static PyTypeObject AsyncGenHooksType;
  1088. PyDoc_STRVAR(asyncgen_hooks_doc,
  1089. "asyncgen_hooks\n\
  1090. \n\
  1091. A named tuple providing information about asynchronous\n\
  1092. generators hooks. The attributes are read only.");
  1093. static PyStructSequence_Field asyncgen_hooks_fields[] = {
  1094. {"firstiter", "Hook to intercept first iteration"},
  1095. {"finalizer", "Hook to intercept finalization"},
  1096. {0}
  1097. };
  1098. static PyStructSequence_Desc asyncgen_hooks_desc = {
  1099. "asyncgen_hooks", /* name */
  1100. asyncgen_hooks_doc, /* doc */
  1101. asyncgen_hooks_fields , /* fields */
  1102. 2
  1103. };
  1104. static PyObject *
  1105. sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
  1106. {
  1107. static char *keywords[] = {"firstiter", "finalizer", NULL};
  1108. PyObject *firstiter = NULL;
  1109. PyObject *finalizer = NULL;
  1110. if (!PyArg_ParseTupleAndKeywords(
  1111. args, kw, "|OO", keywords,
  1112. &firstiter, &finalizer)) {
  1113. return NULL;
  1114. }
  1115. if (finalizer && finalizer != Py_None) {
  1116. if (!PyCallable_Check(finalizer)) {
  1117. PyErr_Format(PyExc_TypeError,
  1118. "callable finalizer expected, got %.50s",
  1119. Py_TYPE(finalizer)->tp_name);
  1120. return NULL;
  1121. }
  1122. if (_PyEval_SetAsyncGenFinalizer(finalizer) < 0) {
  1123. return NULL;
  1124. }
  1125. }
  1126. else if (finalizer == Py_None && _PyEval_SetAsyncGenFinalizer(NULL) < 0) {
  1127. return NULL;
  1128. }
  1129. if (firstiter && firstiter != Py_None) {
  1130. if (!PyCallable_Check(firstiter)) {
  1131. PyErr_Format(PyExc_TypeError,
  1132. "callable firstiter expected, got %.50s",
  1133. Py_TYPE(firstiter)->tp_name);
  1134. return NULL;
  1135. }
  1136. if (_PyEval_SetAsyncGenFirstiter(firstiter) < 0) {
  1137. return NULL;
  1138. }
  1139. }
  1140. else if (firstiter == Py_None && _PyEval_SetAsyncGenFirstiter(NULL) < 0) {
  1141. return NULL;
  1142. }
  1143. Py_RETURN_NONE;
  1144. }
  1145. PyDoc_STRVAR(set_asyncgen_hooks_doc,
  1146. "set_asyncgen_hooks([firstiter] [, finalizer])\n\
  1147. \n\
  1148. Set a finalizer for async generators objects."
  1149. );
  1150. /*[clinic input]
  1151. sys.get_asyncgen_hooks
  1152. Return the installed asynchronous generators hooks.
  1153. This returns a namedtuple of the form (firstiter, finalizer).
  1154. [clinic start generated code]*/
  1155. static PyObject *
  1156. sys_get_asyncgen_hooks_impl(PyObject *module)
  1157. /*[clinic end generated code: output=53a253707146f6cf input=3676b9ea62b14625]*/
  1158. {
  1159. PyObject *res;
  1160. PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
  1161. PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
  1162. res = PyStructSequence_New(&AsyncGenHooksType);
  1163. if (res == NULL) {
  1164. return NULL;
  1165. }
  1166. if (firstiter == NULL) {
  1167. firstiter = Py_None;
  1168. }
  1169. if (finalizer == NULL) {
  1170. finalizer = Py_None;
  1171. }
  1172. PyStructSequence_SET_ITEM(res, 0, Py_NewRef(firstiter));
  1173. PyStructSequence_SET_ITEM(res, 1, Py_NewRef(finalizer));
  1174. return res;
  1175. }
  1176. static PyTypeObject Hash_InfoType;
  1177. PyDoc_STRVAR(hash_info_doc,
  1178. "hash_info\n\
  1179. \n\
  1180. A named tuple providing parameters used for computing\n\
  1181. hashes. The attributes are read only.");
  1182. static PyStructSequence_Field hash_info_fields[] = {
  1183. {"width", "width of the type used for hashing, in bits"},
  1184. {"modulus", "prime number giving the modulus on which the hash "
  1185. "function is based"},
  1186. {"inf", "value to be used for hash of a positive infinity"},
  1187. {"nan", "value to be used for hash of a nan"},
  1188. {"imag", "multiplier used for the imaginary part of a complex number"},
  1189. {"algorithm", "name of the algorithm for hashing of str, bytes and "
  1190. "memoryviews"},
  1191. {"hash_bits", "internal output size of hash algorithm"},
  1192. {"seed_bits", "seed size of hash algorithm"},
  1193. {"cutoff", "small string optimization cutoff"},
  1194. {NULL, NULL}
  1195. };
  1196. static PyStructSequence_Desc hash_info_desc = {
  1197. "sys.hash_info",
  1198. hash_info_doc,
  1199. hash_info_fields,
  1200. 9,
  1201. };
  1202. static PyObject *
  1203. get_hash_info(PyThreadState *tstate)
  1204. {
  1205. PyObject *hash_info;
  1206. int field = 0;
  1207. PyHash_FuncDef *hashfunc;
  1208. hash_info = PyStructSequence_New(&Hash_InfoType);
  1209. if (hash_info == NULL) {
  1210. return NULL;
  1211. }
  1212. hashfunc = PyHash_GetFuncDef();
  1213. #define SET_HASH_INFO_ITEM(CALL) \
  1214. do { \
  1215. PyObject *item = (CALL); \
  1216. if (item == NULL) { \
  1217. Py_CLEAR(hash_info); \
  1218. return NULL; \
  1219. } \
  1220. PyStructSequence_SET_ITEM(hash_info, field++, item); \
  1221. } while(0)
  1222. SET_HASH_INFO_ITEM(PyLong_FromLong(8 * sizeof(Py_hash_t)));
  1223. SET_HASH_INFO_ITEM(PyLong_FromSsize_t(_PyHASH_MODULUS));
  1224. SET_HASH_INFO_ITEM(PyLong_FromLong(_PyHASH_INF));
  1225. SET_HASH_INFO_ITEM(PyLong_FromLong(0)); // This is no longer used
  1226. SET_HASH_INFO_ITEM(PyLong_FromLong(_PyHASH_IMAG));
  1227. SET_HASH_INFO_ITEM(PyUnicode_FromString(hashfunc->name));
  1228. SET_HASH_INFO_ITEM(PyLong_FromLong(hashfunc->hash_bits));
  1229. SET_HASH_INFO_ITEM(PyLong_FromLong(hashfunc->seed_bits));
  1230. SET_HASH_INFO_ITEM(PyLong_FromLong(Py_HASH_CUTOFF));
  1231. #undef SET_HASH_INFO_ITEM
  1232. return hash_info;
  1233. }
  1234. /*[clinic input]
  1235. sys.getrecursionlimit
  1236. Return the current value of the recursion limit.
  1237. The recursion limit is the maximum depth of the Python interpreter
  1238. stack. This limit prevents infinite recursion from causing an overflow
  1239. of the C stack and crashing Python.
  1240. [clinic start generated code]*/
  1241. static PyObject *
  1242. sys_getrecursionlimit_impl(PyObject *module)
  1243. /*[clinic end generated code: output=d571fb6b4549ef2e input=1c6129fd2efaeea8]*/
  1244. {
  1245. return PyLong_FromLong(Py_GetRecursionLimit());
  1246. }
  1247. #ifdef MS_WINDOWS
  1248. static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
  1249. static PyStructSequence_Field windows_version_fields[] = {
  1250. {"major", "Major version number"},
  1251. {"minor", "Minor version number"},
  1252. {"build", "Build number"},
  1253. {"platform", "Operating system platform"},
  1254. {"service_pack", "Latest Service Pack installed on the system"},
  1255. {"service_pack_major", "Service Pack major version number"},
  1256. {"service_pack_minor", "Service Pack minor version number"},
  1257. {"suite_mask", "Bit mask identifying available product suites"},
  1258. {"product_type", "System product type"},
  1259. {"platform_version", "Diagnostic version number"},
  1260. {0}
  1261. };
  1262. static PyStructSequence_Desc windows_version_desc = {
  1263. "sys.getwindowsversion", /* name */
  1264. sys_getwindowsversion__doc__, /* doc */
  1265. windows_version_fields, /* fields */
  1266. 5 /* For backward compatibility,
  1267. only the first 5 items are accessible
  1268. via indexing, the rest are name only */
  1269. };
  1270. static PyObject *
  1271. _sys_getwindowsversion_from_kernel32(void)
  1272. {
  1273. #ifndef MS_WINDOWS_DESKTOP
  1274. return NULL;
  1275. #else
  1276. HANDLE hKernel32;
  1277. wchar_t kernel32_path[MAX_PATH];
  1278. LPVOID verblock;
  1279. DWORD verblock_size;
  1280. VS_FIXEDFILEINFO *ffi;
  1281. UINT ffi_len;
  1282. DWORD realMajor, realMinor, realBuild;
  1283. Py_BEGIN_ALLOW_THREADS
  1284. hKernel32 = GetModuleHandleW(L"kernel32.dll");
  1285. Py_END_ALLOW_THREADS
  1286. if (!hKernel32 || !GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH)) {
  1287. PyErr_SetFromWindowsErr(0);
  1288. return NULL;
  1289. }
  1290. verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL);
  1291. if (!verblock_size) {
  1292. PyErr_SetFromWindowsErr(0);
  1293. return NULL;
  1294. }
  1295. verblock = PyMem_RawMalloc(verblock_size);
  1296. if (!verblock ||
  1297. !GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) ||
  1298. !VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
  1299. PyErr_SetFromWindowsErr(0);
  1300. return NULL;
  1301. }
  1302. realMajor = HIWORD(ffi->dwProductVersionMS);
  1303. realMinor = LOWORD(ffi->dwProductVersionMS);
  1304. realBuild = HIWORD(ffi->dwProductVersionLS);
  1305. PyMem_RawFree(verblock);
  1306. return Py_BuildValue("(kkk)", realMajor, realMinor, realBuild);
  1307. #endif /* !MS_WINDOWS_DESKTOP */
  1308. }
  1309. /* Disable deprecation warnings about GetVersionEx as the result is
  1310. being passed straight through to the caller, who is responsible for
  1311. using it correctly. */
  1312. #pragma warning(push)
  1313. #pragma warning(disable:4996)
  1314. /*[clinic input]
  1315. sys.getwindowsversion
  1316. Return info about the running version of Windows as a named tuple.
  1317. The members are named: major, minor, build, platform, service_pack,
  1318. service_pack_major, service_pack_minor, suite_mask, product_type and
  1319. platform_version. For backward compatibility, only the first 5 items
  1320. are available by indexing. All elements are numbers, except
  1321. service_pack and platform_type which are strings, and platform_version
  1322. which is a 3-tuple. Platform is always 2. Product_type may be 1 for a
  1323. workstation, 2 for a domain controller, 3 for a server.
  1324. Platform_version is a 3-tuple containing a version number that is
  1325. intended for identifying the OS rather than feature detection.
  1326. [clinic start generated code]*/
  1327. static PyObject *
  1328. sys_getwindowsversion_impl(PyObject *module)
  1329. /*[clinic end generated code: output=1ec063280b932857 input=73a228a328fee63a]*/
  1330. {
  1331. PyObject *version;
  1332. int pos = 0;
  1333. OSVERSIONINFOEXW ver;
  1334. version = PyObject_GetAttrString(module, "_cached_windows_version");
  1335. if (version && PyObject_TypeCheck(version, &WindowsVersionType)) {
  1336. return version;
  1337. }
  1338. if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
  1339. return NULL;
  1340. }
  1341. Py_XDECREF(version);
  1342. PyErr_Clear();
  1343. ver.dwOSVersionInfoSize = sizeof(ver);
  1344. if (!GetVersionExW((OSVERSIONINFOW*) &ver))
  1345. return PyErr_SetFromWindowsErr(0);
  1346. version = PyStructSequence_New(&WindowsVersionType);
  1347. if (version == NULL)
  1348. return NULL;
  1349. #define SET_VERSION_INFO(CALL) \
  1350. do { \
  1351. PyObject *item = (CALL); \
  1352. if (item == NULL) { \
  1353. goto error; \
  1354. } \
  1355. PyStructSequence_SET_ITEM(version, pos++, item); \
  1356. } while(0)
  1357. SET_VERSION_INFO(PyLong_FromLong(ver.dwMajorVersion));
  1358. SET_VERSION_INFO(PyLong_FromLong(ver.dwMinorVersion));
  1359. SET_VERSION_INFO(PyLong_FromLong(ver.dwBuildNumber));
  1360. SET_VERSION_INFO(PyLong_FromLong(ver.dwPlatformId));
  1361. SET_VERSION_INFO(PyUnicode_FromWideChar(ver.szCSDVersion, -1));
  1362. SET_VERSION_INFO(PyLong_FromLong(ver.wServicePackMajor));
  1363. SET_VERSION_INFO(PyLong_FromLong(ver.wServicePackMinor));
  1364. SET_VERSION_INFO(PyLong_FromLong(ver.wSuiteMask));
  1365. SET_VERSION_INFO(PyLong_FromLong(ver.wProductType));
  1366. // GetVersion will lie if we are running in a compatibility mode.
  1367. // We need to read the version info from a system file resource
  1368. // to accurately identify the OS version. If we fail for any reason,
  1369. // just return whatever GetVersion said.
  1370. PyObject *realVersion = _sys_getwindowsversion_from_kernel32();
  1371. if (!realVersion) {
  1372. if (!PyErr_ExceptionMatches(PyExc_WindowsError)) {
  1373. return NULL;
  1374. }
  1375. PyErr_Clear();
  1376. realVersion = Py_BuildValue("(kkk)",
  1377. ver.dwMajorVersion,
  1378. ver.dwMinorVersion,
  1379. ver.dwBuildNumber
  1380. );
  1381. }
  1382. SET_VERSION_INFO(realVersion);
  1383. #undef SET_VERSION_INFO
  1384. if (PyObject_SetAttrString(module, "_cached_windows_version", version) < 0) {
  1385. goto error;
  1386. }
  1387. return version;
  1388. error:
  1389. Py_DECREF(version);
  1390. return NULL;
  1391. }
  1392. #pragma warning(pop)
  1393. /*[clinic input]
  1394. sys._enablelegacywindowsfsencoding
  1395. Changes the default filesystem encoding to mbcs:replace.
  1396. This is done for consistency with earlier versions of Python. See PEP
  1397. 529 for more information.
  1398. This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING
  1399. environment variable before launching Python.
  1400. [clinic start generated code]*/
  1401. static PyObject *
  1402. sys__enablelegacywindowsfsencoding_impl(PyObject *module)
  1403. /*[clinic end generated code: output=f5c3855b45e24fe9 input=2bfa931a20704492]*/
  1404. {
  1405. if (_PyUnicode_EnableLegacyWindowsFSEncoding() < 0) {
  1406. return NULL;
  1407. }
  1408. Py_RETURN_NONE;
  1409. }
  1410. #endif /* MS_WINDOWS */
  1411. #ifdef HAVE_DLOPEN
  1412. /*[clinic input]
  1413. sys.setdlopenflags
  1414. flags as new_val: int
  1415. /
  1416. Set the flags used by the interpreter for dlopen calls.
  1417. This is used, for example, when the interpreter loads extension
  1418. modules. Among other things, this will enable a lazy resolving of
  1419. symbols when importing a module, if called as sys.setdlopenflags(0).
  1420. To share symbols across extension modules, call as
  1421. sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag
  1422. modules can be found in the os module (RTLD_xxx constants, e.g.
  1423. os.RTLD_LAZY).
  1424. [clinic start generated code]*/
  1425. static PyObject *
  1426. sys_setdlopenflags_impl(PyObject *module, int new_val)
  1427. /*[clinic end generated code: output=ec918b7fe0a37281 input=4c838211e857a77f]*/
  1428. {
  1429. PyInterpreterState *interp = _PyInterpreterState_GET();
  1430. _PyImport_SetDLOpenFlags(interp, new_val);
  1431. Py_RETURN_NONE;
  1432. }
  1433. /*[clinic input]
  1434. sys.getdlopenflags
  1435. Return the current value of the flags that are used for dlopen calls.
  1436. The flag constants are defined in the os module.
  1437. [clinic start generated code]*/
  1438. static PyObject *
  1439. sys_getdlopenflags_impl(PyObject *module)
  1440. /*[clinic end generated code: output=e92cd1bc5005da6e input=dc4ea0899c53b4b6]*/
  1441. {
  1442. PyInterpreterState *interp = _PyInterpreterState_GET();
  1443. return PyLong_FromLong(
  1444. _PyImport_GetDLOpenFlags(interp));
  1445. }
  1446. #endif /* HAVE_DLOPEN */
  1447. #ifdef USE_MALLOPT
  1448. /* Link with -lmalloc (or -lmpc) on an SGI */
  1449. #include <malloc.h>
  1450. /*[clinic input]
  1451. sys.mdebug
  1452. flag: int
  1453. /
  1454. [clinic start generated code]*/
  1455. static PyObject *
  1456. sys_mdebug_impl(PyObject *module, int flag)
  1457. /*[clinic end generated code: output=5431d545847c3637 input=151d150ae1636f8a]*/
  1458. {
  1459. int flag;
  1460. mallopt(M_DEBUG, flag);
  1461. Py_RETURN_NONE;
  1462. }
  1463. #endif /* USE_MALLOPT */
  1464. /*[clinic input]
  1465. sys.get_int_max_str_digits
  1466. Return the maximum string digits limit for non-binary int<->str conversions.
  1467. [clinic start generated code]*/
  1468. static PyObject *
  1469. sys_get_int_max_str_digits_impl(PyObject *module)
  1470. /*[clinic end generated code: output=0042f5e8ae0e8631 input=61bf9f99bc8b112d]*/
  1471. {
  1472. PyInterpreterState *interp = _PyInterpreterState_GET();
  1473. return PyLong_FromLong(interp->long_state.max_str_digits);
  1474. }
  1475. /*[clinic input]
  1476. sys.set_int_max_str_digits
  1477. maxdigits: int
  1478. Set the maximum string digits limit for non-binary int<->str conversions.
  1479. [clinic start generated code]*/
  1480. static PyObject *
  1481. sys_set_int_max_str_digits_impl(PyObject *module, int maxdigits)
  1482. /*[clinic end generated code: output=734d4c2511f2a56d input=d7e3f325db6910c5]*/
  1483. {
  1484. PyThreadState *tstate = _PyThreadState_GET();
  1485. if ((!maxdigits) || (maxdigits >= _PY_LONG_MAX_STR_DIGITS_THRESHOLD)) {
  1486. tstate->interp->long_state.max_str_digits = maxdigits;
  1487. Py_RETURN_NONE;
  1488. } else {
  1489. PyErr_Format(
  1490. PyExc_ValueError, "maxdigits must be 0 or larger than %d",
  1491. _PY_LONG_MAX_STR_DIGITS_THRESHOLD);
  1492. return NULL;
  1493. }
  1494. }
  1495. size_t
  1496. _PySys_GetSizeOf(PyObject *o)
  1497. {
  1498. PyObject *res = NULL;
  1499. PyObject *method;
  1500. Py_ssize_t size;
  1501. PyThreadState *tstate = _PyThreadState_GET();
  1502. /* Make sure the type is initialized. float gets initialized late */
  1503. if (PyType_Ready(Py_TYPE(o)) < 0) {
  1504. return (size_t)-1;
  1505. }
  1506. method = _PyObject_LookupSpecial(o, &_Py_ID(__sizeof__));
  1507. if (method == NULL) {
  1508. if (!_PyErr_Occurred(tstate)) {
  1509. _PyErr_Format(tstate, PyExc_TypeError,
  1510. "Type %.100s doesn't define __sizeof__",
  1511. Py_TYPE(o)->tp_name);
  1512. }
  1513. }
  1514. else {
  1515. res = _PyObject_CallNoArgs(method);
  1516. Py_DECREF(method);
  1517. }
  1518. if (res == NULL)
  1519. return (size_t)-1;
  1520. size = PyLong_AsSsize_t(res);
  1521. Py_DECREF(res);
  1522. if (size == -1 && _PyErr_Occurred(tstate))
  1523. return (size_t)-1;
  1524. if (size < 0) {
  1525. _PyErr_SetString(tstate, PyExc_ValueError,
  1526. "__sizeof__() should return >= 0");
  1527. return (size_t)-1;
  1528. }
  1529. return (size_t)size + _PyType_PreHeaderSize(Py_TYPE(o));
  1530. }
  1531. static PyObject *
  1532. sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
  1533. {
  1534. static char *kwlist[] = {"object", "default", 0};
  1535. size_t size;
  1536. PyObject *o, *dflt = NULL;
  1537. PyThreadState *tstate = _PyThreadState_GET();
  1538. if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
  1539. kwlist, &o, &dflt)) {
  1540. return NULL;
  1541. }
  1542. size = _PySys_GetSizeOf(o);
  1543. if (size == (size_t)-1 && _PyErr_Occurred(tstate)) {
  1544. /* Has a default value been given */
  1545. if (dflt != NULL && _PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
  1546. _PyErr_Clear(tstate);
  1547. return Py_NewRef(dflt);
  1548. }
  1549. else
  1550. return NULL;
  1551. }
  1552. return PyLong_FromSize_t(size);
  1553. }
  1554. PyDoc_STRVAR(getsizeof_doc,
  1555. "getsizeof(object [, default]) -> int\n\
  1556. \n\
  1557. Return the size of object in bytes.");
  1558. /*[clinic input]
  1559. sys.getrefcount -> Py_ssize_t
  1560. object: object
  1561. /
  1562. Return the reference count of object.
  1563. The count returned is generally one higher than you might expect,
  1564. because it includes the (temporary) reference as an argument to
  1565. getrefcount().
  1566. [clinic start generated code]*/
  1567. static Py_ssize_t
  1568. sys_getrefcount_impl(PyObject *module, PyObject *object)
  1569. /*[clinic end generated code: output=5fd477f2264b85b2 input=bf474efd50a21535]*/
  1570. {
  1571. return Py_REFCNT(object);
  1572. }
  1573. #ifdef Py_REF_DEBUG
  1574. /*[clinic input]
  1575. sys.gettotalrefcount -> Py_ssize_t
  1576. [clinic start generated code]*/
  1577. static Py_ssize_t
  1578. sys_gettotalrefcount_impl(PyObject *module)
  1579. /*[clinic end generated code: output=4103886cf17c25bc input=53b744faa5d2e4f6]*/
  1580. {
  1581. /* It may make sense to return the total for the current interpreter
  1582. or have a second function that does so. */
  1583. return _Py_GetGlobalRefTotal();
  1584. }
  1585. #endif /* Py_REF_DEBUG */
  1586. /*[clinic input]
  1587. sys.getallocatedblocks -> Py_ssize_t
  1588. Return the number of memory blocks currently allocated.
  1589. [clinic start generated code]*/
  1590. static Py_ssize_t
  1591. sys_getallocatedblocks_impl(PyObject *module)
  1592. /*[clinic end generated code: output=f0c4e873f0b6dcf7 input=dab13ee346a0673e]*/
  1593. {
  1594. // It might make sense to return the count
  1595. // for just the current interpreter.
  1596. return _Py_GetGlobalAllocatedBlocks();
  1597. }
  1598. /*[clinic input]
  1599. sys.getunicodeinternedsize -> Py_ssize_t
  1600. Return the number of elements of the unicode interned dictionary
  1601. [clinic start generated code]*/
  1602. static Py_ssize_t
  1603. sys_getunicodeinternedsize_impl(PyObject *module)
  1604. /*[clinic end generated code: output=ad0e4c9738ed4129 input=726298eaa063347a]*/
  1605. {
  1606. return _PyUnicode_InternedSize();
  1607. }
  1608. /*[clinic input]
  1609. sys._getframe
  1610. depth: int = 0
  1611. /
  1612. Return a frame object from the call stack.
  1613. If optional integer depth is given, return the frame object that many
  1614. calls below the top of the stack. If that is deeper than the call
  1615. stack, ValueError is raised. The default for depth is zero, returning
  1616. the frame at the top of the call stack.
  1617. This function should be used for internal and specialized purposes
  1618. only.
  1619. [clinic start generated code]*/
  1620. static PyObject *
  1621. sys__getframe_impl(PyObject *module, int depth)
  1622. /*[clinic end generated code: output=d438776c04d59804 input=c1be8a6464b11ee5]*/
  1623. {
  1624. PyThreadState *tstate = _PyThreadState_GET();
  1625. _PyInterpreterFrame *frame = tstate->cframe->current_frame;
  1626. if (frame != NULL) {
  1627. while (depth > 0) {
  1628. frame = _PyFrame_GetFirstComplete(frame->previous);
  1629. if (frame == NULL) {
  1630. break;
  1631. }
  1632. --depth;
  1633. }
  1634. }
  1635. if (frame == NULL) {
  1636. _PyErr_SetString(tstate, PyExc_ValueError,
  1637. "call stack is not deep enough");
  1638. return NULL;
  1639. }
  1640. PyObject *pyFrame = Py_XNewRef((PyObject *)_PyFrame_GetFrameObject(frame));
  1641. if (pyFrame && _PySys_Audit(tstate, "sys._getframe", "(O)", pyFrame) < 0) {
  1642. Py_DECREF(pyFrame);
  1643. return NULL;
  1644. }
  1645. return pyFrame;
  1646. }
  1647. /*[clinic input]
  1648. sys._current_frames
  1649. Return a dict mapping each thread's thread id to its current stack frame.
  1650. This function should be used for specialized purposes only.
  1651. [clinic start generated code]*/
  1652. static PyObject *
  1653. sys__current_frames_impl(PyObject *module)
  1654. /*[clinic end generated code: output=d2a41ac0a0a3809a input=2a9049c5f5033691]*/
  1655. {
  1656. return _PyThread_CurrentFrames();
  1657. }
  1658. /*[clinic input]
  1659. sys._current_exceptions
  1660. Return a dict mapping each thread's identifier to its current raised exception.
  1661. This function should be used for specialized purposes only.
  1662. [clinic start generated code]*/
  1663. static PyObject *
  1664. sys__current_exceptions_impl(PyObject *module)
  1665. /*[clinic end generated code: output=2ccfd838c746f0ba input=0e91818fbf2edc1f]*/
  1666. {
  1667. return _PyThread_CurrentExceptions();
  1668. }
  1669. /*[clinic input]
  1670. sys.call_tracing
  1671. func: object
  1672. args as funcargs: object(subclass_of='&PyTuple_Type')
  1673. /
  1674. Call func(*args), while tracing is enabled.
  1675. The tracing state is saved, and restored afterwards. This is intended
  1676. to be called from a debugger from a checkpoint, to recursively debug
  1677. some other code.
  1678. [clinic start generated code]*/
  1679. static PyObject *
  1680. sys_call_tracing_impl(PyObject *module, PyObject *func, PyObject *funcargs)
  1681. /*[clinic end generated code: output=7e4999853cd4e5a6 input=5102e8b11049f92f]*/
  1682. {
  1683. return _PyEval_CallTracing(func, funcargs);
  1684. }
  1685. #ifdef __cplusplus
  1686. extern "C" {
  1687. #endif
  1688. /*[clinic input]
  1689. sys._debugmallocstats
  1690. Print summary info to stderr about the state of pymalloc's structures.
  1691. In Py_DEBUG mode, also perform some expensive internal consistency
  1692. checks.
  1693. [clinic start generated code]*/
  1694. static PyObject *
  1695. sys__debugmallocstats_impl(PyObject *module)
  1696. /*[clinic end generated code: output=ec3565f8c7cee46a input=33c0c9c416f98424]*/
  1697. {
  1698. #ifdef WITH_PYMALLOC
  1699. if (_PyObject_DebugMallocStats(stderr)) {
  1700. fputc('\n', stderr);
  1701. }
  1702. #endif
  1703. _PyObject_DebugTypeStats(stderr);
  1704. Py_RETURN_NONE;
  1705. }
  1706. #ifdef Py_TRACE_REFS
  1707. /* Defined in objects.c because it uses static globals in that file */
  1708. extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
  1709. #endif
  1710. #ifdef __cplusplus
  1711. }
  1712. #endif
  1713. /*[clinic input]
  1714. sys._clear_type_cache
  1715. Clear the internal type lookup cache.
  1716. [clinic start generated code]*/
  1717. static PyObject *
  1718. sys__clear_type_cache_impl(PyObject *module)
  1719. /*[clinic end generated code: output=20e48ca54a6f6971 input=127f3e04a8d9b555]*/
  1720. {
  1721. PyType_ClearCache();
  1722. Py_RETURN_NONE;
  1723. }
  1724. /* Note that, for now, we do not have a per-interpreter equivalent
  1725. for sys.is_finalizing(). */
  1726. /*[clinic input]
  1727. sys.is_finalizing
  1728. Return True if Python is exiting.
  1729. [clinic start generated code]*/
  1730. static PyObject *
  1731. sys_is_finalizing_impl(PyObject *module)
  1732. /*[clinic end generated code: output=735b5ff7962ab281 input=f0df747a039948a5]*/
  1733. {
  1734. return PyBool_FromLong(_Py_IsFinalizing());
  1735. }
  1736. #ifdef Py_STATS
  1737. /*[clinic input]
  1738. sys._stats_on
  1739. Turns on stats gathering (stats gathering is on by default).
  1740. [clinic start generated code]*/
  1741. static PyObject *
  1742. sys__stats_on_impl(PyObject *module)
  1743. /*[clinic end generated code: output=aca53eafcbb4d9fe input=8ddc6df94e484f3a]*/
  1744. {
  1745. _py_stats = &_py_stats_struct;
  1746. Py_RETURN_NONE;
  1747. }
  1748. /*[clinic input]
  1749. sys._stats_off
  1750. Turns off stats gathering (stats gathering is on by default).
  1751. [clinic start generated code]*/
  1752. static PyObject *
  1753. sys__stats_off_impl(PyObject *module)
  1754. /*[clinic end generated code: output=1534c1ee63812214 input=b3e50e71ecf29f66]*/
  1755. {
  1756. _py_stats = NULL;
  1757. Py_RETURN_NONE;
  1758. }
  1759. /*[clinic input]
  1760. sys._stats_clear
  1761. Clears the stats.
  1762. [clinic start generated code]*/
  1763. static PyObject *
  1764. sys__stats_clear_impl(PyObject *module)
  1765. /*[clinic end generated code: output=fb65a2525ee50604 input=3e03f2654f44da96]*/
  1766. {
  1767. _Py_StatsClear();
  1768. Py_RETURN_NONE;
  1769. }
  1770. /*[clinic input]
  1771. sys._stats_dump
  1772. Dump stats to file, and clears the stats.
  1773. [clinic start generated code]*/
  1774. static PyObject *
  1775. sys__stats_dump_impl(PyObject *module)
  1776. /*[clinic end generated code: output=79f796fb2b4ddf05 input=92346f16d64f6f95]*/
  1777. {
  1778. _Py_PrintSpecializationStats(1);
  1779. _Py_StatsClear();
  1780. Py_RETURN_NONE;
  1781. }
  1782. #endif
  1783. #ifdef ANDROID_API_LEVEL
  1784. /*[clinic input]
  1785. sys.getandroidapilevel
  1786. Return the build time API version of Android as an integer.
  1787. [clinic start generated code]*/
  1788. static PyObject *
  1789. sys_getandroidapilevel_impl(PyObject *module)
  1790. /*[clinic end generated code: output=214abf183a1c70c1 input=3e6d6c9fcdd24ac6]*/
  1791. {
  1792. return PyLong_FromLong(ANDROID_API_LEVEL);
  1793. }
  1794. #endif /* ANDROID_API_LEVEL */
  1795. /*[clinic input]
  1796. sys.activate_stack_trampoline
  1797. backend: str
  1798. /
  1799. Activate stack profiler trampoline *backend*.
  1800. [clinic start generated code]*/
  1801. static PyObject *
  1802. sys_activate_stack_trampoline_impl(PyObject *module, const char *backend)
  1803. /*[clinic end generated code: output=5783cdeb51874b43 input=a12df928758a82b4]*/
  1804. {
  1805. #ifdef PY_HAVE_PERF_TRAMPOLINE
  1806. if (strcmp(backend, "perf") == 0) {
  1807. _PyPerf_Callbacks cur_cb;
  1808. _PyPerfTrampoline_GetCallbacks(&cur_cb);
  1809. if (cur_cb.write_state != _Py_perfmap_callbacks.write_state) {
  1810. if (_PyPerfTrampoline_SetCallbacks(&_Py_perfmap_callbacks) < 0 ) {
  1811. PyErr_SetString(PyExc_ValueError, "can't activate perf trampoline");
  1812. return NULL;
  1813. }
  1814. }
  1815. }
  1816. else {
  1817. PyErr_Format(PyExc_ValueError, "invalid backend: %s", backend);
  1818. return NULL;
  1819. }
  1820. if (_PyPerfTrampoline_Init(1) < 0) {
  1821. return NULL;
  1822. }
  1823. Py_RETURN_NONE;
  1824. #else
  1825. PyErr_SetString(PyExc_ValueError, "perf trampoline not available");
  1826. return NULL;
  1827. #endif
  1828. }
  1829. /*[clinic input]
  1830. sys.deactivate_stack_trampoline
  1831. Deactivate the current stack profiler trampoline backend.
  1832. If no stack profiler is activated, this function has no effect.
  1833. [clinic start generated code]*/
  1834. static PyObject *
  1835. sys_deactivate_stack_trampoline_impl(PyObject *module)
  1836. /*[clinic end generated code: output=b50da25465df0ef1 input=9f629a6be9fe7fc8]*/
  1837. {
  1838. if (_PyPerfTrampoline_Init(0) < 0) {
  1839. return NULL;
  1840. }
  1841. Py_RETURN_NONE;
  1842. }
  1843. /*[clinic input]
  1844. sys.is_stack_trampoline_active
  1845. Return *True* if a stack profiler trampoline is active.
  1846. [clinic start generated code]*/
  1847. static PyObject *
  1848. sys_is_stack_trampoline_active_impl(PyObject *module)
  1849. /*[clinic end generated code: output=ab2746de0ad9d293 input=29616b7bf6a0b703]*/
  1850. {
  1851. #ifdef PY_HAVE_PERF_TRAMPOLINE
  1852. if (_PyIsPerfTrampolineActive()) {
  1853. Py_RETURN_TRUE;
  1854. }
  1855. #endif
  1856. Py_RETURN_FALSE;
  1857. }
  1858. /*[clinic input]
  1859. sys._getframemodulename
  1860. depth: int = 0
  1861. Return the name of the module for a calling frame.
  1862. The default depth returns the module containing the call to this API.
  1863. A more typical use in a library will pass a depth of 1 to get the user's
  1864. module rather than the library module.
  1865. If no frame, module, or name can be found, returns None.
  1866. [clinic start generated code]*/
  1867. static PyObject *
  1868. sys__getframemodulename_impl(PyObject *module, int depth)
  1869. /*[clinic end generated code: output=1d70ef691f09d2db input=d4f1a8ed43b8fb46]*/
  1870. {
  1871. if (PySys_Audit("sys._getframemodulename", "i", depth) < 0) {
  1872. return NULL;
  1873. }
  1874. _PyInterpreterFrame *f = _PyThreadState_GET()->cframe->current_frame;
  1875. while (f && (_PyFrame_IsIncomplete(f) || depth-- > 0)) {
  1876. f = f->previous;
  1877. }
  1878. if (f == NULL || f->f_funcobj == NULL) {
  1879. Py_RETURN_NONE;
  1880. }
  1881. PyObject *r = PyFunction_GetModule(f->f_funcobj);
  1882. if (!r) {
  1883. PyErr_Clear();
  1884. r = Py_None;
  1885. }
  1886. return Py_NewRef(r);
  1887. }
  1888. #ifdef __cplusplus
  1889. extern "C" {
  1890. #endif
  1891. static PerfMapState perf_map_state;
  1892. PyAPI_FUNC(int) PyUnstable_PerfMapState_Init(void) {
  1893. #ifndef MS_WINDOWS
  1894. char filename[100];
  1895. pid_t pid = getpid();
  1896. // Use nofollow flag to prevent symlink attacks.
  1897. int flags = O_WRONLY | O_CREAT | O_APPEND | O_NOFOLLOW;
  1898. #ifdef O_CLOEXEC
  1899. flags |= O_CLOEXEC;
  1900. #endif
  1901. snprintf(filename, sizeof(filename) - 1, "/tmp/perf-%jd.map",
  1902. (intmax_t)pid);
  1903. int fd = open(filename, flags, 0600);
  1904. if (fd == -1) {
  1905. return -1;
  1906. }
  1907. else{
  1908. perf_map_state.perf_map = fdopen(fd, "a");
  1909. if (perf_map_state.perf_map == NULL) {
  1910. close(fd);
  1911. return -1;
  1912. }
  1913. }
  1914. perf_map_state.map_lock = PyThread_allocate_lock();
  1915. if (perf_map_state.map_lock == NULL) {
  1916. fclose(perf_map_state.perf_map);
  1917. return -2;
  1918. }
  1919. #endif
  1920. return 0;
  1921. }
  1922. PyAPI_FUNC(int) PyUnstable_WritePerfMapEntry(
  1923. const void *code_addr,
  1924. unsigned int code_size,
  1925. const char *entry_name
  1926. ) {
  1927. #ifndef MS_WINDOWS
  1928. if (perf_map_state.perf_map == NULL) {
  1929. int ret = PyUnstable_PerfMapState_Init();
  1930. if(ret != 0){
  1931. return ret;
  1932. }
  1933. }
  1934. PyThread_acquire_lock(perf_map_state.map_lock, 1);
  1935. fprintf(perf_map_state.perf_map, "%" PRIxPTR " %x %s\n", (uintptr_t) code_addr, code_size, entry_name);
  1936. fflush(perf_map_state.perf_map);
  1937. PyThread_release_lock(perf_map_state.map_lock);
  1938. #endif
  1939. return 0;
  1940. }
  1941. PyAPI_FUNC(void) PyUnstable_PerfMapState_Fini(void) {
  1942. #ifndef MS_WINDOWS
  1943. if (perf_map_state.perf_map != NULL) {
  1944. // close the file
  1945. PyThread_acquire_lock(perf_map_state.map_lock, 1);
  1946. fclose(perf_map_state.perf_map);
  1947. PyThread_release_lock(perf_map_state.map_lock);
  1948. // clean up the lock and state
  1949. PyThread_free_lock(perf_map_state.map_lock);
  1950. perf_map_state.perf_map = NULL;
  1951. }
  1952. #endif
  1953. }
  1954. #ifdef __cplusplus
  1955. }
  1956. #endif
  1957. static PyMethodDef sys_methods[] = {
  1958. /* Might as well keep this in alphabetic order */
  1959. SYS_ADDAUDITHOOK_METHODDEF
  1960. {"audit", _PyCFunction_CAST(sys_audit), METH_FASTCALL, audit_doc },
  1961. {"breakpointhook", _PyCFunction_CAST(sys_breakpointhook),
  1962. METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
  1963. SYS__CLEAR_TYPE_CACHE_METHODDEF
  1964. SYS__CURRENT_FRAMES_METHODDEF
  1965. SYS__CURRENT_EXCEPTIONS_METHODDEF
  1966. SYS_DISPLAYHOOK_METHODDEF
  1967. SYS_EXCEPTION_METHODDEF
  1968. SYS_EXC_INFO_METHODDEF
  1969. SYS_EXCEPTHOOK_METHODDEF
  1970. SYS_EXIT_METHODDEF
  1971. SYS_GETDEFAULTENCODING_METHODDEF
  1972. SYS_GETDLOPENFLAGS_METHODDEF
  1973. SYS_GETALLOCATEDBLOCKS_METHODDEF
  1974. SYS_GETUNICODEINTERNEDSIZE_METHODDEF
  1975. SYS_GETFILESYSTEMENCODING_METHODDEF
  1976. SYS_GETFILESYSTEMENCODEERRORS_METHODDEF
  1977. #ifdef Py_TRACE_REFS
  1978. {"getobjects", _Py_GetObjects, METH_VARARGS},
  1979. #endif
  1980. SYS_GETTOTALREFCOUNT_METHODDEF
  1981. SYS_GETREFCOUNT_METHODDEF
  1982. SYS_GETRECURSIONLIMIT_METHODDEF
  1983. {"getsizeof", _PyCFunction_CAST(sys_getsizeof),
  1984. METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
  1985. SYS__GETFRAME_METHODDEF
  1986. SYS__GETFRAMEMODULENAME_METHODDEF
  1987. SYS_GETWINDOWSVERSION_METHODDEF
  1988. SYS__ENABLELEGACYWINDOWSFSENCODING_METHODDEF
  1989. SYS_INTERN_METHODDEF
  1990. SYS_IS_FINALIZING_METHODDEF
  1991. SYS_MDEBUG_METHODDEF
  1992. SYS_SETSWITCHINTERVAL_METHODDEF
  1993. SYS_GETSWITCHINTERVAL_METHODDEF
  1994. SYS_SETDLOPENFLAGS_METHODDEF
  1995. {"setprofile", sys_setprofile, METH_O, setprofile_doc},
  1996. SYS__SETPROFILEALLTHREADS_METHODDEF
  1997. SYS_GETPROFILE_METHODDEF
  1998. SYS_SETRECURSIONLIMIT_METHODDEF
  1999. {"settrace", sys_settrace, METH_O, settrace_doc},
  2000. SYS__SETTRACEALLTHREADS_METHODDEF
  2001. SYS_GETTRACE_METHODDEF
  2002. SYS_CALL_TRACING_METHODDEF
  2003. SYS__DEBUGMALLOCSTATS_METHODDEF
  2004. SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
  2005. SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
  2006. {"set_asyncgen_hooks", _PyCFunction_CAST(sys_set_asyncgen_hooks),
  2007. METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
  2008. SYS_GET_ASYNCGEN_HOOKS_METHODDEF
  2009. SYS_GETANDROIDAPILEVEL_METHODDEF
  2010. SYS_ACTIVATE_STACK_TRAMPOLINE_METHODDEF
  2011. SYS_DEACTIVATE_STACK_TRAMPOLINE_METHODDEF
  2012. SYS_IS_STACK_TRAMPOLINE_ACTIVE_METHODDEF
  2013. SYS_UNRAISABLEHOOK_METHODDEF
  2014. SYS_GET_INT_MAX_STR_DIGITS_METHODDEF
  2015. SYS_SET_INT_MAX_STR_DIGITS_METHODDEF
  2016. #ifdef Py_STATS
  2017. SYS__STATS_ON_METHODDEF
  2018. SYS__STATS_OFF_METHODDEF
  2019. SYS__STATS_CLEAR_METHODDEF
  2020. SYS__STATS_DUMP_METHODDEF
  2021. #endif
  2022. {NULL, NULL} // sentinel
  2023. };
  2024. static PyObject *
  2025. list_builtin_module_names(void)
  2026. {
  2027. PyObject *list = _PyImport_GetBuiltinModuleNames();
  2028. if (list == NULL) {
  2029. return NULL;
  2030. }
  2031. if (PyList_Sort(list) != 0) {
  2032. goto error;
  2033. }
  2034. PyObject *tuple = PyList_AsTuple(list);
  2035. Py_DECREF(list);
  2036. return tuple;
  2037. error:
  2038. Py_DECREF(list);
  2039. return NULL;
  2040. }
  2041. static PyObject *
  2042. list_stdlib_module_names(void)
  2043. {
  2044. Py_ssize_t len = Py_ARRAY_LENGTH(_Py_stdlib_module_names);
  2045. PyObject *names = PyTuple_New(len);
  2046. if (names == NULL) {
  2047. return NULL;
  2048. }
  2049. for (Py_ssize_t i = 0; i < len; i++) {
  2050. PyObject *name = PyUnicode_FromString(_Py_stdlib_module_names[i]);
  2051. if (name == NULL) {
  2052. Py_DECREF(names);
  2053. return NULL;
  2054. }
  2055. PyTuple_SET_ITEM(names, i, name);
  2056. }
  2057. PyObject *set = PyObject_CallFunction((PyObject *)&PyFrozenSet_Type,
  2058. "(O)", names);
  2059. Py_DECREF(names);
  2060. return set;
  2061. }
  2062. /* Pre-initialization support for sys.warnoptions and sys._xoptions
  2063. *
  2064. * Modern internal code paths:
  2065. * These APIs get called after _Py_InitializeCore and get to use the
  2066. * regular CPython list, dict, and unicode APIs.
  2067. *
  2068. * Legacy embedding code paths:
  2069. * The multi-phase initialization API isn't public yet, so embedding
  2070. * apps still need to be able configure sys.warnoptions and sys._xoptions
  2071. * before they call Py_Initialize. To support this, we stash copies of
  2072. * the supplied wchar * sequences in linked lists, and then migrate the
  2073. * contents of those lists to the sys module in _PyInitializeCore.
  2074. *
  2075. */
  2076. struct _preinit_entry {
  2077. wchar_t *value;
  2078. struct _preinit_entry *next;
  2079. };
  2080. typedef struct _preinit_entry *_Py_PreInitEntry;
  2081. static _Py_PreInitEntry _preinit_warnoptions = NULL;
  2082. static _Py_PreInitEntry _preinit_xoptions = NULL;
  2083. static _Py_PreInitEntry
  2084. _alloc_preinit_entry(const wchar_t *value)
  2085. {
  2086. /* To get this to work, we have to initialize the runtime implicitly */
  2087. _PyRuntime_Initialize();
  2088. /* Force default allocator, so we can ensure that it also gets used to
  2089. * destroy the linked list in _clear_preinit_entries.
  2090. */
  2091. PyMemAllocatorEx old_alloc;
  2092. _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  2093. _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
  2094. if (node != NULL) {
  2095. node->value = _PyMem_RawWcsdup(value);
  2096. if (node->value == NULL) {
  2097. PyMem_RawFree(node);
  2098. node = NULL;
  2099. };
  2100. };
  2101. PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  2102. return node;
  2103. }
  2104. static int
  2105. _append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
  2106. {
  2107. _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
  2108. if (new_entry == NULL) {
  2109. return -1;
  2110. }
  2111. /* We maintain the linked list in this order so it's easy to play back
  2112. * the add commands in the same order later on in _Py_InitializeCore
  2113. */
  2114. _Py_PreInitEntry last_entry = *optionlist;
  2115. if (last_entry == NULL) {
  2116. *optionlist = new_entry;
  2117. } else {
  2118. while (last_entry->next != NULL) {
  2119. last_entry = last_entry->next;
  2120. }
  2121. last_entry->next = new_entry;
  2122. }
  2123. return 0;
  2124. }
  2125. static void
  2126. _clear_preinit_entries(_Py_PreInitEntry *optionlist)
  2127. {
  2128. _Py_PreInitEntry current = *optionlist;
  2129. *optionlist = NULL;
  2130. /* Deallocate the nodes and their contents using the default allocator */
  2131. PyMemAllocatorEx old_alloc;
  2132. _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  2133. while (current != NULL) {
  2134. _Py_PreInitEntry next = current->next;
  2135. PyMem_RawFree(current->value);
  2136. PyMem_RawFree(current);
  2137. current = next;
  2138. }
  2139. PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  2140. }
  2141. PyStatus
  2142. _PySys_ReadPreinitWarnOptions(PyWideStringList *options)
  2143. {
  2144. PyStatus status;
  2145. _Py_PreInitEntry entry;
  2146. for (entry = _preinit_warnoptions; entry != NULL; entry = entry->next) {
  2147. status = PyWideStringList_Append(options, entry->value);
  2148. if (_PyStatus_EXCEPTION(status)) {
  2149. return status;
  2150. }
  2151. }
  2152. _clear_preinit_entries(&_preinit_warnoptions);
  2153. return _PyStatus_OK();
  2154. }
  2155. PyStatus
  2156. _PySys_ReadPreinitXOptions(PyConfig *config)
  2157. {
  2158. PyStatus status;
  2159. _Py_PreInitEntry entry;
  2160. for (entry = _preinit_xoptions; entry != NULL; entry = entry->next) {
  2161. status = PyWideStringList_Append(&config->xoptions, entry->value);
  2162. if (_PyStatus_EXCEPTION(status)) {
  2163. return status;
  2164. }
  2165. }
  2166. _clear_preinit_entries(&_preinit_xoptions);
  2167. return _PyStatus_OK();
  2168. }
  2169. static PyObject *
  2170. get_warnoptions(PyThreadState *tstate)
  2171. {
  2172. PyObject *warnoptions = _PySys_GetAttr(tstate, &_Py_ID(warnoptions));
  2173. if (warnoptions == NULL || !PyList_Check(warnoptions)) {
  2174. /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
  2175. * interpreter config. When that happens, we need to properly set
  2176. * the `warnoptions` reference in the main interpreter config as well.
  2177. *
  2178. * For Python 3.7, we shouldn't be able to get here due to the
  2179. * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
  2180. * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
  2181. * call optional for embedding applications, thus making this
  2182. * reachable again.
  2183. */
  2184. warnoptions = PyList_New(0);
  2185. if (warnoptions == NULL) {
  2186. return NULL;
  2187. }
  2188. if (sys_set_object(tstate->interp, &_Py_ID(warnoptions), warnoptions)) {
  2189. Py_DECREF(warnoptions);
  2190. return NULL;
  2191. }
  2192. Py_DECREF(warnoptions);
  2193. }
  2194. return warnoptions;
  2195. }
  2196. void
  2197. PySys_ResetWarnOptions(void)
  2198. {
  2199. PyThreadState *tstate = _PyThreadState_GET();
  2200. if (tstate == NULL) {
  2201. _clear_preinit_entries(&_preinit_warnoptions);
  2202. return;
  2203. }
  2204. PyObject *warnoptions = _PySys_GetAttr(tstate, &_Py_ID(warnoptions));
  2205. if (warnoptions == NULL || !PyList_Check(warnoptions))
  2206. return;
  2207. PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
  2208. }
  2209. static int
  2210. _PySys_AddWarnOptionWithError(PyThreadState *tstate, PyObject *option)
  2211. {
  2212. PyObject *warnoptions = get_warnoptions(tstate);
  2213. if (warnoptions == NULL) {
  2214. return -1;
  2215. }
  2216. if (PyList_Append(warnoptions, option)) {
  2217. return -1;
  2218. }
  2219. return 0;
  2220. }
  2221. void
  2222. PySys_AddWarnOptionUnicode(PyObject *option)
  2223. {
  2224. PyThreadState *tstate = _PyThreadState_GET();
  2225. if (_PySys_AddWarnOptionWithError(tstate, option) < 0) {
  2226. /* No return value, therefore clear error state if possible */
  2227. if (tstate) {
  2228. _PyErr_Clear(tstate);
  2229. }
  2230. }
  2231. }
  2232. void
  2233. PySys_AddWarnOption(const wchar_t *s)
  2234. {
  2235. PyThreadState *tstate = _PyThreadState_GET();
  2236. if (tstate == NULL) {
  2237. _append_preinit_entry(&_preinit_warnoptions, s);
  2238. return;
  2239. }
  2240. PyObject *unicode;
  2241. unicode = PyUnicode_FromWideChar(s, -1);
  2242. if (unicode == NULL)
  2243. return;
  2244. _Py_COMP_DIAG_PUSH
  2245. _Py_COMP_DIAG_IGNORE_DEPR_DECLS
  2246. PySys_AddWarnOptionUnicode(unicode);
  2247. _Py_COMP_DIAG_POP
  2248. Py_DECREF(unicode);
  2249. }
  2250. int
  2251. PySys_HasWarnOptions(void)
  2252. {
  2253. PyThreadState *tstate = _PyThreadState_GET();
  2254. PyObject *warnoptions = _PySys_GetAttr(tstate, &_Py_ID(warnoptions));
  2255. return (warnoptions != NULL && PyList_Check(warnoptions)
  2256. && PyList_GET_SIZE(warnoptions) > 0);
  2257. }
  2258. static PyObject *
  2259. get_xoptions(PyThreadState *tstate)
  2260. {
  2261. PyObject *xoptions = _PySys_GetAttr(tstate, &_Py_ID(_xoptions));
  2262. if (xoptions == NULL || !PyDict_Check(xoptions)) {
  2263. /* PEP432 TODO: we can reach this if xoptions is NULL in the main
  2264. * interpreter config. When that happens, we need to properly set
  2265. * the `xoptions` reference in the main interpreter config as well.
  2266. *
  2267. * For Python 3.7, we shouldn't be able to get here due to the
  2268. * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
  2269. * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
  2270. * call optional for embedding applications, thus making this
  2271. * reachable again.
  2272. */
  2273. xoptions = PyDict_New();
  2274. if (xoptions == NULL) {
  2275. return NULL;
  2276. }
  2277. if (sys_set_object(tstate->interp, &_Py_ID(_xoptions), xoptions)) {
  2278. Py_DECREF(xoptions);
  2279. return NULL;
  2280. }
  2281. Py_DECREF(xoptions);
  2282. }
  2283. return xoptions;
  2284. }
  2285. static int
  2286. _PySys_AddXOptionWithError(const wchar_t *s)
  2287. {
  2288. PyObject *name = NULL, *value = NULL;
  2289. PyThreadState *tstate = _PyThreadState_GET();
  2290. PyObject *opts = get_xoptions(tstate);
  2291. if (opts == NULL) {
  2292. goto error;
  2293. }
  2294. const wchar_t *name_end = wcschr(s, L'=');
  2295. if (!name_end) {
  2296. name = PyUnicode_FromWideChar(s, -1);
  2297. if (name == NULL) {
  2298. goto error;
  2299. }
  2300. value = Py_NewRef(Py_True);
  2301. }
  2302. else {
  2303. name = PyUnicode_FromWideChar(s, name_end - s);
  2304. if (name == NULL) {
  2305. goto error;
  2306. }
  2307. value = PyUnicode_FromWideChar(name_end + 1, -1);
  2308. if (value == NULL) {
  2309. goto error;
  2310. }
  2311. }
  2312. if (PyDict_SetItem(opts, name, value) < 0) {
  2313. goto error;
  2314. }
  2315. Py_DECREF(name);
  2316. Py_DECREF(value);
  2317. return 0;
  2318. error:
  2319. Py_XDECREF(name);
  2320. Py_XDECREF(value);
  2321. return -1;
  2322. }
  2323. void
  2324. PySys_AddXOption(const wchar_t *s)
  2325. {
  2326. PyThreadState *tstate = _PyThreadState_GET();
  2327. if (tstate == NULL) {
  2328. _append_preinit_entry(&_preinit_xoptions, s);
  2329. return;
  2330. }
  2331. if (_PySys_AddXOptionWithError(s) < 0) {
  2332. /* No return value, therefore clear error state if possible */
  2333. _PyErr_Clear(tstate);
  2334. }
  2335. }
  2336. PyObject *
  2337. PySys_GetXOptions(void)
  2338. {
  2339. PyThreadState *tstate = _PyThreadState_GET();
  2340. return get_xoptions(tstate);
  2341. }
  2342. /* XXX This doc string is too long to be a single string literal in VC++ 5.0.
  2343. Two literals concatenated works just fine. If you have a K&R compiler
  2344. or other abomination that however *does* understand longer strings,
  2345. get rid of the !!! comment in the middle and the quotes that surround it. */
  2346. PyDoc_VAR(sys_doc) =
  2347. PyDoc_STR(
  2348. "This module provides access to some objects used or maintained by the\n\
  2349. interpreter and to functions that interact strongly with the interpreter.\n\
  2350. \n\
  2351. Dynamic objects:\n\
  2352. \n\
  2353. argv -- command line arguments; argv[0] is the script pathname if known\n\
  2354. path -- module search path; path[0] is the script directory, else ''\n\
  2355. modules -- dictionary of loaded modules\n\
  2356. \n\
  2357. displayhook -- called to show results in an interactive session\n\
  2358. excepthook -- called to handle any uncaught exception other than SystemExit\n\
  2359. To customize printing in an interactive session or to install a custom\n\
  2360. top-level exception handler, assign other functions to replace these.\n\
  2361. \n\
  2362. stdin -- standard input file object; used by input()\n\
  2363. stdout -- standard output file object; used by print()\n\
  2364. stderr -- standard error object; used for error messages\n\
  2365. By assigning other file objects (or objects that behave like files)\n\
  2366. to these, it is possible to redirect all of the interpreter's I/O.\n\
  2367. \n\
  2368. last_exc - the last uncaught exception\n\
  2369. Only available in an interactive session after a\n\
  2370. traceback has been printed.\n\
  2371. last_type -- type of last uncaught exception\n\
  2372. last_value -- value of last uncaught exception\n\
  2373. last_traceback -- traceback of last uncaught exception\n\
  2374. These three are the (deprecated) legacy representation of last_exc.\n\
  2375. "
  2376. )
  2377. /* concatenating string here */
  2378. PyDoc_STR(
  2379. "\n\
  2380. Static objects:\n\
  2381. \n\
  2382. builtin_module_names -- tuple of module names built into this interpreter\n\
  2383. copyright -- copyright notice pertaining to this interpreter\n\
  2384. exec_prefix -- prefix used to find the machine-specific Python library\n\
  2385. executable -- absolute path of the executable binary of the Python interpreter\n\
  2386. float_info -- a named tuple with information about the float implementation.\n\
  2387. float_repr_style -- string indicating the style of repr() output for floats\n\
  2388. hash_info -- a named tuple with information about the hash algorithm.\n\
  2389. hexversion -- version information encoded as a single integer\n\
  2390. implementation -- Python implementation information.\n\
  2391. int_info -- a named tuple with information about the int implementation.\n\
  2392. maxsize -- the largest supported length of containers.\n\
  2393. maxunicode -- the value of the largest Unicode code point\n\
  2394. platform -- platform identifier\n\
  2395. prefix -- prefix used to find the Python library\n\
  2396. thread_info -- a named tuple with information about the thread implementation.\n\
  2397. version -- the version of this interpreter as a string\n\
  2398. version_info -- version information as a named tuple\n\
  2399. "
  2400. )
  2401. #ifdef MS_COREDLL
  2402. /* concatenating string here */
  2403. PyDoc_STR(
  2404. "dllhandle -- [Windows only] integer handle of the Python DLL\n\
  2405. winver -- [Windows only] version number of the Python DLL\n\
  2406. "
  2407. )
  2408. #endif /* MS_COREDLL */
  2409. #ifdef MS_WINDOWS
  2410. /* concatenating string here */
  2411. PyDoc_STR(
  2412. "_enablelegacywindowsfsencoding -- [Windows only]\n\
  2413. "
  2414. )
  2415. #endif
  2416. PyDoc_STR(
  2417. "__stdin__ -- the original stdin; don't touch!\n\
  2418. __stdout__ -- the original stdout; don't touch!\n\
  2419. __stderr__ -- the original stderr; don't touch!\n\
  2420. __displayhook__ -- the original displayhook; don't touch!\n\
  2421. __excepthook__ -- the original excepthook; don't touch!\n\
  2422. \n\
  2423. Functions:\n\
  2424. \n\
  2425. displayhook() -- print an object to the screen, and save it in builtins._\n\
  2426. excepthook() -- print an exception and its traceback to sys.stderr\n\
  2427. exception() -- return the current thread's active exception\n\
  2428. exc_info() -- return information about the current thread's active exception\n\
  2429. exit() -- exit the interpreter by raising SystemExit\n\
  2430. getdlopenflags() -- returns flags to be used for dlopen() calls\n\
  2431. getprofile() -- get the global profiling function\n\
  2432. getrefcount() -- return the reference count for an object (plus one :-)\n\
  2433. getrecursionlimit() -- return the max recursion depth for the interpreter\n\
  2434. getsizeof() -- return the size of an object in bytes\n\
  2435. gettrace() -- get the global debug tracing function\n\
  2436. setdlopenflags() -- set the flags to be used for dlopen() calls\n\
  2437. setprofile() -- set the global profiling function\n\
  2438. setrecursionlimit() -- set the max recursion depth for the interpreter\n\
  2439. settrace() -- set the global debug tracing function\n\
  2440. "
  2441. )
  2442. /* end of sys_doc */ ;
  2443. PyDoc_STRVAR(flags__doc__,
  2444. "sys.flags\n\
  2445. \n\
  2446. Flags provided through command line arguments or environment vars.");
  2447. static PyTypeObject FlagsType;
  2448. static PyStructSequence_Field flags_fields[] = {
  2449. {"debug", "-d"},
  2450. {"inspect", "-i"},
  2451. {"interactive", "-i"},
  2452. {"optimize", "-O or -OO"},
  2453. {"dont_write_bytecode", "-B"},
  2454. {"no_user_site", "-s"},
  2455. {"no_site", "-S"},
  2456. {"ignore_environment", "-E"},
  2457. {"verbose", "-v"},
  2458. {"bytes_warning", "-b"},
  2459. {"quiet", "-q"},
  2460. {"hash_randomization", "-R"},
  2461. {"isolated", "-I"},
  2462. {"dev_mode", "-X dev"},
  2463. {"utf8_mode", "-X utf8"},
  2464. {"warn_default_encoding", "-X warn_default_encoding"},
  2465. {"safe_path", "-P"},
  2466. {"int_max_str_digits", "-X int_max_str_digits"},
  2467. {0}
  2468. };
  2469. static PyStructSequence_Desc flags_desc = {
  2470. "sys.flags", /* name */
  2471. flags__doc__, /* doc */
  2472. flags_fields, /* fields */
  2473. 18
  2474. };
  2475. static int
  2476. set_flags_from_config(PyInterpreterState *interp, PyObject *flags)
  2477. {
  2478. const PyPreConfig *preconfig = &interp->runtime->preconfig;
  2479. const PyConfig *config = _PyInterpreterState_GetConfig(interp);
  2480. // _PySys_UpdateConfig() modifies sys.flags in-place:
  2481. // Py_XDECREF() is needed in this case.
  2482. Py_ssize_t pos = 0;
  2483. #define SetFlagObj(expr) \
  2484. do { \
  2485. PyObject *value = (expr); \
  2486. if (value == NULL) { \
  2487. return -1; \
  2488. } \
  2489. Py_XDECREF(PyStructSequence_GET_ITEM(flags, pos)); \
  2490. PyStructSequence_SET_ITEM(flags, pos, value); \
  2491. pos++; \
  2492. } while (0)
  2493. #define SetFlag(expr) SetFlagObj(PyLong_FromLong(expr))
  2494. SetFlag(config->parser_debug);
  2495. SetFlag(config->inspect);
  2496. SetFlag(config->interactive);
  2497. SetFlag(config->optimization_level);
  2498. SetFlag(!config->write_bytecode);
  2499. SetFlag(!config->user_site_directory);
  2500. SetFlag(!config->site_import);
  2501. SetFlag(!config->use_environment);
  2502. SetFlag(config->verbose);
  2503. SetFlag(config->bytes_warning);
  2504. SetFlag(config->quiet);
  2505. SetFlag(config->use_hash_seed == 0 || config->hash_seed != 0);
  2506. SetFlag(config->isolated);
  2507. SetFlagObj(PyBool_FromLong(config->dev_mode));
  2508. SetFlag(preconfig->utf8_mode);
  2509. SetFlag(config->warn_default_encoding);
  2510. SetFlagObj(PyBool_FromLong(config->safe_path));
  2511. SetFlag(config->int_max_str_digits);
  2512. #undef SetFlagObj
  2513. #undef SetFlag
  2514. return 0;
  2515. }
  2516. static PyObject*
  2517. make_flags(PyInterpreterState *interp)
  2518. {
  2519. PyObject *flags = PyStructSequence_New(&FlagsType);
  2520. if (flags == NULL) {
  2521. return NULL;
  2522. }
  2523. if (set_flags_from_config(interp, flags) < 0) {
  2524. Py_DECREF(flags);
  2525. return NULL;
  2526. }
  2527. return flags;
  2528. }
  2529. PyDoc_STRVAR(version_info__doc__,
  2530. "sys.version_info\n\
  2531. \n\
  2532. Version information as a named tuple.");
  2533. static PyTypeObject VersionInfoType;
  2534. static PyStructSequence_Field version_info_fields[] = {
  2535. {"major", "Major release number"},
  2536. {"minor", "Minor release number"},
  2537. {"micro", "Patch release number"},
  2538. {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
  2539. {"serial", "Serial release number"},
  2540. {0}
  2541. };
  2542. static PyStructSequence_Desc version_info_desc = {
  2543. "sys.version_info", /* name */
  2544. version_info__doc__, /* doc */
  2545. version_info_fields, /* fields */
  2546. 5
  2547. };
  2548. static PyObject *
  2549. make_version_info(PyThreadState *tstate)
  2550. {
  2551. PyObject *version_info;
  2552. char *s;
  2553. int pos = 0;
  2554. version_info = PyStructSequence_New(&VersionInfoType);
  2555. if (version_info == NULL) {
  2556. return NULL;
  2557. }
  2558. /*
  2559. * These release level checks are mutually exclusive and cover
  2560. * the field, so don't get too fancy with the pre-processor!
  2561. */
  2562. #if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
  2563. s = "alpha";
  2564. #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
  2565. s = "beta";
  2566. #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
  2567. s = "candidate";
  2568. #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
  2569. s = "final";
  2570. #endif
  2571. #define SetIntItem(flag) \
  2572. PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
  2573. #define SetStrItem(flag) \
  2574. PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
  2575. SetIntItem(PY_MAJOR_VERSION);
  2576. SetIntItem(PY_MINOR_VERSION);
  2577. SetIntItem(PY_MICRO_VERSION);
  2578. SetStrItem(s);
  2579. SetIntItem(PY_RELEASE_SERIAL);
  2580. #undef SetIntItem
  2581. #undef SetStrItem
  2582. if (_PyErr_Occurred(tstate)) {
  2583. Py_CLEAR(version_info);
  2584. return NULL;
  2585. }
  2586. return version_info;
  2587. }
  2588. /* sys.implementation values */
  2589. #define NAME "cpython"
  2590. const char *_PySys_ImplName = NAME;
  2591. #define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
  2592. #define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
  2593. #define TAG NAME "-" MAJOR MINOR
  2594. const char *_PySys_ImplCacheTag = TAG;
  2595. #undef NAME
  2596. #undef MAJOR
  2597. #undef MINOR
  2598. #undef TAG
  2599. static PyObject *
  2600. make_impl_info(PyObject *version_info)
  2601. {
  2602. int res;
  2603. PyObject *impl_info, *value, *ns;
  2604. impl_info = PyDict_New();
  2605. if (impl_info == NULL)
  2606. return NULL;
  2607. /* populate the dict */
  2608. value = PyUnicode_FromString(_PySys_ImplName);
  2609. if (value == NULL)
  2610. goto error;
  2611. res = PyDict_SetItemString(impl_info, "name", value);
  2612. Py_DECREF(value);
  2613. if (res < 0)
  2614. goto error;
  2615. value = PyUnicode_FromString(_PySys_ImplCacheTag);
  2616. if (value == NULL)
  2617. goto error;
  2618. res = PyDict_SetItemString(impl_info, "cache_tag", value);
  2619. Py_DECREF(value);
  2620. if (res < 0)
  2621. goto error;
  2622. res = PyDict_SetItemString(impl_info, "version", version_info);
  2623. if (res < 0)
  2624. goto error;
  2625. value = PyLong_FromLong(PY_VERSION_HEX);
  2626. if (value == NULL)
  2627. goto error;
  2628. res = PyDict_SetItemString(impl_info, "hexversion", value);
  2629. Py_DECREF(value);
  2630. if (res < 0)
  2631. goto error;
  2632. #ifdef MULTIARCH
  2633. value = PyUnicode_FromString(MULTIARCH);
  2634. if (value == NULL)
  2635. goto error;
  2636. res = PyDict_SetItemString(impl_info, "_multiarch", value);
  2637. Py_DECREF(value);
  2638. if (res < 0)
  2639. goto error;
  2640. #endif
  2641. /* dict ready */
  2642. ns = _PyNamespace_New(impl_info);
  2643. Py_DECREF(impl_info);
  2644. return ns;
  2645. error:
  2646. Py_CLEAR(impl_info);
  2647. return NULL;
  2648. }
  2649. #ifdef __EMSCRIPTEN__
  2650. PyDoc_STRVAR(emscripten_info__doc__,
  2651. "sys._emscripten_info\n\
  2652. \n\
  2653. WebAssembly Emscripten platform information.");
  2654. static PyTypeObject *EmscriptenInfoType;
  2655. static PyStructSequence_Field emscripten_info_fields[] = {
  2656. {"emscripten_version", "Emscripten version (major, minor, micro)"},
  2657. {"runtime", "Runtime (Node.JS version, browser user agent)"},
  2658. {"pthreads", "pthread support"},
  2659. {"shared_memory", "shared memory support"},
  2660. {0}
  2661. };
  2662. static PyStructSequence_Desc emscripten_info_desc = {
  2663. "sys._emscripten_info", /* name */
  2664. emscripten_info__doc__ , /* doc */
  2665. emscripten_info_fields, /* fields */
  2666. 4
  2667. };
  2668. EM_JS(char *, _Py_emscripten_runtime, (void), {
  2669. var info;
  2670. if (typeof navigator == 'object') {
  2671. info = navigator.userAgent;
  2672. } else if (typeof process == 'object') {
  2673. info = "Node.js ".concat(process.version);
  2674. } else {
  2675. info = "UNKNOWN";
  2676. }
  2677. var len = lengthBytesUTF8(info) + 1;
  2678. var res = _malloc(len);
  2679. if (res) stringToUTF8(info, res, len);
  2680. #if __wasm64__
  2681. return BigInt(res);
  2682. #else
  2683. return res;
  2684. #endif
  2685. });
  2686. static PyObject *
  2687. make_emscripten_info(void)
  2688. {
  2689. PyObject *emscripten_info = NULL;
  2690. PyObject *version = NULL;
  2691. char *ua;
  2692. int pos = 0;
  2693. emscripten_info = PyStructSequence_New(EmscriptenInfoType);
  2694. if (emscripten_info == NULL) {
  2695. return NULL;
  2696. }
  2697. version = Py_BuildValue("(iii)",
  2698. __EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__);
  2699. if (version == NULL) {
  2700. goto error;
  2701. }
  2702. PyStructSequence_SET_ITEM(emscripten_info, pos++, version);
  2703. ua = _Py_emscripten_runtime();
  2704. if (ua != NULL) {
  2705. PyObject *oua = PyUnicode_DecodeUTF8(ua, strlen(ua), "strict");
  2706. free(ua);
  2707. if (oua == NULL) {
  2708. goto error;
  2709. }
  2710. PyStructSequence_SET_ITEM(emscripten_info, pos++, oua);
  2711. } else {
  2712. PyStructSequence_SET_ITEM(emscripten_info, pos++, Py_NewRef(Py_None));
  2713. }
  2714. #define SetBoolItem(flag) \
  2715. PyStructSequence_SET_ITEM(emscripten_info, pos++, PyBool_FromLong(flag))
  2716. #ifdef __EMSCRIPTEN_PTHREADS__
  2717. SetBoolItem(1);
  2718. #else
  2719. SetBoolItem(0);
  2720. #endif
  2721. #ifdef __EMSCRIPTEN_SHARED_MEMORY__
  2722. SetBoolItem(1);
  2723. #else
  2724. SetBoolItem(0);
  2725. #endif
  2726. #undef SetBoolItem
  2727. if (PyErr_Occurred()) {
  2728. goto error;
  2729. }
  2730. return emscripten_info;
  2731. error:
  2732. Py_CLEAR(emscripten_info);
  2733. return NULL;
  2734. }
  2735. #endif // __EMSCRIPTEN__
  2736. static struct PyModuleDef sysmodule = {
  2737. PyModuleDef_HEAD_INIT,
  2738. "sys",
  2739. sys_doc,
  2740. -1, /* multiple "initialization" just copies the module dict. */
  2741. sys_methods,
  2742. NULL,
  2743. NULL,
  2744. NULL,
  2745. NULL
  2746. };
  2747. /* Updating the sys namespace, returning NULL pointer on error */
  2748. #define SET_SYS(key, value) \
  2749. do { \
  2750. PyObject *v = (value); \
  2751. if (v == NULL) { \
  2752. goto err_occurred; \
  2753. } \
  2754. res = PyDict_SetItemString(sysdict, key, v); \
  2755. Py_DECREF(v); \
  2756. if (res < 0) { \
  2757. goto err_occurred; \
  2758. } \
  2759. } while (0)
  2760. #define SET_SYS_FROM_STRING(key, value) \
  2761. SET_SYS(key, PyUnicode_FromString(value))
  2762. static PyStatus
  2763. _PySys_InitCore(PyThreadState *tstate, PyObject *sysdict)
  2764. {
  2765. PyObject *version_info;
  2766. int res;
  2767. PyInterpreterState *interp = tstate->interp;
  2768. /* stdin/stdout/stderr are set in pylifecycle.c */
  2769. #define COPY_SYS_ATTR(tokey, fromkey) \
  2770. SET_SYS(tokey, PyMapping_GetItemString(sysdict, fromkey))
  2771. COPY_SYS_ATTR("__displayhook__", "displayhook");
  2772. COPY_SYS_ATTR("__excepthook__", "excepthook");
  2773. COPY_SYS_ATTR("__breakpointhook__", "breakpointhook");
  2774. COPY_SYS_ATTR("__unraisablehook__", "unraisablehook");
  2775. #undef COPY_SYS_ATTR
  2776. SET_SYS_FROM_STRING("version", Py_GetVersion());
  2777. SET_SYS("hexversion", PyLong_FromLong(PY_VERSION_HEX));
  2778. SET_SYS("_git", Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
  2779. _Py_gitversion()));
  2780. SET_SYS_FROM_STRING("_framework", _PYTHONFRAMEWORK);
  2781. SET_SYS("api_version", PyLong_FromLong(PYTHON_API_VERSION));
  2782. SET_SYS_FROM_STRING("copyright", Py_GetCopyright());
  2783. SET_SYS_FROM_STRING("platform", Py_GetPlatform());
  2784. SET_SYS("maxsize", PyLong_FromSsize_t(PY_SSIZE_T_MAX));
  2785. SET_SYS("float_info", PyFloat_GetInfo());
  2786. SET_SYS("int_info", PyLong_GetInfo());
  2787. /* initialize hash_info */
  2788. if (_PyStructSequence_InitBuiltin(interp, &Hash_InfoType,
  2789. &hash_info_desc) < 0)
  2790. {
  2791. goto type_init_failed;
  2792. }
  2793. SET_SYS("hash_info", get_hash_info(tstate));
  2794. SET_SYS("maxunicode", PyLong_FromLong(0x10FFFF));
  2795. SET_SYS("builtin_module_names", list_builtin_module_names());
  2796. SET_SYS("stdlib_module_names", list_stdlib_module_names());
  2797. #if PY_BIG_ENDIAN
  2798. SET_SYS_FROM_STRING("byteorder", "big");
  2799. #else
  2800. SET_SYS_FROM_STRING("byteorder", "little");
  2801. #endif
  2802. #ifdef MS_COREDLL
  2803. SET_SYS("dllhandle", PyLong_FromVoidPtr(PyWin_DLLhModule));
  2804. SET_SYS_FROM_STRING("winver", PyWin_DLLVersionString);
  2805. #endif
  2806. #ifdef ABIFLAGS
  2807. SET_SYS_FROM_STRING("abiflags", ABIFLAGS);
  2808. #endif
  2809. #define ENSURE_INFO_TYPE(TYPE, DESC) \
  2810. do { \
  2811. if (_PyStructSequence_InitBuiltinWithFlags( \
  2812. interp, &TYPE, &DESC, Py_TPFLAGS_DISALLOW_INSTANTIATION) < 0) { \
  2813. goto type_init_failed; \
  2814. } \
  2815. } while (0)
  2816. /* version_info */
  2817. ENSURE_INFO_TYPE(VersionInfoType, version_info_desc);
  2818. version_info = make_version_info(tstate);
  2819. SET_SYS("version_info", version_info);
  2820. /* implementation */
  2821. SET_SYS("implementation", make_impl_info(version_info));
  2822. // sys.flags: updated in-place later by _PySys_UpdateConfig()
  2823. ENSURE_INFO_TYPE(FlagsType, flags_desc);
  2824. SET_SYS("flags", make_flags(tstate->interp));
  2825. #if defined(MS_WINDOWS)
  2826. /* getwindowsversion */
  2827. ENSURE_INFO_TYPE(WindowsVersionType, windows_version_desc);
  2828. SET_SYS_FROM_STRING("_vpath", VPATH);
  2829. #endif
  2830. #undef ENSURE_INFO_TYPE
  2831. /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
  2832. #if _PY_SHORT_FLOAT_REPR == 1
  2833. SET_SYS_FROM_STRING("float_repr_style", "short");
  2834. #else
  2835. SET_SYS_FROM_STRING("float_repr_style", "legacy");
  2836. #endif
  2837. SET_SYS("thread_info", PyThread_GetInfo());
  2838. /* initialize asyncgen_hooks */
  2839. if (_PyStructSequence_InitBuiltin(interp, &AsyncGenHooksType,
  2840. &asyncgen_hooks_desc) < 0)
  2841. {
  2842. goto type_init_failed;
  2843. }
  2844. #ifdef __EMSCRIPTEN__
  2845. if (EmscriptenInfoType == NULL) {
  2846. EmscriptenInfoType = PyStructSequence_NewType(&emscripten_info_desc);
  2847. if (EmscriptenInfoType == NULL) {
  2848. goto type_init_failed;
  2849. }
  2850. }
  2851. SET_SYS("_emscripten_info", make_emscripten_info());
  2852. #endif
  2853. /* adding sys.path_hooks and sys.path_importer_cache */
  2854. SET_SYS("meta_path", PyList_New(0));
  2855. SET_SYS("path_importer_cache", PyDict_New());
  2856. SET_SYS("path_hooks", PyList_New(0));
  2857. if (_PyErr_Occurred(tstate)) {
  2858. goto err_occurred;
  2859. }
  2860. return _PyStatus_OK();
  2861. type_init_failed:
  2862. return _PyStatus_ERR("failed to initialize a type");
  2863. err_occurred:
  2864. return _PyStatus_ERR("can't initialize sys module");
  2865. }
  2866. static int
  2867. sys_add_xoption(PyObject *opts, const wchar_t *s)
  2868. {
  2869. PyObject *name, *value = NULL;
  2870. const wchar_t *name_end = wcschr(s, L'=');
  2871. if (!name_end) {
  2872. name = PyUnicode_FromWideChar(s, -1);
  2873. if (name == NULL) {
  2874. goto error;
  2875. }
  2876. value = Py_NewRef(Py_True);
  2877. }
  2878. else {
  2879. name = PyUnicode_FromWideChar(s, name_end - s);
  2880. if (name == NULL) {
  2881. goto error;
  2882. }
  2883. value = PyUnicode_FromWideChar(name_end + 1, -1);
  2884. if (value == NULL) {
  2885. goto error;
  2886. }
  2887. }
  2888. if (PyDict_SetItem(opts, name, value) < 0) {
  2889. goto error;
  2890. }
  2891. Py_DECREF(name);
  2892. Py_DECREF(value);
  2893. return 0;
  2894. error:
  2895. Py_XDECREF(name);
  2896. Py_XDECREF(value);
  2897. return -1;
  2898. }
  2899. static PyObject*
  2900. sys_create_xoptions_dict(const PyConfig *config)
  2901. {
  2902. Py_ssize_t nxoption = config->xoptions.length;
  2903. wchar_t * const * xoptions = config->xoptions.items;
  2904. PyObject *dict = PyDict_New();
  2905. if (dict == NULL) {
  2906. return NULL;
  2907. }
  2908. for (Py_ssize_t i=0; i < nxoption; i++) {
  2909. const wchar_t *option = xoptions[i];
  2910. if (sys_add_xoption(dict, option) < 0) {
  2911. Py_DECREF(dict);
  2912. return NULL;
  2913. }
  2914. }
  2915. return dict;
  2916. }
  2917. // Update sys attributes for a new PyConfig configuration.
  2918. // This function also adds attributes that _PySys_InitCore() didn't add.
  2919. int
  2920. _PySys_UpdateConfig(PyThreadState *tstate)
  2921. {
  2922. PyInterpreterState *interp = tstate->interp;
  2923. PyObject *sysdict = interp->sysdict;
  2924. const PyConfig *config = _PyInterpreterState_GetConfig(interp);
  2925. int res;
  2926. #define COPY_LIST(KEY, VALUE) \
  2927. SET_SYS(KEY, _PyWideStringList_AsList(&(VALUE)));
  2928. #define SET_SYS_FROM_WSTR(KEY, VALUE) \
  2929. SET_SYS(KEY, PyUnicode_FromWideChar(VALUE, -1));
  2930. #define COPY_WSTR(SYS_ATTR, WSTR) \
  2931. if (WSTR != NULL) { \
  2932. SET_SYS_FROM_WSTR(SYS_ATTR, WSTR); \
  2933. }
  2934. if (config->module_search_paths_set) {
  2935. COPY_LIST("path", config->module_search_paths);
  2936. }
  2937. COPY_WSTR("executable", config->executable);
  2938. COPY_WSTR("_base_executable", config->base_executable);
  2939. COPY_WSTR("prefix", config->prefix);
  2940. COPY_WSTR("base_prefix", config->base_prefix);
  2941. COPY_WSTR("exec_prefix", config->exec_prefix);
  2942. COPY_WSTR("base_exec_prefix", config->base_exec_prefix);
  2943. COPY_WSTR("platlibdir", config->platlibdir);
  2944. if (config->pycache_prefix != NULL) {
  2945. SET_SYS_FROM_WSTR("pycache_prefix", config->pycache_prefix);
  2946. } else {
  2947. if (PyDict_SetItemString(sysdict, "pycache_prefix", Py_None) < 0) {
  2948. return -1;
  2949. }
  2950. }
  2951. COPY_LIST("argv", config->argv);
  2952. COPY_LIST("orig_argv", config->orig_argv);
  2953. COPY_LIST("warnoptions", config->warnoptions);
  2954. SET_SYS("_xoptions", sys_create_xoptions_dict(config));
  2955. const wchar_t *stdlibdir = _Py_GetStdlibDir();
  2956. if (stdlibdir != NULL) {
  2957. SET_SYS_FROM_WSTR("_stdlib_dir", stdlibdir);
  2958. }
  2959. else {
  2960. if (PyDict_SetItemString(sysdict, "_stdlib_dir", Py_None) < 0) {
  2961. return -1;
  2962. }
  2963. }
  2964. #undef SET_SYS_FROM_WSTR
  2965. #undef COPY_LIST
  2966. #undef COPY_WSTR
  2967. // sys.flags
  2968. PyObject *flags = _PySys_GetObject(interp, "flags"); // borrowed ref
  2969. if (flags == NULL) {
  2970. if (!_PyErr_Occurred(tstate)) {
  2971. _PyErr_SetString(tstate, PyExc_RuntimeError, "lost sys.flags");
  2972. }
  2973. return -1;
  2974. }
  2975. if (set_flags_from_config(interp, flags) < 0) {
  2976. return -1;
  2977. }
  2978. SET_SYS("dont_write_bytecode", PyBool_FromLong(!config->write_bytecode));
  2979. if (_PyErr_Occurred(tstate)) {
  2980. goto err_occurred;
  2981. }
  2982. return 0;
  2983. err_occurred:
  2984. return -1;
  2985. }
  2986. #undef SET_SYS
  2987. #undef SET_SYS_FROM_STRING
  2988. /* Set up a preliminary stderr printer until we have enough
  2989. infrastructure for the io module in place.
  2990. Use UTF-8/backslashreplace and ignore EAGAIN errors. */
  2991. static PyStatus
  2992. _PySys_SetPreliminaryStderr(PyObject *sysdict)
  2993. {
  2994. PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
  2995. if (pstderr == NULL) {
  2996. goto error;
  2997. }
  2998. if (PyDict_SetItem(sysdict, &_Py_ID(stderr), pstderr) < 0) {
  2999. goto error;
  3000. }
  3001. if (PyDict_SetItemString(sysdict, "__stderr__", pstderr) < 0) {
  3002. goto error;
  3003. }
  3004. Py_DECREF(pstderr);
  3005. return _PyStatus_OK();
  3006. error:
  3007. Py_XDECREF(pstderr);
  3008. return _PyStatus_ERR("can't set preliminary stderr");
  3009. }
  3010. PyObject *_Py_CreateMonitoringObject(void);
  3011. /* Create sys module without all attributes.
  3012. _PySys_UpdateConfig() should be called later to add remaining attributes. */
  3013. PyStatus
  3014. _PySys_Create(PyThreadState *tstate, PyObject **sysmod_p)
  3015. {
  3016. assert(!_PyErr_Occurred(tstate));
  3017. PyInterpreterState *interp = tstate->interp;
  3018. PyObject *modules = _PyImport_InitModules(interp);
  3019. if (modules == NULL) {
  3020. goto error;
  3021. }
  3022. PyObject *sysmod = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
  3023. if (sysmod == NULL) {
  3024. return _PyStatus_ERR("failed to create a module object");
  3025. }
  3026. PyObject *sysdict = PyModule_GetDict(sysmod);
  3027. if (sysdict == NULL) {
  3028. goto error;
  3029. }
  3030. interp->sysdict = Py_NewRef(sysdict);
  3031. interp->sysdict_copy = PyDict_Copy(sysdict);
  3032. if (interp->sysdict_copy == NULL) {
  3033. goto error;
  3034. }
  3035. if (PyDict_SetItemString(sysdict, "modules", modules) < 0) {
  3036. goto error;
  3037. }
  3038. PyStatus status = _PySys_SetPreliminaryStderr(sysdict);
  3039. if (_PyStatus_EXCEPTION(status)) {
  3040. return status;
  3041. }
  3042. status = _PySys_InitCore(tstate, sysdict);
  3043. if (_PyStatus_EXCEPTION(status)) {
  3044. return status;
  3045. }
  3046. if (_PyImport_FixupBuiltin(sysmod, "sys", modules) < 0) {
  3047. goto error;
  3048. }
  3049. PyObject *monitoring = _Py_CreateMonitoringObject();
  3050. if (monitoring == NULL) {
  3051. goto error;
  3052. }
  3053. int err = PyDict_SetItemString(sysdict, "monitoring", monitoring);
  3054. Py_DECREF(monitoring);
  3055. if (err < 0) {
  3056. goto error;
  3057. }
  3058. assert(!_PyErr_Occurred(tstate));
  3059. *sysmod_p = sysmod;
  3060. return _PyStatus_OK();
  3061. error:
  3062. return _PyStatus_ERR("can't initialize sys module");
  3063. }
  3064. void
  3065. _PySys_FiniTypes(PyInterpreterState *interp)
  3066. {
  3067. _PyStructSequence_FiniBuiltin(interp, &VersionInfoType);
  3068. _PyStructSequence_FiniBuiltin(interp, &FlagsType);
  3069. #if defined(MS_WINDOWS)
  3070. _PyStructSequence_FiniBuiltin(interp, &WindowsVersionType);
  3071. #endif
  3072. _PyStructSequence_FiniBuiltin(interp, &Hash_InfoType);
  3073. _PyStructSequence_FiniBuiltin(interp, &AsyncGenHooksType);
  3074. #ifdef __EMSCRIPTEN__
  3075. if (_Py_IsMainInterpreter(interp)) {
  3076. Py_CLEAR(EmscriptenInfoType);
  3077. }
  3078. #endif
  3079. }
  3080. static PyObject *
  3081. makepathobject(const wchar_t *path, wchar_t delim)
  3082. {
  3083. int i, n;
  3084. const wchar_t *p;
  3085. PyObject *v, *w;
  3086. n = 1;
  3087. p = path;
  3088. while ((p = wcschr(p, delim)) != NULL) {
  3089. n++;
  3090. p++;
  3091. }
  3092. v = PyList_New(n);
  3093. if (v == NULL)
  3094. return NULL;
  3095. for (i = 0; ; i++) {
  3096. p = wcschr(path, delim);
  3097. if (p == NULL)
  3098. p = path + wcslen(path); /* End of string */
  3099. w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
  3100. if (w == NULL) {
  3101. Py_DECREF(v);
  3102. return NULL;
  3103. }
  3104. PyList_SET_ITEM(v, i, w);
  3105. if (*p == '\0')
  3106. break;
  3107. path = p+1;
  3108. }
  3109. return v;
  3110. }
  3111. void
  3112. PySys_SetPath(const wchar_t *path)
  3113. {
  3114. PyObject *v;
  3115. if ((v = makepathobject(path, DELIM)) == NULL)
  3116. Py_FatalError("can't create sys.path");
  3117. PyInterpreterState *interp = _PyInterpreterState_GET();
  3118. if (sys_set_object(interp, &_Py_ID(path), v) != 0) {
  3119. Py_FatalError("can't assign sys.path");
  3120. }
  3121. Py_DECREF(v);
  3122. }
  3123. static PyObject *
  3124. make_sys_argv(int argc, wchar_t * const * argv)
  3125. {
  3126. PyObject *list = PyList_New(argc);
  3127. if (list == NULL) {
  3128. return NULL;
  3129. }
  3130. for (Py_ssize_t i = 0; i < argc; i++) {
  3131. PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
  3132. if (v == NULL) {
  3133. Py_DECREF(list);
  3134. return NULL;
  3135. }
  3136. PyList_SET_ITEM(list, i, v);
  3137. }
  3138. return list;
  3139. }
  3140. void
  3141. PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
  3142. {
  3143. wchar_t* empty_argv[1] = {L""};
  3144. PyThreadState *tstate = _PyThreadState_GET();
  3145. if (argc < 1 || argv == NULL) {
  3146. /* Ensure at least one (empty) argument is seen */
  3147. argv = empty_argv;
  3148. argc = 1;
  3149. }
  3150. PyObject *av = make_sys_argv(argc, argv);
  3151. if (av == NULL) {
  3152. Py_FatalError("no mem for sys.argv");
  3153. }
  3154. if (sys_set_object_str(tstate->interp, "argv", av) != 0) {
  3155. Py_DECREF(av);
  3156. Py_FatalError("can't assign sys.argv");
  3157. }
  3158. Py_DECREF(av);
  3159. if (updatepath) {
  3160. /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
  3161. If argv[0] is a symlink, use the real path. */
  3162. const PyWideStringList argv_list = {.length = argc, .items = argv};
  3163. PyObject *path0 = NULL;
  3164. if (_PyPathConfig_ComputeSysPath0(&argv_list, &path0)) {
  3165. if (path0 == NULL) {
  3166. Py_FatalError("can't compute path0 from argv");
  3167. }
  3168. PyObject *sys_path = _PySys_GetAttr(tstate, &_Py_ID(path));
  3169. if (sys_path != NULL) {
  3170. if (PyList_Insert(sys_path, 0, path0) < 0) {
  3171. Py_DECREF(path0);
  3172. Py_FatalError("can't prepend path0 to sys.path");
  3173. }
  3174. }
  3175. Py_DECREF(path0);
  3176. }
  3177. }
  3178. }
  3179. void
  3180. PySys_SetArgv(int argc, wchar_t **argv)
  3181. {
  3182. _Py_COMP_DIAG_PUSH
  3183. _Py_COMP_DIAG_IGNORE_DEPR_DECLS
  3184. PySys_SetArgvEx(argc, argv, 0);
  3185. _Py_COMP_DIAG_POP
  3186. }
  3187. /* Reimplementation of PyFile_WriteString() no calling indirectly
  3188. PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
  3189. static int
  3190. sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
  3191. {
  3192. if (file == NULL)
  3193. return -1;
  3194. assert(unicode != NULL);
  3195. PyObject *result = _PyObject_CallMethodOneArg(file, &_Py_ID(write), unicode);
  3196. if (result == NULL) {
  3197. return -1;
  3198. }
  3199. Py_DECREF(result);
  3200. return 0;
  3201. }
  3202. static int
  3203. sys_pyfile_write(const char *text, PyObject *file)
  3204. {
  3205. PyObject *unicode = NULL;
  3206. int err;
  3207. if (file == NULL)
  3208. return -1;
  3209. unicode = PyUnicode_FromString(text);
  3210. if (unicode == NULL)
  3211. return -1;
  3212. err = sys_pyfile_write_unicode(unicode, file);
  3213. Py_DECREF(unicode);
  3214. return err;
  3215. }
  3216. /* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
  3217. Adapted from code submitted by Just van Rossum.
  3218. PySys_WriteStdout(format, ...)
  3219. PySys_WriteStderr(format, ...)
  3220. The first function writes to sys.stdout; the second to sys.stderr. When
  3221. there is a problem, they write to the real (C level) stdout or stderr;
  3222. no exceptions are raised.
  3223. PyErr_CheckSignals() is not called to avoid the execution of the Python
  3224. signal handlers: they may raise a new exception whereas sys_write()
  3225. ignores all exceptions.
  3226. Both take a printf-style format string as their first argument followed
  3227. by a variable length argument list determined by the format string.
  3228. *** WARNING ***
  3229. The format should limit the total size of the formatted output string to
  3230. 1000 bytes. In particular, this means that no unrestricted "%s" formats
  3231. should occur; these should be limited using "%.<N>s where <N> is a
  3232. decimal number calculated so that <N> plus the maximum size of other
  3233. formatted text does not exceed 1000 bytes. Also watch out for "%f",
  3234. which can print hundreds of digits for very large numbers.
  3235. */
  3236. static void
  3237. sys_write(PyObject *key, FILE *fp, const char *format, va_list va)
  3238. {
  3239. PyObject *file;
  3240. char buffer[1001];
  3241. int written;
  3242. PyThreadState *tstate = _PyThreadState_GET();
  3243. PyObject *exc = _PyErr_GetRaisedException(tstate);
  3244. file = _PySys_GetAttr(tstate, key);
  3245. written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
  3246. if (sys_pyfile_write(buffer, file) != 0) {
  3247. _PyErr_Clear(tstate);
  3248. fputs(buffer, fp);
  3249. }
  3250. if (written < 0 || (size_t)written >= sizeof(buffer)) {
  3251. const char *truncated = "... truncated";
  3252. if (sys_pyfile_write(truncated, file) != 0)
  3253. fputs(truncated, fp);
  3254. }
  3255. _PyErr_SetRaisedException(tstate, exc);
  3256. }
  3257. void
  3258. PySys_WriteStdout(const char *format, ...)
  3259. {
  3260. va_list va;
  3261. va_start(va, format);
  3262. sys_write(&_Py_ID(stdout), stdout, format, va);
  3263. va_end(va);
  3264. }
  3265. void
  3266. PySys_WriteStderr(const char *format, ...)
  3267. {
  3268. va_list va;
  3269. va_start(va, format);
  3270. sys_write(&_Py_ID(stderr), stderr, format, va);
  3271. va_end(va);
  3272. }
  3273. static void
  3274. sys_format(PyObject *key, FILE *fp, const char *format, va_list va)
  3275. {
  3276. PyObject *file, *message;
  3277. const char *utf8;
  3278. PyThreadState *tstate = _PyThreadState_GET();
  3279. PyObject *exc = _PyErr_GetRaisedException(tstate);
  3280. file = _PySys_GetAttr(tstate, key);
  3281. message = PyUnicode_FromFormatV(format, va);
  3282. if (message != NULL) {
  3283. if (sys_pyfile_write_unicode(message, file) != 0) {
  3284. _PyErr_Clear(tstate);
  3285. utf8 = PyUnicode_AsUTF8(message);
  3286. if (utf8 != NULL)
  3287. fputs(utf8, fp);
  3288. }
  3289. Py_DECREF(message);
  3290. }
  3291. _PyErr_SetRaisedException(tstate, exc);
  3292. }
  3293. void
  3294. PySys_FormatStdout(const char *format, ...)
  3295. {
  3296. va_list va;
  3297. va_start(va, format);
  3298. sys_format(&_Py_ID(stdout), stdout, format, va);
  3299. va_end(va);
  3300. }
  3301. void
  3302. PySys_FormatStderr(const char *format, ...)
  3303. {
  3304. va_list va;
  3305. va_start(va, format);
  3306. sys_format(&_Py_ID(stderr), stderr, format, va);
  3307. va_end(va);
  3308. }