blob: c86d0e1f4ab71492423e81be6cd479088a23db6b [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
Pablo Galindo109826c2020-10-20 06:22:44 +0100304 // TODO: LOAD_METHOD
305 if (opcode == LOAD_GLOBAL || opcode == LOAD_ATTR) {
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
Serhiy Storchaka0f9aa472020-07-10 10:12:04 +0300445/*[clinic input]
446@classmethod
447code.__new__ as code_new
448
449 argcount: int
450 posonlyargcount: int
451 kwonlyargcount: int
452 nlocals: int
453 stacksize: int
454 flags: int
455 codestring as code: object(subclass_of="&PyBytes_Type")
456 constants as consts: object(subclass_of="&PyTuple_Type")
457 names: object(subclass_of="&PyTuple_Type")
458 varnames: object(subclass_of="&PyTuple_Type")
459 filename: unicode
460 name: unicode
461 firstlineno: int
462 lnotab: object(subclass_of="&PyBytes_Type")
463 freevars: object(subclass_of="&PyTuple_Type", c_default="NULL") = ()
464 cellvars: object(subclass_of="&PyTuple_Type", c_default="NULL") = ()
465 /
466
467Create a code object. Not for the faint of heart.
468[clinic start generated code]*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000469
470static PyObject *
Serhiy Storchaka0f9aa472020-07-10 10:12:04 +0300471code_new_impl(PyTypeObject *type, int argcount, int posonlyargcount,
472 int kwonlyargcount, int nlocals, int stacksize, int flags,
473 PyObject *code, PyObject *consts, PyObject *names,
474 PyObject *varnames, PyObject *filename, PyObject *name,
475 int firstlineno, PyObject *lnotab, PyObject *freevars,
476 PyObject *cellvars)
477/*[clinic end generated code: output=612aac5395830184 input=85e678ea4178f234]*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 PyObject *co = NULL;
Serhiy Storchaka0f9aa472020-07-10 10:12:04 +0300480 PyObject *ournames = NULL;
481 PyObject *ourvarnames = NULL;
482 PyObject *ourfreevars = NULL;
483 PyObject *ourcellvars = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000484
Pablo Galindo3b57f502019-06-01 21:18:48 +0100485 if (PySys_Audit("code.__new__", "OOOiiiiii",
486 code, filename, name, argcount, posonlyargcount,
487 kwonlyargcount, nlocals, stacksize, flags) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700488 goto cleanup;
489 }
490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 if (argcount < 0) {
492 PyErr_SetString(
493 PyExc_ValueError,
494 "code: argcount must not be negative");
495 goto cleanup;
496 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000497
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100498 if (posonlyargcount < 0) {
499 PyErr_SetString(
500 PyExc_ValueError,
501 "code: posonlyargcount must not be negative");
502 goto cleanup;
503 }
504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 if (kwonlyargcount < 0) {
506 PyErr_SetString(
507 PyExc_ValueError,
508 "code: kwonlyargcount must not be negative");
509 goto cleanup;
510 }
511 if (nlocals < 0) {
512 PyErr_SetString(
513 PyExc_ValueError,
514 "code: nlocals must not be negative");
515 goto cleanup;
516 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 ournames = validate_and_copy_tuple(names);
519 if (ournames == NULL)
520 goto cleanup;
521 ourvarnames = validate_and_copy_tuple(varnames);
522 if (ourvarnames == NULL)
523 goto cleanup;
524 if (freevars)
525 ourfreevars = validate_and_copy_tuple(freevars);
526 else
527 ourfreevars = PyTuple_New(0);
528 if (ourfreevars == NULL)
529 goto cleanup;
530 if (cellvars)
531 ourcellvars = validate_and_copy_tuple(cellvars);
532 else
533 ourcellvars = PyTuple_New(0);
534 if (ourcellvars == NULL)
535 goto cleanup;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000536
Pablo Galindo4a2edc32019-07-01 11:35:05 +0100537 co = (PyObject *)PyCode_NewWithPosOnlyArgs(argcount, posonlyargcount,
538 kwonlyargcount,
539 nlocals, stacksize, flags,
540 code, consts, ournames,
541 ourvarnames, ourfreevars,
542 ourcellvars, filename,
543 name, firstlineno, lnotab);
Victor Stinnera2783132020-01-27 23:24:13 +0100544 cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 Py_XDECREF(ournames);
546 Py_XDECREF(ourvarnames);
547 Py_XDECREF(ourfreevars);
548 Py_XDECREF(ourcellvars);
549 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000550}
551
552static void
553code_dealloc(PyCodeObject *co)
554{
Inada Naoki91234a12019-06-03 21:30:58 +0900555 if (co->co_opcache != NULL) {
556 PyMem_FREE(co->co_opcache);
557 }
558 if (co->co_opcache_map != NULL) {
559 PyMem_FREE(co->co_opcache_map);
560 }
561 co->co_opcache_flag = 0;
562 co->co_opcache_size = 0;
563
Brett Cannon5c4de282016-09-07 11:16:41 -0700564 if (co->co_extra != NULL) {
Victor Stinner81a7be32020-04-14 15:14:01 +0200565 PyInterpreterState *interp = _PyInterpreterState_GET();
Brett Cannond0600ed2016-09-07 14:30:39 -0700566 _PyCodeObjectExtra *co_extra = co->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700567
Brett Cannond0600ed2016-09-07 14:30:39 -0700568 for (Py_ssize_t i = 0; i < co_extra->ce_size; i++) {
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700569 freefunc free_extra = interp->co_extra_freefuncs[i];
Brett Cannon5c4de282016-09-07 11:16:41 -0700570
571 if (free_extra != NULL) {
Brett Cannond0600ed2016-09-07 14:30:39 -0700572 free_extra(co_extra->ce_extras[i]);
Brett Cannon5c4de282016-09-07 11:16:41 -0700573 }
574 }
575
Victor Stinner23e79442017-06-28 02:12:00 +0200576 PyMem_Free(co_extra);
Brett Cannon5c4de282016-09-07 11:16:41 -0700577 }
578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 Py_XDECREF(co->co_code);
580 Py_XDECREF(co->co_consts);
581 Py_XDECREF(co->co_names);
582 Py_XDECREF(co->co_varnames);
583 Py_XDECREF(co->co_freevars);
584 Py_XDECREF(co->co_cellvars);
585 Py_XDECREF(co->co_filename);
586 Py_XDECREF(co->co_name);
587 Py_XDECREF(co->co_lnotab);
Benjamin Peterson90037602011-06-25 22:54:45 -0500588 if (co->co_cell2arg != NULL)
589 PyMem_FREE(co->co_cell2arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 if (co->co_zombieframe != NULL)
591 PyObject_GC_Del(co->co_zombieframe);
592 if (co->co_weakreflist != NULL)
593 PyObject_ClearWeakRefs((PyObject*)co);
594 PyObject_DEL(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000595}
596
597static PyObject *
Victor Stinnera9f05d62019-05-24 23:57:23 +0200598code_sizeof(PyCodeObject *co, PyObject *Py_UNUSED(args))
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200599{
Dong-hee Nab4dc6af2017-04-20 16:31:17 +0900600 Py_ssize_t res = _PyObject_SIZE(Py_TYPE(co));
601 _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra*) co->co_extra;
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200602
Serhiy Storchaka378ebb62017-07-04 15:06:16 +0300603 if (co->co_cell2arg != NULL && co->co_cellvars != NULL) {
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200604 res += PyTuple_GET_SIZE(co->co_cellvars) * sizeof(Py_ssize_t);
Serhiy Storchaka378ebb62017-07-04 15:06:16 +0300605 }
606 if (co_extra != NULL) {
607 res += sizeof(_PyCodeObjectExtra) +
608 (co_extra->ce_size-1) * sizeof(co_extra->ce_extras[0]);
609 }
Inada Naoki91234a12019-06-03 21:30:58 +0900610 if (co->co_opcache != NULL) {
611 assert(co->co_opcache_map != NULL);
612 // co_opcache_map
613 res += PyBytes_GET_SIZE(co->co_code) / sizeof(_Py_CODEUNIT);
614 // co_opcache
615 res += co->co_opcache_size * sizeof(_PyOpcache);
616 }
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200617 return PyLong_FromSsize_t(res);
618}
619
Victor Stinnera9f05d62019-05-24 23:57:23 +0200620/*[clinic input]
621code.replace
622
623 *
624 co_argcount: int(c_default="self->co_argcount") = -1
625 co_posonlyargcount: int(c_default="self->co_posonlyargcount") = -1
626 co_kwonlyargcount: int(c_default="self->co_kwonlyargcount") = -1
627 co_nlocals: int(c_default="self->co_nlocals") = -1
628 co_stacksize: int(c_default="self->co_stacksize") = -1
629 co_flags: int(c_default="self->co_flags") = -1
630 co_firstlineno: int(c_default="self->co_firstlineno") = -1
631 co_code: PyBytesObject(c_default="(PyBytesObject *)self->co_code") = None
632 co_consts: object(subclass_of="&PyTuple_Type", c_default="self->co_consts") = None
633 co_names: object(subclass_of="&PyTuple_Type", c_default="self->co_names") = None
634 co_varnames: object(subclass_of="&PyTuple_Type", c_default="self->co_varnames") = None
635 co_freevars: object(subclass_of="&PyTuple_Type", c_default="self->co_freevars") = None
636 co_cellvars: object(subclass_of="&PyTuple_Type", c_default="self->co_cellvars") = None
637 co_filename: unicode(c_default="self->co_filename") = None
638 co_name: unicode(c_default="self->co_name") = None
639 co_lnotab: PyBytesObject(c_default="(PyBytesObject *)self->co_lnotab") = None
640
Anthony Sottile22424c02020-01-01 01:11:16 -0500641Return a copy of the code object with new values for the specified fields.
Victor Stinnera9f05d62019-05-24 23:57:23 +0200642[clinic start generated code]*/
643
644static PyObject *
645code_replace_impl(PyCodeObject *self, int co_argcount,
646 int co_posonlyargcount, int co_kwonlyargcount,
647 int co_nlocals, int co_stacksize, int co_flags,
648 int co_firstlineno, PyBytesObject *co_code,
649 PyObject *co_consts, PyObject *co_names,
650 PyObject *co_varnames, PyObject *co_freevars,
651 PyObject *co_cellvars, PyObject *co_filename,
652 PyObject *co_name, PyBytesObject *co_lnotab)
Anthony Sottile22424c02020-01-01 01:11:16 -0500653/*[clinic end generated code: output=25c8e303913bcace input=d9051bc8f24e6b28]*/
Victor Stinnera9f05d62019-05-24 23:57:23 +0200654{
655#define CHECK_INT_ARG(ARG) \
656 if (ARG < 0) { \
657 PyErr_SetString(PyExc_ValueError, \
658 #ARG " must be a positive integer"); \
659 return NULL; \
660 }
661
662 CHECK_INT_ARG(co_argcount);
663 CHECK_INT_ARG(co_posonlyargcount);
664 CHECK_INT_ARG(co_kwonlyargcount);
665 CHECK_INT_ARG(co_nlocals);
666 CHECK_INT_ARG(co_stacksize);
667 CHECK_INT_ARG(co_flags);
668 CHECK_INT_ARG(co_firstlineno);
669
670#undef CHECK_INT_ARG
671
Steve Dowerc7c01ab2019-11-26 16:27:50 -0800672 if (PySys_Audit("code.__new__", "OOOiiiiii",
673 co_code, co_filename, co_name, co_argcount,
674 co_posonlyargcount, co_kwonlyargcount, co_nlocals,
675 co_stacksize, co_flags) < 0) {
676 return NULL;
677 }
678
Pablo Galindo4a2edc32019-07-01 11:35:05 +0100679 return (PyObject *)PyCode_NewWithPosOnlyArgs(
Victor Stinnera9f05d62019-05-24 23:57:23 +0200680 co_argcount, co_posonlyargcount, co_kwonlyargcount, co_nlocals,
681 co_stacksize, co_flags, (PyObject*)co_code, co_consts, co_names,
682 co_varnames, co_freevars, co_cellvars, co_filename, co_name,
683 co_firstlineno, (PyObject*)co_lnotab);
684}
685
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200686static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000687code_repr(PyCodeObject *co)
688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 int lineno;
690 if (co->co_firstlineno != 0)
691 lineno = co->co_firstlineno;
692 else
693 lineno = -1;
694 if (co->co_filename && PyUnicode_Check(co->co_filename)) {
695 return PyUnicode_FromFormat(
Victor Stinneraaa4e9a2011-01-05 03:33:26 +0000696 "<code object %U at %p, file \"%U\", line %d>",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 co->co_name, co, co->co_filename, lineno);
698 } else {
699 return PyUnicode_FromFormat(
Victor Stinneraaa4e9a2011-01-05 03:33:26 +0000700 "<code object %U at %p, file ???, line %d>",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 co->co_name, co, lineno);
702 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000703}
704
Victor Stinnerefb24132016-01-22 12:33:12 +0100705PyObject*
706_PyCode_ConstantKey(PyObject *op)
707{
708 PyObject *key;
709
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +0300710 /* Py_None and Py_Ellipsis are singletons. */
Victor Stinnerefb24132016-01-22 12:33:12 +0100711 if (op == Py_None || op == Py_Ellipsis
712 || PyLong_CheckExact(op)
Victor Stinnerefb24132016-01-22 12:33:12 +0100713 || PyUnicode_CheckExact(op)
714 /* code_richcompare() uses _PyCode_ConstantKey() internally */
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +0300715 || PyCode_Check(op))
716 {
717 /* Objects of these types are always different from object of other
718 * type and from tuples. */
719 Py_INCREF(op);
720 key = op;
721 }
722 else if (PyBool_Check(op) || PyBytes_CheckExact(op)) {
723 /* Make booleans different from integers 0 and 1.
724 * Avoid BytesWarning from comparing bytes with strings. */
Victor Stinnerefb24132016-01-22 12:33:12 +0100725 key = PyTuple_Pack(2, Py_TYPE(op), op);
726 }
727 else if (PyFloat_CheckExact(op)) {
728 double d = PyFloat_AS_DOUBLE(op);
729 /* all we need is to make the tuple different in either the 0.0
730 * or -0.0 case from all others, just to avoid the "coercion".
731 */
732 if (d == 0.0 && copysign(1.0, d) < 0.0)
733 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
734 else
735 key = PyTuple_Pack(2, Py_TYPE(op), op);
736 }
737 else if (PyComplex_CheckExact(op)) {
738 Py_complex z;
739 int real_negzero, imag_negzero;
740 /* For the complex case we must make complex(x, 0.)
741 different from complex(x, -0.) and complex(0., y)
742 different from complex(-0., y), for any x and y.
743 All four complex zeros must be distinguished.*/
744 z = PyComplex_AsCComplex(op);
745 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
746 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
747 /* use True, False and None singleton as tags for the real and imag
748 * sign, to make tuples different */
749 if (real_negzero && imag_negzero) {
750 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_True);
751 }
752 else if (imag_negzero) {
753 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_False);
754 }
755 else if (real_negzero) {
756 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
757 }
758 else {
759 key = PyTuple_Pack(2, Py_TYPE(op), op);
760 }
761 }
762 else if (PyTuple_CheckExact(op)) {
763 Py_ssize_t i, len;
764 PyObject *tuple;
765
766 len = PyTuple_GET_SIZE(op);
767 tuple = PyTuple_New(len);
768 if (tuple == NULL)
769 return NULL;
770
771 for (i=0; i < len; i++) {
772 PyObject *item, *item_key;
773
774 item = PyTuple_GET_ITEM(op, i);
775 item_key = _PyCode_ConstantKey(item);
776 if (item_key == NULL) {
777 Py_DECREF(tuple);
778 return NULL;
779 }
780
781 PyTuple_SET_ITEM(tuple, i, item_key);
782 }
783
Serhiy Storchaka713640c2017-01-24 20:49:26 +0200784 key = PyTuple_Pack(2, tuple, op);
Victor Stinnerefb24132016-01-22 12:33:12 +0100785 Py_DECREF(tuple);
786 }
787 else if (PyFrozenSet_CheckExact(op)) {
788 Py_ssize_t pos = 0;
789 PyObject *item;
790 Py_hash_t hash;
791 Py_ssize_t i, len;
792 PyObject *tuple, *set;
793
794 len = PySet_GET_SIZE(op);
795 tuple = PyTuple_New(len);
796 if (tuple == NULL)
797 return NULL;
798
799 i = 0;
800 while (_PySet_NextEntry(op, &pos, &item, &hash)) {
801 PyObject *item_key;
802
803 item_key = _PyCode_ConstantKey(item);
804 if (item_key == NULL) {
805 Py_DECREF(tuple);
806 return NULL;
807 }
808
809 assert(i < len);
810 PyTuple_SET_ITEM(tuple, i, item_key);
811 i++;
812 }
813 set = PyFrozenSet_New(tuple);
814 Py_DECREF(tuple);
815 if (set == NULL)
816 return NULL;
817
Serhiy Storchaka713640c2017-01-24 20:49:26 +0200818 key = PyTuple_Pack(2, set, op);
Victor Stinnerefb24132016-01-22 12:33:12 +0100819 Py_DECREF(set);
820 return key;
821 }
822 else {
Martin Panter6245cb32016-04-15 02:14:19 +0000823 /* for other types, use the object identifier as a unique identifier
Victor Stinnerefb24132016-01-22 12:33:12 +0100824 * to ensure that they are seen as unequal. */
825 PyObject *obj_id = PyLong_FromVoidPtr(op);
826 if (obj_id == NULL)
827 return NULL;
828
Serhiy Storchaka713640c2017-01-24 20:49:26 +0200829 key = PyTuple_Pack(2, obj_id, op);
Victor Stinnerefb24132016-01-22 12:33:12 +0100830 Py_DECREF(obj_id);
831 }
832 return key;
833}
834
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000835static PyObject *
836code_richcompare(PyObject *self, PyObject *other, int op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000837{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 PyCodeObject *co, *cp;
839 int eq;
Victor Stinnerefb24132016-01-22 12:33:12 +0100840 PyObject *consts1, *consts2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 if ((op != Py_EQ && op != Py_NE) ||
844 !PyCode_Check(self) ||
845 !PyCode_Check(other)) {
Brian Curtindfc80e32011-08-10 20:28:54 -0500846 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 co = (PyCodeObject *)self;
850 cp = (PyCodeObject *)other;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 eq = PyObject_RichCompareBool(co->co_name, cp->co_name, Py_EQ);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100853 if (!eq) goto unequal;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 eq = co->co_argcount == cp->co_argcount;
855 if (!eq) goto unequal;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100856 eq = co->co_posonlyargcount == cp->co_posonlyargcount;
857 if (!eq) goto unequal;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 eq = co->co_kwonlyargcount == cp->co_kwonlyargcount;
859 if (!eq) goto unequal;
860 eq = co->co_nlocals == cp->co_nlocals;
861 if (!eq) goto unequal;
862 eq = co->co_flags == cp->co_flags;
863 if (!eq) goto unequal;
864 eq = co->co_firstlineno == cp->co_firstlineno;
865 if (!eq) goto unequal;
866 eq = PyObject_RichCompareBool(co->co_code, cp->co_code, Py_EQ);
867 if (eq <= 0) goto unequal;
Victor Stinnerefb24132016-01-22 12:33:12 +0100868
869 /* compare constants */
870 consts1 = _PyCode_ConstantKey(co->co_consts);
871 if (!consts1)
872 return NULL;
873 consts2 = _PyCode_ConstantKey(cp->co_consts);
874 if (!consts2) {
875 Py_DECREF(consts1);
876 return NULL;
877 }
878 eq = PyObject_RichCompareBool(consts1, consts2, Py_EQ);
879 Py_DECREF(consts1);
880 Py_DECREF(consts2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 if (eq <= 0) goto unequal;
Victor Stinnerefb24132016-01-22 12:33:12 +0100882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 eq = PyObject_RichCompareBool(co->co_names, cp->co_names, Py_EQ);
884 if (eq <= 0) goto unequal;
885 eq = PyObject_RichCompareBool(co->co_varnames, cp->co_varnames, Py_EQ);
886 if (eq <= 0) goto unequal;
887 eq = PyObject_RichCompareBool(co->co_freevars, cp->co_freevars, Py_EQ);
888 if (eq <= 0) goto unequal;
889 eq = PyObject_RichCompareBool(co->co_cellvars, cp->co_cellvars, Py_EQ);
890 if (eq <= 0) goto unequal;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 if (op == Py_EQ)
893 res = Py_True;
894 else
895 res = Py_False;
896 goto done;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000897
898 unequal:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 if (eq < 0)
900 return NULL;
901 if (op == Py_NE)
902 res = Py_True;
903 else
904 res = Py_False;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000905
906 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 Py_INCREF(res);
908 return res;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000909}
910
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000911static Py_hash_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000912code_hash(PyCodeObject *co)
913{
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000914 Py_hash_t h, h0, h1, h2, h3, h4, h5, h6;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 h0 = PyObject_Hash(co->co_name);
916 if (h0 == -1) return -1;
917 h1 = PyObject_Hash(co->co_code);
918 if (h1 == -1) return -1;
919 h2 = PyObject_Hash(co->co_consts);
920 if (h2 == -1) return -1;
921 h3 = PyObject_Hash(co->co_names);
922 if (h3 == -1) return -1;
923 h4 = PyObject_Hash(co->co_varnames);
924 if (h4 == -1) return -1;
925 h5 = PyObject_Hash(co->co_freevars);
926 if (h5 == -1) return -1;
927 h6 = PyObject_Hash(co->co_cellvars);
928 if (h6 == -1) return -1;
929 h = h0 ^ h1 ^ h2 ^ h3 ^ h4 ^ h5 ^ h6 ^
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100930 co->co_argcount ^ co->co_posonlyargcount ^ co->co_kwonlyargcount ^
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 co->co_nlocals ^ co->co_flags;
932 if (h == -1) h = -2;
933 return h;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000934}
935
936/* XXX code objects need to participate in GC? */
937
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200938static struct PyMethodDef code_methods[] = {
939 {"__sizeof__", (PyCFunction)code_sizeof, METH_NOARGS},
Victor Stinnera9f05d62019-05-24 23:57:23 +0200940 CODE_REPLACE_METHODDEF
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200941 {NULL, NULL} /* sentinel */
942};
943
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000944PyTypeObject PyCode_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 PyVarObject_HEAD_INIT(&PyType_Type, 0)
946 "code",
947 sizeof(PyCodeObject),
948 0,
949 (destructor)code_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200950 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 0, /* tp_getattr */
952 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200953 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 (reprfunc)code_repr, /* tp_repr */
955 0, /* tp_as_number */
956 0, /* tp_as_sequence */
957 0, /* tp_as_mapping */
958 (hashfunc)code_hash, /* tp_hash */
959 0, /* tp_call */
960 0, /* tp_str */
961 PyObject_GenericGetAttr, /* tp_getattro */
962 0, /* tp_setattro */
963 0, /* tp_as_buffer */
964 Py_TPFLAGS_DEFAULT, /* tp_flags */
Serhiy Storchaka0f9aa472020-07-10 10:12:04 +0300965 code_new__doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 0, /* tp_traverse */
967 0, /* tp_clear */
968 code_richcompare, /* tp_richcompare */
969 offsetof(PyCodeObject, co_weakreflist), /* tp_weaklistoffset */
970 0, /* tp_iter */
971 0, /* tp_iternext */
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200972 code_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 code_memberlist, /* tp_members */
974 0, /* tp_getset */
975 0, /* tp_base */
976 0, /* tp_dict */
977 0, /* tp_descr_get */
978 0, /* tp_descr_set */
979 0, /* tp_dictoffset */
980 0, /* tp_init */
981 0, /* tp_alloc */
982 code_new, /* tp_new */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000983};
984
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000985/* Use co_lnotab to compute the line number from a bytecode index, addrq. See
986 lnotab_notes.txt for the details of the lnotab representation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000987*/
988
989int
990PyCode_Addr2Line(PyCodeObject *co, int addrq)
991{
Victor Stinner0fcab4a2011-01-04 12:59:15 +0000992 Py_ssize_t size = PyBytes_Size(co->co_lnotab) / 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 unsigned char *p = (unsigned char*)PyBytes_AsString(co->co_lnotab);
994 int line = co->co_firstlineno;
995 int addr = 0;
996 while (--size >= 0) {
997 addr += *p++;
998 if (addr > addrq)
999 break;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01001000 line += (signed char)*p;
1001 p++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 }
1003 return line;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001004}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001005
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00001006/* Update *bounds to describe the first and one-past-the-last instructions in
1007 the same line as lasti. Return the number of that line. */
1008int
1009_PyCode_CheckLineNumber(PyCodeObject* co, int lasti, PyAddrPair *bounds)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001010{
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001011 Py_ssize_t size;
1012 int addr, line;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 unsigned char* p;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 p = (unsigned char*)PyBytes_AS_STRING(co->co_lnotab);
1016 size = PyBytes_GET_SIZE(co->co_lnotab) / 2;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 addr = 0;
1019 line = co->co_firstlineno;
1020 assert(line > 0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 /* possible optimization: if f->f_lasti == instr_ub
1023 (likely to be a common case) then we already know
1024 instr_lb -- if we stored the matching value of p
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07001025 somewhere we could skip the first while loop. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 /* See lnotab_notes.txt for the description of
1028 co_lnotab. A point to remember: increments to p
1029 come in (addr, line) pairs. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 bounds->ap_lower = 0;
1032 while (size > 0) {
1033 if (addr + *p > lasti)
1034 break;
1035 addr += *p++;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01001036 if ((signed char)*p)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 bounds->ap_lower = addr;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01001038 line += (signed char)*p;
1039 p++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 --size;
1041 }
1042
1043 if (size > 0) {
1044 while (--size >= 0) {
1045 addr += *p++;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01001046 if ((signed char)*p)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 break;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01001048 p++;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001049 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 bounds->ap_upper = addr;
1051 }
1052 else {
1053 bounds->ap_upper = INT_MAX;
1054 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 return line;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001057}
Brett Cannon5c4de282016-09-07 11:16:41 -07001058
1059
1060int
1061_PyCode_GetExtra(PyObject *code, Py_ssize_t index, void **extra)
1062{
Brett Cannon5c4de282016-09-07 11:16:41 -07001063 if (!PyCode_Check(code)) {
1064 PyErr_BadInternalCall();
Brett Cannon3788b852016-09-07 12:51:08 -07001065 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -07001066 }
1067
Brett Cannond0600ed2016-09-07 14:30:39 -07001068 PyCodeObject *o = (PyCodeObject*) code;
1069 _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra*) o->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -07001070
Brett Cannond0600ed2016-09-07 14:30:39 -07001071 if (co_extra == NULL || co_extra->ce_size <= index) {
Dino Viehlandf3cffd22017-06-21 14:44:36 -07001072 *extra = NULL;
Brett Cannon5c4de282016-09-07 11:16:41 -07001073 return 0;
1074 }
1075
Brett Cannond0600ed2016-09-07 14:30:39 -07001076 *extra = co_extra->ce_extras[index];
Brett Cannon5c4de282016-09-07 11:16:41 -07001077 return 0;
1078}
1079
1080
1081int
1082_PyCode_SetExtra(PyObject *code, Py_ssize_t index, void *extra)
1083{
Victor Stinner81a7be32020-04-14 15:14:01 +02001084 PyInterpreterState *interp = _PyInterpreterState_GET();
Brett Cannon5c4de282016-09-07 11:16:41 -07001085
1086 if (!PyCode_Check(code) || index < 0 ||
Dino Viehlandf3cffd22017-06-21 14:44:36 -07001087 index >= interp->co_extra_user_count) {
Brett Cannon5c4de282016-09-07 11:16:41 -07001088 PyErr_BadInternalCall();
Brett Cannon3788b852016-09-07 12:51:08 -07001089 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -07001090 }
1091
Brett Cannond0600ed2016-09-07 14:30:39 -07001092 PyCodeObject *o = (PyCodeObject*) code;
1093 _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra *) o->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -07001094
Serhiy Storchaka378ebb62017-07-04 15:06:16 +03001095 if (co_extra == NULL || co_extra->ce_size <= index) {
1096 Py_ssize_t i = (co_extra == NULL ? 0 : co_extra->ce_size);
1097 co_extra = PyMem_Realloc(
1098 co_extra,
1099 sizeof(_PyCodeObjectExtra) +
1100 (interp->co_extra_user_count-1) * sizeof(void*));
Brian Coleman6a9122c2017-03-02 10:32:18 +00001101 if (co_extra == NULL) {
Brett Cannon3788b852016-09-07 12:51:08 -07001102 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -07001103 }
Serhiy Storchaka378ebb62017-07-04 15:06:16 +03001104 for (; i < interp->co_extra_user_count; i++) {
Brett Cannond0600ed2016-09-07 14:30:39 -07001105 co_extra->ce_extras[i] = NULL;
Brett Cannon5c4de282016-09-07 11:16:41 -07001106 }
Dino Viehlandf3cffd22017-06-21 14:44:36 -07001107 co_extra->ce_size = interp->co_extra_user_count;
Serhiy Storchaka378ebb62017-07-04 15:06:16 +03001108 o->co_extra = co_extra;
Dino Viehlandf3cffd22017-06-21 14:44:36 -07001109 }
1110
1111 if (co_extra->ce_extras[index] != NULL) {
1112 freefunc free = interp->co_extra_freefuncs[index];
Dino Viehlandf3cffd22017-06-21 14:44:36 -07001113 if (free != NULL) {
1114 free(co_extra->ce_extras[index]);
1115 }
Brett Cannon5c4de282016-09-07 11:16:41 -07001116 }
1117
Brett Cannond0600ed2016-09-07 14:30:39 -07001118 co_extra->ce_extras[index] = extra;
Brett Cannon5c4de282016-09-07 11:16:41 -07001119 return 0;
1120}