blob: d45be4c96796e6de7547cbfffdb8a61f7b10a018 [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 Storchakaddb536b2017-09-08 10:43:54 +030025 if (!PyUnicode_IS_ASCII(o))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020026 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000028 if (ok_name_char[*name_chars] == 0) {
Serhiy Storchaka09f3d082016-10-04 18:17:22 +030029 const unsigned char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000030 for (p = name_chars; *p; p++)
31 ok_name_char[*p] = 1;
32 }
Serhiy Storchaka09f3d082016-10-04 18:17:22 +030033 s = PyUnicode_1BYTE_DATA(o);
34 e = s + PyUnicode_GET_LENGTH(o);
35 while (s != e) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000036 if (ok_name_char[*s++] == 0)
37 return 0;
38 }
39 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000040}
41
42static void
43intern_strings(PyObject *tuple)
44{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045 Py_ssize_t i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 for (i = PyTuple_GET_SIZE(tuple); --i >= 0; ) {
48 PyObject *v = PyTuple_GET_ITEM(tuple, i);
49 if (v == NULL || !PyUnicode_CheckExact(v)) {
50 Py_FatalError("non-string found in code slot");
51 }
52 PyUnicode_InternInPlace(&PyTuple_GET_ITEM(tuple, i));
53 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000054}
55
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +030056/* Intern selected string constants */
57static int
58intern_string_constants(PyObject *tuple)
59{
60 int modified = 0;
61 Py_ssize_t i;
62
63 for (i = PyTuple_GET_SIZE(tuple); --i >= 0; ) {
64 PyObject *v = PyTuple_GET_ITEM(tuple, i);
65 if (PyUnicode_CheckExact(v)) {
Serhiy Storchakaddb536b2017-09-08 10:43:54 +030066 if (PyUnicode_READY(v) == -1) {
67 PyErr_Clear();
68 continue;
69 }
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +030070 if (all_name_chars(v)) {
71 PyObject *w = v;
72 PyUnicode_InternInPlace(&v);
73 if (w != v) {
74 PyTuple_SET_ITEM(tuple, i, v);
75 modified = 1;
76 }
77 }
78 }
79 else if (PyTuple_CheckExact(v)) {
80 intern_string_constants(v);
81 }
82 else if (PyFrozenSet_CheckExact(v)) {
Yury Selivanovd2fd3592016-11-09 09:42:14 -050083 PyObject *w = v;
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +030084 PyObject *tmp = PySequence_Tuple(v);
85 if (tmp == NULL) {
86 PyErr_Clear();
87 continue;
88 }
89 if (intern_string_constants(tmp)) {
90 v = PyFrozenSet_New(tmp);
91 if (v == NULL) {
92 PyErr_Clear();
93 }
94 else {
95 PyTuple_SET_ITEM(tuple, i, v);
Yury Selivanovd2fd3592016-11-09 09:42:14 -050096 Py_DECREF(w);
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +030097 modified = 1;
98 }
99 }
100 Py_DECREF(tmp);
101 }
102 }
103 return modified;
104}
105
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000106
107PyCodeObject *
Guido van Rossum4f72a782006-10-27 23:31:49 +0000108PyCode_New(int argcount, int kwonlyargcount,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 int nlocals, int stacksize, int flags,
110 PyObject *code, PyObject *consts, PyObject *names,
111 PyObject *varnames, PyObject *freevars, PyObject *cellvars,
112 PyObject *filename, PyObject *name, int firstlineno,
113 PyObject *lnotab)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 PyCodeObject *co;
Benjamin Peterson90037602011-06-25 22:54:45 -0500116 unsigned char *cell2arg = NULL;
117 Py_ssize_t i, n_cellvars;
Guido van Rossum00bc0e02007-10-15 02:52:41 +0000118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 /* Check argument types */
120 if (argcount < 0 || kwonlyargcount < 0 || nlocals < 0 ||
121 code == NULL ||
122 consts == NULL || !PyTuple_Check(consts) ||
123 names == NULL || !PyTuple_Check(names) ||
124 varnames == NULL || !PyTuple_Check(varnames) ||
125 freevars == NULL || !PyTuple_Check(freevars) ||
126 cellvars == NULL || !PyTuple_Check(cellvars) ||
127 name == NULL || !PyUnicode_Check(name) ||
128 filename == NULL || !PyUnicode_Check(filename) ||
129 lnotab == NULL || !PyBytes_Check(lnotab) ||
130 !PyObject_CheckReadBuffer(code)) {
131 PyErr_BadInternalCall();
132 return NULL;
133 }
Victor Stinner7c74de42013-10-10 15:55:14 +0200134
135 /* Ensure that the filename is a ready Unicode string */
136 if (PyUnicode_READY(filename) < 0)
137 return NULL;
138
Benjamin Peterson90037602011-06-25 22:54:45 -0500139 n_cellvars = PyTuple_GET_SIZE(cellvars);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 intern_strings(names);
141 intern_strings(varnames);
142 intern_strings(freevars);
143 intern_strings(cellvars);
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +0300144 intern_string_constants(consts);
Benjamin Peterson90037602011-06-25 22:54:45 -0500145 /* Create mapping between cells and arguments if needed. */
146 if (n_cellvars) {
147 Py_ssize_t total_args = argcount + kwonlyargcount +
148 ((flags & CO_VARARGS) != 0) + ((flags & CO_VARKEYWORDS) != 0);
149 Py_ssize_t alloc_size = sizeof(unsigned char) * n_cellvars;
Benjamin Peterson1bf494b2016-09-07 11:28:35 -0700150 bool used_cell2arg = false;
Benjamin Peterson90037602011-06-25 22:54:45 -0500151 cell2arg = PyMem_MALLOC(alloc_size);
152 if (cell2arg == NULL)
153 return NULL;
154 memset(cell2arg, CO_CELL_NOT_AN_ARG, alloc_size);
155 /* Find cells which are also arguments. */
156 for (i = 0; i < n_cellvars; i++) {
157 Py_ssize_t j;
158 PyObject *cell = PyTuple_GET_ITEM(cellvars, i);
159 for (j = 0; j < total_args; j++) {
160 PyObject *arg = PyTuple_GET_ITEM(varnames, j);
161 if (!PyUnicode_Compare(cell, arg)) {
162 cell2arg[i] = j;
Benjamin Peterson1bf494b2016-09-07 11:28:35 -0700163 used_cell2arg = true;
Benjamin Peterson90037602011-06-25 22:54:45 -0500164 break;
165 }
166 }
167 }
168 if (!used_cell2arg) {
169 PyMem_FREE(cell2arg);
170 cell2arg = NULL;
171 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 }
Benjamin Peterson90037602011-06-25 22:54:45 -0500173 co = PyObject_NEW(PyCodeObject, &PyCode_Type);
174 if (co == NULL) {
175 if (cell2arg)
176 PyMem_FREE(cell2arg);
177 return NULL;
178 }
179 co->co_argcount = argcount;
180 co->co_kwonlyargcount = kwonlyargcount;
181 co->co_nlocals = nlocals;
182 co->co_stacksize = stacksize;
183 co->co_flags = flags;
184 Py_INCREF(code);
185 co->co_code = code;
186 Py_INCREF(consts);
187 co->co_consts = consts;
188 Py_INCREF(names);
189 co->co_names = names;
190 Py_INCREF(varnames);
191 co->co_varnames = varnames;
192 Py_INCREF(freevars);
193 co->co_freevars = freevars;
194 Py_INCREF(cellvars);
195 co->co_cellvars = cellvars;
196 co->co_cell2arg = cell2arg;
197 Py_INCREF(filename);
198 co->co_filename = filename;
199 Py_INCREF(name);
200 co->co_name = name;
201 co->co_firstlineno = firstlineno;
202 Py_INCREF(lnotab);
203 co->co_lnotab = lnotab;
204 co->co_zombieframe = NULL;
205 co->co_weakreflist = NULL;
Brett Cannon5c4de282016-09-07 11:16:41 -0700206 co->co_extra = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000208}
209
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000210PyCodeObject *
211PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno)
212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 static PyObject *emptystring = NULL;
214 static PyObject *nulltuple = NULL;
215 PyObject *filename_ob = NULL;
216 PyObject *funcname_ob = NULL;
217 PyCodeObject *result = NULL;
218 if (emptystring == NULL) {
219 emptystring = PyBytes_FromString("");
220 if (emptystring == NULL)
221 goto failed;
222 }
223 if (nulltuple == NULL) {
224 nulltuple = PyTuple_New(0);
225 if (nulltuple == NULL)
226 goto failed;
227 }
228 funcname_ob = PyUnicode_FromString(funcname);
229 if (funcname_ob == NULL)
230 goto failed;
231 filename_ob = PyUnicode_DecodeFSDefault(filename);
232 if (filename_ob == NULL)
233 goto failed;
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 result = PyCode_New(0, /* argcount */
236 0, /* kwonlyargcount */
237 0, /* nlocals */
238 0, /* stacksize */
239 0, /* flags */
240 emptystring, /* code */
241 nulltuple, /* consts */
242 nulltuple, /* names */
243 nulltuple, /* varnames */
244 nulltuple, /* freevars */
245 nulltuple, /* cellvars */
246 filename_ob, /* filename */
247 funcname_ob, /* name */
248 firstlineno, /* firstlineno */
249 emptystring /* lnotab */
250 );
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000251
252failed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 Py_XDECREF(funcname_ob);
254 Py_XDECREF(filename_ob);
255 return result;
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000256}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000257
258#define OFF(x) offsetof(PyCodeObject, x)
259
260static PyMemberDef code_memberlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 {"co_argcount", T_INT, OFF(co_argcount), READONLY},
262 {"co_kwonlyargcount", T_INT, OFF(co_kwonlyargcount), READONLY},
263 {"co_nlocals", T_INT, OFF(co_nlocals), READONLY},
264 {"co_stacksize",T_INT, OFF(co_stacksize), READONLY},
265 {"co_flags", T_INT, OFF(co_flags), READONLY},
266 {"co_code", T_OBJECT, OFF(co_code), READONLY},
267 {"co_consts", T_OBJECT, OFF(co_consts), READONLY},
268 {"co_names", T_OBJECT, OFF(co_names), READONLY},
269 {"co_varnames", T_OBJECT, OFF(co_varnames), READONLY},
270 {"co_freevars", T_OBJECT, OFF(co_freevars), READONLY},
271 {"co_cellvars", T_OBJECT, OFF(co_cellvars), READONLY},
272 {"co_filename", T_OBJECT, OFF(co_filename), READONLY},
273 {"co_name", T_OBJECT, OFF(co_name), READONLY},
274 {"co_firstlineno", T_INT, OFF(co_firstlineno), READONLY},
275 {"co_lnotab", T_OBJECT, OFF(co_lnotab), READONLY},
276 {NULL} /* Sentinel */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000277};
278
279/* Helper for code_new: return a shallow copy of a tuple that is
280 guaranteed to contain exact strings, by converting string subclasses
281 to exact strings and complaining if a non-string is found. */
282static PyObject*
283validate_and_copy_tuple(PyObject *tup)
284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 PyObject *newtuple;
286 PyObject *item;
287 Py_ssize_t i, len;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 len = PyTuple_GET_SIZE(tup);
290 newtuple = PyTuple_New(len);
291 if (newtuple == NULL)
292 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 for (i = 0; i < len; i++) {
295 item = PyTuple_GET_ITEM(tup, i);
296 if (PyUnicode_CheckExact(item)) {
297 Py_INCREF(item);
298 }
299 else if (!PyUnicode_Check(item)) {
300 PyErr_Format(
301 PyExc_TypeError,
302 "name tuples must contain only "
303 "strings, not '%.500s'",
304 item->ob_type->tp_name);
305 Py_DECREF(newtuple);
306 return NULL;
307 }
308 else {
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100309 item = _PyUnicode_Copy(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 if (item == NULL) {
311 Py_DECREF(newtuple);
312 return NULL;
313 }
314 }
315 PyTuple_SET_ITEM(newtuple, i, item);
316 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 return newtuple;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000319}
320
321PyDoc_STRVAR(code_doc,
Georg Brandl8c1a50a2009-07-18 09:07:48 +0000322"code(argcount, kwonlyargcount, nlocals, stacksize, flags, codestring,\n\
Georg Brandla1e7e132008-01-26 09:39:23 +0000323 constants, names, varnames, filename, name, firstlineno,\n\
324 lnotab[, freevars[, cellvars]])\n\
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000325\n\
326Create a code object. Not for the faint of heart.");
327
328static PyObject *
329code_new(PyTypeObject *type, PyObject *args, PyObject *kw)
330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 int argcount;
332 int kwonlyargcount;
333 int nlocals;
334 int stacksize;
335 int flags;
336 PyObject *co = NULL;
337 PyObject *code;
338 PyObject *consts;
339 PyObject *names, *ournames = NULL;
340 PyObject *varnames, *ourvarnames = NULL;
341 PyObject *freevars = NULL, *ourfreevars = NULL;
342 PyObject *cellvars = NULL, *ourcellvars = NULL;
343 PyObject *filename;
344 PyObject *name;
345 int firstlineno;
346 PyObject *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 if (!PyArg_ParseTuple(args, "iiiiiSO!O!O!UUiS|O!O!:code",
349 &argcount, &kwonlyargcount,
350 &nlocals, &stacksize, &flags,
351 &code,
352 &PyTuple_Type, &consts,
353 &PyTuple_Type, &names,
354 &PyTuple_Type, &varnames,
355 &filename, &name,
356 &firstlineno, &lnotab,
357 &PyTuple_Type, &freevars,
358 &PyTuple_Type, &cellvars))
359 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 if (argcount < 0) {
362 PyErr_SetString(
363 PyExc_ValueError,
364 "code: argcount must not be negative");
365 goto cleanup;
366 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 if (kwonlyargcount < 0) {
369 PyErr_SetString(
370 PyExc_ValueError,
371 "code: kwonlyargcount must not be negative");
372 goto cleanup;
373 }
374 if (nlocals < 0) {
375 PyErr_SetString(
376 PyExc_ValueError,
377 "code: nlocals must not be negative");
378 goto cleanup;
379 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 ournames = validate_and_copy_tuple(names);
382 if (ournames == NULL)
383 goto cleanup;
384 ourvarnames = validate_and_copy_tuple(varnames);
385 if (ourvarnames == NULL)
386 goto cleanup;
387 if (freevars)
388 ourfreevars = validate_and_copy_tuple(freevars);
389 else
390 ourfreevars = PyTuple_New(0);
391 if (ourfreevars == NULL)
392 goto cleanup;
393 if (cellvars)
394 ourcellvars = validate_and_copy_tuple(cellvars);
395 else
396 ourcellvars = PyTuple_New(0);
397 if (ourcellvars == NULL)
398 goto cleanup;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 co = (PyObject *)PyCode_New(argcount, kwonlyargcount,
401 nlocals, stacksize, flags,
402 code, consts, ournames, ourvarnames,
403 ourfreevars, ourcellvars, filename,
404 name, firstlineno, lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000405 cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 Py_XDECREF(ournames);
407 Py_XDECREF(ourvarnames);
408 Py_XDECREF(ourfreevars);
409 Py_XDECREF(ourcellvars);
410 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000411}
412
413static void
414code_dealloc(PyCodeObject *co)
415{
Brett Cannon5c4de282016-09-07 11:16:41 -0700416 if (co->co_extra != NULL) {
Dino Viehland2997fec2017-06-12 18:46:35 -0700417 __PyCodeExtraState *state = __PyCodeExtraState_Get();
Brett Cannond0600ed2016-09-07 14:30:39 -0700418 _PyCodeObjectExtra *co_extra = co->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700419
Brett Cannond0600ed2016-09-07 14:30:39 -0700420 for (Py_ssize_t i = 0; i < co_extra->ce_size; i++) {
Dino Viehland2997fec2017-06-12 18:46:35 -0700421 freefunc free_extra = state->co_extra_freefuncs[i];
Brett Cannon5c4de282016-09-07 11:16:41 -0700422
423 if (free_extra != NULL) {
Brett Cannond0600ed2016-09-07 14:30:39 -0700424 free_extra(co_extra->ce_extras[i]);
Brett Cannon5c4de282016-09-07 11:16:41 -0700425 }
426 }
427
Victor Stinner26daad42017-06-28 02:28:51 +0200428 PyMem_Free(co_extra->ce_extras);
429 PyMem_Free(co_extra);
Brett Cannon5c4de282016-09-07 11:16:41 -0700430 }
431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 Py_XDECREF(co->co_code);
433 Py_XDECREF(co->co_consts);
434 Py_XDECREF(co->co_names);
435 Py_XDECREF(co->co_varnames);
436 Py_XDECREF(co->co_freevars);
437 Py_XDECREF(co->co_cellvars);
438 Py_XDECREF(co->co_filename);
439 Py_XDECREF(co->co_name);
440 Py_XDECREF(co->co_lnotab);
Benjamin Peterson90037602011-06-25 22:54:45 -0500441 if (co->co_cell2arg != NULL)
442 PyMem_FREE(co->co_cell2arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 if (co->co_zombieframe != NULL)
444 PyObject_GC_Del(co->co_zombieframe);
445 if (co->co_weakreflist != NULL)
446 PyObject_ClearWeakRefs((PyObject*)co);
447 PyObject_DEL(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000448}
449
450static PyObject *
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200451code_sizeof(PyCodeObject *co, void *unused)
452{
Dong-hee Nadf5df132017-04-20 17:26:25 +0900453 Py_ssize_t res = _PyObject_SIZE(Py_TYPE(co));
454 _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra*) co->co_extra;
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200455
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200456 if (co->co_cell2arg != NULL && co->co_cellvars != NULL)
Dong-hee Nadf5df132017-04-20 17:26:25 +0900457 res += PyTuple_GET_SIZE(co->co_cellvars) * sizeof(Py_ssize_t);
458
459 if (co_extra != NULL)
460 res += co_extra->ce_size * sizeof(co_extra->ce_extras[0]);
461
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200462 return PyLong_FromSsize_t(res);
463}
464
465static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000466code_repr(PyCodeObject *co)
467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 int lineno;
469 if (co->co_firstlineno != 0)
470 lineno = co->co_firstlineno;
471 else
472 lineno = -1;
473 if (co->co_filename && PyUnicode_Check(co->co_filename)) {
474 return PyUnicode_FromFormat(
Victor Stinneraaa4e9a2011-01-05 03:33:26 +0000475 "<code object %U at %p, file \"%U\", line %d>",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 co->co_name, co, co->co_filename, lineno);
477 } else {
478 return PyUnicode_FromFormat(
Victor Stinneraaa4e9a2011-01-05 03:33:26 +0000479 "<code object %U at %p, file ???, line %d>",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 co->co_name, co, lineno);
481 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000482}
483
Victor Stinnerefb24132016-01-22 12:33:12 +0100484PyObject*
485_PyCode_ConstantKey(PyObject *op)
486{
487 PyObject *key;
488
489 /* Py_None and Py_Ellipsis are singleton */
490 if (op == Py_None || op == Py_Ellipsis
491 || PyLong_CheckExact(op)
492 || PyBool_Check(op)
493 || PyBytes_CheckExact(op)
494 || PyUnicode_CheckExact(op)
495 /* code_richcompare() uses _PyCode_ConstantKey() internally */
496 || PyCode_Check(op)) {
497 key = PyTuple_Pack(2, Py_TYPE(op), op);
498 }
499 else if (PyFloat_CheckExact(op)) {
500 double d = PyFloat_AS_DOUBLE(op);
501 /* all we need is to make the tuple different in either the 0.0
502 * or -0.0 case from all others, just to avoid the "coercion".
503 */
504 if (d == 0.0 && copysign(1.0, d) < 0.0)
505 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
506 else
507 key = PyTuple_Pack(2, Py_TYPE(op), op);
508 }
509 else if (PyComplex_CheckExact(op)) {
510 Py_complex z;
511 int real_negzero, imag_negzero;
512 /* For the complex case we must make complex(x, 0.)
513 different from complex(x, -0.) and complex(0., y)
514 different from complex(-0., y), for any x and y.
515 All four complex zeros must be distinguished.*/
516 z = PyComplex_AsCComplex(op);
517 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
518 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
519 /* use True, False and None singleton as tags for the real and imag
520 * sign, to make tuples different */
521 if (real_negzero && imag_negzero) {
522 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_True);
523 }
524 else if (imag_negzero) {
525 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_False);
526 }
527 else if (real_negzero) {
528 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
529 }
530 else {
531 key = PyTuple_Pack(2, Py_TYPE(op), op);
532 }
533 }
534 else if (PyTuple_CheckExact(op)) {
535 Py_ssize_t i, len;
536 PyObject *tuple;
537
538 len = PyTuple_GET_SIZE(op);
539 tuple = PyTuple_New(len);
540 if (tuple == NULL)
541 return NULL;
542
543 for (i=0; i < len; i++) {
544 PyObject *item, *item_key;
545
546 item = PyTuple_GET_ITEM(op, i);
547 item_key = _PyCode_ConstantKey(item);
548 if (item_key == NULL) {
549 Py_DECREF(tuple);
550 return NULL;
551 }
552
553 PyTuple_SET_ITEM(tuple, i, item_key);
554 }
555
Serhiy Storchaka713640c2017-01-24 20:49:26 +0200556 key = PyTuple_Pack(2, tuple, op);
Victor Stinnerefb24132016-01-22 12:33:12 +0100557 Py_DECREF(tuple);
558 }
559 else if (PyFrozenSet_CheckExact(op)) {
560 Py_ssize_t pos = 0;
561 PyObject *item;
562 Py_hash_t hash;
563 Py_ssize_t i, len;
564 PyObject *tuple, *set;
565
566 len = PySet_GET_SIZE(op);
567 tuple = PyTuple_New(len);
568 if (tuple == NULL)
569 return NULL;
570
571 i = 0;
572 while (_PySet_NextEntry(op, &pos, &item, &hash)) {
573 PyObject *item_key;
574
575 item_key = _PyCode_ConstantKey(item);
576 if (item_key == NULL) {
577 Py_DECREF(tuple);
578 return NULL;
579 }
580
581 assert(i < len);
582 PyTuple_SET_ITEM(tuple, i, item_key);
583 i++;
584 }
585 set = PyFrozenSet_New(tuple);
586 Py_DECREF(tuple);
587 if (set == NULL)
588 return NULL;
589
Serhiy Storchaka713640c2017-01-24 20:49:26 +0200590 key = PyTuple_Pack(2, set, op);
Victor Stinnerefb24132016-01-22 12:33:12 +0100591 Py_DECREF(set);
592 return key;
593 }
594 else {
Martin Panter6245cb32016-04-15 02:14:19 +0000595 /* for other types, use the object identifier as a unique identifier
Victor Stinnerefb24132016-01-22 12:33:12 +0100596 * to ensure that they are seen as unequal. */
597 PyObject *obj_id = PyLong_FromVoidPtr(op);
598 if (obj_id == NULL)
599 return NULL;
600
Serhiy Storchaka713640c2017-01-24 20:49:26 +0200601 key = PyTuple_Pack(2, obj_id, op);
Victor Stinnerefb24132016-01-22 12:33:12 +0100602 Py_DECREF(obj_id);
603 }
604 return key;
605}
606
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000607static PyObject *
608code_richcompare(PyObject *self, PyObject *other, int op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 PyCodeObject *co, *cp;
611 int eq;
Victor Stinnerefb24132016-01-22 12:33:12 +0100612 PyObject *consts1, *consts2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 if ((op != Py_EQ && op != Py_NE) ||
616 !PyCode_Check(self) ||
617 !PyCode_Check(other)) {
Brian Curtindfc80e32011-08-10 20:28:54 -0500618 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 co = (PyCodeObject *)self;
622 cp = (PyCodeObject *)other;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 eq = PyObject_RichCompareBool(co->co_name, cp->co_name, Py_EQ);
625 if (eq <= 0) goto unequal;
626 eq = co->co_argcount == cp->co_argcount;
627 if (!eq) goto unequal;
628 eq = co->co_kwonlyargcount == cp->co_kwonlyargcount;
629 if (!eq) goto unequal;
630 eq = co->co_nlocals == cp->co_nlocals;
631 if (!eq) goto unequal;
632 eq = co->co_flags == cp->co_flags;
633 if (!eq) goto unequal;
634 eq = co->co_firstlineno == cp->co_firstlineno;
635 if (!eq) goto unequal;
636 eq = PyObject_RichCompareBool(co->co_code, cp->co_code, Py_EQ);
637 if (eq <= 0) goto unequal;
Victor Stinnerefb24132016-01-22 12:33:12 +0100638
639 /* compare constants */
640 consts1 = _PyCode_ConstantKey(co->co_consts);
641 if (!consts1)
642 return NULL;
643 consts2 = _PyCode_ConstantKey(cp->co_consts);
644 if (!consts2) {
645 Py_DECREF(consts1);
646 return NULL;
647 }
648 eq = PyObject_RichCompareBool(consts1, consts2, Py_EQ);
649 Py_DECREF(consts1);
650 Py_DECREF(consts2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 if (eq <= 0) goto unequal;
Victor Stinnerefb24132016-01-22 12:33:12 +0100652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 eq = PyObject_RichCompareBool(co->co_names, cp->co_names, Py_EQ);
654 if (eq <= 0) goto unequal;
655 eq = PyObject_RichCompareBool(co->co_varnames, cp->co_varnames, Py_EQ);
656 if (eq <= 0) goto unequal;
657 eq = PyObject_RichCompareBool(co->co_freevars, cp->co_freevars, Py_EQ);
658 if (eq <= 0) goto unequal;
659 eq = PyObject_RichCompareBool(co->co_cellvars, cp->co_cellvars, Py_EQ);
660 if (eq <= 0) goto unequal;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 if (op == Py_EQ)
663 res = Py_True;
664 else
665 res = Py_False;
666 goto done;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000667
668 unequal:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 if (eq < 0)
670 return NULL;
671 if (op == Py_NE)
672 res = Py_True;
673 else
674 res = Py_False;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000675
676 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 Py_INCREF(res);
678 return res;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000679}
680
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000681static Py_hash_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000682code_hash(PyCodeObject *co)
683{
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000684 Py_hash_t h, h0, h1, h2, h3, h4, h5, h6;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 h0 = PyObject_Hash(co->co_name);
686 if (h0 == -1) return -1;
687 h1 = PyObject_Hash(co->co_code);
688 if (h1 == -1) return -1;
689 h2 = PyObject_Hash(co->co_consts);
690 if (h2 == -1) return -1;
691 h3 = PyObject_Hash(co->co_names);
692 if (h3 == -1) return -1;
693 h4 = PyObject_Hash(co->co_varnames);
694 if (h4 == -1) return -1;
695 h5 = PyObject_Hash(co->co_freevars);
696 if (h5 == -1) return -1;
697 h6 = PyObject_Hash(co->co_cellvars);
698 if (h6 == -1) return -1;
699 h = h0 ^ h1 ^ h2 ^ h3 ^ h4 ^ h5 ^ h6 ^
700 co->co_argcount ^ co->co_kwonlyargcount ^
701 co->co_nlocals ^ co->co_flags;
702 if (h == -1) h = -2;
703 return h;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000704}
705
706/* XXX code objects need to participate in GC? */
707
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200708static struct PyMethodDef code_methods[] = {
709 {"__sizeof__", (PyCFunction)code_sizeof, METH_NOARGS},
710 {NULL, NULL} /* sentinel */
711};
712
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000713PyTypeObject PyCode_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 PyVarObject_HEAD_INIT(&PyType_Type, 0)
715 "code",
716 sizeof(PyCodeObject),
717 0,
718 (destructor)code_dealloc, /* tp_dealloc */
719 0, /* tp_print */
720 0, /* tp_getattr */
721 0, /* tp_setattr */
722 0, /* tp_reserved */
723 (reprfunc)code_repr, /* tp_repr */
724 0, /* tp_as_number */
725 0, /* tp_as_sequence */
726 0, /* tp_as_mapping */
727 (hashfunc)code_hash, /* tp_hash */
728 0, /* tp_call */
729 0, /* tp_str */
730 PyObject_GenericGetAttr, /* tp_getattro */
731 0, /* tp_setattro */
732 0, /* tp_as_buffer */
733 Py_TPFLAGS_DEFAULT, /* tp_flags */
734 code_doc, /* tp_doc */
735 0, /* tp_traverse */
736 0, /* tp_clear */
737 code_richcompare, /* tp_richcompare */
738 offsetof(PyCodeObject, co_weakreflist), /* tp_weaklistoffset */
739 0, /* tp_iter */
740 0, /* tp_iternext */
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200741 code_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 code_memberlist, /* tp_members */
743 0, /* tp_getset */
744 0, /* tp_base */
745 0, /* tp_dict */
746 0, /* tp_descr_get */
747 0, /* tp_descr_set */
748 0, /* tp_dictoffset */
749 0, /* tp_init */
750 0, /* tp_alloc */
751 code_new, /* tp_new */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000752};
753
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000754/* Use co_lnotab to compute the line number from a bytecode index, addrq. See
755 lnotab_notes.txt for the details of the lnotab representation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000756*/
757
758int
759PyCode_Addr2Line(PyCodeObject *co, int addrq)
760{
Victor Stinner0fcab4a2011-01-04 12:59:15 +0000761 Py_ssize_t size = PyBytes_Size(co->co_lnotab) / 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 unsigned char *p = (unsigned char*)PyBytes_AsString(co->co_lnotab);
763 int line = co->co_firstlineno;
764 int addr = 0;
765 while (--size >= 0) {
766 addr += *p++;
767 if (addr > addrq)
768 break;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100769 line += (signed char)*p;
770 p++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 }
772 return line;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000773}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000774
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000775/* Update *bounds to describe the first and one-past-the-last instructions in
776 the same line as lasti. Return the number of that line. */
777int
778_PyCode_CheckLineNumber(PyCodeObject* co, int lasti, PyAddrPair *bounds)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000779{
Victor Stinner0fcab4a2011-01-04 12:59:15 +0000780 Py_ssize_t size;
781 int addr, line;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 unsigned char* p;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 p = (unsigned char*)PyBytes_AS_STRING(co->co_lnotab);
785 size = PyBytes_GET_SIZE(co->co_lnotab) / 2;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 addr = 0;
788 line = co->co_firstlineno;
789 assert(line > 0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 /* possible optimization: if f->f_lasti == instr_ub
792 (likely to be a common case) then we already know
793 instr_lb -- if we stored the matching value of p
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700794 somewhere we could skip the first while loop. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 /* See lnotab_notes.txt for the description of
797 co_lnotab. A point to remember: increments to p
798 come in (addr, line) pairs. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 bounds->ap_lower = 0;
801 while (size > 0) {
802 if (addr + *p > lasti)
803 break;
804 addr += *p++;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100805 if ((signed char)*p)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 bounds->ap_lower = addr;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100807 line += (signed char)*p;
808 p++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 --size;
810 }
811
812 if (size > 0) {
813 while (--size >= 0) {
814 addr += *p++;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100815 if ((signed char)*p)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 break;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100817 p++;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000818 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 bounds->ap_upper = addr;
820 }
821 else {
822 bounds->ap_upper = INT_MAX;
823 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 return line;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000826}
Brett Cannon5c4de282016-09-07 11:16:41 -0700827
828
829int
830_PyCode_GetExtra(PyObject *code, Py_ssize_t index, void **extra)
831{
Brett Cannon5c4de282016-09-07 11:16:41 -0700832 if (!PyCode_Check(code)) {
833 PyErr_BadInternalCall();
Brett Cannon3788b852016-09-07 12:51:08 -0700834 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -0700835 }
836
Brett Cannond0600ed2016-09-07 14:30:39 -0700837 PyCodeObject *o = (PyCodeObject*) code;
838 _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra*) o->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700839
Brett Cannond0600ed2016-09-07 14:30:39 -0700840
841 if (co_extra == NULL || co_extra->ce_size <= index) {
Dino Viehland2997fec2017-06-12 18:46:35 -0700842 *extra = NULL;
Brett Cannon5c4de282016-09-07 11:16:41 -0700843 return 0;
844 }
845
Brett Cannond0600ed2016-09-07 14:30:39 -0700846 *extra = co_extra->ce_extras[index];
Brett Cannon5c4de282016-09-07 11:16:41 -0700847 return 0;
848}
849
850
851int
852_PyCode_SetExtra(PyObject *code, Py_ssize_t index, void *extra)
853{
Dino Viehland2997fec2017-06-12 18:46:35 -0700854 __PyCodeExtraState *state = __PyCodeExtraState_Get();
Brett Cannon5c4de282016-09-07 11:16:41 -0700855
856 if (!PyCode_Check(code) || index < 0 ||
Dino Viehland2997fec2017-06-12 18:46:35 -0700857 index >= state->co_extra_user_count) {
Brett Cannon5c4de282016-09-07 11:16:41 -0700858 PyErr_BadInternalCall();
Brett Cannon3788b852016-09-07 12:51:08 -0700859 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -0700860 }
861
Brett Cannond0600ed2016-09-07 14:30:39 -0700862 PyCodeObject *o = (PyCodeObject*) code;
863 _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra *) o->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700864
Brett Cannond0600ed2016-09-07 14:30:39 -0700865 if (co_extra == NULL) {
Brian Colemana6e84932017-03-02 22:21:53 +0000866 co_extra = PyMem_Malloc(sizeof(_PyCodeObjectExtra));
867 if (co_extra == 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_extras = PyMem_Malloc(
Dino Viehland2997fec2017-06-12 18:46:35 -0700872 state->co_extra_user_count * sizeof(void*));
Brett Cannond0600ed2016-09-07 14:30:39 -0700873 if (co_extra->ce_extras == NULL) {
Brian Colemana6e84932017-03-02 22:21:53 +0000874 PyMem_Free(co_extra);
Brett Cannon3788b852016-09-07 12:51:08 -0700875 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -0700876 }
877
Dino Viehland2997fec2017-06-12 18:46:35 -0700878 co_extra->ce_size = state->co_extra_user_count;
Brett Cannon5c4de282016-09-07 11:16:41 -0700879
Brett Cannond0600ed2016-09-07 14:30:39 -0700880 for (Py_ssize_t i = 0; i < co_extra->ce_size; i++) {
881 co_extra->ce_extras[i] = NULL;
Brett Cannon5c4de282016-09-07 11:16:41 -0700882 }
Brian Colemana6e84932017-03-02 22:21:53 +0000883
884 o->co_extra = co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700885 }
Brett Cannond0600ed2016-09-07 14:30:39 -0700886 else if (co_extra->ce_size <= index) {
Brian Colemana6e84932017-03-02 22:21:53 +0000887 void** ce_extras = PyMem_Realloc(
Dino Viehland2997fec2017-06-12 18:46:35 -0700888 co_extra->ce_extras, state->co_extra_user_count * sizeof(void*));
Brett Cannon5c4de282016-09-07 11:16:41 -0700889
Brian Colemana6e84932017-03-02 22:21:53 +0000890 if (ce_extras == NULL) {
Brett Cannon3788b852016-09-07 12:51:08 -0700891 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -0700892 }
893
Brian Colemana6e84932017-03-02 22:21:53 +0000894 for (Py_ssize_t i = co_extra->ce_size;
Dino Viehland2997fec2017-06-12 18:46:35 -0700895 i < state->co_extra_user_count;
Brian Colemana6e84932017-03-02 22:21:53 +0000896 i++) {
897 ce_extras[i] = NULL;
Brett Cannon5c4de282016-09-07 11:16:41 -0700898 }
Brian Colemana6e84932017-03-02 22:21:53 +0000899
900 co_extra->ce_extras = ce_extras;
Dino Viehland2997fec2017-06-12 18:46:35 -0700901 co_extra->ce_size = state->co_extra_user_count;
902 }
903
904 if (co_extra->ce_extras[index] != NULL) {
905 freefunc free = state->co_extra_freefuncs[index];
906 if (free != NULL) {
907 free(co_extra->ce_extras[index]);
908 }
Brett Cannon5c4de282016-09-07 11:16:41 -0700909 }
910
Brett Cannond0600ed2016-09-07 14:30:39 -0700911 co_extra->ce_extras[index] = extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700912 return 0;
913}