codeobject.c 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429
  1. #include <stdbool.h>
  2. #include "Python.h"
  3. #include "opcode.h"
  4. #include "structmember.h" // PyMemberDef
  5. #include "pycore_code.h" // _PyCodeConstructor
  6. #include "pycore_frame.h" // FRAME_SPECIALS_SIZE
  7. #include "pycore_interp.h" // PyInterpreterState.co_extra_freefuncs
  8. #include "pycore_opcode.h" // _PyOpcode_Deopt
  9. #include "pycore_pystate.h" // _PyInterpreterState_GET()
  10. #include "pycore_tuple.h" // _PyTuple_ITEMS()
  11. #include "clinic/codeobject.c.h"
  12. static PyObject* code_repr(PyCodeObject *co);
  13. static const char *
  14. code_event_name(PyCodeEvent event) {
  15. switch (event) {
  16. #define CASE(op) \
  17. case PY_CODE_EVENT_##op: \
  18. return "PY_CODE_EVENT_" #op;
  19. PY_FOREACH_CODE_EVENT(CASE)
  20. #undef CASE
  21. }
  22. Py_UNREACHABLE();
  23. }
  24. static void
  25. notify_code_watchers(PyCodeEvent event, PyCodeObject *co)
  26. {
  27. assert(Py_REFCNT(co) > 0);
  28. PyInterpreterState *interp = _PyInterpreterState_GET();
  29. assert(interp->_initialized);
  30. uint8_t bits = interp->active_code_watchers;
  31. int i = 0;
  32. while (bits) {
  33. assert(i < CODE_MAX_WATCHERS);
  34. if (bits & 1) {
  35. PyCode_WatchCallback cb = interp->code_watchers[i];
  36. // callback must be non-null if the watcher bit is set
  37. assert(cb != NULL);
  38. if (cb(event, co) < 0) {
  39. // Don't risk resurrecting the object if an unraisablehook keeps
  40. // a reference; pass a string as context.
  41. PyObject *context = NULL;
  42. PyObject *repr = code_repr(co);
  43. if (repr) {
  44. context = PyUnicode_FromFormat(
  45. "%s watcher callback for %U",
  46. code_event_name(event), repr);
  47. Py_DECREF(repr);
  48. }
  49. if (context == NULL) {
  50. context = Py_NewRef(Py_None);
  51. }
  52. PyErr_WriteUnraisable(context);
  53. Py_DECREF(context);
  54. }
  55. }
  56. i++;
  57. bits >>= 1;
  58. }
  59. }
  60. int
  61. PyCode_AddWatcher(PyCode_WatchCallback callback)
  62. {
  63. PyInterpreterState *interp = _PyInterpreterState_GET();
  64. assert(interp->_initialized);
  65. for (int i = 0; i < CODE_MAX_WATCHERS; i++) {
  66. if (!interp->code_watchers[i]) {
  67. interp->code_watchers[i] = callback;
  68. interp->active_code_watchers |= (1 << i);
  69. return i;
  70. }
  71. }
  72. PyErr_SetString(PyExc_RuntimeError, "no more code watcher IDs available");
  73. return -1;
  74. }
  75. static inline int
  76. validate_watcher_id(PyInterpreterState *interp, int watcher_id)
  77. {
  78. if (watcher_id < 0 || watcher_id >= CODE_MAX_WATCHERS) {
  79. PyErr_Format(PyExc_ValueError, "Invalid code watcher ID %d", watcher_id);
  80. return -1;
  81. }
  82. if (!interp->code_watchers[watcher_id]) {
  83. PyErr_Format(PyExc_ValueError, "No code watcher set for ID %d", watcher_id);
  84. return -1;
  85. }
  86. return 0;
  87. }
  88. int
  89. PyCode_ClearWatcher(int watcher_id)
  90. {
  91. PyInterpreterState *interp = _PyInterpreterState_GET();
  92. assert(interp->_initialized);
  93. if (validate_watcher_id(interp, watcher_id) < 0) {
  94. return -1;
  95. }
  96. interp->code_watchers[watcher_id] = NULL;
  97. interp->active_code_watchers &= ~(1 << watcher_id);
  98. return 0;
  99. }
  100. /******************
  101. * generic helpers
  102. ******************/
  103. /* all_name_chars(s): true iff s matches [a-zA-Z0-9_]* */
  104. static int
  105. all_name_chars(PyObject *o)
  106. {
  107. const unsigned char *s, *e;
  108. if (!PyUnicode_IS_ASCII(o))
  109. return 0;
  110. s = PyUnicode_1BYTE_DATA(o);
  111. e = s + PyUnicode_GET_LENGTH(o);
  112. for (; s != e; s++) {
  113. if (!Py_ISALNUM(*s) && *s != '_')
  114. return 0;
  115. }
  116. return 1;
  117. }
  118. static int
  119. intern_strings(PyObject *tuple)
  120. {
  121. Py_ssize_t i;
  122. for (i = PyTuple_GET_SIZE(tuple); --i >= 0; ) {
  123. PyObject *v = PyTuple_GET_ITEM(tuple, i);
  124. if (v == NULL || !PyUnicode_CheckExact(v)) {
  125. PyErr_SetString(PyExc_SystemError,
  126. "non-string found in code slot");
  127. return -1;
  128. }
  129. PyUnicode_InternInPlace(&_PyTuple_ITEMS(tuple)[i]);
  130. }
  131. return 0;
  132. }
  133. /* Intern selected string constants */
  134. static int
  135. intern_string_constants(PyObject *tuple, int *modified)
  136. {
  137. for (Py_ssize_t i = PyTuple_GET_SIZE(tuple); --i >= 0; ) {
  138. PyObject *v = PyTuple_GET_ITEM(tuple, i);
  139. if (PyUnicode_CheckExact(v)) {
  140. if (PyUnicode_READY(v) == -1) {
  141. return -1;
  142. }
  143. if (all_name_chars(v)) {
  144. PyObject *w = v;
  145. PyUnicode_InternInPlace(&v);
  146. if (w != v) {
  147. PyTuple_SET_ITEM(tuple, i, v);
  148. if (modified) {
  149. *modified = 1;
  150. }
  151. }
  152. }
  153. }
  154. else if (PyTuple_CheckExact(v)) {
  155. if (intern_string_constants(v, NULL) < 0) {
  156. return -1;
  157. }
  158. }
  159. else if (PyFrozenSet_CheckExact(v)) {
  160. PyObject *w = v;
  161. PyObject *tmp = PySequence_Tuple(v);
  162. if (tmp == NULL) {
  163. return -1;
  164. }
  165. int tmp_modified = 0;
  166. if (intern_string_constants(tmp, &tmp_modified) < 0) {
  167. Py_DECREF(tmp);
  168. return -1;
  169. }
  170. if (tmp_modified) {
  171. v = PyFrozenSet_New(tmp);
  172. if (v == NULL) {
  173. Py_DECREF(tmp);
  174. return -1;
  175. }
  176. PyTuple_SET_ITEM(tuple, i, v);
  177. Py_DECREF(w);
  178. if (modified) {
  179. *modified = 1;
  180. }
  181. }
  182. Py_DECREF(tmp);
  183. }
  184. }
  185. return 0;
  186. }
  187. /* Return a shallow copy of a tuple that is
  188. guaranteed to contain exact strings, by converting string subclasses
  189. to exact strings and complaining if a non-string is found. */
  190. static PyObject*
  191. validate_and_copy_tuple(PyObject *tup)
  192. {
  193. PyObject *newtuple;
  194. PyObject *item;
  195. Py_ssize_t i, len;
  196. len = PyTuple_GET_SIZE(tup);
  197. newtuple = PyTuple_New(len);
  198. if (newtuple == NULL)
  199. return NULL;
  200. for (i = 0; i < len; i++) {
  201. item = PyTuple_GET_ITEM(tup, i);
  202. if (PyUnicode_CheckExact(item)) {
  203. Py_INCREF(item);
  204. }
  205. else if (!PyUnicode_Check(item)) {
  206. PyErr_Format(
  207. PyExc_TypeError,
  208. "name tuples must contain only "
  209. "strings, not '%.500s'",
  210. Py_TYPE(item)->tp_name);
  211. Py_DECREF(newtuple);
  212. return NULL;
  213. }
  214. else {
  215. item = _PyUnicode_Copy(item);
  216. if (item == NULL) {
  217. Py_DECREF(newtuple);
  218. return NULL;
  219. }
  220. }
  221. PyTuple_SET_ITEM(newtuple, i, item);
  222. }
  223. return newtuple;
  224. }
  225. static int
  226. init_co_cached(PyCodeObject *self) {
  227. if (self->_co_cached == NULL) {
  228. self->_co_cached = PyMem_New(_PyCoCached, 1);
  229. if (self->_co_cached == NULL) {
  230. PyErr_NoMemory();
  231. return -1;
  232. }
  233. self->_co_cached->_co_code = NULL;
  234. self->_co_cached->_co_cellvars = NULL;
  235. self->_co_cached->_co_freevars = NULL;
  236. self->_co_cached->_co_varnames = NULL;
  237. }
  238. return 0;
  239. }
  240. /******************
  241. * _PyCode_New()
  242. ******************/
  243. // This is also used in compile.c.
  244. void
  245. _Py_set_localsplus_info(int offset, PyObject *name, _PyLocals_Kind kind,
  246. PyObject *names, PyObject *kinds)
  247. {
  248. PyTuple_SET_ITEM(names, offset, Py_NewRef(name));
  249. _PyLocals_SetKind(kinds, offset, kind);
  250. }
  251. static void
  252. get_localsplus_counts(PyObject *names, PyObject *kinds,
  253. int *pnlocals, int *pncellvars,
  254. int *pnfreevars)
  255. {
  256. int nlocals = 0;
  257. int ncellvars = 0;
  258. int nfreevars = 0;
  259. Py_ssize_t nlocalsplus = PyTuple_GET_SIZE(names);
  260. for (int i = 0; i < nlocalsplus; i++) {
  261. _PyLocals_Kind kind = _PyLocals_GetKind(kinds, i);
  262. if (kind & CO_FAST_LOCAL) {
  263. nlocals += 1;
  264. if (kind & CO_FAST_CELL) {
  265. ncellvars += 1;
  266. }
  267. }
  268. else if (kind & CO_FAST_CELL) {
  269. ncellvars += 1;
  270. }
  271. else if (kind & CO_FAST_FREE) {
  272. nfreevars += 1;
  273. }
  274. }
  275. if (pnlocals != NULL) {
  276. *pnlocals = nlocals;
  277. }
  278. if (pncellvars != NULL) {
  279. *pncellvars = ncellvars;
  280. }
  281. if (pnfreevars != NULL) {
  282. *pnfreevars = nfreevars;
  283. }
  284. }
  285. static PyObject *
  286. get_localsplus_names(PyCodeObject *co, _PyLocals_Kind kind, int num)
  287. {
  288. PyObject *names = PyTuple_New(num);
  289. if (names == NULL) {
  290. return NULL;
  291. }
  292. int index = 0;
  293. for (int offset = 0; offset < co->co_nlocalsplus; offset++) {
  294. _PyLocals_Kind k = _PyLocals_GetKind(co->co_localspluskinds, offset);
  295. if ((k & kind) == 0) {
  296. continue;
  297. }
  298. assert(index < num);
  299. PyObject *name = PyTuple_GET_ITEM(co->co_localsplusnames, offset);
  300. PyTuple_SET_ITEM(names, index, Py_NewRef(name));
  301. index += 1;
  302. }
  303. assert(index == num);
  304. return names;
  305. }
  306. int
  307. _PyCode_Validate(struct _PyCodeConstructor *con)
  308. {
  309. /* Check argument types */
  310. if (con->argcount < con->posonlyargcount || con->posonlyargcount < 0 ||
  311. con->kwonlyargcount < 0 ||
  312. con->stacksize < 0 || con->flags < 0 ||
  313. con->code == NULL || !PyBytes_Check(con->code) ||
  314. con->consts == NULL || !PyTuple_Check(con->consts) ||
  315. con->names == NULL || !PyTuple_Check(con->names) ||
  316. con->localsplusnames == NULL || !PyTuple_Check(con->localsplusnames) ||
  317. con->localspluskinds == NULL || !PyBytes_Check(con->localspluskinds) ||
  318. PyTuple_GET_SIZE(con->localsplusnames)
  319. != PyBytes_GET_SIZE(con->localspluskinds) ||
  320. con->name == NULL || !PyUnicode_Check(con->name) ||
  321. con->qualname == NULL || !PyUnicode_Check(con->qualname) ||
  322. con->filename == NULL || !PyUnicode_Check(con->filename) ||
  323. con->linetable == NULL || !PyBytes_Check(con->linetable) ||
  324. con->exceptiontable == NULL || !PyBytes_Check(con->exceptiontable)
  325. ) {
  326. PyErr_BadInternalCall();
  327. return -1;
  328. }
  329. /* Make sure that code is indexable with an int, this is
  330. a long running assumption in ceval.c and many parts of
  331. the interpreter. */
  332. if (PyBytes_GET_SIZE(con->code) > INT_MAX) {
  333. PyErr_SetString(PyExc_OverflowError,
  334. "code: co_code larger than INT_MAX");
  335. return -1;
  336. }
  337. if (PyBytes_GET_SIZE(con->code) % sizeof(_Py_CODEUNIT) != 0 ||
  338. !_Py_IS_ALIGNED(PyBytes_AS_STRING(con->code), sizeof(_Py_CODEUNIT))
  339. ) {
  340. PyErr_SetString(PyExc_ValueError, "code: co_code is malformed");
  341. return -1;
  342. }
  343. /* Ensure that the co_varnames has enough names to cover the arg counts.
  344. * Note that totalargs = nlocals - nplainlocals. We check nplainlocals
  345. * here to avoid the possibility of overflow (however remote). */
  346. int nlocals;
  347. get_localsplus_counts(con->localsplusnames, con->localspluskinds,
  348. &nlocals, NULL, NULL);
  349. int nplainlocals = nlocals -
  350. con->argcount -
  351. con->kwonlyargcount -
  352. ((con->flags & CO_VARARGS) != 0) -
  353. ((con->flags & CO_VARKEYWORDS) != 0);
  354. if (nplainlocals < 0) {
  355. PyErr_SetString(PyExc_ValueError, "code: co_varnames is too small");
  356. return -1;
  357. }
  358. return 0;
  359. }
  360. extern void _PyCode_Quicken(PyCodeObject *code);
  361. static void
  362. init_code(PyCodeObject *co, struct _PyCodeConstructor *con)
  363. {
  364. int nlocalsplus = (int)PyTuple_GET_SIZE(con->localsplusnames);
  365. int nlocals, ncellvars, nfreevars;
  366. get_localsplus_counts(con->localsplusnames, con->localspluskinds,
  367. &nlocals, &ncellvars, &nfreevars);
  368. co->co_filename = Py_NewRef(con->filename);
  369. co->co_name = Py_NewRef(con->name);
  370. co->co_qualname = Py_NewRef(con->qualname);
  371. co->co_flags = con->flags;
  372. co->co_firstlineno = con->firstlineno;
  373. co->co_linetable = Py_NewRef(con->linetable);
  374. co->co_consts = Py_NewRef(con->consts);
  375. co->co_names = Py_NewRef(con->names);
  376. co->co_localsplusnames = Py_NewRef(con->localsplusnames);
  377. co->co_localspluskinds = Py_NewRef(con->localspluskinds);
  378. co->co_argcount = con->argcount;
  379. co->co_posonlyargcount = con->posonlyargcount;
  380. co->co_kwonlyargcount = con->kwonlyargcount;
  381. co->co_stacksize = con->stacksize;
  382. co->co_exceptiontable = Py_NewRef(con->exceptiontable);
  383. /* derived values */
  384. co->co_nlocalsplus = nlocalsplus;
  385. co->co_nlocals = nlocals;
  386. co->co_framesize = nlocalsplus + con->stacksize + FRAME_SPECIALS_SIZE;
  387. co->co_ncellvars = ncellvars;
  388. co->co_nfreevars = nfreevars;
  389. co->co_version = _Py_next_func_version;
  390. if (_Py_next_func_version != 0) {
  391. _Py_next_func_version++;
  392. }
  393. co->_co_monitoring = NULL;
  394. co->_co_instrumentation_version = 0;
  395. /* not set */
  396. co->co_weakreflist = NULL;
  397. co->co_extra = NULL;
  398. co->_co_cached = NULL;
  399. memcpy(_PyCode_CODE(co), PyBytes_AS_STRING(con->code),
  400. PyBytes_GET_SIZE(con->code));
  401. int entry_point = 0;
  402. while (entry_point < Py_SIZE(co) &&
  403. _PyCode_CODE(co)[entry_point].op.code != RESUME) {
  404. entry_point++;
  405. }
  406. co->_co_firsttraceable = entry_point;
  407. _PyCode_Quicken(co);
  408. notify_code_watchers(PY_CODE_EVENT_CREATE, co);
  409. }
  410. static int
  411. scan_varint(const uint8_t *ptr)
  412. {
  413. unsigned int read = *ptr++;
  414. unsigned int val = read & 63;
  415. unsigned int shift = 0;
  416. while (read & 64) {
  417. read = *ptr++;
  418. shift += 6;
  419. val |= (read & 63) << shift;
  420. }
  421. return val;
  422. }
  423. static int
  424. scan_signed_varint(const uint8_t *ptr)
  425. {
  426. unsigned int uval = scan_varint(ptr);
  427. if (uval & 1) {
  428. return -(int)(uval >> 1);
  429. }
  430. else {
  431. return uval >> 1;
  432. }
  433. }
  434. static int
  435. get_line_delta(const uint8_t *ptr)
  436. {
  437. int code = ((*ptr) >> 3) & 15;
  438. switch (code) {
  439. case PY_CODE_LOCATION_INFO_NONE:
  440. return 0;
  441. case PY_CODE_LOCATION_INFO_NO_COLUMNS:
  442. case PY_CODE_LOCATION_INFO_LONG:
  443. return scan_signed_varint(ptr+1);
  444. case PY_CODE_LOCATION_INFO_ONE_LINE0:
  445. return 0;
  446. case PY_CODE_LOCATION_INFO_ONE_LINE1:
  447. return 1;
  448. case PY_CODE_LOCATION_INFO_ONE_LINE2:
  449. return 2;
  450. default:
  451. /* Same line */
  452. return 0;
  453. }
  454. }
  455. static PyObject *
  456. remove_column_info(PyObject *locations)
  457. {
  458. int offset = 0;
  459. const uint8_t *data = (const uint8_t *)PyBytes_AS_STRING(locations);
  460. PyObject *res = PyBytes_FromStringAndSize(NULL, 32);
  461. if (res == NULL) {
  462. PyErr_NoMemory();
  463. return NULL;
  464. }
  465. uint8_t *output = (uint8_t *)PyBytes_AS_STRING(res);
  466. while (offset < PyBytes_GET_SIZE(locations)) {
  467. Py_ssize_t write_offset = output - (uint8_t *)PyBytes_AS_STRING(res);
  468. if (write_offset + 16 >= PyBytes_GET_SIZE(res)) {
  469. if (_PyBytes_Resize(&res, PyBytes_GET_SIZE(res) * 2) < 0) {
  470. return NULL;
  471. }
  472. output = (uint8_t *)PyBytes_AS_STRING(res) + write_offset;
  473. }
  474. int code = (data[offset] >> 3) & 15;
  475. if (code == PY_CODE_LOCATION_INFO_NONE) {
  476. *output++ = data[offset];
  477. }
  478. else {
  479. int blength = (data[offset] & 7)+1;
  480. output += write_location_entry_start(
  481. output, PY_CODE_LOCATION_INFO_NO_COLUMNS, blength);
  482. int ldelta = get_line_delta(&data[offset]);
  483. output += write_signed_varint(output, ldelta);
  484. }
  485. offset++;
  486. while (offset < PyBytes_GET_SIZE(locations) &&
  487. (data[offset] & 128) == 0) {
  488. offset++;
  489. }
  490. }
  491. Py_ssize_t write_offset = output - (uint8_t *)PyBytes_AS_STRING(res);
  492. if (_PyBytes_Resize(&res, write_offset)) {
  493. return NULL;
  494. }
  495. return res;
  496. }
  497. /* The caller is responsible for ensuring that the given data is valid. */
  498. PyCodeObject *
  499. _PyCode_New(struct _PyCodeConstructor *con)
  500. {
  501. /* Ensure that strings are ready Unicode string */
  502. if (PyUnicode_READY(con->name) < 0) {
  503. return NULL;
  504. }
  505. if (PyUnicode_READY(con->qualname) < 0) {
  506. return NULL;
  507. }
  508. if (PyUnicode_READY(con->filename) < 0) {
  509. return NULL;
  510. }
  511. if (intern_strings(con->names) < 0) {
  512. return NULL;
  513. }
  514. if (intern_string_constants(con->consts, NULL) < 0) {
  515. return NULL;
  516. }
  517. if (intern_strings(con->localsplusnames) < 0) {
  518. return NULL;
  519. }
  520. PyObject *replacement_locations = NULL;
  521. // Compact the linetable if we are opted out of debug
  522. // ranges.
  523. if (!_Py_GetConfig()->code_debug_ranges) {
  524. replacement_locations = remove_column_info(con->linetable);
  525. if (replacement_locations == NULL) {
  526. return NULL;
  527. }
  528. con->linetable = replacement_locations;
  529. }
  530. Py_ssize_t size = PyBytes_GET_SIZE(con->code) / sizeof(_Py_CODEUNIT);
  531. PyCodeObject *co = PyObject_NewVar(PyCodeObject, &PyCode_Type, size);
  532. if (co == NULL) {
  533. Py_XDECREF(replacement_locations);
  534. PyErr_NoMemory();
  535. return NULL;
  536. }
  537. init_code(co, con);
  538. Py_XDECREF(replacement_locations);
  539. return co;
  540. }
  541. /******************
  542. * the legacy "constructors"
  543. ******************/
  544. PyCodeObject *
  545. PyUnstable_Code_NewWithPosOnlyArgs(
  546. int argcount, int posonlyargcount, int kwonlyargcount,
  547. int nlocals, int stacksize, int flags,
  548. PyObject *code, PyObject *consts, PyObject *names,
  549. PyObject *varnames, PyObject *freevars, PyObject *cellvars,
  550. PyObject *filename, PyObject *name,
  551. PyObject *qualname, int firstlineno,
  552. PyObject *linetable,
  553. PyObject *exceptiontable)
  554. {
  555. PyCodeObject *co = NULL;
  556. PyObject *localsplusnames = NULL;
  557. PyObject *localspluskinds = NULL;
  558. if (varnames == NULL || !PyTuple_Check(varnames) ||
  559. cellvars == NULL || !PyTuple_Check(cellvars) ||
  560. freevars == NULL || !PyTuple_Check(freevars)
  561. ) {
  562. PyErr_BadInternalCall();
  563. return NULL;
  564. }
  565. // Set the "fast locals plus" info.
  566. int nvarnames = (int)PyTuple_GET_SIZE(varnames);
  567. int ncellvars = (int)PyTuple_GET_SIZE(cellvars);
  568. int nfreevars = (int)PyTuple_GET_SIZE(freevars);
  569. int nlocalsplus = nvarnames + ncellvars + nfreevars;
  570. localsplusnames = PyTuple_New(nlocalsplus);
  571. if (localsplusnames == NULL) {
  572. goto error;
  573. }
  574. localspluskinds = PyBytes_FromStringAndSize(NULL, nlocalsplus);
  575. if (localspluskinds == NULL) {
  576. goto error;
  577. }
  578. int offset = 0;
  579. for (int i = 0; i < nvarnames; i++, offset++) {
  580. PyObject *name = PyTuple_GET_ITEM(varnames, i);
  581. _Py_set_localsplus_info(offset, name, CO_FAST_LOCAL,
  582. localsplusnames, localspluskinds);
  583. }
  584. for (int i = 0; i < ncellvars; i++, offset++) {
  585. PyObject *name = PyTuple_GET_ITEM(cellvars, i);
  586. int argoffset = -1;
  587. for (int j = 0; j < nvarnames; j++) {
  588. int cmp = PyUnicode_Compare(PyTuple_GET_ITEM(varnames, j),
  589. name);
  590. assert(!PyErr_Occurred());
  591. if (cmp == 0) {
  592. argoffset = j;
  593. break;
  594. }
  595. }
  596. if (argoffset >= 0) {
  597. // Merge the localsplus indices.
  598. nlocalsplus -= 1;
  599. offset -= 1;
  600. _PyLocals_Kind kind = _PyLocals_GetKind(localspluskinds, argoffset);
  601. _PyLocals_SetKind(localspluskinds, argoffset, kind | CO_FAST_CELL);
  602. continue;
  603. }
  604. _Py_set_localsplus_info(offset, name, CO_FAST_CELL,
  605. localsplusnames, localspluskinds);
  606. }
  607. for (int i = 0; i < nfreevars; i++, offset++) {
  608. PyObject *name = PyTuple_GET_ITEM(freevars, i);
  609. _Py_set_localsplus_info(offset, name, CO_FAST_FREE,
  610. localsplusnames, localspluskinds);
  611. }
  612. // gh-110543: Make sure the CO_FAST_HIDDEN flag is set correctly.
  613. if (!(flags & CO_OPTIMIZED)) {
  614. Py_ssize_t code_len = PyBytes_GET_SIZE(code);
  615. _Py_CODEUNIT *code_data = (_Py_CODEUNIT *)PyBytes_AS_STRING(code);
  616. Py_ssize_t num_code_units = code_len / sizeof(_Py_CODEUNIT);
  617. int extended_arg = 0;
  618. for (int i = 0; i < num_code_units; i += 1 + _PyOpcode_Caches[code_data[i].op.code]) {
  619. _Py_CODEUNIT *instr = &code_data[i];
  620. uint8_t opcode = instr->op.code;
  621. if (opcode == EXTENDED_ARG) {
  622. extended_arg = extended_arg << 8 | instr->op.arg;
  623. continue;
  624. }
  625. if (opcode == LOAD_FAST_AND_CLEAR) {
  626. int oparg = extended_arg << 8 | instr->op.arg;
  627. if (oparg >= nlocalsplus) {
  628. PyErr_Format(PyExc_ValueError,
  629. "code: LOAD_FAST_AND_CLEAR oparg %d out of range",
  630. oparg);
  631. goto error;
  632. }
  633. _PyLocals_Kind kind = _PyLocals_GetKind(localspluskinds, oparg);
  634. _PyLocals_SetKind(localspluskinds, oparg, kind | CO_FAST_HIDDEN);
  635. }
  636. extended_arg = 0;
  637. }
  638. }
  639. // If any cells were args then nlocalsplus will have shrunk.
  640. if (nlocalsplus != PyTuple_GET_SIZE(localsplusnames)) {
  641. if (_PyTuple_Resize(&localsplusnames, nlocalsplus) < 0
  642. || _PyBytes_Resize(&localspluskinds, nlocalsplus) < 0) {
  643. goto error;
  644. }
  645. }
  646. struct _PyCodeConstructor con = {
  647. .filename = filename,
  648. .name = name,
  649. .qualname = qualname,
  650. .flags = flags,
  651. .code = code,
  652. .firstlineno = firstlineno,
  653. .linetable = linetable,
  654. .consts = consts,
  655. .names = names,
  656. .localsplusnames = localsplusnames,
  657. .localspluskinds = localspluskinds,
  658. .argcount = argcount,
  659. .posonlyargcount = posonlyargcount,
  660. .kwonlyargcount = kwonlyargcount,
  661. .stacksize = stacksize,
  662. .exceptiontable = exceptiontable,
  663. };
  664. if (_PyCode_Validate(&con) < 0) {
  665. goto error;
  666. }
  667. assert(PyBytes_GET_SIZE(code) % sizeof(_Py_CODEUNIT) == 0);
  668. assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(code), sizeof(_Py_CODEUNIT)));
  669. if (nlocals != PyTuple_GET_SIZE(varnames)) {
  670. PyErr_SetString(PyExc_ValueError,
  671. "code: co_nlocals != len(co_varnames)");
  672. goto error;
  673. }
  674. co = _PyCode_New(&con);
  675. if (co == NULL) {
  676. goto error;
  677. }
  678. error:
  679. Py_XDECREF(localsplusnames);
  680. Py_XDECREF(localspluskinds);
  681. return co;
  682. }
  683. PyCodeObject *
  684. PyUnstable_Code_New(int argcount, int kwonlyargcount,
  685. int nlocals, int stacksize, int flags,
  686. PyObject *code, PyObject *consts, PyObject *names,
  687. PyObject *varnames, PyObject *freevars, PyObject *cellvars,
  688. PyObject *filename, PyObject *name, PyObject *qualname,
  689. int firstlineno,
  690. PyObject *linetable,
  691. PyObject *exceptiontable)
  692. {
  693. return PyCode_NewWithPosOnlyArgs(argcount, 0, kwonlyargcount, nlocals,
  694. stacksize, flags, code, consts, names,
  695. varnames, freevars, cellvars, filename,
  696. name, qualname, firstlineno,
  697. linetable,
  698. exceptiontable);
  699. }
  700. // NOTE: When modifying the construction of PyCode_NewEmpty, please also change
  701. // test.test_code.CodeLocationTest.test_code_new_empty to keep it in sync!
  702. static const uint8_t assert0[6] = {
  703. RESUME, 0,
  704. LOAD_ASSERTION_ERROR, 0,
  705. RAISE_VARARGS, 1
  706. };
  707. static const uint8_t linetable[2] = {
  708. (1 << 7) // New entry.
  709. | (PY_CODE_LOCATION_INFO_NO_COLUMNS << 3)
  710. | (3 - 1), // Three code units.
  711. 0, // Offset from co_firstlineno.
  712. };
  713. PyCodeObject *
  714. PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno)
  715. {
  716. PyObject *nulltuple = NULL;
  717. PyObject *filename_ob = NULL;
  718. PyObject *funcname_ob = NULL;
  719. PyObject *code_ob = NULL;
  720. PyObject *linetable_ob = NULL;
  721. PyCodeObject *result = NULL;
  722. nulltuple = PyTuple_New(0);
  723. if (nulltuple == NULL) {
  724. goto failed;
  725. }
  726. funcname_ob = PyUnicode_FromString(funcname);
  727. if (funcname_ob == NULL) {
  728. goto failed;
  729. }
  730. filename_ob = PyUnicode_DecodeFSDefault(filename);
  731. if (filename_ob == NULL) {
  732. goto failed;
  733. }
  734. code_ob = PyBytes_FromStringAndSize((const char *)assert0, 6);
  735. if (code_ob == NULL) {
  736. goto failed;
  737. }
  738. linetable_ob = PyBytes_FromStringAndSize((const char *)linetable, 2);
  739. if (linetable_ob == NULL) {
  740. goto failed;
  741. }
  742. #define emptystring (PyObject *)&_Py_SINGLETON(bytes_empty)
  743. struct _PyCodeConstructor con = {
  744. .filename = filename_ob,
  745. .name = funcname_ob,
  746. .qualname = funcname_ob,
  747. .code = code_ob,
  748. .firstlineno = firstlineno,
  749. .linetable = linetable_ob,
  750. .consts = nulltuple,
  751. .names = nulltuple,
  752. .localsplusnames = nulltuple,
  753. .localspluskinds = emptystring,
  754. .exceptiontable = emptystring,
  755. .stacksize = 1,
  756. };
  757. result = _PyCode_New(&con);
  758. failed:
  759. Py_XDECREF(nulltuple);
  760. Py_XDECREF(funcname_ob);
  761. Py_XDECREF(filename_ob);
  762. Py_XDECREF(code_ob);
  763. Py_XDECREF(linetable_ob);
  764. return result;
  765. }
  766. /******************
  767. * source location tracking (co_lines/co_positions)
  768. ******************/
  769. int
  770. PyCode_Addr2Line(PyCodeObject *co, int addrq)
  771. {
  772. if (addrq < 0) {
  773. return co->co_firstlineno;
  774. }
  775. assert(addrq >= 0 && addrq <= _PyCode_NBYTES(co));
  776. PyCodeAddressRange bounds;
  777. _PyCode_InitAddressRange(co, &bounds);
  778. return _PyCode_CheckLineNumber(addrq, &bounds);
  779. }
  780. void
  781. _PyLineTable_InitAddressRange(const char *linetable, Py_ssize_t length, int firstlineno, PyCodeAddressRange *range)
  782. {
  783. range->opaque.lo_next = (const uint8_t *)linetable;
  784. range->opaque.limit = range->opaque.lo_next + length;
  785. range->ar_start = -1;
  786. range->ar_end = 0;
  787. range->opaque.computed_line = firstlineno;
  788. range->ar_line = -1;
  789. }
  790. int
  791. _PyCode_InitAddressRange(PyCodeObject* co, PyCodeAddressRange *bounds)
  792. {
  793. assert(co->co_linetable != NULL);
  794. const char *linetable = PyBytes_AS_STRING(co->co_linetable);
  795. Py_ssize_t length = PyBytes_GET_SIZE(co->co_linetable);
  796. _PyLineTable_InitAddressRange(linetable, length, co->co_firstlineno, bounds);
  797. return bounds->ar_line;
  798. }
  799. /* Update *bounds to describe the first and one-past-the-last instructions in
  800. the same line as lasti. Return the number of that line, or -1 if lasti is out of bounds. */
  801. int
  802. _PyCode_CheckLineNumber(int lasti, PyCodeAddressRange *bounds)
  803. {
  804. while (bounds->ar_end <= lasti) {
  805. if (!_PyLineTable_NextAddressRange(bounds)) {
  806. return -1;
  807. }
  808. }
  809. while (bounds->ar_start > lasti) {
  810. if (!_PyLineTable_PreviousAddressRange(bounds)) {
  811. return -1;
  812. }
  813. }
  814. return bounds->ar_line;
  815. }
  816. static int
  817. is_no_line_marker(uint8_t b)
  818. {
  819. return (b >> 3) == 0x1f;
  820. }
  821. #define ASSERT_VALID_BOUNDS(bounds) \
  822. assert(bounds->opaque.lo_next <= bounds->opaque.limit && \
  823. (bounds->ar_line == -1 || bounds->ar_line == bounds->opaque.computed_line) && \
  824. (bounds->opaque.lo_next == bounds->opaque.limit || \
  825. (*bounds->opaque.lo_next) & 128))
  826. static int
  827. next_code_delta(PyCodeAddressRange *bounds)
  828. {
  829. assert((*bounds->opaque.lo_next) & 128);
  830. return (((*bounds->opaque.lo_next) & 7) + 1) * sizeof(_Py_CODEUNIT);
  831. }
  832. static int
  833. previous_code_delta(PyCodeAddressRange *bounds)
  834. {
  835. if (bounds->ar_start == 0) {
  836. // If we looking at the first entry, the
  837. // "previous" entry has an implicit length of 1.
  838. return 1;
  839. }
  840. const uint8_t *ptr = bounds->opaque.lo_next-1;
  841. while (((*ptr) & 128) == 0) {
  842. ptr--;
  843. }
  844. return (((*ptr) & 7) + 1) * sizeof(_Py_CODEUNIT);
  845. }
  846. static int
  847. read_byte(PyCodeAddressRange *bounds)
  848. {
  849. return *bounds->opaque.lo_next++;
  850. }
  851. static int
  852. read_varint(PyCodeAddressRange *bounds)
  853. {
  854. unsigned int read = read_byte(bounds);
  855. unsigned int val = read & 63;
  856. unsigned int shift = 0;
  857. while (read & 64) {
  858. read = read_byte(bounds);
  859. shift += 6;
  860. val |= (read & 63) << shift;
  861. }
  862. return val;
  863. }
  864. static int
  865. read_signed_varint(PyCodeAddressRange *bounds)
  866. {
  867. unsigned int uval = read_varint(bounds);
  868. if (uval & 1) {
  869. return -(int)(uval >> 1);
  870. }
  871. else {
  872. return uval >> 1;
  873. }
  874. }
  875. static void
  876. retreat(PyCodeAddressRange *bounds)
  877. {
  878. ASSERT_VALID_BOUNDS(bounds);
  879. assert(bounds->ar_start >= 0);
  880. do {
  881. bounds->opaque.lo_next--;
  882. } while (((*bounds->opaque.lo_next) & 128) == 0);
  883. bounds->opaque.computed_line -= get_line_delta(bounds->opaque.lo_next);
  884. bounds->ar_end = bounds->ar_start;
  885. bounds->ar_start -= previous_code_delta(bounds);
  886. if (is_no_line_marker(bounds->opaque.lo_next[-1])) {
  887. bounds->ar_line = -1;
  888. }
  889. else {
  890. bounds->ar_line = bounds->opaque.computed_line;
  891. }
  892. ASSERT_VALID_BOUNDS(bounds);
  893. }
  894. static void
  895. advance(PyCodeAddressRange *bounds)
  896. {
  897. ASSERT_VALID_BOUNDS(bounds);
  898. bounds->opaque.computed_line += get_line_delta(bounds->opaque.lo_next);
  899. if (is_no_line_marker(*bounds->opaque.lo_next)) {
  900. bounds->ar_line = -1;
  901. }
  902. else {
  903. bounds->ar_line = bounds->opaque.computed_line;
  904. }
  905. bounds->ar_start = bounds->ar_end;
  906. bounds->ar_end += next_code_delta(bounds);
  907. do {
  908. bounds->opaque.lo_next++;
  909. } while (bounds->opaque.lo_next < bounds->opaque.limit &&
  910. ((*bounds->opaque.lo_next) & 128) == 0);
  911. ASSERT_VALID_BOUNDS(bounds);
  912. }
  913. static void
  914. advance_with_locations(PyCodeAddressRange *bounds, int *endline, int *column, int *endcolumn)
  915. {
  916. ASSERT_VALID_BOUNDS(bounds);
  917. int first_byte = read_byte(bounds);
  918. int code = (first_byte >> 3) & 15;
  919. bounds->ar_start = bounds->ar_end;
  920. bounds->ar_end = bounds->ar_start + ((first_byte & 7) + 1) * sizeof(_Py_CODEUNIT);
  921. switch(code) {
  922. case PY_CODE_LOCATION_INFO_NONE:
  923. bounds->ar_line = *endline = -1;
  924. *column = *endcolumn = -1;
  925. break;
  926. case PY_CODE_LOCATION_INFO_LONG:
  927. {
  928. bounds->opaque.computed_line += read_signed_varint(bounds);
  929. bounds->ar_line = bounds->opaque.computed_line;
  930. *endline = bounds->ar_line + read_varint(bounds);
  931. *column = read_varint(bounds)-1;
  932. *endcolumn = read_varint(bounds)-1;
  933. break;
  934. }
  935. case PY_CODE_LOCATION_INFO_NO_COLUMNS:
  936. {
  937. /* No column */
  938. bounds->opaque.computed_line += read_signed_varint(bounds);
  939. *endline = bounds->ar_line = bounds->opaque.computed_line;
  940. *column = *endcolumn = -1;
  941. break;
  942. }
  943. case PY_CODE_LOCATION_INFO_ONE_LINE0:
  944. case PY_CODE_LOCATION_INFO_ONE_LINE1:
  945. case PY_CODE_LOCATION_INFO_ONE_LINE2:
  946. {
  947. /* one line form */
  948. int line_delta = code - 10;
  949. bounds->opaque.computed_line += line_delta;
  950. *endline = bounds->ar_line = bounds->opaque.computed_line;
  951. *column = read_byte(bounds);
  952. *endcolumn = read_byte(bounds);
  953. break;
  954. }
  955. default:
  956. {
  957. /* Short forms */
  958. int second_byte = read_byte(bounds);
  959. assert((second_byte & 128) == 0);
  960. *endline = bounds->ar_line = bounds->opaque.computed_line;
  961. *column = code << 3 | (second_byte >> 4);
  962. *endcolumn = *column + (second_byte & 15);
  963. }
  964. }
  965. ASSERT_VALID_BOUNDS(bounds);
  966. }
  967. int
  968. PyCode_Addr2Location(PyCodeObject *co, int addrq,
  969. int *start_line, int *start_column,
  970. int *end_line, int *end_column)
  971. {
  972. if (addrq < 0) {
  973. *start_line = *end_line = co->co_firstlineno;
  974. *start_column = *end_column = 0;
  975. return 1;
  976. }
  977. assert(addrq >= 0 && addrq < _PyCode_NBYTES(co));
  978. PyCodeAddressRange bounds;
  979. _PyCode_InitAddressRange(co, &bounds);
  980. _PyCode_CheckLineNumber(addrq, &bounds);
  981. retreat(&bounds);
  982. advance_with_locations(&bounds, end_line, start_column, end_column);
  983. *start_line = bounds.ar_line;
  984. return 1;
  985. }
  986. static inline int
  987. at_end(PyCodeAddressRange *bounds) {
  988. return bounds->opaque.lo_next >= bounds->opaque.limit;
  989. }
  990. int
  991. _PyLineTable_PreviousAddressRange(PyCodeAddressRange *range)
  992. {
  993. if (range->ar_start <= 0) {
  994. return 0;
  995. }
  996. retreat(range);
  997. assert(range->ar_end > range->ar_start);
  998. return 1;
  999. }
  1000. int
  1001. _PyLineTable_NextAddressRange(PyCodeAddressRange *range)
  1002. {
  1003. if (at_end(range)) {
  1004. return 0;
  1005. }
  1006. advance(range);
  1007. assert(range->ar_end > range->ar_start);
  1008. return 1;
  1009. }
  1010. static int
  1011. emit_pair(PyObject **bytes, int *offset, int a, int b)
  1012. {
  1013. Py_ssize_t len = PyBytes_GET_SIZE(*bytes);
  1014. if (*offset + 2 >= len) {
  1015. if (_PyBytes_Resize(bytes, len * 2) < 0)
  1016. return 0;
  1017. }
  1018. unsigned char *lnotab = (unsigned char *) PyBytes_AS_STRING(*bytes);
  1019. lnotab += *offset;
  1020. *lnotab++ = a;
  1021. *lnotab++ = b;
  1022. *offset += 2;
  1023. return 1;
  1024. }
  1025. static int
  1026. emit_delta(PyObject **bytes, int bdelta, int ldelta, int *offset)
  1027. {
  1028. while (bdelta > 255) {
  1029. if (!emit_pair(bytes, offset, 255, 0)) {
  1030. return 0;
  1031. }
  1032. bdelta -= 255;
  1033. }
  1034. while (ldelta > 127) {
  1035. if (!emit_pair(bytes, offset, bdelta, 127)) {
  1036. return 0;
  1037. }
  1038. bdelta = 0;
  1039. ldelta -= 127;
  1040. }
  1041. while (ldelta < -128) {
  1042. if (!emit_pair(bytes, offset, bdelta, -128)) {
  1043. return 0;
  1044. }
  1045. bdelta = 0;
  1046. ldelta += 128;
  1047. }
  1048. return emit_pair(bytes, offset, bdelta, ldelta);
  1049. }
  1050. static PyObject *
  1051. decode_linetable(PyCodeObject *code)
  1052. {
  1053. PyCodeAddressRange bounds;
  1054. PyObject *bytes;
  1055. int table_offset = 0;
  1056. int code_offset = 0;
  1057. int line = code->co_firstlineno;
  1058. bytes = PyBytes_FromStringAndSize(NULL, 64);
  1059. if (bytes == NULL) {
  1060. return NULL;
  1061. }
  1062. _PyCode_InitAddressRange(code, &bounds);
  1063. while (_PyLineTable_NextAddressRange(&bounds)) {
  1064. if (bounds.opaque.computed_line != line) {
  1065. int bdelta = bounds.ar_start - code_offset;
  1066. int ldelta = bounds.opaque.computed_line - line;
  1067. if (!emit_delta(&bytes, bdelta, ldelta, &table_offset)) {
  1068. Py_DECREF(bytes);
  1069. return NULL;
  1070. }
  1071. code_offset = bounds.ar_start;
  1072. line = bounds.opaque.computed_line;
  1073. }
  1074. }
  1075. _PyBytes_Resize(&bytes, table_offset);
  1076. return bytes;
  1077. }
  1078. typedef struct {
  1079. PyObject_HEAD
  1080. PyCodeObject *li_code;
  1081. PyCodeAddressRange li_line;
  1082. } lineiterator;
  1083. static void
  1084. lineiter_dealloc(lineiterator *li)
  1085. {
  1086. Py_DECREF(li->li_code);
  1087. Py_TYPE(li)->tp_free(li);
  1088. }
  1089. static PyObject *
  1090. _source_offset_converter(int *value) {
  1091. if (*value == -1) {
  1092. Py_RETURN_NONE;
  1093. }
  1094. return PyLong_FromLong(*value);
  1095. }
  1096. static PyObject *
  1097. lineiter_next(lineiterator *li)
  1098. {
  1099. PyCodeAddressRange *bounds = &li->li_line;
  1100. if (!_PyLineTable_NextAddressRange(bounds)) {
  1101. return NULL;
  1102. }
  1103. int start = bounds->ar_start;
  1104. int line = bounds->ar_line;
  1105. // Merge overlapping entries:
  1106. while (_PyLineTable_NextAddressRange(bounds)) {
  1107. if (bounds->ar_line != line) {
  1108. _PyLineTable_PreviousAddressRange(bounds);
  1109. break;
  1110. }
  1111. }
  1112. return Py_BuildValue("iiO&", start, bounds->ar_end,
  1113. _source_offset_converter, &line);
  1114. }
  1115. PyTypeObject _PyLineIterator = {
  1116. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  1117. "line_iterator", /* tp_name */
  1118. sizeof(lineiterator), /* tp_basicsize */
  1119. 0, /* tp_itemsize */
  1120. /* methods */
  1121. (destructor)lineiter_dealloc, /* tp_dealloc */
  1122. 0, /* tp_vectorcall_offset */
  1123. 0, /* tp_getattr */
  1124. 0, /* tp_setattr */
  1125. 0, /* tp_as_async */
  1126. 0, /* tp_repr */
  1127. 0, /* tp_as_number */
  1128. 0, /* tp_as_sequence */
  1129. 0, /* tp_as_mapping */
  1130. 0, /* tp_hash */
  1131. 0, /* tp_call */
  1132. 0, /* tp_str */
  1133. 0, /* tp_getattro */
  1134. 0, /* tp_setattro */
  1135. 0, /* tp_as_buffer */
  1136. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
  1137. 0, /* tp_doc */
  1138. 0, /* tp_traverse */
  1139. 0, /* tp_clear */
  1140. 0, /* tp_richcompare */
  1141. 0, /* tp_weaklistoffset */
  1142. PyObject_SelfIter, /* tp_iter */
  1143. (iternextfunc)lineiter_next, /* tp_iternext */
  1144. 0, /* tp_methods */
  1145. 0, /* tp_members */
  1146. 0, /* tp_getset */
  1147. 0, /* tp_base */
  1148. 0, /* tp_dict */
  1149. 0, /* tp_descr_get */
  1150. 0, /* tp_descr_set */
  1151. 0, /* tp_dictoffset */
  1152. 0, /* tp_init */
  1153. 0, /* tp_alloc */
  1154. 0, /* tp_new */
  1155. PyObject_Del, /* tp_free */
  1156. };
  1157. static lineiterator *
  1158. new_linesiterator(PyCodeObject *code)
  1159. {
  1160. lineiterator *li = (lineiterator *)PyType_GenericAlloc(&_PyLineIterator, 0);
  1161. if (li == NULL) {
  1162. return NULL;
  1163. }
  1164. li->li_code = (PyCodeObject*)Py_NewRef(code);
  1165. _PyCode_InitAddressRange(code, &li->li_line);
  1166. return li;
  1167. }
  1168. /* co_positions iterator object. */
  1169. typedef struct {
  1170. PyObject_HEAD
  1171. PyCodeObject* pi_code;
  1172. PyCodeAddressRange pi_range;
  1173. int pi_offset;
  1174. int pi_endline;
  1175. int pi_column;
  1176. int pi_endcolumn;
  1177. } positionsiterator;
  1178. static void
  1179. positionsiter_dealloc(positionsiterator* pi)
  1180. {
  1181. Py_DECREF(pi->pi_code);
  1182. Py_TYPE(pi)->tp_free(pi);
  1183. }
  1184. static PyObject*
  1185. positionsiter_next(positionsiterator* pi)
  1186. {
  1187. if (pi->pi_offset >= pi->pi_range.ar_end) {
  1188. assert(pi->pi_offset == pi->pi_range.ar_end);
  1189. if (at_end(&pi->pi_range)) {
  1190. return NULL;
  1191. }
  1192. advance_with_locations(&pi->pi_range, &pi->pi_endline, &pi->pi_column, &pi->pi_endcolumn);
  1193. }
  1194. pi->pi_offset += 2;
  1195. return Py_BuildValue("(O&O&O&O&)",
  1196. _source_offset_converter, &pi->pi_range.ar_line,
  1197. _source_offset_converter, &pi->pi_endline,
  1198. _source_offset_converter, &pi->pi_column,
  1199. _source_offset_converter, &pi->pi_endcolumn);
  1200. }
  1201. PyTypeObject _PyPositionsIterator = {
  1202. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  1203. "positions_iterator", /* tp_name */
  1204. sizeof(positionsiterator), /* tp_basicsize */
  1205. 0, /* tp_itemsize */
  1206. /* methods */
  1207. (destructor)positionsiter_dealloc, /* tp_dealloc */
  1208. 0, /* tp_vectorcall_offset */
  1209. 0, /* tp_getattr */
  1210. 0, /* tp_setattr */
  1211. 0, /* tp_as_async */
  1212. 0, /* tp_repr */
  1213. 0, /* tp_as_number */
  1214. 0, /* tp_as_sequence */
  1215. 0, /* tp_as_mapping */
  1216. 0, /* tp_hash */
  1217. 0, /* tp_call */
  1218. 0, /* tp_str */
  1219. 0, /* tp_getattro */
  1220. 0, /* tp_setattro */
  1221. 0, /* tp_as_buffer */
  1222. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
  1223. 0, /* tp_doc */
  1224. 0, /* tp_traverse */
  1225. 0, /* tp_clear */
  1226. 0, /* tp_richcompare */
  1227. 0, /* tp_weaklistoffset */
  1228. PyObject_SelfIter, /* tp_iter */
  1229. (iternextfunc)positionsiter_next, /* tp_iternext */
  1230. 0, /* tp_methods */
  1231. 0, /* tp_members */
  1232. 0, /* tp_getset */
  1233. 0, /* tp_base */
  1234. 0, /* tp_dict */
  1235. 0, /* tp_descr_get */
  1236. 0, /* tp_descr_set */
  1237. 0, /* tp_dictoffset */
  1238. 0, /* tp_init */
  1239. 0, /* tp_alloc */
  1240. 0, /* tp_new */
  1241. PyObject_Del, /* tp_free */
  1242. };
  1243. static PyObject*
  1244. code_positionsiterator(PyCodeObject* code, PyObject* Py_UNUSED(args))
  1245. {
  1246. positionsiterator* pi = (positionsiterator*)PyType_GenericAlloc(&_PyPositionsIterator, 0);
  1247. if (pi == NULL) {
  1248. return NULL;
  1249. }
  1250. pi->pi_code = (PyCodeObject*)Py_NewRef(code);
  1251. _PyCode_InitAddressRange(code, &pi->pi_range);
  1252. pi->pi_offset = pi->pi_range.ar_end;
  1253. return (PyObject*)pi;
  1254. }
  1255. /******************
  1256. * "extra" frame eval info (see PEP 523)
  1257. ******************/
  1258. /* Holder for co_extra information */
  1259. typedef struct {
  1260. Py_ssize_t ce_size;
  1261. void *ce_extras[1];
  1262. } _PyCodeObjectExtra;
  1263. int
  1264. PyUnstable_Code_GetExtra(PyObject *code, Py_ssize_t index, void **extra)
  1265. {
  1266. if (!PyCode_Check(code)) {
  1267. PyErr_BadInternalCall();
  1268. return -1;
  1269. }
  1270. PyCodeObject *o = (PyCodeObject*) code;
  1271. _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra*) o->co_extra;
  1272. if (co_extra == NULL || index < 0 || co_extra->ce_size <= index) {
  1273. *extra = NULL;
  1274. return 0;
  1275. }
  1276. *extra = co_extra->ce_extras[index];
  1277. return 0;
  1278. }
  1279. int
  1280. PyUnstable_Code_SetExtra(PyObject *code, Py_ssize_t index, void *extra)
  1281. {
  1282. PyInterpreterState *interp = _PyInterpreterState_GET();
  1283. if (!PyCode_Check(code) || index < 0 ||
  1284. index >= interp->co_extra_user_count) {
  1285. PyErr_BadInternalCall();
  1286. return -1;
  1287. }
  1288. PyCodeObject *o = (PyCodeObject*) code;
  1289. _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra *) o->co_extra;
  1290. if (co_extra == NULL || co_extra->ce_size <= index) {
  1291. Py_ssize_t i = (co_extra == NULL ? 0 : co_extra->ce_size);
  1292. co_extra = PyMem_Realloc(
  1293. co_extra,
  1294. sizeof(_PyCodeObjectExtra) +
  1295. (interp->co_extra_user_count-1) * sizeof(void*));
  1296. if (co_extra == NULL) {
  1297. return -1;
  1298. }
  1299. for (; i < interp->co_extra_user_count; i++) {
  1300. co_extra->ce_extras[i] = NULL;
  1301. }
  1302. co_extra->ce_size = interp->co_extra_user_count;
  1303. o->co_extra = co_extra;
  1304. }
  1305. if (co_extra->ce_extras[index] != NULL) {
  1306. freefunc free = interp->co_extra_freefuncs[index];
  1307. if (free != NULL) {
  1308. free(co_extra->ce_extras[index]);
  1309. }
  1310. }
  1311. co_extra->ce_extras[index] = extra;
  1312. return 0;
  1313. }
  1314. /******************
  1315. * other PyCodeObject accessor functions
  1316. ******************/
  1317. static PyObject *
  1318. get_cached_locals(PyCodeObject *co, PyObject **cached_field,
  1319. _PyLocals_Kind kind, int num)
  1320. {
  1321. assert(cached_field != NULL);
  1322. assert(co->_co_cached != NULL);
  1323. if (*cached_field != NULL) {
  1324. return Py_NewRef(*cached_field);
  1325. }
  1326. assert(*cached_field == NULL);
  1327. PyObject *varnames = get_localsplus_names(co, kind, num);
  1328. if (varnames == NULL) {
  1329. return NULL;
  1330. }
  1331. *cached_field = Py_NewRef(varnames);
  1332. return varnames;
  1333. }
  1334. PyObject *
  1335. _PyCode_GetVarnames(PyCodeObject *co)
  1336. {
  1337. if (init_co_cached(co)) {
  1338. return NULL;
  1339. }
  1340. return get_cached_locals(co, &co->_co_cached->_co_varnames, CO_FAST_LOCAL, co->co_nlocals);
  1341. }
  1342. PyObject *
  1343. PyCode_GetVarnames(PyCodeObject *code)
  1344. {
  1345. return _PyCode_GetVarnames(code);
  1346. }
  1347. PyObject *
  1348. _PyCode_GetCellvars(PyCodeObject *co)
  1349. {
  1350. if (init_co_cached(co)) {
  1351. return NULL;
  1352. }
  1353. return get_cached_locals(co, &co->_co_cached->_co_cellvars, CO_FAST_CELL, co->co_ncellvars);
  1354. }
  1355. PyObject *
  1356. PyCode_GetCellvars(PyCodeObject *code)
  1357. {
  1358. return _PyCode_GetCellvars(code);
  1359. }
  1360. PyObject *
  1361. _PyCode_GetFreevars(PyCodeObject *co)
  1362. {
  1363. if (init_co_cached(co)) {
  1364. return NULL;
  1365. }
  1366. return get_cached_locals(co, &co->_co_cached->_co_freevars, CO_FAST_FREE, co->co_nfreevars);
  1367. }
  1368. PyObject *
  1369. PyCode_GetFreevars(PyCodeObject *code)
  1370. {
  1371. return _PyCode_GetFreevars(code);
  1372. }
  1373. static void
  1374. deopt_code(PyCodeObject *code, _Py_CODEUNIT *instructions)
  1375. {
  1376. Py_ssize_t len = Py_SIZE(code);
  1377. for (int i = 0; i < len; i++) {
  1378. int opcode = _Py_GetBaseOpcode(code, i);
  1379. int caches = _PyOpcode_Caches[opcode];
  1380. instructions[i].op.code = opcode;
  1381. for (int j = 1; j <= caches; j++) {
  1382. instructions[i+j].cache = 0;
  1383. }
  1384. i += caches;
  1385. }
  1386. }
  1387. PyObject *
  1388. _PyCode_GetCode(PyCodeObject *co)
  1389. {
  1390. if (init_co_cached(co)) {
  1391. return NULL;
  1392. }
  1393. if (co->_co_cached->_co_code != NULL) {
  1394. return Py_NewRef(co->_co_cached->_co_code);
  1395. }
  1396. PyObject *code = PyBytes_FromStringAndSize((const char *)_PyCode_CODE(co),
  1397. _PyCode_NBYTES(co));
  1398. if (code == NULL) {
  1399. return NULL;
  1400. }
  1401. deopt_code(co, (_Py_CODEUNIT *)PyBytes_AS_STRING(code));
  1402. assert(co->_co_cached->_co_code == NULL);
  1403. co->_co_cached->_co_code = Py_NewRef(code);
  1404. return code;
  1405. }
  1406. PyObject *
  1407. PyCode_GetCode(PyCodeObject *co)
  1408. {
  1409. return _PyCode_GetCode(co);
  1410. }
  1411. /******************
  1412. * PyCode_Type
  1413. ******************/
  1414. /*[clinic input]
  1415. class code "PyCodeObject *" "&PyCode_Type"
  1416. [clinic start generated code]*/
  1417. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=78aa5d576683bb4b]*/
  1418. /*[clinic input]
  1419. @classmethod
  1420. code.__new__ as code_new
  1421. argcount: int
  1422. posonlyargcount: int
  1423. kwonlyargcount: int
  1424. nlocals: int
  1425. stacksize: int
  1426. flags: int
  1427. codestring as code: object(subclass_of="&PyBytes_Type")
  1428. constants as consts: object(subclass_of="&PyTuple_Type")
  1429. names: object(subclass_of="&PyTuple_Type")
  1430. varnames: object(subclass_of="&PyTuple_Type")
  1431. filename: unicode
  1432. name: unicode
  1433. qualname: unicode
  1434. firstlineno: int
  1435. linetable: object(subclass_of="&PyBytes_Type")
  1436. exceptiontable: object(subclass_of="&PyBytes_Type")
  1437. freevars: object(subclass_of="&PyTuple_Type", c_default="NULL") = ()
  1438. cellvars: object(subclass_of="&PyTuple_Type", c_default="NULL") = ()
  1439. /
  1440. Create a code object. Not for the faint of heart.
  1441. [clinic start generated code]*/
  1442. static PyObject *
  1443. code_new_impl(PyTypeObject *type, int argcount, int posonlyargcount,
  1444. int kwonlyargcount, int nlocals, int stacksize, int flags,
  1445. PyObject *code, PyObject *consts, PyObject *names,
  1446. PyObject *varnames, PyObject *filename, PyObject *name,
  1447. PyObject *qualname, int firstlineno, PyObject *linetable,
  1448. PyObject *exceptiontable, PyObject *freevars,
  1449. PyObject *cellvars)
  1450. /*[clinic end generated code: output=069fa20d299f9dda input=e31da3c41ad8064a]*/
  1451. {
  1452. PyObject *co = NULL;
  1453. PyObject *ournames = NULL;
  1454. PyObject *ourvarnames = NULL;
  1455. PyObject *ourfreevars = NULL;
  1456. PyObject *ourcellvars = NULL;
  1457. if (PySys_Audit("code.__new__", "OOOiiiiii",
  1458. code, filename, name, argcount, posonlyargcount,
  1459. kwonlyargcount, nlocals, stacksize, flags) < 0) {
  1460. goto cleanup;
  1461. }
  1462. if (argcount < 0) {
  1463. PyErr_SetString(
  1464. PyExc_ValueError,
  1465. "code: argcount must not be negative");
  1466. goto cleanup;
  1467. }
  1468. if (posonlyargcount < 0) {
  1469. PyErr_SetString(
  1470. PyExc_ValueError,
  1471. "code: posonlyargcount must not be negative");
  1472. goto cleanup;
  1473. }
  1474. if (kwonlyargcount < 0) {
  1475. PyErr_SetString(
  1476. PyExc_ValueError,
  1477. "code: kwonlyargcount must not be negative");
  1478. goto cleanup;
  1479. }
  1480. if (nlocals < 0) {
  1481. PyErr_SetString(
  1482. PyExc_ValueError,
  1483. "code: nlocals must not be negative");
  1484. goto cleanup;
  1485. }
  1486. ournames = validate_and_copy_tuple(names);
  1487. if (ournames == NULL)
  1488. goto cleanup;
  1489. ourvarnames = validate_and_copy_tuple(varnames);
  1490. if (ourvarnames == NULL)
  1491. goto cleanup;
  1492. if (freevars)
  1493. ourfreevars = validate_and_copy_tuple(freevars);
  1494. else
  1495. ourfreevars = PyTuple_New(0);
  1496. if (ourfreevars == NULL)
  1497. goto cleanup;
  1498. if (cellvars)
  1499. ourcellvars = validate_and_copy_tuple(cellvars);
  1500. else
  1501. ourcellvars = PyTuple_New(0);
  1502. if (ourcellvars == NULL)
  1503. goto cleanup;
  1504. co = (PyObject *)PyCode_NewWithPosOnlyArgs(argcount, posonlyargcount,
  1505. kwonlyargcount,
  1506. nlocals, stacksize, flags,
  1507. code, consts, ournames,
  1508. ourvarnames, ourfreevars,
  1509. ourcellvars, filename,
  1510. name, qualname, firstlineno,
  1511. linetable,
  1512. exceptiontable
  1513. );
  1514. cleanup:
  1515. Py_XDECREF(ournames);
  1516. Py_XDECREF(ourvarnames);
  1517. Py_XDECREF(ourfreevars);
  1518. Py_XDECREF(ourcellvars);
  1519. return co;
  1520. }
  1521. static void
  1522. free_monitoring_data(_PyCoMonitoringData *data)
  1523. {
  1524. if (data == NULL) {
  1525. return;
  1526. }
  1527. if (data->tools) {
  1528. PyMem_Free(data->tools);
  1529. }
  1530. if (data->lines) {
  1531. PyMem_Free(data->lines);
  1532. }
  1533. if (data->line_tools) {
  1534. PyMem_Free(data->line_tools);
  1535. }
  1536. if (data->per_instruction_opcodes) {
  1537. PyMem_Free(data->per_instruction_opcodes);
  1538. }
  1539. if (data->per_instruction_tools) {
  1540. PyMem_Free(data->per_instruction_tools);
  1541. }
  1542. PyMem_Free(data);
  1543. }
  1544. static void
  1545. code_dealloc(PyCodeObject *co)
  1546. {
  1547. assert(Py_REFCNT(co) == 0);
  1548. Py_SET_REFCNT(co, 1);
  1549. notify_code_watchers(PY_CODE_EVENT_DESTROY, co);
  1550. if (Py_REFCNT(co) > 1) {
  1551. Py_SET_REFCNT(co, Py_REFCNT(co) - 1);
  1552. return;
  1553. }
  1554. Py_SET_REFCNT(co, 0);
  1555. if (co->co_extra != NULL) {
  1556. PyInterpreterState *interp = _PyInterpreterState_GET();
  1557. _PyCodeObjectExtra *co_extra = co->co_extra;
  1558. for (Py_ssize_t i = 0; i < co_extra->ce_size; i++) {
  1559. freefunc free_extra = interp->co_extra_freefuncs[i];
  1560. if (free_extra != NULL) {
  1561. free_extra(co_extra->ce_extras[i]);
  1562. }
  1563. }
  1564. PyMem_Free(co_extra);
  1565. }
  1566. Py_XDECREF(co->co_consts);
  1567. Py_XDECREF(co->co_names);
  1568. Py_XDECREF(co->co_localsplusnames);
  1569. Py_XDECREF(co->co_localspluskinds);
  1570. Py_XDECREF(co->co_filename);
  1571. Py_XDECREF(co->co_name);
  1572. Py_XDECREF(co->co_qualname);
  1573. Py_XDECREF(co->co_linetable);
  1574. Py_XDECREF(co->co_exceptiontable);
  1575. if (co->_co_cached != NULL) {
  1576. Py_XDECREF(co->_co_cached->_co_code);
  1577. Py_XDECREF(co->_co_cached->_co_cellvars);
  1578. Py_XDECREF(co->_co_cached->_co_freevars);
  1579. Py_XDECREF(co->_co_cached->_co_varnames);
  1580. PyMem_Free(co->_co_cached);
  1581. }
  1582. if (co->co_weakreflist != NULL) {
  1583. PyObject_ClearWeakRefs((PyObject*)co);
  1584. }
  1585. free_monitoring_data(co->_co_monitoring);
  1586. PyObject_Free(co);
  1587. }
  1588. static PyObject *
  1589. code_repr(PyCodeObject *co)
  1590. {
  1591. int lineno;
  1592. if (co->co_firstlineno != 0)
  1593. lineno = co->co_firstlineno;
  1594. else
  1595. lineno = -1;
  1596. if (co->co_filename && PyUnicode_Check(co->co_filename)) {
  1597. return PyUnicode_FromFormat(
  1598. "<code object %U at %p, file \"%U\", line %d>",
  1599. co->co_name, co, co->co_filename, lineno);
  1600. } else {
  1601. return PyUnicode_FromFormat(
  1602. "<code object %U at %p, file ???, line %d>",
  1603. co->co_name, co, lineno);
  1604. }
  1605. }
  1606. static PyObject *
  1607. code_richcompare(PyObject *self, PyObject *other, int op)
  1608. {
  1609. PyCodeObject *co, *cp;
  1610. int eq;
  1611. PyObject *consts1, *consts2;
  1612. PyObject *res;
  1613. if ((op != Py_EQ && op != Py_NE) ||
  1614. !PyCode_Check(self) ||
  1615. !PyCode_Check(other)) {
  1616. Py_RETURN_NOTIMPLEMENTED;
  1617. }
  1618. co = (PyCodeObject *)self;
  1619. cp = (PyCodeObject *)other;
  1620. eq = PyObject_RichCompareBool(co->co_name, cp->co_name, Py_EQ);
  1621. if (!eq) goto unequal;
  1622. eq = co->co_argcount == cp->co_argcount;
  1623. if (!eq) goto unequal;
  1624. eq = co->co_posonlyargcount == cp->co_posonlyargcount;
  1625. if (!eq) goto unequal;
  1626. eq = co->co_kwonlyargcount == cp->co_kwonlyargcount;
  1627. if (!eq) goto unequal;
  1628. eq = co->co_flags == cp->co_flags;
  1629. if (!eq) goto unequal;
  1630. eq = co->co_firstlineno == cp->co_firstlineno;
  1631. if (!eq) goto unequal;
  1632. eq = Py_SIZE(co) == Py_SIZE(cp);
  1633. if (!eq) {
  1634. goto unequal;
  1635. }
  1636. for (int i = 0; i < Py_SIZE(co); i++) {
  1637. _Py_CODEUNIT co_instr = _PyCode_CODE(co)[i];
  1638. _Py_CODEUNIT cp_instr = _PyCode_CODE(cp)[i];
  1639. co_instr.op.code = _Py_GetBaseOpcode(co, i);
  1640. cp_instr.op.code = _Py_GetBaseOpcode(cp, i);
  1641. eq = co_instr.cache == cp_instr.cache;
  1642. if (!eq) {
  1643. goto unequal;
  1644. }
  1645. i += _PyOpcode_Caches[co_instr.op.code];
  1646. }
  1647. /* compare constants */
  1648. consts1 = _PyCode_ConstantKey(co->co_consts);
  1649. if (!consts1)
  1650. return NULL;
  1651. consts2 = _PyCode_ConstantKey(cp->co_consts);
  1652. if (!consts2) {
  1653. Py_DECREF(consts1);
  1654. return NULL;
  1655. }
  1656. eq = PyObject_RichCompareBool(consts1, consts2, Py_EQ);
  1657. Py_DECREF(consts1);
  1658. Py_DECREF(consts2);
  1659. if (eq <= 0) goto unequal;
  1660. eq = PyObject_RichCompareBool(co->co_names, cp->co_names, Py_EQ);
  1661. if (eq <= 0) goto unequal;
  1662. eq = PyObject_RichCompareBool(co->co_localsplusnames,
  1663. cp->co_localsplusnames, Py_EQ);
  1664. if (eq <= 0) goto unequal;
  1665. eq = PyObject_RichCompareBool(co->co_linetable, cp->co_linetable, Py_EQ);
  1666. if (eq <= 0) {
  1667. goto unequal;
  1668. }
  1669. eq = PyObject_RichCompareBool(co->co_exceptiontable,
  1670. cp->co_exceptiontable, Py_EQ);
  1671. if (eq <= 0) {
  1672. goto unequal;
  1673. }
  1674. if (op == Py_EQ)
  1675. res = Py_True;
  1676. else
  1677. res = Py_False;
  1678. goto done;
  1679. unequal:
  1680. if (eq < 0)
  1681. return NULL;
  1682. if (op == Py_NE)
  1683. res = Py_True;
  1684. else
  1685. res = Py_False;
  1686. done:
  1687. return Py_NewRef(res);
  1688. }
  1689. static Py_hash_t
  1690. code_hash(PyCodeObject *co)
  1691. {
  1692. Py_uhash_t uhash = 20221211;
  1693. #define SCRAMBLE_IN(H) do { \
  1694. uhash ^= (Py_uhash_t)(H); \
  1695. uhash *= _PyHASH_MULTIPLIER; \
  1696. } while (0)
  1697. #define SCRAMBLE_IN_HASH(EXPR) do { \
  1698. Py_hash_t h = PyObject_Hash(EXPR); \
  1699. if (h == -1) { \
  1700. return -1; \
  1701. } \
  1702. SCRAMBLE_IN(h); \
  1703. } while (0)
  1704. SCRAMBLE_IN_HASH(co->co_name);
  1705. SCRAMBLE_IN_HASH(co->co_consts);
  1706. SCRAMBLE_IN_HASH(co->co_names);
  1707. SCRAMBLE_IN_HASH(co->co_localsplusnames);
  1708. SCRAMBLE_IN_HASH(co->co_linetable);
  1709. SCRAMBLE_IN_HASH(co->co_exceptiontable);
  1710. SCRAMBLE_IN(co->co_argcount);
  1711. SCRAMBLE_IN(co->co_posonlyargcount);
  1712. SCRAMBLE_IN(co->co_kwonlyargcount);
  1713. SCRAMBLE_IN(co->co_flags);
  1714. SCRAMBLE_IN(co->co_firstlineno);
  1715. SCRAMBLE_IN(Py_SIZE(co));
  1716. for (int i = 0; i < Py_SIZE(co); i++) {
  1717. int deop = _Py_GetBaseOpcode(co, i);
  1718. SCRAMBLE_IN(deop);
  1719. SCRAMBLE_IN(_PyCode_CODE(co)[i].op.arg);
  1720. i += _PyOpcode_Caches[deop];
  1721. }
  1722. if ((Py_hash_t)uhash == -1) {
  1723. return -2;
  1724. }
  1725. return (Py_hash_t)uhash;
  1726. }
  1727. #define OFF(x) offsetof(PyCodeObject, x)
  1728. static PyMemberDef code_memberlist[] = {
  1729. {"co_argcount", T_INT, OFF(co_argcount), READONLY},
  1730. {"co_posonlyargcount", T_INT, OFF(co_posonlyargcount), READONLY},
  1731. {"co_kwonlyargcount", T_INT, OFF(co_kwonlyargcount), READONLY},
  1732. {"co_stacksize", T_INT, OFF(co_stacksize), READONLY},
  1733. {"co_flags", T_INT, OFF(co_flags), READONLY},
  1734. {"co_nlocals", T_INT, OFF(co_nlocals), READONLY},
  1735. {"co_consts", T_OBJECT, OFF(co_consts), READONLY},
  1736. {"co_names", T_OBJECT, OFF(co_names), READONLY},
  1737. {"co_filename", T_OBJECT, OFF(co_filename), READONLY},
  1738. {"co_name", T_OBJECT, OFF(co_name), READONLY},
  1739. {"co_qualname", T_OBJECT, OFF(co_qualname), READONLY},
  1740. {"co_firstlineno", T_INT, OFF(co_firstlineno), READONLY},
  1741. {"co_linetable", T_OBJECT, OFF(co_linetable), READONLY},
  1742. {"co_exceptiontable", T_OBJECT, OFF(co_exceptiontable), READONLY},
  1743. {NULL} /* Sentinel */
  1744. };
  1745. static PyObject *
  1746. code_getlnotab(PyCodeObject *code, void *closure)
  1747. {
  1748. if (PyErr_WarnEx(PyExc_DeprecationWarning,
  1749. "co_lnotab is deprecated, use co_lines instead.",
  1750. 1) < 0) {
  1751. return NULL;
  1752. }
  1753. return decode_linetable(code);
  1754. }
  1755. static PyObject *
  1756. code_getvarnames(PyCodeObject *code, void *closure)
  1757. {
  1758. return _PyCode_GetVarnames(code);
  1759. }
  1760. static PyObject *
  1761. code_getcellvars(PyCodeObject *code, void *closure)
  1762. {
  1763. return _PyCode_GetCellvars(code);
  1764. }
  1765. static PyObject *
  1766. code_getfreevars(PyCodeObject *code, void *closure)
  1767. {
  1768. return _PyCode_GetFreevars(code);
  1769. }
  1770. static PyObject *
  1771. code_getcodeadaptive(PyCodeObject *code, void *closure)
  1772. {
  1773. return PyBytes_FromStringAndSize(code->co_code_adaptive,
  1774. _PyCode_NBYTES(code));
  1775. }
  1776. static PyObject *
  1777. code_getcode(PyCodeObject *code, void *closure)
  1778. {
  1779. return _PyCode_GetCode(code);
  1780. }
  1781. static PyGetSetDef code_getsetlist[] = {
  1782. {"co_lnotab", (getter)code_getlnotab, NULL, NULL},
  1783. {"_co_code_adaptive", (getter)code_getcodeadaptive, NULL, NULL},
  1784. // The following old names are kept for backward compatibility.
  1785. {"co_varnames", (getter)code_getvarnames, NULL, NULL},
  1786. {"co_cellvars", (getter)code_getcellvars, NULL, NULL},
  1787. {"co_freevars", (getter)code_getfreevars, NULL, NULL},
  1788. {"co_code", (getter)code_getcode, NULL, NULL},
  1789. {0}
  1790. };
  1791. static PyObject *
  1792. code_sizeof(PyCodeObject *co, PyObject *Py_UNUSED(args))
  1793. {
  1794. size_t res = _PyObject_VAR_SIZE(Py_TYPE(co), Py_SIZE(co));
  1795. _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra*) co->co_extra;
  1796. if (co_extra != NULL) {
  1797. res += sizeof(_PyCodeObjectExtra);
  1798. res += ((size_t)co_extra->ce_size - 1) * sizeof(co_extra->ce_extras[0]);
  1799. }
  1800. return PyLong_FromSize_t(res);
  1801. }
  1802. static PyObject *
  1803. code_linesiterator(PyCodeObject *code, PyObject *Py_UNUSED(args))
  1804. {
  1805. return (PyObject *)new_linesiterator(code);
  1806. }
  1807. /*[clinic input]
  1808. @text_signature "($self, /, **changes)"
  1809. code.replace
  1810. *
  1811. co_argcount: int(c_default="self->co_argcount") = unchanged
  1812. co_posonlyargcount: int(c_default="self->co_posonlyargcount") = unchanged
  1813. co_kwonlyargcount: int(c_default="self->co_kwonlyargcount") = unchanged
  1814. co_nlocals: int(c_default="self->co_nlocals") = unchanged
  1815. co_stacksize: int(c_default="self->co_stacksize") = unchanged
  1816. co_flags: int(c_default="self->co_flags") = unchanged
  1817. co_firstlineno: int(c_default="self->co_firstlineno") = unchanged
  1818. co_code: object(subclass_of="&PyBytes_Type", c_default="NULL") = unchanged
  1819. co_consts: object(subclass_of="&PyTuple_Type", c_default="self->co_consts") = unchanged
  1820. co_names: object(subclass_of="&PyTuple_Type", c_default="self->co_names") = unchanged
  1821. co_varnames: object(subclass_of="&PyTuple_Type", c_default="NULL") = unchanged
  1822. co_freevars: object(subclass_of="&PyTuple_Type", c_default="NULL") = unchanged
  1823. co_cellvars: object(subclass_of="&PyTuple_Type", c_default="NULL") = unchanged
  1824. co_filename: unicode(c_default="self->co_filename") = unchanged
  1825. co_name: unicode(c_default="self->co_name") = unchanged
  1826. co_qualname: unicode(c_default="self->co_qualname") = unchanged
  1827. co_linetable: object(subclass_of="&PyBytes_Type", c_default="self->co_linetable") = unchanged
  1828. co_exceptiontable: object(subclass_of="&PyBytes_Type", c_default="self->co_exceptiontable") = unchanged
  1829. Return a copy of the code object with new values for the specified fields.
  1830. [clinic start generated code]*/
  1831. static PyObject *
  1832. code_replace_impl(PyCodeObject *self, int co_argcount,
  1833. int co_posonlyargcount, int co_kwonlyargcount,
  1834. int co_nlocals, int co_stacksize, int co_flags,
  1835. int co_firstlineno, PyObject *co_code, PyObject *co_consts,
  1836. PyObject *co_names, PyObject *co_varnames,
  1837. PyObject *co_freevars, PyObject *co_cellvars,
  1838. PyObject *co_filename, PyObject *co_name,
  1839. PyObject *co_qualname, PyObject *co_linetable,
  1840. PyObject *co_exceptiontable)
  1841. /*[clinic end generated code: output=e75c48a15def18b9 input=18e280e07846c122]*/
  1842. {
  1843. #define CHECK_INT_ARG(ARG) \
  1844. if (ARG < 0) { \
  1845. PyErr_SetString(PyExc_ValueError, \
  1846. #ARG " must be a positive integer"); \
  1847. return NULL; \
  1848. }
  1849. CHECK_INT_ARG(co_argcount);
  1850. CHECK_INT_ARG(co_posonlyargcount);
  1851. CHECK_INT_ARG(co_kwonlyargcount);
  1852. CHECK_INT_ARG(co_nlocals);
  1853. CHECK_INT_ARG(co_stacksize);
  1854. CHECK_INT_ARG(co_flags);
  1855. CHECK_INT_ARG(co_firstlineno);
  1856. #undef CHECK_INT_ARG
  1857. PyObject *code = NULL;
  1858. if (co_code == NULL) {
  1859. code = _PyCode_GetCode(self);
  1860. if (code == NULL) {
  1861. return NULL;
  1862. }
  1863. co_code = code;
  1864. }
  1865. if (PySys_Audit("code.__new__", "OOOiiiiii",
  1866. co_code, co_filename, co_name, co_argcount,
  1867. co_posonlyargcount, co_kwonlyargcount, co_nlocals,
  1868. co_stacksize, co_flags) < 0) {
  1869. Py_XDECREF(code);
  1870. return NULL;
  1871. }
  1872. PyCodeObject *co = NULL;
  1873. PyObject *varnames = NULL;
  1874. PyObject *cellvars = NULL;
  1875. PyObject *freevars = NULL;
  1876. if (co_varnames == NULL) {
  1877. varnames = get_localsplus_names(self, CO_FAST_LOCAL, self->co_nlocals);
  1878. if (varnames == NULL) {
  1879. goto error;
  1880. }
  1881. co_varnames = varnames;
  1882. }
  1883. if (co_cellvars == NULL) {
  1884. cellvars = get_localsplus_names(self, CO_FAST_CELL, self->co_ncellvars);
  1885. if (cellvars == NULL) {
  1886. goto error;
  1887. }
  1888. co_cellvars = cellvars;
  1889. }
  1890. if (co_freevars == NULL) {
  1891. freevars = get_localsplus_names(self, CO_FAST_FREE, self->co_nfreevars);
  1892. if (freevars == NULL) {
  1893. goto error;
  1894. }
  1895. co_freevars = freevars;
  1896. }
  1897. co = PyCode_NewWithPosOnlyArgs(
  1898. co_argcount, co_posonlyargcount, co_kwonlyargcount, co_nlocals,
  1899. co_stacksize, co_flags, co_code, co_consts, co_names,
  1900. co_varnames, co_freevars, co_cellvars, co_filename, co_name,
  1901. co_qualname, co_firstlineno,
  1902. co_linetable, co_exceptiontable);
  1903. error:
  1904. Py_XDECREF(code);
  1905. Py_XDECREF(varnames);
  1906. Py_XDECREF(cellvars);
  1907. Py_XDECREF(freevars);
  1908. return (PyObject *)co;
  1909. }
  1910. /*[clinic input]
  1911. code._varname_from_oparg
  1912. oparg: int
  1913. (internal-only) Return the local variable name for the given oparg.
  1914. WARNING: this method is for internal use only and may change or go away.
  1915. [clinic start generated code]*/
  1916. static PyObject *
  1917. code__varname_from_oparg_impl(PyCodeObject *self, int oparg)
  1918. /*[clinic end generated code: output=1fd1130413184206 input=c5fa3ee9bac7d4ca]*/
  1919. {
  1920. PyObject *name = PyTuple_GetItem(self->co_localsplusnames, oparg);
  1921. if (name == NULL) {
  1922. return NULL;
  1923. }
  1924. return Py_NewRef(name);
  1925. }
  1926. /* XXX code objects need to participate in GC? */
  1927. static struct PyMethodDef code_methods[] = {
  1928. {"__sizeof__", (PyCFunction)code_sizeof, METH_NOARGS},
  1929. {"co_lines", (PyCFunction)code_linesiterator, METH_NOARGS},
  1930. {"co_positions", (PyCFunction)code_positionsiterator, METH_NOARGS},
  1931. CODE_REPLACE_METHODDEF
  1932. CODE__VARNAME_FROM_OPARG_METHODDEF
  1933. {NULL, NULL} /* sentinel */
  1934. };
  1935. PyTypeObject PyCode_Type = {
  1936. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  1937. "code",
  1938. offsetof(PyCodeObject, co_code_adaptive),
  1939. sizeof(_Py_CODEUNIT),
  1940. (destructor)code_dealloc, /* tp_dealloc */
  1941. 0, /* tp_vectorcall_offset */
  1942. 0, /* tp_getattr */
  1943. 0, /* tp_setattr */
  1944. 0, /* tp_as_async */
  1945. (reprfunc)code_repr, /* tp_repr */
  1946. 0, /* tp_as_number */
  1947. 0, /* tp_as_sequence */
  1948. 0, /* tp_as_mapping */
  1949. (hashfunc)code_hash, /* tp_hash */
  1950. 0, /* tp_call */
  1951. 0, /* tp_str */
  1952. PyObject_GenericGetAttr, /* tp_getattro */
  1953. 0, /* tp_setattro */
  1954. 0, /* tp_as_buffer */
  1955. Py_TPFLAGS_DEFAULT, /* tp_flags */
  1956. code_new__doc__, /* tp_doc */
  1957. 0, /* tp_traverse */
  1958. 0, /* tp_clear */
  1959. code_richcompare, /* tp_richcompare */
  1960. offsetof(PyCodeObject, co_weakreflist), /* tp_weaklistoffset */
  1961. 0, /* tp_iter */
  1962. 0, /* tp_iternext */
  1963. code_methods, /* tp_methods */
  1964. code_memberlist, /* tp_members */
  1965. code_getsetlist, /* tp_getset */
  1966. 0, /* tp_base */
  1967. 0, /* tp_dict */
  1968. 0, /* tp_descr_get */
  1969. 0, /* tp_descr_set */
  1970. 0, /* tp_dictoffset */
  1971. 0, /* tp_init */
  1972. 0, /* tp_alloc */
  1973. code_new, /* tp_new */
  1974. };
  1975. /******************
  1976. * other API
  1977. ******************/
  1978. PyObject*
  1979. _PyCode_ConstantKey(PyObject *op)
  1980. {
  1981. PyObject *key;
  1982. /* Py_None and Py_Ellipsis are singletons. */
  1983. if (op == Py_None || op == Py_Ellipsis
  1984. || PyLong_CheckExact(op)
  1985. || PyUnicode_CheckExact(op)
  1986. /* code_richcompare() uses _PyCode_ConstantKey() internally */
  1987. || PyCode_Check(op))
  1988. {
  1989. /* Objects of these types are always different from object of other
  1990. * type and from tuples. */
  1991. key = Py_NewRef(op);
  1992. }
  1993. else if (PyBool_Check(op) || PyBytes_CheckExact(op)) {
  1994. /* Make booleans different from integers 0 and 1.
  1995. * Avoid BytesWarning from comparing bytes with strings. */
  1996. key = PyTuple_Pack(2, Py_TYPE(op), op);
  1997. }
  1998. else if (PyFloat_CheckExact(op)) {
  1999. double d = PyFloat_AS_DOUBLE(op);
  2000. /* all we need is to make the tuple different in either the 0.0
  2001. * or -0.0 case from all others, just to avoid the "coercion".
  2002. */
  2003. if (d == 0.0 && copysign(1.0, d) < 0.0)
  2004. key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
  2005. else
  2006. key = PyTuple_Pack(2, Py_TYPE(op), op);
  2007. }
  2008. else if (PyComplex_CheckExact(op)) {
  2009. Py_complex z;
  2010. int real_negzero, imag_negzero;
  2011. /* For the complex case we must make complex(x, 0.)
  2012. different from complex(x, -0.) and complex(0., y)
  2013. different from complex(-0., y), for any x and y.
  2014. All four complex zeros must be distinguished.*/
  2015. z = PyComplex_AsCComplex(op);
  2016. real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
  2017. imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
  2018. /* use True, False and None singleton as tags for the real and imag
  2019. * sign, to make tuples different */
  2020. if (real_negzero && imag_negzero) {
  2021. key = PyTuple_Pack(3, Py_TYPE(op), op, Py_True);
  2022. }
  2023. else if (imag_negzero) {
  2024. key = PyTuple_Pack(3, Py_TYPE(op), op, Py_False);
  2025. }
  2026. else if (real_negzero) {
  2027. key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
  2028. }
  2029. else {
  2030. key = PyTuple_Pack(2, Py_TYPE(op), op);
  2031. }
  2032. }
  2033. else if (PyTuple_CheckExact(op)) {
  2034. Py_ssize_t i, len;
  2035. PyObject *tuple;
  2036. len = PyTuple_GET_SIZE(op);
  2037. tuple = PyTuple_New(len);
  2038. if (tuple == NULL)
  2039. return NULL;
  2040. for (i=0; i < len; i++) {
  2041. PyObject *item, *item_key;
  2042. item = PyTuple_GET_ITEM(op, i);
  2043. item_key = _PyCode_ConstantKey(item);
  2044. if (item_key == NULL) {
  2045. Py_DECREF(tuple);
  2046. return NULL;
  2047. }
  2048. PyTuple_SET_ITEM(tuple, i, item_key);
  2049. }
  2050. key = PyTuple_Pack(2, tuple, op);
  2051. Py_DECREF(tuple);
  2052. }
  2053. else if (PyFrozenSet_CheckExact(op)) {
  2054. Py_ssize_t pos = 0;
  2055. PyObject *item;
  2056. Py_hash_t hash;
  2057. Py_ssize_t i, len;
  2058. PyObject *tuple, *set;
  2059. len = PySet_GET_SIZE(op);
  2060. tuple = PyTuple_New(len);
  2061. if (tuple == NULL)
  2062. return NULL;
  2063. i = 0;
  2064. while (_PySet_NextEntry(op, &pos, &item, &hash)) {
  2065. PyObject *item_key;
  2066. item_key = _PyCode_ConstantKey(item);
  2067. if (item_key == NULL) {
  2068. Py_DECREF(tuple);
  2069. return NULL;
  2070. }
  2071. assert(i < len);
  2072. PyTuple_SET_ITEM(tuple, i, item_key);
  2073. i++;
  2074. }
  2075. set = PyFrozenSet_New(tuple);
  2076. Py_DECREF(tuple);
  2077. if (set == NULL)
  2078. return NULL;
  2079. key = PyTuple_Pack(2, set, op);
  2080. Py_DECREF(set);
  2081. return key;
  2082. }
  2083. else {
  2084. /* for other types, use the object identifier as a unique identifier
  2085. * to ensure that they are seen as unequal. */
  2086. PyObject *obj_id = PyLong_FromVoidPtr(op);
  2087. if (obj_id == NULL)
  2088. return NULL;
  2089. key = PyTuple_Pack(2, obj_id, op);
  2090. Py_DECREF(obj_id);
  2091. }
  2092. return key;
  2093. }
  2094. void
  2095. _PyStaticCode_Fini(PyCodeObject *co)
  2096. {
  2097. deopt_code(co, _PyCode_CODE(co));
  2098. PyMem_Free(co->co_extra);
  2099. if (co->_co_cached != NULL) {
  2100. Py_CLEAR(co->_co_cached->_co_code);
  2101. Py_CLEAR(co->_co_cached->_co_cellvars);
  2102. Py_CLEAR(co->_co_cached->_co_freevars);
  2103. Py_CLEAR(co->_co_cached->_co_varnames);
  2104. PyMem_Free(co->_co_cached);
  2105. co->_co_cached = NULL;
  2106. }
  2107. co->co_extra = NULL;
  2108. if (co->co_weakreflist != NULL) {
  2109. PyObject_ClearWeakRefs((PyObject *)co);
  2110. co->co_weakreflist = NULL;
  2111. }
  2112. free_monitoring_data(co->_co_monitoring);
  2113. co->_co_monitoring = NULL;
  2114. }
  2115. int
  2116. _PyStaticCode_Init(PyCodeObject *co)
  2117. {
  2118. int res = intern_strings(co->co_names);
  2119. if (res < 0) {
  2120. return -1;
  2121. }
  2122. res = intern_string_constants(co->co_consts, NULL);
  2123. if (res < 0) {
  2124. return -1;
  2125. }
  2126. res = intern_strings(co->co_localsplusnames);
  2127. if (res < 0) {
  2128. return -1;
  2129. }
  2130. _PyCode_Quicken(co);
  2131. return 0;
  2132. }
  2133. #define MAX_CODE_UNITS_PER_LOC_ENTRY 8
  2134. PyCodeObject *
  2135. _Py_MakeShimCode(const _PyShimCodeDef *codedef)
  2136. {
  2137. PyObject *name = NULL;
  2138. PyObject *co_code = NULL;
  2139. PyObject *lines = NULL;
  2140. PyCodeObject *codeobj = NULL;
  2141. uint8_t *loc_table = NULL;
  2142. name = _PyUnicode_FromASCII(codedef->cname, strlen(codedef->cname));
  2143. if (name == NULL) {
  2144. goto cleanup;
  2145. }
  2146. co_code = PyBytes_FromStringAndSize(
  2147. (const char *)codedef->code, codedef->codelen);
  2148. if (co_code == NULL) {
  2149. goto cleanup;
  2150. }
  2151. int code_units = codedef->codelen / sizeof(_Py_CODEUNIT);
  2152. int loc_entries = (code_units + MAX_CODE_UNITS_PER_LOC_ENTRY - 1) /
  2153. MAX_CODE_UNITS_PER_LOC_ENTRY;
  2154. loc_table = PyMem_Malloc(loc_entries);
  2155. if (loc_table == NULL) {
  2156. PyErr_NoMemory();
  2157. goto cleanup;
  2158. }
  2159. for (int i = 0; i < loc_entries-1; i++) {
  2160. loc_table[i] = 0x80 | (PY_CODE_LOCATION_INFO_NONE << 3) | 7;
  2161. code_units -= MAX_CODE_UNITS_PER_LOC_ENTRY;
  2162. }
  2163. assert(loc_entries > 0);
  2164. assert(code_units > 0 && code_units <= MAX_CODE_UNITS_PER_LOC_ENTRY);
  2165. loc_table[loc_entries-1] = 0x80 |
  2166. (PY_CODE_LOCATION_INFO_NONE << 3) | (code_units-1);
  2167. lines = PyBytes_FromStringAndSize((const char *)loc_table, loc_entries);
  2168. PyMem_Free(loc_table);
  2169. if (lines == NULL) {
  2170. goto cleanup;
  2171. }
  2172. _Py_DECLARE_STR(shim_name, "<shim>");
  2173. struct _PyCodeConstructor con = {
  2174. .filename = &_Py_STR(shim_name),
  2175. .name = name,
  2176. .qualname = name,
  2177. .flags = CO_NEWLOCALS | CO_OPTIMIZED,
  2178. .code = co_code,
  2179. .firstlineno = 1,
  2180. .linetable = lines,
  2181. .consts = (PyObject *)&_Py_SINGLETON(tuple_empty),
  2182. .names = (PyObject *)&_Py_SINGLETON(tuple_empty),
  2183. .localsplusnames = (PyObject *)&_Py_SINGLETON(tuple_empty),
  2184. .localspluskinds = (PyObject *)&_Py_SINGLETON(bytes_empty),
  2185. .argcount = 0,
  2186. .posonlyargcount = 0,
  2187. .kwonlyargcount = 0,
  2188. .stacksize = codedef->stacksize,
  2189. .exceptiontable = (PyObject *)&_Py_SINGLETON(bytes_empty),
  2190. };
  2191. codeobj = _PyCode_New(&con);
  2192. cleanup:
  2193. Py_XDECREF(name);
  2194. Py_XDECREF(co_code);
  2195. Py_XDECREF(lines);
  2196. return codeobj;
  2197. }