You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1416 lines
44 KiB

Merged revisions 72487-72488,72879 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r72487 | jeffrey.yasskin | 2009-05-08 17:51:06 -0400 (Fri, 08 May 2009) | 7 lines PyCode_NewEmpty: Most uses of PyCode_New found by http://www.google.com/codesearch?q=PyCode_New are trying to build an empty code object, usually to put it in a dummy frame object. This patch adds a PyCode_NewEmpty wrapper which lets the user specify just the filename, function name, and first line number, instead of also requiring lots of code internals. ........ r72488 | jeffrey.yasskin | 2009-05-08 18:23:21 -0400 (Fri, 08 May 2009) | 13 lines Issue 5954, PyFrame_GetLineNumber: Most uses of PyCode_Addr2Line (http://www.google.com/codesearch?q=PyCode_Addr2Line) are just trying to get the line number of a specified frame, but there's no way to do that directly. Forcing people to go through the code object makes them know more about the guts of the interpreter than they should need. The remaining uses of PyCode_Addr2Line seem to be getting the line from a traceback (for example, http://www.google.com/codesearch/p?hl=en#u_9_nDrchrw/pygame-1.7.1release/src/base.c&q=PyCode_Addr2Line), which is replaced by the tb_lineno field. So we may be able to deprecate PyCode_Addr2Line entirely for external use. ........ r72879 | jeffrey.yasskin | 2009-05-23 19:23:01 -0400 (Sat, 23 May 2009) | 14 lines Issue #6042: lnotab-based tracing is very complicated and isn't documented very well. There were at least 3 comment blocks purporting to document co_lnotab, and none did a very good job. This patch unifies them into Objects/lnotab_notes.txt which tries to completely capture the current state of affairs. I also discovered that we've attached 2 layers of patches to the basic tracing scheme. The first layer avoids jumping to instructions that don't start a line, to avoid problems in if statements and while loops. The second layer discovered that jumps backward do need to trace at instructions that don't start a line, so it added extra lnotab entries for 'while' and 'for' loops, and added a special case for backward jumps within the same line. I replaced these patches by just treating forward and backward jumps differently. ........
17 years ago
Merged revisions 72487-72488,72879 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r72487 | jeffrey.yasskin | 2009-05-08 17:51:06 -0400 (Fri, 08 May 2009) | 7 lines PyCode_NewEmpty: Most uses of PyCode_New found by http://www.google.com/codesearch?q=PyCode_New are trying to build an empty code object, usually to put it in a dummy frame object. This patch adds a PyCode_NewEmpty wrapper which lets the user specify just the filename, function name, and first line number, instead of also requiring lots of code internals. ........ r72488 | jeffrey.yasskin | 2009-05-08 18:23:21 -0400 (Fri, 08 May 2009) | 13 lines Issue 5954, PyFrame_GetLineNumber: Most uses of PyCode_Addr2Line (http://www.google.com/codesearch?q=PyCode_Addr2Line) are just trying to get the line number of a specified frame, but there's no way to do that directly. Forcing people to go through the code object makes them know more about the guts of the interpreter than they should need. The remaining uses of PyCode_Addr2Line seem to be getting the line from a traceback (for example, http://www.google.com/codesearch/p?hl=en#u_9_nDrchrw/pygame-1.7.1release/src/base.c&q=PyCode_Addr2Line), which is replaced by the tb_lineno field. So we may be able to deprecate PyCode_Addr2Line entirely for external use. ........ r72879 | jeffrey.yasskin | 2009-05-23 19:23:01 -0400 (Sat, 23 May 2009) | 14 lines Issue #6042: lnotab-based tracing is very complicated and isn't documented very well. There were at least 3 comment blocks purporting to document co_lnotab, and none did a very good job. This patch unifies them into Objects/lnotab_notes.txt which tries to completely capture the current state of affairs. I also discovered that we've attached 2 layers of patches to the basic tracing scheme. The first layer avoids jumping to instructions that don't start a line, to avoid problems in if statements and while loops. The second layer discovered that jumps backward do need to trace at instructions that don't start a line, so it added extra lnotab entries for 'while' and 'for' loops, and added a special case for backward jumps within the same line. I replaced these patches by just treating forward and backward jumps differently. ........
17 years ago
Merged revisions 72487-72488,72879 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r72487 | jeffrey.yasskin | 2009-05-08 17:51:06 -0400 (Fri, 08 May 2009) | 7 lines PyCode_NewEmpty: Most uses of PyCode_New found by http://www.google.com/codesearch?q=PyCode_New are trying to build an empty code object, usually to put it in a dummy frame object. This patch adds a PyCode_NewEmpty wrapper which lets the user specify just the filename, function name, and first line number, instead of also requiring lots of code internals. ........ r72488 | jeffrey.yasskin | 2009-05-08 18:23:21 -0400 (Fri, 08 May 2009) | 13 lines Issue 5954, PyFrame_GetLineNumber: Most uses of PyCode_Addr2Line (http://www.google.com/codesearch?q=PyCode_Addr2Line) are just trying to get the line number of a specified frame, but there's no way to do that directly. Forcing people to go through the code object makes them know more about the guts of the interpreter than they should need. The remaining uses of PyCode_Addr2Line seem to be getting the line from a traceback (for example, http://www.google.com/codesearch/p?hl=en#u_9_nDrchrw/pygame-1.7.1release/src/base.c&q=PyCode_Addr2Line), which is replaced by the tb_lineno field. So we may be able to deprecate PyCode_Addr2Line entirely for external use. ........ r72879 | jeffrey.yasskin | 2009-05-23 19:23:01 -0400 (Sat, 23 May 2009) | 14 lines Issue #6042: lnotab-based tracing is very complicated and isn't documented very well. There were at least 3 comment blocks purporting to document co_lnotab, and none did a very good job. This patch unifies them into Objects/lnotab_notes.txt which tries to completely capture the current state of affairs. I also discovered that we've attached 2 layers of patches to the basic tracing scheme. The first layer avoids jumping to instructions that don't start a line, to avoid problems in if statements and while loops. The second layer discovered that jumps backward do need to trace at instructions that don't start a line, so it added extra lnotab entries for 'while' and 'for' loops, and added a special case for backward jumps within the same line. I replaced these patches by just treating forward and backward jumps differently. ........
17 years ago
  1. #include <stdbool.h>
  2. #include "Python.h"
  3. #include "code.h"
  4. #include "opcode.h"
  5. #include "structmember.h" // PyMemberDef
  6. #include "pycore_code.h" // _PyOpcache
  7. #include "pycore_interp.h" // PyInterpreterState.co_extra_freefuncs
  8. #include "pycore_pystate.h" // _PyInterpreterState_GET()
  9. #include "pycore_tuple.h" // _PyTuple_ITEMS()
  10. #include "clinic/codeobject.c.h"
  11. /******************
  12. * generic helpers
  13. ******************/
  14. /* all_name_chars(s): true iff s matches [a-zA-Z0-9_]* */
  15. static int
  16. all_name_chars(PyObject *o)
  17. {
  18. const unsigned char *s, *e;
  19. if (!PyUnicode_IS_ASCII(o))
  20. return 0;
  21. s = PyUnicode_1BYTE_DATA(o);
  22. e = s + PyUnicode_GET_LENGTH(o);
  23. for (; s != e; s++) {
  24. if (!Py_ISALNUM(*s) && *s != '_')
  25. return 0;
  26. }
  27. return 1;
  28. }
  29. static int
  30. intern_strings(PyObject *tuple)
  31. {
  32. Py_ssize_t i;
  33. for (i = PyTuple_GET_SIZE(tuple); --i >= 0; ) {
  34. PyObject *v = PyTuple_GET_ITEM(tuple, i);
  35. if (v == NULL || !PyUnicode_CheckExact(v)) {
  36. PyErr_SetString(PyExc_SystemError,
  37. "non-string found in code slot");
  38. return -1;
  39. }
  40. PyUnicode_InternInPlace(&_PyTuple_ITEMS(tuple)[i]);
  41. }
  42. return 0;
  43. }
  44. /* Intern selected string constants */
  45. static int
  46. intern_string_constants(PyObject *tuple, int *modified)
  47. {
  48. for (Py_ssize_t i = PyTuple_GET_SIZE(tuple); --i >= 0; ) {
  49. PyObject *v = PyTuple_GET_ITEM(tuple, i);
  50. if (PyUnicode_CheckExact(v)) {
  51. if (PyUnicode_READY(v) == -1) {
  52. return -1;
  53. }
  54. if (all_name_chars(v)) {
  55. PyObject *w = v;
  56. PyUnicode_InternInPlace(&v);
  57. if (w != v) {
  58. PyTuple_SET_ITEM(tuple, i, v);
  59. if (modified) {
  60. *modified = 1;
  61. }
  62. }
  63. }
  64. }
  65. else if (PyTuple_CheckExact(v)) {
  66. if (intern_string_constants(v, NULL) < 0) {
  67. return -1;
  68. }
  69. }
  70. else if (PyFrozenSet_CheckExact(v)) {
  71. PyObject *w = v;
  72. PyObject *tmp = PySequence_Tuple(v);
  73. if (tmp == NULL) {
  74. return -1;
  75. }
  76. int tmp_modified = 0;
  77. if (intern_string_constants(tmp, &tmp_modified) < 0) {
  78. Py_DECREF(tmp);
  79. return -1;
  80. }
  81. if (tmp_modified) {
  82. v = PyFrozenSet_New(tmp);
  83. if (v == NULL) {
  84. Py_DECREF(tmp);
  85. return -1;
  86. }
  87. PyTuple_SET_ITEM(tuple, i, v);
  88. Py_DECREF(w);
  89. if (modified) {
  90. *modified = 1;
  91. }
  92. }
  93. Py_DECREF(tmp);
  94. }
  95. }
  96. return 0;
  97. }
  98. /* Return a shallow copy of a tuple that is
  99. guaranteed to contain exact strings, by converting string subclasses
  100. to exact strings and complaining if a non-string is found. */
  101. static PyObject*
  102. validate_and_copy_tuple(PyObject *tup)
  103. {
  104. PyObject *newtuple;
  105. PyObject *item;
  106. Py_ssize_t i, len;
  107. len = PyTuple_GET_SIZE(tup);
  108. newtuple = PyTuple_New(len);
  109. if (newtuple == NULL)
  110. return NULL;
  111. for (i = 0; i < len; i++) {
  112. item = PyTuple_GET_ITEM(tup, i);
  113. if (PyUnicode_CheckExact(item)) {
  114. Py_INCREF(item);
  115. }
  116. else if (!PyUnicode_Check(item)) {
  117. PyErr_Format(
  118. PyExc_TypeError,
  119. "name tuples must contain only "
  120. "strings, not '%.500s'",
  121. Py_TYPE(item)->tp_name);
  122. Py_DECREF(newtuple);
  123. return NULL;
  124. }
  125. else {
  126. item = _PyUnicode_Copy(item);
  127. if (item == NULL) {
  128. Py_DECREF(newtuple);
  129. return NULL;
  130. }
  131. }
  132. PyTuple_SET_ITEM(newtuple, i, item);
  133. }
  134. return newtuple;
  135. }
  136. /******************
  137. * the "constructors"
  138. ******************/
  139. PyCodeObject *
  140. PyCode_NewWithPosOnlyArgs(int argcount, int posonlyargcount, int kwonlyargcount,
  141. int nlocals, int stacksize, int flags,
  142. PyObject *code, PyObject *consts, PyObject *names,
  143. PyObject *varnames, PyObject *freevars, PyObject *cellvars,
  144. PyObject *filename, PyObject *name, int firstlineno,
  145. PyObject *linetable, PyObject *exceptiontable)
  146. {
  147. PyCodeObject *co;
  148. Py_ssize_t *cell2arg = NULL;
  149. Py_ssize_t i, n_cellvars, n_varnames, total_args;
  150. /* Check argument types */
  151. if (argcount < posonlyargcount || posonlyargcount < 0 ||
  152. kwonlyargcount < 0 || nlocals < 0 ||
  153. stacksize < 0 || flags < 0 ||
  154. code == NULL || !PyBytes_Check(code) ||
  155. consts == NULL || !PyTuple_Check(consts) ||
  156. names == NULL || !PyTuple_Check(names) ||
  157. varnames == NULL || !PyTuple_Check(varnames) ||
  158. freevars == NULL || !PyTuple_Check(freevars) ||
  159. cellvars == NULL || !PyTuple_Check(cellvars) ||
  160. name == NULL || !PyUnicode_Check(name) ||
  161. filename == NULL || !PyUnicode_Check(filename) ||
  162. linetable == NULL || !PyBytes_Check(linetable) ||
  163. exceptiontable == NULL || !PyBytes_Check(exceptiontable)) {
  164. PyErr_BadInternalCall();
  165. return NULL;
  166. }
  167. /* Ensure that strings are ready Unicode string */
  168. if (PyUnicode_READY(name) < 0) {
  169. return NULL;
  170. }
  171. if (PyUnicode_READY(filename) < 0) {
  172. return NULL;
  173. }
  174. if (intern_strings(names) < 0) {
  175. return NULL;
  176. }
  177. if (intern_strings(varnames) < 0) {
  178. return NULL;
  179. }
  180. if (intern_strings(freevars) < 0) {
  181. return NULL;
  182. }
  183. if (intern_strings(cellvars) < 0) {
  184. return NULL;
  185. }
  186. if (intern_string_constants(consts, NULL) < 0) {
  187. return NULL;
  188. }
  189. /* Make sure that code is indexable with an int, this is
  190. a long running assumption in ceval.c and many parts of
  191. the interpreter. */
  192. if (PyBytes_GET_SIZE(code) > INT_MAX) {
  193. PyErr_SetString(PyExc_OverflowError, "co_code larger than INT_MAX");
  194. return NULL;
  195. }
  196. /* Check for any inner or outer closure references */
  197. n_cellvars = PyTuple_GET_SIZE(cellvars);
  198. if (!n_cellvars && !PyTuple_GET_SIZE(freevars)) {
  199. flags |= CO_NOFREE;
  200. } else {
  201. flags &= ~CO_NOFREE;
  202. }
  203. n_varnames = PyTuple_GET_SIZE(varnames);
  204. if (argcount <= n_varnames && kwonlyargcount <= n_varnames) {
  205. /* Never overflows. */
  206. total_args = (Py_ssize_t)argcount + (Py_ssize_t)kwonlyargcount +
  207. ((flags & CO_VARARGS) != 0) + ((flags & CO_VARKEYWORDS) != 0);
  208. }
  209. else {
  210. total_args = n_varnames + 1;
  211. }
  212. if (total_args > n_varnames) {
  213. PyErr_SetString(PyExc_ValueError, "code: varnames is too small");
  214. return NULL;
  215. }
  216. /* Create mapping between cells and arguments if needed. */
  217. if (n_cellvars) {
  218. bool used_cell2arg = false;
  219. cell2arg = PyMem_NEW(Py_ssize_t, n_cellvars);
  220. if (cell2arg == NULL) {
  221. PyErr_NoMemory();
  222. return NULL;
  223. }
  224. /* Find cells which are also arguments. */
  225. for (i = 0; i < n_cellvars; i++) {
  226. Py_ssize_t j;
  227. PyObject *cell = PyTuple_GET_ITEM(cellvars, i);
  228. cell2arg[i] = CO_CELL_NOT_AN_ARG;
  229. for (j = 0; j < total_args; j++) {
  230. PyObject *arg = PyTuple_GET_ITEM(varnames, j);
  231. int cmp = PyUnicode_Compare(cell, arg);
  232. if (cmp == -1 && PyErr_Occurred()) {
  233. PyMem_Free(cell2arg);
  234. return NULL;
  235. }
  236. if (cmp == 0) {
  237. cell2arg[i] = j;
  238. used_cell2arg = true;
  239. break;
  240. }
  241. }
  242. }
  243. if (!used_cell2arg) {
  244. PyMem_Free(cell2arg);
  245. cell2arg = NULL;
  246. }
  247. }
  248. co = PyObject_New(PyCodeObject, &PyCode_Type);
  249. if (co == NULL) {
  250. if (cell2arg)
  251. PyMem_Free(cell2arg);
  252. return NULL;
  253. }
  254. co->co_argcount = argcount;
  255. co->co_posonlyargcount = posonlyargcount;
  256. co->co_kwonlyargcount = kwonlyargcount;
  257. co->co_nlocals = nlocals;
  258. co->co_nlocalsplus = nlocals +
  259. (int)PyTuple_GET_SIZE(freevars) + (int)PyTuple_GET_SIZE(cellvars);
  260. co->co_stacksize = stacksize;
  261. co->co_flags = flags;
  262. Py_INCREF(code);
  263. co->co_code = code;
  264. Py_INCREF(consts);
  265. co->co_consts = consts;
  266. Py_INCREF(names);
  267. co->co_names = names;
  268. Py_INCREF(varnames);
  269. co->co_varnames = varnames;
  270. Py_INCREF(freevars);
  271. co->co_freevars = freevars;
  272. Py_INCREF(cellvars);
  273. co->co_cellvars = cellvars;
  274. co->co_cell2arg = cell2arg;
  275. Py_INCREF(filename);
  276. co->co_filename = filename;
  277. Py_INCREF(name);
  278. co->co_name = name;
  279. co->co_firstlineno = firstlineno;
  280. Py_INCREF(linetable);
  281. co->co_linetable = linetable;
  282. Py_INCREF(exceptiontable);
  283. co->co_exceptiontable = exceptiontable;
  284. co->co_weakreflist = NULL;
  285. co->co_extra = NULL;
  286. co->co_opcache_map = NULL;
  287. co->co_opcache = NULL;
  288. co->co_opcache_flag = 0;
  289. co->co_opcache_size = 0;
  290. return co;
  291. }
  292. PyCodeObject *
  293. PyCode_New(int argcount, int kwonlyargcount,
  294. int nlocals, int stacksize, int flags,
  295. PyObject *code, PyObject *consts, PyObject *names,
  296. PyObject *varnames, PyObject *freevars, PyObject *cellvars,
  297. PyObject *filename, PyObject *name, int firstlineno,
  298. PyObject *linetable, PyObject *exceptiontable)
  299. {
  300. return PyCode_NewWithPosOnlyArgs(argcount, 0, kwonlyargcount, nlocals,
  301. stacksize, flags, code, consts, names,
  302. varnames, freevars, cellvars, filename,
  303. name, firstlineno, linetable, exceptiontable);
  304. }
  305. PyCodeObject *
  306. PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno)
  307. {
  308. static PyObject *emptystring = NULL;
  309. static PyObject *nulltuple = NULL;
  310. PyObject *filename_ob = NULL;
  311. PyObject *funcname_ob = NULL;
  312. PyCodeObject *result = NULL;
  313. if (emptystring == NULL) {
  314. emptystring = PyBytes_FromString("");
  315. if (emptystring == NULL)
  316. goto failed;
  317. }
  318. if (nulltuple == NULL) {
  319. nulltuple = PyTuple_New(0);
  320. if (nulltuple == NULL)
  321. goto failed;
  322. }
  323. funcname_ob = PyUnicode_FromString(funcname);
  324. if (funcname_ob == NULL)
  325. goto failed;
  326. filename_ob = PyUnicode_DecodeFSDefault(filename);
  327. if (filename_ob == NULL)
  328. goto failed;
  329. result = PyCode_NewWithPosOnlyArgs(
  330. 0, /* argcount */
  331. 0, /* posonlyargcount */
  332. 0, /* kwonlyargcount */
  333. 0, /* nlocals */
  334. 0, /* stacksize */
  335. 0, /* flags */
  336. emptystring, /* code */
  337. nulltuple, /* consts */
  338. nulltuple, /* names */
  339. nulltuple, /* varnames */
  340. nulltuple, /* freevars */
  341. nulltuple, /* cellvars */
  342. filename_ob, /* filename */
  343. funcname_ob, /* name */
  344. firstlineno, /* firstlineno */
  345. emptystring, /* linetable */
  346. emptystring /* exception table */
  347. );
  348. failed:
  349. Py_XDECREF(funcname_ob);
  350. Py_XDECREF(filename_ob);
  351. return result;
  352. }
  353. /******************
  354. * the line table (co_linetable)
  355. ******************/
  356. /* Use co_linetable to compute the line number from a bytecode index, addrq. See
  357. lnotab_notes.txt for the details of the lnotab representation.
  358. */
  359. int
  360. PyCode_Addr2Line(PyCodeObject *co, int addrq)
  361. {
  362. if (addrq < 0) {
  363. return co->co_firstlineno;
  364. }
  365. assert(addrq >= 0 && addrq < PyBytes_GET_SIZE(co->co_code));
  366. PyCodeAddressRange bounds;
  367. _PyCode_InitAddressRange(co, &bounds);
  368. return _PyCode_CheckLineNumber(addrq, &bounds);
  369. }
  370. void
  371. PyLineTable_InitAddressRange(char *linetable, Py_ssize_t length, int firstlineno, PyCodeAddressRange *range)
  372. {
  373. range->opaque.lo_next = linetable;
  374. range->opaque.limit = range->opaque.lo_next + length;
  375. range->ar_start = -1;
  376. range->ar_end = 0;
  377. range->opaque.computed_line = firstlineno;
  378. range->ar_line = -1;
  379. }
  380. int
  381. _PyCode_InitAddressRange(PyCodeObject* co, PyCodeAddressRange *bounds)
  382. {
  383. char *linetable = PyBytes_AS_STRING(co->co_linetable);
  384. Py_ssize_t length = PyBytes_GET_SIZE(co->co_linetable);
  385. PyLineTable_InitAddressRange(linetable, length, co->co_firstlineno, bounds);
  386. return bounds->ar_line;
  387. }
  388. /* Update *bounds to describe the first and one-past-the-last instructions in
  389. the same line as lasti. Return the number of that line, or -1 if lasti is out of bounds. */
  390. int
  391. _PyCode_CheckLineNumber(int lasti, PyCodeAddressRange *bounds)
  392. {
  393. while (bounds->ar_end <= lasti) {
  394. if (!PyLineTable_NextAddressRange(bounds)) {
  395. return -1;
  396. }
  397. }
  398. while (bounds->ar_start > lasti) {
  399. if (!PyLineTable_PreviousAddressRange(bounds)) {
  400. return -1;
  401. }
  402. }
  403. return bounds->ar_line;
  404. }
  405. static void
  406. retreat(PyCodeAddressRange *bounds)
  407. {
  408. int ldelta = ((signed char *)bounds->opaque.lo_next)[-1];
  409. if (ldelta == -128) {
  410. ldelta = 0;
  411. }
  412. bounds->opaque.computed_line -= ldelta;
  413. bounds->opaque.lo_next -= 2;
  414. bounds->ar_end = bounds->ar_start;
  415. bounds->ar_start -= ((unsigned char *)bounds->opaque.lo_next)[-2];
  416. ldelta = ((signed char *)bounds->opaque.lo_next)[-1];
  417. if (ldelta == -128) {
  418. bounds->ar_line = -1;
  419. }
  420. else {
  421. bounds->ar_line = bounds->opaque.computed_line;
  422. }
  423. }
  424. static void
  425. advance(PyCodeAddressRange *bounds)
  426. {
  427. bounds->ar_start = bounds->ar_end;
  428. int delta = ((unsigned char *)bounds->opaque.lo_next)[0];
  429. bounds->ar_end += delta;
  430. int ldelta = ((signed char *)bounds->opaque.lo_next)[1];
  431. bounds->opaque.lo_next += 2;
  432. if (ldelta == -128) {
  433. bounds->ar_line = -1;
  434. }
  435. else {
  436. bounds->opaque.computed_line += ldelta;
  437. bounds->ar_line = bounds->opaque.computed_line;
  438. }
  439. }
  440. static inline int
  441. at_end(PyCodeAddressRange *bounds) {
  442. return bounds->opaque.lo_next >= bounds->opaque.limit;
  443. }
  444. int
  445. PyLineTable_PreviousAddressRange(PyCodeAddressRange *range)
  446. {
  447. if (range->ar_start <= 0) {
  448. return 0;
  449. }
  450. retreat(range);
  451. while (range->ar_start == range->ar_end) {
  452. assert(range->ar_start > 0);
  453. retreat(range);
  454. }
  455. return 1;
  456. }
  457. int
  458. PyLineTable_NextAddressRange(PyCodeAddressRange *range)
  459. {
  460. if (at_end(range)) {
  461. return 0;
  462. }
  463. advance(range);
  464. while (range->ar_start == range->ar_end) {
  465. assert(!at_end(range));
  466. advance(range);
  467. }
  468. return 1;
  469. }
  470. static int
  471. emit_pair(PyObject **bytes, int *offset, int a, int b)
  472. {
  473. Py_ssize_t len = PyBytes_GET_SIZE(*bytes);
  474. if (*offset + 2 >= len) {
  475. if (_PyBytes_Resize(bytes, len * 2) < 0)
  476. return 0;
  477. }
  478. unsigned char *lnotab = (unsigned char *) PyBytes_AS_STRING(*bytes);
  479. lnotab += *offset;
  480. *lnotab++ = a;
  481. *lnotab++ = b;
  482. *offset += 2;
  483. return 1;
  484. }
  485. static int
  486. emit_delta(PyObject **bytes, int bdelta, int ldelta, int *offset)
  487. {
  488. while (bdelta > 255) {
  489. if (!emit_pair(bytes, offset, 255, 0)) {
  490. return 0;
  491. }
  492. bdelta -= 255;
  493. }
  494. while (ldelta > 127) {
  495. if (!emit_pair(bytes, offset, bdelta, 127)) {
  496. return 0;
  497. }
  498. bdelta = 0;
  499. ldelta -= 127;
  500. }
  501. while (ldelta < -128) {
  502. if (!emit_pair(bytes, offset, bdelta, -128)) {
  503. return 0;
  504. }
  505. bdelta = 0;
  506. ldelta += 128;
  507. }
  508. return emit_pair(bytes, offset, bdelta, ldelta);
  509. }
  510. static PyObject *
  511. decode_linetable(PyCodeObject *code)
  512. {
  513. PyCodeAddressRange bounds;
  514. PyObject *bytes;
  515. int table_offset = 0;
  516. int code_offset = 0;
  517. int line = code->co_firstlineno;
  518. bytes = PyBytes_FromStringAndSize(NULL, 64);
  519. if (bytes == NULL) {
  520. return NULL;
  521. }
  522. _PyCode_InitAddressRange(code, &bounds);
  523. while (PyLineTable_NextAddressRange(&bounds)) {
  524. if (bounds.opaque.computed_line != line) {
  525. int bdelta = bounds.ar_start - code_offset;
  526. int ldelta = bounds.opaque.computed_line - line;
  527. if (!emit_delta(&bytes, bdelta, ldelta, &table_offset)) {
  528. Py_DECREF(bytes);
  529. return NULL;
  530. }
  531. code_offset = bounds.ar_start;
  532. line = bounds.opaque.computed_line;
  533. }
  534. }
  535. _PyBytes_Resize(&bytes, table_offset);
  536. return bytes;
  537. }
  538. typedef struct {
  539. PyObject_HEAD
  540. PyCodeObject *li_code;
  541. PyCodeAddressRange li_line;
  542. char *li_end;
  543. } lineiterator;
  544. static void
  545. lineiter_dealloc(lineiterator *li)
  546. {
  547. Py_DECREF(li->li_code);
  548. Py_TYPE(li)->tp_free(li);
  549. }
  550. static PyObject *
  551. lineiter_next(lineiterator *li)
  552. {
  553. PyCodeAddressRange *bounds = &li->li_line;
  554. if (!PyLineTable_NextAddressRange(bounds)) {
  555. return NULL;
  556. }
  557. PyObject *start = NULL;
  558. PyObject *end = NULL;
  559. PyObject *line = NULL;
  560. PyObject *result = PyTuple_New(3);
  561. start = PyLong_FromLong(bounds->ar_start);
  562. end = PyLong_FromLong(bounds->ar_end);
  563. if (bounds->ar_line < 0) {
  564. Py_INCREF(Py_None);
  565. line = Py_None;
  566. }
  567. else {
  568. line = PyLong_FromLong(bounds->ar_line);
  569. }
  570. if (result == NULL || start == NULL || end == NULL || line == NULL) {
  571. goto error;
  572. }
  573. PyTuple_SET_ITEM(result, 0, start);
  574. PyTuple_SET_ITEM(result, 1, end);
  575. PyTuple_SET_ITEM(result, 2, line);
  576. return result;
  577. error:
  578. Py_XDECREF(start);
  579. Py_XDECREF(end);
  580. Py_XDECREF(line);
  581. Py_XDECREF(result);
  582. return result;
  583. }
  584. static PyTypeObject LineIterator = {
  585. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  586. "line_iterator", /* tp_name */
  587. sizeof(lineiterator), /* tp_basicsize */
  588. 0, /* tp_itemsize */
  589. /* methods */
  590. (destructor)lineiter_dealloc, /* tp_dealloc */
  591. 0, /* tp_vectorcall_offset */
  592. 0, /* tp_getattr */
  593. 0, /* tp_setattr */
  594. 0, /* tp_as_async */
  595. 0, /* tp_repr */
  596. 0, /* tp_as_number */
  597. 0, /* tp_as_sequence */
  598. 0, /* tp_as_mapping */
  599. 0, /* tp_hash */
  600. 0, /* tp_call */
  601. 0, /* tp_str */
  602. 0, /* tp_getattro */
  603. 0, /* tp_setattro */
  604. 0, /* tp_as_buffer */
  605. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
  606. 0, /* tp_doc */
  607. 0, /* tp_traverse */
  608. 0, /* tp_clear */
  609. 0, /* tp_richcompare */
  610. 0, /* tp_weaklistoffset */
  611. PyObject_SelfIter, /* tp_iter */
  612. (iternextfunc)lineiter_next, /* tp_iternext */
  613. 0, /* tp_methods */
  614. 0, /* tp_members */
  615. 0, /* tp_getset */
  616. 0, /* tp_base */
  617. 0, /* tp_dict */
  618. 0, /* tp_descr_get */
  619. 0, /* tp_descr_set */
  620. 0, /* tp_dictoffset */
  621. 0, /* tp_init */
  622. 0, /* tp_alloc */
  623. 0, /* tp_new */
  624. PyObject_Del, /* tp_free */
  625. };
  626. static lineiterator *
  627. new_linesiterator(PyCodeObject *code)
  628. {
  629. lineiterator *li = (lineiterator *)PyType_GenericAlloc(&LineIterator, 0);
  630. if (li == NULL) {
  631. return NULL;
  632. }
  633. Py_INCREF(code);
  634. li->li_code = code;
  635. _PyCode_InitAddressRange(code, &li->li_line);
  636. return li;
  637. }
  638. /******************
  639. * the opcache
  640. ******************/
  641. int
  642. _PyCode_InitOpcache(PyCodeObject *co)
  643. {
  644. Py_ssize_t co_size = PyBytes_Size(co->co_code) / sizeof(_Py_CODEUNIT);
  645. co->co_opcache_map = (unsigned char *)PyMem_Calloc(co_size, 1);
  646. if (co->co_opcache_map == NULL) {
  647. return -1;
  648. }
  649. _Py_CODEUNIT *opcodes = (_Py_CODEUNIT*)PyBytes_AS_STRING(co->co_code);
  650. Py_ssize_t opts = 0;
  651. for (Py_ssize_t i = 0; i < co_size;) {
  652. unsigned char opcode = _Py_OPCODE(opcodes[i]);
  653. i++; // 'i' is now aligned to (next_instr - first_instr)
  654. // TODO: LOAD_METHOD
  655. if (opcode == LOAD_GLOBAL || opcode == LOAD_ATTR) {
  656. opts++;
  657. co->co_opcache_map[i] = (unsigned char)opts;
  658. if (opts > 254) {
  659. break;
  660. }
  661. }
  662. }
  663. if (opts) {
  664. co->co_opcache = (_PyOpcache *)PyMem_Calloc(opts, sizeof(_PyOpcache));
  665. if (co->co_opcache == NULL) {
  666. PyMem_Free(co->co_opcache_map);
  667. return -1;
  668. }
  669. }
  670. else {
  671. PyMem_Free(co->co_opcache_map);
  672. co->co_opcache_map = NULL;
  673. co->co_opcache = NULL;
  674. }
  675. co->co_opcache_size = (unsigned char)opts;
  676. return 0;
  677. }
  678. /******************
  679. * "extra" frame eval info (see PEP 523)
  680. ******************/
  681. /* Holder for co_extra information */
  682. typedef struct {
  683. Py_ssize_t ce_size;
  684. void *ce_extras[1];
  685. } _PyCodeObjectExtra;
  686. int
  687. _PyCode_GetExtra(PyObject *code, Py_ssize_t index, void **extra)
  688. {
  689. if (!PyCode_Check(code)) {
  690. PyErr_BadInternalCall();
  691. return -1;
  692. }
  693. PyCodeObject *o = (PyCodeObject*) code;
  694. _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra*) o->co_extra;
  695. if (co_extra == NULL || co_extra->ce_size <= index) {
  696. *extra = NULL;
  697. return 0;
  698. }
  699. *extra = co_extra->ce_extras[index];
  700. return 0;
  701. }
  702. int
  703. _PyCode_SetExtra(PyObject *code, Py_ssize_t index, void *extra)
  704. {
  705. PyInterpreterState *interp = _PyInterpreterState_GET();
  706. if (!PyCode_Check(code) || index < 0 ||
  707. index >= interp->co_extra_user_count) {
  708. PyErr_BadInternalCall();
  709. return -1;
  710. }
  711. PyCodeObject *o = (PyCodeObject*) code;
  712. _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra *) o->co_extra;
  713. if (co_extra == NULL || co_extra->ce_size <= index) {
  714. Py_ssize_t i = (co_extra == NULL ? 0 : co_extra->ce_size);
  715. co_extra = PyMem_Realloc(
  716. co_extra,
  717. sizeof(_PyCodeObjectExtra) +
  718. (interp->co_extra_user_count-1) * sizeof(void*));
  719. if (co_extra == NULL) {
  720. return -1;
  721. }
  722. for (; i < interp->co_extra_user_count; i++) {
  723. co_extra->ce_extras[i] = NULL;
  724. }
  725. co_extra->ce_size = interp->co_extra_user_count;
  726. o->co_extra = co_extra;
  727. }
  728. if (co_extra->ce_extras[index] != NULL) {
  729. freefunc free = interp->co_extra_freefuncs[index];
  730. if (free != NULL) {
  731. free(co_extra->ce_extras[index]);
  732. }
  733. }
  734. co_extra->ce_extras[index] = extra;
  735. return 0;
  736. }
  737. /******************
  738. * PyCode_Type
  739. ******************/
  740. /*[clinic input]
  741. class code "PyCodeObject *" "&PyCode_Type"
  742. [clinic start generated code]*/
  743. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=78aa5d576683bb4b]*/
  744. /*[clinic input]
  745. @classmethod
  746. code.__new__ as code_new
  747. argcount: int
  748. posonlyargcount: int
  749. kwonlyargcount: int
  750. nlocals: int
  751. stacksize: int
  752. flags: int
  753. codestring as code: object(subclass_of="&PyBytes_Type")
  754. constants as consts: object(subclass_of="&PyTuple_Type")
  755. names: object(subclass_of="&PyTuple_Type")
  756. varnames: object(subclass_of="&PyTuple_Type")
  757. filename: unicode
  758. name: unicode
  759. firstlineno: int
  760. linetable: object(subclass_of="&PyBytes_Type")
  761. exceptiontable: object(subclass_of="&PyBytes_Type")
  762. freevars: object(subclass_of="&PyTuple_Type", c_default="NULL") = ()
  763. cellvars: object(subclass_of="&PyTuple_Type", c_default="NULL") = ()
  764. /
  765. Create a code object. Not for the faint of heart.
  766. [clinic start generated code]*/
  767. static PyObject *
  768. code_new_impl(PyTypeObject *type, int argcount, int posonlyargcount,
  769. int kwonlyargcount, int nlocals, int stacksize, int flags,
  770. PyObject *code, PyObject *consts, PyObject *names,
  771. PyObject *varnames, PyObject *filename, PyObject *name,
  772. int firstlineno, PyObject *linetable, PyObject *exceptiontable,
  773. PyObject *freevars, PyObject *cellvars)
  774. /*[clinic end generated code: output=a3899259c3b4cace input=f823c686da4b3a03]*/
  775. {
  776. PyObject *co = NULL;
  777. PyObject *ournames = NULL;
  778. PyObject *ourvarnames = NULL;
  779. PyObject *ourfreevars = NULL;
  780. PyObject *ourcellvars = NULL;
  781. if (PySys_Audit("code.__new__", "OOOiiiiii",
  782. code, filename, name, argcount, posonlyargcount,
  783. kwonlyargcount, nlocals, stacksize, flags) < 0) {
  784. goto cleanup;
  785. }
  786. if (argcount < 0) {
  787. PyErr_SetString(
  788. PyExc_ValueError,
  789. "code: argcount must not be negative");
  790. goto cleanup;
  791. }
  792. if (posonlyargcount < 0) {
  793. PyErr_SetString(
  794. PyExc_ValueError,
  795. "code: posonlyargcount must not be negative");
  796. goto cleanup;
  797. }
  798. if (kwonlyargcount < 0) {
  799. PyErr_SetString(
  800. PyExc_ValueError,
  801. "code: kwonlyargcount must not be negative");
  802. goto cleanup;
  803. }
  804. if (nlocals < 0) {
  805. PyErr_SetString(
  806. PyExc_ValueError,
  807. "code: nlocals must not be negative");
  808. goto cleanup;
  809. }
  810. ournames = validate_and_copy_tuple(names);
  811. if (ournames == NULL)
  812. goto cleanup;
  813. ourvarnames = validate_and_copy_tuple(varnames);
  814. if (ourvarnames == NULL)
  815. goto cleanup;
  816. if (freevars)
  817. ourfreevars = validate_and_copy_tuple(freevars);
  818. else
  819. ourfreevars = PyTuple_New(0);
  820. if (ourfreevars == NULL)
  821. goto cleanup;
  822. if (cellvars)
  823. ourcellvars = validate_and_copy_tuple(cellvars);
  824. else
  825. ourcellvars = PyTuple_New(0);
  826. if (ourcellvars == NULL)
  827. goto cleanup;
  828. co = (PyObject *)PyCode_NewWithPosOnlyArgs(argcount, posonlyargcount,
  829. kwonlyargcount,
  830. nlocals, stacksize, flags,
  831. code, consts, ournames,
  832. ourvarnames, ourfreevars,
  833. ourcellvars, filename,
  834. name, firstlineno, linetable,
  835. exceptiontable
  836. );
  837. cleanup:
  838. Py_XDECREF(ournames);
  839. Py_XDECREF(ourvarnames);
  840. Py_XDECREF(ourfreevars);
  841. Py_XDECREF(ourcellvars);
  842. return co;
  843. }
  844. static void
  845. code_dealloc(PyCodeObject *co)
  846. {
  847. if (co->co_opcache != NULL) {
  848. PyMem_Free(co->co_opcache);
  849. }
  850. if (co->co_opcache_map != NULL) {
  851. PyMem_Free(co->co_opcache_map);
  852. }
  853. co->co_opcache_flag = 0;
  854. co->co_opcache_size = 0;
  855. if (co->co_extra != NULL) {
  856. PyInterpreterState *interp = _PyInterpreterState_GET();
  857. _PyCodeObjectExtra *co_extra = co->co_extra;
  858. for (Py_ssize_t i = 0; i < co_extra->ce_size; i++) {
  859. freefunc free_extra = interp->co_extra_freefuncs[i];
  860. if (free_extra != NULL) {
  861. free_extra(co_extra->ce_extras[i]);
  862. }
  863. }
  864. PyMem_Free(co_extra);
  865. }
  866. Py_XDECREF(co->co_code);
  867. Py_XDECREF(co->co_consts);
  868. Py_XDECREF(co->co_names);
  869. Py_XDECREF(co->co_varnames);
  870. Py_XDECREF(co->co_freevars);
  871. Py_XDECREF(co->co_cellvars);
  872. Py_XDECREF(co->co_filename);
  873. Py_XDECREF(co->co_name);
  874. Py_XDECREF(co->co_linetable);
  875. Py_XDECREF(co->co_exceptiontable);
  876. if (co->co_cell2arg != NULL)
  877. PyMem_Free(co->co_cell2arg);
  878. if (co->co_weakreflist != NULL)
  879. PyObject_ClearWeakRefs((PyObject*)co);
  880. PyObject_Free(co);
  881. }
  882. static PyObject *
  883. code_repr(PyCodeObject *co)
  884. {
  885. int lineno;
  886. if (co->co_firstlineno != 0)
  887. lineno = co->co_firstlineno;
  888. else
  889. lineno = -1;
  890. if (co->co_filename && PyUnicode_Check(co->co_filename)) {
  891. return PyUnicode_FromFormat(
  892. "<code object %U at %p, file \"%U\", line %d>",
  893. co->co_name, co, co->co_filename, lineno);
  894. } else {
  895. return PyUnicode_FromFormat(
  896. "<code object %U at %p, file ???, line %d>",
  897. co->co_name, co, lineno);
  898. }
  899. }
  900. static PyObject *
  901. code_richcompare(PyObject *self, PyObject *other, int op)
  902. {
  903. PyCodeObject *co, *cp;
  904. int eq;
  905. PyObject *consts1, *consts2;
  906. PyObject *res;
  907. if ((op != Py_EQ && op != Py_NE) ||
  908. !PyCode_Check(self) ||
  909. !PyCode_Check(other)) {
  910. Py_RETURN_NOTIMPLEMENTED;
  911. }
  912. co = (PyCodeObject *)self;
  913. cp = (PyCodeObject *)other;
  914. eq = PyObject_RichCompareBool(co->co_name, cp->co_name, Py_EQ);
  915. if (!eq) goto unequal;
  916. eq = co->co_argcount == cp->co_argcount;
  917. if (!eq) goto unequal;
  918. eq = co->co_posonlyargcount == cp->co_posonlyargcount;
  919. if (!eq) goto unequal;
  920. eq = co->co_kwonlyargcount == cp->co_kwonlyargcount;
  921. if (!eq) goto unequal;
  922. eq = co->co_nlocals == cp->co_nlocals;
  923. if (!eq) goto unequal;
  924. eq = co->co_flags == cp->co_flags;
  925. if (!eq) goto unequal;
  926. eq = co->co_firstlineno == cp->co_firstlineno;
  927. if (!eq) goto unequal;
  928. eq = PyObject_RichCompareBool(co->co_code, cp->co_code, Py_EQ);
  929. if (eq <= 0) goto unequal;
  930. /* compare constants */
  931. consts1 = _PyCode_ConstantKey(co->co_consts);
  932. if (!consts1)
  933. return NULL;
  934. consts2 = _PyCode_ConstantKey(cp->co_consts);
  935. if (!consts2) {
  936. Py_DECREF(consts1);
  937. return NULL;
  938. }
  939. eq = PyObject_RichCompareBool(consts1, consts2, Py_EQ);
  940. Py_DECREF(consts1);
  941. Py_DECREF(consts2);
  942. if (eq <= 0) goto unequal;
  943. eq = PyObject_RichCompareBool(co->co_names, cp->co_names, Py_EQ);
  944. if (eq <= 0) goto unequal;
  945. eq = PyObject_RichCompareBool(co->co_varnames, cp->co_varnames, Py_EQ);
  946. if (eq <= 0) goto unequal;
  947. eq = PyObject_RichCompareBool(co->co_freevars, cp->co_freevars, Py_EQ);
  948. if (eq <= 0) goto unequal;
  949. eq = PyObject_RichCompareBool(co->co_cellvars, cp->co_cellvars, Py_EQ);
  950. if (eq <= 0) goto unequal;
  951. if (op == Py_EQ)
  952. res = Py_True;
  953. else
  954. res = Py_False;
  955. goto done;
  956. unequal:
  957. if (eq < 0)
  958. return NULL;
  959. if (op == Py_NE)
  960. res = Py_True;
  961. else
  962. res = Py_False;
  963. done:
  964. Py_INCREF(res);
  965. return res;
  966. }
  967. static Py_hash_t
  968. code_hash(PyCodeObject *co)
  969. {
  970. Py_hash_t h, h0, h1, h2, h3, h4, h5, h6;
  971. h0 = PyObject_Hash(co->co_name);
  972. if (h0 == -1) return -1;
  973. h1 = PyObject_Hash(co->co_code);
  974. if (h1 == -1) return -1;
  975. h2 = PyObject_Hash(co->co_consts);
  976. if (h2 == -1) return -1;
  977. h3 = PyObject_Hash(co->co_names);
  978. if (h3 == -1) return -1;
  979. h4 = PyObject_Hash(co->co_varnames);
  980. if (h4 == -1) return -1;
  981. h5 = PyObject_Hash(co->co_freevars);
  982. if (h5 == -1) return -1;
  983. h6 = PyObject_Hash(co->co_cellvars);
  984. if (h6 == -1) return -1;
  985. h = h0 ^ h1 ^ h2 ^ h3 ^ h4 ^ h5 ^ h6 ^
  986. co->co_argcount ^ co->co_posonlyargcount ^ co->co_kwonlyargcount ^
  987. co->co_nlocals ^ co->co_flags;
  988. if (h == -1) h = -2;
  989. return h;
  990. }
  991. #define OFF(x) offsetof(PyCodeObject, x)
  992. static PyMemberDef code_memberlist[] = {
  993. {"co_argcount", T_INT, OFF(co_argcount), READONLY},
  994. {"co_posonlyargcount", T_INT, OFF(co_posonlyargcount), READONLY},
  995. {"co_kwonlyargcount", T_INT, OFF(co_kwonlyargcount), READONLY},
  996. {"co_nlocals", T_INT, OFF(co_nlocals), READONLY},
  997. {"co_stacksize",T_INT, OFF(co_stacksize), READONLY},
  998. {"co_flags", T_INT, OFF(co_flags), READONLY},
  999. {"co_code", T_OBJECT, OFF(co_code), READONLY},
  1000. {"co_consts", T_OBJECT, OFF(co_consts), READONLY},
  1001. {"co_names", T_OBJECT, OFF(co_names), READONLY},
  1002. {"co_varnames", T_OBJECT, OFF(co_varnames), READONLY},
  1003. {"co_freevars", T_OBJECT, OFF(co_freevars), READONLY},
  1004. {"co_cellvars", T_OBJECT, OFF(co_cellvars), READONLY},
  1005. {"co_filename", T_OBJECT, OFF(co_filename), READONLY},
  1006. {"co_name", T_OBJECT, OFF(co_name), READONLY},
  1007. {"co_firstlineno", T_INT, OFF(co_firstlineno), READONLY},
  1008. {"co_linetable", T_OBJECT, OFF(co_linetable), READONLY},
  1009. {"co_exceptiontable", T_OBJECT, OFF(co_exceptiontable), READONLY},
  1010. {NULL} /* Sentinel */
  1011. };
  1012. static PyObject *
  1013. code_getlnotab(PyCodeObject *code, void *closure)
  1014. {
  1015. return decode_linetable(code);
  1016. }
  1017. static PyGetSetDef code_getsetlist[] = {
  1018. {"co_lnotab", (getter)code_getlnotab, NULL, NULL},
  1019. {0}
  1020. };
  1021. static PyObject *
  1022. code_sizeof(PyCodeObject *co, PyObject *Py_UNUSED(args))
  1023. {
  1024. Py_ssize_t res = _PyObject_SIZE(Py_TYPE(co));
  1025. _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra*) co->co_extra;
  1026. if (co->co_cell2arg != NULL && co->co_cellvars != NULL) {
  1027. res += PyTuple_GET_SIZE(co->co_cellvars) * sizeof(Py_ssize_t);
  1028. }
  1029. if (co_extra != NULL) {
  1030. res += sizeof(_PyCodeObjectExtra) +
  1031. (co_extra->ce_size-1) * sizeof(co_extra->ce_extras[0]);
  1032. }
  1033. if (co->co_opcache != NULL) {
  1034. assert(co->co_opcache_map != NULL);
  1035. // co_opcache_map
  1036. res += PyBytes_GET_SIZE(co->co_code) / sizeof(_Py_CODEUNIT);
  1037. // co_opcache
  1038. res += co->co_opcache_size * sizeof(_PyOpcache);
  1039. }
  1040. return PyLong_FromSsize_t(res);
  1041. }
  1042. static PyObject *
  1043. code_linesiterator(PyCodeObject *code, PyObject *Py_UNUSED(args))
  1044. {
  1045. return (PyObject *)new_linesiterator(code);
  1046. }
  1047. /*[clinic input]
  1048. code.replace
  1049. *
  1050. co_argcount: int(c_default="self->co_argcount") = -1
  1051. co_posonlyargcount: int(c_default="self->co_posonlyargcount") = -1
  1052. co_kwonlyargcount: int(c_default="self->co_kwonlyargcount") = -1
  1053. co_nlocals: int(c_default="self->co_nlocals") = -1
  1054. co_stacksize: int(c_default="self->co_stacksize") = -1
  1055. co_flags: int(c_default="self->co_flags") = -1
  1056. co_firstlineno: int(c_default="self->co_firstlineno") = -1
  1057. co_code: PyBytesObject(c_default="(PyBytesObject *)self->co_code") = None
  1058. co_consts: object(subclass_of="&PyTuple_Type", c_default="self->co_consts") = None
  1059. co_names: object(subclass_of="&PyTuple_Type", c_default="self->co_names") = None
  1060. co_varnames: object(subclass_of="&PyTuple_Type", c_default="self->co_varnames") = None
  1061. co_freevars: object(subclass_of="&PyTuple_Type", c_default="self->co_freevars") = None
  1062. co_cellvars: object(subclass_of="&PyTuple_Type", c_default="self->co_cellvars") = None
  1063. co_filename: unicode(c_default="self->co_filename") = None
  1064. co_name: unicode(c_default="self->co_name") = None
  1065. co_linetable: PyBytesObject(c_default="(PyBytesObject *)self->co_linetable") = None
  1066. co_exceptiontable: PyBytesObject(c_default="(PyBytesObject *)self->co_exceptiontable") = None
  1067. Return a copy of the code object with new values for the specified fields.
  1068. [clinic start generated code]*/
  1069. static PyObject *
  1070. code_replace_impl(PyCodeObject *self, int co_argcount,
  1071. int co_posonlyargcount, int co_kwonlyargcount,
  1072. int co_nlocals, int co_stacksize, int co_flags,
  1073. int co_firstlineno, PyBytesObject *co_code,
  1074. PyObject *co_consts, PyObject *co_names,
  1075. PyObject *co_varnames, PyObject *co_freevars,
  1076. PyObject *co_cellvars, PyObject *co_filename,
  1077. PyObject *co_name, PyBytesObject *co_linetable,
  1078. PyBytesObject *co_exceptiontable)
  1079. /*[clinic end generated code: output=80957472b7f78ed6 input=38376b1193efbbae]*/
  1080. {
  1081. #define CHECK_INT_ARG(ARG) \
  1082. if (ARG < 0) { \
  1083. PyErr_SetString(PyExc_ValueError, \
  1084. #ARG " must be a positive integer"); \
  1085. return NULL; \
  1086. }
  1087. CHECK_INT_ARG(co_argcount);
  1088. CHECK_INT_ARG(co_posonlyargcount);
  1089. CHECK_INT_ARG(co_kwonlyargcount);
  1090. CHECK_INT_ARG(co_nlocals);
  1091. CHECK_INT_ARG(co_stacksize);
  1092. CHECK_INT_ARG(co_flags);
  1093. CHECK_INT_ARG(co_firstlineno);
  1094. #undef CHECK_INT_ARG
  1095. if (PySys_Audit("code.__new__", "OOOiiiiii",
  1096. co_code, co_filename, co_name, co_argcount,
  1097. co_posonlyargcount, co_kwonlyargcount, co_nlocals,
  1098. co_stacksize, co_flags) < 0) {
  1099. return NULL;
  1100. }
  1101. return (PyObject *)PyCode_NewWithPosOnlyArgs(
  1102. co_argcount, co_posonlyargcount, co_kwonlyargcount, co_nlocals,
  1103. co_stacksize, co_flags, (PyObject*)co_code, co_consts, co_names,
  1104. co_varnames, co_freevars, co_cellvars, co_filename, co_name,
  1105. co_firstlineno, (PyObject*)co_linetable, (PyObject*)co_exceptiontable);
  1106. }
  1107. /* XXX code objects need to participate in GC? */
  1108. static struct PyMethodDef code_methods[] = {
  1109. {"__sizeof__", (PyCFunction)code_sizeof, METH_NOARGS},
  1110. {"co_lines", (PyCFunction)code_linesiterator, METH_NOARGS},
  1111. CODE_REPLACE_METHODDEF
  1112. {NULL, NULL} /* sentinel */
  1113. };
  1114. PyTypeObject PyCode_Type = {
  1115. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  1116. "code",
  1117. sizeof(PyCodeObject),
  1118. 0,
  1119. (destructor)code_dealloc, /* tp_dealloc */
  1120. 0, /* tp_vectorcall_offset */
  1121. 0, /* tp_getattr */
  1122. 0, /* tp_setattr */
  1123. 0, /* tp_as_async */
  1124. (reprfunc)code_repr, /* tp_repr */
  1125. 0, /* tp_as_number */
  1126. 0, /* tp_as_sequence */
  1127. 0, /* tp_as_mapping */
  1128. (hashfunc)code_hash, /* tp_hash */
  1129. 0, /* tp_call */
  1130. 0, /* tp_str */
  1131. PyObject_GenericGetAttr, /* tp_getattro */
  1132. 0, /* tp_setattro */
  1133. 0, /* tp_as_buffer */
  1134. Py_TPFLAGS_DEFAULT, /* tp_flags */
  1135. code_new__doc__, /* tp_doc */
  1136. 0, /* tp_traverse */
  1137. 0, /* tp_clear */
  1138. code_richcompare, /* tp_richcompare */
  1139. offsetof(PyCodeObject, co_weakreflist), /* tp_weaklistoffset */
  1140. 0, /* tp_iter */
  1141. 0, /* tp_iternext */
  1142. code_methods, /* tp_methods */
  1143. code_memberlist, /* tp_members */
  1144. code_getsetlist, /* tp_getset */
  1145. 0, /* tp_base */
  1146. 0, /* tp_dict */
  1147. 0, /* tp_descr_get */
  1148. 0, /* tp_descr_set */
  1149. 0, /* tp_dictoffset */
  1150. 0, /* tp_init */
  1151. 0, /* tp_alloc */
  1152. code_new, /* tp_new */
  1153. };
  1154. /******************
  1155. * other API
  1156. ******************/
  1157. PyObject*
  1158. _PyCode_ConstantKey(PyObject *op)
  1159. {
  1160. PyObject *key;
  1161. /* Py_None and Py_Ellipsis are singletons. */
  1162. if (op == Py_None || op == Py_Ellipsis
  1163. || PyLong_CheckExact(op)
  1164. || PyUnicode_CheckExact(op)
  1165. /* code_richcompare() uses _PyCode_ConstantKey() internally */
  1166. || PyCode_Check(op))
  1167. {
  1168. /* Objects of these types are always different from object of other
  1169. * type and from tuples. */
  1170. Py_INCREF(op);
  1171. key = op;
  1172. }
  1173. else if (PyBool_Check(op) || PyBytes_CheckExact(op)) {
  1174. /* Make booleans different from integers 0 and 1.
  1175. * Avoid BytesWarning from comparing bytes with strings. */
  1176. key = PyTuple_Pack(2, Py_TYPE(op), op);
  1177. }
  1178. else if (PyFloat_CheckExact(op)) {
  1179. double d = PyFloat_AS_DOUBLE(op);
  1180. /* all we need is to make the tuple different in either the 0.0
  1181. * or -0.0 case from all others, just to avoid the "coercion".
  1182. */
  1183. if (d == 0.0 && copysign(1.0, d) < 0.0)
  1184. key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
  1185. else
  1186. key = PyTuple_Pack(2, Py_TYPE(op), op);
  1187. }
  1188. else if (PyComplex_CheckExact(op)) {
  1189. Py_complex z;
  1190. int real_negzero, imag_negzero;
  1191. /* For the complex case we must make complex(x, 0.)
  1192. different from complex(x, -0.) and complex(0., y)
  1193. different from complex(-0., y), for any x and y.
  1194. All four complex zeros must be distinguished.*/
  1195. z = PyComplex_AsCComplex(op);
  1196. real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
  1197. imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
  1198. /* use True, False and None singleton as tags for the real and imag
  1199. * sign, to make tuples different */
  1200. if (real_negzero && imag_negzero) {
  1201. key = PyTuple_Pack(3, Py_TYPE(op), op, Py_True);
  1202. }
  1203. else if (imag_negzero) {
  1204. key = PyTuple_Pack(3, Py_TYPE(op), op, Py_False);
  1205. }
  1206. else if (real_negzero) {
  1207. key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
  1208. }
  1209. else {
  1210. key = PyTuple_Pack(2, Py_TYPE(op), op);
  1211. }
  1212. }
  1213. else if (PyTuple_CheckExact(op)) {
  1214. Py_ssize_t i, len;
  1215. PyObject *tuple;
  1216. len = PyTuple_GET_SIZE(op);
  1217. tuple = PyTuple_New(len);
  1218. if (tuple == NULL)
  1219. return NULL;
  1220. for (i=0; i < len; i++) {
  1221. PyObject *item, *item_key;
  1222. item = PyTuple_GET_ITEM(op, i);
  1223. item_key = _PyCode_ConstantKey(item);
  1224. if (item_key == NULL) {
  1225. Py_DECREF(tuple);
  1226. return NULL;
  1227. }
  1228. PyTuple_SET_ITEM(tuple, i, item_key);
  1229. }
  1230. key = PyTuple_Pack(2, tuple, op);
  1231. Py_DECREF(tuple);
  1232. }
  1233. else if (PyFrozenSet_CheckExact(op)) {
  1234. Py_ssize_t pos = 0;
  1235. PyObject *item;
  1236. Py_hash_t hash;
  1237. Py_ssize_t i, len;
  1238. PyObject *tuple, *set;
  1239. len = PySet_GET_SIZE(op);
  1240. tuple = PyTuple_New(len);
  1241. if (tuple == NULL)
  1242. return NULL;
  1243. i = 0;
  1244. while (_PySet_NextEntry(op, &pos, &item, &hash)) {
  1245. PyObject *item_key;
  1246. item_key = _PyCode_ConstantKey(item);
  1247. if (item_key == NULL) {
  1248. Py_DECREF(tuple);
  1249. return NULL;
  1250. }
  1251. assert(i < len);
  1252. PyTuple_SET_ITEM(tuple, i, item_key);
  1253. i++;
  1254. }
  1255. set = PyFrozenSet_New(tuple);
  1256. Py_DECREF(tuple);
  1257. if (set == NULL)
  1258. return NULL;
  1259. key = PyTuple_Pack(2, set, op);
  1260. Py_DECREF(set);
  1261. return key;
  1262. }
  1263. else {
  1264. /* for other types, use the object identifier as a unique identifier
  1265. * to ensure that they are seen as unequal. */
  1266. PyObject *obj_id = PyLong_FromVoidPtr(op);
  1267. if (obj_id == NULL)
  1268. return NULL;
  1269. key = PyTuple_Pack(2, obj_id, op);
  1270. Py_DECREF(obj_id);
  1271. }
  1272. return key;
  1273. }