blob: 22c4f856cd83e6f89895d03d57f5b7073ef011e6 [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
7#define NAME_CHARS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00008 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00009
Brett Cannond0600ed2016-09-07 14:30:39 -070010/* Holder for co_extra information */
11typedef struct {
12 Py_ssize_t ce_size;
13 void **ce_extras;
14} _PyCodeObjectExtra;
15
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000016/* all_name_chars(s): true iff all chars in s are valid NAME_CHARS */
17
18static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020019all_name_chars(PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000020{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000021 static char ok_name_char[256];
Serhiy Storchaka09f3d082016-10-04 18:17:22 +030022 static const unsigned char *name_chars = (unsigned char *)NAME_CHARS;
23 const unsigned char *s, *e;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020024
Serhiy Storchaka09f3d082016-10-04 18:17:22 +030025 if (!PyUnicode_Check(o) || PyUnicode_READY(o) == -1 ||
26 !PyUnicode_IS_ASCII(o))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020027 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000029 if (ok_name_char[*name_chars] == 0) {
Serhiy Storchaka09f3d082016-10-04 18:17:22 +030030 const unsigned char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000031 for (p = name_chars; *p; p++)
32 ok_name_char[*p] = 1;
33 }
Serhiy Storchaka09f3d082016-10-04 18:17:22 +030034 s = PyUnicode_1BYTE_DATA(o);
35 e = s + PyUnicode_GET_LENGTH(o);
36 while (s != e) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000037 if (ok_name_char[*s++] == 0)
38 return 0;
39 }
40 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000041}
42
43static void
44intern_strings(PyObject *tuple)
45{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000046 Py_ssize_t i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000048 for (i = PyTuple_GET_SIZE(tuple); --i >= 0; ) {
49 PyObject *v = PyTuple_GET_ITEM(tuple, i);
50 if (v == NULL || !PyUnicode_CheckExact(v)) {
51 Py_FatalError("non-string found in code slot");
52 }
53 PyUnicode_InternInPlace(&PyTuple_GET_ITEM(tuple, i));
54 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000055}
56
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +030057/* Intern selected string constants */
58static int
59intern_string_constants(PyObject *tuple)
60{
61 int modified = 0;
62 Py_ssize_t i;
63
64 for (i = PyTuple_GET_SIZE(tuple); --i >= 0; ) {
65 PyObject *v = PyTuple_GET_ITEM(tuple, i);
66 if (PyUnicode_CheckExact(v)) {
67 if (all_name_chars(v)) {
68 PyObject *w = v;
69 PyUnicode_InternInPlace(&v);
70 if (w != v) {
71 PyTuple_SET_ITEM(tuple, i, v);
72 modified = 1;
73 }
74 }
75 }
76 else if (PyTuple_CheckExact(v)) {
77 intern_string_constants(v);
78 }
79 else if (PyFrozenSet_CheckExact(v)) {
Yury Selivanovd2fd3592016-11-09 09:42:14 -050080 PyObject *w = v;
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +030081 PyObject *tmp = PySequence_Tuple(v);
82 if (tmp == NULL) {
83 PyErr_Clear();
84 continue;
85 }
86 if (intern_string_constants(tmp)) {
87 v = PyFrozenSet_New(tmp);
88 if (v == NULL) {
89 PyErr_Clear();
90 }
91 else {
92 PyTuple_SET_ITEM(tuple, i, v);
Yury Selivanovd2fd3592016-11-09 09:42:14 -050093 Py_DECREF(w);
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +030094 modified = 1;
95 }
96 }
97 Py_DECREF(tmp);
98 }
99 }
100 return modified;
101}
102
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000103
104PyCodeObject *
Guido van Rossum4f72a782006-10-27 23:31:49 +0000105PyCode_New(int argcount, int kwonlyargcount,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 int nlocals, int stacksize, int flags,
107 PyObject *code, PyObject *consts, PyObject *names,
108 PyObject *varnames, PyObject *freevars, PyObject *cellvars,
109 PyObject *filename, PyObject *name, int firstlineno,
110 PyObject *lnotab)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000111{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 PyCodeObject *co;
Benjamin Peterson90037602011-06-25 22:54:45 -0500113 unsigned char *cell2arg = NULL;
114 Py_ssize_t i, n_cellvars;
Guido van Rossum00bc0e02007-10-15 02:52:41 +0000115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 /* Check argument types */
117 if (argcount < 0 || kwonlyargcount < 0 || nlocals < 0 ||
118 code == NULL ||
119 consts == NULL || !PyTuple_Check(consts) ||
120 names == NULL || !PyTuple_Check(names) ||
121 varnames == NULL || !PyTuple_Check(varnames) ||
122 freevars == NULL || !PyTuple_Check(freevars) ||
123 cellvars == NULL || !PyTuple_Check(cellvars) ||
124 name == NULL || !PyUnicode_Check(name) ||
125 filename == NULL || !PyUnicode_Check(filename) ||
126 lnotab == NULL || !PyBytes_Check(lnotab) ||
127 !PyObject_CheckReadBuffer(code)) {
128 PyErr_BadInternalCall();
129 return NULL;
130 }
Victor Stinner7c74de42013-10-10 15:55:14 +0200131
132 /* Ensure that the filename is a ready Unicode string */
133 if (PyUnicode_READY(filename) < 0)
134 return NULL;
135
Benjamin Peterson90037602011-06-25 22:54:45 -0500136 n_cellvars = PyTuple_GET_SIZE(cellvars);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 intern_strings(names);
138 intern_strings(varnames);
139 intern_strings(freevars);
140 intern_strings(cellvars);
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +0300141 intern_string_constants(consts);
Benjamin Peterson90037602011-06-25 22:54:45 -0500142 /* Create mapping between cells and arguments if needed. */
143 if (n_cellvars) {
144 Py_ssize_t total_args = argcount + kwonlyargcount +
145 ((flags & CO_VARARGS) != 0) + ((flags & CO_VARKEYWORDS) != 0);
146 Py_ssize_t alloc_size = sizeof(unsigned char) * n_cellvars;
Benjamin Peterson1bf494b2016-09-07 11:28:35 -0700147 bool used_cell2arg = false;
Benjamin Peterson90037602011-06-25 22:54:45 -0500148 cell2arg = PyMem_MALLOC(alloc_size);
149 if (cell2arg == NULL)
150 return NULL;
151 memset(cell2arg, CO_CELL_NOT_AN_ARG, alloc_size);
152 /* Find cells which are also arguments. */
153 for (i = 0; i < n_cellvars; i++) {
154 Py_ssize_t j;
155 PyObject *cell = PyTuple_GET_ITEM(cellvars, i);
156 for (j = 0; j < total_args; j++) {
157 PyObject *arg = PyTuple_GET_ITEM(varnames, j);
158 if (!PyUnicode_Compare(cell, arg)) {
159 cell2arg[i] = j;
Benjamin Peterson1bf494b2016-09-07 11:28:35 -0700160 used_cell2arg = true;
Benjamin Peterson90037602011-06-25 22:54:45 -0500161 break;
162 }
163 }
164 }
165 if (!used_cell2arg) {
166 PyMem_FREE(cell2arg);
167 cell2arg = NULL;
168 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 }
Benjamin Peterson90037602011-06-25 22:54:45 -0500170 co = PyObject_NEW(PyCodeObject, &PyCode_Type);
171 if (co == NULL) {
172 if (cell2arg)
173 PyMem_FREE(cell2arg);
174 return NULL;
175 }
176 co->co_argcount = argcount;
177 co->co_kwonlyargcount = kwonlyargcount;
178 co->co_nlocals = nlocals;
179 co->co_stacksize = stacksize;
180 co->co_flags = flags;
181 Py_INCREF(code);
182 co->co_code = code;
183 Py_INCREF(consts);
184 co->co_consts = consts;
185 Py_INCREF(names);
186 co->co_names = names;
187 Py_INCREF(varnames);
188 co->co_varnames = varnames;
189 Py_INCREF(freevars);
190 co->co_freevars = freevars;
191 Py_INCREF(cellvars);
192 co->co_cellvars = cellvars;
193 co->co_cell2arg = cell2arg;
194 Py_INCREF(filename);
195 co->co_filename = filename;
196 Py_INCREF(name);
197 co->co_name = name;
198 co->co_firstlineno = firstlineno;
199 Py_INCREF(lnotab);
200 co->co_lnotab = lnotab;
201 co->co_zombieframe = NULL;
202 co->co_weakreflist = NULL;
Brett Cannon5c4de282016-09-07 11:16:41 -0700203 co->co_extra = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000205}
206
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000207PyCodeObject *
208PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno)
209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 static PyObject *emptystring = NULL;
211 static PyObject *nulltuple = NULL;
212 PyObject *filename_ob = NULL;
213 PyObject *funcname_ob = NULL;
214 PyCodeObject *result = NULL;
215 if (emptystring == NULL) {
216 emptystring = PyBytes_FromString("");
217 if (emptystring == NULL)
218 goto failed;
219 }
220 if (nulltuple == NULL) {
221 nulltuple = PyTuple_New(0);
222 if (nulltuple == NULL)
223 goto failed;
224 }
225 funcname_ob = PyUnicode_FromString(funcname);
226 if (funcname_ob == NULL)
227 goto failed;
228 filename_ob = PyUnicode_DecodeFSDefault(filename);
229 if (filename_ob == NULL)
230 goto failed;
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 result = PyCode_New(0, /* argcount */
233 0, /* kwonlyargcount */
234 0, /* nlocals */
235 0, /* stacksize */
236 0, /* flags */
237 emptystring, /* code */
238 nulltuple, /* consts */
239 nulltuple, /* names */
240 nulltuple, /* varnames */
241 nulltuple, /* freevars */
242 nulltuple, /* cellvars */
243 filename_ob, /* filename */
244 funcname_ob, /* name */
245 firstlineno, /* firstlineno */
246 emptystring /* lnotab */
247 );
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000248
249failed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 Py_XDECREF(funcname_ob);
251 Py_XDECREF(filename_ob);
252 return result;
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000253}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000254
255#define OFF(x) offsetof(PyCodeObject, x)
256
257static PyMemberDef code_memberlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 {"co_argcount", T_INT, OFF(co_argcount), READONLY},
259 {"co_kwonlyargcount", T_INT, OFF(co_kwonlyargcount), READONLY},
260 {"co_nlocals", T_INT, OFF(co_nlocals), READONLY},
261 {"co_stacksize",T_INT, OFF(co_stacksize), READONLY},
262 {"co_flags", T_INT, OFF(co_flags), READONLY},
263 {"co_code", T_OBJECT, OFF(co_code), READONLY},
264 {"co_consts", T_OBJECT, OFF(co_consts), READONLY},
265 {"co_names", T_OBJECT, OFF(co_names), READONLY},
266 {"co_varnames", T_OBJECT, OFF(co_varnames), READONLY},
267 {"co_freevars", T_OBJECT, OFF(co_freevars), READONLY},
268 {"co_cellvars", T_OBJECT, OFF(co_cellvars), READONLY},
269 {"co_filename", T_OBJECT, OFF(co_filename), READONLY},
270 {"co_name", T_OBJECT, OFF(co_name), READONLY},
271 {"co_firstlineno", T_INT, OFF(co_firstlineno), READONLY},
272 {"co_lnotab", T_OBJECT, OFF(co_lnotab), READONLY},
273 {NULL} /* Sentinel */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000274};
275
276/* Helper for code_new: return a shallow copy of a tuple that is
277 guaranteed to contain exact strings, by converting string subclasses
278 to exact strings and complaining if a non-string is found. */
279static PyObject*
280validate_and_copy_tuple(PyObject *tup)
281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 PyObject *newtuple;
283 PyObject *item;
284 Py_ssize_t i, len;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 len = PyTuple_GET_SIZE(tup);
287 newtuple = PyTuple_New(len);
288 if (newtuple == NULL)
289 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 for (i = 0; i < len; i++) {
292 item = PyTuple_GET_ITEM(tup, i);
293 if (PyUnicode_CheckExact(item)) {
294 Py_INCREF(item);
295 }
296 else if (!PyUnicode_Check(item)) {
297 PyErr_Format(
298 PyExc_TypeError,
299 "name tuples must contain only "
300 "strings, not '%.500s'",
301 item->ob_type->tp_name);
302 Py_DECREF(newtuple);
303 return NULL;
304 }
305 else {
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100306 item = _PyUnicode_Copy(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 if (item == NULL) {
308 Py_DECREF(newtuple);
309 return NULL;
310 }
311 }
312 PyTuple_SET_ITEM(newtuple, i, item);
313 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 return newtuple;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000316}
317
318PyDoc_STRVAR(code_doc,
Georg Brandl8c1a50a2009-07-18 09:07:48 +0000319"code(argcount, kwonlyargcount, nlocals, stacksize, flags, codestring,\n\
Georg Brandla1e7e132008-01-26 09:39:23 +0000320 constants, names, varnames, filename, name, firstlineno,\n\
321 lnotab[, freevars[, cellvars]])\n\
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000322\n\
323Create a code object. Not for the faint of heart.");
324
325static PyObject *
326code_new(PyTypeObject *type, PyObject *args, PyObject *kw)
327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 int argcount;
329 int kwonlyargcount;
330 int nlocals;
331 int stacksize;
332 int flags;
333 PyObject *co = NULL;
334 PyObject *code;
335 PyObject *consts;
336 PyObject *names, *ournames = NULL;
337 PyObject *varnames, *ourvarnames = NULL;
338 PyObject *freevars = NULL, *ourfreevars = NULL;
339 PyObject *cellvars = NULL, *ourcellvars = NULL;
340 PyObject *filename;
341 PyObject *name;
342 int firstlineno;
343 PyObject *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 if (!PyArg_ParseTuple(args, "iiiiiSO!O!O!UUiS|O!O!:code",
346 &argcount, &kwonlyargcount,
347 &nlocals, &stacksize, &flags,
348 &code,
349 &PyTuple_Type, &consts,
350 &PyTuple_Type, &names,
351 &PyTuple_Type, &varnames,
352 &filename, &name,
353 &firstlineno, &lnotab,
354 &PyTuple_Type, &freevars,
355 &PyTuple_Type, &cellvars))
356 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 if (argcount < 0) {
359 PyErr_SetString(
360 PyExc_ValueError,
361 "code: argcount must not be negative");
362 goto cleanup;
363 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 if (kwonlyargcount < 0) {
366 PyErr_SetString(
367 PyExc_ValueError,
368 "code: kwonlyargcount must not be negative");
369 goto cleanup;
370 }
371 if (nlocals < 0) {
372 PyErr_SetString(
373 PyExc_ValueError,
374 "code: nlocals must not be negative");
375 goto cleanup;
376 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 ournames = validate_and_copy_tuple(names);
379 if (ournames == NULL)
380 goto cleanup;
381 ourvarnames = validate_and_copy_tuple(varnames);
382 if (ourvarnames == NULL)
383 goto cleanup;
384 if (freevars)
385 ourfreevars = validate_and_copy_tuple(freevars);
386 else
387 ourfreevars = PyTuple_New(0);
388 if (ourfreevars == NULL)
389 goto cleanup;
390 if (cellvars)
391 ourcellvars = validate_and_copy_tuple(cellvars);
392 else
393 ourcellvars = PyTuple_New(0);
394 if (ourcellvars == NULL)
395 goto cleanup;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 co = (PyObject *)PyCode_New(argcount, kwonlyargcount,
398 nlocals, stacksize, flags,
399 code, consts, ournames, ourvarnames,
400 ourfreevars, ourcellvars, filename,
401 name, firstlineno, lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000402 cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 Py_XDECREF(ournames);
404 Py_XDECREF(ourvarnames);
405 Py_XDECREF(ourfreevars);
406 Py_XDECREF(ourcellvars);
407 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000408}
409
410static void
411code_dealloc(PyCodeObject *co)
412{
Brett Cannon5c4de282016-09-07 11:16:41 -0700413 if (co->co_extra != NULL) {
414 PyThreadState *tstate = PyThreadState_Get();
Brett Cannond0600ed2016-09-07 14:30:39 -0700415 _PyCodeObjectExtra *co_extra = co->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700416
Brett Cannond0600ed2016-09-07 14:30:39 -0700417 for (Py_ssize_t i = 0; i < co_extra->ce_size; i++) {
Brett Cannon5c4de282016-09-07 11:16:41 -0700418 freefunc free_extra = tstate->co_extra_freefuncs[i];
419
420 if (free_extra != NULL) {
Brett Cannond0600ed2016-09-07 14:30:39 -0700421 free_extra(co_extra->ce_extras[i]);
Brett Cannon5c4de282016-09-07 11:16:41 -0700422 }
423 }
424
425 PyMem_FREE(co->co_extra);
426 }
427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 Py_XDECREF(co->co_code);
429 Py_XDECREF(co->co_consts);
430 Py_XDECREF(co->co_names);
431 Py_XDECREF(co->co_varnames);
432 Py_XDECREF(co->co_freevars);
433 Py_XDECREF(co->co_cellvars);
434 Py_XDECREF(co->co_filename);
435 Py_XDECREF(co->co_name);
436 Py_XDECREF(co->co_lnotab);
Benjamin Peterson90037602011-06-25 22:54:45 -0500437 if (co->co_cell2arg != NULL)
438 PyMem_FREE(co->co_cell2arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 if (co->co_zombieframe != NULL)
440 PyObject_GC_Del(co->co_zombieframe);
441 if (co->co_weakreflist != NULL)
442 PyObject_ClearWeakRefs((PyObject*)co);
443 PyObject_DEL(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000444}
445
446static PyObject *
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200447code_sizeof(PyCodeObject *co, void *unused)
448{
Dong-hee Nadf5df132017-04-20 17:26:25 +0900449 Py_ssize_t res = _PyObject_SIZE(Py_TYPE(co));
450 _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra*) co->co_extra;
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200451
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200452 if (co->co_cell2arg != NULL && co->co_cellvars != NULL)
Dong-hee Nadf5df132017-04-20 17:26:25 +0900453 res += PyTuple_GET_SIZE(co->co_cellvars) * sizeof(Py_ssize_t);
454
455 if (co_extra != NULL)
456 res += co_extra->ce_size * sizeof(co_extra->ce_extras[0]);
457
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200458 return PyLong_FromSsize_t(res);
459}
460
461static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000462code_repr(PyCodeObject *co)
463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 int lineno;
465 if (co->co_firstlineno != 0)
466 lineno = co->co_firstlineno;
467 else
468 lineno = -1;
469 if (co->co_filename && PyUnicode_Check(co->co_filename)) {
470 return PyUnicode_FromFormat(
Victor Stinneraaa4e9a2011-01-05 03:33:26 +0000471 "<code object %U at %p, file \"%U\", line %d>",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 co->co_name, co, co->co_filename, lineno);
473 } else {
474 return PyUnicode_FromFormat(
Victor Stinneraaa4e9a2011-01-05 03:33:26 +0000475 "<code object %U at %p, file ???, line %d>",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 co->co_name, co, lineno);
477 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000478}
479
Victor Stinnerefb24132016-01-22 12:33:12 +0100480PyObject*
481_PyCode_ConstantKey(PyObject *op)
482{
483 PyObject *key;
484
485 /* Py_None and Py_Ellipsis are singleton */
486 if (op == Py_None || op == Py_Ellipsis
487 || PyLong_CheckExact(op)
488 || PyBool_Check(op)
489 || PyBytes_CheckExact(op)
490 || PyUnicode_CheckExact(op)
491 /* code_richcompare() uses _PyCode_ConstantKey() internally */
492 || PyCode_Check(op)) {
493 key = PyTuple_Pack(2, Py_TYPE(op), op);
494 }
495 else if (PyFloat_CheckExact(op)) {
496 double d = PyFloat_AS_DOUBLE(op);
497 /* all we need is to make the tuple different in either the 0.0
498 * or -0.0 case from all others, just to avoid the "coercion".
499 */
500 if (d == 0.0 && copysign(1.0, d) < 0.0)
501 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
502 else
503 key = PyTuple_Pack(2, Py_TYPE(op), op);
504 }
505 else if (PyComplex_CheckExact(op)) {
506 Py_complex z;
507 int real_negzero, imag_negzero;
508 /* For the complex case we must make complex(x, 0.)
509 different from complex(x, -0.) and complex(0., y)
510 different from complex(-0., y), for any x and y.
511 All four complex zeros must be distinguished.*/
512 z = PyComplex_AsCComplex(op);
513 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
514 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
515 /* use True, False and None singleton as tags for the real and imag
516 * sign, to make tuples different */
517 if (real_negzero && imag_negzero) {
518 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_True);
519 }
520 else if (imag_negzero) {
521 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_False);
522 }
523 else if (real_negzero) {
524 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
525 }
526 else {
527 key = PyTuple_Pack(2, Py_TYPE(op), op);
528 }
529 }
530 else if (PyTuple_CheckExact(op)) {
531 Py_ssize_t i, len;
532 PyObject *tuple;
533
534 len = PyTuple_GET_SIZE(op);
535 tuple = PyTuple_New(len);
536 if (tuple == NULL)
537 return NULL;
538
539 for (i=0; i < len; i++) {
540 PyObject *item, *item_key;
541
542 item = PyTuple_GET_ITEM(op, i);
543 item_key = _PyCode_ConstantKey(item);
544 if (item_key == NULL) {
545 Py_DECREF(tuple);
546 return NULL;
547 }
548
549 PyTuple_SET_ITEM(tuple, i, item_key);
550 }
551
Serhiy Storchaka713640c2017-01-24 20:49:26 +0200552 key = PyTuple_Pack(2, tuple, op);
Victor Stinnerefb24132016-01-22 12:33:12 +0100553 Py_DECREF(tuple);
554 }
555 else if (PyFrozenSet_CheckExact(op)) {
556 Py_ssize_t pos = 0;
557 PyObject *item;
558 Py_hash_t hash;
559 Py_ssize_t i, len;
560 PyObject *tuple, *set;
561
562 len = PySet_GET_SIZE(op);
563 tuple = PyTuple_New(len);
564 if (tuple == NULL)
565 return NULL;
566
567 i = 0;
568 while (_PySet_NextEntry(op, &pos, &item, &hash)) {
569 PyObject *item_key;
570
571 item_key = _PyCode_ConstantKey(item);
572 if (item_key == NULL) {
573 Py_DECREF(tuple);
574 return NULL;
575 }
576
577 assert(i < len);
578 PyTuple_SET_ITEM(tuple, i, item_key);
579 i++;
580 }
581 set = PyFrozenSet_New(tuple);
582 Py_DECREF(tuple);
583 if (set == NULL)
584 return NULL;
585
Serhiy Storchaka713640c2017-01-24 20:49:26 +0200586 key = PyTuple_Pack(2, set, op);
Victor Stinnerefb24132016-01-22 12:33:12 +0100587 Py_DECREF(set);
588 return key;
589 }
590 else {
Martin Panter6245cb32016-04-15 02:14:19 +0000591 /* for other types, use the object identifier as a unique identifier
Victor Stinnerefb24132016-01-22 12:33:12 +0100592 * to ensure that they are seen as unequal. */
593 PyObject *obj_id = PyLong_FromVoidPtr(op);
594 if (obj_id == NULL)
595 return NULL;
596
Serhiy Storchaka713640c2017-01-24 20:49:26 +0200597 key = PyTuple_Pack(2, obj_id, op);
Victor Stinnerefb24132016-01-22 12:33:12 +0100598 Py_DECREF(obj_id);
599 }
600 return key;
601}
602
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000603static PyObject *
604code_richcompare(PyObject *self, PyObject *other, int op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000605{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 PyCodeObject *co, *cp;
607 int eq;
Victor Stinnerefb24132016-01-22 12:33:12 +0100608 PyObject *consts1, *consts2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 if ((op != Py_EQ && op != Py_NE) ||
612 !PyCode_Check(self) ||
613 !PyCode_Check(other)) {
Brian Curtindfc80e32011-08-10 20:28:54 -0500614 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 co = (PyCodeObject *)self;
618 cp = (PyCodeObject *)other;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 eq = PyObject_RichCompareBool(co->co_name, cp->co_name, Py_EQ);
621 if (eq <= 0) goto unequal;
622 eq = co->co_argcount == cp->co_argcount;
623 if (!eq) goto unequal;
624 eq = co->co_kwonlyargcount == cp->co_kwonlyargcount;
625 if (!eq) goto unequal;
626 eq = co->co_nlocals == cp->co_nlocals;
627 if (!eq) goto unequal;
628 eq = co->co_flags == cp->co_flags;
629 if (!eq) goto unequal;
630 eq = co->co_firstlineno == cp->co_firstlineno;
631 if (!eq) goto unequal;
632 eq = PyObject_RichCompareBool(co->co_code, cp->co_code, Py_EQ);
633 if (eq <= 0) goto unequal;
Victor Stinnerefb24132016-01-22 12:33:12 +0100634
635 /* compare constants */
636 consts1 = _PyCode_ConstantKey(co->co_consts);
637 if (!consts1)
638 return NULL;
639 consts2 = _PyCode_ConstantKey(cp->co_consts);
640 if (!consts2) {
641 Py_DECREF(consts1);
642 return NULL;
643 }
644 eq = PyObject_RichCompareBool(consts1, consts2, Py_EQ);
645 Py_DECREF(consts1);
646 Py_DECREF(consts2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 if (eq <= 0) goto unequal;
Victor Stinnerefb24132016-01-22 12:33:12 +0100648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 eq = PyObject_RichCompareBool(co->co_names, cp->co_names, Py_EQ);
650 if (eq <= 0) goto unequal;
651 eq = PyObject_RichCompareBool(co->co_varnames, cp->co_varnames, Py_EQ);
652 if (eq <= 0) goto unequal;
653 eq = PyObject_RichCompareBool(co->co_freevars, cp->co_freevars, Py_EQ);
654 if (eq <= 0) goto unequal;
655 eq = PyObject_RichCompareBool(co->co_cellvars, cp->co_cellvars, Py_EQ);
656 if (eq <= 0) goto unequal;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 if (op == Py_EQ)
659 res = Py_True;
660 else
661 res = Py_False;
662 goto done;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000663
664 unequal:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 if (eq < 0)
666 return NULL;
667 if (op == Py_NE)
668 res = Py_True;
669 else
670 res = Py_False;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000671
672 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 Py_INCREF(res);
674 return res;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000675}
676
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000677static Py_hash_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000678code_hash(PyCodeObject *co)
679{
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000680 Py_hash_t h, h0, h1, h2, h3, h4, h5, h6;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 h0 = PyObject_Hash(co->co_name);
682 if (h0 == -1) return -1;
683 h1 = PyObject_Hash(co->co_code);
684 if (h1 == -1) return -1;
685 h2 = PyObject_Hash(co->co_consts);
686 if (h2 == -1) return -1;
687 h3 = PyObject_Hash(co->co_names);
688 if (h3 == -1) return -1;
689 h4 = PyObject_Hash(co->co_varnames);
690 if (h4 == -1) return -1;
691 h5 = PyObject_Hash(co->co_freevars);
692 if (h5 == -1) return -1;
693 h6 = PyObject_Hash(co->co_cellvars);
694 if (h6 == -1) return -1;
695 h = h0 ^ h1 ^ h2 ^ h3 ^ h4 ^ h5 ^ h6 ^
696 co->co_argcount ^ co->co_kwonlyargcount ^
697 co->co_nlocals ^ co->co_flags;
698 if (h == -1) h = -2;
699 return h;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000700}
701
702/* XXX code objects need to participate in GC? */
703
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200704static struct PyMethodDef code_methods[] = {
705 {"__sizeof__", (PyCFunction)code_sizeof, METH_NOARGS},
706 {NULL, NULL} /* sentinel */
707};
708
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000709PyTypeObject PyCode_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 PyVarObject_HEAD_INIT(&PyType_Type, 0)
711 "code",
712 sizeof(PyCodeObject),
713 0,
714 (destructor)code_dealloc, /* tp_dealloc */
715 0, /* tp_print */
716 0, /* tp_getattr */
717 0, /* tp_setattr */
718 0, /* tp_reserved */
719 (reprfunc)code_repr, /* tp_repr */
720 0, /* tp_as_number */
721 0, /* tp_as_sequence */
722 0, /* tp_as_mapping */
723 (hashfunc)code_hash, /* tp_hash */
724 0, /* tp_call */
725 0, /* tp_str */
726 PyObject_GenericGetAttr, /* tp_getattro */
727 0, /* tp_setattro */
728 0, /* tp_as_buffer */
729 Py_TPFLAGS_DEFAULT, /* tp_flags */
730 code_doc, /* tp_doc */
731 0, /* tp_traverse */
732 0, /* tp_clear */
733 code_richcompare, /* tp_richcompare */
734 offsetof(PyCodeObject, co_weakreflist), /* tp_weaklistoffset */
735 0, /* tp_iter */
736 0, /* tp_iternext */
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200737 code_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 code_memberlist, /* tp_members */
739 0, /* tp_getset */
740 0, /* tp_base */
741 0, /* tp_dict */
742 0, /* tp_descr_get */
743 0, /* tp_descr_set */
744 0, /* tp_dictoffset */
745 0, /* tp_init */
746 0, /* tp_alloc */
747 code_new, /* tp_new */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000748};
749
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000750/* Use co_lnotab to compute the line number from a bytecode index, addrq. See
751 lnotab_notes.txt for the details of the lnotab representation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000752*/
753
754int
755PyCode_Addr2Line(PyCodeObject *co, int addrq)
756{
Victor Stinner0fcab4a2011-01-04 12:59:15 +0000757 Py_ssize_t size = PyBytes_Size(co->co_lnotab) / 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 unsigned char *p = (unsigned char*)PyBytes_AsString(co->co_lnotab);
759 int line = co->co_firstlineno;
760 int addr = 0;
761 while (--size >= 0) {
762 addr += *p++;
763 if (addr > addrq)
764 break;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100765 line += (signed char)*p;
766 p++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 }
768 return line;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000769}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000770
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000771/* Update *bounds to describe the first and one-past-the-last instructions in
772 the same line as lasti. Return the number of that line. */
773int
774_PyCode_CheckLineNumber(PyCodeObject* co, int lasti, PyAddrPair *bounds)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000775{
Victor Stinner0fcab4a2011-01-04 12:59:15 +0000776 Py_ssize_t size;
777 int addr, line;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 unsigned char* p;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 p = (unsigned char*)PyBytes_AS_STRING(co->co_lnotab);
781 size = PyBytes_GET_SIZE(co->co_lnotab) / 2;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 addr = 0;
784 line = co->co_firstlineno;
785 assert(line > 0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 /* possible optimization: if f->f_lasti == instr_ub
788 (likely to be a common case) then we already know
789 instr_lb -- if we stored the matching value of p
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700790 somewhere we could skip the first while loop. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 /* See lnotab_notes.txt for the description of
793 co_lnotab. A point to remember: increments to p
794 come in (addr, line) pairs. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 bounds->ap_lower = 0;
797 while (size > 0) {
798 if (addr + *p > lasti)
799 break;
800 addr += *p++;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100801 if ((signed char)*p)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 bounds->ap_lower = addr;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100803 line += (signed char)*p;
804 p++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 --size;
806 }
807
808 if (size > 0) {
809 while (--size >= 0) {
810 addr += *p++;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100811 if ((signed char)*p)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 break;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100813 p++;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000814 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 bounds->ap_upper = addr;
816 }
817 else {
818 bounds->ap_upper = INT_MAX;
819 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 return line;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000822}
Brett Cannon5c4de282016-09-07 11:16:41 -0700823
824
825int
826_PyCode_GetExtra(PyObject *code, Py_ssize_t index, void **extra)
827{
Brett Cannon5c4de282016-09-07 11:16:41 -0700828 assert(*extra == NULL);
829
830 if (!PyCode_Check(code)) {
831 PyErr_BadInternalCall();
Brett Cannon3788b852016-09-07 12:51:08 -0700832 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -0700833 }
834
Brett Cannond0600ed2016-09-07 14:30:39 -0700835 PyCodeObject *o = (PyCodeObject*) code;
836 _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra*) o->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700837
Brett Cannond0600ed2016-09-07 14:30:39 -0700838
839 if (co_extra == NULL || co_extra->ce_size <= index) {
Brett Cannon5c4de282016-09-07 11:16:41 -0700840 return 0;
841 }
842
Brett Cannond0600ed2016-09-07 14:30:39 -0700843 *extra = co_extra->ce_extras[index];
Brett Cannon5c4de282016-09-07 11:16:41 -0700844 return 0;
845}
846
847
848int
849_PyCode_SetExtra(PyObject *code, Py_ssize_t index, void *extra)
850{
Brett Cannon5c4de282016-09-07 11:16:41 -0700851 PyThreadState *tstate = PyThreadState_Get();
852
853 if (!PyCode_Check(code) || index < 0 ||
854 index >= tstate->co_extra_user_count) {
855 PyErr_BadInternalCall();
Brett Cannon3788b852016-09-07 12:51:08 -0700856 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -0700857 }
858
Brett Cannond0600ed2016-09-07 14:30:39 -0700859 PyCodeObject *o = (PyCodeObject*) code;
860 _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra *) o->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700861
Brett Cannond0600ed2016-09-07 14:30:39 -0700862 if (co_extra == NULL) {
Brian Colemana6e84932017-03-02 22:21:53 +0000863 co_extra = PyMem_Malloc(sizeof(_PyCodeObjectExtra));
864 if (co_extra == NULL) {
Brett Cannon3788b852016-09-07 12:51:08 -0700865 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -0700866 }
867
Brett Cannond0600ed2016-09-07 14:30:39 -0700868 co_extra->ce_extras = PyMem_Malloc(
Brett Cannon5c4de282016-09-07 11:16:41 -0700869 tstate->co_extra_user_count * sizeof(void*));
Brett Cannond0600ed2016-09-07 14:30:39 -0700870 if (co_extra->ce_extras == NULL) {
Brian Colemana6e84932017-03-02 22:21:53 +0000871 PyMem_Free(co_extra);
Brett Cannon3788b852016-09-07 12:51:08 -0700872 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -0700873 }
874
Brett Cannond0600ed2016-09-07 14:30:39 -0700875 co_extra->ce_size = tstate->co_extra_user_count;
Brett Cannon5c4de282016-09-07 11:16:41 -0700876
Brett Cannond0600ed2016-09-07 14:30:39 -0700877 for (Py_ssize_t i = 0; i < co_extra->ce_size; i++) {
878 co_extra->ce_extras[i] = NULL;
Brett Cannon5c4de282016-09-07 11:16:41 -0700879 }
Brian Colemana6e84932017-03-02 22:21:53 +0000880
881 o->co_extra = co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700882 }
Brett Cannond0600ed2016-09-07 14:30:39 -0700883 else if (co_extra->ce_size <= index) {
Brian Colemana6e84932017-03-02 22:21:53 +0000884 void** ce_extras = PyMem_Realloc(
Brett Cannond0600ed2016-09-07 14:30:39 -0700885 co_extra->ce_extras, tstate->co_extra_user_count * sizeof(void*));
Brett Cannon5c4de282016-09-07 11:16:41 -0700886
Brian Colemana6e84932017-03-02 22:21:53 +0000887 if (ce_extras == NULL) {
Brett Cannon3788b852016-09-07 12:51:08 -0700888 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -0700889 }
890
Brian Colemana6e84932017-03-02 22:21:53 +0000891 for (Py_ssize_t i = co_extra->ce_size;
892 i < tstate->co_extra_user_count;
893 i++) {
894 ce_extras[i] = NULL;
Brett Cannon5c4de282016-09-07 11:16:41 -0700895 }
Brian Colemana6e84932017-03-02 22:21:53 +0000896
897 co_extra->ce_extras = ce_extras;
898 co_extra->ce_size = tstate->co_extra_user_count;
Brett Cannon5c4de282016-09-07 11:16:41 -0700899 }
900
Brett Cannond0600ed2016-09-07 14:30:39 -0700901 co_extra->ce_extras[index] = extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700902 return 0;
903}