codeobject.c 74 KB

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