blob: 7ef012585adc35a65e340bb874262e07cabdad62 [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;
Miss Islington (bot)5594f1d2018-07-16 00:09:44 -0700106 Py_ssize_t i, n_cellvars, n_varnames, total_args;
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
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 intern_strings(names);
128 intern_strings(varnames);
129 intern_strings(freevars);
130 intern_strings(cellvars);
Serhiy Storchaka00a0fc12016-09-30 10:07:26 +0300131 intern_string_constants(consts);
Nick Coghlan078f1812017-12-03 11:12:20 +1000132
133 /* Check for any inner or outer closure references */
134 n_cellvars = PyTuple_GET_SIZE(cellvars);
135 if (!n_cellvars && !PyTuple_GET_SIZE(freevars)) {
136 flags |= CO_NOFREE;
137 } else {
138 flags &= ~CO_NOFREE;
139 }
140
Miss Islington (bot)5594f1d2018-07-16 00:09:44 -0700141 n_varnames = PyTuple_GET_SIZE(varnames);
142 if (argcount <= n_varnames && kwonlyargcount <= n_varnames) {
143 /* Never overflows. */
144 total_args = (Py_ssize_t)argcount + (Py_ssize_t)kwonlyargcount +
145 ((flags & CO_VARARGS) != 0) + ((flags & CO_VARKEYWORDS) != 0);
146 }
147 else {
148 total_args = n_varnames + 1;
149 }
150 if (total_args > n_varnames) {
151 PyErr_SetString(PyExc_ValueError, "code: varnames is too small");
152 return NULL;
153 }
154
Benjamin Peterson90037602011-06-25 22:54:45 -0500155 /* Create mapping between cells and arguments if needed. */
156 if (n_cellvars) {
Benjamin Peterson1bf494b2016-09-07 11:28:35 -0700157 bool used_cell2arg = false;
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200158 cell2arg = PyMem_NEW(Py_ssize_t, n_cellvars);
159 if (cell2arg == NULL) {
160 PyErr_NoMemory();
Benjamin Peterson90037602011-06-25 22:54:45 -0500161 return NULL;
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200162 }
Benjamin Peterson90037602011-06-25 22:54:45 -0500163 /* Find cells which are also arguments. */
164 for (i = 0; i < n_cellvars; i++) {
165 Py_ssize_t j;
166 PyObject *cell = PyTuple_GET_ITEM(cellvars, i);
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200167 cell2arg[i] = CO_CELL_NOT_AN_ARG;
Benjamin Peterson90037602011-06-25 22:54:45 -0500168 for (j = 0; j < total_args; j++) {
169 PyObject *arg = PyTuple_GET_ITEM(varnames, j);
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200170 int cmp = PyUnicode_Compare(cell, arg);
171 if (cmp == -1 && PyErr_Occurred()) {
172 PyMem_FREE(cell2arg);
173 return NULL;
174 }
175 if (cmp == 0) {
Benjamin Peterson90037602011-06-25 22:54:45 -0500176 cell2arg[i] = j;
Benjamin Peterson1bf494b2016-09-07 11:28:35 -0700177 used_cell2arg = true;
Benjamin Peterson90037602011-06-25 22:54:45 -0500178 break;
179 }
180 }
181 }
182 if (!used_cell2arg) {
183 PyMem_FREE(cell2arg);
184 cell2arg = NULL;
185 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 }
Benjamin Peterson90037602011-06-25 22:54:45 -0500187 co = PyObject_NEW(PyCodeObject, &PyCode_Type);
188 if (co == NULL) {
189 if (cell2arg)
190 PyMem_FREE(cell2arg);
191 return NULL;
192 }
193 co->co_argcount = argcount;
194 co->co_kwonlyargcount = kwonlyargcount;
195 co->co_nlocals = nlocals;
196 co->co_stacksize = stacksize;
197 co->co_flags = flags;
198 Py_INCREF(code);
199 co->co_code = code;
200 Py_INCREF(consts);
201 co->co_consts = consts;
202 Py_INCREF(names);
203 co->co_names = names;
204 Py_INCREF(varnames);
205 co->co_varnames = varnames;
206 Py_INCREF(freevars);
207 co->co_freevars = freevars;
208 Py_INCREF(cellvars);
209 co->co_cellvars = cellvars;
210 co->co_cell2arg = cell2arg;
211 Py_INCREF(filename);
212 co->co_filename = filename;
213 Py_INCREF(name);
214 co->co_name = name;
215 co->co_firstlineno = firstlineno;
216 Py_INCREF(lnotab);
217 co->co_lnotab = lnotab;
218 co->co_zombieframe = NULL;
219 co->co_weakreflist = NULL;
Brett Cannon5c4de282016-09-07 11:16:41 -0700220 co->co_extra = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000222}
223
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000224PyCodeObject *
225PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno)
226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 static PyObject *emptystring = NULL;
228 static PyObject *nulltuple = NULL;
229 PyObject *filename_ob = NULL;
230 PyObject *funcname_ob = NULL;
231 PyCodeObject *result = NULL;
232 if (emptystring == NULL) {
233 emptystring = PyBytes_FromString("");
234 if (emptystring == NULL)
235 goto failed;
236 }
237 if (nulltuple == NULL) {
238 nulltuple = PyTuple_New(0);
239 if (nulltuple == NULL)
240 goto failed;
241 }
242 funcname_ob = PyUnicode_FromString(funcname);
243 if (funcname_ob == NULL)
244 goto failed;
245 filename_ob = PyUnicode_DecodeFSDefault(filename);
246 if (filename_ob == NULL)
247 goto failed;
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 result = PyCode_New(0, /* argcount */
250 0, /* kwonlyargcount */
251 0, /* nlocals */
252 0, /* stacksize */
253 0, /* flags */
254 emptystring, /* code */
255 nulltuple, /* consts */
256 nulltuple, /* names */
257 nulltuple, /* varnames */
258 nulltuple, /* freevars */
259 nulltuple, /* cellvars */
260 filename_ob, /* filename */
261 funcname_ob, /* name */
262 firstlineno, /* firstlineno */
263 emptystring /* lnotab */
264 );
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000265
266failed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 Py_XDECREF(funcname_ob);
268 Py_XDECREF(filename_ob);
269 return result;
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000270}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000271
272#define OFF(x) offsetof(PyCodeObject, x)
273
274static PyMemberDef code_memberlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 {"co_argcount", T_INT, OFF(co_argcount), READONLY},
276 {"co_kwonlyargcount", T_INT, OFF(co_kwonlyargcount), READONLY},
277 {"co_nlocals", T_INT, OFF(co_nlocals), READONLY},
278 {"co_stacksize",T_INT, OFF(co_stacksize), READONLY},
279 {"co_flags", T_INT, OFF(co_flags), READONLY},
280 {"co_code", T_OBJECT, OFF(co_code), READONLY},
281 {"co_consts", T_OBJECT, OFF(co_consts), READONLY},
282 {"co_names", T_OBJECT, OFF(co_names), READONLY},
283 {"co_varnames", T_OBJECT, OFF(co_varnames), READONLY},
284 {"co_freevars", T_OBJECT, OFF(co_freevars), READONLY},
285 {"co_cellvars", T_OBJECT, OFF(co_cellvars), READONLY},
286 {"co_filename", T_OBJECT, OFF(co_filename), READONLY},
287 {"co_name", T_OBJECT, OFF(co_name), READONLY},
288 {"co_firstlineno", T_INT, OFF(co_firstlineno), READONLY},
289 {"co_lnotab", T_OBJECT, OFF(co_lnotab), READONLY},
290 {NULL} /* Sentinel */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000291};
292
293/* Helper for code_new: return a shallow copy of a tuple that is
294 guaranteed to contain exact strings, by converting string subclasses
295 to exact strings and complaining if a non-string is found. */
296static PyObject*
297validate_and_copy_tuple(PyObject *tup)
298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 PyObject *newtuple;
300 PyObject *item;
301 Py_ssize_t i, len;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 len = PyTuple_GET_SIZE(tup);
304 newtuple = PyTuple_New(len);
305 if (newtuple == NULL)
306 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 for (i = 0; i < len; i++) {
309 item = PyTuple_GET_ITEM(tup, i);
310 if (PyUnicode_CheckExact(item)) {
311 Py_INCREF(item);
312 }
313 else if (!PyUnicode_Check(item)) {
314 PyErr_Format(
315 PyExc_TypeError,
316 "name tuples must contain only "
317 "strings, not '%.500s'",
318 item->ob_type->tp_name);
319 Py_DECREF(newtuple);
320 return NULL;
321 }
322 else {
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100323 item = _PyUnicode_Copy(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 if (item == NULL) {
325 Py_DECREF(newtuple);
326 return NULL;
327 }
328 }
329 PyTuple_SET_ITEM(newtuple, i, item);
330 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 return newtuple;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000333}
334
335PyDoc_STRVAR(code_doc,
Georg Brandl8c1a50a2009-07-18 09:07:48 +0000336"code(argcount, kwonlyargcount, nlocals, stacksize, flags, codestring,\n\
Georg Brandla1e7e132008-01-26 09:39:23 +0000337 constants, names, varnames, filename, name, firstlineno,\n\
338 lnotab[, freevars[, cellvars]])\n\
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000339\n\
340Create a code object. Not for the faint of heart.");
341
342static PyObject *
343code_new(PyTypeObject *type, PyObject *args, PyObject *kw)
344{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 int argcount;
346 int kwonlyargcount;
347 int nlocals;
348 int stacksize;
349 int flags;
350 PyObject *co = NULL;
351 PyObject *code;
352 PyObject *consts;
353 PyObject *names, *ournames = NULL;
354 PyObject *varnames, *ourvarnames = NULL;
355 PyObject *freevars = NULL, *ourfreevars = NULL;
356 PyObject *cellvars = NULL, *ourcellvars = NULL;
357 PyObject *filename;
358 PyObject *name;
359 int firstlineno;
360 PyObject *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 if (!PyArg_ParseTuple(args, "iiiiiSO!O!O!UUiS|O!O!:code",
363 &argcount, &kwonlyargcount,
364 &nlocals, &stacksize, &flags,
365 &code,
366 &PyTuple_Type, &consts,
367 &PyTuple_Type, &names,
368 &PyTuple_Type, &varnames,
369 &filename, &name,
370 &firstlineno, &lnotab,
371 &PyTuple_Type, &freevars,
372 &PyTuple_Type, &cellvars))
373 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 if (argcount < 0) {
376 PyErr_SetString(
377 PyExc_ValueError,
378 "code: argcount must not be negative");
379 goto cleanup;
380 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 if (kwonlyargcount < 0) {
383 PyErr_SetString(
384 PyExc_ValueError,
385 "code: kwonlyargcount must not be negative");
386 goto cleanup;
387 }
388 if (nlocals < 0) {
389 PyErr_SetString(
390 PyExc_ValueError,
391 "code: nlocals must not be negative");
392 goto cleanup;
393 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 ournames = validate_and_copy_tuple(names);
396 if (ournames == NULL)
397 goto cleanup;
398 ourvarnames = validate_and_copy_tuple(varnames);
399 if (ourvarnames == NULL)
400 goto cleanup;
401 if (freevars)
402 ourfreevars = validate_and_copy_tuple(freevars);
403 else
404 ourfreevars = PyTuple_New(0);
405 if (ourfreevars == NULL)
406 goto cleanup;
407 if (cellvars)
408 ourcellvars = validate_and_copy_tuple(cellvars);
409 else
410 ourcellvars = PyTuple_New(0);
411 if (ourcellvars == NULL)
412 goto cleanup;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 co = (PyObject *)PyCode_New(argcount, kwonlyargcount,
415 nlocals, stacksize, flags,
416 code, consts, ournames, ourvarnames,
417 ourfreevars, ourcellvars, filename,
418 name, firstlineno, lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000419 cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 Py_XDECREF(ournames);
421 Py_XDECREF(ourvarnames);
422 Py_XDECREF(ourfreevars);
423 Py_XDECREF(ourcellvars);
424 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000425}
426
427static void
428code_dealloc(PyCodeObject *co)
429{
Brett Cannon5c4de282016-09-07 11:16:41 -0700430 if (co->co_extra != NULL) {
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700431 PyInterpreterState *interp = PyThreadState_Get()->interp;
Brett Cannond0600ed2016-09-07 14:30:39 -0700432 _PyCodeObjectExtra *co_extra = co->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700433
Brett Cannond0600ed2016-09-07 14:30:39 -0700434 for (Py_ssize_t i = 0; i < co_extra->ce_size; i++) {
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700435 freefunc free_extra = interp->co_extra_freefuncs[i];
Brett Cannon5c4de282016-09-07 11:16:41 -0700436
437 if (free_extra != NULL) {
Brett Cannond0600ed2016-09-07 14:30:39 -0700438 free_extra(co_extra->ce_extras[i]);
Brett Cannon5c4de282016-09-07 11:16:41 -0700439 }
440 }
441
Victor Stinner23e79442017-06-28 02:12:00 +0200442 PyMem_Free(co_extra);
Brett Cannon5c4de282016-09-07 11:16:41 -0700443 }
444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 Py_XDECREF(co->co_code);
446 Py_XDECREF(co->co_consts);
447 Py_XDECREF(co->co_names);
448 Py_XDECREF(co->co_varnames);
449 Py_XDECREF(co->co_freevars);
450 Py_XDECREF(co->co_cellvars);
451 Py_XDECREF(co->co_filename);
452 Py_XDECREF(co->co_name);
453 Py_XDECREF(co->co_lnotab);
Benjamin Peterson90037602011-06-25 22:54:45 -0500454 if (co->co_cell2arg != NULL)
455 PyMem_FREE(co->co_cell2arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 if (co->co_zombieframe != NULL)
457 PyObject_GC_Del(co->co_zombieframe);
458 if (co->co_weakreflist != NULL)
459 PyObject_ClearWeakRefs((PyObject*)co);
460 PyObject_DEL(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000461}
462
463static PyObject *
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200464code_sizeof(PyCodeObject *co, void *unused)
465{
Dong-hee Nab4dc6af2017-04-20 16:31:17 +0900466 Py_ssize_t res = _PyObject_SIZE(Py_TYPE(co));
467 _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra*) co->co_extra;
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200468
Serhiy Storchaka378ebb62017-07-04 15:06:16 +0300469 if (co->co_cell2arg != NULL && co->co_cellvars != NULL) {
Serhiy Storchaka5bb8b912016-12-16 19:19:02 +0200470 res += PyTuple_GET_SIZE(co->co_cellvars) * sizeof(Py_ssize_t);
Serhiy Storchaka378ebb62017-07-04 15:06:16 +0300471 }
472 if (co_extra != NULL) {
473 res += sizeof(_PyCodeObjectExtra) +
474 (co_extra->ce_size-1) * sizeof(co_extra->ce_extras[0]);
475 }
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200476 return PyLong_FromSsize_t(res);
477}
478
479static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000480code_repr(PyCodeObject *co)
481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 int lineno;
483 if (co->co_firstlineno != 0)
484 lineno = co->co_firstlineno;
485 else
486 lineno = -1;
487 if (co->co_filename && PyUnicode_Check(co->co_filename)) {
488 return PyUnicode_FromFormat(
Victor Stinneraaa4e9a2011-01-05 03:33:26 +0000489 "<code object %U at %p, file \"%U\", line %d>",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 co->co_name, co, co->co_filename, lineno);
491 } else {
492 return PyUnicode_FromFormat(
Victor Stinneraaa4e9a2011-01-05 03:33:26 +0000493 "<code object %U at %p, file ???, line %d>",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 co->co_name, co, lineno);
495 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000496}
497
Victor Stinnerefb24132016-01-22 12:33:12 +0100498PyObject*
499_PyCode_ConstantKey(PyObject *op)
500{
501 PyObject *key;
502
503 /* Py_None and Py_Ellipsis are singleton */
504 if (op == Py_None || op == Py_Ellipsis
505 || PyLong_CheckExact(op)
506 || PyBool_Check(op)
507 || PyBytes_CheckExact(op)
508 || PyUnicode_CheckExact(op)
509 /* code_richcompare() uses _PyCode_ConstantKey() internally */
510 || PyCode_Check(op)) {
511 key = PyTuple_Pack(2, Py_TYPE(op), op);
512 }
513 else if (PyFloat_CheckExact(op)) {
514 double d = PyFloat_AS_DOUBLE(op);
515 /* all we need is to make the tuple different in either the 0.0
516 * or -0.0 case from all others, just to avoid the "coercion".
517 */
518 if (d == 0.0 && copysign(1.0, d) < 0.0)
519 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
520 else
521 key = PyTuple_Pack(2, Py_TYPE(op), op);
522 }
523 else if (PyComplex_CheckExact(op)) {
524 Py_complex z;
525 int real_negzero, imag_negzero;
526 /* For the complex case we must make complex(x, 0.)
527 different from complex(x, -0.) and complex(0., y)
528 different from complex(-0., y), for any x and y.
529 All four complex zeros must be distinguished.*/
530 z = PyComplex_AsCComplex(op);
531 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
532 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
533 /* use True, False and None singleton as tags for the real and imag
534 * sign, to make tuples different */
535 if (real_negzero && imag_negzero) {
536 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_True);
537 }
538 else if (imag_negzero) {
539 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_False);
540 }
541 else if (real_negzero) {
542 key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
543 }
544 else {
545 key = PyTuple_Pack(2, Py_TYPE(op), op);
546 }
547 }
548 else if (PyTuple_CheckExact(op)) {
549 Py_ssize_t i, len;
550 PyObject *tuple;
551
552 len = PyTuple_GET_SIZE(op);
553 tuple = PyTuple_New(len);
554 if (tuple == NULL)
555 return NULL;
556
557 for (i=0; i < len; i++) {
558 PyObject *item, *item_key;
559
560 item = PyTuple_GET_ITEM(op, i);
561 item_key = _PyCode_ConstantKey(item);
562 if (item_key == NULL) {
563 Py_DECREF(tuple);
564 return NULL;
565 }
566
567 PyTuple_SET_ITEM(tuple, i, item_key);
568 }
569
Serhiy Storchaka713640c2017-01-24 20:49:26 +0200570 key = PyTuple_Pack(2, tuple, op);
Victor Stinnerefb24132016-01-22 12:33:12 +0100571 Py_DECREF(tuple);
572 }
573 else if (PyFrozenSet_CheckExact(op)) {
574 Py_ssize_t pos = 0;
575 PyObject *item;
576 Py_hash_t hash;
577 Py_ssize_t i, len;
578 PyObject *tuple, *set;
579
580 len = PySet_GET_SIZE(op);
581 tuple = PyTuple_New(len);
582 if (tuple == NULL)
583 return NULL;
584
585 i = 0;
586 while (_PySet_NextEntry(op, &pos, &item, &hash)) {
587 PyObject *item_key;
588
589 item_key = _PyCode_ConstantKey(item);
590 if (item_key == NULL) {
591 Py_DECREF(tuple);
592 return NULL;
593 }
594
595 assert(i < len);
596 PyTuple_SET_ITEM(tuple, i, item_key);
597 i++;
598 }
599 set = PyFrozenSet_New(tuple);
600 Py_DECREF(tuple);
601 if (set == NULL)
602 return NULL;
603
Serhiy Storchaka713640c2017-01-24 20:49:26 +0200604 key = PyTuple_Pack(2, set, op);
Victor Stinnerefb24132016-01-22 12:33:12 +0100605 Py_DECREF(set);
606 return key;
607 }
608 else {
Martin Panter6245cb32016-04-15 02:14:19 +0000609 /* for other types, use the object identifier as a unique identifier
Victor Stinnerefb24132016-01-22 12:33:12 +0100610 * to ensure that they are seen as unequal. */
611 PyObject *obj_id = PyLong_FromVoidPtr(op);
612 if (obj_id == NULL)
613 return NULL;
614
Serhiy Storchaka713640c2017-01-24 20:49:26 +0200615 key = PyTuple_Pack(2, obj_id, op);
Victor Stinnerefb24132016-01-22 12:33:12 +0100616 Py_DECREF(obj_id);
617 }
618 return key;
619}
620
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000621static PyObject *
622code_richcompare(PyObject *self, PyObject *other, int op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000623{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 PyCodeObject *co, *cp;
625 int eq;
Victor Stinnerefb24132016-01-22 12:33:12 +0100626 PyObject *consts1, *consts2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 if ((op != Py_EQ && op != Py_NE) ||
630 !PyCode_Check(self) ||
631 !PyCode_Check(other)) {
Brian Curtindfc80e32011-08-10 20:28:54 -0500632 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 co = (PyCodeObject *)self;
636 cp = (PyCodeObject *)other;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 eq = PyObject_RichCompareBool(co->co_name, cp->co_name, Py_EQ);
639 if (eq <= 0) goto unequal;
640 eq = co->co_argcount == cp->co_argcount;
641 if (!eq) goto unequal;
642 eq = co->co_kwonlyargcount == cp->co_kwonlyargcount;
643 if (!eq) goto unequal;
644 eq = co->co_nlocals == cp->co_nlocals;
645 if (!eq) goto unequal;
646 eq = co->co_flags == cp->co_flags;
647 if (!eq) goto unequal;
648 eq = co->co_firstlineno == cp->co_firstlineno;
649 if (!eq) goto unequal;
650 eq = PyObject_RichCompareBool(co->co_code, cp->co_code, Py_EQ);
651 if (eq <= 0) goto unequal;
Victor Stinnerefb24132016-01-22 12:33:12 +0100652
653 /* compare constants */
654 consts1 = _PyCode_ConstantKey(co->co_consts);
655 if (!consts1)
656 return NULL;
657 consts2 = _PyCode_ConstantKey(cp->co_consts);
658 if (!consts2) {
659 Py_DECREF(consts1);
660 return NULL;
661 }
662 eq = PyObject_RichCompareBool(consts1, consts2, Py_EQ);
663 Py_DECREF(consts1);
664 Py_DECREF(consts2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 if (eq <= 0) goto unequal;
Victor Stinnerefb24132016-01-22 12:33:12 +0100666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 eq = PyObject_RichCompareBool(co->co_names, cp->co_names, Py_EQ);
668 if (eq <= 0) goto unequal;
669 eq = PyObject_RichCompareBool(co->co_varnames, cp->co_varnames, Py_EQ);
670 if (eq <= 0) goto unequal;
671 eq = PyObject_RichCompareBool(co->co_freevars, cp->co_freevars, Py_EQ);
672 if (eq <= 0) goto unequal;
673 eq = PyObject_RichCompareBool(co->co_cellvars, cp->co_cellvars, Py_EQ);
674 if (eq <= 0) goto unequal;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 if (op == Py_EQ)
677 res = Py_True;
678 else
679 res = Py_False;
680 goto done;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000681
682 unequal:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 if (eq < 0)
684 return NULL;
685 if (op == Py_NE)
686 res = Py_True;
687 else
688 res = Py_False;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000689
690 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 Py_INCREF(res);
692 return res;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000693}
694
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000695static Py_hash_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000696code_hash(PyCodeObject *co)
697{
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000698 Py_hash_t h, h0, h1, h2, h3, h4, h5, h6;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 h0 = PyObject_Hash(co->co_name);
700 if (h0 == -1) return -1;
701 h1 = PyObject_Hash(co->co_code);
702 if (h1 == -1) return -1;
703 h2 = PyObject_Hash(co->co_consts);
704 if (h2 == -1) return -1;
705 h3 = PyObject_Hash(co->co_names);
706 if (h3 == -1) return -1;
707 h4 = PyObject_Hash(co->co_varnames);
708 if (h4 == -1) return -1;
709 h5 = PyObject_Hash(co->co_freevars);
710 if (h5 == -1) return -1;
711 h6 = PyObject_Hash(co->co_cellvars);
712 if (h6 == -1) return -1;
713 h = h0 ^ h1 ^ h2 ^ h3 ^ h4 ^ h5 ^ h6 ^
714 co->co_argcount ^ co->co_kwonlyargcount ^
715 co->co_nlocals ^ co->co_flags;
716 if (h == -1) h = -2;
717 return h;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000718}
719
720/* XXX code objects need to participate in GC? */
721
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200722static struct PyMethodDef code_methods[] = {
723 {"__sizeof__", (PyCFunction)code_sizeof, METH_NOARGS},
724 {NULL, NULL} /* sentinel */
725};
726
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000727PyTypeObject PyCode_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 PyVarObject_HEAD_INIT(&PyType_Type, 0)
729 "code",
730 sizeof(PyCodeObject),
731 0,
732 (destructor)code_dealloc, /* tp_dealloc */
733 0, /* tp_print */
734 0, /* tp_getattr */
735 0, /* tp_setattr */
736 0, /* tp_reserved */
737 (reprfunc)code_repr, /* tp_repr */
738 0, /* tp_as_number */
739 0, /* tp_as_sequence */
740 0, /* tp_as_mapping */
741 (hashfunc)code_hash, /* tp_hash */
742 0, /* tp_call */
743 0, /* tp_str */
744 PyObject_GenericGetAttr, /* tp_getattro */
745 0, /* tp_setattro */
746 0, /* tp_as_buffer */
747 Py_TPFLAGS_DEFAULT, /* tp_flags */
748 code_doc, /* tp_doc */
749 0, /* tp_traverse */
750 0, /* tp_clear */
751 code_richcompare, /* tp_richcompare */
752 offsetof(PyCodeObject, co_weakreflist), /* tp_weaklistoffset */
753 0, /* tp_iter */
754 0, /* tp_iternext */
Martin v. Löwis3bbd2fa2012-07-26 22:23:23 +0200755 code_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 code_memberlist, /* tp_members */
757 0, /* tp_getset */
758 0, /* tp_base */
759 0, /* tp_dict */
760 0, /* tp_descr_get */
761 0, /* tp_descr_set */
762 0, /* tp_dictoffset */
763 0, /* tp_init */
764 0, /* tp_alloc */
765 code_new, /* tp_new */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000766};
767
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000768/* Use co_lnotab to compute the line number from a bytecode index, addrq. See
769 lnotab_notes.txt for the details of the lnotab representation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000770*/
771
772int
773PyCode_Addr2Line(PyCodeObject *co, int addrq)
774{
Victor Stinner0fcab4a2011-01-04 12:59:15 +0000775 Py_ssize_t size = PyBytes_Size(co->co_lnotab) / 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 unsigned char *p = (unsigned char*)PyBytes_AsString(co->co_lnotab);
777 int line = co->co_firstlineno;
778 int addr = 0;
779 while (--size >= 0) {
780 addr += *p++;
781 if (addr > addrq)
782 break;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100783 line += (signed char)*p;
784 p++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 }
786 return line;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000787}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000788
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000789/* Update *bounds to describe the first and one-past-the-last instructions in
790 the same line as lasti. Return the number of that line. */
791int
792_PyCode_CheckLineNumber(PyCodeObject* co, int lasti, PyAddrPair *bounds)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000793{
Victor Stinner0fcab4a2011-01-04 12:59:15 +0000794 Py_ssize_t size;
795 int addr, line;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 unsigned char* p;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 p = (unsigned char*)PyBytes_AS_STRING(co->co_lnotab);
799 size = PyBytes_GET_SIZE(co->co_lnotab) / 2;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 addr = 0;
802 line = co->co_firstlineno;
803 assert(line > 0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 /* possible optimization: if f->f_lasti == instr_ub
806 (likely to be a common case) then we already know
807 instr_lb -- if we stored the matching value of p
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700808 somewhere we could skip the first while loop. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 /* See lnotab_notes.txt for the description of
811 co_lnotab. A point to remember: increments to p
812 come in (addr, line) pairs. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 bounds->ap_lower = 0;
815 while (size > 0) {
816 if (addr + *p > lasti)
817 break;
818 addr += *p++;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100819 if ((signed char)*p)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 bounds->ap_lower = addr;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100821 line += (signed char)*p;
822 p++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 --size;
824 }
825
826 if (size > 0) {
827 while (--size >= 0) {
828 addr += *p++;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100829 if ((signed char)*p)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 break;
Victor Stinnerf3914eb2016-01-20 12:16:21 +0100831 p++;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000832 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 bounds->ap_upper = addr;
834 }
835 else {
836 bounds->ap_upper = INT_MAX;
837 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 return line;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000840}
Brett Cannon5c4de282016-09-07 11:16:41 -0700841
842
843int
844_PyCode_GetExtra(PyObject *code, Py_ssize_t index, void **extra)
845{
Brett Cannon5c4de282016-09-07 11:16:41 -0700846 if (!PyCode_Check(code)) {
847 PyErr_BadInternalCall();
Brett Cannon3788b852016-09-07 12:51:08 -0700848 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -0700849 }
850
Brett Cannond0600ed2016-09-07 14:30:39 -0700851 PyCodeObject *o = (PyCodeObject*) code;
852 _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra*) o->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700853
Brett Cannond0600ed2016-09-07 14:30:39 -0700854 if (co_extra == NULL || co_extra->ce_size <= index) {
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700855 *extra = NULL;
Brett Cannon5c4de282016-09-07 11:16:41 -0700856 return 0;
857 }
858
Brett Cannond0600ed2016-09-07 14:30:39 -0700859 *extra = co_extra->ce_extras[index];
Brett Cannon5c4de282016-09-07 11:16:41 -0700860 return 0;
861}
862
863
864int
865_PyCode_SetExtra(PyObject *code, Py_ssize_t index, void *extra)
866{
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700867 PyInterpreterState *interp = PyThreadState_Get()->interp;
Brett Cannon5c4de282016-09-07 11:16:41 -0700868
869 if (!PyCode_Check(code) || index < 0 ||
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700870 index >= interp->co_extra_user_count) {
Brett Cannon5c4de282016-09-07 11:16:41 -0700871 PyErr_BadInternalCall();
Brett Cannon3788b852016-09-07 12:51:08 -0700872 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -0700873 }
874
Brett Cannond0600ed2016-09-07 14:30:39 -0700875 PyCodeObject *o = (PyCodeObject*) code;
876 _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra *) o->co_extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700877
Serhiy Storchaka378ebb62017-07-04 15:06:16 +0300878 if (co_extra == NULL || co_extra->ce_size <= index) {
879 Py_ssize_t i = (co_extra == NULL ? 0 : co_extra->ce_size);
880 co_extra = PyMem_Realloc(
881 co_extra,
882 sizeof(_PyCodeObjectExtra) +
883 (interp->co_extra_user_count-1) * sizeof(void*));
Brian Coleman6a9122c2017-03-02 10:32:18 +0000884 if (co_extra == NULL) {
Brett Cannon3788b852016-09-07 12:51:08 -0700885 return -1;
Brett Cannon5c4de282016-09-07 11:16:41 -0700886 }
Serhiy Storchaka378ebb62017-07-04 15:06:16 +0300887 for (; i < interp->co_extra_user_count; i++) {
Brett Cannond0600ed2016-09-07 14:30:39 -0700888 co_extra->ce_extras[i] = NULL;
Brett Cannon5c4de282016-09-07 11:16:41 -0700889 }
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700890 co_extra->ce_size = interp->co_extra_user_count;
Serhiy Storchaka378ebb62017-07-04 15:06:16 +0300891 o->co_extra = co_extra;
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700892 }
893
894 if (co_extra->ce_extras[index] != NULL) {
895 freefunc free = interp->co_extra_freefuncs[index];
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700896 if (free != NULL) {
897 free(co_extra->ce_extras[index]);
898 }
Brett Cannon5c4de282016-09-07 11:16:41 -0700899 }
900
Brett Cannond0600ed2016-09-07 14:30:39 -0700901 co_extra->ce_extras[index] = extra;
Brett Cannon5c4de282016-09-07 11:16:41 -0700902 return 0;
903}