blob: 0509b8e6400fb8941615777aedb5c53177b6325c [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"
5#include "structmember.h"
6
Brett Cannond0600ed2016-09-07 14:30:39 -07007/* Holder for co_extra information */
8typedef struct {
9 Py_ssize_t ce_size;
Serhiy Storchaka378ebb62017-07-04 15:06:16 +030010 void *ce_extras[1];
Brett Cannond0600ed2016-09-07 14:30:39 -070011} _PyCodeObjectExtra;
12
Benjamin Peterson8e0ad462017-09-07 23:35:53 -070013/* all_name_chars(s): true iff s matches [a-zA-Z0-9_]* */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000014static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015all_name_chars(PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000016{
Serhiy Storchaka09f3d082016-10-04 18:17:22 +030017 const unsigned char *s, *e;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020018
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030019 if (!PyUnicode_IS_ASCII(o))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020020 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000021
Serhiy Storchaka09f3d082016-10-04 18:17:22 +030022 s = PyUnicode_1BYTE_DATA(o);
23 e = s + PyUnicode_GET_LENGTH(o);
Benjamin Peterson9020ac72017-09-07 18:06:23 -070024 for (; s != e; s++) {
Benjamin Peterson2b7953d2017-09-08 10:35:49 -070025 if (!Py_ISALNUM(*s) && *s != '_')
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000026 return 0;
27 }
28 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000029}
30
31static void
32intern_strings(PyObject *tuple)
33{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000034 Py_ssize_t i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000036 for (i = PyTuple_GET_SIZE(tuple); --i >= 0; ) {
37 PyObject *v = PyTuple_GET_ITEM(tuple, i);
38 if (v == NULL || !PyUnicode_CheckExact(v)) {
39 Py_FatalError("non-string found in code slot");
40 }
41 PyUnicode_InternInPlace(&PyTuple_GET_ITEM(tuple, i));
42 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000043}
44
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +030045/* Intern selected string constants */
46static int
47intern_string_constants(PyObject *tuple)
48{
49 int modified = 0;
50 Py_ssize_t i;
51
52 for (i = PyTuple_GET_SIZE(tuple); --i >= 0; ) {
53 PyObject *v = PyTuple_GET_ITEM(tuple, i);
54 if (PyUnicode_CheckExact(v)) {
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030055 if (PyUnicode_READY(v) == -1) {
56 PyErr_Clear();
57 continue;
58 }
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +030059 if (all_name_chars(v)) {
60 PyObject *w = v;
61 PyUnicode_InternInPlace(&v);
62 if (w != v) {
63 PyTuple_SET_ITEM(tuple, i, v);
64 modified = 1;
65 }
66 }
67 }
68 else if (PyTuple_CheckExact(v)) {
69 intern_string_constants(v);
70 }
71 else if (PyFrozenSet_CheckExact(v)) {
Yury Selivanovd2fd3592016-11-09 09:42:14 -050072 PyObject *w = v;
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +030073 PyObject *tmp = PySequence_Tuple(v);
74 if (tmp == NULL) {
75 PyErr_Clear();
76 continue;
77 }
78 if (intern_string_constants(tmp)) {
79 v = PyFrozenSet_New(tmp);
80 if (v == NULL) {
81 PyErr_Clear();
82 }
83 else {
84 PyTuple_SET_ITEM(tuple, i, v);
Yury Selivanovd2fd3592016-11-09 09:42:14 -050085 Py_DECREF(w);
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +030086 modified = 1;
87 }
88 }
89 Py_DECREF(tmp);
90 }
91 }
92 return modified;
93}
94
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000095
96PyCodeObject *
Guido van Rossum4f72a782006-10-27 23:31:49 +000097PyCode_New(int argcount, int kwonlyargcount,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000098 int nlocals, int stacksize, int flags,
99 PyObject *code, PyObject *consts, PyObject *names,
100 PyObject *varnames, PyObject *freevars, PyObject *cellvars,
101 PyObject *filename, PyObject *name, int firstlineno,
102 PyObject *lnotab)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000103{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 PyCodeObject *co;
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200105 Py_ssize_t *cell2arg = NULL;
Benjamin Peterson90037602011-06-25 22:54:45 -0500106 Py_ssize_t i, n_cellvars;
Guido van Rossum00bc0e02007-10-15 02:52:41 +0000107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 /* Check argument types */
109 if (argcount < 0 || kwonlyargcount < 0 || nlocals < 0 ||
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +0200110 code == NULL || !PyBytes_Check(code) ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 consts == NULL || !PyTuple_Check(consts) ||
112 names == NULL || !PyTuple_Check(names) ||
113 varnames == NULL || !PyTuple_Check(varnames) ||
114 freevars == NULL || !PyTuple_Check(freevars) ||
115 cellvars == NULL || !PyTuple_Check(cellvars) ||
116 name == NULL || !PyUnicode_Check(name) ||
117 filename == NULL || !PyUnicode_Check(filename) ||
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +0200118 lnotab == NULL || !PyBytes_Check(lnotab)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 PyErr_BadInternalCall();
120 return NULL;
121 }
Victor Stinner7c74de42013-10-10 15:55:14 +0200122
123 /* Ensure that the filename is a ready Unicode string */
124 if (PyUnicode_READY(filename) < 0)
125 return NULL;
126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 intern_strings(names);
128 intern_strings(varnames);
129 intern_strings(freevars);
130 intern_strings(cellvars);
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +0300131 intern_string_constants(consts);
Nick Coghlan078f1812017-12-03 11:12:20 +1000132
133 /* Check for any inner or outer closure references */
134 n_cellvars = PyTuple_GET_SIZE(cellvars);
135 if (!n_cellvars && !PyTuple_GET_SIZE(freevars)) {
136 flags |= CO_NOFREE;
137 } else {
138 flags &= ~CO_NOFREE;
139 }
140
Benjamin Peterson90037602011-06-25 22:54:45 -0500141 /* Create mapping between cells and arguments if needed. */
142 if (n_cellvars) {
143 Py_ssize_t total_args = argcount + kwonlyargcount +
144 ((flags & CO_VARARGS) != 0) + ((flags & CO_VARKEYWORDS) != 0);
Benjamin Peterson1bf494b2016-09-07 11:28:35 -0700145 bool used_cell2arg = false;
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200146 cell2arg = PyMem_NEW(Py_ssize_t, n_cellvars);
147 if (cell2arg == NULL) {
148 PyErr_NoMemory();
Benjamin Peterson90037602011-06-25 22:54:45 -0500149 return NULL;
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200150 }
Benjamin Peterson90037602011-06-25 22:54:45 -0500151 /* Find cells which are also arguments. */
152 for (i = 0; i < n_cellvars; i++) {
153 Py_ssize_t j;
154 PyObject *cell = PyTuple_GET_ITEM(cellvars, i);
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200155 cell2arg[i] = CO_CELL_NOT_AN_ARG;
Benjamin Peterson90037602011-06-25 22:54:45 -0500156 for (j = 0; j < total_args; j++) {
157 PyObject *arg = PyTuple_GET_ITEM(varnames, j);
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200158 int cmp = PyUnicode_Compare(cell, arg);
159 if (cmp == -1 && PyErr_Occurred()) {
160 PyMem_FREE(cell2arg);
161 return NULL;
162 }
163 if (cmp == 0) {
Benjamin Peterson90037602011-06-25 22:54:45 -0500164 cell2arg[i] = j;
Benjamin Peterson1bf494b2016-09-07 11:28:35 -0700165 used_cell2arg = true;
Benjamin Peterson90037602011-06-25 22:54:45 -0500166 break;
167 }
168 }
169 }
170 if (!used_cell2arg) {
171 PyMem_FREE(cell2arg);
172 cell2arg = NULL;
173 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 }
Benjamin Peterson90037602011-06-25 22:54:45 -0500175 co = PyObject_NEW(PyCodeObject, &PyCode_Type);
176 if (co == NULL) {
177 if (cell2arg)
178 PyMem_FREE(cell2arg);
179 return NULL;
180 }
181 co->co_argcount = argcount;
182 co->co_kwonlyargcount = kwonlyargcount;
183 co->co_nlocals = nlocals;
184 co->co_stacksize = stacksize;
185 co->co_flags = flags;
186 Py_INCREF(code);
187 co->co_code = code;
188 Py_INCREF(consts);
189 co->co_consts = consts;
190 Py_INCREF(names);
191 co->co_names = names;
192 Py_INCREF(varnames);
193 co->co_varnames = varnames;
194 Py_INCREF(freevars);
195 co->co_freevars = freevars;
196 Py_INCREF(cellvars);
197 co->co_cellvars = cellvars;
198 co->co_cell2arg = cell2arg;
199 Py_INCREF(filename);
200 co->co_filename = filename;
201 Py_INCREF(name);
202 co->co_name = name;
203 co->co_firstlineno = firstlineno;
204 Py_INCREF(lnotab);
205 co->co_lnotab = lnotab;
206 co->co_zombieframe = NULL;
207 co->co_weakreflist = NULL;
Brett Cannon5c4de282016-09-07 11:16:41 -0700208 co->co_extra = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000210}
211
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000212PyCodeObject *
213PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno)
214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000215 static PyObject *emptystring = NULL;
216 static PyObject *nulltuple = NULL;
217 PyObject *filename_ob = NULL;
218 PyObject *funcname_ob = NULL;
219 PyCodeObject *result = NULL;
220 if (emptystring == NULL) {
221 emptystring = PyBytes_FromString("");
222 if (emptystring == NULL)
223 goto failed;
224 }
225 if (nulltuple == NULL) {
226 nulltuple = PyTuple_New(0);
227 if (nulltuple == NULL)
228 goto failed;
229 }
230 funcname_ob = PyUnicode_FromString(funcname);
231 if (funcname_ob == NULL)
232 goto failed;
233 filename_ob = PyUnicode_DecodeFSDefault(filename);
234 if (filename_ob == NULL)
235 goto failed;
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 result = PyCode_New(0, /* argcount */
238 0, /* kwonlyargcount */
239 0, /* nlocals */
240 0, /* stacksize */
241 0, /* flags */
242 emptystring, /* code */
243 nulltuple, /* consts */
244 nulltuple, /* names */
245 nulltuple, /* varnames */
246 nulltuple, /* freevars */
247 nulltuple, /* cellvars */
248 filename_ob, /* filename */
249 funcname_ob, /* name */
250 firstlineno, /* firstlineno */
251 emptystring /* lnotab */
252 );
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000253
254failed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 Py_XDECREF(funcname_ob);
256 Py_XDECREF(filename_ob);
257 return result;
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000258}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000259
260#define OFF(x) offsetof(PyCodeObject, x)
261
262static PyMemberDef code_memberlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 {"co_argcount", T_INT, OFF(co_argcount), READONLY},
264 {"co_kwonlyargcount", T_INT, OFF(co_kwonlyargcount), READONLY},
265 {"co_nlocals", T_INT, OFF(co_nlocals), READONLY},
266 {"co_stacksize",T_INT, OFF(co_stacksize), READONLY},
267 {"co_flags", T_INT, OFF(co_flags), READONLY},
268 {"co_code", T_OBJECT, OFF(co_code), READONLY},
269 {"co_consts", T_OBJECT, OFF(co_consts), READONLY},
270 {"co_names", T_OBJECT, OFF(co_names), READONLY},
271 {"co_varnames", T_OBJECT, OFF(co_varnames), READONLY},
272 {"co_freevars", T_OBJECT, OFF(co_freevars), READONLY},
273 {"co_cellvars", T_OBJECT, OFF(co_cellvars), READONLY},
274 {"co_filename", T_OBJECT, OFF(co_filename), READONLY},
275 {"co_name", T_OBJECT, OFF(co_name), READONLY},
276 {"co_firstlineno", T_INT, OFF(co_firstlineno), READONLY},
277 {"co_lnotab", T_OBJECT, OFF(co_lnotab), READONLY},
278 {NULL} /* Sentinel */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000279};
280
281/* Helper for code_new: return a shallow copy of a tuple that is
282 guaranteed to contain exact strings, by converting string subclasses
283 to exact strings and complaining if a non-string is found. */
284static PyObject*
285validate_and_copy_tuple(PyObject *tup)
286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 PyObject *newtuple;
288 PyObject *item;
289 Py_ssize_t i, len;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 len = PyTuple_GET_SIZE(tup);
292 newtuple = PyTuple_New(len);
293 if (newtuple == NULL)
294 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 for (i = 0; i < len; i++) {
297 item = PyTuple_GET_ITEM(tup, i);
298 if (PyUnicode_CheckExact(item)) {
299 Py_INCREF(item);
300 }
301 else if (!PyUnicode_Check(item)) {
302 PyErr_Format(
303 PyExc_TypeError,
304 "name tuples must contain only "
305 "strings, not '%.500s'",
306 item->ob_type->tp_name);
307 Py_DECREF(newtuple);
308 return NULL;
309 }
310 else {
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100311 item = _PyUnicode_Copy(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 if (item == NULL) {
313 Py_DECREF(newtuple);
314 return NULL;
315 }
316 }
317 PyTuple_SET_ITEM(newtuple, i, item);
318 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 return newtuple;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000321}
322
323PyDoc_STRVAR(code_doc,
Georg Brandl8c1a50a2009-07-18 09:07:48 +0000324"code(argcount, kwonlyargcount, nlocals, stacksize, flags, codestring,\n\
Georg Brandla1e7e132008-01-26 09:39:23 +0000325 constants, names, varnames, filename, name, firstlineno,\n\
326 lnotab[, freevars[, cellvars]])\n\
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000327\n\
328Create a code object. Not for the faint of heart.");
329
330static PyObject *
331code_new(PyTypeObject *type, PyObject *args, PyObject *kw)
332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 int argcount;
334 int kwonlyargcount;
335 int nlocals;
336 int stacksize;
337 int flags;
338 PyObject *co = NULL;
339 PyObject *code;
340 PyObject *consts;
341 PyObject *names, *ournames = NULL;
342 PyObject *varnames, *ourvarnames = NULL;
343 PyObject *freevars = NULL, *ourfreevars = NULL;
344 PyObject *cellvars = NULL, *ourcellvars = NULL;
345 PyObject *filename;
346 PyObject *name;
347 int firstlineno;
348 PyObject *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 if (!PyArg_ParseTuple(args, "iiiiiSO!O!O!UUiS|O!O!:code",
351 &argcount, &kwonlyargcount,
352 &nlocals, &stacksize, &flags,
353 &code,
354 &PyTuple_Type, &consts,
355 &PyTuple_Type, &names,
356 &PyTuple_Type, &varnames,
357 &filename, &name,
358 &firstlineno, &lnotab,
359 &PyTuple_Type, &freevars,
360 &PyTuple_Type, &cellvars))
361 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 if (argcount < 0) {
364 PyErr_SetString(
365 PyExc_ValueError,
366 "code: argcount must not be negative");
367 goto cleanup;
368 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 if (kwonlyargcount < 0) {
371 PyErr_SetString(
372 PyExc_ValueError,
373 "code: kwonlyargcount must not be negative");
374 goto cleanup;
375 }
376 if (nlocals < 0) {
377 PyErr_SetString(
378 PyExc_ValueError,
379 "code: nlocals must not be negative");
380 goto cleanup;
381 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 ournames = validate_and_copy_tuple(names);
384 if (ournames == NULL)
385 goto cleanup;
386 ourvarnames = validate_and_copy_tuple(varnames);
387 if (ourvarnames == NULL)
388 goto cleanup;
389 if (freevars)
390 ourfreevars = validate_and_copy_tuple(freevars);
391 else
392 ourfreevars = PyTuple_New(0);
393 if (ourfreevars == NULL)
394 goto cleanup;
395 if (cellvars)
396 ourcellvars = validate_and_copy_tuple(cellvars);
397 else
398 ourcellvars = PyTuple_New(0);
399 if (ourcellvars == NULL)
400 goto cleanup;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 co = (PyObject *)PyCode_New(argcount, kwonlyargcount,
403 nlocals, stacksize, flags,
404 code, consts, ournames, ourvarnames,
405 ourfreevars, ourcellvars, filename,
406 name, firstlineno, lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000407 cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 Py_XDECREF(ournames);
409 Py_XDECREF(ourvarnames);
410 Py_XDECREF(ourfreevars);
411 Py_XDECREF(ourcellvars);
412 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000413}
414
415static void
416code_dealloc(PyCodeObject *co)
417{
Brett Cannon5c4de282016-09-07 11:16:41 -0700418 if (co->co_extra != NULL) {
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700419 PyInterpreterState *interp = PyThreadState_Get()->interp;
Brett Cannond0600ed2016-09-07 14:30:39 -0700420 _PyCodeObjectExtra *co_extra = co->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700421
Brett Cannond0600ed2016-09-07 14:30:39 -0700422 for (Py_ssize_t i = 0; i < co_extra->ce_size; i++) {
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700423 freefunc free_extra = interp->co_extra_freefuncs[i];
Brett Cannon5c4de282016-09-07 11:16:41 -0700424
425 if (free_extra != NULL) {
Brett Cannond0600ed2016-09-07 14:30:39 -0700426 free_extra(co_extra->ce_extras[i]);
Brett Cannon5c4de282016-09-07 11:16:41 -0700427 }
428 }
429
Victor Stinner23e79442017-06-28 02:12:00 +0200430 PyMem_Free(co_extra);
Brett Cannon5c4de282016-09-07 11:16:41 -0700431 }
432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 Py_XDECREF(co->co_code);
434 Py_XDECREF(co->co_consts);
435 Py_XDECREF(co->co_names);
436 Py_XDECREF(co->co_varnames);
437 Py_XDECREF(co->co_freevars);
438 Py_XDECREF(co->co_cellvars);
439 Py_XDECREF(co->co_filename);
440 Py_XDECREF(co->co_name);
441 Py_XDECREF(co->co_lnotab);
Benjamin Peterson90037602011-06-25 22:54:45 -0500442 if (co->co_cell2arg != NULL)
443 PyMem_FREE(co->co_cell2arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 if (co->co_zombieframe != NULL)
445 PyObject_GC_Del(co->co_zombieframe);
446 if (co->co_weakreflist != NULL)
447 PyObject_ClearWeakRefs((PyObject*)co);
448 PyObject_DEL(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000449}
450
451static PyObject *
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200452code_sizeof(PyCodeObject *co, void *unused)
453{
Dong-hee Nab4dc6af2017-04-20 16:31:17 +0900454 Py_ssize_t res = _PyObject_SIZE(Py_TYPE(co));
455 _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra*) co->co_extra;
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200456
Serhiy Storchaka378ebb62017-07-04 15:06:16 +0300457 if (co->co_cell2arg != NULL && co->co_cellvars != NULL) {
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200458 res += PyTuple_GET_SIZE(co->co_cellvars) * sizeof(Py_ssize_t);
Serhiy Storchaka378ebb62017-07-04 15:06:16 +0300459 }
460 if (co_extra != NULL) {
461 res += sizeof(_PyCodeObjectExtra) +
462 (co_extra->ce_size-1) * sizeof(co_extra->ce_extras[0]);
463 }
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200464 return PyLong_FromSsize_t(res);
465}
466
467static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000468code_repr(PyCodeObject *co)
469{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 int lineno;
471 if (co->co_firstlineno != 0)
472 lineno = co->co_firstlineno;
473 else
474 lineno = -1;
475 if (co->co_filename && PyUnicode_Check(co->co_filename)) {
476 return PyUnicode_FromFormat(
Victor Stinneraaa4e9a2011-01-05 03:33:26 +0000477 "<code object %U at %p, file \"%U\", line %d>",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 co->co_name, co, co->co_filename, lineno);
479 } else {
480 return PyUnicode_FromFormat(
Victor Stinneraaa4e9a2011-01-05 03:33:26 +0000481 "<code object %U at %p, file ???, line %d>",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 co->co_name, co, lineno);
483 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000484}
485
Victor Stinnerefb24132016-01-22 12:33:12 +0100486PyObject*
487_PyCode_ConstantKey(PyObject *op)
488{
489 PyObject *key;
490
491 /* Py_None and Py_Ellipsis are singleton */
492 if (op == Py_None || op == Py_Ellipsis
493 || PyLong_CheckExact(op)
494 || PyBool_Check(op)
495 || PyBytes_CheckExact(op)
496 || PyUnicode_CheckExact(op)
497 /* code_richcompare() uses _PyCode_ConstantKey() internally */
498 || PyCode_Check(op)) {
499 key = PyTuple_Pack(2, Py_TYPE(op), op);
500 }
501 else if (PyFloat_CheckExact(op)) {
502 double d = PyFloat_AS_DOUBLE(op);
503 /* all we need is to make the tuple different in either the 0.0
504 * or -0.0 case from all others, just to avoid the "coercion".
505 */
506 if (d == 0.0 && copysign(1.0, d) < 0.0)
507 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
508 else
509 key = PyTuple_Pack(2, Py_TYPE(op), op);
510 }
511 else if (PyComplex_CheckExact(op)) {
512 Py_complex z;
513 int real_negzero, imag_negzero;
514 /* For the complex case we must make complex(x, 0.)
515 different from complex(x, -0.) and complex(0., y)
516 different from complex(-0., y), for any x and y.
517 All four complex zeros must be distinguished.*/
518 z = PyComplex_AsCComplex(op);
519 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
520 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
521 /* use True, False and None singleton as tags for the real and imag
522 * sign, to make tuples different */
523 if (real_negzero && imag_negzero) {
524 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_True);
525 }
526 else if (imag_negzero) {
527 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_False);
528 }
529 else if (real_negzero) {
530 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
531 }
532 else {
533 key = PyTuple_Pack(2, Py_TYPE(op), op);
534 }
535 }
536 else if (PyTuple_CheckExact(op)) {
537 Py_ssize_t i, len;
538 PyObject *tuple;
539
540 len = PyTuple_GET_SIZE(op);
541 tuple = PyTuple_New(len);
542 if (tuple == NULL)
543 return NULL;
544
545 for (i=0; i < len; i++) {
546 PyObject *item, *item_key;
547
548 item = PyTuple_GET_ITEM(op, i);
549 item_key = _PyCode_ConstantKey(item);
550 if (item_key == NULL) {
551 Py_DECREF(tuple);
552 return NULL;
553 }
554
555 PyTuple_SET_ITEM(tuple, i, item_key);
556 }
557
Serhiy Storchaka713640c2017-01-24 20:49:26 +0200558 key = PyTuple_Pack(2, tuple, op);
Victor Stinnerefb24132016-01-22 12:33:12 +0100559 Py_DECREF(tuple);
560 }
561 else if (PyFrozenSet_CheckExact(op)) {
562 Py_ssize_t pos = 0;
563 PyObject *item;
564 Py_hash_t hash;
565 Py_ssize_t i, len;
566 PyObject *tuple, *set;
567
568 len = PySet_GET_SIZE(op);
569 tuple = PyTuple_New(len);
570 if (tuple == NULL)
571 return NULL;
572
573 i = 0;
574 while (_PySet_NextEntry(op, &pos, &item, &hash)) {
575 PyObject *item_key;
576
577 item_key = _PyCode_ConstantKey(item);
578 if (item_key == NULL) {
579 Py_DECREF(tuple);
580 return NULL;
581 }
582
583 assert(i < len);
584 PyTuple_SET_ITEM(tuple, i, item_key);
585 i++;
586 }
587 set = PyFrozenSet_New(tuple);
588 Py_DECREF(tuple);
589 if (set == NULL)
590 return NULL;
591
Serhiy Storchaka713640c2017-01-24 20:49:26 +0200592 key = PyTuple_Pack(2, set, op);
Victor Stinnerefb24132016-01-22 12:33:12 +0100593 Py_DECREF(set);
594 return key;
595 }
596 else {
Martin Panter6245cb32016-04-15 02:14:19 +0000597 /* for other types, use the object identifier as a unique identifier
Victor Stinnerefb24132016-01-22 12:33:12 +0100598 * to ensure that they are seen as unequal. */
599 PyObject *obj_id = PyLong_FromVoidPtr(op);
600 if (obj_id == NULL)
601 return NULL;
602
Serhiy Storchaka713640c2017-01-24 20:49:26 +0200603 key = PyTuple_Pack(2, obj_id, op);
Victor Stinnerefb24132016-01-22 12:33:12 +0100604 Py_DECREF(obj_id);
605 }
606 return key;
607}
608
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000609static PyObject *
610code_richcompare(PyObject *self, PyObject *other, int op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000611{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 PyCodeObject *co, *cp;
613 int eq;
Victor Stinnerefb24132016-01-22 12:33:12 +0100614 PyObject *consts1, *consts2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 if ((op != Py_EQ && op != Py_NE) ||
618 !PyCode_Check(self) ||
619 !PyCode_Check(other)) {
Brian Curtindfc80e32011-08-10 20:28:54 -0500620 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 co = (PyCodeObject *)self;
624 cp = (PyCodeObject *)other;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 eq = PyObject_RichCompareBool(co->co_name, cp->co_name, Py_EQ);
627 if (eq <= 0) goto unequal;
628 eq = co->co_argcount == cp->co_argcount;
629 if (!eq) goto unequal;
630 eq = co->co_kwonlyargcount == cp->co_kwonlyargcount;
631 if (!eq) goto unequal;
632 eq = co->co_nlocals == cp->co_nlocals;
633 if (!eq) goto unequal;
634 eq = co->co_flags == cp->co_flags;
635 if (!eq) goto unequal;
636 eq = co->co_firstlineno == cp->co_firstlineno;
637 if (!eq) goto unequal;
638 eq = PyObject_RichCompareBool(co->co_code, cp->co_code, Py_EQ);
639 if (eq <= 0) goto unequal;
Victor Stinnerefb24132016-01-22 12:33:12 +0100640
641 /* compare constants */
642 consts1 = _PyCode_ConstantKey(co->co_consts);
643 if (!consts1)
644 return NULL;
645 consts2 = _PyCode_ConstantKey(cp->co_consts);
646 if (!consts2) {
647 Py_DECREF(consts1);
648 return NULL;
649 }
650 eq = PyObject_RichCompareBool(consts1, consts2, Py_EQ);
651 Py_DECREF(consts1);
652 Py_DECREF(consts2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 if (eq <= 0) goto unequal;
Victor Stinnerefb24132016-01-22 12:33:12 +0100654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 eq = PyObject_RichCompareBool(co->co_names, cp->co_names, Py_EQ);
656 if (eq <= 0) goto unequal;
657 eq = PyObject_RichCompareBool(co->co_varnames, cp->co_varnames, Py_EQ);
658 if (eq <= 0) goto unequal;
659 eq = PyObject_RichCompareBool(co->co_freevars, cp->co_freevars, Py_EQ);
660 if (eq <= 0) goto unequal;
661 eq = PyObject_RichCompareBool(co->co_cellvars, cp->co_cellvars, Py_EQ);
662 if (eq <= 0) goto unequal;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 if (op == Py_EQ)
665 res = Py_True;
666 else
667 res = Py_False;
668 goto done;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000669
670 unequal:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 if (eq < 0)
672 return NULL;
673 if (op == Py_NE)
674 res = Py_True;
675 else
676 res = Py_False;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000677
678 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 Py_INCREF(res);
680 return res;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000681}
682
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000683static Py_hash_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000684code_hash(PyCodeObject *co)
685{
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000686 Py_hash_t h, h0, h1, h2, h3, h4, h5, h6;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 h0 = PyObject_Hash(co->co_name);
688 if (h0 == -1) return -1;
689 h1 = PyObject_Hash(co->co_code);
690 if (h1 == -1) return -1;
691 h2 = PyObject_Hash(co->co_consts);
692 if (h2 == -1) return -1;
693 h3 = PyObject_Hash(co->co_names);
694 if (h3 == -1) return -1;
695 h4 = PyObject_Hash(co->co_varnames);
696 if (h4 == -1) return -1;
697 h5 = PyObject_Hash(co->co_freevars);
698 if (h5 == -1) return -1;
699 h6 = PyObject_Hash(co->co_cellvars);
700 if (h6 == -1) return -1;
701 h = h0 ^ h1 ^ h2 ^ h3 ^ h4 ^ h5 ^ h6 ^
702 co->co_argcount ^ co->co_kwonlyargcount ^
703 co->co_nlocals ^ co->co_flags;
704 if (h == -1) h = -2;
705 return h;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000706}
707
708/* XXX code objects need to participate in GC? */
709
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200710static struct PyMethodDef code_methods[] = {
711 {"__sizeof__", (PyCFunction)code_sizeof, METH_NOARGS},
712 {NULL, NULL} /* sentinel */
713};
714
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000715PyTypeObject PyCode_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 PyVarObject_HEAD_INIT(&PyType_Type, 0)
717 "code",
718 sizeof(PyCodeObject),
719 0,
720 (destructor)code_dealloc, /* tp_dealloc */
721 0, /* tp_print */
722 0, /* tp_getattr */
723 0, /* tp_setattr */
724 0, /* tp_reserved */
725 (reprfunc)code_repr, /* tp_repr */
726 0, /* tp_as_number */
727 0, /* tp_as_sequence */
728 0, /* tp_as_mapping */
729 (hashfunc)code_hash, /* tp_hash */
730 0, /* tp_call */
731 0, /* tp_str */
732 PyObject_GenericGetAttr, /* tp_getattro */
733 0, /* tp_setattro */
734 0, /* tp_as_buffer */
735 Py_TPFLAGS_DEFAULT, /* tp_flags */
736 code_doc, /* tp_doc */
737 0, /* tp_traverse */
738 0, /* tp_clear */
739 code_richcompare, /* tp_richcompare */
740 offsetof(PyCodeObject, co_weakreflist), /* tp_weaklistoffset */
741 0, /* tp_iter */
742 0, /* tp_iternext */
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200743 code_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 code_memberlist, /* tp_members */
745 0, /* tp_getset */
746 0, /* tp_base */
747 0, /* tp_dict */
748 0, /* tp_descr_get */
749 0, /* tp_descr_set */
750 0, /* tp_dictoffset */
751 0, /* tp_init */
752 0, /* tp_alloc */
753 code_new, /* tp_new */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000754};
755
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000756/* Use co_lnotab to compute the line number from a bytecode index, addrq. See
757 lnotab_notes.txt for the details of the lnotab representation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000758*/
759
760int
761PyCode_Addr2Line(PyCodeObject *co, int addrq)
762{
Victor Stinner0fcab4a2011-01-04 12:59:15 +0000763 Py_ssize_t size = PyBytes_Size(co->co_lnotab) / 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 unsigned char *p = (unsigned char*)PyBytes_AsString(co->co_lnotab);
765 int line = co->co_firstlineno;
766 int addr = 0;
767 while (--size >= 0) {
768 addr += *p++;
769 if (addr > addrq)
770 break;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100771 line += (signed char)*p;
772 p++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 }
774 return line;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000775}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000776
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000777/* Update *bounds to describe the first and one-past-the-last instructions in
778 the same line as lasti. Return the number of that line. */
779int
780_PyCode_CheckLineNumber(PyCodeObject* co, int lasti, PyAddrPair *bounds)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000781{
Victor Stinner0fcab4a2011-01-04 12:59:15 +0000782 Py_ssize_t size;
783 int addr, line;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 unsigned char* p;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 p = (unsigned char*)PyBytes_AS_STRING(co->co_lnotab);
787 size = PyBytes_GET_SIZE(co->co_lnotab) / 2;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 addr = 0;
790 line = co->co_firstlineno;
791 assert(line > 0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 /* possible optimization: if f->f_lasti == instr_ub
794 (likely to be a common case) then we already know
795 instr_lb -- if we stored the matching value of p
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700796 somewhere we could skip the first while loop. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 /* See lnotab_notes.txt for the description of
799 co_lnotab. A point to remember: increments to p
800 come in (addr, line) pairs. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 bounds->ap_lower = 0;
803 while (size > 0) {
804 if (addr + *p > lasti)
805 break;
806 addr += *p++;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100807 if ((signed char)*p)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 bounds->ap_lower = addr;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100809 line += (signed char)*p;
810 p++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 --size;
812 }
813
814 if (size > 0) {
815 while (--size >= 0) {
816 addr += *p++;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100817 if ((signed char)*p)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 break;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100819 p++;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000820 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 bounds->ap_upper = addr;
822 }
823 else {
824 bounds->ap_upper = INT_MAX;
825 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 return line;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000828}
Brett Cannon5c4de282016-09-07 11:16:41 -0700829
830
831int
832_PyCode_GetExtra(PyObject *code, Py_ssize_t index, void **extra)
833{
Brett Cannon5c4de282016-09-07 11:16:41 -0700834 if (!PyCode_Check(code)) {
835 PyErr_BadInternalCall();
Brett Cannon3788b852016-09-07 12:51:08 -0700836 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -0700837 }
838
Brett Cannond0600ed2016-09-07 14:30:39 -0700839 PyCodeObject *o = (PyCodeObject*) code;
840 _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra*) o->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700841
Brett Cannond0600ed2016-09-07 14:30:39 -0700842 if (co_extra == NULL || co_extra->ce_size <= index) {
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700843 *extra = NULL;
Brett Cannon5c4de282016-09-07 11:16:41 -0700844 return 0;
845 }
846
Brett Cannond0600ed2016-09-07 14:30:39 -0700847 *extra = co_extra->ce_extras[index];
Brett Cannon5c4de282016-09-07 11:16:41 -0700848 return 0;
849}
850
851
852int
853_PyCode_SetExtra(PyObject *code, Py_ssize_t index, void *extra)
854{
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700855 PyInterpreterState *interp = PyThreadState_Get()->interp;
Brett Cannon5c4de282016-09-07 11:16:41 -0700856
857 if (!PyCode_Check(code) || index < 0 ||
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700858 index >= interp->co_extra_user_count) {
Brett Cannon5c4de282016-09-07 11:16:41 -0700859 PyErr_BadInternalCall();
Brett Cannon3788b852016-09-07 12:51:08 -0700860 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -0700861 }
862
Brett Cannond0600ed2016-09-07 14:30:39 -0700863 PyCodeObject *o = (PyCodeObject*) code;
864 _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra *) o->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700865
Serhiy Storchaka378ebb62017-07-04 15:06:16 +0300866 if (co_extra == NULL || co_extra->ce_size <= index) {
867 Py_ssize_t i = (co_extra == NULL ? 0 : co_extra->ce_size);
868 co_extra = PyMem_Realloc(
869 co_extra,
870 sizeof(_PyCodeObjectExtra) +
871 (interp->co_extra_user_count-1) * sizeof(void*));
Brian Coleman6a9122c2017-03-02 10:32:18 +0000872 if (co_extra == NULL) {
Brett Cannon3788b852016-09-07 12:51:08 -0700873 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -0700874 }
Serhiy Storchaka378ebb62017-07-04 15:06:16 +0300875 for (; i < interp->co_extra_user_count; i++) {
Brett Cannond0600ed2016-09-07 14:30:39 -0700876 co_extra->ce_extras[i] = NULL;
Brett Cannon5c4de282016-09-07 11:16:41 -0700877 }
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700878 co_extra->ce_size = interp->co_extra_user_count;
Serhiy Storchaka378ebb62017-07-04 15:06:16 +0300879 o->co_extra = co_extra;
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700880 }
881
882 if (co_extra->ce_extras[index] != NULL) {
883 freefunc free = interp->co_extra_freefuncs[index];
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700884 if (free != NULL) {
885 free(co_extra->ce_extras[index]);
886 }
Brett Cannon5c4de282016-09-07 11:16:41 -0700887 }
888
Brett Cannond0600ed2016-09-07 14:30:39 -0700889 co_extra->ce_extras[index] = extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700890 return 0;
891}