ceval.c 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823
  1. /* Execute compiled code */
  2. #define _PY_INTERPRETER
  3. #include "Python.h"
  4. #include "pycore_abstract.h" // _PyIndex_Check()
  5. #include "pycore_call.h" // _PyObject_FastCallDictTstate()
  6. #include "pycore_ceval.h" // _PyEval_SignalAsyncExc()
  7. #include "pycore_code.h"
  8. #include "pycore_function.h"
  9. #include "pycore_intrinsics.h"
  10. #include "pycore_long.h" // _PyLong_GetZero()
  11. #include "pycore_instruments.h"
  12. #include "pycore_object.h" // _PyObject_GC_TRACK()
  13. #include "pycore_moduleobject.h" // PyModuleObject
  14. #include "pycore_opcode.h" // EXTRA_CASES
  15. #include "pycore_pyerrors.h" // _PyErr_GetRaisedException()
  16. #include "pycore_pymem.h" // _PyMem_IsPtrFreed()
  17. #include "pycore_pystate.h" // _PyInterpreterState_GET()
  18. #include "pycore_range.h" // _PyRangeIterObject
  19. #include "pycore_sliceobject.h" // _PyBuildSlice_ConsumeRefs
  20. #include "pycore_sysmodule.h" // _PySys_Audit()
  21. #include "pycore_traceback.h" // _PyTraceBack_FromFrame
  22. #include "pycore_tuple.h" // _PyTuple_ITEMS()
  23. #include "pycore_typeobject.h" // _PySuper_Lookup()
  24. #include "pycore_emscripten_signal.h" // _Py_CHECK_EMSCRIPTEN_SIGNALS
  25. #include "pycore_dict.h"
  26. #include "dictobject.h"
  27. #include "pycore_frame.h"
  28. #include "frameobject.h" // _PyInterpreterFrame_GetLine
  29. #include "opcode.h"
  30. #include "pydtrace.h"
  31. #include "setobject.h"
  32. #include "structmember.h" // struct PyMemberDef, T_OFFSET_EX
  33. #include <ctype.h>
  34. #include <stdbool.h>
  35. #ifdef Py_DEBUG
  36. /* For debugging the interpreter: */
  37. # define LLTRACE 1 /* Low-level trace feature */
  38. #endif
  39. #if !defined(Py_BUILD_CORE)
  40. # error "ceval.c must be build with Py_BUILD_CORE define for best performance"
  41. #endif
  42. #if !defined(Py_DEBUG) && !defined(Py_TRACE_REFS)
  43. // GH-89279: The MSVC compiler does not inline these static inline functions
  44. // in PGO build in _PyEval_EvalFrameDefault(), because this function is over
  45. // the limit of PGO, and that limit cannot be configured.
  46. // Define them as macros to make sure that they are always inlined by the
  47. // preprocessor.
  48. #undef Py_DECREF
  49. #define Py_DECREF(arg) \
  50. do { \
  51. PyObject *op = _PyObject_CAST(arg); \
  52. if (_Py_IsImmortal(op)) { \
  53. break; \
  54. } \
  55. _Py_DECREF_STAT_INC(); \
  56. if (--op->ob_refcnt == 0) { \
  57. destructor dealloc = Py_TYPE(op)->tp_dealloc; \
  58. (*dealloc)(op); \
  59. } \
  60. } while (0)
  61. #undef Py_XDECREF
  62. #define Py_XDECREF(arg) \
  63. do { \
  64. PyObject *xop = _PyObject_CAST(arg); \
  65. if (xop != NULL) { \
  66. Py_DECREF(xop); \
  67. } \
  68. } while (0)
  69. #undef Py_IS_TYPE
  70. #define Py_IS_TYPE(ob, type) \
  71. (_PyObject_CAST(ob)->ob_type == (type))
  72. #undef _Py_DECREF_SPECIALIZED
  73. #define _Py_DECREF_SPECIALIZED(arg, dealloc) \
  74. do { \
  75. PyObject *op = _PyObject_CAST(arg); \
  76. if (_Py_IsImmortal(op)) { \
  77. break; \
  78. } \
  79. _Py_DECREF_STAT_INC(); \
  80. if (--op->ob_refcnt == 0) { \
  81. destructor d = (destructor)(dealloc); \
  82. d(op); \
  83. } \
  84. } while (0)
  85. #endif
  86. // GH-89279: Similar to above, force inlining by using a macro.
  87. #if defined(_MSC_VER) && SIZEOF_INT == 4
  88. #define _Py_atomic_load_relaxed_int32(ATOMIC_VAL) (assert(sizeof((ATOMIC_VAL)->_value) == 4), *((volatile int*)&((ATOMIC_VAL)->_value)))
  89. #else
  90. #define _Py_atomic_load_relaxed_int32(ATOMIC_VAL) _Py_atomic_load_relaxed(ATOMIC_VAL)
  91. #endif
  92. #ifdef LLTRACE
  93. static void
  94. dump_stack(_PyInterpreterFrame *frame, PyObject **stack_pointer)
  95. {
  96. PyObject **stack_base = _PyFrame_Stackbase(frame);
  97. PyObject *exc = PyErr_GetRaisedException();
  98. printf(" stack=[");
  99. for (PyObject **ptr = stack_base; ptr < stack_pointer; ptr++) {
  100. if (ptr != stack_base) {
  101. printf(", ");
  102. }
  103. if (PyObject_Print(*ptr, stdout, 0) != 0) {
  104. PyErr_Clear();
  105. printf("<%s object at %p>",
  106. Py_TYPE(*ptr)->tp_name, (void *)(*ptr));
  107. }
  108. }
  109. printf("]\n");
  110. fflush(stdout);
  111. PyErr_SetRaisedException(exc);
  112. }
  113. static void
  114. lltrace_instruction(_PyInterpreterFrame *frame,
  115. PyObject **stack_pointer,
  116. _Py_CODEUNIT *next_instr)
  117. {
  118. /* This dump_stack() operation is risky, since the repr() of some
  119. objects enters the interpreter recursively. It is also slow.
  120. So you might want to comment it out. */
  121. dump_stack(frame, stack_pointer);
  122. int oparg = next_instr->op.arg;
  123. int opcode = next_instr->op.code;
  124. const char *opname = _PyOpcode_OpName[opcode];
  125. assert(opname != NULL);
  126. int offset = (int)(next_instr - _PyCode_CODE(frame->f_code));
  127. if (HAS_ARG((int)_PyOpcode_Deopt[opcode])) {
  128. printf("%d: %s %d\n", offset * 2, opname, oparg);
  129. }
  130. else {
  131. printf("%d: %s\n", offset * 2, opname);
  132. }
  133. fflush(stdout);
  134. }
  135. static void
  136. lltrace_resume_frame(_PyInterpreterFrame *frame)
  137. {
  138. PyObject *fobj = frame->f_funcobj;
  139. if (frame->owner == FRAME_OWNED_BY_CSTACK ||
  140. fobj == NULL ||
  141. !PyFunction_Check(fobj)
  142. ) {
  143. printf("\nResuming frame.\n");
  144. return;
  145. }
  146. PyFunctionObject *f = (PyFunctionObject *)fobj;
  147. PyObject *exc = PyErr_GetRaisedException();
  148. PyObject *name = f->func_qualname;
  149. if (name == NULL) {
  150. name = f->func_name;
  151. }
  152. printf("\nResuming frame");
  153. if (name) {
  154. printf(" for ");
  155. if (PyObject_Print(name, stdout, 0) < 0) {
  156. PyErr_Clear();
  157. }
  158. }
  159. if (f->func_module) {
  160. printf(" in module ");
  161. if (PyObject_Print(f->func_module, stdout, 0) < 0) {
  162. PyErr_Clear();
  163. }
  164. }
  165. printf("\n");
  166. fflush(stdout);
  167. PyErr_SetRaisedException(exc);
  168. }
  169. #endif
  170. static void monitor_raise(PyThreadState *tstate,
  171. _PyInterpreterFrame *frame,
  172. _Py_CODEUNIT *instr);
  173. static void monitor_reraise(PyThreadState *tstate,
  174. _PyInterpreterFrame *frame,
  175. _Py_CODEUNIT *instr);
  176. static int monitor_stop_iteration(PyThreadState *tstate,
  177. _PyInterpreterFrame *frame,
  178. _Py_CODEUNIT *instr);
  179. static void monitor_unwind(PyThreadState *tstate,
  180. _PyInterpreterFrame *frame,
  181. _Py_CODEUNIT *instr);
  182. static int monitor_handled(PyThreadState *tstate,
  183. _PyInterpreterFrame *frame,
  184. _Py_CODEUNIT *instr, PyObject *exc);
  185. static void monitor_throw(PyThreadState *tstate,
  186. _PyInterpreterFrame *frame,
  187. _Py_CODEUNIT *instr);
  188. static PyObject * import_name(PyThreadState *, _PyInterpreterFrame *,
  189. PyObject *, PyObject *, PyObject *);
  190. static PyObject * import_from(PyThreadState *, PyObject *, PyObject *);
  191. static void format_exc_check_arg(PyThreadState *, PyObject *, const char *, PyObject *);
  192. static void format_exc_unbound(PyThreadState *tstate, PyCodeObject *co, int oparg);
  193. static int check_args_iterable(PyThreadState *, PyObject *func, PyObject *vararg);
  194. static int check_except_type_valid(PyThreadState *tstate, PyObject* right);
  195. static int check_except_star_type_valid(PyThreadState *tstate, PyObject* right);
  196. static void format_kwargs_error(PyThreadState *, PyObject *func, PyObject *kwargs);
  197. static void format_awaitable_error(PyThreadState *, PyTypeObject *, int);
  198. static int get_exception_handler(PyCodeObject *, int, int*, int*, int*);
  199. static _PyInterpreterFrame *
  200. _PyEvalFramePushAndInit(PyThreadState *tstate, PyFunctionObject *func,
  201. PyObject *locals, PyObject* const* args,
  202. size_t argcount, PyObject *kwnames);
  203. static _PyInterpreterFrame *
  204. _PyEvalFramePushAndInit_Ex(PyThreadState *tstate, PyFunctionObject *func,
  205. PyObject *locals, Py_ssize_t nargs, PyObject *callargs, PyObject *kwargs);
  206. static void
  207. _PyEvalFrameClearAndPop(PyThreadState *tstate, _PyInterpreterFrame *frame);
  208. #define UNBOUNDLOCAL_ERROR_MSG \
  209. "cannot access local variable '%s' where it is not associated with a value"
  210. #define UNBOUNDFREE_ERROR_MSG \
  211. "cannot access free variable '%s' where it is not associated with a" \
  212. " value in enclosing scope"
  213. #ifdef HAVE_ERRNO_H
  214. #include <errno.h>
  215. #endif
  216. int
  217. Py_GetRecursionLimit(void)
  218. {
  219. PyInterpreterState *interp = _PyInterpreterState_GET();
  220. return interp->ceval.recursion_limit;
  221. }
  222. void
  223. Py_SetRecursionLimit(int new_limit)
  224. {
  225. PyInterpreterState *interp = _PyInterpreterState_GET();
  226. interp->ceval.recursion_limit = new_limit;
  227. for (PyThreadState *p = interp->threads.head; p != NULL; p = p->next) {
  228. int depth = p->py_recursion_limit - p->py_recursion_remaining;
  229. p->py_recursion_limit = new_limit;
  230. p->py_recursion_remaining = new_limit - depth;
  231. }
  232. }
  233. /* The function _Py_EnterRecursiveCallTstate() only calls _Py_CheckRecursiveCall()
  234. if the recursion_depth reaches recursion_limit. */
  235. int
  236. _Py_CheckRecursiveCall(PyThreadState *tstate, const char *where)
  237. {
  238. #ifdef USE_STACKCHECK
  239. if (PyOS_CheckStack()) {
  240. ++tstate->c_recursion_remaining;
  241. _PyErr_SetString(tstate, PyExc_MemoryError, "Stack overflow");
  242. return -1;
  243. }
  244. #endif
  245. if (tstate->recursion_headroom) {
  246. if (tstate->c_recursion_remaining < -50) {
  247. /* Overflowing while handling an overflow. Give up. */
  248. Py_FatalError("Cannot recover from stack overflow.");
  249. }
  250. }
  251. else {
  252. if (tstate->c_recursion_remaining <= 0) {
  253. tstate->recursion_headroom++;
  254. _PyErr_Format(tstate, PyExc_RecursionError,
  255. "maximum recursion depth exceeded%s",
  256. where);
  257. tstate->recursion_headroom--;
  258. ++tstate->c_recursion_remaining;
  259. return -1;
  260. }
  261. }
  262. return 0;
  263. }
  264. static const binaryfunc binary_ops[] = {
  265. [NB_ADD] = PyNumber_Add,
  266. [NB_AND] = PyNumber_And,
  267. [NB_FLOOR_DIVIDE] = PyNumber_FloorDivide,
  268. [NB_LSHIFT] = PyNumber_Lshift,
  269. [NB_MATRIX_MULTIPLY] = PyNumber_MatrixMultiply,
  270. [NB_MULTIPLY] = PyNumber_Multiply,
  271. [NB_REMAINDER] = PyNumber_Remainder,
  272. [NB_OR] = PyNumber_Or,
  273. [NB_POWER] = _PyNumber_PowerNoMod,
  274. [NB_RSHIFT] = PyNumber_Rshift,
  275. [NB_SUBTRACT] = PyNumber_Subtract,
  276. [NB_TRUE_DIVIDE] = PyNumber_TrueDivide,
  277. [NB_XOR] = PyNumber_Xor,
  278. [NB_INPLACE_ADD] = PyNumber_InPlaceAdd,
  279. [NB_INPLACE_AND] = PyNumber_InPlaceAnd,
  280. [NB_INPLACE_FLOOR_DIVIDE] = PyNumber_InPlaceFloorDivide,
  281. [NB_INPLACE_LSHIFT] = PyNumber_InPlaceLshift,
  282. [NB_INPLACE_MATRIX_MULTIPLY] = PyNumber_InPlaceMatrixMultiply,
  283. [NB_INPLACE_MULTIPLY] = PyNumber_InPlaceMultiply,
  284. [NB_INPLACE_REMAINDER] = PyNumber_InPlaceRemainder,
  285. [NB_INPLACE_OR] = PyNumber_InPlaceOr,
  286. [NB_INPLACE_POWER] = _PyNumber_InPlacePowerNoMod,
  287. [NB_INPLACE_RSHIFT] = PyNumber_InPlaceRshift,
  288. [NB_INPLACE_SUBTRACT] = PyNumber_InPlaceSubtract,
  289. [NB_INPLACE_TRUE_DIVIDE] = PyNumber_InPlaceTrueDivide,
  290. [NB_INPLACE_XOR] = PyNumber_InPlaceXor,
  291. };
  292. // PEP 634: Structural Pattern Matching
  293. // Return a tuple of values corresponding to keys, with error checks for
  294. // duplicate/missing keys.
  295. static PyObject*
  296. match_keys(PyThreadState *tstate, PyObject *map, PyObject *keys)
  297. {
  298. assert(PyTuple_CheckExact(keys));
  299. Py_ssize_t nkeys = PyTuple_GET_SIZE(keys);
  300. if (!nkeys) {
  301. // No keys means no items.
  302. return PyTuple_New(0);
  303. }
  304. PyObject *seen = NULL;
  305. PyObject *dummy = NULL;
  306. PyObject *values = NULL;
  307. PyObject *get = NULL;
  308. // We use the two argument form of map.get(key, default) for two reasons:
  309. // - Atomically check for a key and get its value without error handling.
  310. // - Don't cause key creation or resizing in dict subclasses like
  311. // collections.defaultdict that define __missing__ (or similar).
  312. int meth_found = _PyObject_GetMethod(map, &_Py_ID(get), &get);
  313. if (get == NULL) {
  314. goto fail;
  315. }
  316. seen = PySet_New(NULL);
  317. if (seen == NULL) {
  318. goto fail;
  319. }
  320. // dummy = object()
  321. dummy = _PyObject_CallNoArgs((PyObject *)&PyBaseObject_Type);
  322. if (dummy == NULL) {
  323. goto fail;
  324. }
  325. values = PyTuple_New(nkeys);
  326. if (values == NULL) {
  327. goto fail;
  328. }
  329. for (Py_ssize_t i = 0; i < nkeys; i++) {
  330. PyObject *key = PyTuple_GET_ITEM(keys, i);
  331. if (PySet_Contains(seen, key) || PySet_Add(seen, key)) {
  332. if (!_PyErr_Occurred(tstate)) {
  333. // Seen it before!
  334. _PyErr_Format(tstate, PyExc_ValueError,
  335. "mapping pattern checks duplicate key (%R)", key);
  336. }
  337. goto fail;
  338. }
  339. PyObject *args[] = { map, key, dummy };
  340. PyObject *value = NULL;
  341. if (meth_found) {
  342. value = PyObject_Vectorcall(get, args, 3, NULL);
  343. }
  344. else {
  345. value = PyObject_Vectorcall(get, &args[1], 2, NULL);
  346. }
  347. if (value == NULL) {
  348. goto fail;
  349. }
  350. if (value == dummy) {
  351. // key not in map!
  352. Py_DECREF(value);
  353. Py_DECREF(values);
  354. // Return None:
  355. values = Py_NewRef(Py_None);
  356. goto done;
  357. }
  358. PyTuple_SET_ITEM(values, i, value);
  359. }
  360. // Success:
  361. done:
  362. Py_DECREF(get);
  363. Py_DECREF(seen);
  364. Py_DECREF(dummy);
  365. return values;
  366. fail:
  367. Py_XDECREF(get);
  368. Py_XDECREF(seen);
  369. Py_XDECREF(dummy);
  370. Py_XDECREF(values);
  371. return NULL;
  372. }
  373. // Extract a named attribute from the subject, with additional bookkeeping to
  374. // raise TypeErrors for repeated lookups. On failure, return NULL (with no
  375. // error set). Use _PyErr_Occurred(tstate) to disambiguate.
  376. static PyObject*
  377. match_class_attr(PyThreadState *tstate, PyObject *subject, PyObject *type,
  378. PyObject *name, PyObject *seen)
  379. {
  380. assert(PyUnicode_CheckExact(name));
  381. assert(PySet_CheckExact(seen));
  382. if (PySet_Contains(seen, name) || PySet_Add(seen, name)) {
  383. if (!_PyErr_Occurred(tstate)) {
  384. // Seen it before!
  385. _PyErr_Format(tstate, PyExc_TypeError,
  386. "%s() got multiple sub-patterns for attribute %R",
  387. ((PyTypeObject*)type)->tp_name, name);
  388. }
  389. return NULL;
  390. }
  391. PyObject *attr = PyObject_GetAttr(subject, name);
  392. if (attr == NULL && _PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
  393. _PyErr_Clear(tstate);
  394. }
  395. return attr;
  396. }
  397. // On success (match), return a tuple of extracted attributes. On failure (no
  398. // match), return NULL. Use _PyErr_Occurred(tstate) to disambiguate.
  399. static PyObject*
  400. match_class(PyThreadState *tstate, PyObject *subject, PyObject *type,
  401. Py_ssize_t nargs, PyObject *kwargs)
  402. {
  403. if (!PyType_Check(type)) {
  404. const char *e = "called match pattern must be a class";
  405. _PyErr_Format(tstate, PyExc_TypeError, e);
  406. return NULL;
  407. }
  408. assert(PyTuple_CheckExact(kwargs));
  409. // First, an isinstance check:
  410. if (PyObject_IsInstance(subject, type) <= 0) {
  411. return NULL;
  412. }
  413. // So far so good:
  414. PyObject *seen = PySet_New(NULL);
  415. if (seen == NULL) {
  416. return NULL;
  417. }
  418. PyObject *attrs = PyList_New(0);
  419. if (attrs == NULL) {
  420. Py_DECREF(seen);
  421. return NULL;
  422. }
  423. // NOTE: From this point on, goto fail on failure:
  424. PyObject *match_args = NULL;
  425. // First, the positional subpatterns:
  426. if (nargs) {
  427. int match_self = 0;
  428. match_args = PyObject_GetAttrString(type, "__match_args__");
  429. if (match_args) {
  430. if (!PyTuple_CheckExact(match_args)) {
  431. const char *e = "%s.__match_args__ must be a tuple (got %s)";
  432. _PyErr_Format(tstate, PyExc_TypeError, e,
  433. ((PyTypeObject *)type)->tp_name,
  434. Py_TYPE(match_args)->tp_name);
  435. goto fail;
  436. }
  437. }
  438. else if (_PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
  439. _PyErr_Clear(tstate);
  440. // _Py_TPFLAGS_MATCH_SELF is only acknowledged if the type does not
  441. // define __match_args__. This is natural behavior for subclasses:
  442. // it's as if __match_args__ is some "magic" value that is lost as
  443. // soon as they redefine it.
  444. match_args = PyTuple_New(0);
  445. match_self = PyType_HasFeature((PyTypeObject*)type,
  446. _Py_TPFLAGS_MATCH_SELF);
  447. }
  448. else {
  449. goto fail;
  450. }
  451. assert(PyTuple_CheckExact(match_args));
  452. Py_ssize_t allowed = match_self ? 1 : PyTuple_GET_SIZE(match_args);
  453. if (allowed < nargs) {
  454. const char *plural = (allowed == 1) ? "" : "s";
  455. _PyErr_Format(tstate, PyExc_TypeError,
  456. "%s() accepts %d positional sub-pattern%s (%d given)",
  457. ((PyTypeObject*)type)->tp_name,
  458. allowed, plural, nargs);
  459. goto fail;
  460. }
  461. if (match_self) {
  462. // Easy. Copy the subject itself, and move on to kwargs.
  463. if (PyList_Append(attrs, subject) < 0) {
  464. goto fail;
  465. }
  466. }
  467. else {
  468. for (Py_ssize_t i = 0; i < nargs; i++) {
  469. PyObject *name = PyTuple_GET_ITEM(match_args, i);
  470. if (!PyUnicode_CheckExact(name)) {
  471. _PyErr_Format(tstate, PyExc_TypeError,
  472. "__match_args__ elements must be strings "
  473. "(got %s)", Py_TYPE(name)->tp_name);
  474. goto fail;
  475. }
  476. PyObject *attr = match_class_attr(tstate, subject, type, name,
  477. seen);
  478. if (attr == NULL) {
  479. goto fail;
  480. }
  481. if (PyList_Append(attrs, attr) < 0) {
  482. Py_DECREF(attr);
  483. goto fail;
  484. }
  485. Py_DECREF(attr);
  486. }
  487. }
  488. Py_CLEAR(match_args);
  489. }
  490. // Finally, the keyword subpatterns:
  491. for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(kwargs); i++) {
  492. PyObject *name = PyTuple_GET_ITEM(kwargs, i);
  493. PyObject *attr = match_class_attr(tstate, subject, type, name, seen);
  494. if (attr == NULL) {
  495. goto fail;
  496. }
  497. if (PyList_Append(attrs, attr) < 0) {
  498. Py_DECREF(attr);
  499. goto fail;
  500. }
  501. Py_DECREF(attr);
  502. }
  503. Py_SETREF(attrs, PyList_AsTuple(attrs));
  504. Py_DECREF(seen);
  505. return attrs;
  506. fail:
  507. // We really don't care whether an error was raised or not... that's our
  508. // caller's problem. All we know is that the match failed.
  509. Py_XDECREF(match_args);
  510. Py_DECREF(seen);
  511. Py_DECREF(attrs);
  512. return NULL;
  513. }
  514. static int do_raise(PyThreadState *tstate, PyObject *exc, PyObject *cause);
  515. static int exception_group_match(
  516. _PyInterpreterFrame *frame,
  517. PyObject* exc_value, PyObject *match_type,
  518. PyObject **match, PyObject **rest);
  519. static int unpack_iterable(PyThreadState *, PyObject *, int, int, PyObject **);
  520. PyObject *
  521. PyEval_EvalCode(PyObject *co, PyObject *globals, PyObject *locals)
  522. {
  523. PyThreadState *tstate = _PyThreadState_GET();
  524. if (locals == NULL) {
  525. locals = globals;
  526. }
  527. PyObject *builtins = _PyEval_BuiltinsFromGlobals(tstate, globals); // borrowed ref
  528. if (builtins == NULL) {
  529. return NULL;
  530. }
  531. PyFrameConstructor desc = {
  532. .fc_globals = globals,
  533. .fc_builtins = builtins,
  534. .fc_name = ((PyCodeObject *)co)->co_name,
  535. .fc_qualname = ((PyCodeObject *)co)->co_name,
  536. .fc_code = co,
  537. .fc_defaults = NULL,
  538. .fc_kwdefaults = NULL,
  539. .fc_closure = NULL
  540. };
  541. PyFunctionObject *func = _PyFunction_FromConstructor(&desc);
  542. if (func == NULL) {
  543. return NULL;
  544. }
  545. EVAL_CALL_STAT_INC(EVAL_CALL_LEGACY);
  546. PyObject *res = _PyEval_Vector(tstate, func, locals, NULL, 0, NULL);
  547. Py_DECREF(func);
  548. return res;
  549. }
  550. /* Interpreter main loop */
  551. PyObject *
  552. PyEval_EvalFrame(PyFrameObject *f)
  553. {
  554. /* Function kept for backward compatibility */
  555. PyThreadState *tstate = _PyThreadState_GET();
  556. return _PyEval_EvalFrame(tstate, f->f_frame, 0);
  557. }
  558. PyObject *
  559. PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
  560. {
  561. PyThreadState *tstate = _PyThreadState_GET();
  562. return _PyEval_EvalFrame(tstate, f->f_frame, throwflag);
  563. }
  564. #include "ceval_macros.h"
  565. int _Py_CheckRecursiveCallPy(
  566. PyThreadState *tstate)
  567. {
  568. if (tstate->recursion_headroom) {
  569. if (tstate->py_recursion_remaining < -50) {
  570. /* Overflowing while handling an overflow. Give up. */
  571. Py_FatalError("Cannot recover from Python stack overflow.");
  572. }
  573. }
  574. else {
  575. if (tstate->py_recursion_remaining <= 0) {
  576. tstate->recursion_headroom++;
  577. _PyErr_Format(tstate, PyExc_RecursionError,
  578. "maximum recursion depth exceeded");
  579. tstate->recursion_headroom--;
  580. return -1;
  581. }
  582. }
  583. return 0;
  584. }
  585. static inline int _Py_EnterRecursivePy(PyThreadState *tstate) {
  586. return (tstate->py_recursion_remaining-- <= 0) &&
  587. _Py_CheckRecursiveCallPy(tstate);
  588. }
  589. static inline void _Py_LeaveRecursiveCallPy(PyThreadState *tstate) {
  590. tstate->py_recursion_remaining++;
  591. }
  592. /* Disable unused label warnings. They are handy for debugging, even
  593. if computed gotos aren't used. */
  594. /* TBD - what about other compilers? */
  595. #if defined(__GNUC__)
  596. # pragma GCC diagnostic push
  597. # pragma GCC diagnostic ignored "-Wunused-label"
  598. #elif defined(_MSC_VER) /* MS_WINDOWS */
  599. # pragma warning(push)
  600. # pragma warning(disable:4102)
  601. #endif
  602. /* _PyEval_EvalFrameDefault() is a *big* function,
  603. * so consume 3 units of C stack */
  604. #define PY_EVAL_C_STACK_UNITS 2
  605. PyObject* _Py_HOT_FUNCTION
  606. _PyEval_EvalFrameDefault(PyThreadState *tstate, _PyInterpreterFrame *frame, int throwflag)
  607. {
  608. _Py_EnsureTstateNotNULL(tstate);
  609. CALL_STAT_INC(pyeval_calls);
  610. #if USE_COMPUTED_GOTOS
  611. /* Import the static jump table */
  612. #include "opcode_targets.h"
  613. #endif
  614. #ifdef Py_STATS
  615. int lastopcode = 0;
  616. #endif
  617. // opcode is an 8-bit value to improve the code generated by MSVC
  618. // for the big switch below (in combination with the EXTRA_CASES macro).
  619. uint8_t opcode; /* Current opcode */
  620. int oparg; /* Current opcode argument, if any */
  621. #ifdef LLTRACE
  622. int lltrace = 0;
  623. #endif
  624. _PyCFrame cframe;
  625. _PyInterpreterFrame entry_frame;
  626. PyObject *kwnames = NULL; // Borrowed reference. Reset by CALL instructions.
  627. /* WARNING: Because the _PyCFrame lives on the C stack,
  628. * but can be accessed from a heap allocated object (tstate)
  629. * strict stack discipline must be maintained.
  630. */
  631. _PyCFrame *prev_cframe = tstate->cframe;
  632. cframe.previous = prev_cframe;
  633. tstate->cframe = &cframe;
  634. assert(tstate->interp->interpreter_trampoline != NULL);
  635. #ifdef Py_DEBUG
  636. /* Set these to invalid but identifiable values for debugging. */
  637. entry_frame.f_funcobj = (PyObject*)0xaaa0;
  638. entry_frame.f_locals = (PyObject*)0xaaa1;
  639. entry_frame.frame_obj = (PyFrameObject*)0xaaa2;
  640. entry_frame.f_globals = (PyObject*)0xaaa3;
  641. entry_frame.f_builtins = (PyObject*)0xaaa4;
  642. #endif
  643. entry_frame.f_code = tstate->interp->interpreter_trampoline;
  644. entry_frame.prev_instr =
  645. _PyCode_CODE(tstate->interp->interpreter_trampoline);
  646. entry_frame.stacktop = 0;
  647. entry_frame.owner = FRAME_OWNED_BY_CSTACK;
  648. entry_frame.return_offset = 0;
  649. /* Push frame */
  650. entry_frame.previous = prev_cframe->current_frame;
  651. frame->previous = &entry_frame;
  652. cframe.current_frame = frame;
  653. tstate->c_recursion_remaining -= (PY_EVAL_C_STACK_UNITS - 1);
  654. if (_Py_EnterRecursiveCallTstate(tstate, "")) {
  655. tstate->c_recursion_remaining--;
  656. tstate->py_recursion_remaining--;
  657. goto exit_unwind;
  658. }
  659. /* support for generator.throw() */
  660. if (throwflag) {
  661. if (_Py_EnterRecursivePy(tstate)) {
  662. goto exit_unwind;
  663. }
  664. /* Because this avoids the RESUME,
  665. * we need to update instrumentation */
  666. _Py_Instrument(frame->f_code, tstate->interp);
  667. monitor_throw(tstate, frame, frame->prev_instr);
  668. /* TO DO -- Monitor throw entry. */
  669. goto resume_with_error;
  670. }
  671. /* Local "register" variables.
  672. * These are cached values from the frame and code object. */
  673. _Py_CODEUNIT *next_instr;
  674. PyObject **stack_pointer;
  675. /* Sets the above local variables from the frame */
  676. #define SET_LOCALS_FROM_FRAME() \
  677. assert(_PyInterpreterFrame_LASTI(frame) >= -1); \
  678. /* Jump back to the last instruction executed... */ \
  679. next_instr = frame->prev_instr + 1; \
  680. stack_pointer = _PyFrame_GetStackPointer(frame);
  681. start_frame:
  682. if (_Py_EnterRecursivePy(tstate)) {
  683. goto exit_unwind;
  684. }
  685. resume_frame:
  686. SET_LOCALS_FROM_FRAME();
  687. #ifdef LLTRACE
  688. {
  689. if (frame != &entry_frame) {
  690. int r = PyDict_Contains(GLOBALS(), &_Py_ID(__lltrace__));
  691. if (r < 0) {
  692. goto exit_unwind;
  693. }
  694. lltrace = r;
  695. }
  696. if (lltrace) {
  697. lltrace_resume_frame(frame);
  698. }
  699. }
  700. #endif
  701. #ifdef Py_DEBUG
  702. /* _PyEval_EvalFrameDefault() must not be called with an exception set,
  703. because it can clear it (directly or indirectly) and so the
  704. caller loses its exception */
  705. assert(!_PyErr_Occurred(tstate));
  706. #endif
  707. DISPATCH();
  708. handle_eval_breaker:
  709. /* Do periodic things, like check for signals and async I/0.
  710. * We need to do reasonably frequently, but not too frequently.
  711. * All loops should include a check of the eval breaker.
  712. * We also check on return from any builtin function.
  713. *
  714. * ## More Details ###
  715. *
  716. * The eval loop (this function) normally executes the instructions
  717. * of a code object sequentially. However, the runtime supports a
  718. * number of out-of-band execution scenarios that may pause that
  719. * sequential execution long enough to do that out-of-band work
  720. * in the current thread using the current PyThreadState.
  721. *
  722. * The scenarios include:
  723. *
  724. * - cyclic garbage collection
  725. * - GIL drop requests
  726. * - "async" exceptions
  727. * - "pending calls" (some only in the main thread)
  728. * - signal handling (only in the main thread)
  729. *
  730. * When the need for one of the above is detected, the eval loop
  731. * pauses long enough to handle the detected case. Then, if doing
  732. * so didn't trigger an exception, the eval loop resumes executing
  733. * the sequential instructions.
  734. *
  735. * To make this work, the eval loop periodically checks if any
  736. * of the above needs to happen. The individual checks can be
  737. * expensive if computed each time, so a while back we switched
  738. * to using pre-computed, per-interpreter variables for the checks,
  739. * and later consolidated that to a single "eval breaker" variable
  740. * (now a PyInterpreterState field).
  741. *
  742. * For the longest time, the eval breaker check would happen
  743. * frequently, every 5 or so times through the loop, regardless
  744. * of what instruction ran last or what would run next. Then, in
  745. * early 2021 (gh-18334, commit 4958f5d), we switched to checking
  746. * the eval breaker less frequently, by hard-coding the check to
  747. * specific places in the eval loop (e.g. certain instructions).
  748. * The intent then was to check after returning from calls
  749. * and on the back edges of loops.
  750. *
  751. * In addition to being more efficient, that approach keeps
  752. * the eval loop from running arbitrary code between instructions
  753. * that don't handle that well. (See gh-74174.)
  754. *
  755. * Currently, the eval breaker check happens here at the
  756. * "handle_eval_breaker" label. Some instructions come here
  757. * explicitly (goto) and some indirectly. Notably, the check
  758. * happens on back edges in the control flow graph, which
  759. * pretty much applies to all loops and most calls.
  760. * (See bytecodes.c for exact information.)
  761. *
  762. * One consequence of this approach is that it might not be obvious
  763. * how to force any specific thread to pick up the eval breaker,
  764. * or for any specific thread to not pick it up. Mostly this
  765. * involves judicious uses of locks and careful ordering of code,
  766. * while avoiding code that might trigger the eval breaker
  767. * until so desired.
  768. */
  769. if (_Py_HandlePending(tstate) != 0) {
  770. goto error;
  771. }
  772. DISPATCH();
  773. {
  774. /* Start instructions */
  775. #if !USE_COMPUTED_GOTOS
  776. dispatch_opcode:
  777. switch (opcode)
  778. #endif
  779. {
  780. #include "generated_cases.c.h"
  781. /* INSTRUMENTED_LINE has to be here, rather than in bytecodes.c,
  782. * because it needs to capture frame->prev_instr before it is updated,
  783. * as happens in the standard instruction prologue.
  784. */
  785. #if USE_COMPUTED_GOTOS
  786. TARGET_INSTRUMENTED_LINE:
  787. #else
  788. case INSTRUMENTED_LINE:
  789. #endif
  790. {
  791. _Py_CODEUNIT *prev = frame->prev_instr;
  792. _Py_CODEUNIT *here = frame->prev_instr = next_instr;
  793. _PyFrame_SetStackPointer(frame, stack_pointer);
  794. int original_opcode = _Py_call_instrumentation_line(
  795. tstate, frame, here, prev);
  796. stack_pointer = _PyFrame_GetStackPointer(frame);
  797. if (original_opcode < 0) {
  798. next_instr = here+1;
  799. goto error;
  800. }
  801. next_instr = frame->prev_instr;
  802. if (next_instr != here) {
  803. DISPATCH();
  804. }
  805. if (_PyOpcode_Caches[original_opcode]) {
  806. _PyBinaryOpCache *cache = (_PyBinaryOpCache *)(next_instr+1);
  807. /* Prevent the underlying instruction from specializing
  808. * and overwriting the instrumentation. */
  809. INCREMENT_ADAPTIVE_COUNTER(cache->counter);
  810. }
  811. opcode = original_opcode;
  812. DISPATCH_GOTO();
  813. }
  814. #if USE_COMPUTED_GOTOS
  815. _unknown_opcode:
  816. #else
  817. EXTRA_CASES // From opcode.h, a 'case' for each unused opcode
  818. #endif
  819. /* Tell C compilers not to hold the opcode variable in the loop.
  820. next_instr points the current instruction without TARGET(). */
  821. opcode = next_instr->op.code;
  822. _PyErr_Format(tstate, PyExc_SystemError,
  823. "%U:%d: unknown opcode %d",
  824. frame->f_code->co_filename,
  825. PyUnstable_InterpreterFrame_GetLine(frame),
  826. opcode);
  827. goto error;
  828. } /* End instructions */
  829. /* This should never be reached. Every opcode should end with DISPATCH()
  830. or goto error. */
  831. Py_UNREACHABLE();
  832. unbound_local_error:
  833. {
  834. format_exc_check_arg(tstate, PyExc_UnboundLocalError,
  835. UNBOUNDLOCAL_ERROR_MSG,
  836. PyTuple_GetItem(frame->f_code->co_localsplusnames, oparg)
  837. );
  838. goto error;
  839. }
  840. pop_4_error:
  841. STACK_SHRINK(1);
  842. pop_3_error:
  843. STACK_SHRINK(1);
  844. pop_2_error:
  845. STACK_SHRINK(1);
  846. pop_1_error:
  847. STACK_SHRINK(1);
  848. error:
  849. kwnames = NULL;
  850. /* Double-check exception status. */
  851. #ifdef NDEBUG
  852. if (!_PyErr_Occurred(tstate)) {
  853. _PyErr_SetString(tstate, PyExc_SystemError,
  854. "error return without exception set");
  855. }
  856. #else
  857. assert(_PyErr_Occurred(tstate));
  858. #endif
  859. /* Log traceback info. */
  860. assert(frame != &entry_frame);
  861. if (!_PyFrame_IsIncomplete(frame)) {
  862. PyFrameObject *f = _PyFrame_GetFrameObject(frame);
  863. if (f != NULL) {
  864. PyTraceBack_Here(f);
  865. }
  866. }
  867. monitor_raise(tstate, frame, next_instr-1);
  868. exception_unwind:
  869. {
  870. /* We can't use frame->f_lasti here, as RERAISE may have set it */
  871. int offset = INSTR_OFFSET()-1;
  872. int level, handler, lasti;
  873. if (get_exception_handler(frame->f_code, offset, &level, &handler, &lasti) == 0) {
  874. // No handlers, so exit.
  875. assert(_PyErr_Occurred(tstate));
  876. /* Pop remaining stack entries. */
  877. PyObject **stackbase = _PyFrame_Stackbase(frame);
  878. while (stack_pointer > stackbase) {
  879. PyObject *o = POP();
  880. Py_XDECREF(o);
  881. }
  882. assert(STACK_LEVEL() == 0);
  883. _PyFrame_SetStackPointer(frame, stack_pointer);
  884. monitor_unwind(tstate, frame, next_instr-1);
  885. goto exit_unwind;
  886. }
  887. assert(STACK_LEVEL() >= level);
  888. PyObject **new_top = _PyFrame_Stackbase(frame) + level;
  889. while (stack_pointer > new_top) {
  890. PyObject *v = POP();
  891. Py_XDECREF(v);
  892. }
  893. if (lasti) {
  894. int frame_lasti = _PyInterpreterFrame_LASTI(frame);
  895. PyObject *lasti = PyLong_FromLong(frame_lasti);
  896. if (lasti == NULL) {
  897. goto exception_unwind;
  898. }
  899. PUSH(lasti);
  900. }
  901. /* Make the raw exception data
  902. available to the handler,
  903. so a program can emulate the
  904. Python main loop. */
  905. PyObject *exc = _PyErr_GetRaisedException(tstate);
  906. PUSH(exc);
  907. JUMPTO(handler);
  908. if (monitor_handled(tstate, frame, next_instr, exc) < 0) {
  909. goto exception_unwind;
  910. }
  911. /* Resume normal execution */
  912. DISPATCH();
  913. }
  914. }
  915. exit_unwind:
  916. assert(_PyErr_Occurred(tstate));
  917. _Py_LeaveRecursiveCallPy(tstate);
  918. assert(frame != &entry_frame);
  919. // GH-99729: We need to unlink the frame *before* clearing it:
  920. _PyInterpreterFrame *dying = frame;
  921. frame = cframe.current_frame = dying->previous;
  922. _PyEvalFrameClearAndPop(tstate, dying);
  923. frame->return_offset = 0;
  924. if (frame == &entry_frame) {
  925. /* Restore previous cframe and exit */
  926. tstate->cframe = cframe.previous;
  927. assert(tstate->cframe->current_frame == frame->previous);
  928. tstate->c_recursion_remaining += PY_EVAL_C_STACK_UNITS;
  929. return NULL;
  930. }
  931. resume_with_error:
  932. SET_LOCALS_FROM_FRAME();
  933. goto error;
  934. }
  935. #if defined(__GNUC__)
  936. # pragma GCC diagnostic pop
  937. #elif defined(_MSC_VER) /* MS_WINDOWS */
  938. # pragma warning(pop)
  939. #endif
  940. static void
  941. format_missing(PyThreadState *tstate, const char *kind,
  942. PyCodeObject *co, PyObject *names, PyObject *qualname)
  943. {
  944. int err;
  945. Py_ssize_t len = PyList_GET_SIZE(names);
  946. PyObject *name_str, *comma, *tail, *tmp;
  947. assert(PyList_CheckExact(names));
  948. assert(len >= 1);
  949. /* Deal with the joys of natural language. */
  950. switch (len) {
  951. case 1:
  952. name_str = PyList_GET_ITEM(names, 0);
  953. Py_INCREF(name_str);
  954. break;
  955. case 2:
  956. name_str = PyUnicode_FromFormat("%U and %U",
  957. PyList_GET_ITEM(names, len - 2),
  958. PyList_GET_ITEM(names, len - 1));
  959. break;
  960. default:
  961. tail = PyUnicode_FromFormat(", %U, and %U",
  962. PyList_GET_ITEM(names, len - 2),
  963. PyList_GET_ITEM(names, len - 1));
  964. if (tail == NULL)
  965. return;
  966. /* Chop off the last two objects in the list. This shouldn't actually
  967. fail, but we can't be too careful. */
  968. err = PyList_SetSlice(names, len - 2, len, NULL);
  969. if (err == -1) {
  970. Py_DECREF(tail);
  971. return;
  972. }
  973. /* Stitch everything up into a nice comma-separated list. */
  974. comma = PyUnicode_FromString(", ");
  975. if (comma == NULL) {
  976. Py_DECREF(tail);
  977. return;
  978. }
  979. tmp = PyUnicode_Join(comma, names);
  980. Py_DECREF(comma);
  981. if (tmp == NULL) {
  982. Py_DECREF(tail);
  983. return;
  984. }
  985. name_str = PyUnicode_Concat(tmp, tail);
  986. Py_DECREF(tmp);
  987. Py_DECREF(tail);
  988. break;
  989. }
  990. if (name_str == NULL)
  991. return;
  992. _PyErr_Format(tstate, PyExc_TypeError,
  993. "%U() missing %i required %s argument%s: %U",
  994. qualname,
  995. len,
  996. kind,
  997. len == 1 ? "" : "s",
  998. name_str);
  999. Py_DECREF(name_str);
  1000. }
  1001. static void
  1002. missing_arguments(PyThreadState *tstate, PyCodeObject *co,
  1003. Py_ssize_t missing, Py_ssize_t defcount,
  1004. PyObject **localsplus, PyObject *qualname)
  1005. {
  1006. Py_ssize_t i, j = 0;
  1007. Py_ssize_t start, end;
  1008. int positional = (defcount != -1);
  1009. const char *kind = positional ? "positional" : "keyword-only";
  1010. PyObject *missing_names;
  1011. /* Compute the names of the arguments that are missing. */
  1012. missing_names = PyList_New(missing);
  1013. if (missing_names == NULL)
  1014. return;
  1015. if (positional) {
  1016. start = 0;
  1017. end = co->co_argcount - defcount;
  1018. }
  1019. else {
  1020. start = co->co_argcount;
  1021. end = start + co->co_kwonlyargcount;
  1022. }
  1023. for (i = start; i < end; i++) {
  1024. if (localsplus[i] == NULL) {
  1025. PyObject *raw = PyTuple_GET_ITEM(co->co_localsplusnames, i);
  1026. PyObject *name = PyObject_Repr(raw);
  1027. if (name == NULL) {
  1028. Py_DECREF(missing_names);
  1029. return;
  1030. }
  1031. PyList_SET_ITEM(missing_names, j++, name);
  1032. }
  1033. }
  1034. assert(j == missing);
  1035. format_missing(tstate, kind, co, missing_names, qualname);
  1036. Py_DECREF(missing_names);
  1037. }
  1038. static void
  1039. too_many_positional(PyThreadState *tstate, PyCodeObject *co,
  1040. Py_ssize_t given, PyObject *defaults,
  1041. PyObject **localsplus, PyObject *qualname)
  1042. {
  1043. int plural;
  1044. Py_ssize_t kwonly_given = 0;
  1045. Py_ssize_t i;
  1046. PyObject *sig, *kwonly_sig;
  1047. Py_ssize_t co_argcount = co->co_argcount;
  1048. assert((co->co_flags & CO_VARARGS) == 0);
  1049. /* Count missing keyword-only args. */
  1050. for (i = co_argcount; i < co_argcount + co->co_kwonlyargcount; i++) {
  1051. if (localsplus[i] != NULL) {
  1052. kwonly_given++;
  1053. }
  1054. }
  1055. Py_ssize_t defcount = defaults == NULL ? 0 : PyTuple_GET_SIZE(defaults);
  1056. if (defcount) {
  1057. Py_ssize_t atleast = co_argcount - defcount;
  1058. plural = 1;
  1059. sig = PyUnicode_FromFormat("from %zd to %zd", atleast, co_argcount);
  1060. }
  1061. else {
  1062. plural = (co_argcount != 1);
  1063. sig = PyUnicode_FromFormat("%zd", co_argcount);
  1064. }
  1065. if (sig == NULL)
  1066. return;
  1067. if (kwonly_given) {
  1068. const char *format = " positional argument%s (and %zd keyword-only argument%s)";
  1069. kwonly_sig = PyUnicode_FromFormat(format,
  1070. given != 1 ? "s" : "",
  1071. kwonly_given,
  1072. kwonly_given != 1 ? "s" : "");
  1073. if (kwonly_sig == NULL) {
  1074. Py_DECREF(sig);
  1075. return;
  1076. }
  1077. }
  1078. else {
  1079. /* This will not fail. */
  1080. kwonly_sig = PyUnicode_FromString("");
  1081. assert(kwonly_sig != NULL);
  1082. }
  1083. _PyErr_Format(tstate, PyExc_TypeError,
  1084. "%U() takes %U positional argument%s but %zd%U %s given",
  1085. qualname,
  1086. sig,
  1087. plural ? "s" : "",
  1088. given,
  1089. kwonly_sig,
  1090. given == 1 && !kwonly_given ? "was" : "were");
  1091. Py_DECREF(sig);
  1092. Py_DECREF(kwonly_sig);
  1093. }
  1094. static int
  1095. positional_only_passed_as_keyword(PyThreadState *tstate, PyCodeObject *co,
  1096. Py_ssize_t kwcount, PyObject* kwnames,
  1097. PyObject *qualname)
  1098. {
  1099. int posonly_conflicts = 0;
  1100. PyObject* posonly_names = PyList_New(0);
  1101. if (posonly_names == NULL) {
  1102. goto fail;
  1103. }
  1104. for(int k=0; k < co->co_posonlyargcount; k++){
  1105. PyObject* posonly_name = PyTuple_GET_ITEM(co->co_localsplusnames, k);
  1106. for (int k2=0; k2<kwcount; k2++){
  1107. /* Compare the pointers first and fallback to PyObject_RichCompareBool*/
  1108. PyObject* kwname = PyTuple_GET_ITEM(kwnames, k2);
  1109. if (kwname == posonly_name){
  1110. if(PyList_Append(posonly_names, kwname) != 0) {
  1111. goto fail;
  1112. }
  1113. posonly_conflicts++;
  1114. continue;
  1115. }
  1116. int cmp = PyObject_RichCompareBool(posonly_name, kwname, Py_EQ);
  1117. if ( cmp > 0) {
  1118. if(PyList_Append(posonly_names, kwname) != 0) {
  1119. goto fail;
  1120. }
  1121. posonly_conflicts++;
  1122. } else if (cmp < 0) {
  1123. goto fail;
  1124. }
  1125. }
  1126. }
  1127. if (posonly_conflicts) {
  1128. PyObject* comma = PyUnicode_FromString(", ");
  1129. if (comma == NULL) {
  1130. goto fail;
  1131. }
  1132. PyObject* error_names = PyUnicode_Join(comma, posonly_names);
  1133. Py_DECREF(comma);
  1134. if (error_names == NULL) {
  1135. goto fail;
  1136. }
  1137. _PyErr_Format(tstate, PyExc_TypeError,
  1138. "%U() got some positional-only arguments passed"
  1139. " as keyword arguments: '%U'",
  1140. qualname, error_names);
  1141. Py_DECREF(error_names);
  1142. goto fail;
  1143. }
  1144. Py_DECREF(posonly_names);
  1145. return 0;
  1146. fail:
  1147. Py_XDECREF(posonly_names);
  1148. return 1;
  1149. }
  1150. static inline unsigned char *
  1151. scan_back_to_entry_start(unsigned char *p) {
  1152. for (; (p[0]&128) == 0; p--);
  1153. return p;
  1154. }
  1155. static inline unsigned char *
  1156. skip_to_next_entry(unsigned char *p, unsigned char *end) {
  1157. while (p < end && ((p[0] & 128) == 0)) {
  1158. p++;
  1159. }
  1160. return p;
  1161. }
  1162. #define MAX_LINEAR_SEARCH 40
  1163. static int
  1164. get_exception_handler(PyCodeObject *code, int index, int *level, int *handler, int *lasti)
  1165. {
  1166. unsigned char *start = (unsigned char *)PyBytes_AS_STRING(code->co_exceptiontable);
  1167. unsigned char *end = start + PyBytes_GET_SIZE(code->co_exceptiontable);
  1168. /* Invariants:
  1169. * start_table == end_table OR
  1170. * start_table points to a legal entry and end_table points
  1171. * beyond the table or to a legal entry that is after index.
  1172. */
  1173. if (end - start > MAX_LINEAR_SEARCH) {
  1174. int offset;
  1175. parse_varint(start, &offset);
  1176. if (offset > index) {
  1177. return 0;
  1178. }
  1179. do {
  1180. unsigned char * mid = start + ((end-start)>>1);
  1181. mid = scan_back_to_entry_start(mid);
  1182. parse_varint(mid, &offset);
  1183. if (offset > index) {
  1184. end = mid;
  1185. }
  1186. else {
  1187. start = mid;
  1188. }
  1189. } while (end - start > MAX_LINEAR_SEARCH);
  1190. }
  1191. unsigned char *scan = start;
  1192. while (scan < end) {
  1193. int start_offset, size;
  1194. scan = parse_varint(scan, &start_offset);
  1195. if (start_offset > index) {
  1196. break;
  1197. }
  1198. scan = parse_varint(scan, &size);
  1199. if (start_offset + size > index) {
  1200. scan = parse_varint(scan, handler);
  1201. int depth_and_lasti;
  1202. parse_varint(scan, &depth_and_lasti);
  1203. *level = depth_and_lasti >> 1;
  1204. *lasti = depth_and_lasti & 1;
  1205. return 1;
  1206. }
  1207. scan = skip_to_next_entry(scan, end);
  1208. }
  1209. return 0;
  1210. }
  1211. static int
  1212. initialize_locals(PyThreadState *tstate, PyFunctionObject *func,
  1213. PyObject **localsplus, PyObject *const *args,
  1214. Py_ssize_t argcount, PyObject *kwnames)
  1215. {
  1216. PyCodeObject *co = (PyCodeObject*)func->func_code;
  1217. const Py_ssize_t total_args = co->co_argcount + co->co_kwonlyargcount;
  1218. /* Create a dictionary for keyword parameters (**kwags) */
  1219. PyObject *kwdict;
  1220. Py_ssize_t i;
  1221. if (co->co_flags & CO_VARKEYWORDS) {
  1222. kwdict = PyDict_New();
  1223. if (kwdict == NULL) {
  1224. goto fail_pre_positional;
  1225. }
  1226. i = total_args;
  1227. if (co->co_flags & CO_VARARGS) {
  1228. i++;
  1229. }
  1230. assert(localsplus[i] == NULL);
  1231. localsplus[i] = kwdict;
  1232. }
  1233. else {
  1234. kwdict = NULL;
  1235. }
  1236. /* Copy all positional arguments into local variables */
  1237. Py_ssize_t j, n;
  1238. if (argcount > co->co_argcount) {
  1239. n = co->co_argcount;
  1240. }
  1241. else {
  1242. n = argcount;
  1243. }
  1244. for (j = 0; j < n; j++) {
  1245. PyObject *x = args[j];
  1246. assert(localsplus[j] == NULL);
  1247. localsplus[j] = x;
  1248. }
  1249. /* Pack other positional arguments into the *args argument */
  1250. if (co->co_flags & CO_VARARGS) {
  1251. PyObject *u = NULL;
  1252. if (argcount == n) {
  1253. u = Py_NewRef(&_Py_SINGLETON(tuple_empty));
  1254. }
  1255. else {
  1256. assert(args != NULL);
  1257. u = _PyTuple_FromArraySteal(args + n, argcount - n);
  1258. }
  1259. if (u == NULL) {
  1260. goto fail_post_positional;
  1261. }
  1262. assert(localsplus[total_args] == NULL);
  1263. localsplus[total_args] = u;
  1264. }
  1265. else if (argcount > n) {
  1266. /* Too many postional args. Error is reported later */
  1267. for (j = n; j < argcount; j++) {
  1268. Py_DECREF(args[j]);
  1269. }
  1270. }
  1271. /* Handle keyword arguments */
  1272. if (kwnames != NULL) {
  1273. Py_ssize_t kwcount = PyTuple_GET_SIZE(kwnames);
  1274. for (i = 0; i < kwcount; i++) {
  1275. PyObject **co_varnames;
  1276. PyObject *keyword = PyTuple_GET_ITEM(kwnames, i);
  1277. PyObject *value = args[i+argcount];
  1278. Py_ssize_t j;
  1279. if (keyword == NULL || !PyUnicode_Check(keyword)) {
  1280. _PyErr_Format(tstate, PyExc_TypeError,
  1281. "%U() keywords must be strings",
  1282. func->func_qualname);
  1283. goto kw_fail;
  1284. }
  1285. /* Speed hack: do raw pointer compares. As names are
  1286. normally interned this should almost always hit. */
  1287. co_varnames = ((PyTupleObject *)(co->co_localsplusnames))->ob_item;
  1288. for (j = co->co_posonlyargcount; j < total_args; j++) {
  1289. PyObject *varname = co_varnames[j];
  1290. if (varname == keyword) {
  1291. goto kw_found;
  1292. }
  1293. }
  1294. /* Slow fallback, just in case */
  1295. for (j = co->co_posonlyargcount; j < total_args; j++) {
  1296. PyObject *varname = co_varnames[j];
  1297. int cmp = PyObject_RichCompareBool( keyword, varname, Py_EQ);
  1298. if (cmp > 0) {
  1299. goto kw_found;
  1300. }
  1301. else if (cmp < 0) {
  1302. goto kw_fail;
  1303. }
  1304. }
  1305. assert(j >= total_args);
  1306. if (kwdict == NULL) {
  1307. if (co->co_posonlyargcount
  1308. && positional_only_passed_as_keyword(tstate, co,
  1309. kwcount, kwnames,
  1310. func->func_qualname))
  1311. {
  1312. goto kw_fail;
  1313. }
  1314. _PyErr_Format(tstate, PyExc_TypeError,
  1315. "%U() got an unexpected keyword argument '%S'",
  1316. func->func_qualname, keyword);
  1317. goto kw_fail;
  1318. }
  1319. if (PyDict_SetItem(kwdict, keyword, value) == -1) {
  1320. goto kw_fail;
  1321. }
  1322. Py_DECREF(value);
  1323. continue;
  1324. kw_fail:
  1325. for (;i < kwcount; i++) {
  1326. PyObject *value = args[i+argcount];
  1327. Py_DECREF(value);
  1328. }
  1329. goto fail_post_args;
  1330. kw_found:
  1331. if (localsplus[j] != NULL) {
  1332. _PyErr_Format(tstate, PyExc_TypeError,
  1333. "%U() got multiple values for argument '%S'",
  1334. func->func_qualname, keyword);
  1335. goto kw_fail;
  1336. }
  1337. localsplus[j] = value;
  1338. }
  1339. }
  1340. /* Check the number of positional arguments */
  1341. if ((argcount > co->co_argcount) && !(co->co_flags & CO_VARARGS)) {
  1342. too_many_positional(tstate, co, argcount, func->func_defaults, localsplus,
  1343. func->func_qualname);
  1344. goto fail_post_args;
  1345. }
  1346. /* Add missing positional arguments (copy default values from defs) */
  1347. if (argcount < co->co_argcount) {
  1348. Py_ssize_t defcount = func->func_defaults == NULL ? 0 : PyTuple_GET_SIZE(func->func_defaults);
  1349. Py_ssize_t m = co->co_argcount - defcount;
  1350. Py_ssize_t missing = 0;
  1351. for (i = argcount; i < m; i++) {
  1352. if (localsplus[i] == NULL) {
  1353. missing++;
  1354. }
  1355. }
  1356. if (missing) {
  1357. missing_arguments(tstate, co, missing, defcount, localsplus,
  1358. func->func_qualname);
  1359. goto fail_post_args;
  1360. }
  1361. if (n > m)
  1362. i = n - m;
  1363. else
  1364. i = 0;
  1365. if (defcount) {
  1366. PyObject **defs = &PyTuple_GET_ITEM(func->func_defaults, 0);
  1367. for (; i < defcount; i++) {
  1368. if (localsplus[m+i] == NULL) {
  1369. PyObject *def = defs[i];
  1370. localsplus[m+i] = Py_NewRef(def);
  1371. }
  1372. }
  1373. }
  1374. }
  1375. /* Add missing keyword arguments (copy default values from kwdefs) */
  1376. if (co->co_kwonlyargcount > 0) {
  1377. Py_ssize_t missing = 0;
  1378. for (i = co->co_argcount; i < total_args; i++) {
  1379. if (localsplus[i] != NULL)
  1380. continue;
  1381. PyObject *varname = PyTuple_GET_ITEM(co->co_localsplusnames, i);
  1382. if (func->func_kwdefaults != NULL) {
  1383. PyObject *def = PyDict_GetItemWithError(func->func_kwdefaults, varname);
  1384. if (def) {
  1385. localsplus[i] = Py_NewRef(def);
  1386. continue;
  1387. }
  1388. else if (_PyErr_Occurred(tstate)) {
  1389. goto fail_post_args;
  1390. }
  1391. }
  1392. missing++;
  1393. }
  1394. if (missing) {
  1395. missing_arguments(tstate, co, missing, -1, localsplus,
  1396. func->func_qualname);
  1397. goto fail_post_args;
  1398. }
  1399. }
  1400. return 0;
  1401. fail_pre_positional:
  1402. for (j = 0; j < argcount; j++) {
  1403. Py_DECREF(args[j]);
  1404. }
  1405. /* fall through */
  1406. fail_post_positional:
  1407. if (kwnames) {
  1408. Py_ssize_t kwcount = PyTuple_GET_SIZE(kwnames);
  1409. for (j = argcount; j < argcount+kwcount; j++) {
  1410. Py_DECREF(args[j]);
  1411. }
  1412. }
  1413. /* fall through */
  1414. fail_post_args:
  1415. return -1;
  1416. }
  1417. static void
  1418. clear_thread_frame(PyThreadState *tstate, _PyInterpreterFrame * frame)
  1419. {
  1420. assert(frame->owner == FRAME_OWNED_BY_THREAD);
  1421. // Make sure that this is, indeed, the top frame. We can't check this in
  1422. // _PyThreadState_PopFrame, since f_code is already cleared at that point:
  1423. assert((PyObject **)frame + frame->f_code->co_framesize ==
  1424. tstate->datastack_top);
  1425. tstate->c_recursion_remaining--;
  1426. assert(frame->frame_obj == NULL || frame->frame_obj->f_frame == frame);
  1427. _PyFrame_ClearExceptCode(frame);
  1428. Py_DECREF(frame->f_code);
  1429. tstate->c_recursion_remaining++;
  1430. _PyThreadState_PopFrame(tstate, frame);
  1431. }
  1432. static void
  1433. clear_gen_frame(PyThreadState *tstate, _PyInterpreterFrame * frame)
  1434. {
  1435. assert(frame->owner == FRAME_OWNED_BY_GENERATOR);
  1436. PyGenObject *gen = _PyFrame_GetGenerator(frame);
  1437. gen->gi_frame_state = FRAME_CLEARED;
  1438. assert(tstate->exc_info == &gen->gi_exc_state);
  1439. tstate->exc_info = gen->gi_exc_state.previous_item;
  1440. gen->gi_exc_state.previous_item = NULL;
  1441. tstate->c_recursion_remaining--;
  1442. assert(frame->frame_obj == NULL || frame->frame_obj->f_frame == frame);
  1443. _PyFrame_ClearExceptCode(frame);
  1444. tstate->c_recursion_remaining++;
  1445. frame->previous = NULL;
  1446. }
  1447. static void
  1448. _PyEvalFrameClearAndPop(PyThreadState *tstate, _PyInterpreterFrame * frame)
  1449. {
  1450. if (frame->owner == FRAME_OWNED_BY_THREAD) {
  1451. clear_thread_frame(tstate, frame);
  1452. }
  1453. else {
  1454. clear_gen_frame(tstate, frame);
  1455. }
  1456. }
  1457. /* Consumes references to func, locals and all the args */
  1458. static _PyInterpreterFrame *
  1459. _PyEvalFramePushAndInit(PyThreadState *tstate, PyFunctionObject *func,
  1460. PyObject *locals, PyObject* const* args,
  1461. size_t argcount, PyObject *kwnames)
  1462. {
  1463. PyCodeObject * code = (PyCodeObject *)func->func_code;
  1464. CALL_STAT_INC(frames_pushed);
  1465. _PyInterpreterFrame *frame = _PyThreadState_PushFrame(tstate, code->co_framesize);
  1466. if (frame == NULL) {
  1467. goto fail;
  1468. }
  1469. _PyFrame_Initialize(frame, func, locals, code, 0);
  1470. if (initialize_locals(tstate, func, frame->localsplus, args, argcount, kwnames)) {
  1471. assert(frame->owner == FRAME_OWNED_BY_THREAD);
  1472. clear_thread_frame(tstate, frame);
  1473. return NULL;
  1474. }
  1475. return frame;
  1476. fail:
  1477. /* Consume the references */
  1478. for (size_t i = 0; i < argcount; i++) {
  1479. Py_DECREF(args[i]);
  1480. }
  1481. if (kwnames) {
  1482. Py_ssize_t kwcount = PyTuple_GET_SIZE(kwnames);
  1483. for (Py_ssize_t i = 0; i < kwcount; i++) {
  1484. Py_DECREF(args[i+argcount]);
  1485. }
  1486. }
  1487. PyErr_NoMemory();
  1488. return NULL;
  1489. }
  1490. /* Same as _PyEvalFramePushAndInit but takes an args tuple and kwargs dict.
  1491. Steals references to func, callargs and kwargs.
  1492. */
  1493. static _PyInterpreterFrame *
  1494. _PyEvalFramePushAndInit_Ex(PyThreadState *tstate, PyFunctionObject *func,
  1495. PyObject *locals, Py_ssize_t nargs, PyObject *callargs, PyObject *kwargs)
  1496. {
  1497. bool has_dict = (kwargs != NULL && PyDict_GET_SIZE(kwargs) > 0);
  1498. PyObject *kwnames = NULL;
  1499. PyObject *const *newargs;
  1500. if (has_dict) {
  1501. newargs = _PyStack_UnpackDict(tstate, _PyTuple_ITEMS(callargs), nargs, kwargs, &kwnames);
  1502. if (newargs == NULL) {
  1503. Py_DECREF(func);
  1504. goto error;
  1505. }
  1506. }
  1507. else {
  1508. newargs = &PyTuple_GET_ITEM(callargs, 0);
  1509. /* We need to incref all our args since the new frame steals the references. */
  1510. for (Py_ssize_t i = 0; i < nargs; ++i) {
  1511. Py_INCREF(PyTuple_GET_ITEM(callargs, i));
  1512. }
  1513. }
  1514. _PyInterpreterFrame *new_frame = _PyEvalFramePushAndInit(
  1515. tstate, (PyFunctionObject *)func, locals,
  1516. newargs, nargs, kwnames
  1517. );
  1518. if (has_dict) {
  1519. _PyStack_UnpackDict_FreeNoDecRef(newargs, kwnames);
  1520. }
  1521. /* No need to decref func here because the reference has been stolen by
  1522. _PyEvalFramePushAndInit.
  1523. */
  1524. Py_DECREF(callargs);
  1525. Py_XDECREF(kwargs);
  1526. return new_frame;
  1527. error:
  1528. Py_DECREF(callargs);
  1529. Py_XDECREF(kwargs);
  1530. return NULL;
  1531. }
  1532. PyObject *
  1533. _PyEval_Vector(PyThreadState *tstate, PyFunctionObject *func,
  1534. PyObject *locals,
  1535. PyObject* const* args, size_t argcount,
  1536. PyObject *kwnames)
  1537. {
  1538. /* _PyEvalFramePushAndInit consumes the references
  1539. * to func, locals and all its arguments */
  1540. Py_INCREF(func);
  1541. Py_XINCREF(locals);
  1542. for (size_t i = 0; i < argcount; i++) {
  1543. Py_INCREF(args[i]);
  1544. }
  1545. if (kwnames) {
  1546. Py_ssize_t kwcount = PyTuple_GET_SIZE(kwnames);
  1547. for (Py_ssize_t i = 0; i < kwcount; i++) {
  1548. Py_INCREF(args[i+argcount]);
  1549. }
  1550. }
  1551. _PyInterpreterFrame *frame = _PyEvalFramePushAndInit(
  1552. tstate, func, locals, args, argcount, kwnames);
  1553. if (frame == NULL) {
  1554. return NULL;
  1555. }
  1556. EVAL_CALL_STAT_INC(EVAL_CALL_VECTOR);
  1557. return _PyEval_EvalFrame(tstate, frame, 0);
  1558. }
  1559. /* Legacy API */
  1560. PyObject *
  1561. PyEval_EvalCodeEx(PyObject *_co, PyObject *globals, PyObject *locals,
  1562. PyObject *const *args, int argcount,
  1563. PyObject *const *kws, int kwcount,
  1564. PyObject *const *defs, int defcount,
  1565. PyObject *kwdefs, PyObject *closure)
  1566. {
  1567. PyThreadState *tstate = _PyThreadState_GET();
  1568. PyObject *res = NULL;
  1569. PyObject *defaults = _PyTuple_FromArray(defs, defcount);
  1570. if (defaults == NULL) {
  1571. return NULL;
  1572. }
  1573. PyObject *builtins = _PyEval_BuiltinsFromGlobals(tstate, globals); // borrowed ref
  1574. if (builtins == NULL) {
  1575. Py_DECREF(defaults);
  1576. return NULL;
  1577. }
  1578. if (locals == NULL) {
  1579. locals = globals;
  1580. }
  1581. PyObject *kwnames = NULL;
  1582. PyObject *const *allargs;
  1583. PyObject **newargs = NULL;
  1584. PyFunctionObject *func = NULL;
  1585. if (kwcount == 0) {
  1586. allargs = args;
  1587. }
  1588. else {
  1589. kwnames = PyTuple_New(kwcount);
  1590. if (kwnames == NULL) {
  1591. goto fail;
  1592. }
  1593. newargs = PyMem_Malloc(sizeof(PyObject *)*(kwcount+argcount));
  1594. if (newargs == NULL) {
  1595. goto fail;
  1596. }
  1597. for (int i = 0; i < argcount; i++) {
  1598. newargs[i] = args[i];
  1599. }
  1600. for (int i = 0; i < kwcount; i++) {
  1601. PyTuple_SET_ITEM(kwnames, i, Py_NewRef(kws[2*i]));
  1602. newargs[argcount+i] = kws[2*i+1];
  1603. }
  1604. allargs = newargs;
  1605. }
  1606. PyFrameConstructor constr = {
  1607. .fc_globals = globals,
  1608. .fc_builtins = builtins,
  1609. .fc_name = ((PyCodeObject *)_co)->co_name,
  1610. .fc_qualname = ((PyCodeObject *)_co)->co_name,
  1611. .fc_code = _co,
  1612. .fc_defaults = defaults,
  1613. .fc_kwdefaults = kwdefs,
  1614. .fc_closure = closure
  1615. };
  1616. func = _PyFunction_FromConstructor(&constr);
  1617. if (func == NULL) {
  1618. goto fail;
  1619. }
  1620. EVAL_CALL_STAT_INC(EVAL_CALL_LEGACY);
  1621. res = _PyEval_Vector(tstate, func, locals,
  1622. allargs, argcount,
  1623. kwnames);
  1624. fail:
  1625. Py_XDECREF(func);
  1626. Py_XDECREF(kwnames);
  1627. PyMem_Free(newargs);
  1628. Py_DECREF(defaults);
  1629. return res;
  1630. }
  1631. /* Logic for the raise statement (too complicated for inlining).
  1632. This *consumes* a reference count to each of its arguments. */
  1633. static int
  1634. do_raise(PyThreadState *tstate, PyObject *exc, PyObject *cause)
  1635. {
  1636. PyObject *type = NULL, *value = NULL;
  1637. if (exc == NULL) {
  1638. /* Reraise */
  1639. _PyErr_StackItem *exc_info = _PyErr_GetTopmostException(tstate);
  1640. exc = exc_info->exc_value;
  1641. if (Py_IsNone(exc) || exc == NULL) {
  1642. _PyErr_SetString(tstate, PyExc_RuntimeError,
  1643. "No active exception to reraise");
  1644. return 0;
  1645. }
  1646. Py_INCREF(exc);
  1647. assert(PyExceptionInstance_Check(exc));
  1648. _PyErr_SetRaisedException(tstate, exc);
  1649. return 1;
  1650. }
  1651. /* We support the following forms of raise:
  1652. raise
  1653. raise <instance>
  1654. raise <type> */
  1655. if (PyExceptionClass_Check(exc)) {
  1656. type = exc;
  1657. value = _PyObject_CallNoArgs(exc);
  1658. if (value == NULL)
  1659. goto raise_error;
  1660. if (!PyExceptionInstance_Check(value)) {
  1661. _PyErr_Format(tstate, PyExc_TypeError,
  1662. "calling %R should have returned an instance of "
  1663. "BaseException, not %R",
  1664. type, Py_TYPE(value));
  1665. goto raise_error;
  1666. }
  1667. }
  1668. else if (PyExceptionInstance_Check(exc)) {
  1669. value = exc;
  1670. type = PyExceptionInstance_Class(exc);
  1671. Py_INCREF(type);
  1672. }
  1673. else {
  1674. /* Not something you can raise. You get an exception
  1675. anyway, just not what you specified :-) */
  1676. Py_DECREF(exc);
  1677. _PyErr_SetString(tstate, PyExc_TypeError,
  1678. "exceptions must derive from BaseException");
  1679. goto raise_error;
  1680. }
  1681. assert(type != NULL);
  1682. assert(value != NULL);
  1683. if (cause) {
  1684. PyObject *fixed_cause;
  1685. if (PyExceptionClass_Check(cause)) {
  1686. fixed_cause = _PyObject_CallNoArgs(cause);
  1687. if (fixed_cause == NULL)
  1688. goto raise_error;
  1689. Py_DECREF(cause);
  1690. }
  1691. else if (PyExceptionInstance_Check(cause)) {
  1692. fixed_cause = cause;
  1693. }
  1694. else if (Py_IsNone(cause)) {
  1695. Py_DECREF(cause);
  1696. fixed_cause = NULL;
  1697. }
  1698. else {
  1699. _PyErr_SetString(tstate, PyExc_TypeError,
  1700. "exception causes must derive from "
  1701. "BaseException");
  1702. goto raise_error;
  1703. }
  1704. PyException_SetCause(value, fixed_cause);
  1705. }
  1706. _PyErr_SetObject(tstate, type, value);
  1707. /* _PyErr_SetObject incref's its arguments */
  1708. Py_DECREF(value);
  1709. Py_DECREF(type);
  1710. return 0;
  1711. raise_error:
  1712. Py_XDECREF(value);
  1713. Py_XDECREF(type);
  1714. Py_XDECREF(cause);
  1715. return 0;
  1716. }
  1717. /* Logic for matching an exception in an except* clause (too
  1718. complicated for inlining).
  1719. */
  1720. static int
  1721. exception_group_match(_PyInterpreterFrame *frame, PyObject* exc_value, PyObject *match_type,
  1722. PyObject **match, PyObject **rest)
  1723. {
  1724. if (Py_IsNone(exc_value)) {
  1725. *match = Py_NewRef(Py_None);
  1726. *rest = Py_NewRef(Py_None);
  1727. return 0;
  1728. }
  1729. assert(PyExceptionInstance_Check(exc_value));
  1730. if (PyErr_GivenExceptionMatches(exc_value, match_type)) {
  1731. /* Full match of exc itself */
  1732. bool is_eg = _PyBaseExceptionGroup_Check(exc_value);
  1733. if (is_eg) {
  1734. *match = Py_NewRef(exc_value);
  1735. }
  1736. else {
  1737. /* naked exception - wrap it */
  1738. PyObject *excs = PyTuple_Pack(1, exc_value);
  1739. if (excs == NULL) {
  1740. return -1;
  1741. }
  1742. PyObject *wrapped = _PyExc_CreateExceptionGroup("", excs);
  1743. Py_DECREF(excs);
  1744. if (wrapped == NULL) {
  1745. return -1;
  1746. }
  1747. PyFrameObject *f = _PyFrame_GetFrameObject(frame);
  1748. if (f != NULL) {
  1749. PyObject *tb = _PyTraceBack_FromFrame(NULL, f);
  1750. if (tb == NULL) {
  1751. return -1;
  1752. }
  1753. PyException_SetTraceback(wrapped, tb);
  1754. Py_DECREF(tb);
  1755. }
  1756. *match = wrapped;
  1757. }
  1758. *rest = Py_NewRef(Py_None);
  1759. return 0;
  1760. }
  1761. /* exc_value does not match match_type.
  1762. * Check for partial match if it's an exception group.
  1763. */
  1764. if (_PyBaseExceptionGroup_Check(exc_value)) {
  1765. PyObject *pair = PyObject_CallMethod(exc_value, "split", "(O)",
  1766. match_type);
  1767. if (pair == NULL) {
  1768. return -1;
  1769. }
  1770. if (!PyTuple_CheckExact(pair)) {
  1771. PyErr_Format(PyExc_TypeError,
  1772. "%.200s.split must return a tuple, not %.200s",
  1773. Py_TYPE(exc_value)->tp_name, Py_TYPE(pair)->tp_name);
  1774. Py_DECREF(pair);
  1775. return -1;
  1776. }
  1777. // allow tuples of length > 2 for backwards compatibility
  1778. if (PyTuple_GET_SIZE(pair) < 2) {
  1779. PyErr_Format(PyExc_TypeError,
  1780. "%.200s.split must return a 2-tuple, "
  1781. "got tuple of size %zd",
  1782. Py_TYPE(exc_value)->tp_name, PyTuple_GET_SIZE(pair));
  1783. Py_DECREF(pair);
  1784. return -1;
  1785. }
  1786. *match = Py_NewRef(PyTuple_GET_ITEM(pair, 0));
  1787. *rest = Py_NewRef(PyTuple_GET_ITEM(pair, 1));
  1788. Py_DECREF(pair);
  1789. return 0;
  1790. }
  1791. /* no match */
  1792. *match = Py_NewRef(Py_None);
  1793. *rest = Py_NewRef(exc_value);
  1794. return 0;
  1795. }
  1796. /* Iterate v argcnt times and store the results on the stack (via decreasing
  1797. sp). Return 1 for success, 0 if error.
  1798. If argcntafter == -1, do a simple unpack. If it is >= 0, do an unpack
  1799. with a variable target.
  1800. */
  1801. static int
  1802. unpack_iterable(PyThreadState *tstate, PyObject *v,
  1803. int argcnt, int argcntafter, PyObject **sp)
  1804. {
  1805. int i = 0, j = 0;
  1806. Py_ssize_t ll = 0;
  1807. PyObject *it; /* iter(v) */
  1808. PyObject *w;
  1809. PyObject *l = NULL; /* variable list */
  1810. assert(v != NULL);
  1811. it = PyObject_GetIter(v);
  1812. if (it == NULL) {
  1813. if (_PyErr_ExceptionMatches(tstate, PyExc_TypeError) &&
  1814. Py_TYPE(v)->tp_iter == NULL && !PySequence_Check(v))
  1815. {
  1816. _PyErr_Format(tstate, PyExc_TypeError,
  1817. "cannot unpack non-iterable %.200s object",
  1818. Py_TYPE(v)->tp_name);
  1819. }
  1820. return 0;
  1821. }
  1822. for (; i < argcnt; i++) {
  1823. w = PyIter_Next(it);
  1824. if (w == NULL) {
  1825. /* Iterator done, via error or exhaustion. */
  1826. if (!_PyErr_Occurred(tstate)) {
  1827. if (argcntafter == -1) {
  1828. _PyErr_Format(tstate, PyExc_ValueError,
  1829. "not enough values to unpack "
  1830. "(expected %d, got %d)",
  1831. argcnt, i);
  1832. }
  1833. else {
  1834. _PyErr_Format(tstate, PyExc_ValueError,
  1835. "not enough values to unpack "
  1836. "(expected at least %d, got %d)",
  1837. argcnt + argcntafter, i);
  1838. }
  1839. }
  1840. goto Error;
  1841. }
  1842. *--sp = w;
  1843. }
  1844. if (argcntafter == -1) {
  1845. /* We better have exhausted the iterator now. */
  1846. w = PyIter_Next(it);
  1847. if (w == NULL) {
  1848. if (_PyErr_Occurred(tstate))
  1849. goto Error;
  1850. Py_DECREF(it);
  1851. return 1;
  1852. }
  1853. Py_DECREF(w);
  1854. _PyErr_Format(tstate, PyExc_ValueError,
  1855. "too many values to unpack (expected %d)",
  1856. argcnt);
  1857. goto Error;
  1858. }
  1859. l = PySequence_List(it);
  1860. if (l == NULL)
  1861. goto Error;
  1862. *--sp = l;
  1863. i++;
  1864. ll = PyList_GET_SIZE(l);
  1865. if (ll < argcntafter) {
  1866. _PyErr_Format(tstate, PyExc_ValueError,
  1867. "not enough values to unpack (expected at least %d, got %zd)",
  1868. argcnt + argcntafter, argcnt + ll);
  1869. goto Error;
  1870. }
  1871. /* Pop the "after-variable" args off the list. */
  1872. for (j = argcntafter; j > 0; j--, i++) {
  1873. *--sp = PyList_GET_ITEM(l, ll - j);
  1874. }
  1875. /* Resize the list. */
  1876. Py_SET_SIZE(l, ll - argcntafter);
  1877. Py_DECREF(it);
  1878. return 1;
  1879. Error:
  1880. for (; i > 0; i--, sp++)
  1881. Py_DECREF(*sp);
  1882. Py_XDECREF(it);
  1883. return 0;
  1884. }
  1885. static int
  1886. do_monitor_exc(PyThreadState *tstate, _PyInterpreterFrame *frame,
  1887. _Py_CODEUNIT *instr, int event)
  1888. {
  1889. assert(event < _PY_MONITORING_UNGROUPED_EVENTS);
  1890. PyObject *exc = PyErr_GetRaisedException();
  1891. assert(exc != NULL);
  1892. int err = _Py_call_instrumentation_arg(tstate, event, frame, instr, exc);
  1893. if (err == 0) {
  1894. PyErr_SetRaisedException(exc);
  1895. }
  1896. else {
  1897. assert(PyErr_Occurred());
  1898. Py_DECREF(exc);
  1899. }
  1900. return err;
  1901. }
  1902. static inline bool
  1903. no_tools_for_global_event(PyThreadState *tstate, int event)
  1904. {
  1905. return tstate->interp->monitors.tools[event] == 0;
  1906. }
  1907. static inline bool
  1908. no_tools_for_local_event(PyThreadState *tstate, _PyInterpreterFrame *frame, int event)
  1909. {
  1910. assert(event < _PY_MONITORING_LOCAL_EVENTS);
  1911. _PyCoMonitoringData *data = frame->f_code->_co_monitoring;
  1912. if (data) {
  1913. return data->active_monitors.tools[event] == 0;
  1914. }
  1915. else {
  1916. return no_tools_for_global_event(tstate, event);
  1917. }
  1918. }
  1919. static void
  1920. monitor_raise(PyThreadState *tstate, _PyInterpreterFrame *frame,
  1921. _Py_CODEUNIT *instr)
  1922. {
  1923. if (no_tools_for_global_event(tstate, PY_MONITORING_EVENT_RAISE)) {
  1924. return;
  1925. }
  1926. do_monitor_exc(tstate, frame, instr, PY_MONITORING_EVENT_RAISE);
  1927. }
  1928. static void
  1929. monitor_reraise(PyThreadState *tstate, _PyInterpreterFrame *frame,
  1930. _Py_CODEUNIT *instr)
  1931. {
  1932. if (no_tools_for_global_event(tstate, PY_MONITORING_EVENT_RERAISE)) {
  1933. return;
  1934. }
  1935. do_monitor_exc(tstate, frame, instr, PY_MONITORING_EVENT_RERAISE);
  1936. }
  1937. static int
  1938. monitor_stop_iteration(PyThreadState *tstate, _PyInterpreterFrame *frame,
  1939. _Py_CODEUNIT *instr)
  1940. {
  1941. if (no_tools_for_local_event(tstate, frame, PY_MONITORING_EVENT_STOP_ITERATION)) {
  1942. return 0;
  1943. }
  1944. return do_monitor_exc(tstate, frame, instr, PY_MONITORING_EVENT_STOP_ITERATION);
  1945. }
  1946. static void
  1947. monitor_unwind(PyThreadState *tstate,
  1948. _PyInterpreterFrame *frame,
  1949. _Py_CODEUNIT *instr)
  1950. {
  1951. if (no_tools_for_global_event(tstate, PY_MONITORING_EVENT_PY_UNWIND)) {
  1952. return;
  1953. }
  1954. do_monitor_exc(tstate, frame, instr, PY_MONITORING_EVENT_PY_UNWIND);
  1955. }
  1956. static int
  1957. monitor_handled(PyThreadState *tstate,
  1958. _PyInterpreterFrame *frame,
  1959. _Py_CODEUNIT *instr, PyObject *exc)
  1960. {
  1961. if (no_tools_for_global_event(tstate, PY_MONITORING_EVENT_EXCEPTION_HANDLED)) {
  1962. return 0;
  1963. }
  1964. return _Py_call_instrumentation_arg(tstate, PY_MONITORING_EVENT_EXCEPTION_HANDLED, frame, instr, exc);
  1965. }
  1966. static void
  1967. monitor_throw(PyThreadState *tstate,
  1968. _PyInterpreterFrame *frame,
  1969. _Py_CODEUNIT *instr)
  1970. {
  1971. if (no_tools_for_global_event(tstate, PY_MONITORING_EVENT_PY_THROW)) {
  1972. return;
  1973. }
  1974. do_monitor_exc(tstate, frame, instr, PY_MONITORING_EVENT_PY_THROW);
  1975. }
  1976. void
  1977. PyThreadState_EnterTracing(PyThreadState *tstate)
  1978. {
  1979. assert(tstate->tracing >= 0);
  1980. tstate->tracing++;
  1981. }
  1982. void
  1983. PyThreadState_LeaveTracing(PyThreadState *tstate)
  1984. {
  1985. assert(tstate->tracing > 0);
  1986. tstate->tracing--;
  1987. }
  1988. PyObject*
  1989. _PyEval_CallTracing(PyObject *func, PyObject *args)
  1990. {
  1991. // Save and disable tracing
  1992. PyThreadState *tstate = _PyThreadState_GET();
  1993. int save_tracing = tstate->tracing;
  1994. tstate->tracing = 0;
  1995. // Call the tracing function
  1996. PyObject *result = PyObject_Call(func, args, NULL);
  1997. // Restore tracing
  1998. tstate->tracing = save_tracing;
  1999. return result;
  2000. }
  2001. void
  2002. PyEval_SetProfile(Py_tracefunc func, PyObject *arg)
  2003. {
  2004. PyThreadState *tstate = _PyThreadState_GET();
  2005. if (_PyEval_SetProfile(tstate, func, arg) < 0) {
  2006. /* Log _PySys_Audit() error */
  2007. _PyErr_WriteUnraisableMsg("in PyEval_SetProfile", NULL);
  2008. }
  2009. }
  2010. void
  2011. PyEval_SetProfileAllThreads(Py_tracefunc func, PyObject *arg)
  2012. {
  2013. PyThreadState *this_tstate = _PyThreadState_GET();
  2014. PyInterpreterState* interp = this_tstate->interp;
  2015. _PyRuntimeState *runtime = &_PyRuntime;
  2016. HEAD_LOCK(runtime);
  2017. PyThreadState* ts = PyInterpreterState_ThreadHead(interp);
  2018. HEAD_UNLOCK(runtime);
  2019. while (ts) {
  2020. if (_PyEval_SetProfile(ts, func, arg) < 0) {
  2021. _PyErr_WriteUnraisableMsg("in PyEval_SetProfileAllThreads", NULL);
  2022. }
  2023. HEAD_LOCK(runtime);
  2024. ts = PyThreadState_Next(ts);
  2025. HEAD_UNLOCK(runtime);
  2026. }
  2027. }
  2028. void
  2029. PyEval_SetTrace(Py_tracefunc func, PyObject *arg)
  2030. {
  2031. PyThreadState *tstate = _PyThreadState_GET();
  2032. if (_PyEval_SetTrace(tstate, func, arg) < 0) {
  2033. /* Log _PySys_Audit() error */
  2034. _PyErr_WriteUnraisableMsg("in PyEval_SetTrace", NULL);
  2035. }
  2036. }
  2037. void
  2038. PyEval_SetTraceAllThreads(Py_tracefunc func, PyObject *arg)
  2039. {
  2040. PyThreadState *this_tstate = _PyThreadState_GET();
  2041. PyInterpreterState* interp = this_tstate->interp;
  2042. _PyRuntimeState *runtime = &_PyRuntime;
  2043. HEAD_LOCK(runtime);
  2044. PyThreadState* ts = PyInterpreterState_ThreadHead(interp);
  2045. HEAD_UNLOCK(runtime);
  2046. while (ts) {
  2047. if (_PyEval_SetTrace(ts, func, arg) < 0) {
  2048. _PyErr_WriteUnraisableMsg("in PyEval_SetTraceAllThreads", NULL);
  2049. }
  2050. HEAD_LOCK(runtime);
  2051. ts = PyThreadState_Next(ts);
  2052. HEAD_UNLOCK(runtime);
  2053. }
  2054. }
  2055. int
  2056. _PyEval_SetCoroutineOriginTrackingDepth(int depth)
  2057. {
  2058. PyThreadState *tstate = _PyThreadState_GET();
  2059. if (depth < 0) {
  2060. _PyErr_SetString(tstate, PyExc_ValueError, "depth must be >= 0");
  2061. return -1;
  2062. }
  2063. tstate->coroutine_origin_tracking_depth = depth;
  2064. return 0;
  2065. }
  2066. int
  2067. _PyEval_GetCoroutineOriginTrackingDepth(void)
  2068. {
  2069. PyThreadState *tstate = _PyThreadState_GET();
  2070. return tstate->coroutine_origin_tracking_depth;
  2071. }
  2072. int
  2073. _PyEval_SetAsyncGenFirstiter(PyObject *firstiter)
  2074. {
  2075. PyThreadState *tstate = _PyThreadState_GET();
  2076. if (_PySys_Audit(tstate, "sys.set_asyncgen_hook_firstiter", NULL) < 0) {
  2077. return -1;
  2078. }
  2079. Py_XSETREF(tstate->async_gen_firstiter, Py_XNewRef(firstiter));
  2080. return 0;
  2081. }
  2082. PyObject *
  2083. _PyEval_GetAsyncGenFirstiter(void)
  2084. {
  2085. PyThreadState *tstate = _PyThreadState_GET();
  2086. return tstate->async_gen_firstiter;
  2087. }
  2088. int
  2089. _PyEval_SetAsyncGenFinalizer(PyObject *finalizer)
  2090. {
  2091. PyThreadState *tstate = _PyThreadState_GET();
  2092. if (_PySys_Audit(tstate, "sys.set_asyncgen_hook_finalizer", NULL) < 0) {
  2093. return -1;
  2094. }
  2095. Py_XSETREF(tstate->async_gen_finalizer, Py_XNewRef(finalizer));
  2096. return 0;
  2097. }
  2098. PyObject *
  2099. _PyEval_GetAsyncGenFinalizer(void)
  2100. {
  2101. PyThreadState *tstate = _PyThreadState_GET();
  2102. return tstate->async_gen_finalizer;
  2103. }
  2104. _PyInterpreterFrame *
  2105. _PyEval_GetFrame(void)
  2106. {
  2107. PyThreadState *tstate = _PyThreadState_GET();
  2108. return _PyThreadState_GetFrame(tstate);
  2109. }
  2110. PyFrameObject *
  2111. PyEval_GetFrame(void)
  2112. {
  2113. _PyInterpreterFrame *frame = _PyEval_GetFrame();
  2114. if (frame == NULL) {
  2115. return NULL;
  2116. }
  2117. PyFrameObject *f = _PyFrame_GetFrameObject(frame);
  2118. if (f == NULL) {
  2119. PyErr_Clear();
  2120. }
  2121. return f;
  2122. }
  2123. PyObject *
  2124. _PyEval_GetBuiltins(PyThreadState *tstate)
  2125. {
  2126. _PyInterpreterFrame *frame = _PyThreadState_GetFrame(tstate);
  2127. if (frame != NULL) {
  2128. return frame->f_builtins;
  2129. }
  2130. return tstate->interp->builtins;
  2131. }
  2132. PyObject *
  2133. PyEval_GetBuiltins(void)
  2134. {
  2135. PyThreadState *tstate = _PyThreadState_GET();
  2136. return _PyEval_GetBuiltins(tstate);
  2137. }
  2138. /* Convenience function to get a builtin from its name */
  2139. PyObject *
  2140. _PyEval_GetBuiltin(PyObject *name)
  2141. {
  2142. PyThreadState *tstate = _PyThreadState_GET();
  2143. PyObject *attr = PyObject_GetItem(PyEval_GetBuiltins(), name);
  2144. if (attr == NULL && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
  2145. _PyErr_SetObject(tstate, PyExc_AttributeError, name);
  2146. }
  2147. return attr;
  2148. }
  2149. PyObject *
  2150. _PyEval_GetBuiltinId(_Py_Identifier *name)
  2151. {
  2152. return _PyEval_GetBuiltin(_PyUnicode_FromId(name));
  2153. }
  2154. PyObject *
  2155. PyEval_GetLocals(void)
  2156. {
  2157. PyThreadState *tstate = _PyThreadState_GET();
  2158. _PyInterpreterFrame *current_frame = _PyThreadState_GetFrame(tstate);
  2159. if (current_frame == NULL) {
  2160. _PyErr_SetString(tstate, PyExc_SystemError, "frame does not exist");
  2161. return NULL;
  2162. }
  2163. if (_PyFrame_FastToLocalsWithError(current_frame) < 0) {
  2164. return NULL;
  2165. }
  2166. PyObject *locals = current_frame->f_locals;
  2167. assert(locals != NULL);
  2168. return locals;
  2169. }
  2170. PyObject *
  2171. _PyEval_GetFrameLocals(void)
  2172. {
  2173. PyThreadState *tstate = _PyThreadState_GET();
  2174. _PyInterpreterFrame *current_frame = _PyThreadState_GetFrame(tstate);
  2175. if (current_frame == NULL) {
  2176. _PyErr_SetString(tstate, PyExc_SystemError, "frame does not exist");
  2177. return NULL;
  2178. }
  2179. return _PyFrame_GetLocals(current_frame, 1);
  2180. }
  2181. PyObject *
  2182. PyEval_GetGlobals(void)
  2183. {
  2184. PyThreadState *tstate = _PyThreadState_GET();
  2185. _PyInterpreterFrame *current_frame = _PyThreadState_GetFrame(tstate);
  2186. if (current_frame == NULL) {
  2187. return NULL;
  2188. }
  2189. return current_frame->f_globals;
  2190. }
  2191. int
  2192. PyEval_MergeCompilerFlags(PyCompilerFlags *cf)
  2193. {
  2194. PyThreadState *tstate = _PyThreadState_GET();
  2195. _PyInterpreterFrame *current_frame = tstate->cframe->current_frame;
  2196. int result = cf->cf_flags != 0;
  2197. if (current_frame != NULL) {
  2198. const int codeflags = current_frame->f_code->co_flags;
  2199. const int compilerflags = codeflags & PyCF_MASK;
  2200. if (compilerflags) {
  2201. result = 1;
  2202. cf->cf_flags |= compilerflags;
  2203. }
  2204. }
  2205. return result;
  2206. }
  2207. const char *
  2208. PyEval_GetFuncName(PyObject *func)
  2209. {
  2210. if (PyMethod_Check(func))
  2211. return PyEval_GetFuncName(PyMethod_GET_FUNCTION(func));
  2212. else if (PyFunction_Check(func))
  2213. return PyUnicode_AsUTF8(((PyFunctionObject*)func)->func_name);
  2214. else if (PyCFunction_Check(func))
  2215. return ((PyCFunctionObject*)func)->m_ml->ml_name;
  2216. else
  2217. return Py_TYPE(func)->tp_name;
  2218. }
  2219. const char *
  2220. PyEval_GetFuncDesc(PyObject *func)
  2221. {
  2222. if (PyMethod_Check(func))
  2223. return "()";
  2224. else if (PyFunction_Check(func))
  2225. return "()";
  2226. else if (PyCFunction_Check(func))
  2227. return "()";
  2228. else
  2229. return " object";
  2230. }
  2231. /* Extract a slice index from a PyLong or an object with the
  2232. nb_index slot defined, and store in *pi.
  2233. Silently reduce values larger than PY_SSIZE_T_MAX to PY_SSIZE_T_MAX,
  2234. and silently boost values less than PY_SSIZE_T_MIN to PY_SSIZE_T_MIN.
  2235. Return 0 on error, 1 on success.
  2236. */
  2237. int
  2238. _PyEval_SliceIndex(PyObject *v, Py_ssize_t *pi)
  2239. {
  2240. PyThreadState *tstate = _PyThreadState_GET();
  2241. if (!Py_IsNone(v)) {
  2242. Py_ssize_t x;
  2243. if (_PyIndex_Check(v)) {
  2244. x = PyNumber_AsSsize_t(v, NULL);
  2245. if (x == -1 && _PyErr_Occurred(tstate))
  2246. return 0;
  2247. }
  2248. else {
  2249. _PyErr_SetString(tstate, PyExc_TypeError,
  2250. "slice indices must be integers or "
  2251. "None or have an __index__ method");
  2252. return 0;
  2253. }
  2254. *pi = x;
  2255. }
  2256. return 1;
  2257. }
  2258. int
  2259. _PyEval_SliceIndexNotNone(PyObject *v, Py_ssize_t *pi)
  2260. {
  2261. PyThreadState *tstate = _PyThreadState_GET();
  2262. Py_ssize_t x;
  2263. if (_PyIndex_Check(v)) {
  2264. x = PyNumber_AsSsize_t(v, NULL);
  2265. if (x == -1 && _PyErr_Occurred(tstate))
  2266. return 0;
  2267. }
  2268. else {
  2269. _PyErr_SetString(tstate, PyExc_TypeError,
  2270. "slice indices must be integers or "
  2271. "have an __index__ method");
  2272. return 0;
  2273. }
  2274. *pi = x;
  2275. return 1;
  2276. }
  2277. static PyObject *
  2278. import_name(PyThreadState *tstate, _PyInterpreterFrame *frame,
  2279. PyObject *name, PyObject *fromlist, PyObject *level)
  2280. {
  2281. PyObject *import_func, *res;
  2282. PyObject* stack[5];
  2283. import_func = PyObject_GetItem(frame->f_builtins, &_Py_ID(__import__));
  2284. if (import_func == NULL) {
  2285. if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
  2286. _PyErr_SetString(tstate, PyExc_ImportError, "__import__ not found");
  2287. }
  2288. return NULL;
  2289. }
  2290. PyObject *locals = frame->f_locals;
  2291. /* Fast path for not overloaded __import__. */
  2292. if (_PyImport_IsDefaultImportFunc(tstate->interp, import_func)) {
  2293. Py_DECREF(import_func);
  2294. int ilevel = _PyLong_AsInt(level);
  2295. if (ilevel == -1 && _PyErr_Occurred(tstate)) {
  2296. return NULL;
  2297. }
  2298. res = PyImport_ImportModuleLevelObject(
  2299. name,
  2300. frame->f_globals,
  2301. locals == NULL ? Py_None :locals,
  2302. fromlist,
  2303. ilevel);
  2304. return res;
  2305. }
  2306. stack[0] = name;
  2307. stack[1] = frame->f_globals;
  2308. stack[2] = locals == NULL ? Py_None : locals;
  2309. stack[3] = fromlist;
  2310. stack[4] = level;
  2311. res = _PyObject_FastCall(import_func, stack, 5);
  2312. Py_DECREF(import_func);
  2313. return res;
  2314. }
  2315. static PyObject *
  2316. import_from(PyThreadState *tstate, PyObject *v, PyObject *name)
  2317. {
  2318. PyObject *x;
  2319. PyObject *fullmodname, *pkgname, *pkgpath, *pkgname_or_unknown, *errmsg;
  2320. if (_PyObject_LookupAttr(v, name, &x) != 0) {
  2321. return x;
  2322. }
  2323. /* Issue #17636: in case this failed because of a circular relative
  2324. import, try to fallback on reading the module directly from
  2325. sys.modules. */
  2326. pkgname = PyObject_GetAttr(v, &_Py_ID(__name__));
  2327. if (pkgname == NULL) {
  2328. goto error;
  2329. }
  2330. if (!PyUnicode_Check(pkgname)) {
  2331. Py_CLEAR(pkgname);
  2332. goto error;
  2333. }
  2334. fullmodname = PyUnicode_FromFormat("%U.%U", pkgname, name);
  2335. if (fullmodname == NULL) {
  2336. Py_DECREF(pkgname);
  2337. return NULL;
  2338. }
  2339. x = PyImport_GetModule(fullmodname);
  2340. Py_DECREF(fullmodname);
  2341. if (x == NULL && !_PyErr_Occurred(tstate)) {
  2342. goto error;
  2343. }
  2344. Py_DECREF(pkgname);
  2345. return x;
  2346. error:
  2347. pkgpath = PyModule_GetFilenameObject(v);
  2348. if (pkgname == NULL) {
  2349. pkgname_or_unknown = PyUnicode_FromString("<unknown module name>");
  2350. if (pkgname_or_unknown == NULL) {
  2351. Py_XDECREF(pkgpath);
  2352. return NULL;
  2353. }
  2354. } else {
  2355. pkgname_or_unknown = pkgname;
  2356. }
  2357. if (pkgpath == NULL || !PyUnicode_Check(pkgpath)) {
  2358. _PyErr_Clear(tstate);
  2359. errmsg = PyUnicode_FromFormat(
  2360. "cannot import name %R from %R (unknown location)",
  2361. name, pkgname_or_unknown
  2362. );
  2363. /* NULL checks for errmsg and pkgname done by PyErr_SetImportError. */
  2364. _PyErr_SetImportErrorWithNameFrom(errmsg, pkgname, NULL, name);
  2365. }
  2366. else {
  2367. PyObject *spec = PyObject_GetAttr(v, &_Py_ID(__spec__));
  2368. const char *fmt =
  2369. _PyModuleSpec_IsInitializing(spec) ?
  2370. "cannot import name %R from partially initialized module %R "
  2371. "(most likely due to a circular import) (%S)" :
  2372. "cannot import name %R from %R (%S)";
  2373. Py_XDECREF(spec);
  2374. errmsg = PyUnicode_FromFormat(fmt, name, pkgname_or_unknown, pkgpath);
  2375. /* NULL checks for errmsg and pkgname done by PyErr_SetImportError. */
  2376. _PyErr_SetImportErrorWithNameFrom(errmsg, pkgname, pkgpath, name);
  2377. }
  2378. Py_XDECREF(errmsg);
  2379. Py_XDECREF(pkgname_or_unknown);
  2380. Py_XDECREF(pkgpath);
  2381. return NULL;
  2382. }
  2383. #define CANNOT_CATCH_MSG "catching classes that do not inherit from "\
  2384. "BaseException is not allowed"
  2385. #define CANNOT_EXCEPT_STAR_EG "catching ExceptionGroup with except* "\
  2386. "is not allowed. Use except instead."
  2387. static int
  2388. check_except_type_valid(PyThreadState *tstate, PyObject* right)
  2389. {
  2390. if (PyTuple_Check(right)) {
  2391. Py_ssize_t i, length;
  2392. length = PyTuple_GET_SIZE(right);
  2393. for (i = 0; i < length; i++) {
  2394. PyObject *exc = PyTuple_GET_ITEM(right, i);
  2395. if (!PyExceptionClass_Check(exc)) {
  2396. _PyErr_SetString(tstate, PyExc_TypeError,
  2397. CANNOT_CATCH_MSG);
  2398. return -1;
  2399. }
  2400. }
  2401. }
  2402. else {
  2403. if (!PyExceptionClass_Check(right)) {
  2404. _PyErr_SetString(tstate, PyExc_TypeError,
  2405. CANNOT_CATCH_MSG);
  2406. return -1;
  2407. }
  2408. }
  2409. return 0;
  2410. }
  2411. static int
  2412. check_except_star_type_valid(PyThreadState *tstate, PyObject* right)
  2413. {
  2414. if (check_except_type_valid(tstate, right) < 0) {
  2415. return -1;
  2416. }
  2417. /* reject except *ExceptionGroup */
  2418. int is_subclass = 0;
  2419. if (PyTuple_Check(right)) {
  2420. Py_ssize_t length = PyTuple_GET_SIZE(right);
  2421. for (Py_ssize_t i = 0; i < length; i++) {
  2422. PyObject *exc = PyTuple_GET_ITEM(right, i);
  2423. is_subclass = PyObject_IsSubclass(exc, PyExc_BaseExceptionGroup);
  2424. if (is_subclass < 0) {
  2425. return -1;
  2426. }
  2427. if (is_subclass) {
  2428. break;
  2429. }
  2430. }
  2431. }
  2432. else {
  2433. is_subclass = PyObject_IsSubclass(right, PyExc_BaseExceptionGroup);
  2434. if (is_subclass < 0) {
  2435. return -1;
  2436. }
  2437. }
  2438. if (is_subclass) {
  2439. _PyErr_SetString(tstate, PyExc_TypeError,
  2440. CANNOT_EXCEPT_STAR_EG);
  2441. return -1;
  2442. }
  2443. return 0;
  2444. }
  2445. static int
  2446. check_args_iterable(PyThreadState *tstate, PyObject *func, PyObject *args)
  2447. {
  2448. if (Py_TYPE(args)->tp_iter == NULL && !PySequence_Check(args)) {
  2449. /* check_args_iterable() may be called with a live exception:
  2450. * clear it to prevent calling _PyObject_FunctionStr() with an
  2451. * exception set. */
  2452. _PyErr_Clear(tstate);
  2453. PyObject *funcstr = _PyObject_FunctionStr(func);
  2454. if (funcstr != NULL) {
  2455. _PyErr_Format(tstate, PyExc_TypeError,
  2456. "%U argument after * must be an iterable, not %.200s",
  2457. funcstr, Py_TYPE(args)->tp_name);
  2458. Py_DECREF(funcstr);
  2459. }
  2460. return -1;
  2461. }
  2462. return 0;
  2463. }
  2464. static void
  2465. format_kwargs_error(PyThreadState *tstate, PyObject *func, PyObject *kwargs)
  2466. {
  2467. /* _PyDict_MergeEx raises attribute
  2468. * error (percolated from an attempt
  2469. * to get 'keys' attribute) instead of
  2470. * a type error if its second argument
  2471. * is not a mapping.
  2472. */
  2473. if (_PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
  2474. _PyErr_Clear(tstate);
  2475. PyObject *funcstr = _PyObject_FunctionStr(func);
  2476. if (funcstr != NULL) {
  2477. _PyErr_Format(
  2478. tstate, PyExc_TypeError,
  2479. "%U argument after ** must be a mapping, not %.200s",
  2480. funcstr, Py_TYPE(kwargs)->tp_name);
  2481. Py_DECREF(funcstr);
  2482. }
  2483. }
  2484. else if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
  2485. PyObject *exc = _PyErr_GetRaisedException(tstate);
  2486. PyObject *args = ((PyBaseExceptionObject *)exc)->args;
  2487. if (exc && PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1) {
  2488. _PyErr_Clear(tstate);
  2489. PyObject *funcstr = _PyObject_FunctionStr(func);
  2490. if (funcstr != NULL) {
  2491. PyObject *key = PyTuple_GET_ITEM(args, 0);
  2492. _PyErr_Format(
  2493. tstate, PyExc_TypeError,
  2494. "%U got multiple values for keyword argument '%S'",
  2495. funcstr, key);
  2496. Py_DECREF(funcstr);
  2497. }
  2498. Py_XDECREF(exc);
  2499. }
  2500. else {
  2501. _PyErr_SetRaisedException(tstate, exc);
  2502. }
  2503. }
  2504. }
  2505. static void
  2506. format_exc_check_arg(PyThreadState *tstate, PyObject *exc,
  2507. const char *format_str, PyObject *obj)
  2508. {
  2509. const char *obj_str;
  2510. if (!obj)
  2511. return;
  2512. obj_str = PyUnicode_AsUTF8(obj);
  2513. if (!obj_str)
  2514. return;
  2515. _PyErr_Format(tstate, exc, format_str, obj_str);
  2516. if (exc == PyExc_NameError) {
  2517. // Include the name in the NameError exceptions to offer suggestions later.
  2518. PyObject *exc = PyErr_GetRaisedException();
  2519. if (PyErr_GivenExceptionMatches(exc, PyExc_NameError)) {
  2520. if (((PyNameErrorObject*)exc)->name == NULL) {
  2521. // We do not care if this fails because we are going to restore the
  2522. // NameError anyway.
  2523. (void)PyObject_SetAttr(exc, &_Py_ID(name), obj);
  2524. }
  2525. }
  2526. PyErr_SetRaisedException(exc);
  2527. }
  2528. }
  2529. static void
  2530. format_exc_unbound(PyThreadState *tstate, PyCodeObject *co, int oparg)
  2531. {
  2532. PyObject *name;
  2533. /* Don't stomp existing exception */
  2534. if (_PyErr_Occurred(tstate))
  2535. return;
  2536. name = PyTuple_GET_ITEM(co->co_localsplusnames, oparg);
  2537. if (oparg < PyCode_GetFirstFree(co)) {
  2538. format_exc_check_arg(tstate, PyExc_UnboundLocalError,
  2539. UNBOUNDLOCAL_ERROR_MSG, name);
  2540. } else {
  2541. format_exc_check_arg(tstate, PyExc_NameError,
  2542. UNBOUNDFREE_ERROR_MSG, name);
  2543. }
  2544. }
  2545. static void
  2546. format_awaitable_error(PyThreadState *tstate, PyTypeObject *type, int oparg)
  2547. {
  2548. if (type->tp_as_async == NULL || type->tp_as_async->am_await == NULL) {
  2549. if (oparg == 1) {
  2550. _PyErr_Format(tstate, PyExc_TypeError,
  2551. "'async with' received an object from __aenter__ "
  2552. "that does not implement __await__: %.100s",
  2553. type->tp_name);
  2554. }
  2555. else if (oparg == 2) {
  2556. _PyErr_Format(tstate, PyExc_TypeError,
  2557. "'async with' received an object from __aexit__ "
  2558. "that does not implement __await__: %.100s",
  2559. type->tp_name);
  2560. }
  2561. }
  2562. }
  2563. Py_ssize_t
  2564. PyUnstable_Eval_RequestCodeExtraIndex(freefunc free)
  2565. {
  2566. PyInterpreterState *interp = _PyInterpreterState_GET();
  2567. Py_ssize_t new_index;
  2568. if (interp->co_extra_user_count == MAX_CO_EXTRA_USERS - 1) {
  2569. return -1;
  2570. }
  2571. new_index = interp->co_extra_user_count++;
  2572. interp->co_extra_freefuncs[new_index] = free;
  2573. return new_index;
  2574. }
  2575. /* Implement Py_EnterRecursiveCall() and Py_LeaveRecursiveCall() as functions
  2576. for the limited API. */
  2577. int Py_EnterRecursiveCall(const char *where)
  2578. {
  2579. return _Py_EnterRecursiveCall(where);
  2580. }
  2581. void Py_LeaveRecursiveCall(void)
  2582. {
  2583. _Py_LeaveRecursiveCall();
  2584. }