blob: da04af43a4a253761fdd9b2823ce56bb21a5fa60 [file] [log] [blame]
Benjamin Peterson1bf494b2016-09-07 11:28:35 -07001#include <stdbool.h>
2
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003#include "Python.h"
4#include "code.h"
Inada Naoki91234a12019-06-03 21:30:58 +09005#include "opcode.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "structmember.h"
Inada Naoki91234a12019-06-03 21:30:58 +09007#include "pycore_code.h"
Victor Stinner4a3fe082020-04-14 14:26:24 +02008#include "pycore_interp.h" // PyInterpreterState.co_extra_freefuncs
Victor Stinner81a7be32020-04-14 15:14:01 +02009#include "pycore_pystate.h" // _PyInterpreterState_GET()
Victor Stinnerec13b932018-11-25 23:56:17 +010010#include "pycore_tupleobject.h"
Victor Stinnera9f05d62019-05-24 23:57:23 +020011#include "clinic/codeobject.c.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000012
Brett Cannond0600ed2016-09-07 14:30:39 -070013/* Holder for co_extra information */
14typedef struct {
15 Py_ssize_t ce_size;
Serhiy Storchaka378ebb62017-07-04 15:06:16 +030016 void *ce_extras[1];
Brett Cannond0600ed2016-09-07 14:30:39 -070017} _PyCodeObjectExtra;
18
Victor Stinnera9f05d62019-05-24 23:57:23 +020019/*[clinic input]
20class code "PyCodeObject *" "&PyCode_Type"
21[clinic start generated code]*/
22/*[clinic end generated code: output=da39a3ee5e6b4b0d input=78aa5d576683bb4b]*/
23
Benjamin Peterson8e0ad462017-09-07 23:35:53 -070024/* all_name_chars(s): true iff s matches [a-zA-Z0-9_]* */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000025static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020026all_name_chars(PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000027{
Serhiy Storchaka09f3d082016-10-04 18:17:22 +030028 const unsigned char *s, *e;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020029
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030030 if (!PyUnicode_IS_ASCII(o))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020031 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000032
Serhiy Storchaka09f3d082016-10-04 18:17:22 +030033 s = PyUnicode_1BYTE_DATA(o);
34 e = s + PyUnicode_GET_LENGTH(o);
Benjamin Peterson9020ac72017-09-07 18:06:23 -070035 for (; s != e; s++) {
Benjamin Peterson2b7953d2017-09-08 10:35:49 -070036 if (!Py_ISALNUM(*s) && *s != '_')
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000037 return 0;
38 }
39 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000040}
41
Victor Stinnera2783132020-01-27 23:24:13 +010042static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000043intern_strings(PyObject *tuple)
44{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045 Py_ssize_t i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 for (i = PyTuple_GET_SIZE(tuple); --i >= 0; ) {
48 PyObject *v = PyTuple_GET_ITEM(tuple, i);
49 if (v == NULL || !PyUnicode_CheckExact(v)) {
Victor Stinnera2783132020-01-27 23:24:13 +010050 PyErr_SetString(PyExc_SystemError,
51 "non-string found in code slot");
52 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000053 }
Victor Stinnerd17a6932018-11-09 16:56:48 +010054 PyUnicode_InternInPlace(&_PyTuple_ITEMS(tuple)[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000055 }
Victor Stinnera2783132020-01-27 23:24:13 +010056 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000057}
58
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +030059/* Intern selected string constants */
60static int
Victor Stinnera2783132020-01-27 23:24:13 +010061intern_string_constants(PyObject *tuple, int *modified)
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +030062{
Victor Stinnera2783132020-01-27 23:24:13 +010063 for (Py_ssize_t i = PyTuple_GET_SIZE(tuple); --i >= 0; ) {
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +030064 PyObject *v = PyTuple_GET_ITEM(tuple, i);
65 if (PyUnicode_CheckExact(v)) {
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030066 if (PyUnicode_READY(v) == -1) {
Victor Stinnera2783132020-01-27 23:24:13 +010067 return -1;
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030068 }
Victor Stinnera2783132020-01-27 23:24:13 +010069
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +030070 if (all_name_chars(v)) {
71 PyObject *w = v;
72 PyUnicode_InternInPlace(&v);
73 if (w != v) {
74 PyTuple_SET_ITEM(tuple, i, v);
Victor Stinnera2783132020-01-27 23:24:13 +010075 if (modified) {
76 *modified = 1;
77 }
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +030078 }
79 }
80 }
81 else if (PyTuple_CheckExact(v)) {
Victor Stinnera2783132020-01-27 23:24:13 +010082 if (intern_string_constants(v, NULL) < 0) {
83 return -1;
84 }
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +030085 }
86 else if (PyFrozenSet_CheckExact(v)) {
Yury Selivanovd2fd3592016-11-09 09:42:14 -050087 PyObject *w = v;
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +030088 PyObject *tmp = PySequence_Tuple(v);
89 if (tmp == NULL) {
Victor Stinnera2783132020-01-27 23:24:13 +010090 return -1;
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +030091 }
Victor Stinnera2783132020-01-27 23:24:13 +010092 int tmp_modified = 0;
93 if (intern_string_constants(tmp, &tmp_modified) < 0) {
94 Py_DECREF(tmp);
95 return -1;
96 }
97 if (tmp_modified) {
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +030098 v = PyFrozenSet_New(tmp);
99 if (v == NULL) {
Victor Stinnera2783132020-01-27 23:24:13 +0100100 Py_DECREF(tmp);
101 return -1;
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +0300102 }
Victor Stinnera2783132020-01-27 23:24:13 +0100103
104 PyTuple_SET_ITEM(tuple, i, v);
105 Py_DECREF(w);
106 if (modified) {
107 *modified = 1;
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +0300108 }
109 }
110 Py_DECREF(tmp);
111 }
112 }
Victor Stinnera2783132020-01-27 23:24:13 +0100113 return 0;
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +0300114}
115
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000116PyCodeObject *
Pablo Galindo4a2edc32019-07-01 11:35:05 +0100117PyCode_NewWithPosOnlyArgs(int argcount, int posonlyargcount, int kwonlyargcount,
118 int nlocals, int stacksize, int flags,
119 PyObject *code, PyObject *consts, PyObject *names,
120 PyObject *varnames, PyObject *freevars, PyObject *cellvars,
121 PyObject *filename, PyObject *name, int firstlineno,
122 PyObject *lnotab)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000123{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 PyCodeObject *co;
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200125 Py_ssize_t *cell2arg = NULL;
Serhiy Storchakabd473842018-07-16 09:10:19 +0300126 Py_ssize_t i, n_cellvars, n_varnames, total_args;
Guido van Rossum00bc0e02007-10-15 02:52:41 +0000127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 /* Check argument types */
Pablo Galindocd74e662019-06-01 18:08:04 +0100129 if (argcount < posonlyargcount || posonlyargcount < 0 ||
130 kwonlyargcount < 0 || nlocals < 0 ||
131 stacksize < 0 || flags < 0 ||
Victor Stinnera9f05d62019-05-24 23:57:23 +0200132 code == NULL || !PyBytes_Check(code) ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 consts == NULL || !PyTuple_Check(consts) ||
134 names == NULL || !PyTuple_Check(names) ||
135 varnames == NULL || !PyTuple_Check(varnames) ||
136 freevars == NULL || !PyTuple_Check(freevars) ||
137 cellvars == NULL || !PyTuple_Check(cellvars) ||
138 name == NULL || !PyUnicode_Check(name) ||
139 filename == NULL || !PyUnicode_Check(filename) ||
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +0200140 lnotab == NULL || !PyBytes_Check(lnotab)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 PyErr_BadInternalCall();
142 return NULL;
143 }
Victor Stinner7c74de42013-10-10 15:55:14 +0200144
Victor Stinnera9f05d62019-05-24 23:57:23 +0200145 /* Ensure that strings are ready Unicode string */
146 if (PyUnicode_READY(name) < 0) {
Victor Stinner7c74de42013-10-10 15:55:14 +0200147 return NULL;
Victor Stinnera9f05d62019-05-24 23:57:23 +0200148 }
149 if (PyUnicode_READY(filename) < 0) {
150 return NULL;
151 }
Victor Stinner7c74de42013-10-10 15:55:14 +0200152
Victor Stinnera2783132020-01-27 23:24:13 +0100153 if (intern_strings(names) < 0) {
154 return NULL;
155 }
156 if (intern_strings(varnames) < 0) {
157 return NULL;
158 }
159 if (intern_strings(freevars) < 0) {
160 return NULL;
161 }
162 if (intern_strings(cellvars) < 0) {
163 return NULL;
164 }
165 if (intern_string_constants(consts, NULL) < 0) {
166 return NULL;
167 }
Nick Coghlan078f1812017-12-03 11:12:20 +1000168
169 /* Check for any inner or outer closure references */
170 n_cellvars = PyTuple_GET_SIZE(cellvars);
171 if (!n_cellvars && !PyTuple_GET_SIZE(freevars)) {
172 flags |= CO_NOFREE;
173 } else {
174 flags &= ~CO_NOFREE;
175 }
176
Serhiy Storchakabd473842018-07-16 09:10:19 +0300177 n_varnames = PyTuple_GET_SIZE(varnames);
Pablo Galindocd74e662019-06-01 18:08:04 +0100178 if (argcount <= n_varnames && kwonlyargcount <= n_varnames) {
Serhiy Storchakabd473842018-07-16 09:10:19 +0300179 /* Never overflows. */
Pablo Galindocd74e662019-06-01 18:08:04 +0100180 total_args = (Py_ssize_t)argcount + (Py_ssize_t)kwonlyargcount +
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100181 ((flags & CO_VARARGS) != 0) + ((flags & CO_VARKEYWORDS) != 0);
Serhiy Storchakabd473842018-07-16 09:10:19 +0300182 }
183 else {
184 total_args = n_varnames + 1;
185 }
186 if (total_args > n_varnames) {
187 PyErr_SetString(PyExc_ValueError, "code: varnames is too small");
188 return NULL;
189 }
190
Benjamin Peterson90037602011-06-25 22:54:45 -0500191 /* Create mapping between cells and arguments if needed. */
192 if (n_cellvars) {
Benjamin Peterson1bf494b2016-09-07 11:28:35 -0700193 bool used_cell2arg = false;
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200194 cell2arg = PyMem_NEW(Py_ssize_t, n_cellvars);
195 if (cell2arg == NULL) {
196 PyErr_NoMemory();
Benjamin Peterson90037602011-06-25 22:54:45 -0500197 return NULL;
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200198 }
Benjamin Peterson90037602011-06-25 22:54:45 -0500199 /* Find cells which are also arguments. */
200 for (i = 0; i < n_cellvars; i++) {
201 Py_ssize_t j;
202 PyObject *cell = PyTuple_GET_ITEM(cellvars, i);
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200203 cell2arg[i] = CO_CELL_NOT_AN_ARG;
Benjamin Peterson90037602011-06-25 22:54:45 -0500204 for (j = 0; j < total_args; j++) {
205 PyObject *arg = PyTuple_GET_ITEM(varnames, j);
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200206 int cmp = PyUnicode_Compare(cell, arg);
207 if (cmp == -1 && PyErr_Occurred()) {
208 PyMem_FREE(cell2arg);
209 return NULL;
210 }
211 if (cmp == 0) {
Benjamin Peterson90037602011-06-25 22:54:45 -0500212 cell2arg[i] = j;
Benjamin Peterson1bf494b2016-09-07 11:28:35 -0700213 used_cell2arg = true;
Benjamin Peterson90037602011-06-25 22:54:45 -0500214 break;
215 }
216 }
217 }
218 if (!used_cell2arg) {
219 PyMem_FREE(cell2arg);
220 cell2arg = NULL;
221 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 }
Victor Stinner92055202020-04-08 00:38:15 +0200223 co = PyObject_New(PyCodeObject, &PyCode_Type);
Benjamin Peterson90037602011-06-25 22:54:45 -0500224 if (co == NULL) {
225 if (cell2arg)
226 PyMem_FREE(cell2arg);
227 return NULL;
228 }
229 co->co_argcount = argcount;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100230 co->co_posonlyargcount = posonlyargcount;
Benjamin Peterson90037602011-06-25 22:54:45 -0500231 co->co_kwonlyargcount = kwonlyargcount;
232 co->co_nlocals = nlocals;
233 co->co_stacksize = stacksize;
234 co->co_flags = flags;
235 Py_INCREF(code);
236 co->co_code = code;
237 Py_INCREF(consts);
238 co->co_consts = consts;
239 Py_INCREF(names);
240 co->co_names = names;
241 Py_INCREF(varnames);
242 co->co_varnames = varnames;
243 Py_INCREF(freevars);
244 co->co_freevars = freevars;
245 Py_INCREF(cellvars);
246 co->co_cellvars = cellvars;
247 co->co_cell2arg = cell2arg;
248 Py_INCREF(filename);
249 co->co_filename = filename;
250 Py_INCREF(name);
251 co->co_name = name;
252 co->co_firstlineno = firstlineno;
253 Py_INCREF(lnotab);
254 co->co_lnotab = lnotab;
255 co->co_zombieframe = NULL;
256 co->co_weakreflist = NULL;
Brett Cannon5c4de282016-09-07 11:16:41 -0700257 co->co_extra = NULL;
Inada Naoki91234a12019-06-03 21:30:58 +0900258
259 co->co_opcache_map = NULL;
260 co->co_opcache = NULL;
261 co->co_opcache_flag = 0;
262 co->co_opcache_size = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000264}
265
Pablo Galindo4a2edc32019-07-01 11:35:05 +0100266PyCodeObject *
267PyCode_New(int argcount, int kwonlyargcount,
268 int nlocals, int stacksize, int flags,
269 PyObject *code, PyObject *consts, PyObject *names,
270 PyObject *varnames, PyObject *freevars, PyObject *cellvars,
271 PyObject *filename, PyObject *name, int firstlineno,
272 PyObject *lnotab)
273{
274 return PyCode_NewWithPosOnlyArgs(argcount, 0, kwonlyargcount, nlocals,
275 stacksize, flags, code, consts, names,
276 varnames, freevars, cellvars, filename,
277 name, firstlineno, lnotab);
278}
279
Inada Naoki91234a12019-06-03 21:30:58 +0900280int
281_PyCode_InitOpcache(PyCodeObject *co)
282{
283 Py_ssize_t co_size = PyBytes_Size(co->co_code) / sizeof(_Py_CODEUNIT);
284 co->co_opcache_map = (unsigned char *)PyMem_Calloc(co_size, 1);
285 if (co->co_opcache_map == NULL) {
286 return -1;
287 }
288
289 _Py_CODEUNIT *opcodes = (_Py_CODEUNIT*)PyBytes_AS_STRING(co->co_code);
290 Py_ssize_t opts = 0;
291
292 for (Py_ssize_t i = 0; i < co_size;) {
293 unsigned char opcode = _Py_OPCODE(opcodes[i]);
294 i++; // 'i' is now aligned to (next_instr - first_instr)
295
296 // TODO: LOAD_METHOD, LOAD_ATTR
297 if (opcode == LOAD_GLOBAL) {
Victor Stinnerea9f1682019-06-04 17:08:24 +0200298 opts++;
299 co->co_opcache_map[i] = (unsigned char)opts;
Inada Naoki91234a12019-06-03 21:30:58 +0900300 if (opts > 254) {
301 break;
302 }
303 }
304 }
305
306 if (opts) {
307 co->co_opcache = (_PyOpcache *)PyMem_Calloc(opts, sizeof(_PyOpcache));
308 if (co->co_opcache == NULL) {
309 PyMem_FREE(co->co_opcache_map);
310 return -1;
311 }
312 }
313 else {
314 PyMem_FREE(co->co_opcache_map);
315 co->co_opcache_map = NULL;
316 co->co_opcache = NULL;
317 }
318
Victor Stinner376ce982019-06-12 04:41:16 +0200319 co->co_opcache_size = (unsigned char)opts;
Inada Naoki91234a12019-06-03 21:30:58 +0900320 return 0;
321}
322
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000323PyCodeObject *
324PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno)
325{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 static PyObject *emptystring = NULL;
327 static PyObject *nulltuple = NULL;
328 PyObject *filename_ob = NULL;
329 PyObject *funcname_ob = NULL;
330 PyCodeObject *result = NULL;
331 if (emptystring == NULL) {
332 emptystring = PyBytes_FromString("");
333 if (emptystring == NULL)
334 goto failed;
335 }
336 if (nulltuple == NULL) {
337 nulltuple = PyTuple_New(0);
338 if (nulltuple == NULL)
339 goto failed;
340 }
341 funcname_ob = PyUnicode_FromString(funcname);
342 if (funcname_ob == NULL)
343 goto failed;
344 filename_ob = PyUnicode_DecodeFSDefault(filename);
345 if (filename_ob == NULL)
346 goto failed;
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000347
Pablo Galindo4a2edc32019-07-01 11:35:05 +0100348 result = PyCode_NewWithPosOnlyArgs(
349 0, /* argcount */
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100350 0, /* posonlyargcount */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 0, /* kwonlyargcount */
352 0, /* nlocals */
353 0, /* stacksize */
354 0, /* flags */
355 emptystring, /* code */
356 nulltuple, /* consts */
357 nulltuple, /* names */
358 nulltuple, /* varnames */
359 nulltuple, /* freevars */
360 nulltuple, /* cellvars */
361 filename_ob, /* filename */
362 funcname_ob, /* name */
363 firstlineno, /* firstlineno */
364 emptystring /* lnotab */
365 );
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000366
367failed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 Py_XDECREF(funcname_ob);
369 Py_XDECREF(filename_ob);
370 return result;
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000371}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000372
373#define OFF(x) offsetof(PyCodeObject, x)
374
375static PyMemberDef code_memberlist[] = {
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100376 {"co_argcount", T_INT, OFF(co_argcount), READONLY},
377 {"co_posonlyargcount", T_INT, OFF(co_posonlyargcount), READONLY},
378 {"co_kwonlyargcount", T_INT, OFF(co_kwonlyargcount), READONLY},
379 {"co_nlocals", T_INT, OFF(co_nlocals), READONLY},
380 {"co_stacksize",T_INT, OFF(co_stacksize), READONLY},
381 {"co_flags", T_INT, OFF(co_flags), READONLY},
382 {"co_code", T_OBJECT, OFF(co_code), READONLY},
383 {"co_consts", T_OBJECT, OFF(co_consts), READONLY},
384 {"co_names", T_OBJECT, OFF(co_names), READONLY},
385 {"co_varnames", T_OBJECT, OFF(co_varnames), READONLY},
386 {"co_freevars", T_OBJECT, OFF(co_freevars), READONLY},
387 {"co_cellvars", T_OBJECT, OFF(co_cellvars), READONLY},
388 {"co_filename", T_OBJECT, OFF(co_filename), READONLY},
389 {"co_name", T_OBJECT, OFF(co_name), READONLY},
390 {"co_firstlineno", T_INT, OFF(co_firstlineno), READONLY},
391 {"co_lnotab", T_OBJECT, OFF(co_lnotab), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 {NULL} /* Sentinel */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000393};
394
395/* Helper for code_new: return a shallow copy of a tuple that is
396 guaranteed to contain exact strings, by converting string subclasses
397 to exact strings and complaining if a non-string is found. */
398static PyObject*
399validate_and_copy_tuple(PyObject *tup)
400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 PyObject *newtuple;
402 PyObject *item;
403 Py_ssize_t i, len;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 len = PyTuple_GET_SIZE(tup);
406 newtuple = PyTuple_New(len);
407 if (newtuple == NULL)
408 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 for (i = 0; i < len; i++) {
411 item = PyTuple_GET_ITEM(tup, i);
412 if (PyUnicode_CheckExact(item)) {
413 Py_INCREF(item);
414 }
415 else if (!PyUnicode_Check(item)) {
416 PyErr_Format(
417 PyExc_TypeError,
418 "name tuples must contain only "
419 "strings, not '%.500s'",
Victor Stinner58ac7002020-02-07 03:04:21 +0100420 Py_TYPE(item)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 Py_DECREF(newtuple);
422 return NULL;
423 }
424 else {
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100425 item = _PyUnicode_Copy(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 if (item == NULL) {
427 Py_DECREF(newtuple);
428 return NULL;
429 }
430 }
431 PyTuple_SET_ITEM(newtuple, i, item);
432 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 return newtuple;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000435}
436
437PyDoc_STRVAR(code_doc,
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100438"code(argcount, posonlyargcount, kwonlyargcount, nlocals, stacksize,\n\
439 flags, codestring, constants, names, varnames, filename, name,\n\
440 firstlineno, lnotab[, freevars[, cellvars]])\n\
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000441\n\
442Create a code object. Not for the faint of heart.");
443
444static PyObject *
445code_new(PyTypeObject *type, PyObject *args, PyObject *kw)
446{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 int argcount;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100448 int posonlyargcount;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 int kwonlyargcount;
450 int nlocals;
451 int stacksize;
452 int flags;
453 PyObject *co = NULL;
454 PyObject *code;
455 PyObject *consts;
456 PyObject *names, *ournames = NULL;
457 PyObject *varnames, *ourvarnames = NULL;
458 PyObject *freevars = NULL, *ourfreevars = NULL;
459 PyObject *cellvars = NULL, *ourcellvars = NULL;
460 PyObject *filename;
461 PyObject *name;
462 int firstlineno;
463 PyObject *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000464
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100465 if (!PyArg_ParseTuple(args, "iiiiiiSO!O!O!UUiS|O!O!:code",
466 &argcount, &posonlyargcount, &kwonlyargcount,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 &nlocals, &stacksize, &flags,
468 &code,
469 &PyTuple_Type, &consts,
470 &PyTuple_Type, &names,
471 &PyTuple_Type, &varnames,
472 &filename, &name,
473 &firstlineno, &lnotab,
474 &PyTuple_Type, &freevars,
475 &PyTuple_Type, &cellvars))
476 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000477
Pablo Galindo3b57f502019-06-01 21:18:48 +0100478 if (PySys_Audit("code.__new__", "OOOiiiiii",
479 code, filename, name, argcount, posonlyargcount,
480 kwonlyargcount, nlocals, stacksize, flags) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700481 goto cleanup;
482 }
483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 if (argcount < 0) {
485 PyErr_SetString(
486 PyExc_ValueError,
487 "code: argcount must not be negative");
488 goto cleanup;
489 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000490
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100491 if (posonlyargcount < 0) {
492 PyErr_SetString(
493 PyExc_ValueError,
494 "code: posonlyargcount must not be negative");
495 goto cleanup;
496 }
497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 if (kwonlyargcount < 0) {
499 PyErr_SetString(
500 PyExc_ValueError,
501 "code: kwonlyargcount must not be negative");
502 goto cleanup;
503 }
504 if (nlocals < 0) {
505 PyErr_SetString(
506 PyExc_ValueError,
507 "code: nlocals must not be negative");
508 goto cleanup;
509 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 ournames = validate_and_copy_tuple(names);
512 if (ournames == NULL)
513 goto cleanup;
514 ourvarnames = validate_and_copy_tuple(varnames);
515 if (ourvarnames == NULL)
516 goto cleanup;
517 if (freevars)
518 ourfreevars = validate_and_copy_tuple(freevars);
519 else
520 ourfreevars = PyTuple_New(0);
521 if (ourfreevars == NULL)
522 goto cleanup;
523 if (cellvars)
524 ourcellvars = validate_and_copy_tuple(cellvars);
525 else
526 ourcellvars = PyTuple_New(0);
527 if (ourcellvars == NULL)
528 goto cleanup;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000529
Pablo Galindo4a2edc32019-07-01 11:35:05 +0100530 co = (PyObject *)PyCode_NewWithPosOnlyArgs(argcount, posonlyargcount,
531 kwonlyargcount,
532 nlocals, stacksize, flags,
533 code, consts, ournames,
534 ourvarnames, ourfreevars,
535 ourcellvars, filename,
536 name, firstlineno, lnotab);
Victor Stinnera2783132020-01-27 23:24:13 +0100537 cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 Py_XDECREF(ournames);
539 Py_XDECREF(ourvarnames);
540 Py_XDECREF(ourfreevars);
541 Py_XDECREF(ourcellvars);
542 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000543}
544
545static void
546code_dealloc(PyCodeObject *co)
547{
Inada Naoki91234a12019-06-03 21:30:58 +0900548 if (co->co_opcache != NULL) {
549 PyMem_FREE(co->co_opcache);
550 }
551 if (co->co_opcache_map != NULL) {
552 PyMem_FREE(co->co_opcache_map);
553 }
554 co->co_opcache_flag = 0;
555 co->co_opcache_size = 0;
556
Brett Cannon5c4de282016-09-07 11:16:41 -0700557 if (co->co_extra != NULL) {
Victor Stinner81a7be32020-04-14 15:14:01 +0200558 PyInterpreterState *interp = _PyInterpreterState_GET();
Brett Cannond0600ed2016-09-07 14:30:39 -0700559 _PyCodeObjectExtra *co_extra = co->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700560
Brett Cannond0600ed2016-09-07 14:30:39 -0700561 for (Py_ssize_t i = 0; i < co_extra->ce_size; i++) {
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700562 freefunc free_extra = interp->co_extra_freefuncs[i];
Brett Cannon5c4de282016-09-07 11:16:41 -0700563
564 if (free_extra != NULL) {
Brett Cannond0600ed2016-09-07 14:30:39 -0700565 free_extra(co_extra->ce_extras[i]);
Brett Cannon5c4de282016-09-07 11:16:41 -0700566 }
567 }
568
Victor Stinner23e79442017-06-28 02:12:00 +0200569 PyMem_Free(co_extra);
Brett Cannon5c4de282016-09-07 11:16:41 -0700570 }
571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 Py_XDECREF(co->co_code);
573 Py_XDECREF(co->co_consts);
574 Py_XDECREF(co->co_names);
575 Py_XDECREF(co->co_varnames);
576 Py_XDECREF(co->co_freevars);
577 Py_XDECREF(co->co_cellvars);
578 Py_XDECREF(co->co_filename);
579 Py_XDECREF(co->co_name);
580 Py_XDECREF(co->co_lnotab);
Benjamin Peterson90037602011-06-25 22:54:45 -0500581 if (co->co_cell2arg != NULL)
582 PyMem_FREE(co->co_cell2arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 if (co->co_zombieframe != NULL)
584 PyObject_GC_Del(co->co_zombieframe);
585 if (co->co_weakreflist != NULL)
586 PyObject_ClearWeakRefs((PyObject*)co);
587 PyObject_DEL(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000588}
589
590static PyObject *
Victor Stinnera9f05d62019-05-24 23:57:23 +0200591code_sizeof(PyCodeObject *co, PyObject *Py_UNUSED(args))
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200592{
Dong-hee Nab4dc6af2017-04-20 16:31:17 +0900593 Py_ssize_t res = _PyObject_SIZE(Py_TYPE(co));
594 _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra*) co->co_extra;
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200595
Serhiy Storchaka378ebb62017-07-04 15:06:16 +0300596 if (co->co_cell2arg != NULL && co->co_cellvars != NULL) {
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200597 res += PyTuple_GET_SIZE(co->co_cellvars) * sizeof(Py_ssize_t);
Serhiy Storchaka378ebb62017-07-04 15:06:16 +0300598 }
599 if (co_extra != NULL) {
600 res += sizeof(_PyCodeObjectExtra) +
601 (co_extra->ce_size-1) * sizeof(co_extra->ce_extras[0]);
602 }
Inada Naoki91234a12019-06-03 21:30:58 +0900603 if (co->co_opcache != NULL) {
604 assert(co->co_opcache_map != NULL);
605 // co_opcache_map
606 res += PyBytes_GET_SIZE(co->co_code) / sizeof(_Py_CODEUNIT);
607 // co_opcache
608 res += co->co_opcache_size * sizeof(_PyOpcache);
609 }
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200610 return PyLong_FromSsize_t(res);
611}
612
Victor Stinnera9f05d62019-05-24 23:57:23 +0200613/*[clinic input]
614code.replace
615
616 *
617 co_argcount: int(c_default="self->co_argcount") = -1
618 co_posonlyargcount: int(c_default="self->co_posonlyargcount") = -1
619 co_kwonlyargcount: int(c_default="self->co_kwonlyargcount") = -1
620 co_nlocals: int(c_default="self->co_nlocals") = -1
621 co_stacksize: int(c_default="self->co_stacksize") = -1
622 co_flags: int(c_default="self->co_flags") = -1
623 co_firstlineno: int(c_default="self->co_firstlineno") = -1
624 co_code: PyBytesObject(c_default="(PyBytesObject *)self->co_code") = None
625 co_consts: object(subclass_of="&PyTuple_Type", c_default="self->co_consts") = None
626 co_names: object(subclass_of="&PyTuple_Type", c_default="self->co_names") = None
627 co_varnames: object(subclass_of="&PyTuple_Type", c_default="self->co_varnames") = None
628 co_freevars: object(subclass_of="&PyTuple_Type", c_default="self->co_freevars") = None
629 co_cellvars: object(subclass_of="&PyTuple_Type", c_default="self->co_cellvars") = None
630 co_filename: unicode(c_default="self->co_filename") = None
631 co_name: unicode(c_default="self->co_name") = None
632 co_lnotab: PyBytesObject(c_default="(PyBytesObject *)self->co_lnotab") = None
633
Anthony Sottile22424c02020-01-01 01:11:16 -0500634Return a copy of the code object with new values for the specified fields.
Victor Stinnera9f05d62019-05-24 23:57:23 +0200635[clinic start generated code]*/
636
637static PyObject *
638code_replace_impl(PyCodeObject *self, int co_argcount,
639 int co_posonlyargcount, int co_kwonlyargcount,
640 int co_nlocals, int co_stacksize, int co_flags,
641 int co_firstlineno, PyBytesObject *co_code,
642 PyObject *co_consts, PyObject *co_names,
643 PyObject *co_varnames, PyObject *co_freevars,
644 PyObject *co_cellvars, PyObject *co_filename,
645 PyObject *co_name, PyBytesObject *co_lnotab)
Anthony Sottile22424c02020-01-01 01:11:16 -0500646/*[clinic end generated code: output=25c8e303913bcace input=d9051bc8f24e6b28]*/
Victor Stinnera9f05d62019-05-24 23:57:23 +0200647{
648#define CHECK_INT_ARG(ARG) \
649 if (ARG < 0) { \
650 PyErr_SetString(PyExc_ValueError, \
651 #ARG " must be a positive integer"); \
652 return NULL; \
653 }
654
655 CHECK_INT_ARG(co_argcount);
656 CHECK_INT_ARG(co_posonlyargcount);
657 CHECK_INT_ARG(co_kwonlyargcount);
658 CHECK_INT_ARG(co_nlocals);
659 CHECK_INT_ARG(co_stacksize);
660 CHECK_INT_ARG(co_flags);
661 CHECK_INT_ARG(co_firstlineno);
662
663#undef CHECK_INT_ARG
664
Steve Dowerc7c01ab2019-11-26 16:27:50 -0800665 if (PySys_Audit("code.__new__", "OOOiiiiii",
666 co_code, co_filename, co_name, co_argcount,
667 co_posonlyargcount, co_kwonlyargcount, co_nlocals,
668 co_stacksize, co_flags) < 0) {
669 return NULL;
670 }
671
Pablo Galindo4a2edc32019-07-01 11:35:05 +0100672 return (PyObject *)PyCode_NewWithPosOnlyArgs(
Victor Stinnera9f05d62019-05-24 23:57:23 +0200673 co_argcount, co_posonlyargcount, co_kwonlyargcount, co_nlocals,
674 co_stacksize, co_flags, (PyObject*)co_code, co_consts, co_names,
675 co_varnames, co_freevars, co_cellvars, co_filename, co_name,
676 co_firstlineno, (PyObject*)co_lnotab);
677}
678
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200679static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000680code_repr(PyCodeObject *co)
681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 int lineno;
683 if (co->co_firstlineno != 0)
684 lineno = co->co_firstlineno;
685 else
686 lineno = -1;
687 if (co->co_filename && PyUnicode_Check(co->co_filename)) {
688 return PyUnicode_FromFormat(
Victor Stinneraaa4e9a2011-01-05 03:33:26 +0000689 "<code object %U at %p, file \"%U\", line %d>",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 co->co_name, co, co->co_filename, lineno);
691 } else {
692 return PyUnicode_FromFormat(
Victor Stinneraaa4e9a2011-01-05 03:33:26 +0000693 "<code object %U at %p, file ???, line %d>",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 co->co_name, co, lineno);
695 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000696}
697
Victor Stinnerefb24132016-01-22 12:33:12 +0100698PyObject*
699_PyCode_ConstantKey(PyObject *op)
700{
701 PyObject *key;
702
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +0300703 /* Py_None and Py_Ellipsis are singletons. */
Victor Stinnerefb24132016-01-22 12:33:12 +0100704 if (op == Py_None || op == Py_Ellipsis
705 || PyLong_CheckExact(op)
Victor Stinnerefb24132016-01-22 12:33:12 +0100706 || PyUnicode_CheckExact(op)
707 /* code_richcompare() uses _PyCode_ConstantKey() internally */
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +0300708 || PyCode_Check(op))
709 {
710 /* Objects of these types are always different from object of other
711 * type and from tuples. */
712 Py_INCREF(op);
713 key = op;
714 }
715 else if (PyBool_Check(op) || PyBytes_CheckExact(op)) {
716 /* Make booleans different from integers 0 and 1.
717 * Avoid BytesWarning from comparing bytes with strings. */
Victor Stinnerefb24132016-01-22 12:33:12 +0100718 key = PyTuple_Pack(2, Py_TYPE(op), op);
719 }
720 else if (PyFloat_CheckExact(op)) {
721 double d = PyFloat_AS_DOUBLE(op);
722 /* all we need is to make the tuple different in either the 0.0
723 * or -0.0 case from all others, just to avoid the "coercion".
724 */
725 if (d == 0.0 && copysign(1.0, d) < 0.0)
726 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
727 else
728 key = PyTuple_Pack(2, Py_TYPE(op), op);
729 }
730 else if (PyComplex_CheckExact(op)) {
731 Py_complex z;
732 int real_negzero, imag_negzero;
733 /* For the complex case we must make complex(x, 0.)
734 different from complex(x, -0.) and complex(0., y)
735 different from complex(-0., y), for any x and y.
736 All four complex zeros must be distinguished.*/
737 z = PyComplex_AsCComplex(op);
738 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
739 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
740 /* use True, False and None singleton as tags for the real and imag
741 * sign, to make tuples different */
742 if (real_negzero && imag_negzero) {
743 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_True);
744 }
745 else if (imag_negzero) {
746 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_False);
747 }
748 else if (real_negzero) {
749 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
750 }
751 else {
752 key = PyTuple_Pack(2, Py_TYPE(op), op);
753 }
754 }
755 else if (PyTuple_CheckExact(op)) {
756 Py_ssize_t i, len;
757 PyObject *tuple;
758
759 len = PyTuple_GET_SIZE(op);
760 tuple = PyTuple_New(len);
761 if (tuple == NULL)
762 return NULL;
763
764 for (i=0; i < len; i++) {
765 PyObject *item, *item_key;
766
767 item = PyTuple_GET_ITEM(op, i);
768 item_key = _PyCode_ConstantKey(item);
769 if (item_key == NULL) {
770 Py_DECREF(tuple);
771 return NULL;
772 }
773
774 PyTuple_SET_ITEM(tuple, i, item_key);
775 }
776
Serhiy Storchaka713640c2017-01-24 20:49:26 +0200777 key = PyTuple_Pack(2, tuple, op);
Victor Stinnerefb24132016-01-22 12:33:12 +0100778 Py_DECREF(tuple);
779 }
780 else if (PyFrozenSet_CheckExact(op)) {
781 Py_ssize_t pos = 0;
782 PyObject *item;
783 Py_hash_t hash;
784 Py_ssize_t i, len;
785 PyObject *tuple, *set;
786
787 len = PySet_GET_SIZE(op);
788 tuple = PyTuple_New(len);
789 if (tuple == NULL)
790 return NULL;
791
792 i = 0;
793 while (_PySet_NextEntry(op, &pos, &item, &hash)) {
794 PyObject *item_key;
795
796 item_key = _PyCode_ConstantKey(item);
797 if (item_key == NULL) {
798 Py_DECREF(tuple);
799 return NULL;
800 }
801
802 assert(i < len);
803 PyTuple_SET_ITEM(tuple, i, item_key);
804 i++;
805 }
806 set = PyFrozenSet_New(tuple);
807 Py_DECREF(tuple);
808 if (set == NULL)
809 return NULL;
810
Serhiy Storchaka713640c2017-01-24 20:49:26 +0200811 key = PyTuple_Pack(2, set, op);
Victor Stinnerefb24132016-01-22 12:33:12 +0100812 Py_DECREF(set);
813 return key;
814 }
815 else {
Martin Panter6245cb32016-04-15 02:14:19 +0000816 /* for other types, use the object identifier as a unique identifier
Victor Stinnerefb24132016-01-22 12:33:12 +0100817 * to ensure that they are seen as unequal. */
818 PyObject *obj_id = PyLong_FromVoidPtr(op);
819 if (obj_id == NULL)
820 return NULL;
821
Serhiy Storchaka713640c2017-01-24 20:49:26 +0200822 key = PyTuple_Pack(2, obj_id, op);
Victor Stinnerefb24132016-01-22 12:33:12 +0100823 Py_DECREF(obj_id);
824 }
825 return key;
826}
827
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000828static PyObject *
829code_richcompare(PyObject *self, PyObject *other, int op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 PyCodeObject *co, *cp;
832 int eq;
Victor Stinnerefb24132016-01-22 12:33:12 +0100833 PyObject *consts1, *consts2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 if ((op != Py_EQ && op != Py_NE) ||
837 !PyCode_Check(self) ||
838 !PyCode_Check(other)) {
Brian Curtindfc80e32011-08-10 20:28:54 -0500839 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 co = (PyCodeObject *)self;
843 cp = (PyCodeObject *)other;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 eq = PyObject_RichCompareBool(co->co_name, cp->co_name, Py_EQ);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100846 if (!eq) goto unequal;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 eq = co->co_argcount == cp->co_argcount;
848 if (!eq) goto unequal;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100849 eq = co->co_posonlyargcount == cp->co_posonlyargcount;
850 if (!eq) goto unequal;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 eq = co->co_kwonlyargcount == cp->co_kwonlyargcount;
852 if (!eq) goto unequal;
853 eq = co->co_nlocals == cp->co_nlocals;
854 if (!eq) goto unequal;
855 eq = co->co_flags == cp->co_flags;
856 if (!eq) goto unequal;
857 eq = co->co_firstlineno == cp->co_firstlineno;
858 if (!eq) goto unequal;
859 eq = PyObject_RichCompareBool(co->co_code, cp->co_code, Py_EQ);
860 if (eq <= 0) goto unequal;
Victor Stinnerefb24132016-01-22 12:33:12 +0100861
862 /* compare constants */
863 consts1 = _PyCode_ConstantKey(co->co_consts);
864 if (!consts1)
865 return NULL;
866 consts2 = _PyCode_ConstantKey(cp->co_consts);
867 if (!consts2) {
868 Py_DECREF(consts1);
869 return NULL;
870 }
871 eq = PyObject_RichCompareBool(consts1, consts2, Py_EQ);
872 Py_DECREF(consts1);
873 Py_DECREF(consts2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 if (eq <= 0) goto unequal;
Victor Stinnerefb24132016-01-22 12:33:12 +0100875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 eq = PyObject_RichCompareBool(co->co_names, cp->co_names, Py_EQ);
877 if (eq <= 0) goto unequal;
878 eq = PyObject_RichCompareBool(co->co_varnames, cp->co_varnames, Py_EQ);
879 if (eq <= 0) goto unequal;
880 eq = PyObject_RichCompareBool(co->co_freevars, cp->co_freevars, Py_EQ);
881 if (eq <= 0) goto unequal;
882 eq = PyObject_RichCompareBool(co->co_cellvars, cp->co_cellvars, Py_EQ);
883 if (eq <= 0) goto unequal;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 if (op == Py_EQ)
886 res = Py_True;
887 else
888 res = Py_False;
889 goto done;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000890
891 unequal:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 if (eq < 0)
893 return NULL;
894 if (op == Py_NE)
895 res = Py_True;
896 else
897 res = Py_False;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000898
899 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 Py_INCREF(res);
901 return res;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000902}
903
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000904static Py_hash_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000905code_hash(PyCodeObject *co)
906{
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000907 Py_hash_t h, h0, h1, h2, h3, h4, h5, h6;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 h0 = PyObject_Hash(co->co_name);
909 if (h0 == -1) return -1;
910 h1 = PyObject_Hash(co->co_code);
911 if (h1 == -1) return -1;
912 h2 = PyObject_Hash(co->co_consts);
913 if (h2 == -1) return -1;
914 h3 = PyObject_Hash(co->co_names);
915 if (h3 == -1) return -1;
916 h4 = PyObject_Hash(co->co_varnames);
917 if (h4 == -1) return -1;
918 h5 = PyObject_Hash(co->co_freevars);
919 if (h5 == -1) return -1;
920 h6 = PyObject_Hash(co->co_cellvars);
921 if (h6 == -1) return -1;
922 h = h0 ^ h1 ^ h2 ^ h3 ^ h4 ^ h5 ^ h6 ^
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100923 co->co_argcount ^ co->co_posonlyargcount ^ co->co_kwonlyargcount ^
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 co->co_nlocals ^ co->co_flags;
925 if (h == -1) h = -2;
926 return h;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000927}
928
929/* XXX code objects need to participate in GC? */
930
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200931static struct PyMethodDef code_methods[] = {
932 {"__sizeof__", (PyCFunction)code_sizeof, METH_NOARGS},
Victor Stinnera9f05d62019-05-24 23:57:23 +0200933 CODE_REPLACE_METHODDEF
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200934 {NULL, NULL} /* sentinel */
935};
936
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000937PyTypeObject PyCode_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 PyVarObject_HEAD_INIT(&PyType_Type, 0)
939 "code",
940 sizeof(PyCodeObject),
941 0,
942 (destructor)code_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200943 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 0, /* tp_getattr */
945 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200946 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 (reprfunc)code_repr, /* tp_repr */
948 0, /* tp_as_number */
949 0, /* tp_as_sequence */
950 0, /* tp_as_mapping */
951 (hashfunc)code_hash, /* tp_hash */
952 0, /* tp_call */
953 0, /* tp_str */
954 PyObject_GenericGetAttr, /* tp_getattro */
955 0, /* tp_setattro */
956 0, /* tp_as_buffer */
957 Py_TPFLAGS_DEFAULT, /* tp_flags */
958 code_doc, /* tp_doc */
959 0, /* tp_traverse */
960 0, /* tp_clear */
961 code_richcompare, /* tp_richcompare */
962 offsetof(PyCodeObject, co_weakreflist), /* tp_weaklistoffset */
963 0, /* tp_iter */
964 0, /* tp_iternext */
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200965 code_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 code_memberlist, /* tp_members */
967 0, /* tp_getset */
968 0, /* tp_base */
969 0, /* tp_dict */
970 0, /* tp_descr_get */
971 0, /* tp_descr_set */
972 0, /* tp_dictoffset */
973 0, /* tp_init */
974 0, /* tp_alloc */
975 code_new, /* tp_new */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000976};
977
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000978/* Use co_lnotab to compute the line number from a bytecode index, addrq. See
979 lnotab_notes.txt for the details of the lnotab representation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000980*/
981
982int
983PyCode_Addr2Line(PyCodeObject *co, int addrq)
984{
Victor Stinner0fcab4a2011-01-04 12:59:15 +0000985 Py_ssize_t size = PyBytes_Size(co->co_lnotab) / 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 unsigned char *p = (unsigned char*)PyBytes_AsString(co->co_lnotab);
987 int line = co->co_firstlineno;
988 int addr = 0;
989 while (--size >= 0) {
990 addr += *p++;
991 if (addr > addrq)
992 break;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100993 line += (signed char)*p;
994 p++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 }
996 return line;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000997}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000998
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000999/* Update *bounds to describe the first and one-past-the-last instructions in
1000 the same line as lasti. Return the number of that line. */
1001int
1002_PyCode_CheckLineNumber(PyCodeObject* co, int lasti, PyAddrPair *bounds)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001003{
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001004 Py_ssize_t size;
1005 int addr, line;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 unsigned char* p;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 p = (unsigned char*)PyBytes_AS_STRING(co->co_lnotab);
1009 size = PyBytes_GET_SIZE(co->co_lnotab) / 2;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 addr = 0;
1012 line = co->co_firstlineno;
1013 assert(line > 0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 /* possible optimization: if f->f_lasti == instr_ub
1016 (likely to be a common case) then we already know
1017 instr_lb -- if we stored the matching value of p
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07001018 somewhere we could skip the first while loop. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 /* See lnotab_notes.txt for the description of
1021 co_lnotab. A point to remember: increments to p
1022 come in (addr, line) pairs. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 bounds->ap_lower = 0;
1025 while (size > 0) {
1026 if (addr + *p > lasti)
1027 break;
1028 addr += *p++;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01001029 if ((signed char)*p)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 bounds->ap_lower = addr;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01001031 line += (signed char)*p;
1032 p++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 --size;
1034 }
1035
1036 if (size > 0) {
1037 while (--size >= 0) {
1038 addr += *p++;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01001039 if ((signed char)*p)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 break;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01001041 p++;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001042 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 bounds->ap_upper = addr;
1044 }
1045 else {
1046 bounds->ap_upper = INT_MAX;
1047 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 return line;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001050}
Brett Cannon5c4de282016-09-07 11:16:41 -07001051
1052
1053int
1054_PyCode_GetExtra(PyObject *code, Py_ssize_t index, void **extra)
1055{
Brett Cannon5c4de282016-09-07 11:16:41 -07001056 if (!PyCode_Check(code)) {
1057 PyErr_BadInternalCall();
Brett Cannon3788b852016-09-07 12:51:08 -07001058 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -07001059 }
1060
Brett Cannond0600ed2016-09-07 14:30:39 -07001061 PyCodeObject *o = (PyCodeObject*) code;
1062 _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra*) o->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -07001063
Brett Cannond0600ed2016-09-07 14:30:39 -07001064 if (co_extra == NULL || co_extra->ce_size <= index) {
Dino Viehlandf3cffd22017-06-21 14:44:36 -07001065 *extra = NULL;
Brett Cannon5c4de282016-09-07 11:16:41 -07001066 return 0;
1067 }
1068
Brett Cannond0600ed2016-09-07 14:30:39 -07001069 *extra = co_extra->ce_extras[index];
Brett Cannon5c4de282016-09-07 11:16:41 -07001070 return 0;
1071}
1072
1073
1074int
1075_PyCode_SetExtra(PyObject *code, Py_ssize_t index, void *extra)
1076{
Victor Stinner81a7be32020-04-14 15:14:01 +02001077 PyInterpreterState *interp = _PyInterpreterState_GET();
Brett Cannon5c4de282016-09-07 11:16:41 -07001078
1079 if (!PyCode_Check(code) || index < 0 ||
Dino Viehlandf3cffd22017-06-21 14:44:36 -07001080 index >= interp->co_extra_user_count) {
Brett Cannon5c4de282016-09-07 11:16:41 -07001081 PyErr_BadInternalCall();
Brett Cannon3788b852016-09-07 12:51:08 -07001082 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -07001083 }
1084
Brett Cannond0600ed2016-09-07 14:30:39 -07001085 PyCodeObject *o = (PyCodeObject*) code;
1086 _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra *) o->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -07001087
Serhiy Storchaka378ebb62017-07-04 15:06:16 +03001088 if (co_extra == NULL || co_extra->ce_size <= index) {
1089 Py_ssize_t i = (co_extra == NULL ? 0 : co_extra->ce_size);
1090 co_extra = PyMem_Realloc(
1091 co_extra,
1092 sizeof(_PyCodeObjectExtra) +
1093 (interp->co_extra_user_count-1) * sizeof(void*));
Brian Coleman6a9122c2017-03-02 10:32:18 +00001094 if (co_extra == NULL) {
Brett Cannon3788b852016-09-07 12:51:08 -07001095 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -07001096 }
Serhiy Storchaka378ebb62017-07-04 15:06:16 +03001097 for (; i < interp->co_extra_user_count; i++) {
Brett Cannond0600ed2016-09-07 14:30:39 -07001098 co_extra->ce_extras[i] = NULL;
Brett Cannon5c4de282016-09-07 11:16:41 -07001099 }
Dino Viehlandf3cffd22017-06-21 14:44:36 -07001100 co_extra->ce_size = interp->co_extra_user_count;
Serhiy Storchaka378ebb62017-07-04 15:06:16 +03001101 o->co_extra = co_extra;
Dino Viehlandf3cffd22017-06-21 14:44:36 -07001102 }
1103
1104 if (co_extra->ce_extras[index] != NULL) {
1105 freefunc free = interp->co_extra_freefuncs[index];
Dino Viehlandf3cffd22017-06-21 14:44:36 -07001106 if (free != NULL) {
1107 free(co_extra->ce_extras[index]);
1108 }
Brett Cannon5c4de282016-09-07 11:16:41 -07001109 }
1110
Brett Cannond0600ed2016-09-07 14:30:39 -07001111 co_extra->ce_extras[index] = extra;
Brett Cannon5c4de282016-09-07 11:16:41 -07001112 return 0;
1113}