blob: f312f338a9b4eba1a11633004243c4699054eb2a [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
Brett Cannond0600ed2016-09-07 14:30:39 -07007/* Holder for co_extra information */
8typedef struct {
9 Py_ssize_t ce_size;
Serhiy Storchaka378ebb62017-07-04 15:06:16 +030010 void *ce_extras[1];
Brett Cannond0600ed2016-09-07 14:30:39 -070011} _PyCodeObjectExtra;
12
Benjamin Peterson8e0ad462017-09-07 23:35:53 -070013/* all_name_chars(s): true iff s matches [a-zA-Z0-9_]* */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000014static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015all_name_chars(PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000016{
Serhiy Storchaka09f3d082016-10-04 18:17:22 +030017 const unsigned char *s, *e;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020018
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030019 if (!PyUnicode_IS_ASCII(o))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020020 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000021
Serhiy Storchaka09f3d082016-10-04 18:17:22 +030022 s = PyUnicode_1BYTE_DATA(o);
23 e = s + PyUnicode_GET_LENGTH(o);
Benjamin Peterson9020ac72017-09-07 18:06:23 -070024 for (; s != e; s++) {
Benjamin Peterson2b7953d2017-09-08 10:35:49 -070025 if (!Py_ISALNUM(*s) && *s != '_')
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000026 return 0;
27 }
28 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000029}
30
31static void
32intern_strings(PyObject *tuple)
33{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000034 Py_ssize_t i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000036 for (i = PyTuple_GET_SIZE(tuple); --i >= 0; ) {
37 PyObject *v = PyTuple_GET_ITEM(tuple, i);
38 if (v == NULL || !PyUnicode_CheckExact(v)) {
39 Py_FatalError("non-string found in code slot");
40 }
41 PyUnicode_InternInPlace(&PyTuple_GET_ITEM(tuple, i));
42 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000043}
44
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +030045/* Intern selected string constants */
46static int
47intern_string_constants(PyObject *tuple)
48{
49 int modified = 0;
50 Py_ssize_t i;
51
52 for (i = PyTuple_GET_SIZE(tuple); --i >= 0; ) {
53 PyObject *v = PyTuple_GET_ITEM(tuple, i);
54 if (PyUnicode_CheckExact(v)) {
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030055 if (PyUnicode_READY(v) == -1) {
56 PyErr_Clear();
57 continue;
58 }
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +030059 if (all_name_chars(v)) {
60 PyObject *w = v;
61 PyUnicode_InternInPlace(&v);
62 if (w != v) {
63 PyTuple_SET_ITEM(tuple, i, v);
64 modified = 1;
65 }
66 }
67 }
68 else if (PyTuple_CheckExact(v)) {
69 intern_string_constants(v);
70 }
71 else if (PyFrozenSet_CheckExact(v)) {
Yury Selivanovd2fd3592016-11-09 09:42:14 -050072 PyObject *w = v;
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +030073 PyObject *tmp = PySequence_Tuple(v);
74 if (tmp == NULL) {
75 PyErr_Clear();
76 continue;
77 }
78 if (intern_string_constants(tmp)) {
79 v = PyFrozenSet_New(tmp);
80 if (v == NULL) {
81 PyErr_Clear();
82 }
83 else {
84 PyTuple_SET_ITEM(tuple, i, v);
Yury Selivanovd2fd3592016-11-09 09:42:14 -050085 Py_DECREF(w);
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +030086 modified = 1;
87 }
88 }
89 Py_DECREF(tmp);
90 }
91 }
92 return modified;
93}
94
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000095
96PyCodeObject *
Guido van Rossum4f72a782006-10-27 23:31:49 +000097PyCode_New(int argcount, int kwonlyargcount,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000098 int nlocals, int stacksize, int flags,
99 PyObject *code, PyObject *consts, PyObject *names,
100 PyObject *varnames, PyObject *freevars, PyObject *cellvars,
101 PyObject *filename, PyObject *name, int firstlineno,
102 PyObject *lnotab)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000103{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 PyCodeObject *co;
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200105 Py_ssize_t *cell2arg = NULL;
Benjamin Peterson90037602011-06-25 22:54:45 -0500106 Py_ssize_t i, n_cellvars;
Guido van Rossum00bc0e02007-10-15 02:52:41 +0000107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 /* Check argument types */
109 if (argcount < 0 || kwonlyargcount < 0 || nlocals < 0 ||
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +0200110 code == NULL || !PyBytes_Check(code) ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 consts == NULL || !PyTuple_Check(consts) ||
112 names == NULL || !PyTuple_Check(names) ||
113 varnames == NULL || !PyTuple_Check(varnames) ||
114 freevars == NULL || !PyTuple_Check(freevars) ||
115 cellvars == NULL || !PyTuple_Check(cellvars) ||
116 name == NULL || !PyUnicode_Check(name) ||
117 filename == NULL || !PyUnicode_Check(filename) ||
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +0200118 lnotab == NULL || !PyBytes_Check(lnotab)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 PyErr_BadInternalCall();
120 return NULL;
121 }
Victor Stinner7c74de42013-10-10 15:55:14 +0200122
123 /* Ensure that the filename is a ready Unicode string */
124 if (PyUnicode_READY(filename) < 0)
125 return NULL;
126
Benjamin Peterson90037602011-06-25 22:54:45 -0500127 n_cellvars = PyTuple_GET_SIZE(cellvars);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 intern_strings(names);
129 intern_strings(varnames);
130 intern_strings(freevars);
131 intern_strings(cellvars);
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +0300132 intern_string_constants(consts);
Benjamin Peterson90037602011-06-25 22:54:45 -0500133 /* Create mapping between cells and arguments if needed. */
134 if (n_cellvars) {
135 Py_ssize_t total_args = argcount + kwonlyargcount +
136 ((flags & CO_VARARGS) != 0) + ((flags & CO_VARKEYWORDS) != 0);
Benjamin Peterson1bf494b2016-09-07 11:28:35 -0700137 bool used_cell2arg = false;
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200138 cell2arg = PyMem_NEW(Py_ssize_t, n_cellvars);
139 if (cell2arg == NULL) {
140 PyErr_NoMemory();
Benjamin Peterson90037602011-06-25 22:54:45 -0500141 return NULL;
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200142 }
Benjamin Peterson90037602011-06-25 22:54:45 -0500143 /* Find cells which are also arguments. */
144 for (i = 0; i < n_cellvars; i++) {
145 Py_ssize_t j;
146 PyObject *cell = PyTuple_GET_ITEM(cellvars, i);
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200147 cell2arg[i] = CO_CELL_NOT_AN_ARG;
Benjamin Peterson90037602011-06-25 22:54:45 -0500148 for (j = 0; j < total_args; j++) {
149 PyObject *arg = PyTuple_GET_ITEM(varnames, j);
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200150 int cmp = PyUnicode_Compare(cell, arg);
151 if (cmp == -1 && PyErr_Occurred()) {
152 PyMem_FREE(cell2arg);
153 return NULL;
154 }
155 if (cmp == 0) {
Benjamin Peterson90037602011-06-25 22:54:45 -0500156 cell2arg[i] = j;
Benjamin Peterson1bf494b2016-09-07 11:28:35 -0700157 used_cell2arg = true;
Benjamin Peterson90037602011-06-25 22:54:45 -0500158 break;
159 }
160 }
161 }
162 if (!used_cell2arg) {
163 PyMem_FREE(cell2arg);
164 cell2arg = NULL;
165 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 }
Benjamin Peterson90037602011-06-25 22:54:45 -0500167 co = PyObject_NEW(PyCodeObject, &PyCode_Type);
168 if (co == NULL) {
169 if (cell2arg)
170 PyMem_FREE(cell2arg);
171 return NULL;
172 }
173 co->co_argcount = argcount;
174 co->co_kwonlyargcount = kwonlyargcount;
175 co->co_nlocals = nlocals;
176 co->co_stacksize = stacksize;
177 co->co_flags = flags;
178 Py_INCREF(code);
179 co->co_code = code;
180 Py_INCREF(consts);
181 co->co_consts = consts;
182 Py_INCREF(names);
183 co->co_names = names;
184 Py_INCREF(varnames);
185 co->co_varnames = varnames;
186 Py_INCREF(freevars);
187 co->co_freevars = freevars;
188 Py_INCREF(cellvars);
189 co->co_cellvars = cellvars;
190 co->co_cell2arg = cell2arg;
191 Py_INCREF(filename);
192 co->co_filename = filename;
193 Py_INCREF(name);
194 co->co_name = name;
195 co->co_firstlineno = firstlineno;
196 Py_INCREF(lnotab);
197 co->co_lnotab = lnotab;
198 co->co_zombieframe = NULL;
199 co->co_weakreflist = NULL;
Brett Cannon5c4de282016-09-07 11:16:41 -0700200 co->co_extra = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000202}
203
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000204PyCodeObject *
205PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno)
206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 static PyObject *emptystring = NULL;
208 static PyObject *nulltuple = NULL;
209 PyObject *filename_ob = NULL;
210 PyObject *funcname_ob = NULL;
211 PyCodeObject *result = NULL;
212 if (emptystring == NULL) {
213 emptystring = PyBytes_FromString("");
214 if (emptystring == NULL)
215 goto failed;
216 }
217 if (nulltuple == NULL) {
218 nulltuple = PyTuple_New(0);
219 if (nulltuple == NULL)
220 goto failed;
221 }
222 funcname_ob = PyUnicode_FromString(funcname);
223 if (funcname_ob == NULL)
224 goto failed;
225 filename_ob = PyUnicode_DecodeFSDefault(filename);
226 if (filename_ob == NULL)
227 goto failed;
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 result = PyCode_New(0, /* argcount */
230 0, /* kwonlyargcount */
231 0, /* nlocals */
232 0, /* stacksize */
233 0, /* flags */
234 emptystring, /* code */
235 nulltuple, /* consts */
236 nulltuple, /* names */
237 nulltuple, /* varnames */
238 nulltuple, /* freevars */
239 nulltuple, /* cellvars */
240 filename_ob, /* filename */
241 funcname_ob, /* name */
242 firstlineno, /* firstlineno */
243 emptystring /* lnotab */
244 );
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000245
246failed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 Py_XDECREF(funcname_ob);
248 Py_XDECREF(filename_ob);
249 return result;
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000250}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000251
252#define OFF(x) offsetof(PyCodeObject, x)
253
254static PyMemberDef code_memberlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 {"co_argcount", T_INT, OFF(co_argcount), READONLY},
256 {"co_kwonlyargcount", T_INT, OFF(co_kwonlyargcount), READONLY},
257 {"co_nlocals", T_INT, OFF(co_nlocals), READONLY},
258 {"co_stacksize",T_INT, OFF(co_stacksize), READONLY},
259 {"co_flags", T_INT, OFF(co_flags), READONLY},
260 {"co_code", T_OBJECT, OFF(co_code), READONLY},
261 {"co_consts", T_OBJECT, OFF(co_consts), READONLY},
262 {"co_names", T_OBJECT, OFF(co_names), READONLY},
263 {"co_varnames", T_OBJECT, OFF(co_varnames), READONLY},
264 {"co_freevars", T_OBJECT, OFF(co_freevars), READONLY},
265 {"co_cellvars", T_OBJECT, OFF(co_cellvars), READONLY},
266 {"co_filename", T_OBJECT, OFF(co_filename), READONLY},
267 {"co_name", T_OBJECT, OFF(co_name), READONLY},
268 {"co_firstlineno", T_INT, OFF(co_firstlineno), READONLY},
269 {"co_lnotab", T_OBJECT, OFF(co_lnotab), READONLY},
270 {NULL} /* Sentinel */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000271};
272
273/* Helper for code_new: return a shallow copy of a tuple that is
274 guaranteed to contain exact strings, by converting string subclasses
275 to exact strings and complaining if a non-string is found. */
276static PyObject*
277validate_and_copy_tuple(PyObject *tup)
278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 PyObject *newtuple;
280 PyObject *item;
281 Py_ssize_t i, len;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 len = PyTuple_GET_SIZE(tup);
284 newtuple = PyTuple_New(len);
285 if (newtuple == NULL)
286 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 for (i = 0; i < len; i++) {
289 item = PyTuple_GET_ITEM(tup, i);
290 if (PyUnicode_CheckExact(item)) {
291 Py_INCREF(item);
292 }
293 else if (!PyUnicode_Check(item)) {
294 PyErr_Format(
295 PyExc_TypeError,
296 "name tuples must contain only "
297 "strings, not '%.500s'",
298 item->ob_type->tp_name);
299 Py_DECREF(newtuple);
300 return NULL;
301 }
302 else {
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100303 item = _PyUnicode_Copy(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 if (item == NULL) {
305 Py_DECREF(newtuple);
306 return NULL;
307 }
308 }
309 PyTuple_SET_ITEM(newtuple, i, item);
310 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 return newtuple;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000313}
314
315PyDoc_STRVAR(code_doc,
Georg Brandl8c1a50a2009-07-18 09:07:48 +0000316"code(argcount, kwonlyargcount, nlocals, stacksize, flags, codestring,\n\
Georg Brandla1e7e132008-01-26 09:39:23 +0000317 constants, names, varnames, filename, name, firstlineno,\n\
318 lnotab[, freevars[, cellvars]])\n\
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000319\n\
320Create a code object. Not for the faint of heart.");
321
322static PyObject *
323code_new(PyTypeObject *type, PyObject *args, PyObject *kw)
324{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 int argcount;
326 int kwonlyargcount;
327 int nlocals;
328 int stacksize;
329 int flags;
330 PyObject *co = NULL;
331 PyObject *code;
332 PyObject *consts;
333 PyObject *names, *ournames = NULL;
334 PyObject *varnames, *ourvarnames = NULL;
335 PyObject *freevars = NULL, *ourfreevars = NULL;
336 PyObject *cellvars = NULL, *ourcellvars = NULL;
337 PyObject *filename;
338 PyObject *name;
339 int firstlineno;
340 PyObject *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 if (!PyArg_ParseTuple(args, "iiiiiSO!O!O!UUiS|O!O!:code",
343 &argcount, &kwonlyargcount,
344 &nlocals, &stacksize, &flags,
345 &code,
346 &PyTuple_Type, &consts,
347 &PyTuple_Type, &names,
348 &PyTuple_Type, &varnames,
349 &filename, &name,
350 &firstlineno, &lnotab,
351 &PyTuple_Type, &freevars,
352 &PyTuple_Type, &cellvars))
353 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 if (argcount < 0) {
356 PyErr_SetString(
357 PyExc_ValueError,
358 "code: argcount must not be negative");
359 goto cleanup;
360 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 if (kwonlyargcount < 0) {
363 PyErr_SetString(
364 PyExc_ValueError,
365 "code: kwonlyargcount must not be negative");
366 goto cleanup;
367 }
368 if (nlocals < 0) {
369 PyErr_SetString(
370 PyExc_ValueError,
371 "code: nlocals must not be negative");
372 goto cleanup;
373 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 ournames = validate_and_copy_tuple(names);
376 if (ournames == NULL)
377 goto cleanup;
378 ourvarnames = validate_and_copy_tuple(varnames);
379 if (ourvarnames == NULL)
380 goto cleanup;
381 if (freevars)
382 ourfreevars = validate_and_copy_tuple(freevars);
383 else
384 ourfreevars = PyTuple_New(0);
385 if (ourfreevars == NULL)
386 goto cleanup;
387 if (cellvars)
388 ourcellvars = validate_and_copy_tuple(cellvars);
389 else
390 ourcellvars = PyTuple_New(0);
391 if (ourcellvars == NULL)
392 goto cleanup;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 co = (PyObject *)PyCode_New(argcount, kwonlyargcount,
395 nlocals, stacksize, flags,
396 code, consts, ournames, ourvarnames,
397 ourfreevars, ourcellvars, filename,
398 name, firstlineno, lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000399 cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 Py_XDECREF(ournames);
401 Py_XDECREF(ourvarnames);
402 Py_XDECREF(ourfreevars);
403 Py_XDECREF(ourcellvars);
404 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000405}
406
407static void
408code_dealloc(PyCodeObject *co)
409{
Brett Cannon5c4de282016-09-07 11:16:41 -0700410 if (co->co_extra != NULL) {
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700411 PyInterpreterState *interp = PyThreadState_Get()->interp;
Brett Cannond0600ed2016-09-07 14:30:39 -0700412 _PyCodeObjectExtra *co_extra = co->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700413
Brett Cannond0600ed2016-09-07 14:30:39 -0700414 for (Py_ssize_t i = 0; i < co_extra->ce_size; i++) {
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700415 freefunc free_extra = interp->co_extra_freefuncs[i];
Brett Cannon5c4de282016-09-07 11:16:41 -0700416
417 if (free_extra != NULL) {
Brett Cannond0600ed2016-09-07 14:30:39 -0700418 free_extra(co_extra->ce_extras[i]);
Brett Cannon5c4de282016-09-07 11:16:41 -0700419 }
420 }
421
Victor Stinner23e79442017-06-28 02:12:00 +0200422 PyMem_Free(co_extra);
Brett Cannon5c4de282016-09-07 11:16:41 -0700423 }
424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 Py_XDECREF(co->co_code);
426 Py_XDECREF(co->co_consts);
427 Py_XDECREF(co->co_names);
428 Py_XDECREF(co->co_varnames);
429 Py_XDECREF(co->co_freevars);
430 Py_XDECREF(co->co_cellvars);
431 Py_XDECREF(co->co_filename);
432 Py_XDECREF(co->co_name);
433 Py_XDECREF(co->co_lnotab);
Benjamin Peterson90037602011-06-25 22:54:45 -0500434 if (co->co_cell2arg != NULL)
435 PyMem_FREE(co->co_cell2arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 if (co->co_zombieframe != NULL)
437 PyObject_GC_Del(co->co_zombieframe);
438 if (co->co_weakreflist != NULL)
439 PyObject_ClearWeakRefs((PyObject*)co);
440 PyObject_DEL(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000441}
442
443static PyObject *
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200444code_sizeof(PyCodeObject *co, void *unused)
445{
Dong-hee Nab4dc6af2017-04-20 16:31:17 +0900446 Py_ssize_t res = _PyObject_SIZE(Py_TYPE(co));
447 _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra*) co->co_extra;
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200448
Serhiy Storchaka378ebb62017-07-04 15:06:16 +0300449 if (co->co_cell2arg != NULL && co->co_cellvars != NULL) {
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200450 res += PyTuple_GET_SIZE(co->co_cellvars) * sizeof(Py_ssize_t);
Serhiy Storchaka378ebb62017-07-04 15:06:16 +0300451 }
452 if (co_extra != NULL) {
453 res += sizeof(_PyCodeObjectExtra) +
454 (co_extra->ce_size-1) * sizeof(co_extra->ce_extras[0]);
455 }
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200456 return PyLong_FromSsize_t(res);
457}
458
459static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000460code_repr(PyCodeObject *co)
461{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 int lineno;
463 if (co->co_firstlineno != 0)
464 lineno = co->co_firstlineno;
465 else
466 lineno = -1;
467 if (co->co_filename && PyUnicode_Check(co->co_filename)) {
468 return PyUnicode_FromFormat(
Victor Stinneraaa4e9a2011-01-05 03:33:26 +0000469 "<code object %U at %p, file \"%U\", line %d>",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 co->co_name, co, co->co_filename, lineno);
471 } else {
472 return PyUnicode_FromFormat(
Victor Stinneraaa4e9a2011-01-05 03:33:26 +0000473 "<code object %U at %p, file ???, line %d>",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 co->co_name, co, lineno);
475 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000476}
477
Victor Stinnerefb24132016-01-22 12:33:12 +0100478PyObject*
479_PyCode_ConstantKey(PyObject *op)
480{
481 PyObject *key;
482
483 /* Py_None and Py_Ellipsis are singleton */
484 if (op == Py_None || op == Py_Ellipsis
485 || PyLong_CheckExact(op)
486 || PyBool_Check(op)
487 || PyBytes_CheckExact(op)
488 || PyUnicode_CheckExact(op)
489 /* code_richcompare() uses _PyCode_ConstantKey() internally */
490 || PyCode_Check(op)) {
491 key = PyTuple_Pack(2, Py_TYPE(op), op);
492 }
493 else if (PyFloat_CheckExact(op)) {
494 double d = PyFloat_AS_DOUBLE(op);
495 /* all we need is to make the tuple different in either the 0.0
496 * or -0.0 case from all others, just to avoid the "coercion".
497 */
498 if (d == 0.0 && copysign(1.0, d) < 0.0)
499 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
500 else
501 key = PyTuple_Pack(2, Py_TYPE(op), op);
502 }
503 else if (PyComplex_CheckExact(op)) {
504 Py_complex z;
505 int real_negzero, imag_negzero;
506 /* For the complex case we must make complex(x, 0.)
507 different from complex(x, -0.) and complex(0., y)
508 different from complex(-0., y), for any x and y.
509 All four complex zeros must be distinguished.*/
510 z = PyComplex_AsCComplex(op);
511 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
512 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
513 /* use True, False and None singleton as tags for the real and imag
514 * sign, to make tuples different */
515 if (real_negzero && imag_negzero) {
516 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_True);
517 }
518 else if (imag_negzero) {
519 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_False);
520 }
521 else if (real_negzero) {
522 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
523 }
524 else {
525 key = PyTuple_Pack(2, Py_TYPE(op), op);
526 }
527 }
528 else if (PyTuple_CheckExact(op)) {
529 Py_ssize_t i, len;
530 PyObject *tuple;
531
532 len = PyTuple_GET_SIZE(op);
533 tuple = PyTuple_New(len);
534 if (tuple == NULL)
535 return NULL;
536
537 for (i=0; i < len; i++) {
538 PyObject *item, *item_key;
539
540 item = PyTuple_GET_ITEM(op, i);
541 item_key = _PyCode_ConstantKey(item);
542 if (item_key == NULL) {
543 Py_DECREF(tuple);
544 return NULL;
545 }
546
547 PyTuple_SET_ITEM(tuple, i, item_key);
548 }
549
Serhiy Storchaka713640c2017-01-24 20:49:26 +0200550 key = PyTuple_Pack(2, tuple, op);
Victor Stinnerefb24132016-01-22 12:33:12 +0100551 Py_DECREF(tuple);
552 }
553 else if (PyFrozenSet_CheckExact(op)) {
554 Py_ssize_t pos = 0;
555 PyObject *item;
556 Py_hash_t hash;
557 Py_ssize_t i, len;
558 PyObject *tuple, *set;
559
560 len = PySet_GET_SIZE(op);
561 tuple = PyTuple_New(len);
562 if (tuple == NULL)
563 return NULL;
564
565 i = 0;
566 while (_PySet_NextEntry(op, &pos, &item, &hash)) {
567 PyObject *item_key;
568
569 item_key = _PyCode_ConstantKey(item);
570 if (item_key == NULL) {
571 Py_DECREF(tuple);
572 return NULL;
573 }
574
575 assert(i < len);
576 PyTuple_SET_ITEM(tuple, i, item_key);
577 i++;
578 }
579 set = PyFrozenSet_New(tuple);
580 Py_DECREF(tuple);
581 if (set == NULL)
582 return NULL;
583
Serhiy Storchaka713640c2017-01-24 20:49:26 +0200584 key = PyTuple_Pack(2, set, op);
Victor Stinnerefb24132016-01-22 12:33:12 +0100585 Py_DECREF(set);
586 return key;
587 }
588 else {
Martin Panter6245cb32016-04-15 02:14:19 +0000589 /* for other types, use the object identifier as a unique identifier
Victor Stinnerefb24132016-01-22 12:33:12 +0100590 * to ensure that they are seen as unequal. */
591 PyObject *obj_id = PyLong_FromVoidPtr(op);
592 if (obj_id == NULL)
593 return NULL;
594
Serhiy Storchaka713640c2017-01-24 20:49:26 +0200595 key = PyTuple_Pack(2, obj_id, op);
Victor Stinnerefb24132016-01-22 12:33:12 +0100596 Py_DECREF(obj_id);
597 }
598 return key;
599}
600
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000601static PyObject *
602code_richcompare(PyObject *self, PyObject *other, int op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000603{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 PyCodeObject *co, *cp;
605 int eq;
Victor Stinnerefb24132016-01-22 12:33:12 +0100606 PyObject *consts1, *consts2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 if ((op != Py_EQ && op != Py_NE) ||
610 !PyCode_Check(self) ||
611 !PyCode_Check(other)) {
Brian Curtindfc80e32011-08-10 20:28:54 -0500612 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 co = (PyCodeObject *)self;
616 cp = (PyCodeObject *)other;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 eq = PyObject_RichCompareBool(co->co_name, cp->co_name, Py_EQ);
619 if (eq <= 0) goto unequal;
620 eq = co->co_argcount == cp->co_argcount;
621 if (!eq) goto unequal;
622 eq = co->co_kwonlyargcount == cp->co_kwonlyargcount;
623 if (!eq) goto unequal;
624 eq = co->co_nlocals == cp->co_nlocals;
625 if (!eq) goto unequal;
626 eq = co->co_flags == cp->co_flags;
627 if (!eq) goto unequal;
628 eq = co->co_firstlineno == cp->co_firstlineno;
629 if (!eq) goto unequal;
630 eq = PyObject_RichCompareBool(co->co_code, cp->co_code, Py_EQ);
631 if (eq <= 0) goto unequal;
Victor Stinnerefb24132016-01-22 12:33:12 +0100632
633 /* compare constants */
634 consts1 = _PyCode_ConstantKey(co->co_consts);
635 if (!consts1)
636 return NULL;
637 consts2 = _PyCode_ConstantKey(cp->co_consts);
638 if (!consts2) {
639 Py_DECREF(consts1);
640 return NULL;
641 }
642 eq = PyObject_RichCompareBool(consts1, consts2, Py_EQ);
643 Py_DECREF(consts1);
644 Py_DECREF(consts2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 if (eq <= 0) goto unequal;
Victor Stinnerefb24132016-01-22 12:33:12 +0100646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 eq = PyObject_RichCompareBool(co->co_names, cp->co_names, Py_EQ);
648 if (eq <= 0) goto unequal;
649 eq = PyObject_RichCompareBool(co->co_varnames, cp->co_varnames, Py_EQ);
650 if (eq <= 0) goto unequal;
651 eq = PyObject_RichCompareBool(co->co_freevars, cp->co_freevars, Py_EQ);
652 if (eq <= 0) goto unequal;
653 eq = PyObject_RichCompareBool(co->co_cellvars, cp->co_cellvars, Py_EQ);
654 if (eq <= 0) goto unequal;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 if (op == Py_EQ)
657 res = Py_True;
658 else
659 res = Py_False;
660 goto done;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000661
662 unequal:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 if (eq < 0)
664 return NULL;
665 if (op == Py_NE)
666 res = Py_True;
667 else
668 res = Py_False;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000669
670 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 Py_INCREF(res);
672 return res;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000673}
674
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000675static Py_hash_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000676code_hash(PyCodeObject *co)
677{
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000678 Py_hash_t h, h0, h1, h2, h3, h4, h5, h6;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 h0 = PyObject_Hash(co->co_name);
680 if (h0 == -1) return -1;
681 h1 = PyObject_Hash(co->co_code);
682 if (h1 == -1) return -1;
683 h2 = PyObject_Hash(co->co_consts);
684 if (h2 == -1) return -1;
685 h3 = PyObject_Hash(co->co_names);
686 if (h3 == -1) return -1;
687 h4 = PyObject_Hash(co->co_varnames);
688 if (h4 == -1) return -1;
689 h5 = PyObject_Hash(co->co_freevars);
690 if (h5 == -1) return -1;
691 h6 = PyObject_Hash(co->co_cellvars);
692 if (h6 == -1) return -1;
693 h = h0 ^ h1 ^ h2 ^ h3 ^ h4 ^ h5 ^ h6 ^
694 co->co_argcount ^ co->co_kwonlyargcount ^
695 co->co_nlocals ^ co->co_flags;
696 if (h == -1) h = -2;
697 return h;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000698}
699
700/* XXX code objects need to participate in GC? */
701
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200702static struct PyMethodDef code_methods[] = {
703 {"__sizeof__", (PyCFunction)code_sizeof, METH_NOARGS},
704 {NULL, NULL} /* sentinel */
705};
706
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000707PyTypeObject PyCode_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 PyVarObject_HEAD_INIT(&PyType_Type, 0)
709 "code",
710 sizeof(PyCodeObject),
711 0,
712 (destructor)code_dealloc, /* tp_dealloc */
713 0, /* tp_print */
714 0, /* tp_getattr */
715 0, /* tp_setattr */
716 0, /* tp_reserved */
717 (reprfunc)code_repr, /* tp_repr */
718 0, /* tp_as_number */
719 0, /* tp_as_sequence */
720 0, /* tp_as_mapping */
721 (hashfunc)code_hash, /* tp_hash */
722 0, /* tp_call */
723 0, /* tp_str */
724 PyObject_GenericGetAttr, /* tp_getattro */
725 0, /* tp_setattro */
726 0, /* tp_as_buffer */
727 Py_TPFLAGS_DEFAULT, /* tp_flags */
728 code_doc, /* tp_doc */
729 0, /* tp_traverse */
730 0, /* tp_clear */
731 code_richcompare, /* tp_richcompare */
732 offsetof(PyCodeObject, co_weakreflist), /* tp_weaklistoffset */
733 0, /* tp_iter */
734 0, /* tp_iternext */
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200735 code_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 code_memberlist, /* tp_members */
737 0, /* tp_getset */
738 0, /* tp_base */
739 0, /* tp_dict */
740 0, /* tp_descr_get */
741 0, /* tp_descr_set */
742 0, /* tp_dictoffset */
743 0, /* tp_init */
744 0, /* tp_alloc */
745 code_new, /* tp_new */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000746};
747
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000748/* Use co_lnotab to compute the line number from a bytecode index, addrq. See
749 lnotab_notes.txt for the details of the lnotab representation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000750*/
751
752int
753PyCode_Addr2Line(PyCodeObject *co, int addrq)
754{
Victor Stinner0fcab4a2011-01-04 12:59:15 +0000755 Py_ssize_t size = PyBytes_Size(co->co_lnotab) / 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 unsigned char *p = (unsigned char*)PyBytes_AsString(co->co_lnotab);
757 int line = co->co_firstlineno;
758 int addr = 0;
759 while (--size >= 0) {
760 addr += *p++;
761 if (addr > addrq)
762 break;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100763 line += (signed char)*p;
764 p++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 }
766 return line;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000767}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000768
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000769/* Update *bounds to describe the first and one-past-the-last instructions in
770 the same line as lasti. Return the number of that line. */
771int
772_PyCode_CheckLineNumber(PyCodeObject* co, int lasti, PyAddrPair *bounds)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000773{
Victor Stinner0fcab4a2011-01-04 12:59:15 +0000774 Py_ssize_t size;
775 int addr, line;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 unsigned char* p;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 p = (unsigned char*)PyBytes_AS_STRING(co->co_lnotab);
779 size = PyBytes_GET_SIZE(co->co_lnotab) / 2;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 addr = 0;
782 line = co->co_firstlineno;
783 assert(line > 0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 /* possible optimization: if f->f_lasti == instr_ub
786 (likely to be a common case) then we already know
787 instr_lb -- if we stored the matching value of p
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700788 somewhere we could skip the first while loop. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 /* See lnotab_notes.txt for the description of
791 co_lnotab. A point to remember: increments to p
792 come in (addr, line) pairs. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 bounds->ap_lower = 0;
795 while (size > 0) {
796 if (addr + *p > lasti)
797 break;
798 addr += *p++;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100799 if ((signed char)*p)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 bounds->ap_lower = addr;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100801 line += (signed char)*p;
802 p++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 --size;
804 }
805
806 if (size > 0) {
807 while (--size >= 0) {
808 addr += *p++;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100809 if ((signed char)*p)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 break;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100811 p++;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000812 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 bounds->ap_upper = addr;
814 }
815 else {
816 bounds->ap_upper = INT_MAX;
817 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 return line;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000820}
Brett Cannon5c4de282016-09-07 11:16:41 -0700821
822
823int
824_PyCode_GetExtra(PyObject *code, Py_ssize_t index, void **extra)
825{
Brett Cannon5c4de282016-09-07 11:16:41 -0700826 if (!PyCode_Check(code)) {
827 PyErr_BadInternalCall();
Brett Cannon3788b852016-09-07 12:51:08 -0700828 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -0700829 }
830
Brett Cannond0600ed2016-09-07 14:30:39 -0700831 PyCodeObject *o = (PyCodeObject*) code;
832 _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra*) o->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700833
Brett Cannond0600ed2016-09-07 14:30:39 -0700834 if (co_extra == NULL || co_extra->ce_size <= index) {
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700835 *extra = NULL;
Brett Cannon5c4de282016-09-07 11:16:41 -0700836 return 0;
837 }
838
Brett Cannond0600ed2016-09-07 14:30:39 -0700839 *extra = co_extra->ce_extras[index];
Brett Cannon5c4de282016-09-07 11:16:41 -0700840 return 0;
841}
842
843
844int
845_PyCode_SetExtra(PyObject *code, Py_ssize_t index, void *extra)
846{
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700847 PyInterpreterState *interp = PyThreadState_Get()->interp;
Brett Cannon5c4de282016-09-07 11:16:41 -0700848
849 if (!PyCode_Check(code) || index < 0 ||
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700850 index >= interp->co_extra_user_count) {
Brett Cannon5c4de282016-09-07 11:16:41 -0700851 PyErr_BadInternalCall();
Brett Cannon3788b852016-09-07 12:51:08 -0700852 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -0700853 }
854
Brett Cannond0600ed2016-09-07 14:30:39 -0700855 PyCodeObject *o = (PyCodeObject*) code;
856 _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra *) o->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700857
Serhiy Storchaka378ebb62017-07-04 15:06:16 +0300858 if (co_extra == NULL || co_extra->ce_size <= index) {
859 Py_ssize_t i = (co_extra == NULL ? 0 : co_extra->ce_size);
860 co_extra = PyMem_Realloc(
861 co_extra,
862 sizeof(_PyCodeObjectExtra) +
863 (interp->co_extra_user_count-1) * sizeof(void*));
Brian Coleman6a9122c2017-03-02 10:32:18 +0000864 if (co_extra == NULL) {
Brett Cannon3788b852016-09-07 12:51:08 -0700865 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -0700866 }
Serhiy Storchaka378ebb62017-07-04 15:06:16 +0300867 for (; i < interp->co_extra_user_count; i++) {
Brett Cannond0600ed2016-09-07 14:30:39 -0700868 co_extra->ce_extras[i] = NULL;
Brett Cannon5c4de282016-09-07 11:16:41 -0700869 }
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700870 co_extra->ce_size = interp->co_extra_user_count;
Serhiy Storchaka378ebb62017-07-04 15:06:16 +0300871 o->co_extra = co_extra;
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700872 }
873
874 if (co_extra->ce_extras[index] != NULL) {
875 freefunc free = interp->co_extra_freefuncs[index];
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700876 if (free != NULL) {
877 free(co_extra->ce_extras[index]);
878 }
Brett Cannon5c4de282016-09-07 11:16:41 -0700879 }
880
Brett Cannond0600ed2016-09-07 14:30:39 -0700881 co_extra->ce_extras[index] = extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700882 return 0;
883}