blob: 788818d303d95b33382309bc5ac9ddb81f88a880 [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 ||
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +0200118 code == NULL || !PyBytes_Check(code) ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 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) ||
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +0200126 lnotab == NULL || !PyBytes_Check(lnotab)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 PyErr_BadInternalCall();
128 return NULL;
129 }
Victor Stinner7c74de42013-10-10 15:55:14 +0200130
131 /* Ensure that the filename is a ready Unicode string */
132 if (PyUnicode_READY(filename) < 0)
133 return NULL;
134
Benjamin Peterson90037602011-06-25 22:54:45 -0500135 n_cellvars = PyTuple_GET_SIZE(cellvars);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136 intern_strings(names);
137 intern_strings(varnames);
138 intern_strings(freevars);
139 intern_strings(cellvars);
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +0300140 intern_string_constants(consts);
Benjamin Peterson90037602011-06-25 22:54:45 -0500141 /* Create mapping between cells and arguments if needed. */
142 if (n_cellvars) {
143 Py_ssize_t total_args = argcount + kwonlyargcount +
144 ((flags & CO_VARARGS) != 0) + ((flags & CO_VARKEYWORDS) != 0);
145 Py_ssize_t alloc_size = sizeof(unsigned char) * n_cellvars;
Benjamin Peterson1bf494b2016-09-07 11:28:35 -0700146 bool used_cell2arg = false;
Benjamin Peterson90037602011-06-25 22:54:45 -0500147 cell2arg = PyMem_MALLOC(alloc_size);
148 if (cell2arg == NULL)
149 return NULL;
150 memset(cell2arg, CO_CELL_NOT_AN_ARG, alloc_size);
151 /* Find cells which are also arguments. */
152 for (i = 0; i < n_cellvars; i++) {
153 Py_ssize_t j;
154 PyObject *cell = PyTuple_GET_ITEM(cellvars, i);
155 for (j = 0; j < total_args; j++) {
156 PyObject *arg = PyTuple_GET_ITEM(varnames, j);
157 if (!PyUnicode_Compare(cell, arg)) {
158 cell2arg[i] = j;
Benjamin Peterson1bf494b2016-09-07 11:28:35 -0700159 used_cell2arg = true;
Benjamin Peterson90037602011-06-25 22:54:45 -0500160 break;
161 }
162 }
163 }
164 if (!used_cell2arg) {
165 PyMem_FREE(cell2arg);
166 cell2arg = NULL;
167 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 }
Benjamin Peterson90037602011-06-25 22:54:45 -0500169 co = PyObject_NEW(PyCodeObject, &PyCode_Type);
170 if (co == NULL) {
171 if (cell2arg)
172 PyMem_FREE(cell2arg);
173 return NULL;
174 }
175 co->co_argcount = argcount;
176 co->co_kwonlyargcount = kwonlyargcount;
177 co->co_nlocals = nlocals;
178 co->co_stacksize = stacksize;
179 co->co_flags = flags;
180 Py_INCREF(code);
181 co->co_code = code;
182 Py_INCREF(consts);
183 co->co_consts = consts;
184 Py_INCREF(names);
185 co->co_names = names;
186 Py_INCREF(varnames);
187 co->co_varnames = varnames;
188 Py_INCREF(freevars);
189 co->co_freevars = freevars;
190 Py_INCREF(cellvars);
191 co->co_cellvars = cellvars;
192 co->co_cell2arg = cell2arg;
193 Py_INCREF(filename);
194 co->co_filename = filename;
195 Py_INCREF(name);
196 co->co_name = name;
197 co->co_firstlineno = firstlineno;
198 Py_INCREF(lnotab);
199 co->co_lnotab = lnotab;
200 co->co_zombieframe = NULL;
201 co->co_weakreflist = NULL;
Brett Cannon5c4de282016-09-07 11:16:41 -0700202 co->co_extra = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000204}
205
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000206PyCodeObject *
207PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno)
208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 static PyObject *emptystring = NULL;
210 static PyObject *nulltuple = NULL;
211 PyObject *filename_ob = NULL;
212 PyObject *funcname_ob = NULL;
213 PyCodeObject *result = NULL;
214 if (emptystring == NULL) {
215 emptystring = PyBytes_FromString("");
216 if (emptystring == NULL)
217 goto failed;
218 }
219 if (nulltuple == NULL) {
220 nulltuple = PyTuple_New(0);
221 if (nulltuple == NULL)
222 goto failed;
223 }
224 funcname_ob = PyUnicode_FromString(funcname);
225 if (funcname_ob == NULL)
226 goto failed;
227 filename_ob = PyUnicode_DecodeFSDefault(filename);
228 if (filename_ob == NULL)
229 goto failed;
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 result = PyCode_New(0, /* argcount */
232 0, /* kwonlyargcount */
233 0, /* nlocals */
234 0, /* stacksize */
235 0, /* flags */
236 emptystring, /* code */
237 nulltuple, /* consts */
238 nulltuple, /* names */
239 nulltuple, /* varnames */
240 nulltuple, /* freevars */
241 nulltuple, /* cellvars */
242 filename_ob, /* filename */
243 funcname_ob, /* name */
244 firstlineno, /* firstlineno */
245 emptystring /* lnotab */
246 );
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000247
248failed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 Py_XDECREF(funcname_ob);
250 Py_XDECREF(filename_ob);
251 return result;
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000252}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000253
254#define OFF(x) offsetof(PyCodeObject, x)
255
256static PyMemberDef code_memberlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 {"co_argcount", T_INT, OFF(co_argcount), READONLY},
258 {"co_kwonlyargcount", T_INT, OFF(co_kwonlyargcount), READONLY},
259 {"co_nlocals", T_INT, OFF(co_nlocals), READONLY},
260 {"co_stacksize",T_INT, OFF(co_stacksize), READONLY},
261 {"co_flags", T_INT, OFF(co_flags), READONLY},
262 {"co_code", T_OBJECT, OFF(co_code), READONLY},
263 {"co_consts", T_OBJECT, OFF(co_consts), READONLY},
264 {"co_names", T_OBJECT, OFF(co_names), READONLY},
265 {"co_varnames", T_OBJECT, OFF(co_varnames), READONLY},
266 {"co_freevars", T_OBJECT, OFF(co_freevars), READONLY},
267 {"co_cellvars", T_OBJECT, OFF(co_cellvars), READONLY},
268 {"co_filename", T_OBJECT, OFF(co_filename), READONLY},
269 {"co_name", T_OBJECT, OFF(co_name), READONLY},
270 {"co_firstlineno", T_INT, OFF(co_firstlineno), READONLY},
271 {"co_lnotab", T_OBJECT, OFF(co_lnotab), READONLY},
272 {NULL} /* Sentinel */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000273};
274
275/* Helper for code_new: return a shallow copy of a tuple that is
276 guaranteed to contain exact strings, by converting string subclasses
277 to exact strings and complaining if a non-string is found. */
278static PyObject*
279validate_and_copy_tuple(PyObject *tup)
280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 PyObject *newtuple;
282 PyObject *item;
283 Py_ssize_t i, len;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 len = PyTuple_GET_SIZE(tup);
286 newtuple = PyTuple_New(len);
287 if (newtuple == NULL)
288 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 for (i = 0; i < len; i++) {
291 item = PyTuple_GET_ITEM(tup, i);
292 if (PyUnicode_CheckExact(item)) {
293 Py_INCREF(item);
294 }
295 else if (!PyUnicode_Check(item)) {
296 PyErr_Format(
297 PyExc_TypeError,
298 "name tuples must contain only "
299 "strings, not '%.500s'",
300 item->ob_type->tp_name);
301 Py_DECREF(newtuple);
302 return NULL;
303 }
304 else {
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100305 item = _PyUnicode_Copy(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 if (item == NULL) {
307 Py_DECREF(newtuple);
308 return NULL;
309 }
310 }
311 PyTuple_SET_ITEM(newtuple, i, item);
312 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 return newtuple;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000315}
316
317PyDoc_STRVAR(code_doc,
Georg Brandl8c1a50a2009-07-18 09:07:48 +0000318"code(argcount, kwonlyargcount, nlocals, stacksize, flags, codestring,\n\
Georg Brandla1e7e132008-01-26 09:39:23 +0000319 constants, names, varnames, filename, name, firstlineno,\n\
320 lnotab[, freevars[, cellvars]])\n\
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000321\n\
322Create a code object. Not for the faint of heart.");
323
324static PyObject *
325code_new(PyTypeObject *type, PyObject *args, PyObject *kw)
326{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 int argcount;
328 int kwonlyargcount;
329 int nlocals;
330 int stacksize;
331 int flags;
332 PyObject *co = NULL;
333 PyObject *code;
334 PyObject *consts;
335 PyObject *names, *ournames = NULL;
336 PyObject *varnames, *ourvarnames = NULL;
337 PyObject *freevars = NULL, *ourfreevars = NULL;
338 PyObject *cellvars = NULL, *ourcellvars = NULL;
339 PyObject *filename;
340 PyObject *name;
341 int firstlineno;
342 PyObject *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 if (!PyArg_ParseTuple(args, "iiiiiSO!O!O!UUiS|O!O!:code",
345 &argcount, &kwonlyargcount,
346 &nlocals, &stacksize, &flags,
347 &code,
348 &PyTuple_Type, &consts,
349 &PyTuple_Type, &names,
350 &PyTuple_Type, &varnames,
351 &filename, &name,
352 &firstlineno, &lnotab,
353 &PyTuple_Type, &freevars,
354 &PyTuple_Type, &cellvars))
355 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 if (argcount < 0) {
358 PyErr_SetString(
359 PyExc_ValueError,
360 "code: argcount must not be negative");
361 goto cleanup;
362 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 if (kwonlyargcount < 0) {
365 PyErr_SetString(
366 PyExc_ValueError,
367 "code: kwonlyargcount must not be negative");
368 goto cleanup;
369 }
370 if (nlocals < 0) {
371 PyErr_SetString(
372 PyExc_ValueError,
373 "code: nlocals must not be negative");
374 goto cleanup;
375 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 ournames = validate_and_copy_tuple(names);
378 if (ournames == NULL)
379 goto cleanup;
380 ourvarnames = validate_and_copy_tuple(varnames);
381 if (ourvarnames == NULL)
382 goto cleanup;
383 if (freevars)
384 ourfreevars = validate_and_copy_tuple(freevars);
385 else
386 ourfreevars = PyTuple_New(0);
387 if (ourfreevars == NULL)
388 goto cleanup;
389 if (cellvars)
390 ourcellvars = validate_and_copy_tuple(cellvars);
391 else
392 ourcellvars = PyTuple_New(0);
393 if (ourcellvars == NULL)
394 goto cleanup;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 co = (PyObject *)PyCode_New(argcount, kwonlyargcount,
397 nlocals, stacksize, flags,
398 code, consts, ournames, ourvarnames,
399 ourfreevars, ourcellvars, filename,
400 name, firstlineno, lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000401 cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 Py_XDECREF(ournames);
403 Py_XDECREF(ourvarnames);
404 Py_XDECREF(ourfreevars);
405 Py_XDECREF(ourcellvars);
406 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000407}
408
409static void
410code_dealloc(PyCodeObject *co)
411{
Brett Cannon5c4de282016-09-07 11:16:41 -0700412 if (co->co_extra != NULL) {
413 PyThreadState *tstate = PyThreadState_Get();
Brett Cannond0600ed2016-09-07 14:30:39 -0700414 _PyCodeObjectExtra *co_extra = co->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700415
Brett Cannond0600ed2016-09-07 14:30:39 -0700416 for (Py_ssize_t i = 0; i < co_extra->ce_size; i++) {
Brett Cannon5c4de282016-09-07 11:16:41 -0700417 freefunc free_extra = tstate->co_extra_freefuncs[i];
418
419 if (free_extra != NULL) {
Brett Cannond0600ed2016-09-07 14:30:39 -0700420 free_extra(co_extra->ce_extras[i]);
Brett Cannon5c4de282016-09-07 11:16:41 -0700421 }
422 }
423
424 PyMem_FREE(co->co_extra);
425 }
426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 Py_XDECREF(co->co_code);
428 Py_XDECREF(co->co_consts);
429 Py_XDECREF(co->co_names);
430 Py_XDECREF(co->co_varnames);
431 Py_XDECREF(co->co_freevars);
432 Py_XDECREF(co->co_cellvars);
433 Py_XDECREF(co->co_filename);
434 Py_XDECREF(co->co_name);
435 Py_XDECREF(co->co_lnotab);
Benjamin Peterson90037602011-06-25 22:54:45 -0500436 if (co->co_cell2arg != NULL)
437 PyMem_FREE(co->co_cell2arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 if (co->co_zombieframe != NULL)
439 PyObject_GC_Del(co->co_zombieframe);
440 if (co->co_weakreflist != NULL)
441 PyObject_ClearWeakRefs((PyObject*)co);
442 PyObject_DEL(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000443}
444
445static PyObject *
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200446code_sizeof(PyCodeObject *co, void *unused)
447{
448 Py_ssize_t res;
449
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +0200450 res = _PyObject_SIZE(Py_TYPE(co));
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200451 if (co->co_cell2arg != NULL && co->co_cellvars != NULL)
452 res += PyTuple_GET_SIZE(co->co_cellvars) * sizeof(unsigned char);
453 return PyLong_FromSsize_t(res);
454}
455
456static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000457code_repr(PyCodeObject *co)
458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 int lineno;
460 if (co->co_firstlineno != 0)
461 lineno = co->co_firstlineno;
462 else
463 lineno = -1;
464 if (co->co_filename && PyUnicode_Check(co->co_filename)) {
465 return PyUnicode_FromFormat(
Victor Stinneraaa4e9a2011-01-05 03:33:26 +0000466 "<code object %U at %p, file \"%U\", line %d>",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 co->co_name, co, co->co_filename, lineno);
468 } else {
469 return PyUnicode_FromFormat(
Victor Stinneraaa4e9a2011-01-05 03:33:26 +0000470 "<code object %U at %p, file ???, line %d>",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 co->co_name, co, lineno);
472 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000473}
474
Victor Stinnerefb24132016-01-22 12:33:12 +0100475PyObject*
476_PyCode_ConstantKey(PyObject *op)
477{
478 PyObject *key;
479
480 /* Py_None and Py_Ellipsis are singleton */
481 if (op == Py_None || op == Py_Ellipsis
482 || PyLong_CheckExact(op)
483 || PyBool_Check(op)
484 || PyBytes_CheckExact(op)
485 || PyUnicode_CheckExact(op)
486 /* code_richcompare() uses _PyCode_ConstantKey() internally */
487 || PyCode_Check(op)) {
488 key = PyTuple_Pack(2, Py_TYPE(op), op);
489 }
490 else if (PyFloat_CheckExact(op)) {
491 double d = PyFloat_AS_DOUBLE(op);
492 /* all we need is to make the tuple different in either the 0.0
493 * or -0.0 case from all others, just to avoid the "coercion".
494 */
495 if (d == 0.0 && copysign(1.0, d) < 0.0)
496 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
497 else
498 key = PyTuple_Pack(2, Py_TYPE(op), op);
499 }
500 else if (PyComplex_CheckExact(op)) {
501 Py_complex z;
502 int real_negzero, imag_negzero;
503 /* For the complex case we must make complex(x, 0.)
504 different from complex(x, -0.) and complex(0., y)
505 different from complex(-0., y), for any x and y.
506 All four complex zeros must be distinguished.*/
507 z = PyComplex_AsCComplex(op);
508 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
509 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
510 /* use True, False and None singleton as tags for the real and imag
511 * sign, to make tuples different */
512 if (real_negzero && imag_negzero) {
513 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_True);
514 }
515 else if (imag_negzero) {
516 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_False);
517 }
518 else if (real_negzero) {
519 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
520 }
521 else {
522 key = PyTuple_Pack(2, Py_TYPE(op), op);
523 }
524 }
525 else if (PyTuple_CheckExact(op)) {
526 Py_ssize_t i, len;
527 PyObject *tuple;
528
529 len = PyTuple_GET_SIZE(op);
530 tuple = PyTuple_New(len);
531 if (tuple == NULL)
532 return NULL;
533
534 for (i=0; i < len; i++) {
535 PyObject *item, *item_key;
536
537 item = PyTuple_GET_ITEM(op, i);
538 item_key = _PyCode_ConstantKey(item);
539 if (item_key == NULL) {
540 Py_DECREF(tuple);
541 return NULL;
542 }
543
544 PyTuple_SET_ITEM(tuple, i, item_key);
545 }
546
547 key = PyTuple_Pack(3, Py_TYPE(op), op, tuple);
548 Py_DECREF(tuple);
549 }
550 else if (PyFrozenSet_CheckExact(op)) {
551 Py_ssize_t pos = 0;
552 PyObject *item;
553 Py_hash_t hash;
554 Py_ssize_t i, len;
555 PyObject *tuple, *set;
556
557 len = PySet_GET_SIZE(op);
558 tuple = PyTuple_New(len);
559 if (tuple == NULL)
560 return NULL;
561
562 i = 0;
563 while (_PySet_NextEntry(op, &pos, &item, &hash)) {
564 PyObject *item_key;
565
566 item_key = _PyCode_ConstantKey(item);
567 if (item_key == NULL) {
568 Py_DECREF(tuple);
569 return NULL;
570 }
571
572 assert(i < len);
573 PyTuple_SET_ITEM(tuple, i, item_key);
574 i++;
575 }
576 set = PyFrozenSet_New(tuple);
577 Py_DECREF(tuple);
578 if (set == NULL)
579 return NULL;
580
581 key = PyTuple_Pack(3, Py_TYPE(op), op, set);
582 Py_DECREF(set);
583 return key;
584 }
585 else {
Martin Panter6245cb32016-04-15 02:14:19 +0000586 /* for other types, use the object identifier as a unique identifier
Victor Stinnerefb24132016-01-22 12:33:12 +0100587 * to ensure that they are seen as unequal. */
588 PyObject *obj_id = PyLong_FromVoidPtr(op);
589 if (obj_id == NULL)
590 return NULL;
591
592 key = PyTuple_Pack(3, Py_TYPE(op), op, obj_id);
593 Py_DECREF(obj_id);
594 }
595 return key;
596}
597
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000598static PyObject *
599code_richcompare(PyObject *self, PyObject *other, int op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 PyCodeObject *co, *cp;
602 int eq;
Victor Stinnerefb24132016-01-22 12:33:12 +0100603 PyObject *consts1, *consts2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 if ((op != Py_EQ && op != Py_NE) ||
607 !PyCode_Check(self) ||
608 !PyCode_Check(other)) {
Brian Curtindfc80e32011-08-10 20:28:54 -0500609 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 co = (PyCodeObject *)self;
613 cp = (PyCodeObject *)other;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 eq = PyObject_RichCompareBool(co->co_name, cp->co_name, Py_EQ);
616 if (eq <= 0) goto unequal;
617 eq = co->co_argcount == cp->co_argcount;
618 if (!eq) goto unequal;
619 eq = co->co_kwonlyargcount == cp->co_kwonlyargcount;
620 if (!eq) goto unequal;
621 eq = co->co_nlocals == cp->co_nlocals;
622 if (!eq) goto unequal;
623 eq = co->co_flags == cp->co_flags;
624 if (!eq) goto unequal;
625 eq = co->co_firstlineno == cp->co_firstlineno;
626 if (!eq) goto unequal;
627 eq = PyObject_RichCompareBool(co->co_code, cp->co_code, Py_EQ);
628 if (eq <= 0) goto unequal;
Victor Stinnerefb24132016-01-22 12:33:12 +0100629
630 /* compare constants */
631 consts1 = _PyCode_ConstantKey(co->co_consts);
632 if (!consts1)
633 return NULL;
634 consts2 = _PyCode_ConstantKey(cp->co_consts);
635 if (!consts2) {
636 Py_DECREF(consts1);
637 return NULL;
638 }
639 eq = PyObject_RichCompareBool(consts1, consts2, Py_EQ);
640 Py_DECREF(consts1);
641 Py_DECREF(consts2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 if (eq <= 0) goto unequal;
Victor Stinnerefb24132016-01-22 12:33:12 +0100643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 eq = PyObject_RichCompareBool(co->co_names, cp->co_names, Py_EQ);
645 if (eq <= 0) goto unequal;
646 eq = PyObject_RichCompareBool(co->co_varnames, cp->co_varnames, Py_EQ);
647 if (eq <= 0) goto unequal;
648 eq = PyObject_RichCompareBool(co->co_freevars, cp->co_freevars, Py_EQ);
649 if (eq <= 0) goto unequal;
650 eq = PyObject_RichCompareBool(co->co_cellvars, cp->co_cellvars, Py_EQ);
651 if (eq <= 0) goto unequal;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 if (op == Py_EQ)
654 res = Py_True;
655 else
656 res = Py_False;
657 goto done;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000658
659 unequal:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 if (eq < 0)
661 return NULL;
662 if (op == Py_NE)
663 res = Py_True;
664 else
665 res = Py_False;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000666
667 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 Py_INCREF(res);
669 return res;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000670}
671
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000672static Py_hash_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000673code_hash(PyCodeObject *co)
674{
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000675 Py_hash_t h, h0, h1, h2, h3, h4, h5, h6;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 h0 = PyObject_Hash(co->co_name);
677 if (h0 == -1) return -1;
678 h1 = PyObject_Hash(co->co_code);
679 if (h1 == -1) return -1;
680 h2 = PyObject_Hash(co->co_consts);
681 if (h2 == -1) return -1;
682 h3 = PyObject_Hash(co->co_names);
683 if (h3 == -1) return -1;
684 h4 = PyObject_Hash(co->co_varnames);
685 if (h4 == -1) return -1;
686 h5 = PyObject_Hash(co->co_freevars);
687 if (h5 == -1) return -1;
688 h6 = PyObject_Hash(co->co_cellvars);
689 if (h6 == -1) return -1;
690 h = h0 ^ h1 ^ h2 ^ h3 ^ h4 ^ h5 ^ h6 ^
691 co->co_argcount ^ co->co_kwonlyargcount ^
692 co->co_nlocals ^ co->co_flags;
693 if (h == -1) h = -2;
694 return h;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000695}
696
697/* XXX code objects need to participate in GC? */
698
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200699static struct PyMethodDef code_methods[] = {
700 {"__sizeof__", (PyCFunction)code_sizeof, METH_NOARGS},
701 {NULL, NULL} /* sentinel */
702};
703
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000704PyTypeObject PyCode_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 PyVarObject_HEAD_INIT(&PyType_Type, 0)
706 "code",
707 sizeof(PyCodeObject),
708 0,
709 (destructor)code_dealloc, /* tp_dealloc */
710 0, /* tp_print */
711 0, /* tp_getattr */
712 0, /* tp_setattr */
713 0, /* tp_reserved */
714 (reprfunc)code_repr, /* tp_repr */
715 0, /* tp_as_number */
716 0, /* tp_as_sequence */
717 0, /* tp_as_mapping */
718 (hashfunc)code_hash, /* tp_hash */
719 0, /* tp_call */
720 0, /* tp_str */
721 PyObject_GenericGetAttr, /* tp_getattro */
722 0, /* tp_setattro */
723 0, /* tp_as_buffer */
724 Py_TPFLAGS_DEFAULT, /* tp_flags */
725 code_doc, /* tp_doc */
726 0, /* tp_traverse */
727 0, /* tp_clear */
728 code_richcompare, /* tp_richcompare */
729 offsetof(PyCodeObject, co_weakreflist), /* tp_weaklistoffset */
730 0, /* tp_iter */
731 0, /* tp_iternext */
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200732 code_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 code_memberlist, /* tp_members */
734 0, /* tp_getset */
735 0, /* tp_base */
736 0, /* tp_dict */
737 0, /* tp_descr_get */
738 0, /* tp_descr_set */
739 0, /* tp_dictoffset */
740 0, /* tp_init */
741 0, /* tp_alloc */
742 code_new, /* tp_new */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000743};
744
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000745/* Use co_lnotab to compute the line number from a bytecode index, addrq. See
746 lnotab_notes.txt for the details of the lnotab representation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000747*/
748
749int
750PyCode_Addr2Line(PyCodeObject *co, int addrq)
751{
Victor Stinner0fcab4a2011-01-04 12:59:15 +0000752 Py_ssize_t size = PyBytes_Size(co->co_lnotab) / 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 unsigned char *p = (unsigned char*)PyBytes_AsString(co->co_lnotab);
754 int line = co->co_firstlineno;
755 int addr = 0;
756 while (--size >= 0) {
757 addr += *p++;
758 if (addr > addrq)
759 break;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100760 line += (signed char)*p;
761 p++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 }
763 return line;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000764}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000765
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000766/* Update *bounds to describe the first and one-past-the-last instructions in
767 the same line as lasti. Return the number of that line. */
768int
769_PyCode_CheckLineNumber(PyCodeObject* co, int lasti, PyAddrPair *bounds)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000770{
Victor Stinner0fcab4a2011-01-04 12:59:15 +0000771 Py_ssize_t size;
772 int addr, line;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 unsigned char* p;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 p = (unsigned char*)PyBytes_AS_STRING(co->co_lnotab);
776 size = PyBytes_GET_SIZE(co->co_lnotab) / 2;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 addr = 0;
779 line = co->co_firstlineno;
780 assert(line > 0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 /* possible optimization: if f->f_lasti == instr_ub
783 (likely to be a common case) then we already know
784 instr_lb -- if we stored the matching value of p
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700785 somewhere we could skip the first while loop. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 /* See lnotab_notes.txt for the description of
788 co_lnotab. A point to remember: increments to p
789 come in (addr, line) pairs. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 bounds->ap_lower = 0;
792 while (size > 0) {
793 if (addr + *p > lasti)
794 break;
795 addr += *p++;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100796 if ((signed char)*p)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 bounds->ap_lower = addr;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100798 line += (signed char)*p;
799 p++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 --size;
801 }
802
803 if (size > 0) {
804 while (--size >= 0) {
805 addr += *p++;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100806 if ((signed char)*p)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 break;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100808 p++;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000809 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 bounds->ap_upper = addr;
811 }
812 else {
813 bounds->ap_upper = INT_MAX;
814 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 return line;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000817}
Brett Cannon5c4de282016-09-07 11:16:41 -0700818
819
820int
821_PyCode_GetExtra(PyObject *code, Py_ssize_t index, void **extra)
822{
Brett Cannon5c4de282016-09-07 11:16:41 -0700823 assert(*extra == NULL);
824
825 if (!PyCode_Check(code)) {
826 PyErr_BadInternalCall();
Brett Cannon3788b852016-09-07 12:51:08 -0700827 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -0700828 }
829
Brett Cannond0600ed2016-09-07 14:30:39 -0700830 PyCodeObject *o = (PyCodeObject*) code;
831 _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra*) o->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700832
Brett Cannond0600ed2016-09-07 14:30:39 -0700833
834 if (co_extra == NULL || co_extra->ce_size <= index) {
Brett Cannon5c4de282016-09-07 11:16:41 -0700835 return 0;
836 }
837
Brett Cannond0600ed2016-09-07 14:30:39 -0700838 *extra = co_extra->ce_extras[index];
Brett Cannon5c4de282016-09-07 11:16:41 -0700839 return 0;
840}
841
842
843int
844_PyCode_SetExtra(PyObject *code, Py_ssize_t index, void *extra)
845{
Brett Cannon5c4de282016-09-07 11:16:41 -0700846 PyThreadState *tstate = PyThreadState_Get();
847
848 if (!PyCode_Check(code) || index < 0 ||
849 index >= tstate->co_extra_user_count) {
850 PyErr_BadInternalCall();
Brett Cannon3788b852016-09-07 12:51:08 -0700851 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -0700852 }
853
Brett Cannond0600ed2016-09-07 14:30:39 -0700854 PyCodeObject *o = (PyCodeObject*) code;
855 _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra *) o->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700856
Brett Cannond0600ed2016-09-07 14:30:39 -0700857 if (co_extra == NULL) {
Brett Cannon5c4de282016-09-07 11:16:41 -0700858 o->co_extra = (_PyCodeObjectExtra*) PyMem_Malloc(
859 sizeof(_PyCodeObjectExtra));
860 if (o->co_extra == NULL) {
Brett Cannon3788b852016-09-07 12:51:08 -0700861 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -0700862 }
Brett Cannond0600ed2016-09-07 14:30:39 -0700863 co_extra = (_PyCodeObjectExtra *) o->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700864
Brett Cannond0600ed2016-09-07 14:30:39 -0700865 co_extra->ce_extras = PyMem_Malloc(
Brett Cannon5c4de282016-09-07 11:16:41 -0700866 tstate->co_extra_user_count * sizeof(void*));
Brett Cannond0600ed2016-09-07 14:30:39 -0700867 if (co_extra->ce_extras == NULL) {
Brett Cannon3788b852016-09-07 12:51:08 -0700868 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -0700869 }
870
Brett Cannond0600ed2016-09-07 14:30:39 -0700871 co_extra->ce_size = tstate->co_extra_user_count;
Brett Cannon5c4de282016-09-07 11:16:41 -0700872
Brett Cannond0600ed2016-09-07 14:30:39 -0700873 for (Py_ssize_t i = 0; i < co_extra->ce_size; i++) {
874 co_extra->ce_extras[i] = NULL;
Brett Cannon5c4de282016-09-07 11:16:41 -0700875 }
876 }
Brett Cannond0600ed2016-09-07 14:30:39 -0700877 else if (co_extra->ce_size <= index) {
878 co_extra->ce_extras = PyMem_Realloc(
879 co_extra->ce_extras, tstate->co_extra_user_count * sizeof(void*));
Brett Cannon5c4de282016-09-07 11:16:41 -0700880
Brett Cannond0600ed2016-09-07 14:30:39 -0700881 if (co_extra->ce_extras == NULL) {
Brett Cannon3788b852016-09-07 12:51:08 -0700882 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -0700883 }
884
Brett Cannond0600ed2016-09-07 14:30:39 -0700885 co_extra->ce_size = tstate->co_extra_user_count;
Brett Cannon5c4de282016-09-07 11:16:41 -0700886
Brett Cannond0600ed2016-09-07 14:30:39 -0700887 for (Py_ssize_t i = co_extra->ce_size; i < co_extra->ce_size; i++) {
888 co_extra->ce_extras[i] = NULL;
Brett Cannon5c4de282016-09-07 11:16:41 -0700889 }
890 }
891
Brett Cannond0600ed2016-09-07 14:30:39 -0700892 co_extra->ce_extras[index] = extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700893 return 0;
894}