Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
allendowney
GitHub Repository: allendowney/cpython
Path: blob/main/Objects/codeobject.c
12 views
1
#include <stdbool.h>
2
3
#include "Python.h"
4
#include "opcode.h"
5
#include "structmember.h" // PyMemberDef
6
#include "pycore_code.h" // _PyCodeConstructor
7
#include "pycore_frame.h" // FRAME_SPECIALS_SIZE
8
#include "pycore_interp.h" // PyInterpreterState.co_extra_freefuncs
9
#include "pycore_opcode.h" // _PyOpcode_Deopt
10
#include "pycore_pystate.h" // _PyInterpreterState_GET()
11
#include "pycore_tuple.h" // _PyTuple_ITEMS()
12
#include "clinic/codeobject.c.h"
13
14
static PyObject* code_repr(PyCodeObject *co);
15
16
static const char *
17
code_event_name(PyCodeEvent event) {
18
switch (event) {
19
#define CASE(op) \
20
case PY_CODE_EVENT_##op: \
21
return "PY_CODE_EVENT_" #op;
22
PY_FOREACH_CODE_EVENT(CASE)
23
#undef CASE
24
}
25
Py_UNREACHABLE();
26
}
27
28
static void
29
notify_code_watchers(PyCodeEvent event, PyCodeObject *co)
30
{
31
assert(Py_REFCNT(co) > 0);
32
PyInterpreterState *interp = _PyInterpreterState_GET();
33
assert(interp->_initialized);
34
uint8_t bits = interp->active_code_watchers;
35
int i = 0;
36
while (bits) {
37
assert(i < CODE_MAX_WATCHERS);
38
if (bits & 1) {
39
PyCode_WatchCallback cb = interp->code_watchers[i];
40
// callback must be non-null if the watcher bit is set
41
assert(cb != NULL);
42
if (cb(event, co) < 0) {
43
// Don't risk resurrecting the object if an unraisablehook keeps
44
// a reference; pass a string as context.
45
PyObject *context = NULL;
46
PyObject *repr = code_repr(co);
47
if (repr) {
48
context = PyUnicode_FromFormat(
49
"%s watcher callback for %U",
50
code_event_name(event), repr);
51
Py_DECREF(repr);
52
}
53
if (context == NULL) {
54
context = Py_NewRef(Py_None);
55
}
56
PyErr_WriteUnraisable(context);
57
Py_DECREF(context);
58
}
59
}
60
i++;
61
bits >>= 1;
62
}
63
}
64
65
int
66
PyCode_AddWatcher(PyCode_WatchCallback callback)
67
{
68
PyInterpreterState *interp = _PyInterpreterState_GET();
69
assert(interp->_initialized);
70
71
for (int i = 0; i < CODE_MAX_WATCHERS; i++) {
72
if (!interp->code_watchers[i]) {
73
interp->code_watchers[i] = callback;
74
interp->active_code_watchers |= (1 << i);
75
return i;
76
}
77
}
78
79
PyErr_SetString(PyExc_RuntimeError, "no more code watcher IDs available");
80
return -1;
81
}
82
83
static inline int
84
validate_watcher_id(PyInterpreterState *interp, int watcher_id)
85
{
86
if (watcher_id < 0 || watcher_id >= CODE_MAX_WATCHERS) {
87
PyErr_Format(PyExc_ValueError, "Invalid code watcher ID %d", watcher_id);
88
return -1;
89
}
90
if (!interp->code_watchers[watcher_id]) {
91
PyErr_Format(PyExc_ValueError, "No code watcher set for ID %d", watcher_id);
92
return -1;
93
}
94
return 0;
95
}
96
97
int
98
PyCode_ClearWatcher(int watcher_id)
99
{
100
PyInterpreterState *interp = _PyInterpreterState_GET();
101
assert(interp->_initialized);
102
if (validate_watcher_id(interp, watcher_id) < 0) {
103
return -1;
104
}
105
interp->code_watchers[watcher_id] = NULL;
106
interp->active_code_watchers &= ~(1 << watcher_id);
107
return 0;
108
}
109
110
/******************
111
* generic helpers
112
******************/
113
114
/* all_name_chars(s): true iff s matches [a-zA-Z0-9_]* */
115
static int
116
all_name_chars(PyObject *o)
117
{
118
const unsigned char *s, *e;
119
120
if (!PyUnicode_IS_ASCII(o))
121
return 0;
122
123
s = PyUnicode_1BYTE_DATA(o);
124
e = s + PyUnicode_GET_LENGTH(o);
125
for (; s != e; s++) {
126
if (!Py_ISALNUM(*s) && *s != '_')
127
return 0;
128
}
129
return 1;
130
}
131
132
static int
133
intern_strings(PyObject *tuple)
134
{
135
Py_ssize_t i;
136
137
for (i = PyTuple_GET_SIZE(tuple); --i >= 0; ) {
138
PyObject *v = PyTuple_GET_ITEM(tuple, i);
139
if (v == NULL || !PyUnicode_CheckExact(v)) {
140
PyErr_SetString(PyExc_SystemError,
141
"non-string found in code slot");
142
return -1;
143
}
144
PyUnicode_InternInPlace(&_PyTuple_ITEMS(tuple)[i]);
145
}
146
return 0;
147
}
148
149
/* Intern selected string constants */
150
static int
151
intern_string_constants(PyObject *tuple, int *modified)
152
{
153
for (Py_ssize_t i = PyTuple_GET_SIZE(tuple); --i >= 0; ) {
154
PyObject *v = PyTuple_GET_ITEM(tuple, i);
155
if (PyUnicode_CheckExact(v)) {
156
if (all_name_chars(v)) {
157
PyObject *w = v;
158
PyUnicode_InternInPlace(&v);
159
if (w != v) {
160
PyTuple_SET_ITEM(tuple, i, v);
161
if (modified) {
162
*modified = 1;
163
}
164
}
165
}
166
}
167
else if (PyTuple_CheckExact(v)) {
168
if (intern_string_constants(v, NULL) < 0) {
169
return -1;
170
}
171
}
172
else if (PyFrozenSet_CheckExact(v)) {
173
PyObject *w = v;
174
PyObject *tmp = PySequence_Tuple(v);
175
if (tmp == NULL) {
176
return -1;
177
}
178
int tmp_modified = 0;
179
if (intern_string_constants(tmp, &tmp_modified) < 0) {
180
Py_DECREF(tmp);
181
return -1;
182
}
183
if (tmp_modified) {
184
v = PyFrozenSet_New(tmp);
185
if (v == NULL) {
186
Py_DECREF(tmp);
187
return -1;
188
}
189
190
PyTuple_SET_ITEM(tuple, i, v);
191
Py_DECREF(w);
192
if (modified) {
193
*modified = 1;
194
}
195
}
196
Py_DECREF(tmp);
197
}
198
}
199
return 0;
200
}
201
202
/* Return a shallow copy of a tuple that is
203
guaranteed to contain exact strings, by converting string subclasses
204
to exact strings and complaining if a non-string is found. */
205
static PyObject*
206
validate_and_copy_tuple(PyObject *tup)
207
{
208
PyObject *newtuple;
209
PyObject *item;
210
Py_ssize_t i, len;
211
212
len = PyTuple_GET_SIZE(tup);
213
newtuple = PyTuple_New(len);
214
if (newtuple == NULL)
215
return NULL;
216
217
for (i = 0; i < len; i++) {
218
item = PyTuple_GET_ITEM(tup, i);
219
if (PyUnicode_CheckExact(item)) {
220
Py_INCREF(item);
221
}
222
else if (!PyUnicode_Check(item)) {
223
PyErr_Format(
224
PyExc_TypeError,
225
"name tuples must contain only "
226
"strings, not '%.500s'",
227
Py_TYPE(item)->tp_name);
228
Py_DECREF(newtuple);
229
return NULL;
230
}
231
else {
232
item = _PyUnicode_Copy(item);
233
if (item == NULL) {
234
Py_DECREF(newtuple);
235
return NULL;
236
}
237
}
238
PyTuple_SET_ITEM(newtuple, i, item);
239
}
240
241
return newtuple;
242
}
243
244
static int
245
init_co_cached(PyCodeObject *self) {
246
if (self->_co_cached == NULL) {
247
self->_co_cached = PyMem_New(_PyCoCached, 1);
248
if (self->_co_cached == NULL) {
249
PyErr_NoMemory();
250
return -1;
251
}
252
self->_co_cached->_co_code = NULL;
253
self->_co_cached->_co_cellvars = NULL;
254
self->_co_cached->_co_freevars = NULL;
255
self->_co_cached->_co_varnames = NULL;
256
}
257
return 0;
258
259
}
260
/******************
261
* _PyCode_New()
262
******************/
263
264
// This is also used in compile.c.
265
void
266
_Py_set_localsplus_info(int offset, PyObject *name, _PyLocals_Kind kind,
267
PyObject *names, PyObject *kinds)
268
{
269
PyTuple_SET_ITEM(names, offset, Py_NewRef(name));
270
_PyLocals_SetKind(kinds, offset, kind);
271
}
272
273
static void
274
get_localsplus_counts(PyObject *names, PyObject *kinds,
275
int *pnlocals, int *pncellvars,
276
int *pnfreevars)
277
{
278
int nlocals = 0;
279
int ncellvars = 0;
280
int nfreevars = 0;
281
Py_ssize_t nlocalsplus = PyTuple_GET_SIZE(names);
282
for (int i = 0; i < nlocalsplus; i++) {
283
_PyLocals_Kind kind = _PyLocals_GetKind(kinds, i);
284
if (kind & CO_FAST_LOCAL) {
285
nlocals += 1;
286
if (kind & CO_FAST_CELL) {
287
ncellvars += 1;
288
}
289
}
290
else if (kind & CO_FAST_CELL) {
291
ncellvars += 1;
292
}
293
else if (kind & CO_FAST_FREE) {
294
nfreevars += 1;
295
}
296
}
297
if (pnlocals != NULL) {
298
*pnlocals = nlocals;
299
}
300
if (pncellvars != NULL) {
301
*pncellvars = ncellvars;
302
}
303
if (pnfreevars != NULL) {
304
*pnfreevars = nfreevars;
305
}
306
}
307
308
static PyObject *
309
get_localsplus_names(PyCodeObject *co, _PyLocals_Kind kind, int num)
310
{
311
PyObject *names = PyTuple_New(num);
312
if (names == NULL) {
313
return NULL;
314
}
315
int index = 0;
316
for (int offset = 0; offset < co->co_nlocalsplus; offset++) {
317
_PyLocals_Kind k = _PyLocals_GetKind(co->co_localspluskinds, offset);
318
if ((k & kind) == 0) {
319
continue;
320
}
321
assert(index < num);
322
PyObject *name = PyTuple_GET_ITEM(co->co_localsplusnames, offset);
323
PyTuple_SET_ITEM(names, index, Py_NewRef(name));
324
index += 1;
325
}
326
assert(index == num);
327
return names;
328
}
329
330
int
331
_PyCode_Validate(struct _PyCodeConstructor *con)
332
{
333
/* Check argument types */
334
if (con->argcount < con->posonlyargcount || con->posonlyargcount < 0 ||
335
con->kwonlyargcount < 0 ||
336
con->stacksize < 0 || con->flags < 0 ||
337
con->code == NULL || !PyBytes_Check(con->code) ||
338
con->consts == NULL || !PyTuple_Check(con->consts) ||
339
con->names == NULL || !PyTuple_Check(con->names) ||
340
con->localsplusnames == NULL || !PyTuple_Check(con->localsplusnames) ||
341
con->localspluskinds == NULL || !PyBytes_Check(con->localspluskinds) ||
342
PyTuple_GET_SIZE(con->localsplusnames)
343
!= PyBytes_GET_SIZE(con->localspluskinds) ||
344
con->name == NULL || !PyUnicode_Check(con->name) ||
345
con->qualname == NULL || !PyUnicode_Check(con->qualname) ||
346
con->filename == NULL || !PyUnicode_Check(con->filename) ||
347
con->linetable == NULL || !PyBytes_Check(con->linetable) ||
348
con->exceptiontable == NULL || !PyBytes_Check(con->exceptiontable)
349
) {
350
PyErr_BadInternalCall();
351
return -1;
352
}
353
354
/* Make sure that code is indexable with an int, this is
355
a long running assumption in ceval.c and many parts of
356
the interpreter. */
357
if (PyBytes_GET_SIZE(con->code) > INT_MAX) {
358
PyErr_SetString(PyExc_OverflowError,
359
"code: co_code larger than INT_MAX");
360
return -1;
361
}
362
if (PyBytes_GET_SIZE(con->code) % sizeof(_Py_CODEUNIT) != 0 ||
363
!_Py_IS_ALIGNED(PyBytes_AS_STRING(con->code), sizeof(_Py_CODEUNIT))
364
) {
365
PyErr_SetString(PyExc_ValueError, "code: co_code is malformed");
366
return -1;
367
}
368
369
/* Ensure that the co_varnames has enough names to cover the arg counts.
370
* Note that totalargs = nlocals - nplainlocals. We check nplainlocals
371
* here to avoid the possibility of overflow (however remote). */
372
int nlocals;
373
get_localsplus_counts(con->localsplusnames, con->localspluskinds,
374
&nlocals, NULL, NULL);
375
int nplainlocals = nlocals -
376
con->argcount -
377
con->kwonlyargcount -
378
((con->flags & CO_VARARGS) != 0) -
379
((con->flags & CO_VARKEYWORDS) != 0);
380
if (nplainlocals < 0) {
381
PyErr_SetString(PyExc_ValueError, "code: co_varnames is too small");
382
return -1;
383
}
384
385
return 0;
386
}
387
388
extern void _PyCode_Quicken(PyCodeObject *code);
389
390
static void
391
init_code(PyCodeObject *co, struct _PyCodeConstructor *con)
392
{
393
int nlocalsplus = (int)PyTuple_GET_SIZE(con->localsplusnames);
394
int nlocals, ncellvars, nfreevars;
395
get_localsplus_counts(con->localsplusnames, con->localspluskinds,
396
&nlocals, &ncellvars, &nfreevars);
397
398
co->co_filename = Py_NewRef(con->filename);
399
co->co_name = Py_NewRef(con->name);
400
co->co_qualname = Py_NewRef(con->qualname);
401
co->co_flags = con->flags;
402
403
co->co_firstlineno = con->firstlineno;
404
co->co_linetable = Py_NewRef(con->linetable);
405
406
co->co_consts = Py_NewRef(con->consts);
407
co->co_names = Py_NewRef(con->names);
408
409
co->co_localsplusnames = Py_NewRef(con->localsplusnames);
410
co->co_localspluskinds = Py_NewRef(con->localspluskinds);
411
412
co->co_argcount = con->argcount;
413
co->co_posonlyargcount = con->posonlyargcount;
414
co->co_kwonlyargcount = con->kwonlyargcount;
415
416
co->co_stacksize = con->stacksize;
417
418
co->co_exceptiontable = Py_NewRef(con->exceptiontable);
419
420
/* derived values */
421
co->co_nlocalsplus = nlocalsplus;
422
co->co_nlocals = nlocals;
423
co->co_framesize = nlocalsplus + con->stacksize + FRAME_SPECIALS_SIZE;
424
co->co_ncellvars = ncellvars;
425
co->co_nfreevars = nfreevars;
426
co->co_version = _Py_next_func_version;
427
if (_Py_next_func_version != 0) {
428
_Py_next_func_version++;
429
}
430
co->_co_monitoring = NULL;
431
co->_co_instrumentation_version = 0;
432
/* not set */
433
co->co_weakreflist = NULL;
434
co->co_extra = NULL;
435
co->_co_cached = NULL;
436
co->co_executors = NULL;
437
438
memcpy(_PyCode_CODE(co), PyBytes_AS_STRING(con->code),
439
PyBytes_GET_SIZE(con->code));
440
int entry_point = 0;
441
while (entry_point < Py_SIZE(co) &&
442
_PyCode_CODE(co)[entry_point].op.code != RESUME) {
443
entry_point++;
444
}
445
co->_co_firsttraceable = entry_point;
446
_PyCode_Quicken(co);
447
notify_code_watchers(PY_CODE_EVENT_CREATE, co);
448
}
449
450
static int
451
scan_varint(const uint8_t *ptr)
452
{
453
unsigned int read = *ptr++;
454
unsigned int val = read & 63;
455
unsigned int shift = 0;
456
while (read & 64) {
457
read = *ptr++;
458
shift += 6;
459
val |= (read & 63) << shift;
460
}
461
return val;
462
}
463
464
static int
465
scan_signed_varint(const uint8_t *ptr)
466
{
467
unsigned int uval = scan_varint(ptr);
468
if (uval & 1) {
469
return -(int)(uval >> 1);
470
}
471
else {
472
return uval >> 1;
473
}
474
}
475
476
static int
477
get_line_delta(const uint8_t *ptr)
478
{
479
int code = ((*ptr) >> 3) & 15;
480
switch (code) {
481
case PY_CODE_LOCATION_INFO_NONE:
482
return 0;
483
case PY_CODE_LOCATION_INFO_NO_COLUMNS:
484
case PY_CODE_LOCATION_INFO_LONG:
485
return scan_signed_varint(ptr+1);
486
case PY_CODE_LOCATION_INFO_ONE_LINE0:
487
return 0;
488
case PY_CODE_LOCATION_INFO_ONE_LINE1:
489
return 1;
490
case PY_CODE_LOCATION_INFO_ONE_LINE2:
491
return 2;
492
default:
493
/* Same line */
494
return 0;
495
}
496
}
497
498
static PyObject *
499
remove_column_info(PyObject *locations)
500
{
501
int offset = 0;
502
const uint8_t *data = (const uint8_t *)PyBytes_AS_STRING(locations);
503
PyObject *res = PyBytes_FromStringAndSize(NULL, 32);
504
if (res == NULL) {
505
PyErr_NoMemory();
506
return NULL;
507
}
508
uint8_t *output = (uint8_t *)PyBytes_AS_STRING(res);
509
while (offset < PyBytes_GET_SIZE(locations)) {
510
Py_ssize_t write_offset = output - (uint8_t *)PyBytes_AS_STRING(res);
511
if (write_offset + 16 >= PyBytes_GET_SIZE(res)) {
512
if (_PyBytes_Resize(&res, PyBytes_GET_SIZE(res) * 2) < 0) {
513
return NULL;
514
}
515
output = (uint8_t *)PyBytes_AS_STRING(res) + write_offset;
516
}
517
int code = (data[offset] >> 3) & 15;
518
if (code == PY_CODE_LOCATION_INFO_NONE) {
519
*output++ = data[offset];
520
}
521
else {
522
int blength = (data[offset] & 7)+1;
523
output += write_location_entry_start(
524
output, PY_CODE_LOCATION_INFO_NO_COLUMNS, blength);
525
int ldelta = get_line_delta(&data[offset]);
526
output += write_signed_varint(output, ldelta);
527
}
528
offset++;
529
while (offset < PyBytes_GET_SIZE(locations) &&
530
(data[offset] & 128) == 0) {
531
offset++;
532
}
533
}
534
Py_ssize_t write_offset = output - (uint8_t *)PyBytes_AS_STRING(res);
535
if (_PyBytes_Resize(&res, write_offset)) {
536
return NULL;
537
}
538
return res;
539
}
540
541
/* The caller is responsible for ensuring that the given data is valid. */
542
543
PyCodeObject *
544
_PyCode_New(struct _PyCodeConstructor *con)
545
{
546
if (intern_strings(con->names) < 0) {
547
return NULL;
548
}
549
if (intern_string_constants(con->consts, NULL) < 0) {
550
return NULL;
551
}
552
if (intern_strings(con->localsplusnames) < 0) {
553
return NULL;
554
}
555
556
PyObject *replacement_locations = NULL;
557
// Compact the linetable if we are opted out of debug
558
// ranges.
559
if (!_Py_GetConfig()->code_debug_ranges) {
560
replacement_locations = remove_column_info(con->linetable);
561
if (replacement_locations == NULL) {
562
return NULL;
563
}
564
con->linetable = replacement_locations;
565
}
566
567
Py_ssize_t size = PyBytes_GET_SIZE(con->code) / sizeof(_Py_CODEUNIT);
568
PyCodeObject *co = PyObject_NewVar(PyCodeObject, &PyCode_Type, size);
569
if (co == NULL) {
570
Py_XDECREF(replacement_locations);
571
PyErr_NoMemory();
572
return NULL;
573
}
574
init_code(co, con);
575
Py_XDECREF(replacement_locations);
576
return co;
577
}
578
579
580
/******************
581
* the legacy "constructors"
582
******************/
583
584
PyCodeObject *
585
PyUnstable_Code_NewWithPosOnlyArgs(
586
int argcount, int posonlyargcount, int kwonlyargcount,
587
int nlocals, int stacksize, int flags,
588
PyObject *code, PyObject *consts, PyObject *names,
589
PyObject *varnames, PyObject *freevars, PyObject *cellvars,
590
PyObject *filename, PyObject *name,
591
PyObject *qualname, int firstlineno,
592
PyObject *linetable,
593
PyObject *exceptiontable)
594
{
595
PyCodeObject *co = NULL;
596
PyObject *localsplusnames = NULL;
597
PyObject *localspluskinds = NULL;
598
599
if (varnames == NULL || !PyTuple_Check(varnames) ||
600
cellvars == NULL || !PyTuple_Check(cellvars) ||
601
freevars == NULL || !PyTuple_Check(freevars)
602
) {
603
PyErr_BadInternalCall();
604
return NULL;
605
}
606
607
// Set the "fast locals plus" info.
608
int nvarnames = (int)PyTuple_GET_SIZE(varnames);
609
int ncellvars = (int)PyTuple_GET_SIZE(cellvars);
610
int nfreevars = (int)PyTuple_GET_SIZE(freevars);
611
int nlocalsplus = nvarnames + ncellvars + nfreevars;
612
localsplusnames = PyTuple_New(nlocalsplus);
613
if (localsplusnames == NULL) {
614
goto error;
615
}
616
localspluskinds = PyBytes_FromStringAndSize(NULL, nlocalsplus);
617
if (localspluskinds == NULL) {
618
goto error;
619
}
620
int offset = 0;
621
for (int i = 0; i < nvarnames; i++, offset++) {
622
PyObject *name = PyTuple_GET_ITEM(varnames, i);
623
_Py_set_localsplus_info(offset, name, CO_FAST_LOCAL,
624
localsplusnames, localspluskinds);
625
}
626
for (int i = 0; i < ncellvars; i++, offset++) {
627
PyObject *name = PyTuple_GET_ITEM(cellvars, i);
628
int argoffset = -1;
629
for (int j = 0; j < nvarnames; j++) {
630
int cmp = PyUnicode_Compare(PyTuple_GET_ITEM(varnames, j),
631
name);
632
assert(!PyErr_Occurred());
633
if (cmp == 0) {
634
argoffset = j;
635
break;
636
}
637
}
638
if (argoffset >= 0) {
639
// Merge the localsplus indices.
640
nlocalsplus -= 1;
641
offset -= 1;
642
_PyLocals_Kind kind = _PyLocals_GetKind(localspluskinds, argoffset);
643
_PyLocals_SetKind(localspluskinds, argoffset, kind | CO_FAST_CELL);
644
continue;
645
}
646
_Py_set_localsplus_info(offset, name, CO_FAST_CELL,
647
localsplusnames, localspluskinds);
648
}
649
for (int i = 0; i < nfreevars; i++, offset++) {
650
PyObject *name = PyTuple_GET_ITEM(freevars, i);
651
_Py_set_localsplus_info(offset, name, CO_FAST_FREE,
652
localsplusnames, localspluskinds);
653
}
654
// If any cells were args then nlocalsplus will have shrunk.
655
if (nlocalsplus != PyTuple_GET_SIZE(localsplusnames)) {
656
if (_PyTuple_Resize(&localsplusnames, nlocalsplus) < 0
657
|| _PyBytes_Resize(&localspluskinds, nlocalsplus) < 0) {
658
goto error;
659
}
660
}
661
662
struct _PyCodeConstructor con = {
663
.filename = filename,
664
.name = name,
665
.qualname = qualname,
666
.flags = flags,
667
668
.code = code,
669
.firstlineno = firstlineno,
670
.linetable = linetable,
671
672
.consts = consts,
673
.names = names,
674
675
.localsplusnames = localsplusnames,
676
.localspluskinds = localspluskinds,
677
678
.argcount = argcount,
679
.posonlyargcount = posonlyargcount,
680
.kwonlyargcount = kwonlyargcount,
681
682
.stacksize = stacksize,
683
684
.exceptiontable = exceptiontable,
685
};
686
687
if (_PyCode_Validate(&con) < 0) {
688
goto error;
689
}
690
assert(PyBytes_GET_SIZE(code) % sizeof(_Py_CODEUNIT) == 0);
691
assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(code), sizeof(_Py_CODEUNIT)));
692
if (nlocals != PyTuple_GET_SIZE(varnames)) {
693
PyErr_SetString(PyExc_ValueError,
694
"code: co_nlocals != len(co_varnames)");
695
goto error;
696
}
697
698
co = _PyCode_New(&con);
699
if (co == NULL) {
700
goto error;
701
}
702
703
error:
704
Py_XDECREF(localsplusnames);
705
Py_XDECREF(localspluskinds);
706
return co;
707
}
708
709
PyCodeObject *
710
PyUnstable_Code_New(int argcount, int kwonlyargcount,
711
int nlocals, int stacksize, int flags,
712
PyObject *code, PyObject *consts, PyObject *names,
713
PyObject *varnames, PyObject *freevars, PyObject *cellvars,
714
PyObject *filename, PyObject *name, PyObject *qualname,
715
int firstlineno,
716
PyObject *linetable,
717
PyObject *exceptiontable)
718
{
719
return PyCode_NewWithPosOnlyArgs(argcount, 0, kwonlyargcount, nlocals,
720
stacksize, flags, code, consts, names,
721
varnames, freevars, cellvars, filename,
722
name, qualname, firstlineno,
723
linetable,
724
exceptiontable);
725
}
726
727
// NOTE: When modifying the construction of PyCode_NewEmpty, please also change
728
// test.test_code.CodeLocationTest.test_code_new_empty to keep it in sync!
729
730
static const uint8_t assert0[6] = {
731
RESUME, 0,
732
LOAD_ASSERTION_ERROR, 0,
733
RAISE_VARARGS, 1
734
};
735
736
static const uint8_t linetable[2] = {
737
(1 << 7) // New entry.
738
| (PY_CODE_LOCATION_INFO_NO_COLUMNS << 3)
739
| (3 - 1), // Three code units.
740
0, // Offset from co_firstlineno.
741
};
742
743
PyCodeObject *
744
PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno)
745
{
746
PyObject *nulltuple = NULL;
747
PyObject *filename_ob = NULL;
748
PyObject *funcname_ob = NULL;
749
PyObject *code_ob = NULL;
750
PyObject *linetable_ob = NULL;
751
PyCodeObject *result = NULL;
752
753
nulltuple = PyTuple_New(0);
754
if (nulltuple == NULL) {
755
goto failed;
756
}
757
funcname_ob = PyUnicode_FromString(funcname);
758
if (funcname_ob == NULL) {
759
goto failed;
760
}
761
filename_ob = PyUnicode_DecodeFSDefault(filename);
762
if (filename_ob == NULL) {
763
goto failed;
764
}
765
code_ob = PyBytes_FromStringAndSize((const char *)assert0, 6);
766
if (code_ob == NULL) {
767
goto failed;
768
}
769
linetable_ob = PyBytes_FromStringAndSize((const char *)linetable, 2);
770
if (linetable_ob == NULL) {
771
goto failed;
772
}
773
774
#define emptystring (PyObject *)&_Py_SINGLETON(bytes_empty)
775
struct _PyCodeConstructor con = {
776
.filename = filename_ob,
777
.name = funcname_ob,
778
.qualname = funcname_ob,
779
.code = code_ob,
780
.firstlineno = firstlineno,
781
.linetable = linetable_ob,
782
.consts = nulltuple,
783
.names = nulltuple,
784
.localsplusnames = nulltuple,
785
.localspluskinds = emptystring,
786
.exceptiontable = emptystring,
787
.stacksize = 1,
788
};
789
result = _PyCode_New(&con);
790
791
failed:
792
Py_XDECREF(nulltuple);
793
Py_XDECREF(funcname_ob);
794
Py_XDECREF(filename_ob);
795
Py_XDECREF(code_ob);
796
Py_XDECREF(linetable_ob);
797
return result;
798
}
799
800
801
/******************
802
* source location tracking (co_lines/co_positions)
803
******************/
804
805
int
806
PyCode_Addr2Line(PyCodeObject *co, int addrq)
807
{
808
if (addrq < 0) {
809
return co->co_firstlineno;
810
}
811
assert(addrq >= 0 && addrq < _PyCode_NBYTES(co));
812
PyCodeAddressRange bounds;
813
_PyCode_InitAddressRange(co, &bounds);
814
return _PyCode_CheckLineNumber(addrq, &bounds);
815
}
816
817
void
818
_PyLineTable_InitAddressRange(const char *linetable, Py_ssize_t length, int firstlineno, PyCodeAddressRange *range)
819
{
820
range->opaque.lo_next = (const uint8_t *)linetable;
821
range->opaque.limit = range->opaque.lo_next + length;
822
range->ar_start = -1;
823
range->ar_end = 0;
824
range->opaque.computed_line = firstlineno;
825
range->ar_line = -1;
826
}
827
828
int
829
_PyCode_InitAddressRange(PyCodeObject* co, PyCodeAddressRange *bounds)
830
{
831
assert(co->co_linetable != NULL);
832
const char *linetable = PyBytes_AS_STRING(co->co_linetable);
833
Py_ssize_t length = PyBytes_GET_SIZE(co->co_linetable);
834
_PyLineTable_InitAddressRange(linetable, length, co->co_firstlineno, bounds);
835
return bounds->ar_line;
836
}
837
838
/* Update *bounds to describe the first and one-past-the-last instructions in
839
the same line as lasti. Return the number of that line, or -1 if lasti is out of bounds. */
840
int
841
_PyCode_CheckLineNumber(int lasti, PyCodeAddressRange *bounds)
842
{
843
while (bounds->ar_end <= lasti) {
844
if (!_PyLineTable_NextAddressRange(bounds)) {
845
return -1;
846
}
847
}
848
while (bounds->ar_start > lasti) {
849
if (!_PyLineTable_PreviousAddressRange(bounds)) {
850
return -1;
851
}
852
}
853
return bounds->ar_line;
854
}
855
856
static int
857
is_no_line_marker(uint8_t b)
858
{
859
return (b >> 3) == 0x1f;
860
}
861
862
863
#define ASSERT_VALID_BOUNDS(bounds) \
864
assert(bounds->opaque.lo_next <= bounds->opaque.limit && \
865
(bounds->ar_line == -1 || bounds->ar_line == bounds->opaque.computed_line) && \
866
(bounds->opaque.lo_next == bounds->opaque.limit || \
867
(*bounds->opaque.lo_next) & 128))
868
869
static int
870
next_code_delta(PyCodeAddressRange *bounds)
871
{
872
assert((*bounds->opaque.lo_next) & 128);
873
return (((*bounds->opaque.lo_next) & 7) + 1) * sizeof(_Py_CODEUNIT);
874
}
875
876
static int
877
previous_code_delta(PyCodeAddressRange *bounds)
878
{
879
if (bounds->ar_start == 0) {
880
// If we looking at the first entry, the
881
// "previous" entry has an implicit length of 1.
882
return 1;
883
}
884
const uint8_t *ptr = bounds->opaque.lo_next-1;
885
while (((*ptr) & 128) == 0) {
886
ptr--;
887
}
888
return (((*ptr) & 7) + 1) * sizeof(_Py_CODEUNIT);
889
}
890
891
static int
892
read_byte(PyCodeAddressRange *bounds)
893
{
894
return *bounds->opaque.lo_next++;
895
}
896
897
static int
898
read_varint(PyCodeAddressRange *bounds)
899
{
900
unsigned int read = read_byte(bounds);
901
unsigned int val = read & 63;
902
unsigned int shift = 0;
903
while (read & 64) {
904
read = read_byte(bounds);
905
shift += 6;
906
val |= (read & 63) << shift;
907
}
908
return val;
909
}
910
911
static int
912
read_signed_varint(PyCodeAddressRange *bounds)
913
{
914
unsigned int uval = read_varint(bounds);
915
if (uval & 1) {
916
return -(int)(uval >> 1);
917
}
918
else {
919
return uval >> 1;
920
}
921
}
922
923
static void
924
retreat(PyCodeAddressRange *bounds)
925
{
926
ASSERT_VALID_BOUNDS(bounds);
927
assert(bounds->ar_start >= 0);
928
do {
929
bounds->opaque.lo_next--;
930
} while (((*bounds->opaque.lo_next) & 128) == 0);
931
bounds->opaque.computed_line -= get_line_delta(bounds->opaque.lo_next);
932
bounds->ar_end = bounds->ar_start;
933
bounds->ar_start -= previous_code_delta(bounds);
934
if (is_no_line_marker(bounds->opaque.lo_next[-1])) {
935
bounds->ar_line = -1;
936
}
937
else {
938
bounds->ar_line = bounds->opaque.computed_line;
939
}
940
ASSERT_VALID_BOUNDS(bounds);
941
}
942
943
static void
944
advance(PyCodeAddressRange *bounds)
945
{
946
ASSERT_VALID_BOUNDS(bounds);
947
bounds->opaque.computed_line += get_line_delta(bounds->opaque.lo_next);
948
if (is_no_line_marker(*bounds->opaque.lo_next)) {
949
bounds->ar_line = -1;
950
}
951
else {
952
bounds->ar_line = bounds->opaque.computed_line;
953
}
954
bounds->ar_start = bounds->ar_end;
955
bounds->ar_end += next_code_delta(bounds);
956
do {
957
bounds->opaque.lo_next++;
958
} while (bounds->opaque.lo_next < bounds->opaque.limit &&
959
((*bounds->opaque.lo_next) & 128) == 0);
960
ASSERT_VALID_BOUNDS(bounds);
961
}
962
963
static void
964
advance_with_locations(PyCodeAddressRange *bounds, int *endline, int *column, int *endcolumn)
965
{
966
ASSERT_VALID_BOUNDS(bounds);
967
int first_byte = read_byte(bounds);
968
int code = (first_byte >> 3) & 15;
969
bounds->ar_start = bounds->ar_end;
970
bounds->ar_end = bounds->ar_start + ((first_byte & 7) + 1) * sizeof(_Py_CODEUNIT);
971
switch(code) {
972
case PY_CODE_LOCATION_INFO_NONE:
973
bounds->ar_line = *endline = -1;
974
*column = *endcolumn = -1;
975
break;
976
case PY_CODE_LOCATION_INFO_LONG:
977
{
978
bounds->opaque.computed_line += read_signed_varint(bounds);
979
bounds->ar_line = bounds->opaque.computed_line;
980
*endline = bounds->ar_line + read_varint(bounds);
981
*column = read_varint(bounds)-1;
982
*endcolumn = read_varint(bounds)-1;
983
break;
984
}
985
case PY_CODE_LOCATION_INFO_NO_COLUMNS:
986
{
987
/* No column */
988
bounds->opaque.computed_line += read_signed_varint(bounds);
989
*endline = bounds->ar_line = bounds->opaque.computed_line;
990
*column = *endcolumn = -1;
991
break;
992
}
993
case PY_CODE_LOCATION_INFO_ONE_LINE0:
994
case PY_CODE_LOCATION_INFO_ONE_LINE1:
995
case PY_CODE_LOCATION_INFO_ONE_LINE2:
996
{
997
/* one line form */
998
int line_delta = code - 10;
999
bounds->opaque.computed_line += line_delta;
1000
*endline = bounds->ar_line = bounds->opaque.computed_line;
1001
*column = read_byte(bounds);
1002
*endcolumn = read_byte(bounds);
1003
break;
1004
}
1005
default:
1006
{
1007
/* Short forms */
1008
int second_byte = read_byte(bounds);
1009
assert((second_byte & 128) == 0);
1010
*endline = bounds->ar_line = bounds->opaque.computed_line;
1011
*column = code << 3 | (second_byte >> 4);
1012
*endcolumn = *column + (second_byte & 15);
1013
}
1014
}
1015
ASSERT_VALID_BOUNDS(bounds);
1016
}
1017
int
1018
PyCode_Addr2Location(PyCodeObject *co, int addrq,
1019
int *start_line, int *start_column,
1020
int *end_line, int *end_column)
1021
{
1022
if (addrq < 0) {
1023
*start_line = *end_line = co->co_firstlineno;
1024
*start_column = *end_column = 0;
1025
return 1;
1026
}
1027
assert(addrq >= 0 && addrq < _PyCode_NBYTES(co));
1028
PyCodeAddressRange bounds;
1029
_PyCode_InitAddressRange(co, &bounds);
1030
_PyCode_CheckLineNumber(addrq, &bounds);
1031
retreat(&bounds);
1032
advance_with_locations(&bounds, end_line, start_column, end_column);
1033
*start_line = bounds.ar_line;
1034
return 1;
1035
}
1036
1037
1038
static inline int
1039
at_end(PyCodeAddressRange *bounds) {
1040
return bounds->opaque.lo_next >= bounds->opaque.limit;
1041
}
1042
1043
int
1044
_PyLineTable_PreviousAddressRange(PyCodeAddressRange *range)
1045
{
1046
if (range->ar_start <= 0) {
1047
return 0;
1048
}
1049
retreat(range);
1050
assert(range->ar_end > range->ar_start);
1051
return 1;
1052
}
1053
1054
int
1055
_PyLineTable_NextAddressRange(PyCodeAddressRange *range)
1056
{
1057
if (at_end(range)) {
1058
return 0;
1059
}
1060
advance(range);
1061
assert(range->ar_end > range->ar_start);
1062
return 1;
1063
}
1064
1065
static int
1066
emit_pair(PyObject **bytes, int *offset, int a, int b)
1067
{
1068
Py_ssize_t len = PyBytes_GET_SIZE(*bytes);
1069
if (*offset + 2 >= len) {
1070
if (_PyBytes_Resize(bytes, len * 2) < 0)
1071
return 0;
1072
}
1073
unsigned char *lnotab = (unsigned char *) PyBytes_AS_STRING(*bytes);
1074
lnotab += *offset;
1075
*lnotab++ = a;
1076
*lnotab++ = b;
1077
*offset += 2;
1078
return 1;
1079
}
1080
1081
static int
1082
emit_delta(PyObject **bytes, int bdelta, int ldelta, int *offset)
1083
{
1084
while (bdelta > 255) {
1085
if (!emit_pair(bytes, offset, 255, 0)) {
1086
return 0;
1087
}
1088
bdelta -= 255;
1089
}
1090
while (ldelta > 127) {
1091
if (!emit_pair(bytes, offset, bdelta, 127)) {
1092
return 0;
1093
}
1094
bdelta = 0;
1095
ldelta -= 127;
1096
}
1097
while (ldelta < -128) {
1098
if (!emit_pair(bytes, offset, bdelta, -128)) {
1099
return 0;
1100
}
1101
bdelta = 0;
1102
ldelta += 128;
1103
}
1104
return emit_pair(bytes, offset, bdelta, ldelta);
1105
}
1106
1107
static PyObject *
1108
decode_linetable(PyCodeObject *code)
1109
{
1110
PyCodeAddressRange bounds;
1111
PyObject *bytes;
1112
int table_offset = 0;
1113
int code_offset = 0;
1114
int line = code->co_firstlineno;
1115
bytes = PyBytes_FromStringAndSize(NULL, 64);
1116
if (bytes == NULL) {
1117
return NULL;
1118
}
1119
_PyCode_InitAddressRange(code, &bounds);
1120
while (_PyLineTable_NextAddressRange(&bounds)) {
1121
if (bounds.opaque.computed_line != line) {
1122
int bdelta = bounds.ar_start - code_offset;
1123
int ldelta = bounds.opaque.computed_line - line;
1124
if (!emit_delta(&bytes, bdelta, ldelta, &table_offset)) {
1125
Py_DECREF(bytes);
1126
return NULL;
1127
}
1128
code_offset = bounds.ar_start;
1129
line = bounds.opaque.computed_line;
1130
}
1131
}
1132
_PyBytes_Resize(&bytes, table_offset);
1133
return bytes;
1134
}
1135
1136
1137
typedef struct {
1138
PyObject_HEAD
1139
PyCodeObject *li_code;
1140
PyCodeAddressRange li_line;
1141
} lineiterator;
1142
1143
1144
static void
1145
lineiter_dealloc(lineiterator *li)
1146
{
1147
Py_DECREF(li->li_code);
1148
Py_TYPE(li)->tp_free(li);
1149
}
1150
1151
static PyObject *
1152
_source_offset_converter(int *value) {
1153
if (*value == -1) {
1154
Py_RETURN_NONE;
1155
}
1156
return PyLong_FromLong(*value);
1157
}
1158
1159
static PyObject *
1160
lineiter_next(lineiterator *li)
1161
{
1162
PyCodeAddressRange *bounds = &li->li_line;
1163
if (!_PyLineTable_NextAddressRange(bounds)) {
1164
return NULL;
1165
}
1166
int start = bounds->ar_start;
1167
int line = bounds->ar_line;
1168
// Merge overlapping entries:
1169
while (_PyLineTable_NextAddressRange(bounds)) {
1170
if (bounds->ar_line != line) {
1171
_PyLineTable_PreviousAddressRange(bounds);
1172
break;
1173
}
1174
}
1175
return Py_BuildValue("iiO&", start, bounds->ar_end,
1176
_source_offset_converter, &line);
1177
}
1178
1179
PyTypeObject _PyLineIterator = {
1180
PyVarObject_HEAD_INIT(&PyType_Type, 0)
1181
"line_iterator", /* tp_name */
1182
sizeof(lineiterator), /* tp_basicsize */
1183
0, /* tp_itemsize */
1184
/* methods */
1185
(destructor)lineiter_dealloc, /* tp_dealloc */
1186
0, /* tp_vectorcall_offset */
1187
0, /* tp_getattr */
1188
0, /* tp_setattr */
1189
0, /* tp_as_async */
1190
0, /* tp_repr */
1191
0, /* tp_as_number */
1192
0, /* tp_as_sequence */
1193
0, /* tp_as_mapping */
1194
0, /* tp_hash */
1195
0, /* tp_call */
1196
0, /* tp_str */
1197
0, /* tp_getattro */
1198
0, /* tp_setattro */
1199
0, /* tp_as_buffer */
1200
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1201
0, /* tp_doc */
1202
0, /* tp_traverse */
1203
0, /* tp_clear */
1204
0, /* tp_richcompare */
1205
0, /* tp_weaklistoffset */
1206
PyObject_SelfIter, /* tp_iter */
1207
(iternextfunc)lineiter_next, /* tp_iternext */
1208
0, /* tp_methods */
1209
0, /* tp_members */
1210
0, /* tp_getset */
1211
0, /* tp_base */
1212
0, /* tp_dict */
1213
0, /* tp_descr_get */
1214
0, /* tp_descr_set */
1215
0, /* tp_dictoffset */
1216
0, /* tp_init */
1217
0, /* tp_alloc */
1218
0, /* tp_new */
1219
PyObject_Del, /* tp_free */
1220
};
1221
1222
static lineiterator *
1223
new_linesiterator(PyCodeObject *code)
1224
{
1225
lineiterator *li = (lineiterator *)PyType_GenericAlloc(&_PyLineIterator, 0);
1226
if (li == NULL) {
1227
return NULL;
1228
}
1229
li->li_code = (PyCodeObject*)Py_NewRef(code);
1230
_PyCode_InitAddressRange(code, &li->li_line);
1231
return li;
1232
}
1233
1234
/* co_positions iterator object. */
1235
typedef struct {
1236
PyObject_HEAD
1237
PyCodeObject* pi_code;
1238
PyCodeAddressRange pi_range;
1239
int pi_offset;
1240
int pi_endline;
1241
int pi_column;
1242
int pi_endcolumn;
1243
} positionsiterator;
1244
1245
static void
1246
positionsiter_dealloc(positionsiterator* pi)
1247
{
1248
Py_DECREF(pi->pi_code);
1249
Py_TYPE(pi)->tp_free(pi);
1250
}
1251
1252
static PyObject*
1253
positionsiter_next(positionsiterator* pi)
1254
{
1255
if (pi->pi_offset >= pi->pi_range.ar_end) {
1256
assert(pi->pi_offset == pi->pi_range.ar_end);
1257
if (at_end(&pi->pi_range)) {
1258
return NULL;
1259
}
1260
advance_with_locations(&pi->pi_range, &pi->pi_endline, &pi->pi_column, &pi->pi_endcolumn);
1261
}
1262
pi->pi_offset += 2;
1263
return Py_BuildValue("(O&O&O&O&)",
1264
_source_offset_converter, &pi->pi_range.ar_line,
1265
_source_offset_converter, &pi->pi_endline,
1266
_source_offset_converter, &pi->pi_column,
1267
_source_offset_converter, &pi->pi_endcolumn);
1268
}
1269
1270
PyTypeObject _PyPositionsIterator = {
1271
PyVarObject_HEAD_INIT(&PyType_Type, 0)
1272
"positions_iterator", /* tp_name */
1273
sizeof(positionsiterator), /* tp_basicsize */
1274
0, /* tp_itemsize */
1275
/* methods */
1276
(destructor)positionsiter_dealloc, /* tp_dealloc */
1277
0, /* tp_vectorcall_offset */
1278
0, /* tp_getattr */
1279
0, /* tp_setattr */
1280
0, /* tp_as_async */
1281
0, /* tp_repr */
1282
0, /* tp_as_number */
1283
0, /* tp_as_sequence */
1284
0, /* tp_as_mapping */
1285
0, /* tp_hash */
1286
0, /* tp_call */
1287
0, /* tp_str */
1288
0, /* tp_getattro */
1289
0, /* tp_setattro */
1290
0, /* tp_as_buffer */
1291
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1292
0, /* tp_doc */
1293
0, /* tp_traverse */
1294
0, /* tp_clear */
1295
0, /* tp_richcompare */
1296
0, /* tp_weaklistoffset */
1297
PyObject_SelfIter, /* tp_iter */
1298
(iternextfunc)positionsiter_next, /* tp_iternext */
1299
0, /* tp_methods */
1300
0, /* tp_members */
1301
0, /* tp_getset */
1302
0, /* tp_base */
1303
0, /* tp_dict */
1304
0, /* tp_descr_get */
1305
0, /* tp_descr_set */
1306
0, /* tp_dictoffset */
1307
0, /* tp_init */
1308
0, /* tp_alloc */
1309
0, /* tp_new */
1310
PyObject_Del, /* tp_free */
1311
};
1312
1313
static PyObject*
1314
code_positionsiterator(PyCodeObject* code, PyObject* Py_UNUSED(args))
1315
{
1316
positionsiterator* pi = (positionsiterator*)PyType_GenericAlloc(&_PyPositionsIterator, 0);
1317
if (pi == NULL) {
1318
return NULL;
1319
}
1320
pi->pi_code = (PyCodeObject*)Py_NewRef(code);
1321
_PyCode_InitAddressRange(code, &pi->pi_range);
1322
pi->pi_offset = pi->pi_range.ar_end;
1323
return (PyObject*)pi;
1324
}
1325
1326
1327
/******************
1328
* "extra" frame eval info (see PEP 523)
1329
******************/
1330
1331
/* Holder for co_extra information */
1332
typedef struct {
1333
Py_ssize_t ce_size;
1334
void *ce_extras[1];
1335
} _PyCodeObjectExtra;
1336
1337
1338
int
1339
PyUnstable_Code_GetExtra(PyObject *code, Py_ssize_t index, void **extra)
1340
{
1341
if (!PyCode_Check(code)) {
1342
PyErr_BadInternalCall();
1343
return -1;
1344
}
1345
1346
PyCodeObject *o = (PyCodeObject*) code;
1347
_PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra*) o->co_extra;
1348
1349
if (co_extra == NULL || index < 0 || co_extra->ce_size <= index) {
1350
*extra = NULL;
1351
return 0;
1352
}
1353
1354
*extra = co_extra->ce_extras[index];
1355
return 0;
1356
}
1357
1358
1359
int
1360
PyUnstable_Code_SetExtra(PyObject *code, Py_ssize_t index, void *extra)
1361
{
1362
PyInterpreterState *interp = _PyInterpreterState_GET();
1363
1364
if (!PyCode_Check(code) || index < 0 ||
1365
index >= interp->co_extra_user_count) {
1366
PyErr_BadInternalCall();
1367
return -1;
1368
}
1369
1370
PyCodeObject *o = (PyCodeObject*) code;
1371
_PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra *) o->co_extra;
1372
1373
if (co_extra == NULL || co_extra->ce_size <= index) {
1374
Py_ssize_t i = (co_extra == NULL ? 0 : co_extra->ce_size);
1375
co_extra = PyMem_Realloc(
1376
co_extra,
1377
sizeof(_PyCodeObjectExtra) +
1378
(interp->co_extra_user_count-1) * sizeof(void*));
1379
if (co_extra == NULL) {
1380
return -1;
1381
}
1382
for (; i < interp->co_extra_user_count; i++) {
1383
co_extra->ce_extras[i] = NULL;
1384
}
1385
co_extra->ce_size = interp->co_extra_user_count;
1386
o->co_extra = co_extra;
1387
}
1388
1389
if (co_extra->ce_extras[index] != NULL) {
1390
freefunc free = interp->co_extra_freefuncs[index];
1391
if (free != NULL) {
1392
free(co_extra->ce_extras[index]);
1393
}
1394
}
1395
1396
co_extra->ce_extras[index] = extra;
1397
return 0;
1398
}
1399
1400
1401
/******************
1402
* other PyCodeObject accessor functions
1403
******************/
1404
1405
static PyObject *
1406
get_cached_locals(PyCodeObject *co, PyObject **cached_field,
1407
_PyLocals_Kind kind, int num)
1408
{
1409
assert(cached_field != NULL);
1410
assert(co->_co_cached != NULL);
1411
if (*cached_field != NULL) {
1412
return Py_NewRef(*cached_field);
1413
}
1414
assert(*cached_field == NULL);
1415
PyObject *varnames = get_localsplus_names(co, kind, num);
1416
if (varnames == NULL) {
1417
return NULL;
1418
}
1419
*cached_field = Py_NewRef(varnames);
1420
return varnames;
1421
}
1422
1423
PyObject *
1424
_PyCode_GetVarnames(PyCodeObject *co)
1425
{
1426
if (init_co_cached(co)) {
1427
return NULL;
1428
}
1429
return get_cached_locals(co, &co->_co_cached->_co_varnames, CO_FAST_LOCAL, co->co_nlocals);
1430
}
1431
1432
PyObject *
1433
PyCode_GetVarnames(PyCodeObject *code)
1434
{
1435
return _PyCode_GetVarnames(code);
1436
}
1437
1438
PyObject *
1439
_PyCode_GetCellvars(PyCodeObject *co)
1440
{
1441
if (init_co_cached(co)) {
1442
return NULL;
1443
}
1444
return get_cached_locals(co, &co->_co_cached->_co_cellvars, CO_FAST_CELL, co->co_ncellvars);
1445
}
1446
1447
PyObject *
1448
PyCode_GetCellvars(PyCodeObject *code)
1449
{
1450
return _PyCode_GetCellvars(code);
1451
}
1452
1453
PyObject *
1454
_PyCode_GetFreevars(PyCodeObject *co)
1455
{
1456
if (init_co_cached(co)) {
1457
return NULL;
1458
}
1459
return get_cached_locals(co, &co->_co_cached->_co_freevars, CO_FAST_FREE, co->co_nfreevars);
1460
}
1461
1462
PyObject *
1463
PyCode_GetFreevars(PyCodeObject *code)
1464
{
1465
return _PyCode_GetFreevars(code);
1466
}
1467
1468
static void
1469
clear_executors(PyCodeObject *co)
1470
{
1471
for (int i = 0; i < co->co_executors->size; i++) {
1472
Py_CLEAR(co->co_executors->executors[i]);
1473
}
1474
PyMem_Free(co->co_executors);
1475
co->co_executors = NULL;
1476
}
1477
1478
static void
1479
deopt_code(PyCodeObject *code, _Py_CODEUNIT *instructions)
1480
{
1481
Py_ssize_t len = Py_SIZE(code);
1482
for (int i = 0; i < len; i++) {
1483
int opcode = _Py_GetBaseOpcode(code, i);
1484
if (opcode == ENTER_EXECUTOR) {
1485
_PyExecutorObject *exec = code->co_executors->executors[instructions[i].op.arg];
1486
opcode = exec->vm_data.opcode;
1487
instructions[i].op.arg = exec->vm_data.oparg;
1488
}
1489
assert(opcode != ENTER_EXECUTOR);
1490
int caches = _PyOpcode_Caches[opcode];
1491
instructions[i].op.code = opcode;
1492
for (int j = 1; j <= caches; j++) {
1493
instructions[i+j].cache = 0;
1494
}
1495
i += caches;
1496
}
1497
}
1498
1499
PyObject *
1500
_PyCode_GetCode(PyCodeObject *co)
1501
{
1502
if (init_co_cached(co)) {
1503
return NULL;
1504
}
1505
if (co->_co_cached->_co_code != NULL) {
1506
return Py_NewRef(co->_co_cached->_co_code);
1507
}
1508
PyObject *code = PyBytes_FromStringAndSize((const char *)_PyCode_CODE(co),
1509
_PyCode_NBYTES(co));
1510
if (code == NULL) {
1511
return NULL;
1512
}
1513
deopt_code(co, (_Py_CODEUNIT *)PyBytes_AS_STRING(code));
1514
assert(co->_co_cached->_co_code == NULL);
1515
co->_co_cached->_co_code = Py_NewRef(code);
1516
return code;
1517
}
1518
1519
PyObject *
1520
PyCode_GetCode(PyCodeObject *co)
1521
{
1522
return _PyCode_GetCode(co);
1523
}
1524
1525
/******************
1526
* PyCode_Type
1527
******************/
1528
1529
/*[clinic input]
1530
class code "PyCodeObject *" "&PyCode_Type"
1531
[clinic start generated code]*/
1532
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=78aa5d576683bb4b]*/
1533
1534
/*[clinic input]
1535
@classmethod
1536
code.__new__ as code_new
1537
1538
argcount: int
1539
posonlyargcount: int
1540
kwonlyargcount: int
1541
nlocals: int
1542
stacksize: int
1543
flags: int
1544
codestring as code: object(subclass_of="&PyBytes_Type")
1545
constants as consts: object(subclass_of="&PyTuple_Type")
1546
names: object(subclass_of="&PyTuple_Type")
1547
varnames: object(subclass_of="&PyTuple_Type")
1548
filename: unicode
1549
name: unicode
1550
qualname: unicode
1551
firstlineno: int
1552
linetable: object(subclass_of="&PyBytes_Type")
1553
exceptiontable: object(subclass_of="&PyBytes_Type")
1554
freevars: object(subclass_of="&PyTuple_Type", c_default="NULL") = ()
1555
cellvars: object(subclass_of="&PyTuple_Type", c_default="NULL") = ()
1556
/
1557
1558
Create a code object. Not for the faint of heart.
1559
[clinic start generated code]*/
1560
1561
static PyObject *
1562
code_new_impl(PyTypeObject *type, int argcount, int posonlyargcount,
1563
int kwonlyargcount, int nlocals, int stacksize, int flags,
1564
PyObject *code, PyObject *consts, PyObject *names,
1565
PyObject *varnames, PyObject *filename, PyObject *name,
1566
PyObject *qualname, int firstlineno, PyObject *linetable,
1567
PyObject *exceptiontable, PyObject *freevars,
1568
PyObject *cellvars)
1569
/*[clinic end generated code: output=069fa20d299f9dda input=e31da3c41ad8064a]*/
1570
{
1571
PyObject *co = NULL;
1572
PyObject *ournames = NULL;
1573
PyObject *ourvarnames = NULL;
1574
PyObject *ourfreevars = NULL;
1575
PyObject *ourcellvars = NULL;
1576
1577
if (PySys_Audit("code.__new__", "OOOiiiiii",
1578
code, filename, name, argcount, posonlyargcount,
1579
kwonlyargcount, nlocals, stacksize, flags) < 0) {
1580
goto cleanup;
1581
}
1582
1583
if (argcount < 0) {
1584
PyErr_SetString(
1585
PyExc_ValueError,
1586
"code: argcount must not be negative");
1587
goto cleanup;
1588
}
1589
1590
if (posonlyargcount < 0) {
1591
PyErr_SetString(
1592
PyExc_ValueError,
1593
"code: posonlyargcount must not be negative");
1594
goto cleanup;
1595
}
1596
1597
if (kwonlyargcount < 0) {
1598
PyErr_SetString(
1599
PyExc_ValueError,
1600
"code: kwonlyargcount must not be negative");
1601
goto cleanup;
1602
}
1603
if (nlocals < 0) {
1604
PyErr_SetString(
1605
PyExc_ValueError,
1606
"code: nlocals must not be negative");
1607
goto cleanup;
1608
}
1609
1610
ournames = validate_and_copy_tuple(names);
1611
if (ournames == NULL)
1612
goto cleanup;
1613
ourvarnames = validate_and_copy_tuple(varnames);
1614
if (ourvarnames == NULL)
1615
goto cleanup;
1616
if (freevars)
1617
ourfreevars = validate_and_copy_tuple(freevars);
1618
else
1619
ourfreevars = PyTuple_New(0);
1620
if (ourfreevars == NULL)
1621
goto cleanup;
1622
if (cellvars)
1623
ourcellvars = validate_and_copy_tuple(cellvars);
1624
else
1625
ourcellvars = PyTuple_New(0);
1626
if (ourcellvars == NULL)
1627
goto cleanup;
1628
1629
co = (PyObject *)PyCode_NewWithPosOnlyArgs(argcount, posonlyargcount,
1630
kwonlyargcount,
1631
nlocals, stacksize, flags,
1632
code, consts, ournames,
1633
ourvarnames, ourfreevars,
1634
ourcellvars, filename,
1635
name, qualname, firstlineno,
1636
linetable,
1637
exceptiontable
1638
);
1639
cleanup:
1640
Py_XDECREF(ournames);
1641
Py_XDECREF(ourvarnames);
1642
Py_XDECREF(ourfreevars);
1643
Py_XDECREF(ourcellvars);
1644
return co;
1645
}
1646
1647
static void
1648
free_monitoring_data(_PyCoMonitoringData *data)
1649
{
1650
if (data == NULL) {
1651
return;
1652
}
1653
if (data->tools) {
1654
PyMem_Free(data->tools);
1655
}
1656
if (data->lines) {
1657
PyMem_Free(data->lines);
1658
}
1659
if (data->line_tools) {
1660
PyMem_Free(data->line_tools);
1661
}
1662
if (data->per_instruction_opcodes) {
1663
PyMem_Free(data->per_instruction_opcodes);
1664
}
1665
if (data->per_instruction_tools) {
1666
PyMem_Free(data->per_instruction_tools);
1667
}
1668
PyMem_Free(data);
1669
}
1670
1671
static void
1672
code_dealloc(PyCodeObject *co)
1673
{
1674
assert(Py_REFCNT(co) == 0);
1675
Py_SET_REFCNT(co, 1);
1676
notify_code_watchers(PY_CODE_EVENT_DESTROY, co);
1677
if (Py_REFCNT(co) > 1) {
1678
Py_SET_REFCNT(co, Py_REFCNT(co) - 1);
1679
return;
1680
}
1681
Py_SET_REFCNT(co, 0);
1682
1683
if (co->co_extra != NULL) {
1684
PyInterpreterState *interp = _PyInterpreterState_GET();
1685
_PyCodeObjectExtra *co_extra = co->co_extra;
1686
1687
for (Py_ssize_t i = 0; i < co_extra->ce_size; i++) {
1688
freefunc free_extra = interp->co_extra_freefuncs[i];
1689
1690
if (free_extra != NULL) {
1691
free_extra(co_extra->ce_extras[i]);
1692
}
1693
}
1694
1695
PyMem_Free(co_extra);
1696
}
1697
if (co->co_executors != NULL) {
1698
clear_executors(co);
1699
}
1700
1701
Py_XDECREF(co->co_consts);
1702
Py_XDECREF(co->co_names);
1703
Py_XDECREF(co->co_localsplusnames);
1704
Py_XDECREF(co->co_localspluskinds);
1705
Py_XDECREF(co->co_filename);
1706
Py_XDECREF(co->co_name);
1707
Py_XDECREF(co->co_qualname);
1708
Py_XDECREF(co->co_linetable);
1709
Py_XDECREF(co->co_exceptiontable);
1710
if (co->_co_cached != NULL) {
1711
Py_XDECREF(co->_co_cached->_co_code);
1712
Py_XDECREF(co->_co_cached->_co_cellvars);
1713
Py_XDECREF(co->_co_cached->_co_freevars);
1714
Py_XDECREF(co->_co_cached->_co_varnames);
1715
PyMem_Free(co->_co_cached);
1716
}
1717
if (co->co_weakreflist != NULL) {
1718
PyObject_ClearWeakRefs((PyObject*)co);
1719
}
1720
free_monitoring_data(co->_co_monitoring);
1721
PyObject_Free(co);
1722
}
1723
1724
static PyObject *
1725
code_repr(PyCodeObject *co)
1726
{
1727
int lineno;
1728
if (co->co_firstlineno != 0)
1729
lineno = co->co_firstlineno;
1730
else
1731
lineno = -1;
1732
if (co->co_filename && PyUnicode_Check(co->co_filename)) {
1733
return PyUnicode_FromFormat(
1734
"<code object %U at %p, file \"%U\", line %d>",
1735
co->co_name, co, co->co_filename, lineno);
1736
} else {
1737
return PyUnicode_FromFormat(
1738
"<code object %U at %p, file ???, line %d>",
1739
co->co_name, co, lineno);
1740
}
1741
}
1742
1743
static PyObject *
1744
code_richcompare(PyObject *self, PyObject *other, int op)
1745
{
1746
PyCodeObject *co, *cp;
1747
int eq;
1748
PyObject *consts1, *consts2;
1749
PyObject *res;
1750
1751
if ((op != Py_EQ && op != Py_NE) ||
1752
!PyCode_Check(self) ||
1753
!PyCode_Check(other)) {
1754
Py_RETURN_NOTIMPLEMENTED;
1755
}
1756
1757
co = (PyCodeObject *)self;
1758
cp = (PyCodeObject *)other;
1759
1760
eq = PyObject_RichCompareBool(co->co_name, cp->co_name, Py_EQ);
1761
if (!eq) goto unequal;
1762
eq = co->co_argcount == cp->co_argcount;
1763
if (!eq) goto unequal;
1764
eq = co->co_posonlyargcount == cp->co_posonlyargcount;
1765
if (!eq) goto unequal;
1766
eq = co->co_kwonlyargcount == cp->co_kwonlyargcount;
1767
if (!eq) goto unequal;
1768
eq = co->co_flags == cp->co_flags;
1769
if (!eq) goto unequal;
1770
eq = co->co_firstlineno == cp->co_firstlineno;
1771
if (!eq) goto unequal;
1772
eq = Py_SIZE(co) == Py_SIZE(cp);
1773
if (!eq) {
1774
goto unequal;
1775
}
1776
for (int i = 0; i < Py_SIZE(co); i++) {
1777
_Py_CODEUNIT co_instr = _PyCode_CODE(co)[i];
1778
_Py_CODEUNIT cp_instr = _PyCode_CODE(cp)[i];
1779
co_instr.op.code = _PyOpcode_Deopt[co_instr.op.code];
1780
cp_instr.op.code = _PyOpcode_Deopt[cp_instr.op.code];
1781
eq = co_instr.cache == cp_instr.cache;
1782
if (!eq) {
1783
goto unequal;
1784
}
1785
i += _PyOpcode_Caches[co_instr.op.code];
1786
}
1787
1788
/* compare constants */
1789
consts1 = _PyCode_ConstantKey(co->co_consts);
1790
if (!consts1)
1791
return NULL;
1792
consts2 = _PyCode_ConstantKey(cp->co_consts);
1793
if (!consts2) {
1794
Py_DECREF(consts1);
1795
return NULL;
1796
}
1797
eq = PyObject_RichCompareBool(consts1, consts2, Py_EQ);
1798
Py_DECREF(consts1);
1799
Py_DECREF(consts2);
1800
if (eq <= 0) goto unequal;
1801
1802
eq = PyObject_RichCompareBool(co->co_names, cp->co_names, Py_EQ);
1803
if (eq <= 0) goto unequal;
1804
eq = PyObject_RichCompareBool(co->co_localsplusnames,
1805
cp->co_localsplusnames, Py_EQ);
1806
if (eq <= 0) goto unequal;
1807
eq = PyObject_RichCompareBool(co->co_linetable, cp->co_linetable, Py_EQ);
1808
if (eq <= 0) {
1809
goto unequal;
1810
}
1811
eq = PyObject_RichCompareBool(co->co_exceptiontable,
1812
cp->co_exceptiontable, Py_EQ);
1813
if (eq <= 0) {
1814
goto unequal;
1815
}
1816
1817
if (op == Py_EQ)
1818
res = Py_True;
1819
else
1820
res = Py_False;
1821
goto done;
1822
1823
unequal:
1824
if (eq < 0)
1825
return NULL;
1826
if (op == Py_NE)
1827
res = Py_True;
1828
else
1829
res = Py_False;
1830
1831
done:
1832
return Py_NewRef(res);
1833
}
1834
1835
static Py_hash_t
1836
code_hash(PyCodeObject *co)
1837
{
1838
Py_uhash_t uhash = 20221211;
1839
#define SCRAMBLE_IN(H) do { \
1840
uhash ^= (Py_uhash_t)(H); \
1841
uhash *= _PyHASH_MULTIPLIER; \
1842
} while (0)
1843
#define SCRAMBLE_IN_HASH(EXPR) do { \
1844
Py_hash_t h = PyObject_Hash(EXPR); \
1845
if (h == -1) { \
1846
return -1; \
1847
} \
1848
SCRAMBLE_IN(h); \
1849
} while (0)
1850
1851
SCRAMBLE_IN_HASH(co->co_name);
1852
SCRAMBLE_IN_HASH(co->co_consts);
1853
SCRAMBLE_IN_HASH(co->co_names);
1854
SCRAMBLE_IN_HASH(co->co_localsplusnames);
1855
SCRAMBLE_IN_HASH(co->co_linetable);
1856
SCRAMBLE_IN_HASH(co->co_exceptiontable);
1857
SCRAMBLE_IN(co->co_argcount);
1858
SCRAMBLE_IN(co->co_posonlyargcount);
1859
SCRAMBLE_IN(co->co_kwonlyargcount);
1860
SCRAMBLE_IN(co->co_flags);
1861
SCRAMBLE_IN(co->co_firstlineno);
1862
SCRAMBLE_IN(Py_SIZE(co));
1863
for (int i = 0; i < Py_SIZE(co); i++) {
1864
int deop = _Py_GetBaseOpcode(co, i);
1865
SCRAMBLE_IN(deop);
1866
SCRAMBLE_IN(_PyCode_CODE(co)[i].op.arg);
1867
i += _PyOpcode_Caches[deop];
1868
}
1869
if ((Py_hash_t)uhash == -1) {
1870
return -2;
1871
}
1872
return (Py_hash_t)uhash;
1873
}
1874
1875
1876
#define OFF(x) offsetof(PyCodeObject, x)
1877
1878
static PyMemberDef code_memberlist[] = {
1879
{"co_argcount", T_INT, OFF(co_argcount), READONLY},
1880
{"co_posonlyargcount", T_INT, OFF(co_posonlyargcount), READONLY},
1881
{"co_kwonlyargcount", T_INT, OFF(co_kwonlyargcount), READONLY},
1882
{"co_stacksize", T_INT, OFF(co_stacksize), READONLY},
1883
{"co_flags", T_INT, OFF(co_flags), READONLY},
1884
{"co_nlocals", T_INT, OFF(co_nlocals), READONLY},
1885
{"co_consts", T_OBJECT, OFF(co_consts), READONLY},
1886
{"co_names", T_OBJECT, OFF(co_names), READONLY},
1887
{"co_filename", T_OBJECT, OFF(co_filename), READONLY},
1888
{"co_name", T_OBJECT, OFF(co_name), READONLY},
1889
{"co_qualname", T_OBJECT, OFF(co_qualname), READONLY},
1890
{"co_firstlineno", T_INT, OFF(co_firstlineno), READONLY},
1891
{"co_linetable", T_OBJECT, OFF(co_linetable), READONLY},
1892
{"co_exceptiontable", T_OBJECT, OFF(co_exceptiontable), READONLY},
1893
{NULL} /* Sentinel */
1894
};
1895
1896
1897
static PyObject *
1898
code_getlnotab(PyCodeObject *code, void *closure)
1899
{
1900
if (PyErr_WarnEx(PyExc_DeprecationWarning,
1901
"co_lnotab is deprecated, use co_lines instead.",
1902
1) < 0) {
1903
return NULL;
1904
}
1905
return decode_linetable(code);
1906
}
1907
1908
static PyObject *
1909
code_getvarnames(PyCodeObject *code, void *closure)
1910
{
1911
return _PyCode_GetVarnames(code);
1912
}
1913
1914
static PyObject *
1915
code_getcellvars(PyCodeObject *code, void *closure)
1916
{
1917
return _PyCode_GetCellvars(code);
1918
}
1919
1920
static PyObject *
1921
code_getfreevars(PyCodeObject *code, void *closure)
1922
{
1923
return _PyCode_GetFreevars(code);
1924
}
1925
1926
static PyObject *
1927
code_getcodeadaptive(PyCodeObject *code, void *closure)
1928
{
1929
return PyBytes_FromStringAndSize(code->co_code_adaptive,
1930
_PyCode_NBYTES(code));
1931
}
1932
1933
static PyObject *
1934
code_getcode(PyCodeObject *code, void *closure)
1935
{
1936
return _PyCode_GetCode(code);
1937
}
1938
1939
static PyGetSetDef code_getsetlist[] = {
1940
{"co_lnotab", (getter)code_getlnotab, NULL, NULL},
1941
{"_co_code_adaptive", (getter)code_getcodeadaptive, NULL, NULL},
1942
// The following old names are kept for backward compatibility.
1943
{"co_varnames", (getter)code_getvarnames, NULL, NULL},
1944
{"co_cellvars", (getter)code_getcellvars, NULL, NULL},
1945
{"co_freevars", (getter)code_getfreevars, NULL, NULL},
1946
{"co_code", (getter)code_getcode, NULL, NULL},
1947
{0}
1948
};
1949
1950
1951
static PyObject *
1952
code_sizeof(PyCodeObject *co, PyObject *Py_UNUSED(args))
1953
{
1954
size_t res = _PyObject_VAR_SIZE(Py_TYPE(co), Py_SIZE(co));
1955
_PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra*) co->co_extra;
1956
if (co_extra != NULL) {
1957
res += sizeof(_PyCodeObjectExtra);
1958
res += ((size_t)co_extra->ce_size - 1) * sizeof(co_extra->ce_extras[0]);
1959
}
1960
return PyLong_FromSize_t(res);
1961
}
1962
1963
static PyObject *
1964
code_linesiterator(PyCodeObject *code, PyObject *Py_UNUSED(args))
1965
{
1966
return (PyObject *)new_linesiterator(code);
1967
}
1968
1969
/*[clinic input]
1970
code.replace
1971
1972
*
1973
co_argcount: int(c_default="self->co_argcount") = -1
1974
co_posonlyargcount: int(c_default="self->co_posonlyargcount") = -1
1975
co_kwonlyargcount: int(c_default="self->co_kwonlyargcount") = -1
1976
co_nlocals: int(c_default="self->co_nlocals") = -1
1977
co_stacksize: int(c_default="self->co_stacksize") = -1
1978
co_flags: int(c_default="self->co_flags") = -1
1979
co_firstlineno: int(c_default="self->co_firstlineno") = -1
1980
co_code: PyBytesObject(c_default="NULL") = None
1981
co_consts: object(subclass_of="&PyTuple_Type", c_default="self->co_consts") = None
1982
co_names: object(subclass_of="&PyTuple_Type", c_default="self->co_names") = None
1983
co_varnames: object(subclass_of="&PyTuple_Type", c_default="NULL") = None
1984
co_freevars: object(subclass_of="&PyTuple_Type", c_default="NULL") = None
1985
co_cellvars: object(subclass_of="&PyTuple_Type", c_default="NULL") = None
1986
co_filename: unicode(c_default="self->co_filename") = None
1987
co_name: unicode(c_default="self->co_name") = None
1988
co_qualname: unicode(c_default="self->co_qualname") = None
1989
co_linetable: PyBytesObject(c_default="(PyBytesObject *)self->co_linetable") = None
1990
co_exceptiontable: PyBytesObject(c_default="(PyBytesObject *)self->co_exceptiontable") = None
1991
1992
Return a copy of the code object with new values for the specified fields.
1993
[clinic start generated code]*/
1994
1995
static PyObject *
1996
code_replace_impl(PyCodeObject *self, int co_argcount,
1997
int co_posonlyargcount, int co_kwonlyargcount,
1998
int co_nlocals, int co_stacksize, int co_flags,
1999
int co_firstlineno, PyBytesObject *co_code,
2000
PyObject *co_consts, PyObject *co_names,
2001
PyObject *co_varnames, PyObject *co_freevars,
2002
PyObject *co_cellvars, PyObject *co_filename,
2003
PyObject *co_name, PyObject *co_qualname,
2004
PyBytesObject *co_linetable,
2005
PyBytesObject *co_exceptiontable)
2006
/*[clinic end generated code: output=b6cd9988391d5711 input=f6f68e03571f8d7c]*/
2007
{
2008
#define CHECK_INT_ARG(ARG) \
2009
if (ARG < 0) { \
2010
PyErr_SetString(PyExc_ValueError, \
2011
#ARG " must be a positive integer"); \
2012
return NULL; \
2013
}
2014
2015
CHECK_INT_ARG(co_argcount);
2016
CHECK_INT_ARG(co_posonlyargcount);
2017
CHECK_INT_ARG(co_kwonlyargcount);
2018
CHECK_INT_ARG(co_nlocals);
2019
CHECK_INT_ARG(co_stacksize);
2020
CHECK_INT_ARG(co_flags);
2021
CHECK_INT_ARG(co_firstlineno);
2022
2023
#undef CHECK_INT_ARG
2024
2025
PyObject *code = NULL;
2026
if (co_code == NULL) {
2027
code = _PyCode_GetCode(self);
2028
if (code == NULL) {
2029
return NULL;
2030
}
2031
co_code = (PyBytesObject *)code;
2032
}
2033
2034
if (PySys_Audit("code.__new__", "OOOiiiiii",
2035
co_code, co_filename, co_name, co_argcount,
2036
co_posonlyargcount, co_kwonlyargcount, co_nlocals,
2037
co_stacksize, co_flags) < 0) {
2038
Py_XDECREF(code);
2039
return NULL;
2040
}
2041
2042
PyCodeObject *co = NULL;
2043
PyObject *varnames = NULL;
2044
PyObject *cellvars = NULL;
2045
PyObject *freevars = NULL;
2046
if (co_varnames == NULL) {
2047
varnames = get_localsplus_names(self, CO_FAST_LOCAL, self->co_nlocals);
2048
if (varnames == NULL) {
2049
goto error;
2050
}
2051
co_varnames = varnames;
2052
}
2053
if (co_cellvars == NULL) {
2054
cellvars = get_localsplus_names(self, CO_FAST_CELL, self->co_ncellvars);
2055
if (cellvars == NULL) {
2056
goto error;
2057
}
2058
co_cellvars = cellvars;
2059
}
2060
if (co_freevars == NULL) {
2061
freevars = get_localsplus_names(self, CO_FAST_FREE, self->co_nfreevars);
2062
if (freevars == NULL) {
2063
goto error;
2064
}
2065
co_freevars = freevars;
2066
}
2067
2068
co = PyCode_NewWithPosOnlyArgs(
2069
co_argcount, co_posonlyargcount, co_kwonlyargcount, co_nlocals,
2070
co_stacksize, co_flags, (PyObject*)co_code, co_consts, co_names,
2071
co_varnames, co_freevars, co_cellvars, co_filename, co_name,
2072
co_qualname, co_firstlineno,
2073
(PyObject*)co_linetable, (PyObject*)co_exceptiontable);
2074
2075
error:
2076
Py_XDECREF(code);
2077
Py_XDECREF(varnames);
2078
Py_XDECREF(cellvars);
2079
Py_XDECREF(freevars);
2080
return (PyObject *)co;
2081
}
2082
2083
/*[clinic input]
2084
code._varname_from_oparg
2085
2086
oparg: int
2087
2088
(internal-only) Return the local variable name for the given oparg.
2089
2090
WARNING: this method is for internal use only and may change or go away.
2091
[clinic start generated code]*/
2092
2093
static PyObject *
2094
code__varname_from_oparg_impl(PyCodeObject *self, int oparg)
2095
/*[clinic end generated code: output=1fd1130413184206 input=c5fa3ee9bac7d4ca]*/
2096
{
2097
PyObject *name = PyTuple_GetItem(self->co_localsplusnames, oparg);
2098
if (name == NULL) {
2099
return NULL;
2100
}
2101
return Py_NewRef(name);
2102
}
2103
2104
/* XXX code objects need to participate in GC? */
2105
2106
static struct PyMethodDef code_methods[] = {
2107
{"__sizeof__", (PyCFunction)code_sizeof, METH_NOARGS},
2108
{"co_lines", (PyCFunction)code_linesiterator, METH_NOARGS},
2109
{"co_positions", (PyCFunction)code_positionsiterator, METH_NOARGS},
2110
CODE_REPLACE_METHODDEF
2111
CODE__VARNAME_FROM_OPARG_METHODDEF
2112
{NULL, NULL} /* sentinel */
2113
};
2114
2115
2116
PyTypeObject PyCode_Type = {
2117
PyVarObject_HEAD_INIT(&PyType_Type, 0)
2118
"code",
2119
offsetof(PyCodeObject, co_code_adaptive),
2120
sizeof(_Py_CODEUNIT),
2121
(destructor)code_dealloc, /* tp_dealloc */
2122
0, /* tp_vectorcall_offset */
2123
0, /* tp_getattr */
2124
0, /* tp_setattr */
2125
0, /* tp_as_async */
2126
(reprfunc)code_repr, /* tp_repr */
2127
0, /* tp_as_number */
2128
0, /* tp_as_sequence */
2129
0, /* tp_as_mapping */
2130
(hashfunc)code_hash, /* tp_hash */
2131
0, /* tp_call */
2132
0, /* tp_str */
2133
PyObject_GenericGetAttr, /* tp_getattro */
2134
0, /* tp_setattro */
2135
0, /* tp_as_buffer */
2136
Py_TPFLAGS_DEFAULT, /* tp_flags */
2137
code_new__doc__, /* tp_doc */
2138
0, /* tp_traverse */
2139
0, /* tp_clear */
2140
code_richcompare, /* tp_richcompare */
2141
offsetof(PyCodeObject, co_weakreflist), /* tp_weaklistoffset */
2142
0, /* tp_iter */
2143
0, /* tp_iternext */
2144
code_methods, /* tp_methods */
2145
code_memberlist, /* tp_members */
2146
code_getsetlist, /* tp_getset */
2147
0, /* tp_base */
2148
0, /* tp_dict */
2149
0, /* tp_descr_get */
2150
0, /* tp_descr_set */
2151
0, /* tp_dictoffset */
2152
0, /* tp_init */
2153
0, /* tp_alloc */
2154
code_new, /* tp_new */
2155
};
2156
2157
2158
/******************
2159
* other API
2160
******************/
2161
2162
PyObject*
2163
_PyCode_ConstantKey(PyObject *op)
2164
{
2165
PyObject *key;
2166
2167
/* Py_None and Py_Ellipsis are singletons. */
2168
if (op == Py_None || op == Py_Ellipsis
2169
|| PyLong_CheckExact(op)
2170
|| PyUnicode_CheckExact(op)
2171
/* code_richcompare() uses _PyCode_ConstantKey() internally */
2172
|| PyCode_Check(op))
2173
{
2174
/* Objects of these types are always different from object of other
2175
* type and from tuples. */
2176
key = Py_NewRef(op);
2177
}
2178
else if (PyBool_Check(op) || PyBytes_CheckExact(op)) {
2179
/* Make booleans different from integers 0 and 1.
2180
* Avoid BytesWarning from comparing bytes with strings. */
2181
key = PyTuple_Pack(2, Py_TYPE(op), op);
2182
}
2183
else if (PyFloat_CheckExact(op)) {
2184
double d = PyFloat_AS_DOUBLE(op);
2185
/* all we need is to make the tuple different in either the 0.0
2186
* or -0.0 case from all others, just to avoid the "coercion".
2187
*/
2188
if (d == 0.0 && copysign(1.0, d) < 0.0)
2189
key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
2190
else
2191
key = PyTuple_Pack(2, Py_TYPE(op), op);
2192
}
2193
else if (PyComplex_CheckExact(op)) {
2194
Py_complex z;
2195
int real_negzero, imag_negzero;
2196
/* For the complex case we must make complex(x, 0.)
2197
different from complex(x, -0.) and complex(0., y)
2198
different from complex(-0., y), for any x and y.
2199
All four complex zeros must be distinguished.*/
2200
z = PyComplex_AsCComplex(op);
2201
real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
2202
imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
2203
/* use True, False and None singleton as tags for the real and imag
2204
* sign, to make tuples different */
2205
if (real_negzero && imag_negzero) {
2206
key = PyTuple_Pack(3, Py_TYPE(op), op, Py_True);
2207
}
2208
else if (imag_negzero) {
2209
key = PyTuple_Pack(3, Py_TYPE(op), op, Py_False);
2210
}
2211
else if (real_negzero) {
2212
key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
2213
}
2214
else {
2215
key = PyTuple_Pack(2, Py_TYPE(op), op);
2216
}
2217
}
2218
else if (PyTuple_CheckExact(op)) {
2219
Py_ssize_t i, len;
2220
PyObject *tuple;
2221
2222
len = PyTuple_GET_SIZE(op);
2223
tuple = PyTuple_New(len);
2224
if (tuple == NULL)
2225
return NULL;
2226
2227
for (i=0; i < len; i++) {
2228
PyObject *item, *item_key;
2229
2230
item = PyTuple_GET_ITEM(op, i);
2231
item_key = _PyCode_ConstantKey(item);
2232
if (item_key == NULL) {
2233
Py_DECREF(tuple);
2234
return NULL;
2235
}
2236
2237
PyTuple_SET_ITEM(tuple, i, item_key);
2238
}
2239
2240
key = PyTuple_Pack(2, tuple, op);
2241
Py_DECREF(tuple);
2242
}
2243
else if (PyFrozenSet_CheckExact(op)) {
2244
Py_ssize_t pos = 0;
2245
PyObject *item;
2246
Py_hash_t hash;
2247
Py_ssize_t i, len;
2248
PyObject *tuple, *set;
2249
2250
len = PySet_GET_SIZE(op);
2251
tuple = PyTuple_New(len);
2252
if (tuple == NULL)
2253
return NULL;
2254
2255
i = 0;
2256
while (_PySet_NextEntry(op, &pos, &item, &hash)) {
2257
PyObject *item_key;
2258
2259
item_key = _PyCode_ConstantKey(item);
2260
if (item_key == NULL) {
2261
Py_DECREF(tuple);
2262
return NULL;
2263
}
2264
2265
assert(i < len);
2266
PyTuple_SET_ITEM(tuple, i, item_key);
2267
i++;
2268
}
2269
set = PyFrozenSet_New(tuple);
2270
Py_DECREF(tuple);
2271
if (set == NULL)
2272
return NULL;
2273
2274
key = PyTuple_Pack(2, set, op);
2275
Py_DECREF(set);
2276
return key;
2277
}
2278
else {
2279
/* for other types, use the object identifier as a unique identifier
2280
* to ensure that they are seen as unequal. */
2281
PyObject *obj_id = PyLong_FromVoidPtr(op);
2282
if (obj_id == NULL)
2283
return NULL;
2284
2285
key = PyTuple_Pack(2, obj_id, op);
2286
Py_DECREF(obj_id);
2287
}
2288
return key;
2289
}
2290
2291
void
2292
_PyStaticCode_Fini(PyCodeObject *co)
2293
{
2294
deopt_code(co, _PyCode_CODE(co));
2295
if (co->co_executors != NULL) {
2296
clear_executors(co);
2297
}
2298
PyMem_Free(co->co_extra);
2299
if (co->_co_cached != NULL) {
2300
Py_CLEAR(co->_co_cached->_co_code);
2301
Py_CLEAR(co->_co_cached->_co_cellvars);
2302
Py_CLEAR(co->_co_cached->_co_freevars);
2303
Py_CLEAR(co->_co_cached->_co_varnames);
2304
PyMem_Free(co->_co_cached);
2305
co->_co_cached = NULL;
2306
}
2307
co->co_extra = NULL;
2308
if (co->co_weakreflist != NULL) {
2309
PyObject_ClearWeakRefs((PyObject *)co);
2310
co->co_weakreflist = NULL;
2311
}
2312
free_monitoring_data(co->_co_monitoring);
2313
co->_co_monitoring = NULL;
2314
}
2315
2316
int
2317
_PyStaticCode_Init(PyCodeObject *co)
2318
{
2319
int res = intern_strings(co->co_names);
2320
if (res < 0) {
2321
return -1;
2322
}
2323
res = intern_string_constants(co->co_consts, NULL);
2324
if (res < 0) {
2325
return -1;
2326
}
2327
res = intern_strings(co->co_localsplusnames);
2328
if (res < 0) {
2329
return -1;
2330
}
2331
_PyCode_Quicken(co);
2332
return 0;
2333
}
2334
2335
#define MAX_CODE_UNITS_PER_LOC_ENTRY 8
2336
2337