blob: b6e5bd3e1e58b57f74e3b9e2c4ade098073f5c75 [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)) {
80 PyObject *tmp = PySequence_Tuple(v);
81 if (tmp == NULL) {
82 PyErr_Clear();
83 continue;
84 }
85 if (intern_string_constants(tmp)) {
86 v = PyFrozenSet_New(tmp);
87 if (v == NULL) {
88 PyErr_Clear();
89 }
90 else {
91 PyTuple_SET_ITEM(tuple, i, v);
92 modified = 1;
93 }
94 }
95 Py_DECREF(tmp);
96 }
97 }
98 return modified;
99}
100
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000101
102PyCodeObject *
Guido van Rossum4f72a782006-10-27 23:31:49 +0000103PyCode_New(int argcount, int kwonlyargcount,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 int nlocals, int stacksize, int flags,
105 PyObject *code, PyObject *consts, PyObject *names,
106 PyObject *varnames, PyObject *freevars, PyObject *cellvars,
107 PyObject *filename, PyObject *name, int firstlineno,
108 PyObject *lnotab)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 PyCodeObject *co;
Benjamin Peterson90037602011-06-25 22:54:45 -0500111 unsigned char *cell2arg = NULL;
112 Py_ssize_t i, n_cellvars;
Guido van Rossum00bc0e02007-10-15 02:52:41 +0000113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 /* Check argument types */
115 if (argcount < 0 || kwonlyargcount < 0 || nlocals < 0 ||
116 code == NULL ||
117 consts == NULL || !PyTuple_Check(consts) ||
118 names == NULL || !PyTuple_Check(names) ||
119 varnames == NULL || !PyTuple_Check(varnames) ||
120 freevars == NULL || !PyTuple_Check(freevars) ||
121 cellvars == NULL || !PyTuple_Check(cellvars) ||
122 name == NULL || !PyUnicode_Check(name) ||
123 filename == NULL || !PyUnicode_Check(filename) ||
124 lnotab == NULL || !PyBytes_Check(lnotab) ||
125 !PyObject_CheckReadBuffer(code)) {
126 PyErr_BadInternalCall();
127 return NULL;
128 }
Victor Stinner7c74de42013-10-10 15:55:14 +0200129
130 /* Ensure that the filename is a ready Unicode string */
131 if (PyUnicode_READY(filename) < 0)
132 return NULL;
133
Benjamin Peterson90037602011-06-25 22:54:45 -0500134 n_cellvars = PyTuple_GET_SIZE(cellvars);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 intern_strings(names);
136 intern_strings(varnames);
137 intern_strings(freevars);
138 intern_strings(cellvars);
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +0300139 intern_string_constants(consts);
Benjamin Peterson90037602011-06-25 22:54:45 -0500140 /* Create mapping between cells and arguments if needed. */
141 if (n_cellvars) {
142 Py_ssize_t total_args = argcount + kwonlyargcount +
143 ((flags & CO_VARARGS) != 0) + ((flags & CO_VARKEYWORDS) != 0);
144 Py_ssize_t alloc_size = sizeof(unsigned char) * n_cellvars;
Benjamin Peterson1bf494b2016-09-07 11:28:35 -0700145 bool used_cell2arg = false;
Benjamin Peterson90037602011-06-25 22:54:45 -0500146 cell2arg = PyMem_MALLOC(alloc_size);
147 if (cell2arg == NULL)
148 return NULL;
149 memset(cell2arg, CO_CELL_NOT_AN_ARG, alloc_size);
150 /* Find cells which are also arguments. */
151 for (i = 0; i < n_cellvars; i++) {
152 Py_ssize_t j;
153 PyObject *cell = PyTuple_GET_ITEM(cellvars, i);
154 for (j = 0; j < total_args; j++) {
155 PyObject *arg = PyTuple_GET_ITEM(varnames, j);
156 if (!PyUnicode_Compare(cell, arg)) {
157 cell2arg[i] = j;
Benjamin Peterson1bf494b2016-09-07 11:28:35 -0700158 used_cell2arg = true;
Benjamin Peterson90037602011-06-25 22:54:45 -0500159 break;
160 }
161 }
162 }
163 if (!used_cell2arg) {
164 PyMem_FREE(cell2arg);
165 cell2arg = NULL;
166 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 }
Benjamin Peterson90037602011-06-25 22:54:45 -0500168 co = PyObject_NEW(PyCodeObject, &PyCode_Type);
169 if (co == NULL) {
170 if (cell2arg)
171 PyMem_FREE(cell2arg);
172 return NULL;
173 }
174 co->co_argcount = argcount;
175 co->co_kwonlyargcount = kwonlyargcount;
176 co->co_nlocals = nlocals;
177 co->co_stacksize = stacksize;
178 co->co_flags = flags;
179 Py_INCREF(code);
180 co->co_code = code;
181 Py_INCREF(consts);
182 co->co_consts = consts;
183 Py_INCREF(names);
184 co->co_names = names;
185 Py_INCREF(varnames);
186 co->co_varnames = varnames;
187 Py_INCREF(freevars);
188 co->co_freevars = freevars;
189 Py_INCREF(cellvars);
190 co->co_cellvars = cellvars;
191 co->co_cell2arg = cell2arg;
192 Py_INCREF(filename);
193 co->co_filename = filename;
194 Py_INCREF(name);
195 co->co_name = name;
196 co->co_firstlineno = firstlineno;
197 Py_INCREF(lnotab);
198 co->co_lnotab = lnotab;
199 co->co_zombieframe = NULL;
200 co->co_weakreflist = NULL;
Brett Cannon5c4de282016-09-07 11:16:41 -0700201 co->co_extra = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000203}
204
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000205PyCodeObject *
206PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno)
207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 static PyObject *emptystring = NULL;
209 static PyObject *nulltuple = NULL;
210 PyObject *filename_ob = NULL;
211 PyObject *funcname_ob = NULL;
212 PyCodeObject *result = NULL;
213 if (emptystring == NULL) {
214 emptystring = PyBytes_FromString("");
215 if (emptystring == NULL)
216 goto failed;
217 }
218 if (nulltuple == NULL) {
219 nulltuple = PyTuple_New(0);
220 if (nulltuple == NULL)
221 goto failed;
222 }
223 funcname_ob = PyUnicode_FromString(funcname);
224 if (funcname_ob == NULL)
225 goto failed;
226 filename_ob = PyUnicode_DecodeFSDefault(filename);
227 if (filename_ob == NULL)
228 goto failed;
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 result = PyCode_New(0, /* argcount */
231 0, /* kwonlyargcount */
232 0, /* nlocals */
233 0, /* stacksize */
234 0, /* flags */
235 emptystring, /* code */
236 nulltuple, /* consts */
237 nulltuple, /* names */
238 nulltuple, /* varnames */
239 nulltuple, /* freevars */
240 nulltuple, /* cellvars */
241 filename_ob, /* filename */
242 funcname_ob, /* name */
243 firstlineno, /* firstlineno */
244 emptystring /* lnotab */
245 );
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000246
247failed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 Py_XDECREF(funcname_ob);
249 Py_XDECREF(filename_ob);
250 return result;
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000251}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000252
253#define OFF(x) offsetof(PyCodeObject, x)
254
255static PyMemberDef code_memberlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 {"co_argcount", T_INT, OFF(co_argcount), READONLY},
257 {"co_kwonlyargcount", T_INT, OFF(co_kwonlyargcount), READONLY},
258 {"co_nlocals", T_INT, OFF(co_nlocals), READONLY},
259 {"co_stacksize",T_INT, OFF(co_stacksize), READONLY},
260 {"co_flags", T_INT, OFF(co_flags), READONLY},
261 {"co_code", T_OBJECT, OFF(co_code), READONLY},
262 {"co_consts", T_OBJECT, OFF(co_consts), READONLY},
263 {"co_names", T_OBJECT, OFF(co_names), READONLY},
264 {"co_varnames", T_OBJECT, OFF(co_varnames), READONLY},
265 {"co_freevars", T_OBJECT, OFF(co_freevars), READONLY},
266 {"co_cellvars", T_OBJECT, OFF(co_cellvars), READONLY},
267 {"co_filename", T_OBJECT, OFF(co_filename), READONLY},
268 {"co_name", T_OBJECT, OFF(co_name), READONLY},
269 {"co_firstlineno", T_INT, OFF(co_firstlineno), READONLY},
270 {"co_lnotab", T_OBJECT, OFF(co_lnotab), READONLY},
271 {NULL} /* Sentinel */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000272};
273
274/* Helper for code_new: return a shallow copy of a tuple that is
275 guaranteed to contain exact strings, by converting string subclasses
276 to exact strings and complaining if a non-string is found. */
277static PyObject*
278validate_and_copy_tuple(PyObject *tup)
279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 PyObject *newtuple;
281 PyObject *item;
282 Py_ssize_t i, len;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 len = PyTuple_GET_SIZE(tup);
285 newtuple = PyTuple_New(len);
286 if (newtuple == NULL)
287 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 for (i = 0; i < len; i++) {
290 item = PyTuple_GET_ITEM(tup, i);
291 if (PyUnicode_CheckExact(item)) {
292 Py_INCREF(item);
293 }
294 else if (!PyUnicode_Check(item)) {
295 PyErr_Format(
296 PyExc_TypeError,
297 "name tuples must contain only "
298 "strings, not '%.500s'",
299 item->ob_type->tp_name);
300 Py_DECREF(newtuple);
301 return NULL;
302 }
303 else {
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100304 item = _PyUnicode_Copy(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 if (item == NULL) {
306 Py_DECREF(newtuple);
307 return NULL;
308 }
309 }
310 PyTuple_SET_ITEM(newtuple, i, item);
311 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 return newtuple;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000314}
315
316PyDoc_STRVAR(code_doc,
Georg Brandl8c1a50a2009-07-18 09:07:48 +0000317"code(argcount, kwonlyargcount, nlocals, stacksize, flags, codestring,\n\
Georg Brandla1e7e132008-01-26 09:39:23 +0000318 constants, names, varnames, filename, name, firstlineno,\n\
319 lnotab[, freevars[, cellvars]])\n\
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000320\n\
321Create a code object. Not for the faint of heart.");
322
323static PyObject *
324code_new(PyTypeObject *type, PyObject *args, PyObject *kw)
325{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 int argcount;
327 int kwonlyargcount;
328 int nlocals;
329 int stacksize;
330 int flags;
331 PyObject *co = NULL;
332 PyObject *code;
333 PyObject *consts;
334 PyObject *names, *ournames = NULL;
335 PyObject *varnames, *ourvarnames = NULL;
336 PyObject *freevars = NULL, *ourfreevars = NULL;
337 PyObject *cellvars = NULL, *ourcellvars = NULL;
338 PyObject *filename;
339 PyObject *name;
340 int firstlineno;
341 PyObject *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 if (!PyArg_ParseTuple(args, "iiiiiSO!O!O!UUiS|O!O!:code",
344 &argcount, &kwonlyargcount,
345 &nlocals, &stacksize, &flags,
346 &code,
347 &PyTuple_Type, &consts,
348 &PyTuple_Type, &names,
349 &PyTuple_Type, &varnames,
350 &filename, &name,
351 &firstlineno, &lnotab,
352 &PyTuple_Type, &freevars,
353 &PyTuple_Type, &cellvars))
354 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 if (argcount < 0) {
357 PyErr_SetString(
358 PyExc_ValueError,
359 "code: argcount must not be negative");
360 goto cleanup;
361 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 if (kwonlyargcount < 0) {
364 PyErr_SetString(
365 PyExc_ValueError,
366 "code: kwonlyargcount must not be negative");
367 goto cleanup;
368 }
369 if (nlocals < 0) {
370 PyErr_SetString(
371 PyExc_ValueError,
372 "code: nlocals must not be negative");
373 goto cleanup;
374 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 ournames = validate_and_copy_tuple(names);
377 if (ournames == NULL)
378 goto cleanup;
379 ourvarnames = validate_and_copy_tuple(varnames);
380 if (ourvarnames == NULL)
381 goto cleanup;
382 if (freevars)
383 ourfreevars = validate_and_copy_tuple(freevars);
384 else
385 ourfreevars = PyTuple_New(0);
386 if (ourfreevars == NULL)
387 goto cleanup;
388 if (cellvars)
389 ourcellvars = validate_and_copy_tuple(cellvars);
390 else
391 ourcellvars = PyTuple_New(0);
392 if (ourcellvars == NULL)
393 goto cleanup;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 co = (PyObject *)PyCode_New(argcount, kwonlyargcount,
396 nlocals, stacksize, flags,
397 code, consts, ournames, ourvarnames,
398 ourfreevars, ourcellvars, filename,
399 name, firstlineno, lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000400 cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 Py_XDECREF(ournames);
402 Py_XDECREF(ourvarnames);
403 Py_XDECREF(ourfreevars);
404 Py_XDECREF(ourcellvars);
405 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000406}
407
408static void
409code_dealloc(PyCodeObject *co)
410{
Brett Cannon5c4de282016-09-07 11:16:41 -0700411 if (co->co_extra != NULL) {
412 PyThreadState *tstate = PyThreadState_Get();
Brett Cannond0600ed2016-09-07 14:30:39 -0700413 _PyCodeObjectExtra *co_extra = co->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700414
Brett Cannond0600ed2016-09-07 14:30:39 -0700415 for (Py_ssize_t i = 0; i < co_extra->ce_size; i++) {
Brett Cannon5c4de282016-09-07 11:16:41 -0700416 freefunc free_extra = tstate->co_extra_freefuncs[i];
417
418 if (free_extra != NULL) {
Brett Cannond0600ed2016-09-07 14:30:39 -0700419 free_extra(co_extra->ce_extras[i]);
Brett Cannon5c4de282016-09-07 11:16:41 -0700420 }
421 }
422
423 PyMem_FREE(co->co_extra);
424 }
425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 Py_XDECREF(co->co_code);
427 Py_XDECREF(co->co_consts);
428 Py_XDECREF(co->co_names);
429 Py_XDECREF(co->co_varnames);
430 Py_XDECREF(co->co_freevars);
431 Py_XDECREF(co->co_cellvars);
432 Py_XDECREF(co->co_filename);
433 Py_XDECREF(co->co_name);
434 Py_XDECREF(co->co_lnotab);
Benjamin Peterson90037602011-06-25 22:54:45 -0500435 if (co->co_cell2arg != NULL)
436 PyMem_FREE(co->co_cell2arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 if (co->co_zombieframe != NULL)
438 PyObject_GC_Del(co->co_zombieframe);
439 if (co->co_weakreflist != NULL)
440 PyObject_ClearWeakRefs((PyObject*)co);
441 PyObject_DEL(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000442}
443
444static PyObject *
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200445code_sizeof(PyCodeObject *co, void *unused)
446{
447 Py_ssize_t res;
448
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +0200449 res = _PyObject_SIZE(Py_TYPE(co));
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200450 if (co->co_cell2arg != NULL && co->co_cellvars != NULL)
451 res += PyTuple_GET_SIZE(co->co_cellvars) * sizeof(unsigned char);
452 return PyLong_FromSsize_t(res);
453}
454
455static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000456code_repr(PyCodeObject *co)
457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 int lineno;
459 if (co->co_firstlineno != 0)
460 lineno = co->co_firstlineno;
461 else
462 lineno = -1;
463 if (co->co_filename && PyUnicode_Check(co->co_filename)) {
464 return PyUnicode_FromFormat(
Victor Stinneraaa4e9a2011-01-05 03:33:26 +0000465 "<code object %U at %p, file \"%U\", line %d>",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 co->co_name, co, co->co_filename, lineno);
467 } else {
468 return PyUnicode_FromFormat(
Victor Stinneraaa4e9a2011-01-05 03:33:26 +0000469 "<code object %U at %p, file ???, line %d>",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 co->co_name, co, lineno);
471 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000472}
473
Victor Stinnerefb24132016-01-22 12:33:12 +0100474PyObject*
475_PyCode_ConstantKey(PyObject *op)
476{
477 PyObject *key;
478
479 /* Py_None and Py_Ellipsis are singleton */
480 if (op == Py_None || op == Py_Ellipsis
481 || PyLong_CheckExact(op)
482 || PyBool_Check(op)
483 || PyBytes_CheckExact(op)
484 || PyUnicode_CheckExact(op)
485 /* code_richcompare() uses _PyCode_ConstantKey() internally */
486 || PyCode_Check(op)) {
487 key = PyTuple_Pack(2, Py_TYPE(op), op);
488 }
489 else if (PyFloat_CheckExact(op)) {
490 double d = PyFloat_AS_DOUBLE(op);
491 /* all we need is to make the tuple different in either the 0.0
492 * or -0.0 case from all others, just to avoid the "coercion".
493 */
494 if (d == 0.0 && copysign(1.0, d) < 0.0)
495 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
496 else
497 key = PyTuple_Pack(2, Py_TYPE(op), op);
498 }
499 else if (PyComplex_CheckExact(op)) {
500 Py_complex z;
501 int real_negzero, imag_negzero;
502 /* For the complex case we must make complex(x, 0.)
503 different from complex(x, -0.) and complex(0., y)
504 different from complex(-0., y), for any x and y.
505 All four complex zeros must be distinguished.*/
506 z = PyComplex_AsCComplex(op);
507 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
508 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
509 /* use True, False and None singleton as tags for the real and imag
510 * sign, to make tuples different */
511 if (real_negzero && imag_negzero) {
512 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_True);
513 }
514 else if (imag_negzero) {
515 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_False);
516 }
517 else if (real_negzero) {
518 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
519 }
520 else {
521 key = PyTuple_Pack(2, Py_TYPE(op), op);
522 }
523 }
524 else if (PyTuple_CheckExact(op)) {
525 Py_ssize_t i, len;
526 PyObject *tuple;
527
528 len = PyTuple_GET_SIZE(op);
529 tuple = PyTuple_New(len);
530 if (tuple == NULL)
531 return NULL;
532
533 for (i=0; i < len; i++) {
534 PyObject *item, *item_key;
535
536 item = PyTuple_GET_ITEM(op, i);
537 item_key = _PyCode_ConstantKey(item);
538 if (item_key == NULL) {
539 Py_DECREF(tuple);
540 return NULL;
541 }
542
543 PyTuple_SET_ITEM(tuple, i, item_key);
544 }
545
546 key = PyTuple_Pack(3, Py_TYPE(op), op, tuple);
547 Py_DECREF(tuple);
548 }
549 else if (PyFrozenSet_CheckExact(op)) {
550 Py_ssize_t pos = 0;
551 PyObject *item;
552 Py_hash_t hash;
553 Py_ssize_t i, len;
554 PyObject *tuple, *set;
555
556 len = PySet_GET_SIZE(op);
557 tuple = PyTuple_New(len);
558 if (tuple == NULL)
559 return NULL;
560
561 i = 0;
562 while (_PySet_NextEntry(op, &pos, &item, &hash)) {
563 PyObject *item_key;
564
565 item_key = _PyCode_ConstantKey(item);
566 if (item_key == NULL) {
567 Py_DECREF(tuple);
568 return NULL;
569 }
570
571 assert(i < len);
572 PyTuple_SET_ITEM(tuple, i, item_key);
573 i++;
574 }
575 set = PyFrozenSet_New(tuple);
576 Py_DECREF(tuple);
577 if (set == NULL)
578 return NULL;
579
580 key = PyTuple_Pack(3, Py_TYPE(op), op, set);
581 Py_DECREF(set);
582 return key;
583 }
584 else {
Martin Panter6245cb32016-04-15 02:14:19 +0000585 /* for other types, use the object identifier as a unique identifier
Victor Stinnerefb24132016-01-22 12:33:12 +0100586 * to ensure that they are seen as unequal. */
587 PyObject *obj_id = PyLong_FromVoidPtr(op);
588 if (obj_id == NULL)
589 return NULL;
590
591 key = PyTuple_Pack(3, Py_TYPE(op), op, obj_id);
592 Py_DECREF(obj_id);
593 }
594 return key;
595}
596
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000597static PyObject *
598code_richcompare(PyObject *self, PyObject *other, int op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000599{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 PyCodeObject *co, *cp;
601 int eq;
Victor Stinnerefb24132016-01-22 12:33:12 +0100602 PyObject *consts1, *consts2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 if ((op != Py_EQ && op != Py_NE) ||
606 !PyCode_Check(self) ||
607 !PyCode_Check(other)) {
Brian Curtindfc80e32011-08-10 20:28:54 -0500608 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 co = (PyCodeObject *)self;
612 cp = (PyCodeObject *)other;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 eq = PyObject_RichCompareBool(co->co_name, cp->co_name, Py_EQ);
615 if (eq <= 0) goto unequal;
616 eq = co->co_argcount == cp->co_argcount;
617 if (!eq) goto unequal;
618 eq = co->co_kwonlyargcount == cp->co_kwonlyargcount;
619 if (!eq) goto unequal;
620 eq = co->co_nlocals == cp->co_nlocals;
621 if (!eq) goto unequal;
622 eq = co->co_flags == cp->co_flags;
623 if (!eq) goto unequal;
624 eq = co->co_firstlineno == cp->co_firstlineno;
625 if (!eq) goto unequal;
626 eq = PyObject_RichCompareBool(co->co_code, cp->co_code, Py_EQ);
627 if (eq <= 0) goto unequal;
Victor Stinnerefb24132016-01-22 12:33:12 +0100628
629 /* compare constants */
630 consts1 = _PyCode_ConstantKey(co->co_consts);
631 if (!consts1)
632 return NULL;
633 consts2 = _PyCode_ConstantKey(cp->co_consts);
634 if (!consts2) {
635 Py_DECREF(consts1);
636 return NULL;
637 }
638 eq = PyObject_RichCompareBool(consts1, consts2, Py_EQ);
639 Py_DECREF(consts1);
640 Py_DECREF(consts2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 if (eq <= 0) goto unequal;
Victor Stinnerefb24132016-01-22 12:33:12 +0100642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 eq = PyObject_RichCompareBool(co->co_names, cp->co_names, Py_EQ);
644 if (eq <= 0) goto unequal;
645 eq = PyObject_RichCompareBool(co->co_varnames, cp->co_varnames, Py_EQ);
646 if (eq <= 0) goto unequal;
647 eq = PyObject_RichCompareBool(co->co_freevars, cp->co_freevars, Py_EQ);
648 if (eq <= 0) goto unequal;
649 eq = PyObject_RichCompareBool(co->co_cellvars, cp->co_cellvars, Py_EQ);
650 if (eq <= 0) goto unequal;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 if (op == Py_EQ)
653 res = Py_True;
654 else
655 res = Py_False;
656 goto done;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000657
658 unequal:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 if (eq < 0)
660 return NULL;
661 if (op == Py_NE)
662 res = Py_True;
663 else
664 res = Py_False;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000665
666 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 Py_INCREF(res);
668 return res;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000669}
670
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000671static Py_hash_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000672code_hash(PyCodeObject *co)
673{
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000674 Py_hash_t h, h0, h1, h2, h3, h4, h5, h6;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 h0 = PyObject_Hash(co->co_name);
676 if (h0 == -1) return -1;
677 h1 = PyObject_Hash(co->co_code);
678 if (h1 == -1) return -1;
679 h2 = PyObject_Hash(co->co_consts);
680 if (h2 == -1) return -1;
681 h3 = PyObject_Hash(co->co_names);
682 if (h3 == -1) return -1;
683 h4 = PyObject_Hash(co->co_varnames);
684 if (h4 == -1) return -1;
685 h5 = PyObject_Hash(co->co_freevars);
686 if (h5 == -1) return -1;
687 h6 = PyObject_Hash(co->co_cellvars);
688 if (h6 == -1) return -1;
689 h = h0 ^ h1 ^ h2 ^ h3 ^ h4 ^ h5 ^ h6 ^
690 co->co_argcount ^ co->co_kwonlyargcount ^
691 co->co_nlocals ^ co->co_flags;
692 if (h == -1) h = -2;
693 return h;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000694}
695
696/* XXX code objects need to participate in GC? */
697
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200698static struct PyMethodDef code_methods[] = {
699 {"__sizeof__", (PyCFunction)code_sizeof, METH_NOARGS},
700 {NULL, NULL} /* sentinel */
701};
702
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000703PyTypeObject PyCode_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 PyVarObject_HEAD_INIT(&PyType_Type, 0)
705 "code",
706 sizeof(PyCodeObject),
707 0,
708 (destructor)code_dealloc, /* tp_dealloc */
709 0, /* tp_print */
710 0, /* tp_getattr */
711 0, /* tp_setattr */
712 0, /* tp_reserved */
713 (reprfunc)code_repr, /* tp_repr */
714 0, /* tp_as_number */
715 0, /* tp_as_sequence */
716 0, /* tp_as_mapping */
717 (hashfunc)code_hash, /* tp_hash */
718 0, /* tp_call */
719 0, /* tp_str */
720 PyObject_GenericGetAttr, /* tp_getattro */
721 0, /* tp_setattro */
722 0, /* tp_as_buffer */
723 Py_TPFLAGS_DEFAULT, /* tp_flags */
724 code_doc, /* tp_doc */
725 0, /* tp_traverse */
726 0, /* tp_clear */
727 code_richcompare, /* tp_richcompare */
728 offsetof(PyCodeObject, co_weakreflist), /* tp_weaklistoffset */
729 0, /* tp_iter */
730 0, /* tp_iternext */
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200731 code_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 code_memberlist, /* tp_members */
733 0, /* tp_getset */
734 0, /* tp_base */
735 0, /* tp_dict */
736 0, /* tp_descr_get */
737 0, /* tp_descr_set */
738 0, /* tp_dictoffset */
739 0, /* tp_init */
740 0, /* tp_alloc */
741 code_new, /* tp_new */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000742};
743
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000744/* Use co_lnotab to compute the line number from a bytecode index, addrq. See
745 lnotab_notes.txt for the details of the lnotab representation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000746*/
747
748int
749PyCode_Addr2Line(PyCodeObject *co, int addrq)
750{
Victor Stinner0fcab4a2011-01-04 12:59:15 +0000751 Py_ssize_t size = PyBytes_Size(co->co_lnotab) / 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 unsigned char *p = (unsigned char*)PyBytes_AsString(co->co_lnotab);
753 int line = co->co_firstlineno;
754 int addr = 0;
755 while (--size >= 0) {
756 addr += *p++;
757 if (addr > addrq)
758 break;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100759 line += (signed char)*p;
760 p++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 }
762 return line;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000763}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000764
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000765/* Update *bounds to describe the first and one-past-the-last instructions in
766 the same line as lasti. Return the number of that line. */
767int
768_PyCode_CheckLineNumber(PyCodeObject* co, int lasti, PyAddrPair *bounds)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000769{
Victor Stinner0fcab4a2011-01-04 12:59:15 +0000770 Py_ssize_t size;
771 int addr, line;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 unsigned char* p;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 p = (unsigned char*)PyBytes_AS_STRING(co->co_lnotab);
775 size = PyBytes_GET_SIZE(co->co_lnotab) / 2;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 addr = 0;
778 line = co->co_firstlineno;
779 assert(line > 0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 /* possible optimization: if f->f_lasti == instr_ub
782 (likely to be a common case) then we already know
783 instr_lb -- if we stored the matching value of p
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700784 somewhere we could skip the first while loop. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 /* See lnotab_notes.txt for the description of
787 co_lnotab. A point to remember: increments to p
788 come in (addr, line) pairs. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 bounds->ap_lower = 0;
791 while (size > 0) {
792 if (addr + *p > lasti)
793 break;
794 addr += *p++;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100795 if ((signed char)*p)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 bounds->ap_lower = addr;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100797 line += (signed char)*p;
798 p++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 --size;
800 }
801
802 if (size > 0) {
803 while (--size >= 0) {
804 addr += *p++;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100805 if ((signed char)*p)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 break;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100807 p++;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000808 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 bounds->ap_upper = addr;
810 }
811 else {
812 bounds->ap_upper = INT_MAX;
813 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 return line;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000816}
Brett Cannon5c4de282016-09-07 11:16:41 -0700817
818
819int
820_PyCode_GetExtra(PyObject *code, Py_ssize_t index, void **extra)
821{
Brett Cannon5c4de282016-09-07 11:16:41 -0700822 assert(*extra == NULL);
823
824 if (!PyCode_Check(code)) {
825 PyErr_BadInternalCall();
Brett Cannon3788b852016-09-07 12:51:08 -0700826 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -0700827 }
828
Brett Cannond0600ed2016-09-07 14:30:39 -0700829 PyCodeObject *o = (PyCodeObject*) code;
830 _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra*) o->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700831
Brett Cannond0600ed2016-09-07 14:30:39 -0700832
833 if (co_extra == NULL || co_extra->ce_size <= index) {
Brett Cannon5c4de282016-09-07 11:16:41 -0700834 return 0;
835 }
836
Brett Cannond0600ed2016-09-07 14:30:39 -0700837 *extra = co_extra->ce_extras[index];
Brett Cannon5c4de282016-09-07 11:16:41 -0700838 return 0;
839}
840
841
842int
843_PyCode_SetExtra(PyObject *code, Py_ssize_t index, void *extra)
844{
Brett Cannon5c4de282016-09-07 11:16:41 -0700845 PyThreadState *tstate = PyThreadState_Get();
846
847 if (!PyCode_Check(code) || index < 0 ||
848 index >= tstate->co_extra_user_count) {
849 PyErr_BadInternalCall();
Brett Cannon3788b852016-09-07 12:51:08 -0700850 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -0700851 }
852
Brett Cannond0600ed2016-09-07 14:30:39 -0700853 PyCodeObject *o = (PyCodeObject*) code;
854 _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra *) o->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700855
Brett Cannond0600ed2016-09-07 14:30:39 -0700856 if (co_extra == NULL) {
Brett Cannon5c4de282016-09-07 11:16:41 -0700857 o->co_extra = (_PyCodeObjectExtra*) PyMem_Malloc(
858 sizeof(_PyCodeObjectExtra));
859 if (o->co_extra == NULL) {
Brett Cannon3788b852016-09-07 12:51:08 -0700860 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -0700861 }
Brett Cannond0600ed2016-09-07 14:30:39 -0700862 co_extra = (_PyCodeObjectExtra *) o->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700863
Brett Cannond0600ed2016-09-07 14:30:39 -0700864 co_extra->ce_extras = PyMem_Malloc(
Brett Cannon5c4de282016-09-07 11:16:41 -0700865 tstate->co_extra_user_count * sizeof(void*));
Brett Cannond0600ed2016-09-07 14:30:39 -0700866 if (co_extra->ce_extras == NULL) {
Brett Cannon3788b852016-09-07 12:51:08 -0700867 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -0700868 }
869
Brett Cannond0600ed2016-09-07 14:30:39 -0700870 co_extra->ce_size = tstate->co_extra_user_count;
Brett Cannon5c4de282016-09-07 11:16:41 -0700871
Brett Cannond0600ed2016-09-07 14:30:39 -0700872 for (Py_ssize_t i = 0; i < co_extra->ce_size; i++) {
873 co_extra->ce_extras[i] = NULL;
Brett Cannon5c4de282016-09-07 11:16:41 -0700874 }
875 }
Brett Cannond0600ed2016-09-07 14:30:39 -0700876 else if (co_extra->ce_size <= index) {
877 co_extra->ce_extras = PyMem_Realloc(
878 co_extra->ce_extras, tstate->co_extra_user_count * sizeof(void*));
Brett Cannon5c4de282016-09-07 11:16:41 -0700879
Brett Cannond0600ed2016-09-07 14:30:39 -0700880 if (co_extra->ce_extras == NULL) {
Brett Cannon3788b852016-09-07 12:51:08 -0700881 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -0700882 }
883
Brett Cannond0600ed2016-09-07 14:30:39 -0700884 co_extra->ce_size = tstate->co_extra_user_count;
Brett Cannon5c4de282016-09-07 11:16:41 -0700885
Brett Cannond0600ed2016-09-07 14:30:39 -0700886 for (Py_ssize_t i = co_extra->ce_size; i < co_extra->ce_size; i++) {
887 co_extra->ce_extras[i] = NULL;
Brett Cannon5c4de282016-09-07 11:16:41 -0700888 }
889 }
890
Brett Cannond0600ed2016-09-07 14:30:39 -0700891 co_extra->ce_extras[index] = extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700892 return 0;
893}