sysmodule.c 107 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923
  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_LATIN1_CHR('_'), 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. if (PyFile_WriteObject(_Py_LATIN1_CHR('\n'), outf, Py_PRINT_RAW) != 0)
  656. return NULL;
  657. if (PyObject_SetAttr(builtins, _Py_LATIN1_CHR('_'), o) != 0)
  658. return NULL;
  659. Py_RETURN_NONE;
  660. }
  661. /*[clinic input]
  662. sys.excepthook
  663. exctype: object
  664. value: object
  665. traceback: object
  666. /
  667. Handle an exception by displaying it with a traceback on sys.stderr.
  668. [clinic start generated code]*/
  669. static PyObject *
  670. sys_excepthook_impl(PyObject *module, PyObject *exctype, PyObject *value,
  671. PyObject *traceback)
  672. /*[clinic end generated code: output=18d99fdda21b6b5e input=ecf606fa826f19d9]*/
  673. {
  674. PyErr_Display(NULL, value, traceback);
  675. Py_RETURN_NONE;
  676. }
  677. /*[clinic input]
  678. sys.exception
  679. Return the current exception.
  680. Return the most recent exception caught by an except clause
  681. in the current stack frame or in an older stack frame, or None
  682. if no such exception exists.
  683. [clinic start generated code]*/
  684. static PyObject *
  685. sys_exception_impl(PyObject *module)
  686. /*[clinic end generated code: output=2381ee2f25953e40 input=c88fbb94b6287431]*/
  687. {
  688. _PyErr_StackItem *err_info = _PyErr_GetTopmostException(_PyThreadState_GET());
  689. if (err_info->exc_value != NULL) {
  690. return Py_NewRef(err_info->exc_value);
  691. }
  692. Py_RETURN_NONE;
  693. }
  694. /*[clinic input]
  695. sys.exc_info
  696. Return current exception information: (type, value, traceback).
  697. Return information about the most recent exception caught by an except
  698. clause in the current stack frame or in an older stack frame.
  699. [clinic start generated code]*/
  700. static PyObject *
  701. sys_exc_info_impl(PyObject *module)
  702. /*[clinic end generated code: output=3afd0940cf3a4d30 input=b5c5bf077788a3e5]*/
  703. {
  704. _PyErr_StackItem *err_info = _PyErr_GetTopmostException(_PyThreadState_GET());
  705. return _PyErr_StackItemToExcInfoTuple(err_info);
  706. }
  707. /*[clinic input]
  708. sys.unraisablehook
  709. unraisable: object
  710. /
  711. Handle an unraisable exception.
  712. The unraisable argument has the following attributes:
  713. * exc_type: Exception type.
  714. * exc_value: Exception value, can be None.
  715. * exc_traceback: Exception traceback, can be None.
  716. * err_msg: Error message, can be None.
  717. * object: Object causing the exception, can be None.
  718. [clinic start generated code]*/
  719. static PyObject *
  720. sys_unraisablehook(PyObject *module, PyObject *unraisable)
  721. /*[clinic end generated code: output=bb92838b32abaa14 input=ec3af148294af8d3]*/
  722. {
  723. return _PyErr_WriteUnraisableDefaultHook(unraisable);
  724. }
  725. /*[clinic input]
  726. sys.exit
  727. status: object = None
  728. /
  729. Exit the interpreter by raising SystemExit(status).
  730. If the status is omitted or None, it defaults to zero (i.e., success).
  731. If the status is an integer, it will be used as the system exit status.
  732. If it is another kind of object, it will be printed and the system
  733. exit status will be one (i.e., failure).
  734. [clinic start generated code]*/
  735. static PyObject *
  736. sys_exit_impl(PyObject *module, PyObject *status)
  737. /*[clinic end generated code: output=13870986c1ab2ec0 input=b86ca9497baa94f2]*/
  738. {
  739. /* Raise SystemExit so callers may catch it or clean up. */
  740. PyErr_SetObject(PyExc_SystemExit, status);
  741. return NULL;
  742. }
  743. /*[clinic input]
  744. sys.getdefaultencoding
  745. Return the current default encoding used by the Unicode implementation.
  746. [clinic start generated code]*/
  747. static PyObject *
  748. sys_getdefaultencoding_impl(PyObject *module)
  749. /*[clinic end generated code: output=256d19dfcc0711e6 input=d416856ddbef6909]*/
  750. {
  751. _Py_DECLARE_STR(utf_8, "utf-8");
  752. PyObject *ret = &_Py_STR(utf_8);
  753. return Py_NewRef(ret);
  754. }
  755. /*[clinic input]
  756. sys.getfilesystemencoding
  757. Return the encoding used to convert Unicode filenames to OS filenames.
  758. [clinic start generated code]*/
  759. static PyObject *
  760. sys_getfilesystemencoding_impl(PyObject *module)
  761. /*[clinic end generated code: output=1dc4bdbe9be44aa7 input=8475f8649b8c7d8c]*/
  762. {
  763. PyInterpreterState *interp = _PyInterpreterState_GET();
  764. const PyConfig *config = _PyInterpreterState_GetConfig(interp);
  765. return PyUnicode_FromWideChar(config->filesystem_encoding, -1);
  766. }
  767. /*[clinic input]
  768. sys.getfilesystemencodeerrors
  769. Return the error mode used Unicode to OS filename conversion.
  770. [clinic start generated code]*/
  771. static PyObject *
  772. sys_getfilesystemencodeerrors_impl(PyObject *module)
  773. /*[clinic end generated code: output=ba77b36bbf7c96f5 input=22a1e8365566f1e5]*/
  774. {
  775. PyInterpreterState *interp = _PyInterpreterState_GET();
  776. const PyConfig *config = _PyInterpreterState_GetConfig(interp);
  777. return PyUnicode_FromWideChar(config->filesystem_errors, -1);
  778. }
  779. /*[clinic input]
  780. sys.intern
  781. string as s: unicode
  782. /
  783. ``Intern'' the given string.
  784. This enters the string in the (global) table of interned strings whose
  785. purpose is to speed up dictionary lookups. Return the string itself or
  786. the previously interned string object with the same value.
  787. [clinic start generated code]*/
  788. static PyObject *
  789. sys_intern_impl(PyObject *module, PyObject *s)
  790. /*[clinic end generated code: output=be680c24f5c9e5d6 input=849483c006924e2f]*/
  791. {
  792. if (PyUnicode_CheckExact(s)) {
  793. PyInterpreterState *interp = _PyInterpreterState_GET();
  794. Py_INCREF(s);
  795. _PyUnicode_InternMortal(interp, &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. *
  1601. _only_immortal: bool = False
  1602. Return the number of elements of the unicode interned dictionary
  1603. [clinic start generated code]*/
  1604. static Py_ssize_t
  1605. sys_getunicodeinternedsize_impl(PyObject *module, int _only_immortal)
  1606. /*[clinic end generated code: output=29a6377a94a14f70 input=0330b3408dd5bcc6]*/
  1607. {
  1608. if (_only_immortal) {
  1609. return _PyUnicode_InternedSize_Immortal();
  1610. }
  1611. else {
  1612. return _PyUnicode_InternedSize();
  1613. }
  1614. }
  1615. /*[clinic input]
  1616. sys._getframe
  1617. depth: int = 0
  1618. /
  1619. Return a frame object from the call stack.
  1620. If optional integer depth is given, return the frame object that many
  1621. calls below the top of the stack. If that is deeper than the call
  1622. stack, ValueError is raised. The default for depth is zero, returning
  1623. the frame at the top of the call stack.
  1624. This function should be used for internal and specialized purposes
  1625. only.
  1626. [clinic start generated code]*/
  1627. static PyObject *
  1628. sys__getframe_impl(PyObject *module, int depth)
  1629. /*[clinic end generated code: output=d438776c04d59804 input=c1be8a6464b11ee5]*/
  1630. {
  1631. PyThreadState *tstate = _PyThreadState_GET();
  1632. _PyInterpreterFrame *frame = tstate->cframe->current_frame;
  1633. if (frame != NULL) {
  1634. while (depth > 0) {
  1635. frame = _PyFrame_GetFirstComplete(frame->previous);
  1636. if (frame == NULL) {
  1637. break;
  1638. }
  1639. --depth;
  1640. }
  1641. }
  1642. if (frame == NULL) {
  1643. _PyErr_SetString(tstate, PyExc_ValueError,
  1644. "call stack is not deep enough");
  1645. return NULL;
  1646. }
  1647. PyObject *pyFrame = Py_XNewRef((PyObject *)_PyFrame_GetFrameObject(frame));
  1648. if (pyFrame && _PySys_Audit(tstate, "sys._getframe", "(O)", pyFrame) < 0) {
  1649. Py_DECREF(pyFrame);
  1650. return NULL;
  1651. }
  1652. return pyFrame;
  1653. }
  1654. /*[clinic input]
  1655. sys._current_frames
  1656. Return a dict mapping each thread's thread id to its current stack frame.
  1657. This function should be used for specialized purposes only.
  1658. [clinic start generated code]*/
  1659. static PyObject *
  1660. sys__current_frames_impl(PyObject *module)
  1661. /*[clinic end generated code: output=d2a41ac0a0a3809a input=2a9049c5f5033691]*/
  1662. {
  1663. return _PyThread_CurrentFrames();
  1664. }
  1665. /*[clinic input]
  1666. sys._current_exceptions
  1667. Return a dict mapping each thread's identifier to its current raised exception.
  1668. This function should be used for specialized purposes only.
  1669. [clinic start generated code]*/
  1670. static PyObject *
  1671. sys__current_exceptions_impl(PyObject *module)
  1672. /*[clinic end generated code: output=2ccfd838c746f0ba input=0e91818fbf2edc1f]*/
  1673. {
  1674. return _PyThread_CurrentExceptions();
  1675. }
  1676. /*[clinic input]
  1677. sys.call_tracing
  1678. func: object
  1679. args as funcargs: object(subclass_of='&PyTuple_Type')
  1680. /
  1681. Call func(*args), while tracing is enabled.
  1682. The tracing state is saved, and restored afterwards. This is intended
  1683. to be called from a debugger from a checkpoint, to recursively debug
  1684. some other code.
  1685. [clinic start generated code]*/
  1686. static PyObject *
  1687. sys_call_tracing_impl(PyObject *module, PyObject *func, PyObject *funcargs)
  1688. /*[clinic end generated code: output=7e4999853cd4e5a6 input=5102e8b11049f92f]*/
  1689. {
  1690. return _PyEval_CallTracing(func, funcargs);
  1691. }
  1692. #ifdef __cplusplus
  1693. extern "C" {
  1694. #endif
  1695. /*[clinic input]
  1696. sys._debugmallocstats
  1697. Print summary info to stderr about the state of pymalloc's structures.
  1698. In Py_DEBUG mode, also perform some expensive internal consistency
  1699. checks.
  1700. [clinic start generated code]*/
  1701. static PyObject *
  1702. sys__debugmallocstats_impl(PyObject *module)
  1703. /*[clinic end generated code: output=ec3565f8c7cee46a input=33c0c9c416f98424]*/
  1704. {
  1705. #ifdef WITH_PYMALLOC
  1706. if (_PyObject_DebugMallocStats(stderr)) {
  1707. fputc('\n', stderr);
  1708. }
  1709. #endif
  1710. _PyObject_DebugTypeStats(stderr);
  1711. Py_RETURN_NONE;
  1712. }
  1713. #ifdef Py_TRACE_REFS
  1714. /* Defined in objects.c because it uses static globals in that file */
  1715. extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
  1716. #endif
  1717. #ifdef __cplusplus
  1718. }
  1719. #endif
  1720. /*[clinic input]
  1721. sys._clear_type_cache
  1722. Clear the internal type lookup cache.
  1723. [clinic start generated code]*/
  1724. static PyObject *
  1725. sys__clear_type_cache_impl(PyObject *module)
  1726. /*[clinic end generated code: output=20e48ca54a6f6971 input=127f3e04a8d9b555]*/
  1727. {
  1728. PyType_ClearCache();
  1729. Py_RETURN_NONE;
  1730. }
  1731. /* Note that, for now, we do not have a per-interpreter equivalent
  1732. for sys.is_finalizing(). */
  1733. /*[clinic input]
  1734. sys.is_finalizing
  1735. Return True if Python is exiting.
  1736. [clinic start generated code]*/
  1737. static PyObject *
  1738. sys_is_finalizing_impl(PyObject *module)
  1739. /*[clinic end generated code: output=735b5ff7962ab281 input=f0df747a039948a5]*/
  1740. {
  1741. return PyBool_FromLong(_Py_IsFinalizing());
  1742. }
  1743. #ifdef Py_STATS
  1744. /*[clinic input]
  1745. sys._stats_on
  1746. Turns on stats gathering (stats gathering is on by default).
  1747. [clinic start generated code]*/
  1748. static PyObject *
  1749. sys__stats_on_impl(PyObject *module)
  1750. /*[clinic end generated code: output=aca53eafcbb4d9fe input=8ddc6df94e484f3a]*/
  1751. {
  1752. _py_stats = &_py_stats_struct;
  1753. Py_RETURN_NONE;
  1754. }
  1755. /*[clinic input]
  1756. sys._stats_off
  1757. Turns off stats gathering (stats gathering is on by default).
  1758. [clinic start generated code]*/
  1759. static PyObject *
  1760. sys__stats_off_impl(PyObject *module)
  1761. /*[clinic end generated code: output=1534c1ee63812214 input=b3e50e71ecf29f66]*/
  1762. {
  1763. _py_stats = NULL;
  1764. Py_RETURN_NONE;
  1765. }
  1766. /*[clinic input]
  1767. sys._stats_clear
  1768. Clears the stats.
  1769. [clinic start generated code]*/
  1770. static PyObject *
  1771. sys__stats_clear_impl(PyObject *module)
  1772. /*[clinic end generated code: output=fb65a2525ee50604 input=3e03f2654f44da96]*/
  1773. {
  1774. _Py_StatsClear();
  1775. Py_RETURN_NONE;
  1776. }
  1777. /*[clinic input]
  1778. sys._stats_dump
  1779. Dump stats to file, and clears the stats.
  1780. [clinic start generated code]*/
  1781. static PyObject *
  1782. sys__stats_dump_impl(PyObject *module)
  1783. /*[clinic end generated code: output=79f796fb2b4ddf05 input=92346f16d64f6f95]*/
  1784. {
  1785. _Py_PrintSpecializationStats(1);
  1786. _Py_StatsClear();
  1787. Py_RETURN_NONE;
  1788. }
  1789. #endif
  1790. #ifdef ANDROID_API_LEVEL
  1791. /*[clinic input]
  1792. sys.getandroidapilevel
  1793. Return the build time API version of Android as an integer.
  1794. [clinic start generated code]*/
  1795. static PyObject *
  1796. sys_getandroidapilevel_impl(PyObject *module)
  1797. /*[clinic end generated code: output=214abf183a1c70c1 input=3e6d6c9fcdd24ac6]*/
  1798. {
  1799. return PyLong_FromLong(ANDROID_API_LEVEL);
  1800. }
  1801. #endif /* ANDROID_API_LEVEL */
  1802. /*[clinic input]
  1803. sys.activate_stack_trampoline
  1804. backend: str
  1805. /
  1806. Activate stack profiler trampoline *backend*.
  1807. [clinic start generated code]*/
  1808. static PyObject *
  1809. sys_activate_stack_trampoline_impl(PyObject *module, const char *backend)
  1810. /*[clinic end generated code: output=5783cdeb51874b43 input=a12df928758a82b4]*/
  1811. {
  1812. #ifdef PY_HAVE_PERF_TRAMPOLINE
  1813. if (strcmp(backend, "perf") == 0) {
  1814. _PyPerf_Callbacks cur_cb;
  1815. _PyPerfTrampoline_GetCallbacks(&cur_cb);
  1816. if (cur_cb.write_state != _Py_perfmap_callbacks.write_state) {
  1817. if (_PyPerfTrampoline_SetCallbacks(&_Py_perfmap_callbacks) < 0 ) {
  1818. PyErr_SetString(PyExc_ValueError, "can't activate perf trampoline");
  1819. return NULL;
  1820. }
  1821. }
  1822. }
  1823. else {
  1824. PyErr_Format(PyExc_ValueError, "invalid backend: %s", backend);
  1825. return NULL;
  1826. }
  1827. if (_PyPerfTrampoline_Init(1) < 0) {
  1828. return NULL;
  1829. }
  1830. Py_RETURN_NONE;
  1831. #else
  1832. PyErr_SetString(PyExc_ValueError, "perf trampoline not available");
  1833. return NULL;
  1834. #endif
  1835. }
  1836. /*[clinic input]
  1837. sys.deactivate_stack_trampoline
  1838. Deactivate the current stack profiler trampoline backend.
  1839. If no stack profiler is activated, this function has no effect.
  1840. [clinic start generated code]*/
  1841. static PyObject *
  1842. sys_deactivate_stack_trampoline_impl(PyObject *module)
  1843. /*[clinic end generated code: output=b50da25465df0ef1 input=9f629a6be9fe7fc8]*/
  1844. {
  1845. if (_PyPerfTrampoline_Init(0) < 0) {
  1846. return NULL;
  1847. }
  1848. Py_RETURN_NONE;
  1849. }
  1850. /*[clinic input]
  1851. sys.is_stack_trampoline_active
  1852. Return *True* if a stack profiler trampoline is active.
  1853. [clinic start generated code]*/
  1854. static PyObject *
  1855. sys_is_stack_trampoline_active_impl(PyObject *module)
  1856. /*[clinic end generated code: output=ab2746de0ad9d293 input=29616b7bf6a0b703]*/
  1857. {
  1858. #ifdef PY_HAVE_PERF_TRAMPOLINE
  1859. if (_PyIsPerfTrampolineActive()) {
  1860. Py_RETURN_TRUE;
  1861. }
  1862. #endif
  1863. Py_RETURN_FALSE;
  1864. }
  1865. /*[clinic input]
  1866. sys._getframemodulename
  1867. depth: int = 0
  1868. Return the name of the module for a calling frame.
  1869. The default depth returns the module containing the call to this API.
  1870. A more typical use in a library will pass a depth of 1 to get the user's
  1871. module rather than the library module.
  1872. If no frame, module, or name can be found, returns None.
  1873. [clinic start generated code]*/
  1874. static PyObject *
  1875. sys__getframemodulename_impl(PyObject *module, int depth)
  1876. /*[clinic end generated code: output=1d70ef691f09d2db input=d4f1a8ed43b8fb46]*/
  1877. {
  1878. if (PySys_Audit("sys._getframemodulename", "i", depth) < 0) {
  1879. return NULL;
  1880. }
  1881. _PyInterpreterFrame *f = _PyThreadState_GET()->cframe->current_frame;
  1882. while (f && (_PyFrame_IsIncomplete(f) || depth-- > 0)) {
  1883. f = f->previous;
  1884. }
  1885. if (f == NULL || f->f_funcobj == NULL) {
  1886. Py_RETURN_NONE;
  1887. }
  1888. PyObject *r = PyFunction_GetModule(f->f_funcobj);
  1889. if (!r) {
  1890. PyErr_Clear();
  1891. r = Py_None;
  1892. }
  1893. return Py_NewRef(r);
  1894. }
  1895. #ifdef __cplusplus
  1896. extern "C" {
  1897. #endif
  1898. static PerfMapState perf_map_state;
  1899. PyAPI_FUNC(int) PyUnstable_PerfMapState_Init(void) {
  1900. #ifndef MS_WINDOWS
  1901. char filename[100];
  1902. pid_t pid = getpid();
  1903. // Use nofollow flag to prevent symlink attacks.
  1904. int flags = O_WRONLY | O_CREAT | O_APPEND | O_NOFOLLOW;
  1905. #ifdef O_CLOEXEC
  1906. flags |= O_CLOEXEC;
  1907. #endif
  1908. snprintf(filename, sizeof(filename) - 1, "/tmp/perf-%jd.map",
  1909. (intmax_t)pid);
  1910. int fd = open(filename, flags, 0600);
  1911. if (fd == -1) {
  1912. return -1;
  1913. }
  1914. else{
  1915. perf_map_state.perf_map = fdopen(fd, "a");
  1916. if (perf_map_state.perf_map == NULL) {
  1917. close(fd);
  1918. return -1;
  1919. }
  1920. }
  1921. perf_map_state.map_lock = PyThread_allocate_lock();
  1922. if (perf_map_state.map_lock == NULL) {
  1923. fclose(perf_map_state.perf_map);
  1924. return -2;
  1925. }
  1926. #endif
  1927. return 0;
  1928. }
  1929. PyAPI_FUNC(int) PyUnstable_WritePerfMapEntry(
  1930. const void *code_addr,
  1931. unsigned int code_size,
  1932. const char *entry_name
  1933. ) {
  1934. #ifndef MS_WINDOWS
  1935. if (perf_map_state.perf_map == NULL) {
  1936. int ret = PyUnstable_PerfMapState_Init();
  1937. if(ret != 0){
  1938. return ret;
  1939. }
  1940. }
  1941. PyThread_acquire_lock(perf_map_state.map_lock, 1);
  1942. fprintf(perf_map_state.perf_map, "%" PRIxPTR " %x %s\n", (uintptr_t) code_addr, code_size, entry_name);
  1943. fflush(perf_map_state.perf_map);
  1944. PyThread_release_lock(perf_map_state.map_lock);
  1945. #endif
  1946. return 0;
  1947. }
  1948. PyAPI_FUNC(void) PyUnstable_PerfMapState_Fini(void) {
  1949. #ifndef MS_WINDOWS
  1950. if (perf_map_state.perf_map != NULL) {
  1951. // close the file
  1952. PyThread_acquire_lock(perf_map_state.map_lock, 1);
  1953. fclose(perf_map_state.perf_map);
  1954. PyThread_release_lock(perf_map_state.map_lock);
  1955. // clean up the lock and state
  1956. PyThread_free_lock(perf_map_state.map_lock);
  1957. perf_map_state.perf_map = NULL;
  1958. }
  1959. #endif
  1960. }
  1961. #ifdef __cplusplus
  1962. }
  1963. #endif
  1964. static PyMethodDef sys_methods[] = {
  1965. /* Might as well keep this in alphabetic order */
  1966. SYS_ADDAUDITHOOK_METHODDEF
  1967. {"audit", _PyCFunction_CAST(sys_audit), METH_FASTCALL, audit_doc },
  1968. {"breakpointhook", _PyCFunction_CAST(sys_breakpointhook),
  1969. METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
  1970. SYS__CLEAR_TYPE_CACHE_METHODDEF
  1971. SYS__CURRENT_FRAMES_METHODDEF
  1972. SYS__CURRENT_EXCEPTIONS_METHODDEF
  1973. SYS_DISPLAYHOOK_METHODDEF
  1974. SYS_EXCEPTION_METHODDEF
  1975. SYS_EXC_INFO_METHODDEF
  1976. SYS_EXCEPTHOOK_METHODDEF
  1977. SYS_EXIT_METHODDEF
  1978. SYS_GETDEFAULTENCODING_METHODDEF
  1979. SYS_GETDLOPENFLAGS_METHODDEF
  1980. SYS_GETALLOCATEDBLOCKS_METHODDEF
  1981. SYS_GETUNICODEINTERNEDSIZE_METHODDEF
  1982. SYS_GETFILESYSTEMENCODING_METHODDEF
  1983. SYS_GETFILESYSTEMENCODEERRORS_METHODDEF
  1984. #ifdef Py_TRACE_REFS
  1985. {"getobjects", _Py_GetObjects, METH_VARARGS},
  1986. #endif
  1987. SYS_GETTOTALREFCOUNT_METHODDEF
  1988. SYS_GETREFCOUNT_METHODDEF
  1989. SYS_GETRECURSIONLIMIT_METHODDEF
  1990. {"getsizeof", _PyCFunction_CAST(sys_getsizeof),
  1991. METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
  1992. SYS__GETFRAME_METHODDEF
  1993. SYS__GETFRAMEMODULENAME_METHODDEF
  1994. SYS_GETWINDOWSVERSION_METHODDEF
  1995. SYS__ENABLELEGACYWINDOWSFSENCODING_METHODDEF
  1996. SYS_INTERN_METHODDEF
  1997. SYS_IS_FINALIZING_METHODDEF
  1998. SYS_MDEBUG_METHODDEF
  1999. SYS_SETSWITCHINTERVAL_METHODDEF
  2000. SYS_GETSWITCHINTERVAL_METHODDEF
  2001. SYS_SETDLOPENFLAGS_METHODDEF
  2002. {"setprofile", sys_setprofile, METH_O, setprofile_doc},
  2003. SYS__SETPROFILEALLTHREADS_METHODDEF
  2004. SYS_GETPROFILE_METHODDEF
  2005. SYS_SETRECURSIONLIMIT_METHODDEF
  2006. {"settrace", sys_settrace, METH_O, settrace_doc},
  2007. SYS__SETTRACEALLTHREADS_METHODDEF
  2008. SYS_GETTRACE_METHODDEF
  2009. SYS_CALL_TRACING_METHODDEF
  2010. SYS__DEBUGMALLOCSTATS_METHODDEF
  2011. SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
  2012. SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
  2013. {"set_asyncgen_hooks", _PyCFunction_CAST(sys_set_asyncgen_hooks),
  2014. METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
  2015. SYS_GET_ASYNCGEN_HOOKS_METHODDEF
  2016. SYS_GETANDROIDAPILEVEL_METHODDEF
  2017. SYS_ACTIVATE_STACK_TRAMPOLINE_METHODDEF
  2018. SYS_DEACTIVATE_STACK_TRAMPOLINE_METHODDEF
  2019. SYS_IS_STACK_TRAMPOLINE_ACTIVE_METHODDEF
  2020. SYS_UNRAISABLEHOOK_METHODDEF
  2021. SYS_GET_INT_MAX_STR_DIGITS_METHODDEF
  2022. SYS_SET_INT_MAX_STR_DIGITS_METHODDEF
  2023. #ifdef Py_STATS
  2024. SYS__STATS_ON_METHODDEF
  2025. SYS__STATS_OFF_METHODDEF
  2026. SYS__STATS_CLEAR_METHODDEF
  2027. SYS__STATS_DUMP_METHODDEF
  2028. #endif
  2029. {NULL, NULL} // sentinel
  2030. };
  2031. static PyObject *
  2032. list_builtin_module_names(void)
  2033. {
  2034. PyObject *list = _PyImport_GetBuiltinModuleNames();
  2035. if (list == NULL) {
  2036. return NULL;
  2037. }
  2038. if (PyList_Sort(list) != 0) {
  2039. goto error;
  2040. }
  2041. PyObject *tuple = PyList_AsTuple(list);
  2042. Py_DECREF(list);
  2043. return tuple;
  2044. error:
  2045. Py_DECREF(list);
  2046. return NULL;
  2047. }
  2048. static PyObject *
  2049. list_stdlib_module_names(void)
  2050. {
  2051. Py_ssize_t len = Py_ARRAY_LENGTH(_Py_stdlib_module_names);
  2052. PyObject *names = PyTuple_New(len);
  2053. if (names == NULL) {
  2054. return NULL;
  2055. }
  2056. for (Py_ssize_t i = 0; i < len; i++) {
  2057. PyObject *name = PyUnicode_FromString(_Py_stdlib_module_names[i]);
  2058. if (name == NULL) {
  2059. Py_DECREF(names);
  2060. return NULL;
  2061. }
  2062. PyTuple_SET_ITEM(names, i, name);
  2063. }
  2064. PyObject *set = PyObject_CallFunction((PyObject *)&PyFrozenSet_Type,
  2065. "(O)", names);
  2066. Py_DECREF(names);
  2067. return set;
  2068. }
  2069. /* Pre-initialization support for sys.warnoptions and sys._xoptions
  2070. *
  2071. * Modern internal code paths:
  2072. * These APIs get called after _Py_InitializeCore and get to use the
  2073. * regular CPython list, dict, and unicode APIs.
  2074. *
  2075. * Legacy embedding code paths:
  2076. * The multi-phase initialization API isn't public yet, so embedding
  2077. * apps still need to be able configure sys.warnoptions and sys._xoptions
  2078. * before they call Py_Initialize. To support this, we stash copies of
  2079. * the supplied wchar * sequences in linked lists, and then migrate the
  2080. * contents of those lists to the sys module in _PyInitializeCore.
  2081. *
  2082. */
  2083. struct _preinit_entry {
  2084. wchar_t *value;
  2085. struct _preinit_entry *next;
  2086. };
  2087. typedef struct _preinit_entry *_Py_PreInitEntry;
  2088. static _Py_PreInitEntry _preinit_warnoptions = NULL;
  2089. static _Py_PreInitEntry _preinit_xoptions = NULL;
  2090. static _Py_PreInitEntry
  2091. _alloc_preinit_entry(const wchar_t *value)
  2092. {
  2093. /* To get this to work, we have to initialize the runtime implicitly */
  2094. _PyRuntime_Initialize();
  2095. /* Force default allocator, so we can ensure that it also gets used to
  2096. * destroy the linked list in _clear_preinit_entries.
  2097. */
  2098. PyMemAllocatorEx old_alloc;
  2099. _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  2100. _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
  2101. if (node != NULL) {
  2102. node->value = _PyMem_RawWcsdup(value);
  2103. if (node->value == NULL) {
  2104. PyMem_RawFree(node);
  2105. node = NULL;
  2106. };
  2107. };
  2108. PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  2109. return node;
  2110. }
  2111. static int
  2112. _append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
  2113. {
  2114. _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
  2115. if (new_entry == NULL) {
  2116. return -1;
  2117. }
  2118. /* We maintain the linked list in this order so it's easy to play back
  2119. * the add commands in the same order later on in _Py_InitializeCore
  2120. */
  2121. _Py_PreInitEntry last_entry = *optionlist;
  2122. if (last_entry == NULL) {
  2123. *optionlist = new_entry;
  2124. } else {
  2125. while (last_entry->next != NULL) {
  2126. last_entry = last_entry->next;
  2127. }
  2128. last_entry->next = new_entry;
  2129. }
  2130. return 0;
  2131. }
  2132. static void
  2133. _clear_preinit_entries(_Py_PreInitEntry *optionlist)
  2134. {
  2135. _Py_PreInitEntry current = *optionlist;
  2136. *optionlist = NULL;
  2137. /* Deallocate the nodes and their contents using the default allocator */
  2138. PyMemAllocatorEx old_alloc;
  2139. _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  2140. while (current != NULL) {
  2141. _Py_PreInitEntry next = current->next;
  2142. PyMem_RawFree(current->value);
  2143. PyMem_RawFree(current);
  2144. current = next;
  2145. }
  2146. PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  2147. }
  2148. PyStatus
  2149. _PySys_ReadPreinitWarnOptions(PyWideStringList *options)
  2150. {
  2151. PyStatus status;
  2152. _Py_PreInitEntry entry;
  2153. for (entry = _preinit_warnoptions; entry != NULL; entry = entry->next) {
  2154. status = PyWideStringList_Append(options, entry->value);
  2155. if (_PyStatus_EXCEPTION(status)) {
  2156. return status;
  2157. }
  2158. }
  2159. _clear_preinit_entries(&_preinit_warnoptions);
  2160. return _PyStatus_OK();
  2161. }
  2162. PyStatus
  2163. _PySys_ReadPreinitXOptions(PyConfig *config)
  2164. {
  2165. PyStatus status;
  2166. _Py_PreInitEntry entry;
  2167. for (entry = _preinit_xoptions; entry != NULL; entry = entry->next) {
  2168. status = PyWideStringList_Append(&config->xoptions, entry->value);
  2169. if (_PyStatus_EXCEPTION(status)) {
  2170. return status;
  2171. }
  2172. }
  2173. _clear_preinit_entries(&_preinit_xoptions);
  2174. return _PyStatus_OK();
  2175. }
  2176. static PyObject *
  2177. get_warnoptions(PyThreadState *tstate)
  2178. {
  2179. PyObject *warnoptions = _PySys_GetAttr(tstate, &_Py_ID(warnoptions));
  2180. if (warnoptions == NULL || !PyList_Check(warnoptions)) {
  2181. /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
  2182. * interpreter config. When that happens, we need to properly set
  2183. * the `warnoptions` reference in the main interpreter config as well.
  2184. *
  2185. * For Python 3.7, we shouldn't be able to get here due to the
  2186. * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
  2187. * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
  2188. * call optional for embedding applications, thus making this
  2189. * reachable again.
  2190. */
  2191. warnoptions = PyList_New(0);
  2192. if (warnoptions == NULL) {
  2193. return NULL;
  2194. }
  2195. if (sys_set_object(tstate->interp, &_Py_ID(warnoptions), warnoptions)) {
  2196. Py_DECREF(warnoptions);
  2197. return NULL;
  2198. }
  2199. Py_DECREF(warnoptions);
  2200. }
  2201. return warnoptions;
  2202. }
  2203. void
  2204. PySys_ResetWarnOptions(void)
  2205. {
  2206. PyThreadState *tstate = _PyThreadState_GET();
  2207. if (tstate == NULL) {
  2208. _clear_preinit_entries(&_preinit_warnoptions);
  2209. return;
  2210. }
  2211. PyObject *warnoptions = _PySys_GetAttr(tstate, &_Py_ID(warnoptions));
  2212. if (warnoptions == NULL || !PyList_Check(warnoptions))
  2213. return;
  2214. PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
  2215. }
  2216. static int
  2217. _PySys_AddWarnOptionWithError(PyThreadState *tstate, PyObject *option)
  2218. {
  2219. PyObject *warnoptions = get_warnoptions(tstate);
  2220. if (warnoptions == NULL) {
  2221. return -1;
  2222. }
  2223. if (PyList_Append(warnoptions, option)) {
  2224. return -1;
  2225. }
  2226. return 0;
  2227. }
  2228. void
  2229. PySys_AddWarnOptionUnicode(PyObject *option)
  2230. {
  2231. PyThreadState *tstate = _PyThreadState_GET();
  2232. if (_PySys_AddWarnOptionWithError(tstate, option) < 0) {
  2233. /* No return value, therefore clear error state if possible */
  2234. if (tstate) {
  2235. _PyErr_Clear(tstate);
  2236. }
  2237. }
  2238. }
  2239. void
  2240. PySys_AddWarnOption(const wchar_t *s)
  2241. {
  2242. PyThreadState *tstate = _PyThreadState_GET();
  2243. if (tstate == NULL) {
  2244. _append_preinit_entry(&_preinit_warnoptions, s);
  2245. return;
  2246. }
  2247. PyObject *unicode;
  2248. unicode = PyUnicode_FromWideChar(s, -1);
  2249. if (unicode == NULL)
  2250. return;
  2251. _Py_COMP_DIAG_PUSH
  2252. _Py_COMP_DIAG_IGNORE_DEPR_DECLS
  2253. PySys_AddWarnOptionUnicode(unicode);
  2254. _Py_COMP_DIAG_POP
  2255. Py_DECREF(unicode);
  2256. }
  2257. int
  2258. PySys_HasWarnOptions(void)
  2259. {
  2260. PyThreadState *tstate = _PyThreadState_GET();
  2261. PyObject *warnoptions = _PySys_GetAttr(tstate, &_Py_ID(warnoptions));
  2262. return (warnoptions != NULL && PyList_Check(warnoptions)
  2263. && PyList_GET_SIZE(warnoptions) > 0);
  2264. }
  2265. static PyObject *
  2266. get_xoptions(PyThreadState *tstate)
  2267. {
  2268. PyObject *xoptions = _PySys_GetAttr(tstate, &_Py_ID(_xoptions));
  2269. if (xoptions == NULL || !PyDict_Check(xoptions)) {
  2270. /* PEP432 TODO: we can reach this if xoptions is NULL in the main
  2271. * interpreter config. When that happens, we need to properly set
  2272. * the `xoptions` reference in the main interpreter config as well.
  2273. *
  2274. * For Python 3.7, we shouldn't be able to get here due to the
  2275. * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
  2276. * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
  2277. * call optional for embedding applications, thus making this
  2278. * reachable again.
  2279. */
  2280. xoptions = PyDict_New();
  2281. if (xoptions == NULL) {
  2282. return NULL;
  2283. }
  2284. if (sys_set_object(tstate->interp, &_Py_ID(_xoptions), xoptions)) {
  2285. Py_DECREF(xoptions);
  2286. return NULL;
  2287. }
  2288. Py_DECREF(xoptions);
  2289. }
  2290. return xoptions;
  2291. }
  2292. static int
  2293. _PySys_AddXOptionWithError(const wchar_t *s)
  2294. {
  2295. PyObject *name = NULL, *value = NULL;
  2296. PyThreadState *tstate = _PyThreadState_GET();
  2297. PyObject *opts = get_xoptions(tstate);
  2298. if (opts == NULL) {
  2299. goto error;
  2300. }
  2301. const wchar_t *name_end = wcschr(s, L'=');
  2302. if (!name_end) {
  2303. name = PyUnicode_FromWideChar(s, -1);
  2304. if (name == NULL) {
  2305. goto error;
  2306. }
  2307. value = Py_NewRef(Py_True);
  2308. }
  2309. else {
  2310. name = PyUnicode_FromWideChar(s, name_end - s);
  2311. if (name == NULL) {
  2312. goto error;
  2313. }
  2314. value = PyUnicode_FromWideChar(name_end + 1, -1);
  2315. if (value == NULL) {
  2316. goto error;
  2317. }
  2318. }
  2319. if (PyDict_SetItem(opts, name, value) < 0) {
  2320. goto error;
  2321. }
  2322. Py_DECREF(name);
  2323. Py_DECREF(value);
  2324. return 0;
  2325. error:
  2326. Py_XDECREF(name);
  2327. Py_XDECREF(value);
  2328. return -1;
  2329. }
  2330. void
  2331. PySys_AddXOption(const wchar_t *s)
  2332. {
  2333. PyThreadState *tstate = _PyThreadState_GET();
  2334. if (tstate == NULL) {
  2335. _append_preinit_entry(&_preinit_xoptions, s);
  2336. return;
  2337. }
  2338. if (_PySys_AddXOptionWithError(s) < 0) {
  2339. /* No return value, therefore clear error state if possible */
  2340. _PyErr_Clear(tstate);
  2341. }
  2342. }
  2343. PyObject *
  2344. PySys_GetXOptions(void)
  2345. {
  2346. PyThreadState *tstate = _PyThreadState_GET();
  2347. return get_xoptions(tstate);
  2348. }
  2349. /* XXX This doc string is too long to be a single string literal in VC++ 5.0.
  2350. Two literals concatenated works just fine. If you have a K&R compiler
  2351. or other abomination that however *does* understand longer strings,
  2352. get rid of the !!! comment in the middle and the quotes that surround it. */
  2353. PyDoc_VAR(sys_doc) =
  2354. PyDoc_STR(
  2355. "This module provides access to some objects used or maintained by the\n\
  2356. interpreter and to functions that interact strongly with the interpreter.\n\
  2357. \n\
  2358. Dynamic objects:\n\
  2359. \n\
  2360. argv -- command line arguments; argv[0] is the script pathname if known\n\
  2361. path -- module search path; path[0] is the script directory, else ''\n\
  2362. modules -- dictionary of loaded modules\n\
  2363. \n\
  2364. displayhook -- called to show results in an interactive session\n\
  2365. excepthook -- called to handle any uncaught exception other than SystemExit\n\
  2366. To customize printing in an interactive session or to install a custom\n\
  2367. top-level exception handler, assign other functions to replace these.\n\
  2368. \n\
  2369. stdin -- standard input file object; used by input()\n\
  2370. stdout -- standard output file object; used by print()\n\
  2371. stderr -- standard error object; used for error messages\n\
  2372. By assigning other file objects (or objects that behave like files)\n\
  2373. to these, it is possible to redirect all of the interpreter's I/O.\n\
  2374. \n\
  2375. last_exc - the last uncaught exception\n\
  2376. Only available in an interactive session after a\n\
  2377. traceback has been printed.\n\
  2378. last_type -- type of last uncaught exception\n\
  2379. last_value -- value of last uncaught exception\n\
  2380. last_traceback -- traceback of last uncaught exception\n\
  2381. These three are the (deprecated) legacy representation of last_exc.\n\
  2382. "
  2383. )
  2384. /* concatenating string here */
  2385. PyDoc_STR(
  2386. "\n\
  2387. Static objects:\n\
  2388. \n\
  2389. builtin_module_names -- tuple of module names built into this interpreter\n\
  2390. copyright -- copyright notice pertaining to this interpreter\n\
  2391. exec_prefix -- prefix used to find the machine-specific Python library\n\
  2392. executable -- absolute path of the executable binary of the Python interpreter\n\
  2393. float_info -- a named tuple with information about the float implementation.\n\
  2394. float_repr_style -- string indicating the style of repr() output for floats\n\
  2395. hash_info -- a named tuple with information about the hash algorithm.\n\
  2396. hexversion -- version information encoded as a single integer\n\
  2397. implementation -- Python implementation information.\n\
  2398. int_info -- a named tuple with information about the int implementation.\n\
  2399. maxsize -- the largest supported length of containers.\n\
  2400. maxunicode -- the value of the largest Unicode code point\n\
  2401. platform -- platform identifier\n\
  2402. prefix -- prefix used to find the Python library\n\
  2403. thread_info -- a named tuple with information about the thread implementation.\n\
  2404. version -- the version of this interpreter as a string\n\
  2405. version_info -- version information as a named tuple\n\
  2406. "
  2407. )
  2408. #ifdef MS_COREDLL
  2409. /* concatenating string here */
  2410. PyDoc_STR(
  2411. "dllhandle -- [Windows only] integer handle of the Python DLL\n\
  2412. winver -- [Windows only] version number of the Python DLL\n\
  2413. "
  2414. )
  2415. #endif /* MS_COREDLL */
  2416. #ifdef MS_WINDOWS
  2417. /* concatenating string here */
  2418. PyDoc_STR(
  2419. "_enablelegacywindowsfsencoding -- [Windows only]\n\
  2420. "
  2421. )
  2422. #endif
  2423. PyDoc_STR(
  2424. "__stdin__ -- the original stdin; don't touch!\n\
  2425. __stdout__ -- the original stdout; don't touch!\n\
  2426. __stderr__ -- the original stderr; don't touch!\n\
  2427. __displayhook__ -- the original displayhook; don't touch!\n\
  2428. __excepthook__ -- the original excepthook; don't touch!\n\
  2429. \n\
  2430. Functions:\n\
  2431. \n\
  2432. displayhook() -- print an object to the screen, and save it in builtins._\n\
  2433. excepthook() -- print an exception and its traceback to sys.stderr\n\
  2434. exception() -- return the current thread's active exception\n\
  2435. exc_info() -- return information about the current thread's active exception\n\
  2436. exit() -- exit the interpreter by raising SystemExit\n\
  2437. getdlopenflags() -- returns flags to be used for dlopen() calls\n\
  2438. getprofile() -- get the global profiling function\n\
  2439. getrefcount() -- return the reference count for an object (plus one :-)\n\
  2440. getrecursionlimit() -- return the max recursion depth for the interpreter\n\
  2441. getsizeof() -- return the size of an object in bytes\n\
  2442. gettrace() -- get the global debug tracing function\n\
  2443. setdlopenflags() -- set the flags to be used for dlopen() calls\n\
  2444. setprofile() -- set the global profiling function\n\
  2445. setrecursionlimit() -- set the max recursion depth for the interpreter\n\
  2446. settrace() -- set the global debug tracing function\n\
  2447. "
  2448. )
  2449. /* end of sys_doc */ ;
  2450. PyDoc_STRVAR(flags__doc__,
  2451. "sys.flags\n\
  2452. \n\
  2453. Flags provided through command line arguments or environment vars.");
  2454. static PyTypeObject FlagsType;
  2455. static PyStructSequence_Field flags_fields[] = {
  2456. {"debug", "-d"},
  2457. {"inspect", "-i"},
  2458. {"interactive", "-i"},
  2459. {"optimize", "-O or -OO"},
  2460. {"dont_write_bytecode", "-B"},
  2461. {"no_user_site", "-s"},
  2462. {"no_site", "-S"},
  2463. {"ignore_environment", "-E"},
  2464. {"verbose", "-v"},
  2465. {"bytes_warning", "-b"},
  2466. {"quiet", "-q"},
  2467. {"hash_randomization", "-R"},
  2468. {"isolated", "-I"},
  2469. {"dev_mode", "-X dev"},
  2470. {"utf8_mode", "-X utf8"},
  2471. {"warn_default_encoding", "-X warn_default_encoding"},
  2472. {"safe_path", "-P"},
  2473. {"int_max_str_digits", "-X int_max_str_digits"},
  2474. {0}
  2475. };
  2476. static PyStructSequence_Desc flags_desc = {
  2477. "sys.flags", /* name */
  2478. flags__doc__, /* doc */
  2479. flags_fields, /* fields */
  2480. 18
  2481. };
  2482. static int
  2483. set_flags_from_config(PyInterpreterState *interp, PyObject *flags)
  2484. {
  2485. const PyPreConfig *preconfig = &interp->runtime->preconfig;
  2486. const PyConfig *config = _PyInterpreterState_GetConfig(interp);
  2487. // _PySys_UpdateConfig() modifies sys.flags in-place:
  2488. // Py_XDECREF() is needed in this case.
  2489. Py_ssize_t pos = 0;
  2490. #define SetFlagObj(expr) \
  2491. do { \
  2492. PyObject *value = (expr); \
  2493. if (value == NULL) { \
  2494. return -1; \
  2495. } \
  2496. Py_XDECREF(PyStructSequence_GET_ITEM(flags, pos)); \
  2497. PyStructSequence_SET_ITEM(flags, pos, value); \
  2498. pos++; \
  2499. } while (0)
  2500. #define SetFlag(expr) SetFlagObj(PyLong_FromLong(expr))
  2501. SetFlag(config->parser_debug);
  2502. SetFlag(config->inspect);
  2503. SetFlag(config->interactive);
  2504. SetFlag(config->optimization_level);
  2505. SetFlag(!config->write_bytecode);
  2506. SetFlag(!config->user_site_directory);
  2507. SetFlag(!config->site_import);
  2508. SetFlag(!config->use_environment);
  2509. SetFlag(config->verbose);
  2510. SetFlag(config->bytes_warning);
  2511. SetFlag(config->quiet);
  2512. SetFlag(config->use_hash_seed == 0 || config->hash_seed != 0);
  2513. SetFlag(config->isolated);
  2514. SetFlagObj(PyBool_FromLong(config->dev_mode));
  2515. SetFlag(preconfig->utf8_mode);
  2516. SetFlag(config->warn_default_encoding);
  2517. SetFlagObj(PyBool_FromLong(config->safe_path));
  2518. SetFlag(config->int_max_str_digits);
  2519. #undef SetFlagObj
  2520. #undef SetFlag
  2521. return 0;
  2522. }
  2523. static PyObject*
  2524. make_flags(PyInterpreterState *interp)
  2525. {
  2526. PyObject *flags = PyStructSequence_New(&FlagsType);
  2527. if (flags == NULL) {
  2528. return NULL;
  2529. }
  2530. if (set_flags_from_config(interp, flags) < 0) {
  2531. Py_DECREF(flags);
  2532. return NULL;
  2533. }
  2534. return flags;
  2535. }
  2536. PyDoc_STRVAR(version_info__doc__,
  2537. "sys.version_info\n\
  2538. \n\
  2539. Version information as a named tuple.");
  2540. static PyTypeObject VersionInfoType;
  2541. static PyStructSequence_Field version_info_fields[] = {
  2542. {"major", "Major release number"},
  2543. {"minor", "Minor release number"},
  2544. {"micro", "Patch release number"},
  2545. {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
  2546. {"serial", "Serial release number"},
  2547. {0}
  2548. };
  2549. static PyStructSequence_Desc version_info_desc = {
  2550. "sys.version_info", /* name */
  2551. version_info__doc__, /* doc */
  2552. version_info_fields, /* fields */
  2553. 5
  2554. };
  2555. static PyObject *
  2556. make_version_info(PyThreadState *tstate)
  2557. {
  2558. PyObject *version_info;
  2559. char *s;
  2560. int pos = 0;
  2561. version_info = PyStructSequence_New(&VersionInfoType);
  2562. if (version_info == NULL) {
  2563. return NULL;
  2564. }
  2565. /*
  2566. * These release level checks are mutually exclusive and cover
  2567. * the field, so don't get too fancy with the pre-processor!
  2568. */
  2569. #if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
  2570. s = "alpha";
  2571. #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
  2572. s = "beta";
  2573. #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
  2574. s = "candidate";
  2575. #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
  2576. s = "final";
  2577. #endif
  2578. #define SetIntItem(flag) \
  2579. PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
  2580. #define SetStrItem(flag) \
  2581. PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
  2582. SetIntItem(PY_MAJOR_VERSION);
  2583. SetIntItem(PY_MINOR_VERSION);
  2584. SetIntItem(PY_MICRO_VERSION);
  2585. SetStrItem(s);
  2586. SetIntItem(PY_RELEASE_SERIAL);
  2587. #undef SetIntItem
  2588. #undef SetStrItem
  2589. if (_PyErr_Occurred(tstate)) {
  2590. Py_CLEAR(version_info);
  2591. return NULL;
  2592. }
  2593. return version_info;
  2594. }
  2595. /* sys.implementation values */
  2596. #define NAME "cpython"
  2597. const char *_PySys_ImplName = NAME;
  2598. #define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
  2599. #define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
  2600. #define TAG NAME "-" MAJOR MINOR
  2601. const char *_PySys_ImplCacheTag = TAG;
  2602. #undef NAME
  2603. #undef MAJOR
  2604. #undef MINOR
  2605. #undef TAG
  2606. static PyObject *
  2607. make_impl_info(PyObject *version_info)
  2608. {
  2609. int res;
  2610. PyObject *impl_info, *value, *ns;
  2611. impl_info = PyDict_New();
  2612. if (impl_info == NULL)
  2613. return NULL;
  2614. /* populate the dict */
  2615. value = PyUnicode_FromString(_PySys_ImplName);
  2616. if (value == NULL)
  2617. goto error;
  2618. res = PyDict_SetItemString(impl_info, "name", value);
  2619. Py_DECREF(value);
  2620. if (res < 0)
  2621. goto error;
  2622. value = PyUnicode_FromString(_PySys_ImplCacheTag);
  2623. if (value == NULL)
  2624. goto error;
  2625. res = PyDict_SetItemString(impl_info, "cache_tag", value);
  2626. Py_DECREF(value);
  2627. if (res < 0)
  2628. goto error;
  2629. res = PyDict_SetItemString(impl_info, "version", version_info);
  2630. if (res < 0)
  2631. goto error;
  2632. value = PyLong_FromLong(PY_VERSION_HEX);
  2633. if (value == NULL)
  2634. goto error;
  2635. res = PyDict_SetItemString(impl_info, "hexversion", value);
  2636. Py_DECREF(value);
  2637. if (res < 0)
  2638. goto error;
  2639. #ifdef MULTIARCH
  2640. value = PyUnicode_FromString(MULTIARCH);
  2641. if (value == NULL)
  2642. goto error;
  2643. res = PyDict_SetItemString(impl_info, "_multiarch", value);
  2644. Py_DECREF(value);
  2645. if (res < 0)
  2646. goto error;
  2647. #endif
  2648. /* dict ready */
  2649. ns = _PyNamespace_New(impl_info);
  2650. Py_DECREF(impl_info);
  2651. return ns;
  2652. error:
  2653. Py_CLEAR(impl_info);
  2654. return NULL;
  2655. }
  2656. #ifdef __EMSCRIPTEN__
  2657. PyDoc_STRVAR(emscripten_info__doc__,
  2658. "sys._emscripten_info\n\
  2659. \n\
  2660. WebAssembly Emscripten platform information.");
  2661. static PyTypeObject *EmscriptenInfoType;
  2662. static PyStructSequence_Field emscripten_info_fields[] = {
  2663. {"emscripten_version", "Emscripten version (major, minor, micro)"},
  2664. {"runtime", "Runtime (Node.JS version, browser user agent)"},
  2665. {"pthreads", "pthread support"},
  2666. {"shared_memory", "shared memory support"},
  2667. {0}
  2668. };
  2669. static PyStructSequence_Desc emscripten_info_desc = {
  2670. "sys._emscripten_info", /* name */
  2671. emscripten_info__doc__ , /* doc */
  2672. emscripten_info_fields, /* fields */
  2673. 4
  2674. };
  2675. EM_JS(char *, _Py_emscripten_runtime, (void), {
  2676. var info;
  2677. if (typeof navigator == 'object') {
  2678. info = navigator.userAgent;
  2679. } else if (typeof process == 'object') {
  2680. info = "Node.js ".concat(process.version);
  2681. } else {
  2682. info = "UNKNOWN";
  2683. }
  2684. var len = lengthBytesUTF8(info) + 1;
  2685. var res = _malloc(len);
  2686. if (res) stringToUTF8(info, res, len);
  2687. #if __wasm64__
  2688. return BigInt(res);
  2689. #else
  2690. return res;
  2691. #endif
  2692. });
  2693. static PyObject *
  2694. make_emscripten_info(void)
  2695. {
  2696. PyObject *emscripten_info = NULL;
  2697. PyObject *version = NULL;
  2698. char *ua;
  2699. int pos = 0;
  2700. emscripten_info = PyStructSequence_New(EmscriptenInfoType);
  2701. if (emscripten_info == NULL) {
  2702. return NULL;
  2703. }
  2704. version = Py_BuildValue("(iii)",
  2705. __EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__);
  2706. if (version == NULL) {
  2707. goto error;
  2708. }
  2709. PyStructSequence_SET_ITEM(emscripten_info, pos++, version);
  2710. ua = _Py_emscripten_runtime();
  2711. if (ua != NULL) {
  2712. PyObject *oua = PyUnicode_DecodeUTF8(ua, strlen(ua), "strict");
  2713. free(ua);
  2714. if (oua == NULL) {
  2715. goto error;
  2716. }
  2717. PyStructSequence_SET_ITEM(emscripten_info, pos++, oua);
  2718. } else {
  2719. PyStructSequence_SET_ITEM(emscripten_info, pos++, Py_NewRef(Py_None));
  2720. }
  2721. #define SetBoolItem(flag) \
  2722. PyStructSequence_SET_ITEM(emscripten_info, pos++, PyBool_FromLong(flag))
  2723. #ifdef __EMSCRIPTEN_PTHREADS__
  2724. SetBoolItem(1);
  2725. #else
  2726. SetBoolItem(0);
  2727. #endif
  2728. #ifdef __EMSCRIPTEN_SHARED_MEMORY__
  2729. SetBoolItem(1);
  2730. #else
  2731. SetBoolItem(0);
  2732. #endif
  2733. #undef SetBoolItem
  2734. if (PyErr_Occurred()) {
  2735. goto error;
  2736. }
  2737. return emscripten_info;
  2738. error:
  2739. Py_CLEAR(emscripten_info);
  2740. return NULL;
  2741. }
  2742. #endif // __EMSCRIPTEN__
  2743. static struct PyModuleDef sysmodule = {
  2744. PyModuleDef_HEAD_INIT,
  2745. "sys",
  2746. sys_doc,
  2747. -1, /* multiple "initialization" just copies the module dict. */
  2748. sys_methods,
  2749. NULL,
  2750. NULL,
  2751. NULL,
  2752. NULL
  2753. };
  2754. /* Updating the sys namespace, returning NULL pointer on error */
  2755. #define SET_SYS(key, value) \
  2756. do { \
  2757. PyObject *v = (value); \
  2758. if (v == NULL) { \
  2759. goto err_occurred; \
  2760. } \
  2761. res = PyDict_SetItemString(sysdict, key, v); \
  2762. Py_DECREF(v); \
  2763. if (res < 0) { \
  2764. goto err_occurred; \
  2765. } \
  2766. } while (0)
  2767. #define SET_SYS_FROM_STRING(key, value) \
  2768. SET_SYS(key, PyUnicode_FromString(value))
  2769. static PyStatus
  2770. _PySys_InitCore(PyThreadState *tstate, PyObject *sysdict)
  2771. {
  2772. PyObject *version_info;
  2773. int res;
  2774. PyInterpreterState *interp = tstate->interp;
  2775. /* stdin/stdout/stderr are set in pylifecycle.c */
  2776. #define COPY_SYS_ATTR(tokey, fromkey) \
  2777. SET_SYS(tokey, PyMapping_GetItemString(sysdict, fromkey))
  2778. COPY_SYS_ATTR("__displayhook__", "displayhook");
  2779. COPY_SYS_ATTR("__excepthook__", "excepthook");
  2780. COPY_SYS_ATTR("__breakpointhook__", "breakpointhook");
  2781. COPY_SYS_ATTR("__unraisablehook__", "unraisablehook");
  2782. #undef COPY_SYS_ATTR
  2783. SET_SYS_FROM_STRING("version", Py_GetVersion());
  2784. SET_SYS("hexversion", PyLong_FromLong(PY_VERSION_HEX));
  2785. SET_SYS("_git", Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
  2786. _Py_gitversion()));
  2787. SET_SYS_FROM_STRING("_framework", _PYTHONFRAMEWORK);
  2788. SET_SYS("api_version", PyLong_FromLong(PYTHON_API_VERSION));
  2789. SET_SYS_FROM_STRING("copyright", Py_GetCopyright());
  2790. SET_SYS_FROM_STRING("platform", Py_GetPlatform());
  2791. SET_SYS("maxsize", PyLong_FromSsize_t(PY_SSIZE_T_MAX));
  2792. SET_SYS("float_info", PyFloat_GetInfo());
  2793. SET_SYS("int_info", PyLong_GetInfo());
  2794. /* initialize hash_info */
  2795. if (_PyStructSequence_InitBuiltin(interp, &Hash_InfoType,
  2796. &hash_info_desc) < 0)
  2797. {
  2798. goto type_init_failed;
  2799. }
  2800. SET_SYS("hash_info", get_hash_info(tstate));
  2801. SET_SYS("maxunicode", PyLong_FromLong(0x10FFFF));
  2802. SET_SYS("builtin_module_names", list_builtin_module_names());
  2803. SET_SYS("stdlib_module_names", list_stdlib_module_names());
  2804. #if PY_BIG_ENDIAN
  2805. SET_SYS_FROM_STRING("byteorder", "big");
  2806. #else
  2807. SET_SYS_FROM_STRING("byteorder", "little");
  2808. #endif
  2809. #ifdef MS_COREDLL
  2810. SET_SYS("dllhandle", PyLong_FromVoidPtr(PyWin_DLLhModule));
  2811. SET_SYS_FROM_STRING("winver", PyWin_DLLVersionString);
  2812. #endif
  2813. #ifdef ABIFLAGS
  2814. SET_SYS_FROM_STRING("abiflags", ABIFLAGS);
  2815. #endif
  2816. #define ENSURE_INFO_TYPE(TYPE, DESC) \
  2817. do { \
  2818. if (_PyStructSequence_InitBuiltinWithFlags( \
  2819. interp, &TYPE, &DESC, Py_TPFLAGS_DISALLOW_INSTANTIATION) < 0) { \
  2820. goto type_init_failed; \
  2821. } \
  2822. } while (0)
  2823. /* version_info */
  2824. ENSURE_INFO_TYPE(VersionInfoType, version_info_desc);
  2825. version_info = make_version_info(tstate);
  2826. SET_SYS("version_info", version_info);
  2827. /* implementation */
  2828. SET_SYS("implementation", make_impl_info(version_info));
  2829. // sys.flags: updated in-place later by _PySys_UpdateConfig()
  2830. ENSURE_INFO_TYPE(FlagsType, flags_desc);
  2831. SET_SYS("flags", make_flags(tstate->interp));
  2832. #if defined(MS_WINDOWS)
  2833. /* getwindowsversion */
  2834. ENSURE_INFO_TYPE(WindowsVersionType, windows_version_desc);
  2835. SET_SYS_FROM_STRING("_vpath", VPATH);
  2836. #endif
  2837. #undef ENSURE_INFO_TYPE
  2838. /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
  2839. #if _PY_SHORT_FLOAT_REPR == 1
  2840. SET_SYS_FROM_STRING("float_repr_style", "short");
  2841. #else
  2842. SET_SYS_FROM_STRING("float_repr_style", "legacy");
  2843. #endif
  2844. SET_SYS("thread_info", PyThread_GetInfo());
  2845. /* initialize asyncgen_hooks */
  2846. if (_PyStructSequence_InitBuiltin(interp, &AsyncGenHooksType,
  2847. &asyncgen_hooks_desc) < 0)
  2848. {
  2849. goto type_init_failed;
  2850. }
  2851. #ifdef __EMSCRIPTEN__
  2852. if (EmscriptenInfoType == NULL) {
  2853. EmscriptenInfoType = PyStructSequence_NewType(&emscripten_info_desc);
  2854. if (EmscriptenInfoType == NULL) {
  2855. goto type_init_failed;
  2856. }
  2857. }
  2858. SET_SYS("_emscripten_info", make_emscripten_info());
  2859. #endif
  2860. /* adding sys.path_hooks and sys.path_importer_cache */
  2861. SET_SYS("meta_path", PyList_New(0));
  2862. SET_SYS("path_importer_cache", PyDict_New());
  2863. SET_SYS("path_hooks", PyList_New(0));
  2864. if (_PyErr_Occurred(tstate)) {
  2865. goto err_occurred;
  2866. }
  2867. return _PyStatus_OK();
  2868. type_init_failed:
  2869. return _PyStatus_ERR("failed to initialize a type");
  2870. err_occurred:
  2871. return _PyStatus_ERR("can't initialize sys module");
  2872. }
  2873. static int
  2874. sys_add_xoption(PyObject *opts, const wchar_t *s)
  2875. {
  2876. PyObject *name, *value = NULL;
  2877. const wchar_t *name_end = wcschr(s, L'=');
  2878. if (!name_end) {
  2879. name = PyUnicode_FromWideChar(s, -1);
  2880. if (name == NULL) {
  2881. goto error;
  2882. }
  2883. value = Py_NewRef(Py_True);
  2884. }
  2885. else {
  2886. name = PyUnicode_FromWideChar(s, name_end - s);
  2887. if (name == NULL) {
  2888. goto error;
  2889. }
  2890. value = PyUnicode_FromWideChar(name_end + 1, -1);
  2891. if (value == NULL) {
  2892. goto error;
  2893. }
  2894. }
  2895. if (PyDict_SetItem(opts, name, value) < 0) {
  2896. goto error;
  2897. }
  2898. Py_DECREF(name);
  2899. Py_DECREF(value);
  2900. return 0;
  2901. error:
  2902. Py_XDECREF(name);
  2903. Py_XDECREF(value);
  2904. return -1;
  2905. }
  2906. static PyObject*
  2907. sys_create_xoptions_dict(const PyConfig *config)
  2908. {
  2909. Py_ssize_t nxoption = config->xoptions.length;
  2910. wchar_t * const * xoptions = config->xoptions.items;
  2911. PyObject *dict = PyDict_New();
  2912. if (dict == NULL) {
  2913. return NULL;
  2914. }
  2915. for (Py_ssize_t i=0; i < nxoption; i++) {
  2916. const wchar_t *option = xoptions[i];
  2917. if (sys_add_xoption(dict, option) < 0) {
  2918. Py_DECREF(dict);
  2919. return NULL;
  2920. }
  2921. }
  2922. return dict;
  2923. }
  2924. // Update sys attributes for a new PyConfig configuration.
  2925. // This function also adds attributes that _PySys_InitCore() didn't add.
  2926. int
  2927. _PySys_UpdateConfig(PyThreadState *tstate)
  2928. {
  2929. PyInterpreterState *interp = tstate->interp;
  2930. PyObject *sysdict = interp->sysdict;
  2931. const PyConfig *config = _PyInterpreterState_GetConfig(interp);
  2932. int res;
  2933. #define COPY_LIST(KEY, VALUE) \
  2934. SET_SYS(KEY, _PyWideStringList_AsList(&(VALUE)));
  2935. #define SET_SYS_FROM_WSTR(KEY, VALUE) \
  2936. SET_SYS(KEY, PyUnicode_FromWideChar(VALUE, -1));
  2937. #define COPY_WSTR(SYS_ATTR, WSTR) \
  2938. if (WSTR != NULL) { \
  2939. SET_SYS_FROM_WSTR(SYS_ATTR, WSTR); \
  2940. }
  2941. if (config->module_search_paths_set) {
  2942. COPY_LIST("path", config->module_search_paths);
  2943. }
  2944. COPY_WSTR("executable", config->executable);
  2945. COPY_WSTR("_base_executable", config->base_executable);
  2946. COPY_WSTR("prefix", config->prefix);
  2947. COPY_WSTR("base_prefix", config->base_prefix);
  2948. COPY_WSTR("exec_prefix", config->exec_prefix);
  2949. COPY_WSTR("base_exec_prefix", config->base_exec_prefix);
  2950. COPY_WSTR("platlibdir", config->platlibdir);
  2951. if (config->pycache_prefix != NULL) {
  2952. SET_SYS_FROM_WSTR("pycache_prefix", config->pycache_prefix);
  2953. } else {
  2954. if (PyDict_SetItemString(sysdict, "pycache_prefix", Py_None) < 0) {
  2955. return -1;
  2956. }
  2957. }
  2958. COPY_LIST("argv", config->argv);
  2959. COPY_LIST("orig_argv", config->orig_argv);
  2960. COPY_LIST("warnoptions", config->warnoptions);
  2961. SET_SYS("_xoptions", sys_create_xoptions_dict(config));
  2962. const wchar_t *stdlibdir = _Py_GetStdlibDir();
  2963. if (stdlibdir != NULL) {
  2964. SET_SYS_FROM_WSTR("_stdlib_dir", stdlibdir);
  2965. }
  2966. else {
  2967. if (PyDict_SetItemString(sysdict, "_stdlib_dir", Py_None) < 0) {
  2968. return -1;
  2969. }
  2970. }
  2971. #undef SET_SYS_FROM_WSTR
  2972. #undef COPY_LIST
  2973. #undef COPY_WSTR
  2974. // sys.flags
  2975. PyObject *flags = _PySys_GetObject(interp, "flags"); // borrowed ref
  2976. if (flags == NULL) {
  2977. if (!_PyErr_Occurred(tstate)) {
  2978. _PyErr_SetString(tstate, PyExc_RuntimeError, "lost sys.flags");
  2979. }
  2980. return -1;
  2981. }
  2982. if (set_flags_from_config(interp, flags) < 0) {
  2983. return -1;
  2984. }
  2985. SET_SYS("dont_write_bytecode", PyBool_FromLong(!config->write_bytecode));
  2986. if (_PyErr_Occurred(tstate)) {
  2987. goto err_occurred;
  2988. }
  2989. return 0;
  2990. err_occurred:
  2991. return -1;
  2992. }
  2993. #undef SET_SYS
  2994. #undef SET_SYS_FROM_STRING
  2995. /* Set up a preliminary stderr printer until we have enough
  2996. infrastructure for the io module in place.
  2997. Use UTF-8/backslashreplace and ignore EAGAIN errors. */
  2998. static PyStatus
  2999. _PySys_SetPreliminaryStderr(PyObject *sysdict)
  3000. {
  3001. PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
  3002. if (pstderr == NULL) {
  3003. goto error;
  3004. }
  3005. if (PyDict_SetItem(sysdict, &_Py_ID(stderr), pstderr) < 0) {
  3006. goto error;
  3007. }
  3008. if (PyDict_SetItemString(sysdict, "__stderr__", pstderr) < 0) {
  3009. goto error;
  3010. }
  3011. Py_DECREF(pstderr);
  3012. return _PyStatus_OK();
  3013. error:
  3014. Py_XDECREF(pstderr);
  3015. return _PyStatus_ERR("can't set preliminary stderr");
  3016. }
  3017. PyObject *_Py_CreateMonitoringObject(void);
  3018. /* Create sys module without all attributes.
  3019. _PySys_UpdateConfig() should be called later to add remaining attributes. */
  3020. PyStatus
  3021. _PySys_Create(PyThreadState *tstate, PyObject **sysmod_p)
  3022. {
  3023. assert(!_PyErr_Occurred(tstate));
  3024. PyInterpreterState *interp = tstate->interp;
  3025. PyObject *modules = _PyImport_InitModules(interp);
  3026. if (modules == NULL) {
  3027. goto error;
  3028. }
  3029. PyObject *sysmod = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
  3030. if (sysmod == NULL) {
  3031. return _PyStatus_ERR("failed to create a module object");
  3032. }
  3033. PyObject *sysdict = PyModule_GetDict(sysmod);
  3034. if (sysdict == NULL) {
  3035. goto error;
  3036. }
  3037. interp->sysdict = Py_NewRef(sysdict);
  3038. interp->sysdict_copy = PyDict_Copy(sysdict);
  3039. if (interp->sysdict_copy == NULL) {
  3040. goto error;
  3041. }
  3042. if (PyDict_SetItemString(sysdict, "modules", modules) < 0) {
  3043. goto error;
  3044. }
  3045. PyStatus status = _PySys_SetPreliminaryStderr(sysdict);
  3046. if (_PyStatus_EXCEPTION(status)) {
  3047. return status;
  3048. }
  3049. status = _PySys_InitCore(tstate, sysdict);
  3050. if (_PyStatus_EXCEPTION(status)) {
  3051. return status;
  3052. }
  3053. if (_PyImport_FixupBuiltin(sysmod, "sys", modules) < 0) {
  3054. goto error;
  3055. }
  3056. PyObject *monitoring = _Py_CreateMonitoringObject();
  3057. if (monitoring == NULL) {
  3058. goto error;
  3059. }
  3060. int err = PyDict_SetItemString(sysdict, "monitoring", monitoring);
  3061. Py_DECREF(monitoring);
  3062. if (err < 0) {
  3063. goto error;
  3064. }
  3065. assert(!_PyErr_Occurred(tstate));
  3066. *sysmod_p = sysmod;
  3067. return _PyStatus_OK();
  3068. error:
  3069. return _PyStatus_ERR("can't initialize sys module");
  3070. }
  3071. void
  3072. _PySys_FiniTypes(PyInterpreterState *interp)
  3073. {
  3074. _PyStructSequence_FiniBuiltin(interp, &VersionInfoType);
  3075. _PyStructSequence_FiniBuiltin(interp, &FlagsType);
  3076. #if defined(MS_WINDOWS)
  3077. _PyStructSequence_FiniBuiltin(interp, &WindowsVersionType);
  3078. #endif
  3079. _PyStructSequence_FiniBuiltin(interp, &Hash_InfoType);
  3080. _PyStructSequence_FiniBuiltin(interp, &AsyncGenHooksType);
  3081. #ifdef __EMSCRIPTEN__
  3082. if (_Py_IsMainInterpreter(interp)) {
  3083. Py_CLEAR(EmscriptenInfoType);
  3084. }
  3085. #endif
  3086. }
  3087. static PyObject *
  3088. makepathobject(const wchar_t *path, wchar_t delim)
  3089. {
  3090. int i, n;
  3091. const wchar_t *p;
  3092. PyObject *v, *w;
  3093. n = 1;
  3094. p = path;
  3095. while ((p = wcschr(p, delim)) != NULL) {
  3096. n++;
  3097. p++;
  3098. }
  3099. v = PyList_New(n);
  3100. if (v == NULL)
  3101. return NULL;
  3102. for (i = 0; ; i++) {
  3103. p = wcschr(path, delim);
  3104. if (p == NULL)
  3105. p = path + wcslen(path); /* End of string */
  3106. w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
  3107. if (w == NULL) {
  3108. Py_DECREF(v);
  3109. return NULL;
  3110. }
  3111. PyList_SET_ITEM(v, i, w);
  3112. if (*p == '\0')
  3113. break;
  3114. path = p+1;
  3115. }
  3116. return v;
  3117. }
  3118. void
  3119. PySys_SetPath(const wchar_t *path)
  3120. {
  3121. PyObject *v;
  3122. if ((v = makepathobject(path, DELIM)) == NULL)
  3123. Py_FatalError("can't create sys.path");
  3124. PyInterpreterState *interp = _PyInterpreterState_GET();
  3125. if (sys_set_object(interp, &_Py_ID(path), v) != 0) {
  3126. Py_FatalError("can't assign sys.path");
  3127. }
  3128. Py_DECREF(v);
  3129. }
  3130. static PyObject *
  3131. make_sys_argv(int argc, wchar_t * const * argv)
  3132. {
  3133. PyObject *list = PyList_New(argc);
  3134. if (list == NULL) {
  3135. return NULL;
  3136. }
  3137. for (Py_ssize_t i = 0; i < argc; i++) {
  3138. PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
  3139. if (v == NULL) {
  3140. Py_DECREF(list);
  3141. return NULL;
  3142. }
  3143. PyList_SET_ITEM(list, i, v);
  3144. }
  3145. return list;
  3146. }
  3147. void
  3148. PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
  3149. {
  3150. wchar_t* empty_argv[1] = {L""};
  3151. PyThreadState *tstate = _PyThreadState_GET();
  3152. if (argc < 1 || argv == NULL) {
  3153. /* Ensure at least one (empty) argument is seen */
  3154. argv = empty_argv;
  3155. argc = 1;
  3156. }
  3157. PyObject *av = make_sys_argv(argc, argv);
  3158. if (av == NULL) {
  3159. Py_FatalError("no mem for sys.argv");
  3160. }
  3161. if (sys_set_object_str(tstate->interp, "argv", av) != 0) {
  3162. Py_DECREF(av);
  3163. Py_FatalError("can't assign sys.argv");
  3164. }
  3165. Py_DECREF(av);
  3166. if (updatepath) {
  3167. /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
  3168. If argv[0] is a symlink, use the real path. */
  3169. const PyWideStringList argv_list = {.length = argc, .items = argv};
  3170. PyObject *path0 = NULL;
  3171. if (_PyPathConfig_ComputeSysPath0(&argv_list, &path0)) {
  3172. if (path0 == NULL) {
  3173. Py_FatalError("can't compute path0 from argv");
  3174. }
  3175. PyObject *sys_path = _PySys_GetAttr(tstate, &_Py_ID(path));
  3176. if (sys_path != NULL) {
  3177. if (PyList_Insert(sys_path, 0, path0) < 0) {
  3178. Py_DECREF(path0);
  3179. Py_FatalError("can't prepend path0 to sys.path");
  3180. }
  3181. }
  3182. Py_DECREF(path0);
  3183. }
  3184. }
  3185. }
  3186. void
  3187. PySys_SetArgv(int argc, wchar_t **argv)
  3188. {
  3189. _Py_COMP_DIAG_PUSH
  3190. _Py_COMP_DIAG_IGNORE_DEPR_DECLS
  3191. PySys_SetArgvEx(argc, argv, 0);
  3192. _Py_COMP_DIAG_POP
  3193. }
  3194. /* Reimplementation of PyFile_WriteString() no calling indirectly
  3195. PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
  3196. static int
  3197. sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
  3198. {
  3199. if (file == NULL)
  3200. return -1;
  3201. assert(unicode != NULL);
  3202. PyObject *result = _PyObject_CallMethodOneArg(file, &_Py_ID(write), unicode);
  3203. if (result == NULL) {
  3204. return -1;
  3205. }
  3206. Py_DECREF(result);
  3207. return 0;
  3208. }
  3209. static int
  3210. sys_pyfile_write(const char *text, PyObject *file)
  3211. {
  3212. PyObject *unicode = NULL;
  3213. int err;
  3214. if (file == NULL)
  3215. return -1;
  3216. unicode = PyUnicode_FromString(text);
  3217. if (unicode == NULL)
  3218. return -1;
  3219. err = sys_pyfile_write_unicode(unicode, file);
  3220. Py_DECREF(unicode);
  3221. return err;
  3222. }
  3223. /* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
  3224. Adapted from code submitted by Just van Rossum.
  3225. PySys_WriteStdout(format, ...)
  3226. PySys_WriteStderr(format, ...)
  3227. The first function writes to sys.stdout; the second to sys.stderr. When
  3228. there is a problem, they write to the real (C level) stdout or stderr;
  3229. no exceptions are raised.
  3230. PyErr_CheckSignals() is not called to avoid the execution of the Python
  3231. signal handlers: they may raise a new exception whereas sys_write()
  3232. ignores all exceptions.
  3233. Both take a printf-style format string as their first argument followed
  3234. by a variable length argument list determined by the format string.
  3235. *** WARNING ***
  3236. The format should limit the total size of the formatted output string to
  3237. 1000 bytes. In particular, this means that no unrestricted "%s" formats
  3238. should occur; these should be limited using "%.<N>s where <N> is a
  3239. decimal number calculated so that <N> plus the maximum size of other
  3240. formatted text does not exceed 1000 bytes. Also watch out for "%f",
  3241. which can print hundreds of digits for very large numbers.
  3242. */
  3243. static void
  3244. sys_write(PyObject *key, FILE *fp, const char *format, va_list va)
  3245. {
  3246. PyObject *file;
  3247. char buffer[1001];
  3248. int written;
  3249. PyThreadState *tstate = _PyThreadState_GET();
  3250. PyObject *exc = _PyErr_GetRaisedException(tstate);
  3251. file = _PySys_GetAttr(tstate, key);
  3252. written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
  3253. if (sys_pyfile_write(buffer, file) != 0) {
  3254. _PyErr_Clear(tstate);
  3255. fputs(buffer, fp);
  3256. }
  3257. if (written < 0 || (size_t)written >= sizeof(buffer)) {
  3258. const char *truncated = "... truncated";
  3259. if (sys_pyfile_write(truncated, file) != 0)
  3260. fputs(truncated, fp);
  3261. }
  3262. _PyErr_SetRaisedException(tstate, exc);
  3263. }
  3264. void
  3265. PySys_WriteStdout(const char *format, ...)
  3266. {
  3267. va_list va;
  3268. va_start(va, format);
  3269. sys_write(&_Py_ID(stdout), stdout, format, va);
  3270. va_end(va);
  3271. }
  3272. void
  3273. PySys_WriteStderr(const char *format, ...)
  3274. {
  3275. va_list va;
  3276. va_start(va, format);
  3277. sys_write(&_Py_ID(stderr), stderr, format, va);
  3278. va_end(va);
  3279. }
  3280. static void
  3281. sys_format(PyObject *key, FILE *fp, const char *format, va_list va)
  3282. {
  3283. PyObject *file, *message;
  3284. const char *utf8;
  3285. PyThreadState *tstate = _PyThreadState_GET();
  3286. PyObject *exc = _PyErr_GetRaisedException(tstate);
  3287. file = _PySys_GetAttr(tstate, key);
  3288. message = PyUnicode_FromFormatV(format, va);
  3289. if (message != NULL) {
  3290. if (sys_pyfile_write_unicode(message, file) != 0) {
  3291. _PyErr_Clear(tstate);
  3292. utf8 = PyUnicode_AsUTF8(message);
  3293. if (utf8 != NULL)
  3294. fputs(utf8, fp);
  3295. }
  3296. Py_DECREF(message);
  3297. }
  3298. _PyErr_SetRaisedException(tstate, exc);
  3299. }
  3300. void
  3301. PySys_FormatStdout(const char *format, ...)
  3302. {
  3303. va_list va;
  3304. va_start(va, format);
  3305. sys_format(&_Py_ID(stdout), stdout, format, va);
  3306. va_end(va);
  3307. }
  3308. void
  3309. PySys_FormatStderr(const char *format, ...)
  3310. {
  3311. va_list va;
  3312. va_start(va, format);
  3313. sys_format(&_Py_ID(stderr), stderr, format, va);
  3314. va_end(va);
  3315. }