blob: 98e504a5a92615798a96425d3e670e1ece9acb51 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001#include "Python.h"
2#include "code.h"
3#include "structmember.h"
4
5#define NAME_CHARS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00007
8/* all_name_chars(s): true iff all chars in s are valid NAME_CHARS */
9
10static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011all_name_chars(PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000012{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000013 static char ok_name_char[256];
14 static unsigned char *name_chars = (unsigned char *)NAME_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015 PyUnicodeObject *u = (PyUnicodeObject *)o;
16 const unsigned char *s;
17
18 if (!PyUnicode_Check(o) || PyUnicode_READY(u) == -1 ||
19 PyUnicode_MAX_CHAR_VALUE(u) >= 128)
20 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000022 if (ok_name_char[*name_chars] == 0) {
23 unsigned char *p;
24 for (p = name_chars; *p; p++)
25 ok_name_char[*p] = 1;
26 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020027 s = PyUnicode_1BYTE_DATA(u);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000028 while (*s) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000029 if (ok_name_char[*s++] == 0)
30 return 0;
31 }
32 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000033}
34
35static void
36intern_strings(PyObject *tuple)
37{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000038 Py_ssize_t i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000040 for (i = PyTuple_GET_SIZE(tuple); --i >= 0; ) {
41 PyObject *v = PyTuple_GET_ITEM(tuple, i);
42 if (v == NULL || !PyUnicode_CheckExact(v)) {
43 Py_FatalError("non-string found in code slot");
44 }
45 PyUnicode_InternInPlace(&PyTuple_GET_ITEM(tuple, i));
46 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000047}
48
49
50PyCodeObject *
Guido van Rossum4f72a782006-10-27 23:31:49 +000051PyCode_New(int argcount, int kwonlyargcount,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000052 int nlocals, int stacksize, int flags,
53 PyObject *code, PyObject *consts, PyObject *names,
54 PyObject *varnames, PyObject *freevars, PyObject *cellvars,
55 PyObject *filename, PyObject *name, int firstlineno,
56 PyObject *lnotab)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000057{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 PyCodeObject *co;
Benjamin Peterson90037602011-06-25 22:54:45 -050059 unsigned char *cell2arg = NULL;
60 Py_ssize_t i, n_cellvars;
Guido van Rossum00bc0e02007-10-15 02:52:41 +000061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000062 /* Check argument types */
63 if (argcount < 0 || kwonlyargcount < 0 || nlocals < 0 ||
64 code == NULL ||
65 consts == NULL || !PyTuple_Check(consts) ||
66 names == NULL || !PyTuple_Check(names) ||
67 varnames == NULL || !PyTuple_Check(varnames) ||
68 freevars == NULL || !PyTuple_Check(freevars) ||
69 cellvars == NULL || !PyTuple_Check(cellvars) ||
70 name == NULL || !PyUnicode_Check(name) ||
71 filename == NULL || !PyUnicode_Check(filename) ||
72 lnotab == NULL || !PyBytes_Check(lnotab) ||
73 !PyObject_CheckReadBuffer(code)) {
74 PyErr_BadInternalCall();
75 return NULL;
76 }
Victor Stinner7c74de42013-10-10 15:55:14 +020077
78 /* Ensure that the filename is a ready Unicode string */
79 if (PyUnicode_READY(filename) < 0)
80 return NULL;
81
Benjamin Peterson90037602011-06-25 22:54:45 -050082 n_cellvars = PyTuple_GET_SIZE(cellvars);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000083 intern_strings(names);
84 intern_strings(varnames);
85 intern_strings(freevars);
86 intern_strings(cellvars);
87 /* Intern selected string constants */
Benjamin Peterson90037602011-06-25 22:54:45 -050088 for (i = PyTuple_GET_SIZE(consts); --i >= 0; ) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000089 PyObject *v = PyTuple_GetItem(consts, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020090 if (!all_name_chars(v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 continue;
92 PyUnicode_InternInPlace(&PyTuple_GET_ITEM(consts, i));
93 }
Benjamin Peterson90037602011-06-25 22:54:45 -050094 /* Create mapping between cells and arguments if needed. */
95 if (n_cellvars) {
96 Py_ssize_t total_args = argcount + kwonlyargcount +
97 ((flags & CO_VARARGS) != 0) + ((flags & CO_VARKEYWORDS) != 0);
98 Py_ssize_t alloc_size = sizeof(unsigned char) * n_cellvars;
99 int used_cell2arg = 0;
100 cell2arg = PyMem_MALLOC(alloc_size);
101 if (cell2arg == NULL)
102 return NULL;
103 memset(cell2arg, CO_CELL_NOT_AN_ARG, alloc_size);
104 /* Find cells which are also arguments. */
105 for (i = 0; i < n_cellvars; i++) {
106 Py_ssize_t j;
107 PyObject *cell = PyTuple_GET_ITEM(cellvars, i);
108 for (j = 0; j < total_args; j++) {
109 PyObject *arg = PyTuple_GET_ITEM(varnames, j);
110 if (!PyUnicode_Compare(cell, arg)) {
111 cell2arg[i] = j;
112 used_cell2arg = 1;
113 break;
114 }
115 }
116 }
117 if (!used_cell2arg) {
118 PyMem_FREE(cell2arg);
119 cell2arg = NULL;
120 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 }
Benjamin Peterson90037602011-06-25 22:54:45 -0500122 co = PyObject_NEW(PyCodeObject, &PyCode_Type);
123 if (co == NULL) {
124 if (cell2arg)
125 PyMem_FREE(cell2arg);
126 return NULL;
127 }
128 co->co_argcount = argcount;
129 co->co_kwonlyargcount = kwonlyargcount;
130 co->co_nlocals = nlocals;
131 co->co_stacksize = stacksize;
132 co->co_flags = flags;
133 Py_INCREF(code);
134 co->co_code = code;
135 Py_INCREF(consts);
136 co->co_consts = consts;
137 Py_INCREF(names);
138 co->co_names = names;
139 Py_INCREF(varnames);
140 co->co_varnames = varnames;
141 Py_INCREF(freevars);
142 co->co_freevars = freevars;
143 Py_INCREF(cellvars);
144 co->co_cellvars = cellvars;
145 co->co_cell2arg = cell2arg;
146 Py_INCREF(filename);
147 co->co_filename = filename;
148 Py_INCREF(name);
149 co->co_name = name;
150 co->co_firstlineno = firstlineno;
151 Py_INCREF(lnotab);
152 co->co_lnotab = lnotab;
153 co->co_zombieframe = NULL;
154 co->co_weakreflist = NULL;
Brett Cannon5c4de282016-09-07 11:16:41 -0700155 co->co_extra = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000157}
158
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000159PyCodeObject *
160PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno)
161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 static PyObject *emptystring = NULL;
163 static PyObject *nulltuple = NULL;
164 PyObject *filename_ob = NULL;
165 PyObject *funcname_ob = NULL;
166 PyCodeObject *result = NULL;
167 if (emptystring == NULL) {
168 emptystring = PyBytes_FromString("");
169 if (emptystring == NULL)
170 goto failed;
171 }
172 if (nulltuple == NULL) {
173 nulltuple = PyTuple_New(0);
174 if (nulltuple == NULL)
175 goto failed;
176 }
177 funcname_ob = PyUnicode_FromString(funcname);
178 if (funcname_ob == NULL)
179 goto failed;
180 filename_ob = PyUnicode_DecodeFSDefault(filename);
181 if (filename_ob == NULL)
182 goto failed;
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 result = PyCode_New(0, /* argcount */
185 0, /* kwonlyargcount */
186 0, /* nlocals */
187 0, /* stacksize */
188 0, /* flags */
189 emptystring, /* code */
190 nulltuple, /* consts */
191 nulltuple, /* names */
192 nulltuple, /* varnames */
193 nulltuple, /* freevars */
194 nulltuple, /* cellvars */
195 filename_ob, /* filename */
196 funcname_ob, /* name */
197 firstlineno, /* firstlineno */
198 emptystring /* lnotab */
199 );
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000200
201failed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 Py_XDECREF(funcname_ob);
203 Py_XDECREF(filename_ob);
204 return result;
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000205}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000206
207#define OFF(x) offsetof(PyCodeObject, x)
208
209static PyMemberDef code_memberlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 {"co_argcount", T_INT, OFF(co_argcount), READONLY},
211 {"co_kwonlyargcount", T_INT, OFF(co_kwonlyargcount), READONLY},
212 {"co_nlocals", T_INT, OFF(co_nlocals), READONLY},
213 {"co_stacksize",T_INT, OFF(co_stacksize), READONLY},
214 {"co_flags", T_INT, OFF(co_flags), READONLY},
215 {"co_code", T_OBJECT, OFF(co_code), READONLY},
216 {"co_consts", T_OBJECT, OFF(co_consts), READONLY},
217 {"co_names", T_OBJECT, OFF(co_names), READONLY},
218 {"co_varnames", T_OBJECT, OFF(co_varnames), READONLY},
219 {"co_freevars", T_OBJECT, OFF(co_freevars), READONLY},
220 {"co_cellvars", T_OBJECT, OFF(co_cellvars), READONLY},
221 {"co_filename", T_OBJECT, OFF(co_filename), READONLY},
222 {"co_name", T_OBJECT, OFF(co_name), READONLY},
223 {"co_firstlineno", T_INT, OFF(co_firstlineno), READONLY},
224 {"co_lnotab", T_OBJECT, OFF(co_lnotab), READONLY},
225 {NULL} /* Sentinel */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000226};
227
228/* Helper for code_new: return a shallow copy of a tuple that is
229 guaranteed to contain exact strings, by converting string subclasses
230 to exact strings and complaining if a non-string is found. */
231static PyObject*
232validate_and_copy_tuple(PyObject *tup)
233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 PyObject *newtuple;
235 PyObject *item;
236 Py_ssize_t i, len;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 len = PyTuple_GET_SIZE(tup);
239 newtuple = PyTuple_New(len);
240 if (newtuple == NULL)
241 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 for (i = 0; i < len; i++) {
244 item = PyTuple_GET_ITEM(tup, i);
245 if (PyUnicode_CheckExact(item)) {
246 Py_INCREF(item);
247 }
248 else if (!PyUnicode_Check(item)) {
249 PyErr_Format(
250 PyExc_TypeError,
251 "name tuples must contain only "
252 "strings, not '%.500s'",
253 item->ob_type->tp_name);
254 Py_DECREF(newtuple);
255 return NULL;
256 }
257 else {
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100258 item = _PyUnicode_Copy(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 if (item == NULL) {
260 Py_DECREF(newtuple);
261 return NULL;
262 }
263 }
264 PyTuple_SET_ITEM(newtuple, i, item);
265 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 return newtuple;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000268}
269
270PyDoc_STRVAR(code_doc,
Georg Brandl8c1a50a2009-07-18 09:07:48 +0000271"code(argcount, kwonlyargcount, nlocals, stacksize, flags, codestring,\n\
Georg Brandla1e7e132008-01-26 09:39:23 +0000272 constants, names, varnames, filename, name, firstlineno,\n\
273 lnotab[, freevars[, cellvars]])\n\
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000274\n\
275Create a code object. Not for the faint of heart.");
276
277static PyObject *
278code_new(PyTypeObject *type, PyObject *args, PyObject *kw)
279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 int argcount;
281 int kwonlyargcount;
282 int nlocals;
283 int stacksize;
284 int flags;
285 PyObject *co = NULL;
286 PyObject *code;
287 PyObject *consts;
288 PyObject *names, *ournames = NULL;
289 PyObject *varnames, *ourvarnames = NULL;
290 PyObject *freevars = NULL, *ourfreevars = NULL;
291 PyObject *cellvars = NULL, *ourcellvars = NULL;
292 PyObject *filename;
293 PyObject *name;
294 int firstlineno;
295 PyObject *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 if (!PyArg_ParseTuple(args, "iiiiiSO!O!O!UUiS|O!O!:code",
298 &argcount, &kwonlyargcount,
299 &nlocals, &stacksize, &flags,
300 &code,
301 &PyTuple_Type, &consts,
302 &PyTuple_Type, &names,
303 &PyTuple_Type, &varnames,
304 &filename, &name,
305 &firstlineno, &lnotab,
306 &PyTuple_Type, &freevars,
307 &PyTuple_Type, &cellvars))
308 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 if (argcount < 0) {
311 PyErr_SetString(
312 PyExc_ValueError,
313 "code: argcount must not be negative");
314 goto cleanup;
315 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 if (kwonlyargcount < 0) {
318 PyErr_SetString(
319 PyExc_ValueError,
320 "code: kwonlyargcount must not be negative");
321 goto cleanup;
322 }
323 if (nlocals < 0) {
324 PyErr_SetString(
325 PyExc_ValueError,
326 "code: nlocals must not be negative");
327 goto cleanup;
328 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 ournames = validate_and_copy_tuple(names);
331 if (ournames == NULL)
332 goto cleanup;
333 ourvarnames = validate_and_copy_tuple(varnames);
334 if (ourvarnames == NULL)
335 goto cleanup;
336 if (freevars)
337 ourfreevars = validate_and_copy_tuple(freevars);
338 else
339 ourfreevars = PyTuple_New(0);
340 if (ourfreevars == NULL)
341 goto cleanup;
342 if (cellvars)
343 ourcellvars = validate_and_copy_tuple(cellvars);
344 else
345 ourcellvars = PyTuple_New(0);
346 if (ourcellvars == NULL)
347 goto cleanup;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 co = (PyObject *)PyCode_New(argcount, kwonlyargcount,
350 nlocals, stacksize, flags,
351 code, consts, ournames, ourvarnames,
352 ourfreevars, ourcellvars, filename,
353 name, firstlineno, lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000354 cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 Py_XDECREF(ournames);
356 Py_XDECREF(ourvarnames);
357 Py_XDECREF(ourfreevars);
358 Py_XDECREF(ourcellvars);
359 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000360}
361
362static void
363code_dealloc(PyCodeObject *co)
364{
Brett Cannon5c4de282016-09-07 11:16:41 -0700365 if (co->co_extra != NULL) {
366 PyThreadState *tstate = PyThreadState_Get();
367
368 for (Py_ssize_t i = 0; i < co->co_extra->ce_size; i++) {
369 freefunc free_extra = tstate->co_extra_freefuncs[i];
370
371 if (free_extra != NULL) {
372 free_extra(co->co_extra->ce_extras[i]);
373 }
374 }
375
376 PyMem_FREE(co->co_extra);
377 }
378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 Py_XDECREF(co->co_code);
380 Py_XDECREF(co->co_consts);
381 Py_XDECREF(co->co_names);
382 Py_XDECREF(co->co_varnames);
383 Py_XDECREF(co->co_freevars);
384 Py_XDECREF(co->co_cellvars);
385 Py_XDECREF(co->co_filename);
386 Py_XDECREF(co->co_name);
387 Py_XDECREF(co->co_lnotab);
Benjamin Peterson90037602011-06-25 22:54:45 -0500388 if (co->co_cell2arg != NULL)
389 PyMem_FREE(co->co_cell2arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 if (co->co_zombieframe != NULL)
391 PyObject_GC_Del(co->co_zombieframe);
392 if (co->co_weakreflist != NULL)
393 PyObject_ClearWeakRefs((PyObject*)co);
394 PyObject_DEL(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000395}
396
397static PyObject *
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200398code_sizeof(PyCodeObject *co, void *unused)
399{
400 Py_ssize_t res;
401
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +0200402 res = _PyObject_SIZE(Py_TYPE(co));
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200403 if (co->co_cell2arg != NULL && co->co_cellvars != NULL)
404 res += PyTuple_GET_SIZE(co->co_cellvars) * sizeof(unsigned char);
405 return PyLong_FromSsize_t(res);
406}
407
408static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000409code_repr(PyCodeObject *co)
410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 int lineno;
412 if (co->co_firstlineno != 0)
413 lineno = co->co_firstlineno;
414 else
415 lineno = -1;
416 if (co->co_filename && PyUnicode_Check(co->co_filename)) {
417 return PyUnicode_FromFormat(
Victor Stinneraaa4e9a2011-01-05 03:33:26 +0000418 "<code object %U at %p, file \"%U\", line %d>",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 co->co_name, co, co->co_filename, lineno);
420 } else {
421 return PyUnicode_FromFormat(
Victor Stinneraaa4e9a2011-01-05 03:33:26 +0000422 "<code object %U at %p, file ???, line %d>",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 co->co_name, co, lineno);
424 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000425}
426
Victor Stinnerefb24132016-01-22 12:33:12 +0100427PyObject*
428_PyCode_ConstantKey(PyObject *op)
429{
430 PyObject *key;
431
432 /* Py_None and Py_Ellipsis are singleton */
433 if (op == Py_None || op == Py_Ellipsis
434 || PyLong_CheckExact(op)
435 || PyBool_Check(op)
436 || PyBytes_CheckExact(op)
437 || PyUnicode_CheckExact(op)
438 /* code_richcompare() uses _PyCode_ConstantKey() internally */
439 || PyCode_Check(op)) {
440 key = PyTuple_Pack(2, Py_TYPE(op), op);
441 }
442 else if (PyFloat_CheckExact(op)) {
443 double d = PyFloat_AS_DOUBLE(op);
444 /* all we need is to make the tuple different in either the 0.0
445 * or -0.0 case from all others, just to avoid the "coercion".
446 */
447 if (d == 0.0 && copysign(1.0, d) < 0.0)
448 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
449 else
450 key = PyTuple_Pack(2, Py_TYPE(op), op);
451 }
452 else if (PyComplex_CheckExact(op)) {
453 Py_complex z;
454 int real_negzero, imag_negzero;
455 /* For the complex case we must make complex(x, 0.)
456 different from complex(x, -0.) and complex(0., y)
457 different from complex(-0., y), for any x and y.
458 All four complex zeros must be distinguished.*/
459 z = PyComplex_AsCComplex(op);
460 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
461 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
462 /* use True, False and None singleton as tags for the real and imag
463 * sign, to make tuples different */
464 if (real_negzero && imag_negzero) {
465 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_True);
466 }
467 else if (imag_negzero) {
468 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_False);
469 }
470 else if (real_negzero) {
471 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
472 }
473 else {
474 key = PyTuple_Pack(2, Py_TYPE(op), op);
475 }
476 }
477 else if (PyTuple_CheckExact(op)) {
478 Py_ssize_t i, len;
479 PyObject *tuple;
480
481 len = PyTuple_GET_SIZE(op);
482 tuple = PyTuple_New(len);
483 if (tuple == NULL)
484 return NULL;
485
486 for (i=0; i < len; i++) {
487 PyObject *item, *item_key;
488
489 item = PyTuple_GET_ITEM(op, i);
490 item_key = _PyCode_ConstantKey(item);
491 if (item_key == NULL) {
492 Py_DECREF(tuple);
493 return NULL;
494 }
495
496 PyTuple_SET_ITEM(tuple, i, item_key);
497 }
498
499 key = PyTuple_Pack(3, Py_TYPE(op), op, tuple);
500 Py_DECREF(tuple);
501 }
502 else if (PyFrozenSet_CheckExact(op)) {
503 Py_ssize_t pos = 0;
504 PyObject *item;
505 Py_hash_t hash;
506 Py_ssize_t i, len;
507 PyObject *tuple, *set;
508
509 len = PySet_GET_SIZE(op);
510 tuple = PyTuple_New(len);
511 if (tuple == NULL)
512 return NULL;
513
514 i = 0;
515 while (_PySet_NextEntry(op, &pos, &item, &hash)) {
516 PyObject *item_key;
517
518 item_key = _PyCode_ConstantKey(item);
519 if (item_key == NULL) {
520 Py_DECREF(tuple);
521 return NULL;
522 }
523
524 assert(i < len);
525 PyTuple_SET_ITEM(tuple, i, item_key);
526 i++;
527 }
528 set = PyFrozenSet_New(tuple);
529 Py_DECREF(tuple);
530 if (set == NULL)
531 return NULL;
532
533 key = PyTuple_Pack(3, Py_TYPE(op), op, set);
534 Py_DECREF(set);
535 return key;
536 }
537 else {
Martin Panter6245cb32016-04-15 02:14:19 +0000538 /* for other types, use the object identifier as a unique identifier
Victor Stinnerefb24132016-01-22 12:33:12 +0100539 * to ensure that they are seen as unequal. */
540 PyObject *obj_id = PyLong_FromVoidPtr(op);
541 if (obj_id == NULL)
542 return NULL;
543
544 key = PyTuple_Pack(3, Py_TYPE(op), op, obj_id);
545 Py_DECREF(obj_id);
546 }
547 return key;
548}
549
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000550static PyObject *
551code_richcompare(PyObject *self, PyObject *other, int op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 PyCodeObject *co, *cp;
554 int eq;
Victor Stinnerefb24132016-01-22 12:33:12 +0100555 PyObject *consts1, *consts2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 if ((op != Py_EQ && op != Py_NE) ||
559 !PyCode_Check(self) ||
560 !PyCode_Check(other)) {
Brian Curtindfc80e32011-08-10 20:28:54 -0500561 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 co = (PyCodeObject *)self;
565 cp = (PyCodeObject *)other;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 eq = PyObject_RichCompareBool(co->co_name, cp->co_name, Py_EQ);
568 if (eq <= 0) goto unequal;
569 eq = co->co_argcount == cp->co_argcount;
570 if (!eq) goto unequal;
571 eq = co->co_kwonlyargcount == cp->co_kwonlyargcount;
572 if (!eq) goto unequal;
573 eq = co->co_nlocals == cp->co_nlocals;
574 if (!eq) goto unequal;
575 eq = co->co_flags == cp->co_flags;
576 if (!eq) goto unequal;
577 eq = co->co_firstlineno == cp->co_firstlineno;
578 if (!eq) goto unequal;
579 eq = PyObject_RichCompareBool(co->co_code, cp->co_code, Py_EQ);
580 if (eq <= 0) goto unequal;
Victor Stinnerefb24132016-01-22 12:33:12 +0100581
582 /* compare constants */
583 consts1 = _PyCode_ConstantKey(co->co_consts);
584 if (!consts1)
585 return NULL;
586 consts2 = _PyCode_ConstantKey(cp->co_consts);
587 if (!consts2) {
588 Py_DECREF(consts1);
589 return NULL;
590 }
591 eq = PyObject_RichCompareBool(consts1, consts2, Py_EQ);
592 Py_DECREF(consts1);
593 Py_DECREF(consts2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 if (eq <= 0) goto unequal;
Victor Stinnerefb24132016-01-22 12:33:12 +0100595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 eq = PyObject_RichCompareBool(co->co_names, cp->co_names, Py_EQ);
597 if (eq <= 0) goto unequal;
598 eq = PyObject_RichCompareBool(co->co_varnames, cp->co_varnames, Py_EQ);
599 if (eq <= 0) goto unequal;
600 eq = PyObject_RichCompareBool(co->co_freevars, cp->co_freevars, Py_EQ);
601 if (eq <= 0) goto unequal;
602 eq = PyObject_RichCompareBool(co->co_cellvars, cp->co_cellvars, Py_EQ);
603 if (eq <= 0) goto unequal;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 if (op == Py_EQ)
606 res = Py_True;
607 else
608 res = Py_False;
609 goto done;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000610
611 unequal:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 if (eq < 0)
613 return NULL;
614 if (op == Py_NE)
615 res = Py_True;
616 else
617 res = Py_False;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000618
619 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 Py_INCREF(res);
621 return res;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000622}
623
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000624static Py_hash_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000625code_hash(PyCodeObject *co)
626{
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000627 Py_hash_t h, h0, h1, h2, h3, h4, h5, h6;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 h0 = PyObject_Hash(co->co_name);
629 if (h0 == -1) return -1;
630 h1 = PyObject_Hash(co->co_code);
631 if (h1 == -1) return -1;
632 h2 = PyObject_Hash(co->co_consts);
633 if (h2 == -1) return -1;
634 h3 = PyObject_Hash(co->co_names);
635 if (h3 == -1) return -1;
636 h4 = PyObject_Hash(co->co_varnames);
637 if (h4 == -1) return -1;
638 h5 = PyObject_Hash(co->co_freevars);
639 if (h5 == -1) return -1;
640 h6 = PyObject_Hash(co->co_cellvars);
641 if (h6 == -1) return -1;
642 h = h0 ^ h1 ^ h2 ^ h3 ^ h4 ^ h5 ^ h6 ^
643 co->co_argcount ^ co->co_kwonlyargcount ^
644 co->co_nlocals ^ co->co_flags;
645 if (h == -1) h = -2;
646 return h;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000647}
648
649/* XXX code objects need to participate in GC? */
650
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200651static struct PyMethodDef code_methods[] = {
652 {"__sizeof__", (PyCFunction)code_sizeof, METH_NOARGS},
653 {NULL, NULL} /* sentinel */
654};
655
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000656PyTypeObject PyCode_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 PyVarObject_HEAD_INIT(&PyType_Type, 0)
658 "code",
659 sizeof(PyCodeObject),
660 0,
661 (destructor)code_dealloc, /* tp_dealloc */
662 0, /* tp_print */
663 0, /* tp_getattr */
664 0, /* tp_setattr */
665 0, /* tp_reserved */
666 (reprfunc)code_repr, /* tp_repr */
667 0, /* tp_as_number */
668 0, /* tp_as_sequence */
669 0, /* tp_as_mapping */
670 (hashfunc)code_hash, /* tp_hash */
671 0, /* tp_call */
672 0, /* tp_str */
673 PyObject_GenericGetAttr, /* tp_getattro */
674 0, /* tp_setattro */
675 0, /* tp_as_buffer */
676 Py_TPFLAGS_DEFAULT, /* tp_flags */
677 code_doc, /* tp_doc */
678 0, /* tp_traverse */
679 0, /* tp_clear */
680 code_richcompare, /* tp_richcompare */
681 offsetof(PyCodeObject, co_weakreflist), /* tp_weaklistoffset */
682 0, /* tp_iter */
683 0, /* tp_iternext */
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200684 code_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 code_memberlist, /* tp_members */
686 0, /* tp_getset */
687 0, /* tp_base */
688 0, /* tp_dict */
689 0, /* tp_descr_get */
690 0, /* tp_descr_set */
691 0, /* tp_dictoffset */
692 0, /* tp_init */
693 0, /* tp_alloc */
694 code_new, /* tp_new */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000695};
696
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000697/* Use co_lnotab to compute the line number from a bytecode index, addrq. See
698 lnotab_notes.txt for the details of the lnotab representation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000699*/
700
701int
702PyCode_Addr2Line(PyCodeObject *co, int addrq)
703{
Victor Stinner0fcab4a2011-01-04 12:59:15 +0000704 Py_ssize_t size = PyBytes_Size(co->co_lnotab) / 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 unsigned char *p = (unsigned char*)PyBytes_AsString(co->co_lnotab);
706 int line = co->co_firstlineno;
707 int addr = 0;
708 while (--size >= 0) {
709 addr += *p++;
710 if (addr > addrq)
711 break;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100712 line += (signed char)*p;
713 p++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 }
715 return line;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000716}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000717
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000718/* Update *bounds to describe the first and one-past-the-last instructions in
719 the same line as lasti. Return the number of that line. */
720int
721_PyCode_CheckLineNumber(PyCodeObject* co, int lasti, PyAddrPair *bounds)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000722{
Victor Stinner0fcab4a2011-01-04 12:59:15 +0000723 Py_ssize_t size;
724 int addr, line;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 unsigned char* p;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 p = (unsigned char*)PyBytes_AS_STRING(co->co_lnotab);
728 size = PyBytes_GET_SIZE(co->co_lnotab) / 2;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 addr = 0;
731 line = co->co_firstlineno;
732 assert(line > 0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 /* possible optimization: if f->f_lasti == instr_ub
735 (likely to be a common case) then we already know
736 instr_lb -- if we stored the matching value of p
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700737 somewhere we could skip the first while loop. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 /* See lnotab_notes.txt for the description of
740 co_lnotab. A point to remember: increments to p
741 come in (addr, line) pairs. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 bounds->ap_lower = 0;
744 while (size > 0) {
745 if (addr + *p > lasti)
746 break;
747 addr += *p++;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100748 if ((signed char)*p)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 bounds->ap_lower = addr;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100750 line += (signed char)*p;
751 p++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 --size;
753 }
754
755 if (size > 0) {
756 while (--size >= 0) {
757 addr += *p++;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100758 if ((signed char)*p)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 break;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100760 p++;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000761 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 bounds->ap_upper = addr;
763 }
764 else {
765 bounds->ap_upper = INT_MAX;
766 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 return line;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000769}
Brett Cannon5c4de282016-09-07 11:16:41 -0700770
771
772int
773_PyCode_GetExtra(PyObject *code, Py_ssize_t index, void **extra)
774{
775 PyCodeObject *o;
776
777 assert(*extra == NULL);
778
779 if (!PyCode_Check(code)) {
780 PyErr_BadInternalCall();
781 return 1;
782 }
783
784 o = (PyCodeObject*) code;
785
786 if (o->co_extra == NULL || o->co_extra->ce_size <= index) {
787 return 0;
788 }
789
790 *extra = o->co_extra->ce_extras[index];
791 return 0;
792}
793
794
795int
796_PyCode_SetExtra(PyObject *code, Py_ssize_t index, void *extra)
797{
798 PyCodeObject *o;
799 PyThreadState *tstate = PyThreadState_Get();
800
801 if (!PyCode_Check(code) || index < 0 ||
802 index >= tstate->co_extra_user_count) {
803 PyErr_BadInternalCall();
804 return 1;
805 }
806
807 o = (PyCodeObject*) code;
808
809 if (o->co_extra == NULL) {
810 o->co_extra = (_PyCodeObjectExtra*) PyMem_Malloc(
811 sizeof(_PyCodeObjectExtra));
812 if (o->co_extra == NULL) {
813 return 1;
814 }
815
816 o->co_extra->ce_extras = PyMem_Malloc(
817 tstate->co_extra_user_count * sizeof(void*));
818 if (o->co_extra->ce_extras == NULL) {
819 return 1;
820 }
821
822 o->co_extra->ce_size = tstate->co_extra_user_count;
823
824 for (Py_ssize_t i = 0; i < o->co_extra->ce_size; i++) {
825 o->co_extra->ce_extras[i] = NULL;
826 }
827 }
828 else if (o->co_extra->ce_size <= index) {
829 o->co_extra->ce_extras = PyMem_Realloc(
830 o->co_extra->ce_extras, tstate->co_extra_user_count * sizeof(void*));
831
832 if (o->co_extra->ce_extras == NULL) {
833 return 1;
834 }
835
836 o->co_extra->ce_size = tstate->co_extra_user_count;
837
838 for (Py_ssize_t i = o->co_extra->ce_size; i < o->co_extra->ce_size; i++) {
839 o->co_extra->ce_extras[i] = NULL;
840 }
841 }
842
843 o->co_extra->ce_extras[index] = extra;
844 return 0;
845}