ceval.c 86 KB

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