blob: 49011db1014e7db87fa6bcb99ca9304a4624c9d1 [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"
Victor Stinner4a21e572020-04-15 02:35:41 +02006#include "structmember.h" // PyMemberDef
Victor Stinner384621c2020-06-22 17:27:35 +02007#include "pycore_code.h" // _PyOpcache
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 Stinner384621c2020-06-22 17:27:35 +020010#include "pycore_tuple.h" // _PyTuple_ITEMS()
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
Ammar Askar3b3b83c2020-06-10 23:31:22 +0000169 /* Make sure that code is indexable with an int, this is
170 a long running assumption in ceval.c and many parts of
171 the interpreter. */
172 if (PyBytes_GET_SIZE(code) > INT_MAX) {
173 PyErr_SetString(PyExc_OverflowError, "co_code larger than INT_MAX");
174 return NULL;
175 }
176
Nick Coghlan078f1812017-12-03 11:12:20 +1000177 /* Check for any inner or outer closure references */
178 n_cellvars = PyTuple_GET_SIZE(cellvars);
179 if (!n_cellvars && !PyTuple_GET_SIZE(freevars)) {
180 flags |= CO_NOFREE;
181 } else {
182 flags &= ~CO_NOFREE;
183 }
184
Serhiy Storchakabd473842018-07-16 09:10:19 +0300185 n_varnames = PyTuple_GET_SIZE(varnames);
Pablo Galindocd74e662019-06-01 18:08:04 +0100186 if (argcount <= n_varnames && kwonlyargcount <= n_varnames) {
Serhiy Storchakabd473842018-07-16 09:10:19 +0300187 /* Never overflows. */
Pablo Galindocd74e662019-06-01 18:08:04 +0100188 total_args = (Py_ssize_t)argcount + (Py_ssize_t)kwonlyargcount +
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100189 ((flags & CO_VARARGS) != 0) + ((flags & CO_VARKEYWORDS) != 0);
Serhiy Storchakabd473842018-07-16 09:10:19 +0300190 }
191 else {
192 total_args = n_varnames + 1;
193 }
194 if (total_args > n_varnames) {
195 PyErr_SetString(PyExc_ValueError, "code: varnames is too small");
196 return NULL;
197 }
198
Benjamin Peterson90037602011-06-25 22:54:45 -0500199 /* Create mapping between cells and arguments if needed. */
200 if (n_cellvars) {
Benjamin Peterson1bf494b2016-09-07 11:28:35 -0700201 bool used_cell2arg = false;
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200202 cell2arg = PyMem_NEW(Py_ssize_t, n_cellvars);
203 if (cell2arg == NULL) {
204 PyErr_NoMemory();
Benjamin Peterson90037602011-06-25 22:54:45 -0500205 return NULL;
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200206 }
Benjamin Peterson90037602011-06-25 22:54:45 -0500207 /* Find cells which are also arguments. */
208 for (i = 0; i < n_cellvars; i++) {
209 Py_ssize_t j;
210 PyObject *cell = PyTuple_GET_ITEM(cellvars, i);
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200211 cell2arg[i] = CO_CELL_NOT_AN_ARG;
Benjamin Peterson90037602011-06-25 22:54:45 -0500212 for (j = 0; j < total_args; j++) {
213 PyObject *arg = PyTuple_GET_ITEM(varnames, j);
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200214 int cmp = PyUnicode_Compare(cell, arg);
215 if (cmp == -1 && PyErr_Occurred()) {
216 PyMem_FREE(cell2arg);
217 return NULL;
218 }
219 if (cmp == 0) {
Benjamin Peterson90037602011-06-25 22:54:45 -0500220 cell2arg[i] = j;
Benjamin Peterson1bf494b2016-09-07 11:28:35 -0700221 used_cell2arg = true;
Benjamin Peterson90037602011-06-25 22:54:45 -0500222 break;
223 }
224 }
225 }
226 if (!used_cell2arg) {
227 PyMem_FREE(cell2arg);
228 cell2arg = NULL;
229 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 }
Victor Stinner92055202020-04-08 00:38:15 +0200231 co = PyObject_New(PyCodeObject, &PyCode_Type);
Benjamin Peterson90037602011-06-25 22:54:45 -0500232 if (co == NULL) {
233 if (cell2arg)
234 PyMem_FREE(cell2arg);
235 return NULL;
236 }
237 co->co_argcount = argcount;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100238 co->co_posonlyargcount = posonlyargcount;
Benjamin Peterson90037602011-06-25 22:54:45 -0500239 co->co_kwonlyargcount = kwonlyargcount;
240 co->co_nlocals = nlocals;
241 co->co_stacksize = stacksize;
242 co->co_flags = flags;
243 Py_INCREF(code);
244 co->co_code = code;
245 Py_INCREF(consts);
246 co->co_consts = consts;
247 Py_INCREF(names);
248 co->co_names = names;
249 Py_INCREF(varnames);
250 co->co_varnames = varnames;
251 Py_INCREF(freevars);
252 co->co_freevars = freevars;
253 Py_INCREF(cellvars);
254 co->co_cellvars = cellvars;
255 co->co_cell2arg = cell2arg;
256 Py_INCREF(filename);
257 co->co_filename = filename;
258 Py_INCREF(name);
259 co->co_name = name;
260 co->co_firstlineno = firstlineno;
261 Py_INCREF(lnotab);
262 co->co_lnotab = lnotab;
263 co->co_zombieframe = NULL;
264 co->co_weakreflist = NULL;
Brett Cannon5c4de282016-09-07 11:16:41 -0700265 co->co_extra = NULL;
Inada Naoki91234a12019-06-03 21:30:58 +0900266
267 co->co_opcache_map = NULL;
268 co->co_opcache = NULL;
269 co->co_opcache_flag = 0;
270 co->co_opcache_size = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000272}
273
Pablo Galindo4a2edc32019-07-01 11:35:05 +0100274PyCodeObject *
275PyCode_New(int argcount, int kwonlyargcount,
276 int nlocals, int stacksize, int flags,
277 PyObject *code, PyObject *consts, PyObject *names,
278 PyObject *varnames, PyObject *freevars, PyObject *cellvars,
279 PyObject *filename, PyObject *name, int firstlineno,
280 PyObject *lnotab)
281{
282 return PyCode_NewWithPosOnlyArgs(argcount, 0, kwonlyargcount, nlocals,
283 stacksize, flags, code, consts, names,
284 varnames, freevars, cellvars, filename,
285 name, firstlineno, lnotab);
286}
287
Inada Naoki91234a12019-06-03 21:30:58 +0900288int
289_PyCode_InitOpcache(PyCodeObject *co)
290{
291 Py_ssize_t co_size = PyBytes_Size(co->co_code) / sizeof(_Py_CODEUNIT);
292 co->co_opcache_map = (unsigned char *)PyMem_Calloc(co_size, 1);
293 if (co->co_opcache_map == NULL) {
294 return -1;
295 }
296
297 _Py_CODEUNIT *opcodes = (_Py_CODEUNIT*)PyBytes_AS_STRING(co->co_code);
298 Py_ssize_t opts = 0;
299
300 for (Py_ssize_t i = 0; i < co_size;) {
301 unsigned char opcode = _Py_OPCODE(opcodes[i]);
302 i++; // 'i' is now aligned to (next_instr - first_instr)
303
304 // TODO: LOAD_METHOD, LOAD_ATTR
305 if (opcode == LOAD_GLOBAL) {
Victor Stinnerea9f1682019-06-04 17:08:24 +0200306 opts++;
307 co->co_opcache_map[i] = (unsigned char)opts;
Inada Naoki91234a12019-06-03 21:30:58 +0900308 if (opts > 254) {
309 break;
310 }
311 }
312 }
313
314 if (opts) {
315 co->co_opcache = (_PyOpcache *)PyMem_Calloc(opts, sizeof(_PyOpcache));
316 if (co->co_opcache == NULL) {
317 PyMem_FREE(co->co_opcache_map);
318 return -1;
319 }
320 }
321 else {
322 PyMem_FREE(co->co_opcache_map);
323 co->co_opcache_map = NULL;
324 co->co_opcache = NULL;
325 }
326
Victor Stinner376ce982019-06-12 04:41:16 +0200327 co->co_opcache_size = (unsigned char)opts;
Inada Naoki91234a12019-06-03 21:30:58 +0900328 return 0;
329}
330
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000331PyCodeObject *
332PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno)
333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 static PyObject *emptystring = NULL;
335 static PyObject *nulltuple = NULL;
336 PyObject *filename_ob = NULL;
337 PyObject *funcname_ob = NULL;
338 PyCodeObject *result = NULL;
339 if (emptystring == NULL) {
340 emptystring = PyBytes_FromString("");
341 if (emptystring == NULL)
342 goto failed;
343 }
344 if (nulltuple == NULL) {
345 nulltuple = PyTuple_New(0);
346 if (nulltuple == NULL)
347 goto failed;
348 }
349 funcname_ob = PyUnicode_FromString(funcname);
350 if (funcname_ob == NULL)
351 goto failed;
352 filename_ob = PyUnicode_DecodeFSDefault(filename);
353 if (filename_ob == NULL)
354 goto failed;
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000355
Pablo Galindo4a2edc32019-07-01 11:35:05 +0100356 result = PyCode_NewWithPosOnlyArgs(
357 0, /* argcount */
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100358 0, /* posonlyargcount */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 0, /* kwonlyargcount */
360 0, /* nlocals */
361 0, /* stacksize */
362 0, /* flags */
363 emptystring, /* code */
364 nulltuple, /* consts */
365 nulltuple, /* names */
366 nulltuple, /* varnames */
367 nulltuple, /* freevars */
368 nulltuple, /* cellvars */
369 filename_ob, /* filename */
370 funcname_ob, /* name */
371 firstlineno, /* firstlineno */
372 emptystring /* lnotab */
373 );
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000374
375failed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 Py_XDECREF(funcname_ob);
377 Py_XDECREF(filename_ob);
378 return result;
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000379}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000380
381#define OFF(x) offsetof(PyCodeObject, x)
382
383static PyMemberDef code_memberlist[] = {
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100384 {"co_argcount", T_INT, OFF(co_argcount), READONLY},
385 {"co_posonlyargcount", T_INT, OFF(co_posonlyargcount), READONLY},
386 {"co_kwonlyargcount", T_INT, OFF(co_kwonlyargcount), READONLY},
387 {"co_nlocals", T_INT, OFF(co_nlocals), READONLY},
388 {"co_stacksize",T_INT, OFF(co_stacksize), READONLY},
389 {"co_flags", T_INT, OFF(co_flags), READONLY},
390 {"co_code", T_OBJECT, OFF(co_code), READONLY},
391 {"co_consts", T_OBJECT, OFF(co_consts), READONLY},
392 {"co_names", T_OBJECT, OFF(co_names), READONLY},
393 {"co_varnames", T_OBJECT, OFF(co_varnames), READONLY},
394 {"co_freevars", T_OBJECT, OFF(co_freevars), READONLY},
395 {"co_cellvars", T_OBJECT, OFF(co_cellvars), READONLY},
396 {"co_filename", T_OBJECT, OFF(co_filename), READONLY},
397 {"co_name", T_OBJECT, OFF(co_name), READONLY},
398 {"co_firstlineno", T_INT, OFF(co_firstlineno), READONLY},
399 {"co_lnotab", T_OBJECT, OFF(co_lnotab), READONLY},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 {NULL} /* Sentinel */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000401};
402
403/* Helper for code_new: return a shallow copy of a tuple that is
404 guaranteed to contain exact strings, by converting string subclasses
405 to exact strings and complaining if a non-string is found. */
406static PyObject*
407validate_and_copy_tuple(PyObject *tup)
408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 PyObject *newtuple;
410 PyObject *item;
411 Py_ssize_t i, len;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 len = PyTuple_GET_SIZE(tup);
414 newtuple = PyTuple_New(len);
415 if (newtuple == NULL)
416 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 for (i = 0; i < len; i++) {
419 item = PyTuple_GET_ITEM(tup, i);
420 if (PyUnicode_CheckExact(item)) {
421 Py_INCREF(item);
422 }
423 else if (!PyUnicode_Check(item)) {
424 PyErr_Format(
425 PyExc_TypeError,
426 "name tuples must contain only "
427 "strings, not '%.500s'",
Victor Stinner58ac7002020-02-07 03:04:21 +0100428 Py_TYPE(item)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 Py_DECREF(newtuple);
430 return NULL;
431 }
432 else {
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100433 item = _PyUnicode_Copy(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 if (item == NULL) {
435 Py_DECREF(newtuple);
436 return NULL;
437 }
438 }
439 PyTuple_SET_ITEM(newtuple, i, item);
440 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 return newtuple;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000443}
444
445PyDoc_STRVAR(code_doc,
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100446"code(argcount, posonlyargcount, kwonlyargcount, nlocals, stacksize,\n\
447 flags, codestring, constants, names, varnames, filename, name,\n\
448 firstlineno, lnotab[, freevars[, cellvars]])\n\
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000449\n\
450Create a code object. Not for the faint of heart.");
451
452static PyObject *
453code_new(PyTypeObject *type, PyObject *args, PyObject *kw)
454{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 int argcount;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100456 int posonlyargcount;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 int kwonlyargcount;
458 int nlocals;
459 int stacksize;
460 int flags;
461 PyObject *co = NULL;
462 PyObject *code;
463 PyObject *consts;
464 PyObject *names, *ournames = NULL;
465 PyObject *varnames, *ourvarnames = NULL;
466 PyObject *freevars = NULL, *ourfreevars = NULL;
467 PyObject *cellvars = NULL, *ourcellvars = NULL;
468 PyObject *filename;
469 PyObject *name;
470 int firstlineno;
471 PyObject *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000472
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100473 if (!PyArg_ParseTuple(args, "iiiiiiSO!O!O!UUiS|O!O!:code",
474 &argcount, &posonlyargcount, &kwonlyargcount,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 &nlocals, &stacksize, &flags,
476 &code,
477 &PyTuple_Type, &consts,
478 &PyTuple_Type, &names,
479 &PyTuple_Type, &varnames,
480 &filename, &name,
481 &firstlineno, &lnotab,
482 &PyTuple_Type, &freevars,
483 &PyTuple_Type, &cellvars))
484 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000485
Pablo Galindo3b57f502019-06-01 21:18:48 +0100486 if (PySys_Audit("code.__new__", "OOOiiiiii",
487 code, filename, name, argcount, posonlyargcount,
488 kwonlyargcount, nlocals, stacksize, flags) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700489 goto cleanup;
490 }
491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 if (argcount < 0) {
493 PyErr_SetString(
494 PyExc_ValueError,
495 "code: argcount must not be negative");
496 goto cleanup;
497 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000498
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100499 if (posonlyargcount < 0) {
500 PyErr_SetString(
501 PyExc_ValueError,
502 "code: posonlyargcount must not be negative");
503 goto cleanup;
504 }
505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 if (kwonlyargcount < 0) {
507 PyErr_SetString(
508 PyExc_ValueError,
509 "code: kwonlyargcount must not be negative");
510 goto cleanup;
511 }
512 if (nlocals < 0) {
513 PyErr_SetString(
514 PyExc_ValueError,
515 "code: nlocals must not be negative");
516 goto cleanup;
517 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 ournames = validate_and_copy_tuple(names);
520 if (ournames == NULL)
521 goto cleanup;
522 ourvarnames = validate_and_copy_tuple(varnames);
523 if (ourvarnames == NULL)
524 goto cleanup;
525 if (freevars)
526 ourfreevars = validate_and_copy_tuple(freevars);
527 else
528 ourfreevars = PyTuple_New(0);
529 if (ourfreevars == NULL)
530 goto cleanup;
531 if (cellvars)
532 ourcellvars = validate_and_copy_tuple(cellvars);
533 else
534 ourcellvars = PyTuple_New(0);
535 if (ourcellvars == NULL)
536 goto cleanup;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000537
Pablo Galindo4a2edc32019-07-01 11:35:05 +0100538 co = (PyObject *)PyCode_NewWithPosOnlyArgs(argcount, posonlyargcount,
539 kwonlyargcount,
540 nlocals, stacksize, flags,
541 code, consts, ournames,
542 ourvarnames, ourfreevars,
543 ourcellvars, filename,
544 name, firstlineno, lnotab);
Victor Stinnera2783132020-01-27 23:24:13 +0100545 cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 Py_XDECREF(ournames);
547 Py_XDECREF(ourvarnames);
548 Py_XDECREF(ourfreevars);
549 Py_XDECREF(ourcellvars);
550 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000551}
552
553static void
554code_dealloc(PyCodeObject *co)
555{
Inada Naoki91234a12019-06-03 21:30:58 +0900556 if (co->co_opcache != NULL) {
557 PyMem_FREE(co->co_opcache);
558 }
559 if (co->co_opcache_map != NULL) {
560 PyMem_FREE(co->co_opcache_map);
561 }
562 co->co_opcache_flag = 0;
563 co->co_opcache_size = 0;
564
Brett Cannon5c4de282016-09-07 11:16:41 -0700565 if (co->co_extra != NULL) {
Victor Stinner81a7be32020-04-14 15:14:01 +0200566 PyInterpreterState *interp = _PyInterpreterState_GET();
Brett Cannond0600ed2016-09-07 14:30:39 -0700567 _PyCodeObjectExtra *co_extra = co->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700568
Brett Cannond0600ed2016-09-07 14:30:39 -0700569 for (Py_ssize_t i = 0; i < co_extra->ce_size; i++) {
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700570 freefunc free_extra = interp->co_extra_freefuncs[i];
Brett Cannon5c4de282016-09-07 11:16:41 -0700571
572 if (free_extra != NULL) {
Brett Cannond0600ed2016-09-07 14:30:39 -0700573 free_extra(co_extra->ce_extras[i]);
Brett Cannon5c4de282016-09-07 11:16:41 -0700574 }
575 }
576
Victor Stinner23e79442017-06-28 02:12:00 +0200577 PyMem_Free(co_extra);
Brett Cannon5c4de282016-09-07 11:16:41 -0700578 }
579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 Py_XDECREF(co->co_code);
581 Py_XDECREF(co->co_consts);
582 Py_XDECREF(co->co_names);
583 Py_XDECREF(co->co_varnames);
584 Py_XDECREF(co->co_freevars);
585 Py_XDECREF(co->co_cellvars);
586 Py_XDECREF(co->co_filename);
587 Py_XDECREF(co->co_name);
588 Py_XDECREF(co->co_lnotab);
Benjamin Peterson90037602011-06-25 22:54:45 -0500589 if (co->co_cell2arg != NULL)
590 PyMem_FREE(co->co_cell2arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 if (co->co_zombieframe != NULL)
592 PyObject_GC_Del(co->co_zombieframe);
593 if (co->co_weakreflist != NULL)
594 PyObject_ClearWeakRefs((PyObject*)co);
595 PyObject_DEL(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000596}
597
598static PyObject *
Victor Stinnera9f05d62019-05-24 23:57:23 +0200599code_sizeof(PyCodeObject *co, PyObject *Py_UNUSED(args))
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200600{
Dong-hee Nab4dc6af2017-04-20 16:31:17 +0900601 Py_ssize_t res = _PyObject_SIZE(Py_TYPE(co));
602 _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra*) co->co_extra;
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200603
Serhiy Storchaka378ebb62017-07-04 15:06:16 +0300604 if (co->co_cell2arg != NULL && co->co_cellvars != NULL) {
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200605 res += PyTuple_GET_SIZE(co->co_cellvars) * sizeof(Py_ssize_t);
Serhiy Storchaka378ebb62017-07-04 15:06:16 +0300606 }
607 if (co_extra != NULL) {
608 res += sizeof(_PyCodeObjectExtra) +
609 (co_extra->ce_size-1) * sizeof(co_extra->ce_extras[0]);
610 }
Inada Naoki91234a12019-06-03 21:30:58 +0900611 if (co->co_opcache != NULL) {
612 assert(co->co_opcache_map != NULL);
613 // co_opcache_map
614 res += PyBytes_GET_SIZE(co->co_code) / sizeof(_Py_CODEUNIT);
615 // co_opcache
616 res += co->co_opcache_size * sizeof(_PyOpcache);
617 }
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200618 return PyLong_FromSsize_t(res);
619}
620
Victor Stinnera9f05d62019-05-24 23:57:23 +0200621/*[clinic input]
622code.replace
623
624 *
625 co_argcount: int(c_default="self->co_argcount") = -1
626 co_posonlyargcount: int(c_default="self->co_posonlyargcount") = -1
627 co_kwonlyargcount: int(c_default="self->co_kwonlyargcount") = -1
628 co_nlocals: int(c_default="self->co_nlocals") = -1
629 co_stacksize: int(c_default="self->co_stacksize") = -1
630 co_flags: int(c_default="self->co_flags") = -1
631 co_firstlineno: int(c_default="self->co_firstlineno") = -1
632 co_code: PyBytesObject(c_default="(PyBytesObject *)self->co_code") = None
633 co_consts: object(subclass_of="&PyTuple_Type", c_default="self->co_consts") = None
634 co_names: object(subclass_of="&PyTuple_Type", c_default="self->co_names") = None
635 co_varnames: object(subclass_of="&PyTuple_Type", c_default="self->co_varnames") = None
636 co_freevars: object(subclass_of="&PyTuple_Type", c_default="self->co_freevars") = None
637 co_cellvars: object(subclass_of="&PyTuple_Type", c_default="self->co_cellvars") = None
638 co_filename: unicode(c_default="self->co_filename") = None
639 co_name: unicode(c_default="self->co_name") = None
640 co_lnotab: PyBytesObject(c_default="(PyBytesObject *)self->co_lnotab") = None
641
Anthony Sottile22424c02020-01-01 01:11:16 -0500642Return a copy of the code object with new values for the specified fields.
Victor Stinnera9f05d62019-05-24 23:57:23 +0200643[clinic start generated code]*/
644
645static PyObject *
646code_replace_impl(PyCodeObject *self, int co_argcount,
647 int co_posonlyargcount, int co_kwonlyargcount,
648 int co_nlocals, int co_stacksize, int co_flags,
649 int co_firstlineno, PyBytesObject *co_code,
650 PyObject *co_consts, PyObject *co_names,
651 PyObject *co_varnames, PyObject *co_freevars,
652 PyObject *co_cellvars, PyObject *co_filename,
653 PyObject *co_name, PyBytesObject *co_lnotab)
Anthony Sottile22424c02020-01-01 01:11:16 -0500654/*[clinic end generated code: output=25c8e303913bcace input=d9051bc8f24e6b28]*/
Victor Stinnera9f05d62019-05-24 23:57:23 +0200655{
656#define CHECK_INT_ARG(ARG) \
657 if (ARG < 0) { \
658 PyErr_SetString(PyExc_ValueError, \
659 #ARG " must be a positive integer"); \
660 return NULL; \
661 }
662
663 CHECK_INT_ARG(co_argcount);
664 CHECK_INT_ARG(co_posonlyargcount);
665 CHECK_INT_ARG(co_kwonlyargcount);
666 CHECK_INT_ARG(co_nlocals);
667 CHECK_INT_ARG(co_stacksize);
668 CHECK_INT_ARG(co_flags);
669 CHECK_INT_ARG(co_firstlineno);
670
671#undef CHECK_INT_ARG
672
Steve Dowerc7c01ab2019-11-26 16:27:50 -0800673 if (PySys_Audit("code.__new__", "OOOiiiiii",
674 co_code, co_filename, co_name, co_argcount,
675 co_posonlyargcount, co_kwonlyargcount, co_nlocals,
676 co_stacksize, co_flags) < 0) {
677 return NULL;
678 }
679
Pablo Galindo4a2edc32019-07-01 11:35:05 +0100680 return (PyObject *)PyCode_NewWithPosOnlyArgs(
Victor Stinnera9f05d62019-05-24 23:57:23 +0200681 co_argcount, co_posonlyargcount, co_kwonlyargcount, co_nlocals,
682 co_stacksize, co_flags, (PyObject*)co_code, co_consts, co_names,
683 co_varnames, co_freevars, co_cellvars, co_filename, co_name,
684 co_firstlineno, (PyObject*)co_lnotab);
685}
686
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200687static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000688code_repr(PyCodeObject *co)
689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 int lineno;
691 if (co->co_firstlineno != 0)
692 lineno = co->co_firstlineno;
693 else
694 lineno = -1;
695 if (co->co_filename && PyUnicode_Check(co->co_filename)) {
696 return PyUnicode_FromFormat(
Victor Stinneraaa4e9a2011-01-05 03:33:26 +0000697 "<code object %U at %p, file \"%U\", line %d>",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 co->co_name, co, co->co_filename, lineno);
699 } else {
700 return PyUnicode_FromFormat(
Victor Stinneraaa4e9a2011-01-05 03:33:26 +0000701 "<code object %U at %p, file ???, line %d>",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 co->co_name, co, lineno);
703 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000704}
705
Victor Stinnerefb24132016-01-22 12:33:12 +0100706PyObject*
707_PyCode_ConstantKey(PyObject *op)
708{
709 PyObject *key;
710
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +0300711 /* Py_None and Py_Ellipsis are singletons. */
Victor Stinnerefb24132016-01-22 12:33:12 +0100712 if (op == Py_None || op == Py_Ellipsis
713 || PyLong_CheckExact(op)
Victor Stinnerefb24132016-01-22 12:33:12 +0100714 || PyUnicode_CheckExact(op)
715 /* code_richcompare() uses _PyCode_ConstantKey() internally */
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +0300716 || PyCode_Check(op))
717 {
718 /* Objects of these types are always different from object of other
719 * type and from tuples. */
720 Py_INCREF(op);
721 key = op;
722 }
723 else if (PyBool_Check(op) || PyBytes_CheckExact(op)) {
724 /* Make booleans different from integers 0 and 1.
725 * Avoid BytesWarning from comparing bytes with strings. */
Victor Stinnerefb24132016-01-22 12:33:12 +0100726 key = PyTuple_Pack(2, Py_TYPE(op), op);
727 }
728 else if (PyFloat_CheckExact(op)) {
729 double d = PyFloat_AS_DOUBLE(op);
730 /* all we need is to make the tuple different in either the 0.0
731 * or -0.0 case from all others, just to avoid the "coercion".
732 */
733 if (d == 0.0 && copysign(1.0, d) < 0.0)
734 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
735 else
736 key = PyTuple_Pack(2, Py_TYPE(op), op);
737 }
738 else if (PyComplex_CheckExact(op)) {
739 Py_complex z;
740 int real_negzero, imag_negzero;
741 /* For the complex case we must make complex(x, 0.)
742 different from complex(x, -0.) and complex(0., y)
743 different from complex(-0., y), for any x and y.
744 All four complex zeros must be distinguished.*/
745 z = PyComplex_AsCComplex(op);
746 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
747 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
748 /* use True, False and None singleton as tags for the real and imag
749 * sign, to make tuples different */
750 if (real_negzero && imag_negzero) {
751 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_True);
752 }
753 else if (imag_negzero) {
754 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_False);
755 }
756 else if (real_negzero) {
757 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
758 }
759 else {
760 key = PyTuple_Pack(2, Py_TYPE(op), op);
761 }
762 }
763 else if (PyTuple_CheckExact(op)) {
764 Py_ssize_t i, len;
765 PyObject *tuple;
766
767 len = PyTuple_GET_SIZE(op);
768 tuple = PyTuple_New(len);
769 if (tuple == NULL)
770 return NULL;
771
772 for (i=0; i < len; i++) {
773 PyObject *item, *item_key;
774
775 item = PyTuple_GET_ITEM(op, i);
776 item_key = _PyCode_ConstantKey(item);
777 if (item_key == NULL) {
778 Py_DECREF(tuple);
779 return NULL;
780 }
781
782 PyTuple_SET_ITEM(tuple, i, item_key);
783 }
784
Serhiy Storchaka713640c2017-01-24 20:49:26 +0200785 key = PyTuple_Pack(2, tuple, op);
Victor Stinnerefb24132016-01-22 12:33:12 +0100786 Py_DECREF(tuple);
787 }
788 else if (PyFrozenSet_CheckExact(op)) {
789 Py_ssize_t pos = 0;
790 PyObject *item;
791 Py_hash_t hash;
792 Py_ssize_t i, len;
793 PyObject *tuple, *set;
794
795 len = PySet_GET_SIZE(op);
796 tuple = PyTuple_New(len);
797 if (tuple == NULL)
798 return NULL;
799
800 i = 0;
801 while (_PySet_NextEntry(op, &pos, &item, &hash)) {
802 PyObject *item_key;
803
804 item_key = _PyCode_ConstantKey(item);
805 if (item_key == NULL) {
806 Py_DECREF(tuple);
807 return NULL;
808 }
809
810 assert(i < len);
811 PyTuple_SET_ITEM(tuple, i, item_key);
812 i++;
813 }
814 set = PyFrozenSet_New(tuple);
815 Py_DECREF(tuple);
816 if (set == NULL)
817 return NULL;
818
Serhiy Storchaka713640c2017-01-24 20:49:26 +0200819 key = PyTuple_Pack(2, set, op);
Victor Stinnerefb24132016-01-22 12:33:12 +0100820 Py_DECREF(set);
821 return key;
822 }
823 else {
Martin Panter6245cb32016-04-15 02:14:19 +0000824 /* for other types, use the object identifier as a unique identifier
Victor Stinnerefb24132016-01-22 12:33:12 +0100825 * to ensure that they are seen as unequal. */
826 PyObject *obj_id = PyLong_FromVoidPtr(op);
827 if (obj_id == NULL)
828 return NULL;
829
Serhiy Storchaka713640c2017-01-24 20:49:26 +0200830 key = PyTuple_Pack(2, obj_id, op);
Victor Stinnerefb24132016-01-22 12:33:12 +0100831 Py_DECREF(obj_id);
832 }
833 return key;
834}
835
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000836static PyObject *
837code_richcompare(PyObject *self, PyObject *other, int op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000838{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 PyCodeObject *co, *cp;
840 int eq;
Victor Stinnerefb24132016-01-22 12:33:12 +0100841 PyObject *consts1, *consts2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 if ((op != Py_EQ && op != Py_NE) ||
845 !PyCode_Check(self) ||
846 !PyCode_Check(other)) {
Brian Curtindfc80e32011-08-10 20:28:54 -0500847 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 co = (PyCodeObject *)self;
851 cp = (PyCodeObject *)other;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 eq = PyObject_RichCompareBool(co->co_name, cp->co_name, Py_EQ);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100854 if (!eq) goto unequal;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 eq = co->co_argcount == cp->co_argcount;
856 if (!eq) goto unequal;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100857 eq = co->co_posonlyargcount == cp->co_posonlyargcount;
858 if (!eq) goto unequal;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 eq = co->co_kwonlyargcount == cp->co_kwonlyargcount;
860 if (!eq) goto unequal;
861 eq = co->co_nlocals == cp->co_nlocals;
862 if (!eq) goto unequal;
863 eq = co->co_flags == cp->co_flags;
864 if (!eq) goto unequal;
865 eq = co->co_firstlineno == cp->co_firstlineno;
866 if (!eq) goto unequal;
867 eq = PyObject_RichCompareBool(co->co_code, cp->co_code, Py_EQ);
868 if (eq <= 0) goto unequal;
Victor Stinnerefb24132016-01-22 12:33:12 +0100869
870 /* compare constants */
871 consts1 = _PyCode_ConstantKey(co->co_consts);
872 if (!consts1)
873 return NULL;
874 consts2 = _PyCode_ConstantKey(cp->co_consts);
875 if (!consts2) {
876 Py_DECREF(consts1);
877 return NULL;
878 }
879 eq = PyObject_RichCompareBool(consts1, consts2, Py_EQ);
880 Py_DECREF(consts1);
881 Py_DECREF(consts2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 if (eq <= 0) goto unequal;
Victor Stinnerefb24132016-01-22 12:33:12 +0100883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 eq = PyObject_RichCompareBool(co->co_names, cp->co_names, Py_EQ);
885 if (eq <= 0) goto unequal;
886 eq = PyObject_RichCompareBool(co->co_varnames, cp->co_varnames, Py_EQ);
887 if (eq <= 0) goto unequal;
888 eq = PyObject_RichCompareBool(co->co_freevars, cp->co_freevars, Py_EQ);
889 if (eq <= 0) goto unequal;
890 eq = PyObject_RichCompareBool(co->co_cellvars, cp->co_cellvars, Py_EQ);
891 if (eq <= 0) goto unequal;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 if (op == Py_EQ)
894 res = Py_True;
895 else
896 res = Py_False;
897 goto done;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000898
899 unequal:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 if (eq < 0)
901 return NULL;
902 if (op == Py_NE)
903 res = Py_True;
904 else
905 res = Py_False;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000906
907 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 Py_INCREF(res);
909 return res;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000910}
911
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000912static Py_hash_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000913code_hash(PyCodeObject *co)
914{
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000915 Py_hash_t h, h0, h1, h2, h3, h4, h5, h6;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 h0 = PyObject_Hash(co->co_name);
917 if (h0 == -1) return -1;
918 h1 = PyObject_Hash(co->co_code);
919 if (h1 == -1) return -1;
920 h2 = PyObject_Hash(co->co_consts);
921 if (h2 == -1) return -1;
922 h3 = PyObject_Hash(co->co_names);
923 if (h3 == -1) return -1;
924 h4 = PyObject_Hash(co->co_varnames);
925 if (h4 == -1) return -1;
926 h5 = PyObject_Hash(co->co_freevars);
927 if (h5 == -1) return -1;
928 h6 = PyObject_Hash(co->co_cellvars);
929 if (h6 == -1) return -1;
930 h = h0 ^ h1 ^ h2 ^ h3 ^ h4 ^ h5 ^ h6 ^
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100931 co->co_argcount ^ co->co_posonlyargcount ^ co->co_kwonlyargcount ^
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 co->co_nlocals ^ co->co_flags;
933 if (h == -1) h = -2;
934 return h;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000935}
936
937/* XXX code objects need to participate in GC? */
938
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200939static struct PyMethodDef code_methods[] = {
940 {"__sizeof__", (PyCFunction)code_sizeof, METH_NOARGS},
Victor Stinnera9f05d62019-05-24 23:57:23 +0200941 CODE_REPLACE_METHODDEF
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200942 {NULL, NULL} /* sentinel */
943};
944
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000945PyTypeObject PyCode_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 PyVarObject_HEAD_INIT(&PyType_Type, 0)
947 "code",
948 sizeof(PyCodeObject),
949 0,
950 (destructor)code_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200951 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 0, /* tp_getattr */
953 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200954 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 (reprfunc)code_repr, /* tp_repr */
956 0, /* tp_as_number */
957 0, /* tp_as_sequence */
958 0, /* tp_as_mapping */
959 (hashfunc)code_hash, /* tp_hash */
960 0, /* tp_call */
961 0, /* tp_str */
962 PyObject_GenericGetAttr, /* tp_getattro */
963 0, /* tp_setattro */
964 0, /* tp_as_buffer */
965 Py_TPFLAGS_DEFAULT, /* tp_flags */
966 code_doc, /* tp_doc */
967 0, /* tp_traverse */
968 0, /* tp_clear */
969 code_richcompare, /* tp_richcompare */
970 offsetof(PyCodeObject, co_weakreflist), /* tp_weaklistoffset */
971 0, /* tp_iter */
972 0, /* tp_iternext */
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200973 code_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 code_memberlist, /* tp_members */
975 0, /* tp_getset */
976 0, /* tp_base */
977 0, /* tp_dict */
978 0, /* tp_descr_get */
979 0, /* tp_descr_set */
980 0, /* tp_dictoffset */
981 0, /* tp_init */
982 0, /* tp_alloc */
983 code_new, /* tp_new */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000984};
985
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000986/* Use co_lnotab to compute the line number from a bytecode index, addrq. See
987 lnotab_notes.txt for the details of the lnotab representation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000988*/
989
990int
991PyCode_Addr2Line(PyCodeObject *co, int addrq)
992{
Victor Stinner0fcab4a2011-01-04 12:59:15 +0000993 Py_ssize_t size = PyBytes_Size(co->co_lnotab) / 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 unsigned char *p = (unsigned char*)PyBytes_AsString(co->co_lnotab);
995 int line = co->co_firstlineno;
996 int addr = 0;
997 while (--size >= 0) {
998 addr += *p++;
999 if (addr > addrq)
1000 break;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01001001 line += (signed char)*p;
1002 p++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 }
1004 return line;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001005}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001006
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00001007/* Update *bounds to describe the first and one-past-the-last instructions in
1008 the same line as lasti. Return the number of that line. */
1009int
1010_PyCode_CheckLineNumber(PyCodeObject* co, int lasti, PyAddrPair *bounds)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001011{
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001012 Py_ssize_t size;
1013 int addr, line;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 unsigned char* p;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 p = (unsigned char*)PyBytes_AS_STRING(co->co_lnotab);
1017 size = PyBytes_GET_SIZE(co->co_lnotab) / 2;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 addr = 0;
1020 line = co->co_firstlineno;
1021 assert(line > 0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 /* possible optimization: if f->f_lasti == instr_ub
1024 (likely to be a common case) then we already know
1025 instr_lb -- if we stored the matching value of p
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07001026 somewhere we could skip the first while loop. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 /* See lnotab_notes.txt for the description of
1029 co_lnotab. A point to remember: increments to p
1030 come in (addr, line) pairs. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 bounds->ap_lower = 0;
1033 while (size > 0) {
1034 if (addr + *p > lasti)
1035 break;
1036 addr += *p++;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01001037 if ((signed char)*p)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 bounds->ap_lower = addr;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01001039 line += (signed char)*p;
1040 p++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 --size;
1042 }
1043
1044 if (size > 0) {
1045 while (--size >= 0) {
1046 addr += *p++;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01001047 if ((signed char)*p)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 break;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01001049 p++;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001050 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 bounds->ap_upper = addr;
1052 }
1053 else {
1054 bounds->ap_upper = INT_MAX;
1055 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 return line;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001058}
Brett Cannon5c4de282016-09-07 11:16:41 -07001059
1060
1061int
1062_PyCode_GetExtra(PyObject *code, Py_ssize_t index, void **extra)
1063{
Brett Cannon5c4de282016-09-07 11:16:41 -07001064 if (!PyCode_Check(code)) {
1065 PyErr_BadInternalCall();
Brett Cannon3788b852016-09-07 12:51:08 -07001066 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -07001067 }
1068
Brett Cannond0600ed2016-09-07 14:30:39 -07001069 PyCodeObject *o = (PyCodeObject*) code;
1070 _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra*) o->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -07001071
Brett Cannond0600ed2016-09-07 14:30:39 -07001072 if (co_extra == NULL || co_extra->ce_size <= index) {
Dino Viehlandf3cffd22017-06-21 14:44:36 -07001073 *extra = NULL;
Brett Cannon5c4de282016-09-07 11:16:41 -07001074 return 0;
1075 }
1076
Brett Cannond0600ed2016-09-07 14:30:39 -07001077 *extra = co_extra->ce_extras[index];
Brett Cannon5c4de282016-09-07 11:16:41 -07001078 return 0;
1079}
1080
1081
1082int
1083_PyCode_SetExtra(PyObject *code, Py_ssize_t index, void *extra)
1084{
Victor Stinner81a7be32020-04-14 15:14:01 +02001085 PyInterpreterState *interp = _PyInterpreterState_GET();
Brett Cannon5c4de282016-09-07 11:16:41 -07001086
1087 if (!PyCode_Check(code) || index < 0 ||
Dino Viehlandf3cffd22017-06-21 14:44:36 -07001088 index >= interp->co_extra_user_count) {
Brett Cannon5c4de282016-09-07 11:16:41 -07001089 PyErr_BadInternalCall();
Brett Cannon3788b852016-09-07 12:51:08 -07001090 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -07001091 }
1092
Brett Cannond0600ed2016-09-07 14:30:39 -07001093 PyCodeObject *o = (PyCodeObject*) code;
1094 _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra *) o->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -07001095
Serhiy Storchaka378ebb62017-07-04 15:06:16 +03001096 if (co_extra == NULL || co_extra->ce_size <= index) {
1097 Py_ssize_t i = (co_extra == NULL ? 0 : co_extra->ce_size);
1098 co_extra = PyMem_Realloc(
1099 co_extra,
1100 sizeof(_PyCodeObjectExtra) +
1101 (interp->co_extra_user_count-1) * sizeof(void*));
Brian Coleman6a9122c2017-03-02 10:32:18 +00001102 if (co_extra == NULL) {
Brett Cannon3788b852016-09-07 12:51:08 -07001103 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -07001104 }
Serhiy Storchaka378ebb62017-07-04 15:06:16 +03001105 for (; i < interp->co_extra_user_count; i++) {
Brett Cannond0600ed2016-09-07 14:30:39 -07001106 co_extra->ce_extras[i] = NULL;
Brett Cannon5c4de282016-09-07 11:16:41 -07001107 }
Dino Viehlandf3cffd22017-06-21 14:44:36 -07001108 co_extra->ce_size = interp->co_extra_user_count;
Serhiy Storchaka378ebb62017-07-04 15:06:16 +03001109 o->co_extra = co_extra;
Dino Viehlandf3cffd22017-06-21 14:44:36 -07001110 }
1111
1112 if (co_extra->ce_extras[index] != NULL) {
1113 freefunc free = interp->co_extra_freefuncs[index];
Dino Viehlandf3cffd22017-06-21 14:44:36 -07001114 if (free != NULL) {
1115 free(co_extra->ce_extras[index]);
1116 }
Brett Cannon5c4de282016-09-07 11:16:41 -07001117 }
1118
Brett Cannond0600ed2016-09-07 14:30:39 -07001119 co_extra->ce_extras[index] = extra;
Brett Cannon5c4de282016-09-07 11:16:41 -07001120 return 0;
1121}