blob: 0857554adc3bae3c83d86a9339cb4d74f5308672 [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;
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200113 Py_ssize_t *cell2arg = NULL;
Benjamin Peterson90037602011-06-25 22:54:45 -0500114 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);
Benjamin Peterson1bf494b2016-09-07 11:28:35 -0700145 bool used_cell2arg = false;
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200146 cell2arg = PyMem_NEW(Py_ssize_t, n_cellvars);
147 if (cell2arg == NULL) {
148 PyErr_NoMemory();
Benjamin Peterson90037602011-06-25 22:54:45 -0500149 return NULL;
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200150 }
Benjamin Peterson90037602011-06-25 22:54:45 -0500151 /* Find cells which are also arguments. */
152 for (i = 0; i < n_cellvars; i++) {
153 Py_ssize_t j;
154 PyObject *cell = PyTuple_GET_ITEM(cellvars, i);
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200155 cell2arg[i] = CO_CELL_NOT_AN_ARG;
Benjamin Peterson90037602011-06-25 22:54:45 -0500156 for (j = 0; j < total_args; j++) {
157 PyObject *arg = PyTuple_GET_ITEM(varnames, j);
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200158 int cmp = PyUnicode_Compare(cell, arg);
159 if (cmp == -1 && PyErr_Occurred()) {
160 PyMem_FREE(cell2arg);
161 return NULL;
162 }
163 if (cmp == 0) {
Benjamin Peterson90037602011-06-25 22:54:45 -0500164 cell2arg[i] = j;
Benjamin Peterson1bf494b2016-09-07 11:28:35 -0700165 used_cell2arg = true;
Benjamin Peterson90037602011-06-25 22:54:45 -0500166 break;
167 }
168 }
169 }
170 if (!used_cell2arg) {
171 PyMem_FREE(cell2arg);
172 cell2arg = NULL;
173 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 }
Benjamin Peterson90037602011-06-25 22:54:45 -0500175 co = PyObject_NEW(PyCodeObject, &PyCode_Type);
176 if (co == NULL) {
177 if (cell2arg)
178 PyMem_FREE(cell2arg);
179 return NULL;
180 }
181 co->co_argcount = argcount;
182 co->co_kwonlyargcount = kwonlyargcount;
183 co->co_nlocals = nlocals;
184 co->co_stacksize = stacksize;
185 co->co_flags = flags;
186 Py_INCREF(code);
187 co->co_code = code;
188 Py_INCREF(consts);
189 co->co_consts = consts;
190 Py_INCREF(names);
191 co->co_names = names;
192 Py_INCREF(varnames);
193 co->co_varnames = varnames;
194 Py_INCREF(freevars);
195 co->co_freevars = freevars;
196 Py_INCREF(cellvars);
197 co->co_cellvars = cellvars;
198 co->co_cell2arg = cell2arg;
199 Py_INCREF(filename);
200 co->co_filename = filename;
201 Py_INCREF(name);
202 co->co_name = name;
203 co->co_firstlineno = firstlineno;
204 Py_INCREF(lnotab);
205 co->co_lnotab = lnotab;
206 co->co_zombieframe = NULL;
207 co->co_weakreflist = NULL;
Brett Cannon5c4de282016-09-07 11:16:41 -0700208 co->co_extra = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000210}
211
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000212PyCodeObject *
213PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno)
214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000215 static PyObject *emptystring = NULL;
216 static PyObject *nulltuple = NULL;
217 PyObject *filename_ob = NULL;
218 PyObject *funcname_ob = NULL;
219 PyCodeObject *result = NULL;
220 if (emptystring == NULL) {
221 emptystring = PyBytes_FromString("");
222 if (emptystring == NULL)
223 goto failed;
224 }
225 if (nulltuple == NULL) {
226 nulltuple = PyTuple_New(0);
227 if (nulltuple == NULL)
228 goto failed;
229 }
230 funcname_ob = PyUnicode_FromString(funcname);
231 if (funcname_ob == NULL)
232 goto failed;
233 filename_ob = PyUnicode_DecodeFSDefault(filename);
234 if (filename_ob == NULL)
235 goto failed;
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 result = PyCode_New(0, /* argcount */
238 0, /* kwonlyargcount */
239 0, /* nlocals */
240 0, /* stacksize */
241 0, /* flags */
242 emptystring, /* code */
243 nulltuple, /* consts */
244 nulltuple, /* names */
245 nulltuple, /* varnames */
246 nulltuple, /* freevars */
247 nulltuple, /* cellvars */
248 filename_ob, /* filename */
249 funcname_ob, /* name */
250 firstlineno, /* firstlineno */
251 emptystring /* lnotab */
252 );
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000253
254failed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 Py_XDECREF(funcname_ob);
256 Py_XDECREF(filename_ob);
257 return result;
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000258}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000259
260#define OFF(x) offsetof(PyCodeObject, x)
261
262static PyMemberDef code_memberlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 {"co_argcount", T_INT, OFF(co_argcount), READONLY},
264 {"co_kwonlyargcount", T_INT, OFF(co_kwonlyargcount), READONLY},
265 {"co_nlocals", T_INT, OFF(co_nlocals), READONLY},
266 {"co_stacksize",T_INT, OFF(co_stacksize), READONLY},
267 {"co_flags", T_INT, OFF(co_flags), READONLY},
268 {"co_code", T_OBJECT, OFF(co_code), READONLY},
269 {"co_consts", T_OBJECT, OFF(co_consts), READONLY},
270 {"co_names", T_OBJECT, OFF(co_names), READONLY},
271 {"co_varnames", T_OBJECT, OFF(co_varnames), READONLY},
272 {"co_freevars", T_OBJECT, OFF(co_freevars), READONLY},
273 {"co_cellvars", T_OBJECT, OFF(co_cellvars), READONLY},
274 {"co_filename", T_OBJECT, OFF(co_filename), READONLY},
275 {"co_name", T_OBJECT, OFF(co_name), READONLY},
276 {"co_firstlineno", T_INT, OFF(co_firstlineno), READONLY},
277 {"co_lnotab", T_OBJECT, OFF(co_lnotab), READONLY},
278 {NULL} /* Sentinel */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000279};
280
281/* Helper for code_new: return a shallow copy of a tuple that is
282 guaranteed to contain exact strings, by converting string subclasses
283 to exact strings and complaining if a non-string is found. */
284static PyObject*
285validate_and_copy_tuple(PyObject *tup)
286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 PyObject *newtuple;
288 PyObject *item;
289 Py_ssize_t i, len;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 len = PyTuple_GET_SIZE(tup);
292 newtuple = PyTuple_New(len);
293 if (newtuple == NULL)
294 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 for (i = 0; i < len; i++) {
297 item = PyTuple_GET_ITEM(tup, i);
298 if (PyUnicode_CheckExact(item)) {
299 Py_INCREF(item);
300 }
301 else if (!PyUnicode_Check(item)) {
302 PyErr_Format(
303 PyExc_TypeError,
304 "name tuples must contain only "
305 "strings, not '%.500s'",
306 item->ob_type->tp_name);
307 Py_DECREF(newtuple);
308 return NULL;
309 }
310 else {
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100311 item = _PyUnicode_Copy(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 if (item == NULL) {
313 Py_DECREF(newtuple);
314 return NULL;
315 }
316 }
317 PyTuple_SET_ITEM(newtuple, i, item);
318 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 return newtuple;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000321}
322
323PyDoc_STRVAR(code_doc,
Georg Brandl8c1a50a2009-07-18 09:07:48 +0000324"code(argcount, kwonlyargcount, nlocals, stacksize, flags, codestring,\n\
Georg Brandla1e7e132008-01-26 09:39:23 +0000325 constants, names, varnames, filename, name, firstlineno,\n\
326 lnotab[, freevars[, cellvars]])\n\
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000327\n\
328Create a code object. Not for the faint of heart.");
329
330static PyObject *
331code_new(PyTypeObject *type, PyObject *args, PyObject *kw)
332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 int argcount;
334 int kwonlyargcount;
335 int nlocals;
336 int stacksize;
337 int flags;
338 PyObject *co = NULL;
339 PyObject *code;
340 PyObject *consts;
341 PyObject *names, *ournames = NULL;
342 PyObject *varnames, *ourvarnames = NULL;
343 PyObject *freevars = NULL, *ourfreevars = NULL;
344 PyObject *cellvars = NULL, *ourcellvars = NULL;
345 PyObject *filename;
346 PyObject *name;
347 int firstlineno;
348 PyObject *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 if (!PyArg_ParseTuple(args, "iiiiiSO!O!O!UUiS|O!O!:code",
351 &argcount, &kwonlyargcount,
352 &nlocals, &stacksize, &flags,
353 &code,
354 &PyTuple_Type, &consts,
355 &PyTuple_Type, &names,
356 &PyTuple_Type, &varnames,
357 &filename, &name,
358 &firstlineno, &lnotab,
359 &PyTuple_Type, &freevars,
360 &PyTuple_Type, &cellvars))
361 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 if (argcount < 0) {
364 PyErr_SetString(
365 PyExc_ValueError,
366 "code: argcount must not be negative");
367 goto cleanup;
368 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 if (kwonlyargcount < 0) {
371 PyErr_SetString(
372 PyExc_ValueError,
373 "code: kwonlyargcount must not be negative");
374 goto cleanup;
375 }
376 if (nlocals < 0) {
377 PyErr_SetString(
378 PyExc_ValueError,
379 "code: nlocals must not be negative");
380 goto cleanup;
381 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 ournames = validate_and_copy_tuple(names);
384 if (ournames == NULL)
385 goto cleanup;
386 ourvarnames = validate_and_copy_tuple(varnames);
387 if (ourvarnames == NULL)
388 goto cleanup;
389 if (freevars)
390 ourfreevars = validate_and_copy_tuple(freevars);
391 else
392 ourfreevars = PyTuple_New(0);
393 if (ourfreevars == NULL)
394 goto cleanup;
395 if (cellvars)
396 ourcellvars = validate_and_copy_tuple(cellvars);
397 else
398 ourcellvars = PyTuple_New(0);
399 if (ourcellvars == NULL)
400 goto cleanup;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 co = (PyObject *)PyCode_New(argcount, kwonlyargcount,
403 nlocals, stacksize, flags,
404 code, consts, ournames, ourvarnames,
405 ourfreevars, ourcellvars, filename,
406 name, firstlineno, lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000407 cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 Py_XDECREF(ournames);
409 Py_XDECREF(ourvarnames);
410 Py_XDECREF(ourfreevars);
411 Py_XDECREF(ourcellvars);
412 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000413}
414
415static void
416code_dealloc(PyCodeObject *co)
417{
Brett Cannon5c4de282016-09-07 11:16:41 -0700418 if (co->co_extra != NULL) {
419 PyThreadState *tstate = PyThreadState_Get();
Brett Cannond0600ed2016-09-07 14:30:39 -0700420 _PyCodeObjectExtra *co_extra = co->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700421
Brett Cannond0600ed2016-09-07 14:30:39 -0700422 for (Py_ssize_t i = 0; i < co_extra->ce_size; i++) {
Brett Cannon5c4de282016-09-07 11:16:41 -0700423 freefunc free_extra = tstate->co_extra_freefuncs[i];
424
425 if (free_extra != NULL) {
Brett Cannond0600ed2016-09-07 14:30:39 -0700426 free_extra(co_extra->ce_extras[i]);
Brett Cannon5c4de282016-09-07 11:16:41 -0700427 }
428 }
429
430 PyMem_FREE(co->co_extra);
431 }
432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 Py_XDECREF(co->co_code);
434 Py_XDECREF(co->co_consts);
435 Py_XDECREF(co->co_names);
436 Py_XDECREF(co->co_varnames);
437 Py_XDECREF(co->co_freevars);
438 Py_XDECREF(co->co_cellvars);
439 Py_XDECREF(co->co_filename);
440 Py_XDECREF(co->co_name);
441 Py_XDECREF(co->co_lnotab);
Benjamin Peterson90037602011-06-25 22:54:45 -0500442 if (co->co_cell2arg != NULL)
443 PyMem_FREE(co->co_cell2arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 if (co->co_zombieframe != NULL)
445 PyObject_GC_Del(co->co_zombieframe);
446 if (co->co_weakreflist != NULL)
447 PyObject_ClearWeakRefs((PyObject*)co);
448 PyObject_DEL(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000449}
450
451static PyObject *
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200452code_sizeof(PyCodeObject *co, void *unused)
453{
454 Py_ssize_t res;
455
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +0200456 res = _PyObject_SIZE(Py_TYPE(co));
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200457 if (co->co_cell2arg != NULL && co->co_cellvars != NULL)
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200458 res += PyTuple_GET_SIZE(co->co_cellvars) * sizeof(Py_ssize_t);
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200459 return PyLong_FromSsize_t(res);
460}
461
462static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000463code_repr(PyCodeObject *co)
464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 int lineno;
466 if (co->co_firstlineno != 0)
467 lineno = co->co_firstlineno;
468 else
469 lineno = -1;
470 if (co->co_filename && PyUnicode_Check(co->co_filename)) {
471 return PyUnicode_FromFormat(
Victor Stinneraaa4e9a2011-01-05 03:33:26 +0000472 "<code object %U at %p, file \"%U\", line %d>",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 co->co_name, co, co->co_filename, lineno);
474 } else {
475 return PyUnicode_FromFormat(
Victor Stinneraaa4e9a2011-01-05 03:33:26 +0000476 "<code object %U at %p, file ???, line %d>",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 co->co_name, co, lineno);
478 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000479}
480
Victor Stinnerefb24132016-01-22 12:33:12 +0100481PyObject*
482_PyCode_ConstantKey(PyObject *op)
483{
484 PyObject *key;
485
486 /* Py_None and Py_Ellipsis are singleton */
487 if (op == Py_None || op == Py_Ellipsis
488 || PyLong_CheckExact(op)
489 || PyBool_Check(op)
490 || PyBytes_CheckExact(op)
491 || PyUnicode_CheckExact(op)
492 /* code_richcompare() uses _PyCode_ConstantKey() internally */
493 || PyCode_Check(op)) {
494 key = PyTuple_Pack(2, Py_TYPE(op), op);
495 }
496 else if (PyFloat_CheckExact(op)) {
497 double d = PyFloat_AS_DOUBLE(op);
498 /* all we need is to make the tuple different in either the 0.0
499 * or -0.0 case from all others, just to avoid the "coercion".
500 */
501 if (d == 0.0 && copysign(1.0, d) < 0.0)
502 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
503 else
504 key = PyTuple_Pack(2, Py_TYPE(op), op);
505 }
506 else if (PyComplex_CheckExact(op)) {
507 Py_complex z;
508 int real_negzero, imag_negzero;
509 /* For the complex case we must make complex(x, 0.)
510 different from complex(x, -0.) and complex(0., y)
511 different from complex(-0., y), for any x and y.
512 All four complex zeros must be distinguished.*/
513 z = PyComplex_AsCComplex(op);
514 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
515 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
516 /* use True, False and None singleton as tags for the real and imag
517 * sign, to make tuples different */
518 if (real_negzero && imag_negzero) {
519 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_True);
520 }
521 else if (imag_negzero) {
522 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_False);
523 }
524 else if (real_negzero) {
525 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
526 }
527 else {
528 key = PyTuple_Pack(2, Py_TYPE(op), op);
529 }
530 }
531 else if (PyTuple_CheckExact(op)) {
532 Py_ssize_t i, len;
533 PyObject *tuple;
534
535 len = PyTuple_GET_SIZE(op);
536 tuple = PyTuple_New(len);
537 if (tuple == NULL)
538 return NULL;
539
540 for (i=0; i < len; i++) {
541 PyObject *item, *item_key;
542
543 item = PyTuple_GET_ITEM(op, i);
544 item_key = _PyCode_ConstantKey(item);
545 if (item_key == NULL) {
546 Py_DECREF(tuple);
547 return NULL;
548 }
549
550 PyTuple_SET_ITEM(tuple, i, item_key);
551 }
552
553 key = PyTuple_Pack(3, Py_TYPE(op), op, tuple);
554 Py_DECREF(tuple);
555 }
556 else if (PyFrozenSet_CheckExact(op)) {
557 Py_ssize_t pos = 0;
558 PyObject *item;
559 Py_hash_t hash;
560 Py_ssize_t i, len;
561 PyObject *tuple, *set;
562
563 len = PySet_GET_SIZE(op);
564 tuple = PyTuple_New(len);
565 if (tuple == NULL)
566 return NULL;
567
568 i = 0;
569 while (_PySet_NextEntry(op, &pos, &item, &hash)) {
570 PyObject *item_key;
571
572 item_key = _PyCode_ConstantKey(item);
573 if (item_key == NULL) {
574 Py_DECREF(tuple);
575 return NULL;
576 }
577
578 assert(i < len);
579 PyTuple_SET_ITEM(tuple, i, item_key);
580 i++;
581 }
582 set = PyFrozenSet_New(tuple);
583 Py_DECREF(tuple);
584 if (set == NULL)
585 return NULL;
586
587 key = PyTuple_Pack(3, Py_TYPE(op), op, set);
588 Py_DECREF(set);
589 return key;
590 }
591 else {
Martin Panter6245cb32016-04-15 02:14:19 +0000592 /* for other types, use the object identifier as a unique identifier
Victor Stinnerefb24132016-01-22 12:33:12 +0100593 * to ensure that they are seen as unequal. */
594 PyObject *obj_id = PyLong_FromVoidPtr(op);
595 if (obj_id == NULL)
596 return NULL;
597
598 key = PyTuple_Pack(3, Py_TYPE(op), op, obj_id);
599 Py_DECREF(obj_id);
600 }
601 return key;
602}
603
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000604static PyObject *
605code_richcompare(PyObject *self, PyObject *other, int op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000606{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 PyCodeObject *co, *cp;
608 int eq;
Victor Stinnerefb24132016-01-22 12:33:12 +0100609 PyObject *consts1, *consts2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 if ((op != Py_EQ && op != Py_NE) ||
613 !PyCode_Check(self) ||
614 !PyCode_Check(other)) {
Brian Curtindfc80e32011-08-10 20:28:54 -0500615 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 co = (PyCodeObject *)self;
619 cp = (PyCodeObject *)other;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 eq = PyObject_RichCompareBool(co->co_name, cp->co_name, Py_EQ);
622 if (eq <= 0) goto unequal;
623 eq = co->co_argcount == cp->co_argcount;
624 if (!eq) goto unequal;
625 eq = co->co_kwonlyargcount == cp->co_kwonlyargcount;
626 if (!eq) goto unequal;
627 eq = co->co_nlocals == cp->co_nlocals;
628 if (!eq) goto unequal;
629 eq = co->co_flags == cp->co_flags;
630 if (!eq) goto unequal;
631 eq = co->co_firstlineno == cp->co_firstlineno;
632 if (!eq) goto unequal;
633 eq = PyObject_RichCompareBool(co->co_code, cp->co_code, Py_EQ);
634 if (eq <= 0) goto unequal;
Victor Stinnerefb24132016-01-22 12:33:12 +0100635
636 /* compare constants */
637 consts1 = _PyCode_ConstantKey(co->co_consts);
638 if (!consts1)
639 return NULL;
640 consts2 = _PyCode_ConstantKey(cp->co_consts);
641 if (!consts2) {
642 Py_DECREF(consts1);
643 return NULL;
644 }
645 eq = PyObject_RichCompareBool(consts1, consts2, Py_EQ);
646 Py_DECREF(consts1);
647 Py_DECREF(consts2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 if (eq <= 0) goto unequal;
Victor Stinnerefb24132016-01-22 12:33:12 +0100649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 eq = PyObject_RichCompareBool(co->co_names, cp->co_names, Py_EQ);
651 if (eq <= 0) goto unequal;
652 eq = PyObject_RichCompareBool(co->co_varnames, cp->co_varnames, Py_EQ);
653 if (eq <= 0) goto unequal;
654 eq = PyObject_RichCompareBool(co->co_freevars, cp->co_freevars, Py_EQ);
655 if (eq <= 0) goto unequal;
656 eq = PyObject_RichCompareBool(co->co_cellvars, cp->co_cellvars, Py_EQ);
657 if (eq <= 0) goto unequal;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 if (op == Py_EQ)
660 res = Py_True;
661 else
662 res = Py_False;
663 goto done;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000664
665 unequal:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 if (eq < 0)
667 return NULL;
668 if (op == Py_NE)
669 res = Py_True;
670 else
671 res = Py_False;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000672
673 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 Py_INCREF(res);
675 return res;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000676}
677
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000678static Py_hash_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000679code_hash(PyCodeObject *co)
680{
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000681 Py_hash_t h, h0, h1, h2, h3, h4, h5, h6;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 h0 = PyObject_Hash(co->co_name);
683 if (h0 == -1) return -1;
684 h1 = PyObject_Hash(co->co_code);
685 if (h1 == -1) return -1;
686 h2 = PyObject_Hash(co->co_consts);
687 if (h2 == -1) return -1;
688 h3 = PyObject_Hash(co->co_names);
689 if (h3 == -1) return -1;
690 h4 = PyObject_Hash(co->co_varnames);
691 if (h4 == -1) return -1;
692 h5 = PyObject_Hash(co->co_freevars);
693 if (h5 == -1) return -1;
694 h6 = PyObject_Hash(co->co_cellvars);
695 if (h6 == -1) return -1;
696 h = h0 ^ h1 ^ h2 ^ h3 ^ h4 ^ h5 ^ h6 ^
697 co->co_argcount ^ co->co_kwonlyargcount ^
698 co->co_nlocals ^ co->co_flags;
699 if (h == -1) h = -2;
700 return h;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000701}
702
703/* XXX code objects need to participate in GC? */
704
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200705static struct PyMethodDef code_methods[] = {
706 {"__sizeof__", (PyCFunction)code_sizeof, METH_NOARGS},
707 {NULL, NULL} /* sentinel */
708};
709
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000710PyTypeObject PyCode_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 PyVarObject_HEAD_INIT(&PyType_Type, 0)
712 "code",
713 sizeof(PyCodeObject),
714 0,
715 (destructor)code_dealloc, /* tp_dealloc */
716 0, /* tp_print */
717 0, /* tp_getattr */
718 0, /* tp_setattr */
719 0, /* tp_reserved */
720 (reprfunc)code_repr, /* tp_repr */
721 0, /* tp_as_number */
722 0, /* tp_as_sequence */
723 0, /* tp_as_mapping */
724 (hashfunc)code_hash, /* tp_hash */
725 0, /* tp_call */
726 0, /* tp_str */
727 PyObject_GenericGetAttr, /* tp_getattro */
728 0, /* tp_setattro */
729 0, /* tp_as_buffer */
730 Py_TPFLAGS_DEFAULT, /* tp_flags */
731 code_doc, /* tp_doc */
732 0, /* tp_traverse */
733 0, /* tp_clear */
734 code_richcompare, /* tp_richcompare */
735 offsetof(PyCodeObject, co_weakreflist), /* tp_weaklistoffset */
736 0, /* tp_iter */
737 0, /* tp_iternext */
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200738 code_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 code_memberlist, /* tp_members */
740 0, /* tp_getset */
741 0, /* tp_base */
742 0, /* tp_dict */
743 0, /* tp_descr_get */
744 0, /* tp_descr_set */
745 0, /* tp_dictoffset */
746 0, /* tp_init */
747 0, /* tp_alloc */
748 code_new, /* tp_new */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000749};
750
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000751/* Use co_lnotab to compute the line number from a bytecode index, addrq. See
752 lnotab_notes.txt for the details of the lnotab representation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000753*/
754
755int
756PyCode_Addr2Line(PyCodeObject *co, int addrq)
757{
Victor Stinner0fcab4a2011-01-04 12:59:15 +0000758 Py_ssize_t size = PyBytes_Size(co->co_lnotab) / 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 unsigned char *p = (unsigned char*)PyBytes_AsString(co->co_lnotab);
760 int line = co->co_firstlineno;
761 int addr = 0;
762 while (--size >= 0) {
763 addr += *p++;
764 if (addr > addrq)
765 break;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100766 line += (signed char)*p;
767 p++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 }
769 return line;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000770}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000771
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000772/* Update *bounds to describe the first and one-past-the-last instructions in
773 the same line as lasti. Return the number of that line. */
774int
775_PyCode_CheckLineNumber(PyCodeObject* co, int lasti, PyAddrPair *bounds)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000776{
Victor Stinner0fcab4a2011-01-04 12:59:15 +0000777 Py_ssize_t size;
778 int addr, line;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 unsigned char* p;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 p = (unsigned char*)PyBytes_AS_STRING(co->co_lnotab);
782 size = PyBytes_GET_SIZE(co->co_lnotab) / 2;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 addr = 0;
785 line = co->co_firstlineno;
786 assert(line > 0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 /* possible optimization: if f->f_lasti == instr_ub
789 (likely to be a common case) then we already know
790 instr_lb -- if we stored the matching value of p
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700791 somewhere we could skip the first while loop. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 /* See lnotab_notes.txt for the description of
794 co_lnotab. A point to remember: increments to p
795 come in (addr, line) pairs. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 bounds->ap_lower = 0;
798 while (size > 0) {
799 if (addr + *p > lasti)
800 break;
801 addr += *p++;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100802 if ((signed char)*p)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 bounds->ap_lower = addr;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100804 line += (signed char)*p;
805 p++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 --size;
807 }
808
809 if (size > 0) {
810 while (--size >= 0) {
811 addr += *p++;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100812 if ((signed char)*p)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 break;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100814 p++;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000815 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 bounds->ap_upper = addr;
817 }
818 else {
819 bounds->ap_upper = INT_MAX;
820 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 return line;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000823}
Brett Cannon5c4de282016-09-07 11:16:41 -0700824
825
826int
827_PyCode_GetExtra(PyObject *code, Py_ssize_t index, void **extra)
828{
Brett Cannon5c4de282016-09-07 11:16:41 -0700829 assert(*extra == NULL);
830
831 if (!PyCode_Check(code)) {
832 PyErr_BadInternalCall();
Brett Cannon3788b852016-09-07 12:51:08 -0700833 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -0700834 }
835
Brett Cannond0600ed2016-09-07 14:30:39 -0700836 PyCodeObject *o = (PyCodeObject*) code;
837 _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra*) o->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700838
Brett Cannond0600ed2016-09-07 14:30:39 -0700839
840 if (co_extra == NULL || co_extra->ce_size <= index) {
Brett Cannon5c4de282016-09-07 11:16:41 -0700841 return 0;
842 }
843
Brett Cannond0600ed2016-09-07 14:30:39 -0700844 *extra = co_extra->ce_extras[index];
Brett Cannon5c4de282016-09-07 11:16:41 -0700845 return 0;
846}
847
848
849int
850_PyCode_SetExtra(PyObject *code, Py_ssize_t index, void *extra)
851{
Brett Cannon5c4de282016-09-07 11:16:41 -0700852 PyThreadState *tstate = PyThreadState_Get();
853
854 if (!PyCode_Check(code) || index < 0 ||
855 index >= tstate->co_extra_user_count) {
856 PyErr_BadInternalCall();
Brett Cannon3788b852016-09-07 12:51:08 -0700857 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -0700858 }
859
Brett Cannond0600ed2016-09-07 14:30:39 -0700860 PyCodeObject *o = (PyCodeObject*) code;
861 _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra *) o->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700862
Brett Cannond0600ed2016-09-07 14:30:39 -0700863 if (co_extra == NULL) {
Brett Cannon5c4de282016-09-07 11:16:41 -0700864 o->co_extra = (_PyCodeObjectExtra*) PyMem_Malloc(
865 sizeof(_PyCodeObjectExtra));
866 if (o->co_extra == NULL) {
Brett Cannon3788b852016-09-07 12:51:08 -0700867 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -0700868 }
Brett Cannond0600ed2016-09-07 14:30:39 -0700869 co_extra = (_PyCodeObjectExtra *) o->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700870
Brett Cannond0600ed2016-09-07 14:30:39 -0700871 co_extra->ce_extras = PyMem_Malloc(
Brett Cannon5c4de282016-09-07 11:16:41 -0700872 tstate->co_extra_user_count * sizeof(void*));
Brett Cannond0600ed2016-09-07 14:30:39 -0700873 if (co_extra->ce_extras == NULL) {
Brett Cannon3788b852016-09-07 12:51:08 -0700874 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -0700875 }
876
Brett Cannond0600ed2016-09-07 14:30:39 -0700877 co_extra->ce_size = tstate->co_extra_user_count;
Brett Cannon5c4de282016-09-07 11:16:41 -0700878
Brett Cannond0600ed2016-09-07 14:30:39 -0700879 for (Py_ssize_t i = 0; i < co_extra->ce_size; i++) {
880 co_extra->ce_extras[i] = NULL;
Brett Cannon5c4de282016-09-07 11:16:41 -0700881 }
882 }
Brett Cannond0600ed2016-09-07 14:30:39 -0700883 else if (co_extra->ce_size <= index) {
884 co_extra->ce_extras = PyMem_Realloc(
885 co_extra->ce_extras, tstate->co_extra_user_count * sizeof(void*));
Brett Cannon5c4de282016-09-07 11:16:41 -0700886
Brett Cannond0600ed2016-09-07 14:30:39 -0700887 if (co_extra->ce_extras == NULL) {
Brett Cannon3788b852016-09-07 12:51:08 -0700888 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -0700889 }
890
Brett Cannond0600ed2016-09-07 14:30:39 -0700891 co_extra->ce_size = tstate->co_extra_user_count;
Brett Cannon5c4de282016-09-07 11:16:41 -0700892
Brett Cannond0600ed2016-09-07 14:30:39 -0700893 for (Py_ssize_t i = co_extra->ce_size; i < co_extra->ce_size; i++) {
894 co_extra->ce_extras[i] = NULL;
Brett Cannon5c4de282016-09-07 11:16:41 -0700895 }
896 }
897
Brett Cannond0600ed2016-09-07 14:30:39 -0700898 co_extra->ce_extras[index] = extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700899 return 0;
900}