Coverage Report

Created: 2026-08-28 06:28

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython3/Objects/codeobject.c
Line
Count
Source
1
#include "Python.h"
2
#include "opcode.h"
3
4
#include "pycore_code.h"          // _PyCodeConstructor
5
#include "pycore_function.h"      // _PyFunction_ClearCodeByVersion()
6
#include "pycore_hashtable.h"     // _Py_hashtable_t
7
#include "pycore_index_pool.h"    // _PyIndexPool_Fini()
8
#include "pycore_initconfig.h"    // _PyStatus_OK()
9
#include "pycore_interp.h"        // PyInterpreterState.co_extra_freefuncs
10
#include "pycore_interpframe.h"   // FRAME_SPECIALS_SIZE
11
#include "pycore_opcode_metadata.h" // _PyOpcode_Caches
12
#include "pycore_opcode_utils.h"  // RESUME_AT_FUNC_START
13
#include "pycore_optimizer.h"     // _Py_ExecutorDetach
14
#include "pycore_pymem.h"         // _PyMem_FreeDelayed()
15
#include "pycore_pystate.h"       // _PyInterpreterState_GET()
16
#include "pycore_setobject.h"     // _PySet_NextEntry()
17
#include "pycore_tuple.h"         // _PyTuple_ITEMS()
18
#include "pycore_unicodeobject.h" // _PyUnicode_InternImmortal()
19
#include "pycore_uniqueid.h"      // _PyObject_AssignUniqueId()
20
#include "pycore_weakref.h"       // FT_CLEAR_WEAKREFS()
21
22
#include "clinic/codeobject.c.h"
23
#include <stdbool.h>
24
25
26
#define INITIAL_SPECIALIZED_CODE_SIZE 16
27
28
static const char *
29
0
code_event_name(PyCodeEvent event) {
30
0
    switch (event) {
31
0
        #define CASE(op)                \
32
0
        case PY_CODE_EVENT_##op:         \
33
0
            return "PY_CODE_EVENT_" #op;
34
0
        PY_FOREACH_CODE_EVENT(CASE)
35
0
        #undef CASE
36
0
    }
37
0
    Py_UNREACHABLE();
38
0
}
39
40
static void
41
notify_code_watchers(PyCodeEvent event, PyCodeObject *co)
42
132k
{
43
132k
    assert(Py_REFCNT(co) > 0);
44
132k
    PyInterpreterState *interp = _PyInterpreterState_GET();
45
132k
    assert(interp->_initialized);
46
132k
    uint8_t bits = interp->active_code_watchers;
47
132k
    int i = 0;
48
132k
    while (bits) {
49
0
        assert(i < CODE_MAX_WATCHERS);
50
0
        if (bits & 1) {
51
0
            PyCode_WatchCallback cb = interp->code_watchers[i];
52
            // callback must be non-null if the watcher bit is set
53
0
            assert(cb != NULL);
54
0
            if (cb(event, co) < 0) {
55
0
                PyErr_FormatUnraisable(
56
0
                    "Exception ignored in %s watcher callback for %R",
57
0
                    code_event_name(event), co);
58
0
            }
59
0
        }
60
0
        i++;
61
0
        bits >>= 1;
62
0
    }
63
132k
}
64
65
int
66
PyCode_AddWatcher(PyCode_WatchCallback callback)
67
0
{
68
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
69
0
    assert(interp->_initialized);
70
71
0
    for (int i = 0; i < CODE_MAX_WATCHERS; i++) {
72
0
        if (!interp->code_watchers[i]) {
73
0
            interp->code_watchers[i] = callback;
74
0
            interp->active_code_watchers |= (1 << i);
75
0
            return i;
76
0
        }
77
0
    }
78
79
0
    PyErr_SetString(PyExc_RuntimeError, "no more code watcher IDs available");
80
0
    return -1;
81
0
}
82
83
static inline int
84
validate_watcher_id(PyInterpreterState *interp, int watcher_id)
85
0
{
86
0
    if (watcher_id < 0 || watcher_id >= CODE_MAX_WATCHERS) {
87
0
        PyErr_Format(PyExc_ValueError, "Invalid code watcher ID %d", watcher_id);
88
0
        return -1;
89
0
    }
90
0
    if (!interp->code_watchers[watcher_id]) {
91
0
        PyErr_Format(PyExc_ValueError, "No code watcher set for ID %d", watcher_id);
92
0
        return -1;
93
0
    }
94
0
    return 0;
95
0
}
96
97
int
98
PyCode_ClearWatcher(int watcher_id)
99
0
{
100
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
101
0
    assert(interp->_initialized);
102
0
    if (validate_watcher_id(interp, watcher_id) < 0) {
103
0
        return -1;
104
0
    }
105
0
    interp->code_watchers[watcher_id] = NULL;
106
0
    interp->active_code_watchers &= ~(1 << watcher_id);
107
0
    return 0;
108
0
}
109
110
/******************
111
 * generic helpers
112
 ******************/
113
114
266k
#define _PyCodeObject_CAST(op)  (assert(PyCode_Check(op)), (PyCodeObject *)(op))
115
116
static int
117
should_intern_string(PyObject *o)
118
138k
{
119
#ifdef Py_GIL_DISABLED
120
    // The free-threaded build interns (and immortalizes) all string constants
121
    return 1;
122
#else
123
    // compute if s matches [a-zA-Z0-9_]
124
138k
    const unsigned char *s, *e;
125
126
138k
    if (!PyUnicode_IS_ASCII(o))
127
25.5k
        return 0;
128
129
113k
    s = PyUnicode_1BYTE_DATA(o);
130
113k
    e = s + PyUnicode_GET_LENGTH(o);
131
768k
    for (; s != e; s++) {
132
691k
        if (!Py_ISALNUM(*s) && *s != '_')
133
35.9k
            return 0;
134
691k
    }
135
77.5k
    return 1;
136
113k
#endif
137
113k
}
138
139
#ifdef Py_GIL_DISABLED
140
static PyObject *intern_one_constant(PyObject *op);
141
142
// gh-130851: In the free threading build, we intern and immortalize most
143
// constants, except code objects. However, users can generate code objects
144
// with arbitrary co_consts. We don't want to immortalize or intern unexpected
145
// constants or tuples/sets containing unexpected constants.
146
static int
147
should_immortalize_constant(PyObject *v)
148
{
149
    // Only immortalize containers if we've already immortalized all their
150
    // elements.
151
    if (PyTuple_CheckExact(v)) {
152
        for (Py_ssize_t i = PyTuple_GET_SIZE(v); --i >= 0; ) {
153
            if (!_Py_IsImmortal(PyTuple_GET_ITEM(v, i))) {
154
                return 0;
155
            }
156
        }
157
        return 1;
158
    }
159
    else if (PyFrozenSet_CheckExact(v)) {
160
        PyObject *item;
161
        Py_hash_t hash;
162
        Py_ssize_t pos = 0;
163
        while (_PySet_NextEntry(v, &pos, &item, &hash)) {
164
            if (!_Py_IsImmortal(item)) {
165
                return 0;
166
            }
167
        }
168
        return 1;
169
    }
170
    else if (PySlice_Check(v)) {
171
        PySliceObject *slice = (PySliceObject *)v;
172
        return (_Py_IsImmortal(slice->start) &&
173
                _Py_IsImmortal(slice->stop) &&
174
                _Py_IsImmortal(slice->step));
175
    }
176
    return (PyLong_CheckExact(v) || PyFloat_CheckExact(v) ||
177
            PyComplex_Check(v) || PyBytes_CheckExact(v));
178
}
179
#endif
180
181
static int
182
intern_strings(PyObject *tuple)
183
151k
{
184
151k
    PyInterpreterState *interp = _PyInterpreterState_GET();
185
151k
    Py_ssize_t i;
186
187
680k
    for (i = PyTuple_GET_SIZE(tuple); --i >= 0; ) {
188
529k
        PyObject *v = PyTuple_GET_ITEM(tuple, i);
189
529k
        if (v == NULL || !PyUnicode_CheckExact(v)) {
190
0
            PyErr_SetString(PyExc_SystemError,
191
0
                            "non-string found in code slot");
192
0
            return -1;
193
0
        }
194
529k
        _PyUnicode_InternImmortal(interp, &_PyTuple_ITEMS(tuple)[i]);
195
529k
    }
196
151k
    return 0;
197
151k
}
198
199
/* Intern constants. In the default build, this interns selected string
200
   constants. In the free-threaded build, this also interns non-string
201
   constants. */
202
static int
203
intern_constants(PyObject *tuple, int *modified)
204
143k
{
205
143k
    PyInterpreterState *interp = _PyInterpreterState_GET();
206
3.11M
    for (Py_ssize_t i = PyTuple_GET_SIZE(tuple); --i >= 0; ) {
207
2.97M
        PyObject *v = PyTuple_GET_ITEM(tuple, i);
208
2.97M
        if (PyUnicode_CheckExact(v)) {
209
138k
            if (should_intern_string(v)) {
210
77.5k
                PyObject *w = v;
211
77.5k
                _PyUnicode_InternMortal(interp, &v);
212
77.5k
                if (w != v) {
213
95
                    PyTuple_SET_ITEM(tuple, i, v);
214
95
                    if (modified) {
215
0
                        *modified = 1;
216
0
                    }
217
95
                }
218
77.5k
            }
219
138k
        }
220
2.83M
        else if (PyTuple_CheckExact(v)) {
221
66.1k
            if (intern_constants(v, NULL) < 0) {
222
0
                return -1;
223
0
            }
224
66.1k
        }
225
2.76M
        else if (PyFrozenSet_CheckExact(v)) {
226
1.24k
            PyObject *w = v;
227
1.24k
            PyObject *tmp = PySequence_Tuple(v);
228
1.24k
            if (tmp == NULL) {
229
0
                return -1;
230
0
            }
231
1.24k
            int tmp_modified = 0;
232
1.24k
            if (intern_constants(tmp, &tmp_modified) < 0) {
233
0
                Py_DECREF(tmp);
234
0
                return -1;
235
0
            }
236
1.24k
            if (tmp_modified) {
237
0
                v = PyFrozenSet_New(tmp);
238
0
                if (v == NULL) {
239
0
                    Py_DECREF(tmp);
240
0
                    return -1;
241
0
                }
242
243
0
                PyTuple_SET_ITEM(tuple, i, v);
244
0
                Py_DECREF(w);
245
0
                if (modified) {
246
0
                    *modified = 1;
247
0
                }
248
0
            }
249
1.24k
            Py_DECREF(tmp);
250
1.24k
        }
251
#ifdef Py_GIL_DISABLED
252
        else if (PySlice_Check(v)) {
253
            PySliceObject *slice = (PySliceObject *)v;
254
            PyObject *tmp = PyTuple_New(3);
255
            if (tmp == NULL) {
256
                return -1;
257
            }
258
            PyTuple_SET_ITEM(tmp, 0, Py_NewRef(slice->start));
259
            PyTuple_SET_ITEM(tmp, 1, Py_NewRef(slice->stop));
260
            PyTuple_SET_ITEM(tmp, 2, Py_NewRef(slice->step));
261
            int tmp_modified = 0;
262
            if (intern_constants(tmp, &tmp_modified) < 0) {
263
                Py_DECREF(tmp);
264
                return -1;
265
            }
266
            if (tmp_modified) {
267
                v = PySlice_New(PyTuple_GET_ITEM(tmp, 0),
268
                                PyTuple_GET_ITEM(tmp, 1),
269
                                PyTuple_GET_ITEM(tmp, 2));
270
                if (v == NULL) {
271
                    Py_DECREF(tmp);
272
                    return -1;
273
                }
274
                PyTuple_SET_ITEM(tuple, i, v);
275
                Py_DECREF(slice);
276
                if (modified) {
277
                    *modified = 1;
278
                }
279
            }
280
            Py_DECREF(tmp);
281
        }
282
283
        // Intern non-string constants in the free-threaded build
284
        _PyThreadStateImpl *tstate = (_PyThreadStateImpl *)_PyThreadState_GET();
285
        if (!_Py_IsImmortal(v) && !PyUnicode_CheckExact(v) &&
286
            should_immortalize_constant(v) &&
287
            !tstate->suppress_co_const_immortalization)
288
        {
289
            PyObject *interned = intern_one_constant(v);
290
            if (interned == NULL) {
291
                return -1;
292
            }
293
            else if (interned != v) {
294
                PyTuple_SET_ITEM(tuple, i, interned);
295
                Py_SETREF(v, interned);
296
                if (modified) {
297
                    *modified = 1;
298
                }
299
            }
300
        }
301
#endif
302
2.97M
    }
303
143k
    return 0;
304
143k
}
305
306
/* Return a shallow copy of a tuple that is
307
   guaranteed to contain exact strings, by converting string subclasses
308
   to exact strings and complaining if a non-string is found. */
309
static PyObject*
310
validate_and_copy_tuple(PyObject *tup)
311
0
{
312
0
    PyObject *newtuple;
313
0
    PyObject *item;
314
0
    Py_ssize_t i, len;
315
316
0
    len = PyTuple_GET_SIZE(tup);
317
0
    newtuple = PyTuple_New(len);
318
0
    if (newtuple == NULL)
319
0
        return NULL;
320
321
0
    for (i = 0; i < len; i++) {
322
0
        item = PyTuple_GET_ITEM(tup, i);
323
0
        if (PyUnicode_CheckExact(item)) {
324
0
            Py_INCREF(item);
325
0
        }
326
0
        else if (!PyUnicode_Check(item)) {
327
0
            PyErr_Format(
328
0
                PyExc_TypeError,
329
0
                "name tuples must contain only "
330
0
                "strings, not '%.500s'",
331
0
                Py_TYPE(item)->tp_name);
332
0
            Py_DECREF(newtuple);
333
0
            return NULL;
334
0
        }
335
0
        else {
336
0
            item = _PyUnicode_Copy(item);
337
0
            if (item == NULL) {
338
0
                Py_DECREF(newtuple);
339
0
                return NULL;
340
0
            }
341
0
        }
342
0
        PyTuple_SET_ITEM(newtuple, i, item);
343
0
    }
344
345
0
    return newtuple;
346
0
}
347
348
static int
349
init_co_cached(PyCodeObject *self)
350
0
{
351
0
    _PyCoCached *cached = FT_ATOMIC_LOAD_PTR(self->_co_cached);
352
0
    if (cached != NULL) {
353
0
        return 0;
354
0
    }
355
356
0
    Py_BEGIN_CRITICAL_SECTION(self);
357
0
    cached = self->_co_cached;
358
0
    if (cached == NULL) {
359
0
        cached = PyMem_New(_PyCoCached, 1);
360
0
        if (cached == NULL) {
361
0
            PyErr_NoMemory();
362
0
        }
363
0
        else {
364
0
            cached->_co_code = NULL;
365
0
            cached->_co_cellvars = NULL;
366
0
            cached->_co_freevars = NULL;
367
0
            cached->_co_varnames = NULL;
368
0
            FT_ATOMIC_STORE_PTR(self->_co_cached, cached);
369
0
        }
370
0
    }
371
0
    Py_END_CRITICAL_SECTION();
372
0
    return cached != NULL ? 0 : -1;
373
0
}
374
375
/******************
376
 * _PyCode_New()
377
 ******************/
378
379
// This is also used in compile.c.
380
void
381
_Py_set_localsplus_info(int offset, PyObject *name, _PyLocals_Kind kind,
382
                        PyObject *names, PyObject *kinds)
383
110k
{
384
110k
    PyTuple_SET_ITEM(names, offset, Py_NewRef(name));
385
110k
    _PyLocals_SetKind(kinds, offset, kind);
386
110k
}
387
388
static void
389
get_localsplus_counts(PyObject *names, PyObject *kinds,
390
                      int *pnlocals, int *pncellvars,
391
                      int *pnfreevars)
392
151k
{
393
151k
    int nlocals = 0;
394
151k
    int ncellvars = 0;
395
151k
    int nfreevars = 0;
396
151k
    Py_ssize_t nlocalsplus = PyTuple_GET_SIZE(names);
397
514k
    for (int i = 0; i < nlocalsplus; i++) {
398
362k
        _PyLocals_Kind kind = _PyLocals_GetKind(kinds, i);
399
362k
        if (kind & CO_FAST_LOCAL) {
400
302k
            nlocals += 1;
401
302k
            if (kind & CO_FAST_CELL) {
402
1.38k
                ncellvars += 1;
403
1.38k
            }
404
302k
        }
405
59.7k
        else if (kind & CO_FAST_CELL) {
406
30.0k
            ncellvars += 1;
407
30.0k
        }
408
29.6k
        else if (kind & CO_FAST_FREE) {
409
29.6k
            nfreevars += 1;
410
29.6k
        }
411
362k
    }
412
151k
    if (pnlocals != NULL) {
413
151k
        *pnlocals = nlocals;
414
151k
    }
415
151k
    if (pncellvars != NULL) {
416
75.7k
        *pncellvars = ncellvars;
417
75.7k
    }
418
151k
    if (pnfreevars != NULL) {
419
75.7k
        *pnfreevars = nfreevars;
420
75.7k
    }
421
151k
}
422
423
static PyObject *
424
get_localsplus_names(PyCodeObject *co, _PyLocals_Kind kind, int num)
425
0
{
426
0
    PyObject *names = PyTuple_New(num);
427
0
    if (names == NULL) {
428
0
        return NULL;
429
0
    }
430
0
    int index = 0;
431
0
    for (int offset = 0; offset < co->co_nlocalsplus; offset++) {
432
0
        _PyLocals_Kind k = _PyLocals_GetKind(co->co_localspluskinds, offset);
433
0
        if ((k & kind) == 0) {
434
0
            continue;
435
0
        }
436
0
        assert(index < num);
437
0
        PyObject *name = PyTuple_GET_ITEM(co->co_localsplusnames, offset);
438
0
        PyTuple_SET_ITEM(names, index, Py_NewRef(name));
439
0
        index += 1;
440
0
    }
441
0
    assert(index == num);
442
0
    return names;
443
0
}
444
445
int
446
_PyCode_Validate(struct _PyCodeConstructor *con)
447
75.7k
{
448
    /* Check argument types */
449
75.7k
    if (con->argcount < con->posonlyargcount || con->posonlyargcount < 0 ||
450
75.7k
        con->kwonlyargcount < 0 ||
451
75.7k
        con->stacksize < 0 || con->flags < 0 ||
452
75.7k
        con->code == NULL || !PyBytes_Check(con->code) ||
453
75.7k
        con->consts == NULL || !PyTuple_Check(con->consts) ||
454
75.7k
        con->names == NULL || !PyTuple_Check(con->names) ||
455
75.7k
        con->localsplusnames == NULL || !PyTuple_Check(con->localsplusnames) ||
456
75.7k
        con->localspluskinds == NULL || !PyBytes_Check(con->localspluskinds) ||
457
75.7k
        PyTuple_GET_SIZE(con->localsplusnames)
458
75.7k
            != PyBytes_GET_SIZE(con->localspluskinds) ||
459
75.7k
        con->name == NULL || !PyUnicode_Check(con->name) ||
460
75.7k
        con->qualname == NULL || !PyUnicode_Check(con->qualname) ||
461
75.7k
        con->filename == NULL || !PyUnicode_Check(con->filename) ||
462
75.7k
        con->linetable == NULL || !PyBytes_Check(con->linetable) ||
463
75.7k
        con->exceptiontable == NULL || !PyBytes_Check(con->exceptiontable)
464
75.7k
        ) {
465
0
        PyErr_BadInternalCall();
466
0
        return -1;
467
0
    }
468
469
    /* Make sure that code is indexable with an int, this is
470
       a long running assumption in ceval.c and many parts of
471
       the interpreter. */
472
75.7k
    if (PyBytes_GET_SIZE(con->code) > INT_MAX) {
473
0
        PyErr_SetString(PyExc_OverflowError,
474
0
                        "code: co_code larger than INT_MAX");
475
0
        return -1;
476
0
    }
477
75.7k
    if (PyBytes_GET_SIZE(con->code) % sizeof(_Py_CODEUNIT) != 0 ||
478
75.7k
        !_Py_IS_ALIGNED(PyBytes_AS_STRING(con->code), sizeof(_Py_CODEUNIT))
479
75.7k
        ) {
480
0
        PyErr_SetString(PyExc_ValueError, "code: co_code is malformed");
481
0
        return -1;
482
0
    }
483
484
    /* Ensure that the co_varnames has enough names to cover the arg counts.
485
     * Note that totalargs = nlocals - nplainlocals.  We check nplainlocals
486
     * here to avoid the possibility of overflow (however remote). */
487
75.7k
    int nlocals;
488
75.7k
    get_localsplus_counts(con->localsplusnames, con->localspluskinds,
489
75.7k
                          &nlocals, NULL, NULL);
490
75.7k
    int nplainlocals = nlocals -
491
75.7k
                       con->argcount -
492
75.7k
                       con->kwonlyargcount -
493
75.7k
                       ((con->flags & CO_VARARGS) != 0) -
494
75.7k
                       ((con->flags & CO_VARKEYWORDS) != 0);
495
75.7k
    if (nplainlocals < 0) {
496
0
        PyErr_SetString(PyExc_ValueError, "code: co_varnames is too small");
497
0
        return -1;
498
0
    }
499
500
75.7k
    return 0;
501
75.7k
}
502
503
extern void
504
_PyCode_Quicken(_Py_CODEUNIT *instructions, Py_ssize_t size, int enable_counters, int flags);
505
506
#ifdef Py_GIL_DISABLED
507
static _PyCodeArray * _PyCodeArray_New(Py_ssize_t size);
508
#endif
509
510
static int
511
init_code(PyCodeObject *co, struct _PyCodeConstructor *con)
512
75.7k
{
513
75.7k
    int nlocalsplus = (int)PyTuple_GET_SIZE(con->localsplusnames);
514
75.7k
    int nlocals, ncellvars, nfreevars;
515
75.7k
    get_localsplus_counts(con->localsplusnames, con->localspluskinds,
516
75.7k
                          &nlocals, &ncellvars, &nfreevars);
517
75.7k
    if (con->stacksize == 0) {
518
3
        con->stacksize = 1;
519
3
    }
520
521
75.7k
    PyInterpreterState *interp = _PyInterpreterState_GET();
522
75.7k
    co->co_filename = Py_NewRef(con->filename);
523
75.7k
    co->co_name = Py_NewRef(con->name);
524
75.7k
    co->co_qualname = Py_NewRef(con->qualname);
525
75.7k
    _PyUnicode_InternMortal(interp, &co->co_filename);
526
75.7k
    _PyUnicode_InternMortal(interp, &co->co_name);
527
75.7k
    _PyUnicode_InternMortal(interp, &co->co_qualname);
528
75.7k
    co->co_flags = con->flags;
529
530
75.7k
    co->co_firstlineno = con->firstlineno;
531
75.7k
    co->co_linetable = Py_NewRef(con->linetable);
532
533
75.7k
    co->co_consts = Py_NewRef(con->consts);
534
75.7k
    co->co_names = Py_NewRef(con->names);
535
536
75.7k
    co->co_localsplusnames = Py_NewRef(con->localsplusnames);
537
75.7k
    co->co_localspluskinds = Py_NewRef(con->localspluskinds);
538
539
75.7k
    co->co_argcount = con->argcount;
540
75.7k
    co->co_posonlyargcount = con->posonlyargcount;
541
75.7k
    co->co_kwonlyargcount = con->kwonlyargcount;
542
543
75.7k
    co->co_stacksize = con->stacksize;
544
545
75.7k
    co->co_exceptiontable = Py_NewRef(con->exceptiontable);
546
547
    /* derived values */
548
75.7k
    co->co_nlocalsplus = nlocalsplus;
549
75.7k
    co->co_nlocals = nlocals;
550
75.7k
    co->co_framesize = nlocalsplus + con->stacksize + FRAME_SPECIALS_SIZE;
551
75.7k
    co->co_ncellvars = ncellvars;
552
75.7k
    co->co_nfreevars = nfreevars;
553
75.7k
    FT_MUTEX_LOCK(&interp->func_state.mutex);
554
75.7k
    co->co_version = interp->func_state.next_version;
555
75.7k
    if (interp->func_state.next_version != 0) {
556
75.7k
        interp->func_state.next_version++;
557
75.7k
    }
558
75.7k
    FT_MUTEX_UNLOCK(&interp->func_state.mutex);
559
75.7k
    co->_co_monitoring = NULL;
560
75.7k
    co->_co_instrumentation_version = 0;
561
    /* not set */
562
75.7k
    co->co_weakreflist = NULL;
563
75.7k
    co->co_extra = NULL;
564
75.7k
    co->_co_cached = NULL;
565
75.7k
    co->co_executors = NULL;
566
567
75.7k
    memcpy(_PyCode_CODE(co), PyBytes_AS_STRING(con->code),
568
75.7k
           PyBytes_GET_SIZE(con->code));
569
#ifdef Py_GIL_DISABLED
570
    co->co_tlbc = _PyCodeArray_New(INITIAL_SPECIALIZED_CODE_SIZE);
571
    if (co->co_tlbc == NULL) {
572
        return -1;
573
    }
574
    co->co_tlbc->entries[0] = co->co_code_adaptive;
575
#endif
576
75.7k
    int entry_point = 0;
577
116k
    while (entry_point < Py_SIZE(co)) {
578
116k
        if (_PyCode_CODE(co)[entry_point].op.code == RESUME &&
579
76.7k
           (_PyCode_CODE(co)[entry_point].op.arg & RESUME_OPARG_LOCATION_MASK) != RESUME_AT_GEN_EXPR_START
580
116k
        ) {
581
75.7k
            break;
582
75.7k
        }
583
41.0k
        entry_point++;
584
41.0k
    }
585
75.7k
    co->_co_firsttraceable = entry_point;
586
587
#ifdef Py_GIL_DISABLED
588
    int enable_counters = interp->config.tlbc_enabled && interp->opt_config.specialization_enabled;
589
    _PyCode_Quicken(_PyCode_CODE(co), Py_SIZE(co), enable_counters, co->co_flags);
590
#else
591
75.7k
    _PyCode_Quicken(_PyCode_CODE(co), Py_SIZE(co), interp->opt_config.specialization_enabled, co->co_flags);
592
75.7k
#endif
593
75.7k
    notify_code_watchers(PY_CODE_EVENT_CREATE, co);
594
75.7k
    return 0;
595
75.7k
}
596
597
static int
598
scan_varint(const uint8_t *ptr)
599
4.61M
{
600
4.61M
    unsigned int read = *ptr++;
601
4.61M
    unsigned int val = read & 63;
602
4.61M
    unsigned int shift = 0;
603
4.61M
    while (read & 64) {
604
0
        read = *ptr++;
605
0
        shift += 6;
606
0
        val |= (read & 63) << shift;
607
0
    }
608
4.61M
    return val;
609
4.61M
}
610
611
static int
612
scan_signed_varint(const uint8_t *ptr)
613
4.61M
{
614
4.61M
    unsigned int uval = scan_varint(ptr);
615
4.61M
    if (uval & 1) {
616
1.55M
        return -(int)(uval >> 1);
617
1.55M
    }
618
3.05M
    else {
619
3.05M
        return uval >> 1;
620
3.05M
    }
621
4.61M
}
622
623
static int
624
get_line_delta(const uint8_t *ptr)
625
88.2M
{
626
88.2M
    int code = ((*ptr) >> 3) & 15;
627
88.2M
    switch (code) {
628
447k
        case PY_CODE_LOCATION_INFO_NONE:
629
447k
            return 0;
630
0
        case PY_CODE_LOCATION_INFO_NO_COLUMNS:
631
4.61M
        case PY_CODE_LOCATION_INFO_LONG:
632
4.61M
            return scan_signed_varint(ptr+1);
633
18.6M
        case PY_CODE_LOCATION_INFO_ONE_LINE0:
634
18.6M
            return 0;
635
15.0M
        case PY_CODE_LOCATION_INFO_ONE_LINE1:
636
15.0M
            return 1;
637
4.79M
        case PY_CODE_LOCATION_INFO_ONE_LINE2:
638
4.79M
            return 2;
639
44.7M
        default:
640
            /* Same line */
641
44.7M
            return 0;
642
88.2M
    }
643
88.2M
}
644
645
static PyObject *
646
remove_column_info(PyObject *locations)
647
0
{
648
0
    Py_ssize_t offset = 0;
649
0
    const uint8_t *data = (const uint8_t *)PyBytes_AS_STRING(locations);
650
0
    PyObject *res = PyBytes_FromStringAndSize(NULL, 32);
651
0
    if (res == NULL) {
652
0
        PyErr_NoMemory();
653
0
        return NULL;
654
0
    }
655
0
    uint8_t *output = (uint8_t *)PyBytes_AS_STRING(res);
656
0
    while (offset < PyBytes_GET_SIZE(locations)) {
657
0
        Py_ssize_t write_offset = output - (uint8_t *)PyBytes_AS_STRING(res);
658
0
        if (write_offset + 16 >= PyBytes_GET_SIZE(res)) {
659
0
            if (_PyBytes_Resize(&res, PyBytes_GET_SIZE(res) * 2) < 0) {
660
0
                return NULL;
661
0
            }
662
0
            output = (uint8_t *)PyBytes_AS_STRING(res) + write_offset;
663
0
        }
664
0
        int code = (data[offset] >> 3) & 15;
665
0
        if (code == PY_CODE_LOCATION_INFO_NONE) {
666
0
            *output++ = data[offset];
667
0
        }
668
0
        else {
669
0
            int blength = (data[offset] & 7)+1;
670
0
            output += write_location_entry_start(
671
0
                output, PY_CODE_LOCATION_INFO_NO_COLUMNS, blength);
672
0
            int ldelta = get_line_delta(&data[offset]);
673
0
            output += write_signed_varint(output, ldelta);
674
0
        }
675
0
        offset++;
676
0
        while (offset < PyBytes_GET_SIZE(locations) &&
677
0
            (data[offset] & 128) == 0) {
678
0
            offset++;
679
0
        }
680
0
    }
681
0
    Py_ssize_t write_offset = output - (uint8_t *)PyBytes_AS_STRING(res);
682
0
    if (_PyBytes_Resize(&res, write_offset)) {
683
0
        return NULL;
684
0
    }
685
0
    return res;
686
0
}
687
688
static int
689
intern_code_constants(struct _PyCodeConstructor *con)
690
75.7k
{
691
#ifdef Py_GIL_DISABLED
692
    PyInterpreterState *interp = _PyInterpreterState_GET();
693
    struct _py_code_state *state = &interp->code_state;
694
    FT_MUTEX_LOCK(&state->mutex);
695
#endif
696
75.7k
    if (intern_strings(con->names) < 0) {
697
0
        goto error;
698
0
    }
699
75.7k
    if (intern_constants(con->consts, NULL) < 0) {
700
0
        goto error;
701
0
    }
702
75.7k
    if (intern_strings(con->localsplusnames) < 0) {
703
0
        goto error;
704
0
    }
705
75.7k
    FT_MUTEX_UNLOCK(&state->mutex);
706
75.7k
    return 0;
707
708
0
error:
709
0
    FT_MUTEX_UNLOCK(&state->mutex);
710
0
    return -1;
711
75.7k
}
712
713
/* The caller is responsible for ensuring that the given data is valid. */
714
715
PyCodeObject *
716
_PyCode_New(struct _PyCodeConstructor *con)
717
75.7k
{
718
75.7k
    if (intern_code_constants(con) < 0) {
719
0
        return NULL;
720
0
    }
721
722
75.7k
    PyObject *replacement_locations = NULL;
723
    // Compact the linetable if we are opted out of debug
724
    // ranges.
725
75.7k
    if (!_Py_GetConfig()->code_debug_ranges) {
726
0
        replacement_locations = remove_column_info(con->linetable);
727
0
        if (replacement_locations == NULL) {
728
0
            return NULL;
729
0
        }
730
0
        con->linetable = replacement_locations;
731
0
    }
732
733
75.7k
    Py_ssize_t size = PyBytes_GET_SIZE(con->code) / sizeof(_Py_CODEUNIT);
734
75.7k
    PyCodeObject *co;
735
#ifdef Py_GIL_DISABLED
736
    co = PyObject_GC_NewVar(PyCodeObject, &PyCode_Type, size);
737
#else
738
75.7k
    co = PyObject_NewVar(PyCodeObject, &PyCode_Type, size);
739
75.7k
#endif
740
75.7k
    if (co == NULL) {
741
0
        Py_XDECREF(replacement_locations);
742
0
        PyErr_NoMemory();
743
0
        return NULL;
744
0
    }
745
746
#ifdef Py_GIL_DISABLED
747
    co->_co_unique_id = _Py_INVALID_UNIQUE_ID;
748
#endif
749
750
75.7k
    if (init_code(co, con) < 0) {
751
0
        Py_XDECREF(replacement_locations);
752
0
        Py_DECREF(co);
753
0
        return NULL;
754
0
    }
755
756
#ifdef Py_GIL_DISABLED
757
    co->_co_unique_id = _PyObject_AssignUniqueId((PyObject *)co);
758
    _PyObject_GC_TRACK(co);
759
#endif
760
75.7k
    Py_XDECREF(replacement_locations);
761
75.7k
    return co;
762
75.7k
}
763
764
765
/******************
766
 * the legacy "constructors"
767
 ******************/
768
769
PyCodeObject *
770
PyUnstable_Code_NewWithPosOnlyArgs(
771
                          int argcount, int posonlyargcount, int kwonlyargcount,
772
                          int nlocals, int stacksize, int flags,
773
                          PyObject *code, PyObject *consts, PyObject *names,
774
                          PyObject *varnames, PyObject *freevars, PyObject *cellvars,
775
                          PyObject *filename, PyObject *name,
776
                          PyObject *qualname, int firstlineno,
777
                          PyObject *linetable,
778
                          PyObject *exceptiontable)
779
0
{
780
0
    PyCodeObject *co = NULL;
781
0
    PyObject *localsplusnames = NULL;
782
0
    PyObject *localspluskinds = NULL;
783
784
0
    if (varnames == NULL || !PyTuple_Check(varnames) ||
785
0
        cellvars == NULL || !PyTuple_Check(cellvars) ||
786
0
        freevars == NULL || !PyTuple_Check(freevars)
787
0
        ) {
788
0
        PyErr_BadInternalCall();
789
0
        return NULL;
790
0
    }
791
792
    // Set the "fast locals plus" info.
793
0
    int nvarnames = (int)PyTuple_GET_SIZE(varnames);
794
0
    int ncellvars = (int)PyTuple_GET_SIZE(cellvars);
795
0
    int nfreevars = (int)PyTuple_GET_SIZE(freevars);
796
0
    int nlocalsplus = nvarnames + ncellvars + nfreevars;
797
0
    localsplusnames = PyTuple_New(nlocalsplus);
798
0
    if (localsplusnames == NULL) {
799
0
        goto error;
800
0
    }
801
0
    localspluskinds = PyBytes_FromStringAndSize(NULL, nlocalsplus);
802
0
    if (localspluskinds == NULL) {
803
0
        goto error;
804
0
    }
805
0
    int  offset = 0;
806
0
    for (int i = 0; i < nvarnames; i++, offset++) {
807
0
        PyObject *name = PyTuple_GET_ITEM(varnames, i);
808
0
        _Py_set_localsplus_info(offset, name, CO_FAST_LOCAL,
809
0
                               localsplusnames, localspluskinds);
810
0
    }
811
0
    for (int i = 0; i < ncellvars; i++, offset++) {
812
0
        PyObject *name = PyTuple_GET_ITEM(cellvars, i);
813
0
        int argoffset = -1;
814
0
        for (int j = 0; j < nvarnames; j++) {
815
0
            int cmp = PyUnicode_Compare(PyTuple_GET_ITEM(varnames, j),
816
0
                                        name);
817
0
            assert(!PyErr_Occurred());
818
0
            if (cmp == 0) {
819
0
                argoffset = j;
820
0
                break;
821
0
            }
822
0
        }
823
0
        if (argoffset >= 0) {
824
            // Merge the localsplus indices.
825
0
            nlocalsplus -= 1;
826
0
            offset -= 1;
827
0
            _PyLocals_Kind kind = _PyLocals_GetKind(localspluskinds, argoffset);
828
0
            _PyLocals_SetKind(localspluskinds, argoffset, kind | CO_FAST_CELL);
829
0
            continue;
830
0
        }
831
0
        _Py_set_localsplus_info(offset, name, CO_FAST_CELL,
832
0
                               localsplusnames, localspluskinds);
833
0
    }
834
0
    for (int i = 0; i < nfreevars; i++, offset++) {
835
0
        PyObject *name = PyTuple_GET_ITEM(freevars, i);
836
0
        _Py_set_localsplus_info(offset, name, CO_FAST_FREE,
837
0
                               localsplusnames, localspluskinds);
838
0
    }
839
840
    // gh-110543: Make sure the CO_FAST_HIDDEN flag is set correctly.
841
0
    if (!(flags & CO_OPTIMIZED)) {
842
0
        Py_ssize_t code_len = PyBytes_GET_SIZE(code);
843
0
        _Py_CODEUNIT *code_data = (_Py_CODEUNIT *)PyBytes_AS_STRING(code);
844
0
        Py_ssize_t num_code_units = code_len / sizeof(_Py_CODEUNIT);
845
0
        int extended_arg = 0;
846
0
        for (int i = 0; i < num_code_units; i += 1 + _PyOpcode_Caches[code_data[i].op.code]) {
847
0
            _Py_CODEUNIT *instr = &code_data[i];
848
0
            uint8_t opcode = instr->op.code;
849
0
            if (opcode == EXTENDED_ARG) {
850
0
                extended_arg = extended_arg << 8 | instr->op.arg;
851
0
                continue;
852
0
            }
853
0
            if (opcode == LOAD_FAST_AND_CLEAR) {
854
0
                int oparg = extended_arg << 8 | instr->op.arg;
855
0
                if (oparg >= nlocalsplus) {
856
0
                    PyErr_Format(PyExc_ValueError,
857
0
                                "code: LOAD_FAST_AND_CLEAR oparg %d out of range",
858
0
                                oparg);
859
0
                    goto error;
860
0
                }
861
0
                _PyLocals_Kind kind = _PyLocals_GetKind(localspluskinds, oparg);
862
0
                _PyLocals_SetKind(localspluskinds, oparg, kind | CO_FAST_HIDDEN);
863
0
            }
864
0
            extended_arg = 0;
865
0
        }
866
0
    }
867
868
    // If any cells were args then nlocalsplus will have shrunk.
869
0
    if (nlocalsplus != PyTuple_GET_SIZE(localsplusnames)) {
870
0
        if (_PyTuple_Resize(&localsplusnames, nlocalsplus) < 0
871
0
                || _PyBytes_Resize(&localspluskinds, nlocalsplus) < 0) {
872
0
            goto error;
873
0
        }
874
0
    }
875
876
0
    struct _PyCodeConstructor con = {
877
0
        .filename = filename,
878
0
        .name = name,
879
0
        .qualname = qualname,
880
0
        .flags = flags,
881
882
0
        .code = code,
883
0
        .firstlineno = firstlineno,
884
0
        .linetable = linetable,
885
886
0
        .consts = consts,
887
0
        .names = names,
888
889
0
        .localsplusnames = localsplusnames,
890
0
        .localspluskinds = localspluskinds,
891
892
0
        .argcount = argcount,
893
0
        .posonlyargcount = posonlyargcount,
894
0
        .kwonlyargcount = kwonlyargcount,
895
896
0
        .stacksize = stacksize,
897
898
0
        .exceptiontable = exceptiontable,
899
0
    };
900
901
0
    if (_PyCode_Validate(&con) < 0) {
902
0
        goto error;
903
0
    }
904
0
    assert(PyBytes_GET_SIZE(code) % sizeof(_Py_CODEUNIT) == 0);
905
0
    assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(code), sizeof(_Py_CODEUNIT)));
906
0
    if (nlocals != PyTuple_GET_SIZE(varnames)) {
907
0
        PyErr_SetString(PyExc_ValueError,
908
0
                        "code: co_nlocals != len(co_varnames)");
909
0
        goto error;
910
0
    }
911
912
0
    co = _PyCode_New(&con);
913
0
    if (co == NULL) {
914
0
        goto error;
915
0
    }
916
917
0
error:
918
0
    Py_XDECREF(localsplusnames);
919
0
    Py_XDECREF(localspluskinds);
920
0
    return co;
921
0
}
922
923
PyCodeObject *
924
PyUnstable_Code_New(int argcount, int kwonlyargcount,
925
           int nlocals, int stacksize, int flags,
926
           PyObject *code, PyObject *consts, PyObject *names,
927
           PyObject *varnames, PyObject *freevars, PyObject *cellvars,
928
           PyObject *filename, PyObject *name, PyObject *qualname,
929
           int firstlineno,
930
           PyObject *linetable,
931
           PyObject *exceptiontable)
932
0
{
933
0
    return PyCode_NewWithPosOnlyArgs(argcount, 0, kwonlyargcount, nlocals,
934
0
                                     stacksize, flags, code, consts, names,
935
0
                                     varnames, freevars, cellvars, filename,
936
0
                                     name, qualname, firstlineno,
937
0
                                     linetable,
938
0
                                     exceptiontable);
939
0
}
940
941
// NOTE: When modifying the construction of PyCode_NewEmpty, please also change
942
// test.test_code.CodeLocationTest.test_code_new_empty to keep it in sync!
943
944
static const uint8_t assert0[8] = {
945
    RESUME, RESUME_AT_FUNC_START,
946
    CACHE, 0,
947
    LOAD_COMMON_CONSTANT, CONSTANT_ASSERTIONERROR,
948
    RAISE_VARARGS, 1
949
};
950
951
static const uint8_t linetable[2] = {
952
    (1 << 7)  // New entry.
953
    | (PY_CODE_LOCATION_INFO_NO_COLUMNS << 3)
954
    | (4 - 1),  // Four code units.
955
    0,  // Offset from co_firstlineno.
956
};
957
958
PyCodeObject *
959
PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno)
960
0
{
961
0
    PyObject *nulltuple = NULL;
962
0
    PyObject *filename_ob = NULL;
963
0
    PyObject *funcname_ob = NULL;
964
0
    PyObject *code_ob = NULL;
965
0
    PyObject *linetable_ob = NULL;
966
0
    PyCodeObject *result = NULL;
967
968
0
    nulltuple = PyTuple_New(0);
969
0
    if (nulltuple == NULL) {
970
0
        goto failed;
971
0
    }
972
0
    funcname_ob = PyUnicode_FromString(funcname);
973
0
    if (funcname_ob == NULL) {
974
0
        goto failed;
975
0
    }
976
0
    filename_ob = PyUnicode_DecodeFSDefault(filename);
977
0
    if (filename_ob == NULL) {
978
0
        goto failed;
979
0
    }
980
0
    code_ob = PyBytes_FromStringAndSize((const char *)assert0, 8);
981
0
    if (code_ob == NULL) {
982
0
        goto failed;
983
0
    }
984
0
    linetable_ob = PyBytes_FromStringAndSize((const char *)linetable, 2);
985
0
    if (linetable_ob == NULL) {
986
0
        goto failed;
987
0
    }
988
989
0
#define emptystring (PyObject *)&_Py_SINGLETON(bytes_empty)
990
0
    struct _PyCodeConstructor con = {
991
0
        .filename = filename_ob,
992
0
        .name = funcname_ob,
993
0
        .qualname = funcname_ob,
994
0
        .code = code_ob,
995
0
        .firstlineno = firstlineno,
996
0
        .linetable = linetable_ob,
997
0
        .consts = nulltuple,
998
0
        .names = nulltuple,
999
0
        .localsplusnames = nulltuple,
1000
0
        .localspluskinds = emptystring,
1001
0
        .exceptiontable = emptystring,
1002
0
        .stacksize = 1,
1003
0
    };
1004
0
    result = _PyCode_New(&con);
1005
1006
0
failed:
1007
0
    Py_XDECREF(nulltuple);
1008
0
    Py_XDECREF(funcname_ob);
1009
0
    Py_XDECREF(filename_ob);
1010
0
    Py_XDECREF(code_ob);
1011
0
    Py_XDECREF(linetable_ob);
1012
0
    return result;
1013
0
}
1014
1015
1016
/******************
1017
 * source location tracking (co_lines/co_positions)
1018
 ******************/
1019
1020
int
1021
PyCode_Addr2Line(PyCodeObject *co, int addrq)
1022
634k
{
1023
634k
    if (addrq < 0) {
1024
0
        return co->co_firstlineno;
1025
0
    }
1026
634k
    _PyCoMonitoringData *data = _Py_atomic_load_ptr_acquire(&co->_co_monitoring);
1027
634k
    if (data) {
1028
0
        _PyCoLineInstrumentationData *lines = _Py_atomic_load_ptr_acquire(&data->lines);
1029
0
        if (lines) {
1030
0
            return _Py_Instrumentation_GetLine(co, lines, addrq/sizeof(_Py_CODEUNIT));
1031
0
        }
1032
0
    }
1033
634k
    assert(addrq >= 0 && addrq < _PyCode_NBYTES(co));
1034
634k
    PyCodeAddressRange bounds;
1035
634k
    _PyCode_InitAddressRange(co, &bounds);
1036
634k
    return _PyCode_CheckLineNumber(addrq, &bounds);
1037
634k
}
1038
1039
int
1040
_PyCode_SafeAddr2Line(PyCodeObject *co, int addrq)
1041
0
{
1042
0
    if (addrq < 0) {
1043
0
        return co->co_firstlineno;
1044
0
    }
1045
0
    if (co->_co_monitoring && co->_co_monitoring->lines) {
1046
0
        return _Py_Instrumentation_GetLine(co, co->_co_monitoring->lines, addrq/sizeof(_Py_CODEUNIT));
1047
0
    }
1048
0
    if (!(addrq >= 0 && addrq < _PyCode_NBYTES(co))) {
1049
0
        return -1;
1050
0
    }
1051
0
    PyCodeAddressRange bounds;
1052
0
    _PyCode_InitAddressRange(co, &bounds);
1053
0
    return _PyCode_CheckLineNumber(addrq, &bounds);
1054
0
}
1055
1056
void
1057
_PyLineTable_InitAddressRange(const char *linetable, Py_ssize_t length, int firstlineno, PyCodeAddressRange *range)
1058
634k
{
1059
634k
    range->opaque.lo_next = (const uint8_t *)linetable;
1060
634k
    range->opaque.limit = range->opaque.lo_next + length;
1061
634k
    range->ar_start = -1;
1062
634k
    range->ar_end = 0;
1063
634k
    range->opaque.computed_line = firstlineno;
1064
634k
    range->ar_line = -1;
1065
634k
}
1066
1067
int
1068
_PyCode_InitAddressRange(PyCodeObject* co, PyCodeAddressRange *bounds)
1069
634k
{
1070
634k
    assert(co->co_linetable != NULL);
1071
634k
    const char *linetable = PyBytes_AS_STRING(co->co_linetable);
1072
634k
    Py_ssize_t length = PyBytes_GET_SIZE(co->co_linetable);
1073
634k
    _PyLineTable_InitAddressRange(linetable, length, co->co_firstlineno, bounds);
1074
634k
    return bounds->ar_line;
1075
634k
}
1076
1077
/* Update *bounds to describe the first and one-past-the-last instructions in
1078
   the same line as lasti.  Return the number of that line, or -1 if lasti is out of bounds. */
1079
int
1080
_PyCode_CheckLineNumber(int lasti, PyCodeAddressRange *bounds)
1081
634k
{
1082
88.9M
    while (bounds->ar_end <= lasti) {
1083
88.2M
        if (!_PyLineTable_NextAddressRange(bounds)) {
1084
0
            return -1;
1085
0
        }
1086
88.2M
    }
1087
634k
    while (bounds->ar_start > lasti) {
1088
0
        if (!_PyLineTable_PreviousAddressRange(bounds)) {
1089
0
            return -1;
1090
0
        }
1091
0
    }
1092
634k
    return bounds->ar_line;
1093
634k
}
1094
1095
static int
1096
is_no_line_marker(uint8_t b)
1097
88.2M
{
1098
88.2M
    return (b >> 3) == 0x1f;
1099
88.2M
}
1100
1101
1102
#define ASSERT_VALID_BOUNDS(bounds) \
1103
176M
    assert(bounds->opaque.lo_next <=  bounds->opaque.limit && \
1104
176M
        (bounds->ar_line == -1 || bounds->ar_line == bounds->opaque.computed_line) && \
1105
176M
        (bounds->opaque.lo_next == bounds->opaque.limit || \
1106
176M
        (*bounds->opaque.lo_next) & 128))
1107
1108
static int
1109
next_code_delta(PyCodeAddressRange *bounds)
1110
88.2M
{
1111
88.2M
    assert((*bounds->opaque.lo_next) & 128);
1112
88.2M
    return (((*bounds->opaque.lo_next) & 7) + 1) * sizeof(_Py_CODEUNIT);
1113
88.2M
}
1114
1115
static int
1116
previous_code_delta(PyCodeAddressRange *bounds)
1117
0
{
1118
0
    if (bounds->ar_start == 0) {
1119
        // If we looking at the first entry, the
1120
        // "previous" entry has an implicit length of 1.
1121
0
        return 1;
1122
0
    }
1123
0
    const uint8_t *ptr = bounds->opaque.lo_next-1;
1124
0
    while (((*ptr) & 128) == 0) {
1125
0
        ptr--;
1126
0
    }
1127
0
    return (((*ptr) & 7) + 1) * sizeof(_Py_CODEUNIT);
1128
0
}
1129
1130
static int
1131
read_byte(PyCodeAddressRange *bounds)
1132
0
{
1133
0
    return *bounds->opaque.lo_next++;
1134
0
}
1135
1136
static int
1137
read_varint(PyCodeAddressRange *bounds)
1138
0
{
1139
0
    unsigned int read = read_byte(bounds);
1140
0
    unsigned int val = read & 63;
1141
0
    unsigned int shift = 0;
1142
0
    while (read & 64) {
1143
0
        read = read_byte(bounds);
1144
0
        shift += 6;
1145
0
        val |= (read & 63) << shift;
1146
0
    }
1147
0
    return val;
1148
0
}
1149
1150
static int
1151
read_signed_varint(PyCodeAddressRange *bounds)
1152
0
{
1153
0
    unsigned int uval = read_varint(bounds);
1154
0
    if (uval & 1) {
1155
0
        return -(int)(uval >> 1);
1156
0
    }
1157
0
    else {
1158
0
        return uval >> 1;
1159
0
    }
1160
0
}
1161
1162
static void
1163
retreat(PyCodeAddressRange *bounds)
1164
0
{
1165
0
    ASSERT_VALID_BOUNDS(bounds);
1166
0
    assert(bounds->ar_start >= 0);
1167
0
    do {
1168
0
        bounds->opaque.lo_next--;
1169
0
    } while (((*bounds->opaque.lo_next) & 128) == 0);
1170
0
    bounds->opaque.computed_line -= get_line_delta(bounds->opaque.lo_next);
1171
0
    bounds->ar_end = bounds->ar_start;
1172
0
    bounds->ar_start -= previous_code_delta(bounds);
1173
0
    if (is_no_line_marker(bounds->opaque.lo_next[-1])) {
1174
0
        bounds->ar_line = -1;
1175
0
    }
1176
0
    else {
1177
0
        bounds->ar_line = bounds->opaque.computed_line;
1178
0
    }
1179
0
    ASSERT_VALID_BOUNDS(bounds);
1180
0
}
1181
1182
static void
1183
advance(PyCodeAddressRange *bounds)
1184
88.2M
{
1185
88.2M
    ASSERT_VALID_BOUNDS(bounds);
1186
88.2M
    bounds->opaque.computed_line += get_line_delta(bounds->opaque.lo_next);
1187
88.2M
    if (is_no_line_marker(*bounds->opaque.lo_next)) {
1188
447k
        bounds->ar_line = -1;
1189
447k
    }
1190
87.8M
    else {
1191
87.8M
        bounds->ar_line = bounds->opaque.computed_line;
1192
87.8M
    }
1193
88.2M
    bounds->ar_start = bounds->ar_end;
1194
88.2M
    bounds->ar_end += next_code_delta(bounds);
1195
230M
    do {
1196
230M
        bounds->opaque.lo_next++;
1197
230M
    } while (bounds->opaque.lo_next < bounds->opaque.limit &&
1198
230M
        ((*bounds->opaque.lo_next) & 128) == 0);
1199
88.2M
    ASSERT_VALID_BOUNDS(bounds);
1200
88.2M
}
1201
1202
static void
1203
advance_with_locations(PyCodeAddressRange *bounds, int *endline, int *column, int *endcolumn)
1204
0
{
1205
0
    ASSERT_VALID_BOUNDS(bounds);
1206
0
    int first_byte = read_byte(bounds);
1207
0
    int code = (first_byte >> 3) & 15;
1208
0
    bounds->ar_start = bounds->ar_end;
1209
0
    bounds->ar_end = bounds->ar_start + ((first_byte & 7) + 1) * sizeof(_Py_CODEUNIT);
1210
0
    switch(code) {
1211
0
        case PY_CODE_LOCATION_INFO_NONE:
1212
0
            bounds->ar_line = *endline = -1;
1213
0
            *column =  *endcolumn = -1;
1214
0
            break;
1215
0
        case PY_CODE_LOCATION_INFO_LONG:
1216
0
        {
1217
0
            bounds->opaque.computed_line += read_signed_varint(bounds);
1218
0
            bounds->ar_line = bounds->opaque.computed_line;
1219
0
            *endline = bounds->ar_line + read_varint(bounds);
1220
0
            *column = read_varint(bounds)-1;
1221
0
            *endcolumn = read_varint(bounds)-1;
1222
0
            break;
1223
0
        }
1224
0
        case PY_CODE_LOCATION_INFO_NO_COLUMNS:
1225
0
        {
1226
            /* No column */
1227
0
            bounds->opaque.computed_line += read_signed_varint(bounds);
1228
0
            *endline = bounds->ar_line = bounds->opaque.computed_line;
1229
0
            *column = *endcolumn = -1;
1230
0
            break;
1231
0
        }
1232
0
        case PY_CODE_LOCATION_INFO_ONE_LINE0:
1233
0
        case PY_CODE_LOCATION_INFO_ONE_LINE1:
1234
0
        case PY_CODE_LOCATION_INFO_ONE_LINE2:
1235
0
        {
1236
            /* one line form */
1237
0
            int line_delta = code - 10;
1238
0
            bounds->opaque.computed_line += line_delta;
1239
0
            *endline = bounds->ar_line = bounds->opaque.computed_line;
1240
0
            *column = read_byte(bounds);
1241
0
            *endcolumn = read_byte(bounds);
1242
0
            break;
1243
0
        }
1244
0
        default:
1245
0
        {
1246
            /* Short forms */
1247
0
            int second_byte = read_byte(bounds);
1248
0
            assert((second_byte & 128) == 0);
1249
0
            *endline = bounds->ar_line = bounds->opaque.computed_line;
1250
0
            *column = code << 3 | (second_byte >> 4);
1251
0
            *endcolumn = *column + (second_byte & 15);
1252
0
        }
1253
0
    }
1254
0
    ASSERT_VALID_BOUNDS(bounds);
1255
0
}
1256
int
1257
PyCode_Addr2Location(PyCodeObject *co, int addrq,
1258
                     int *start_line, int *start_column,
1259
                     int *end_line, int *end_column)
1260
0
{
1261
0
    if (addrq < 0) {
1262
0
        *start_line = *end_line = co->co_firstlineno;
1263
0
        *start_column = *end_column = 0;
1264
0
        return 1;
1265
0
    }
1266
0
    assert(addrq >= 0 && addrq < _PyCode_NBYTES(co));
1267
0
    PyCodeAddressRange bounds;
1268
0
    _PyCode_InitAddressRange(co, &bounds);
1269
0
    _PyCode_CheckLineNumber(addrq, &bounds);
1270
0
    retreat(&bounds);
1271
0
    advance_with_locations(&bounds, end_line, start_column, end_column);
1272
0
    *start_line = bounds.ar_line;
1273
0
    return 1;
1274
0
}
1275
1276
1277
static inline int
1278
88.2M
at_end(PyCodeAddressRange *bounds) {
1279
88.2M
    return bounds->opaque.lo_next >= bounds->opaque.limit;
1280
88.2M
}
1281
1282
int
1283
_PyLineTable_PreviousAddressRange(PyCodeAddressRange *range)
1284
0
{
1285
0
    if (range->ar_start <= 0) {
1286
0
        return 0;
1287
0
    }
1288
0
    retreat(range);
1289
0
    assert(range->ar_end > range->ar_start);
1290
0
    return 1;
1291
0
}
1292
1293
int
1294
_PyLineTable_NextAddressRange(PyCodeAddressRange *range)
1295
88.2M
{
1296
88.2M
    if (at_end(range)) {
1297
0
        return 0;
1298
0
    }
1299
88.2M
    advance(range);
1300
88.2M
    assert(range->ar_end > range->ar_start);
1301
88.2M
    return 1;
1302
88.2M
}
1303
1304
1305
typedef struct {
1306
    PyObject_HEAD
1307
    PyCodeObject *li_code;
1308
    PyCodeAddressRange li_line;
1309
} lineiterator;
1310
1311
1312
static void
1313
lineiter_dealloc(PyObject *self)
1314
0
{
1315
0
    lineiterator *li = (lineiterator*)self;
1316
0
    Py_DECREF(li->li_code);
1317
0
    Py_TYPE(li)->tp_free(li);
1318
0
}
1319
1320
static PyObject *
1321
0
_source_offset_converter(void *arg) {
1322
0
    int *value = (int*)arg;
1323
0
    if (*value == -1) {
1324
0
        Py_RETURN_NONE;
1325
0
    }
1326
0
    return PyLong_FromLong(*value);
1327
0
}
1328
1329
static PyObject *
1330
lineiter_next(PyObject *self)
1331
0
{
1332
0
    lineiterator *li = (lineiterator*)self;
1333
0
    PyCodeAddressRange *bounds = &li->li_line;
1334
0
    if (!_PyLineTable_NextAddressRange(bounds)) {
1335
0
        return NULL;
1336
0
    }
1337
0
    int start = bounds->ar_start;
1338
0
    int line = bounds->ar_line;
1339
    // Merge overlapping entries:
1340
0
    while (_PyLineTable_NextAddressRange(bounds)) {
1341
0
        if (bounds->ar_line != line) {
1342
0
            _PyLineTable_PreviousAddressRange(bounds);
1343
0
            break;
1344
0
        }
1345
0
    }
1346
0
    return Py_BuildValue("iiO&", start, bounds->ar_end,
1347
0
                         _source_offset_converter, &line);
1348
0
}
1349
1350
PyTypeObject _PyLineIterator = {
1351
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1352
    "line_iterator",                    /* tp_name */
1353
    sizeof(lineiterator),               /* tp_basicsize */
1354
    0,                                  /* tp_itemsize */
1355
    /* methods */
1356
    lineiter_dealloc,                   /* tp_dealloc */
1357
    0,                                  /* tp_vectorcall_offset */
1358
    0,                                  /* tp_getattr */
1359
    0,                                  /* tp_setattr */
1360
    0,                                  /* tp_as_async */
1361
    0,                                  /* tp_repr */
1362
    0,                                  /* tp_as_number */
1363
    0,                                  /* tp_as_sequence */
1364
    0,                                  /* tp_as_mapping */
1365
    0,                                  /* tp_hash */
1366
    0,                                  /* tp_call */
1367
    0,                                  /* tp_str */
1368
    0,                                  /* tp_getattro */
1369
    0,                                  /* tp_setattro */
1370
    0,                                  /* tp_as_buffer */
1371
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,       /* tp_flags */
1372
    0,                                  /* tp_doc */
1373
    0,                                  /* tp_traverse */
1374
    0,                                  /* tp_clear */
1375
    0,                                  /* tp_richcompare */
1376
    0,                                  /* tp_weaklistoffset */
1377
    PyObject_SelfIter,                  /* tp_iter */
1378
    lineiter_next,                      /* tp_iternext */
1379
    0,                                  /* tp_methods */
1380
    0,                                  /* tp_members */
1381
    0,                                  /* tp_getset */
1382
    0,                                  /* tp_base */
1383
    0,                                  /* tp_dict */
1384
    0,                                  /* tp_descr_get */
1385
    0,                                  /* tp_descr_set */
1386
    0,                                  /* tp_dictoffset */
1387
    0,                                  /* tp_init */
1388
    0,                                  /* tp_alloc */
1389
    0,                                  /* tp_new */
1390
    PyObject_Free,                      /* tp_free */
1391
};
1392
1393
static lineiterator *
1394
new_linesiterator(PyCodeObject *code)
1395
0
{
1396
0
    lineiterator *li = (lineiterator *)PyType_GenericAlloc(&_PyLineIterator, 0);
1397
0
    if (li == NULL) {
1398
0
        return NULL;
1399
0
    }
1400
0
    li->li_code = (PyCodeObject*)Py_NewRef(code);
1401
0
    _PyCode_InitAddressRange(code, &li->li_line);
1402
0
    return li;
1403
0
}
1404
1405
/* co_positions iterator object. */
1406
typedef struct {
1407
    PyObject_HEAD
1408
    PyCodeObject* pi_code;
1409
    PyCodeAddressRange pi_range;
1410
    int pi_offset;
1411
    int pi_endline;
1412
    int pi_column;
1413
    int pi_endcolumn;
1414
} positionsiterator;
1415
1416
static void
1417
positionsiter_dealloc(PyObject *self)
1418
0
{
1419
0
    positionsiterator *pi = (positionsiterator*)self;
1420
0
    Py_DECREF(pi->pi_code);
1421
0
    Py_TYPE(pi)->tp_free(pi);
1422
0
}
1423
1424
static PyObject*
1425
positionsiter_next(PyObject *self)
1426
0
{
1427
0
    positionsiterator *pi = (positionsiterator*)self;
1428
0
    if (pi->pi_offset >= pi->pi_range.ar_end) {
1429
0
        assert(pi->pi_offset == pi->pi_range.ar_end);
1430
0
        if (at_end(&pi->pi_range)) {
1431
0
            return NULL;
1432
0
        }
1433
0
        advance_with_locations(&pi->pi_range, &pi->pi_endline, &pi->pi_column, &pi->pi_endcolumn);
1434
0
    }
1435
0
    pi->pi_offset += 2;
1436
0
    return Py_BuildValue("(O&O&O&O&)",
1437
0
        _source_offset_converter, &pi->pi_range.ar_line,
1438
0
        _source_offset_converter, &pi->pi_endline,
1439
0
        _source_offset_converter, &pi->pi_column,
1440
0
        _source_offset_converter, &pi->pi_endcolumn);
1441
0
}
1442
1443
PyTypeObject _PyPositionsIterator = {
1444
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1445
    "positions_iterator",               /* tp_name */
1446
    sizeof(positionsiterator),          /* tp_basicsize */
1447
    0,                                  /* tp_itemsize */
1448
    /* methods */
1449
    positionsiter_dealloc,              /* tp_dealloc */
1450
    0,                                  /* tp_vectorcall_offset */
1451
    0,                                  /* tp_getattr */
1452
    0,                                  /* tp_setattr */
1453
    0,                                  /* tp_as_async */
1454
    0,                                  /* tp_repr */
1455
    0,                                  /* tp_as_number */
1456
    0,                                  /* tp_as_sequence */
1457
    0,                                  /* tp_as_mapping */
1458
    0,                                  /* tp_hash */
1459
    0,                                  /* tp_call */
1460
    0,                                  /* tp_str */
1461
    0,                                  /* tp_getattro */
1462
    0,                                  /* tp_setattro */
1463
    0,                                  /* tp_as_buffer */
1464
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,       /* tp_flags */
1465
    0,                                  /* tp_doc */
1466
    0,                                  /* tp_traverse */
1467
    0,                                  /* tp_clear */
1468
    0,                                  /* tp_richcompare */
1469
    0,                                  /* tp_weaklistoffset */
1470
    PyObject_SelfIter,                  /* tp_iter */
1471
    positionsiter_next,                 /* tp_iternext */
1472
    0,                                  /* tp_methods */
1473
    0,                                  /* tp_members */
1474
    0,                                  /* tp_getset */
1475
    0,                                  /* tp_base */
1476
    0,                                  /* tp_dict */
1477
    0,                                  /* tp_descr_get */
1478
    0,                                  /* tp_descr_set */
1479
    0,                                  /* tp_dictoffset */
1480
    0,                                  /* tp_init */
1481
    0,                                  /* tp_alloc */
1482
    0,                                  /* tp_new */
1483
    PyObject_Free,                      /* tp_free */
1484
};
1485
1486
static PyObject*
1487
code_positionsiterator(PyObject *self, PyObject* Py_UNUSED(args))
1488
0
{
1489
0
    PyCodeObject *code = (PyCodeObject*)self;
1490
0
    positionsiterator* pi = (positionsiterator*)PyType_GenericAlloc(&_PyPositionsIterator, 0);
1491
0
    if (pi == NULL) {
1492
0
        return NULL;
1493
0
    }
1494
0
    pi->pi_code = (PyCodeObject*)Py_NewRef(code);
1495
0
    _PyCode_InitAddressRange(code, &pi->pi_range);
1496
0
    pi->pi_offset = pi->pi_range.ar_end;
1497
0
    return (PyObject*)pi;
1498
0
}
1499
1500
1501
/******************
1502
 * "extra" frame eval info (see PEP 523)
1503
 ******************/
1504
1505
/* Holder for co_extra information */
1506
typedef struct {
1507
    Py_ssize_t ce_size;
1508
    void *ce_extras[1];
1509
} _PyCodeObjectExtra;
1510
1511
1512
static inline size_t
1513
code_extra_size(Py_ssize_t n)
1514
0
{
1515
0
    return sizeof(_PyCodeObjectExtra) + (n - 1) * sizeof(void *);
1516
0
}
1517
1518
#ifdef Py_GIL_DISABLED
1519
static int
1520
code_extra_grow_ft(PyCodeObject *co, _PyCodeObjectExtra *old_co_extra,
1521
                   Py_ssize_t old_ce_size, Py_ssize_t new_ce_size,
1522
                   Py_ssize_t index, void *extra)
1523
{
1524
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(co);
1525
    _PyCodeObjectExtra *new_co_extra = PyMem_Malloc(
1526
        code_extra_size(new_ce_size));
1527
    if (new_co_extra == NULL) {
1528
        PyErr_NoMemory();
1529
        return -1;
1530
    }
1531
1532
    if (old_ce_size > 0) {
1533
        memcpy(new_co_extra->ce_extras, old_co_extra->ce_extras,
1534
               old_ce_size * sizeof(void *));
1535
    }
1536
    for (Py_ssize_t i = old_ce_size; i < new_ce_size; i++) {
1537
        new_co_extra->ce_extras[i] = NULL;
1538
    }
1539
    new_co_extra->ce_size = new_ce_size;
1540
    new_co_extra->ce_extras[index] = extra;
1541
1542
    // Publish new buffer and its contents to lock-free readers.
1543
    FT_ATOMIC_STORE_PTR_RELEASE(co->co_extra, new_co_extra);
1544
    if (old_co_extra != NULL) {
1545
        // QSBR: defer old-buffer free until lock-free readers quiesce.
1546
        _PyMem_FreeDelayed(old_co_extra, code_extra_size(old_ce_size));
1547
    }
1548
    return 0;
1549
}
1550
#else
1551
static int
1552
code_extra_grow_gil(PyCodeObject *co, _PyCodeObjectExtra *old_co_extra,
1553
                    Py_ssize_t old_ce_size, Py_ssize_t new_ce_size,
1554
                    Py_ssize_t index, void *extra)
1555
0
{
1556
0
    _PyCodeObjectExtra *new_co_extra = PyMem_Realloc(
1557
0
        old_co_extra, code_extra_size(new_ce_size));
1558
0
    if (new_co_extra == NULL) {
1559
0
        PyErr_NoMemory();
1560
0
        return -1;
1561
0
    }
1562
1563
0
    for (Py_ssize_t i = old_ce_size; i < new_ce_size; i++) {
1564
0
        new_co_extra->ce_extras[i] = NULL;
1565
0
    }
1566
0
    new_co_extra->ce_size = new_ce_size;
1567
0
    new_co_extra->ce_extras[index] = extra;
1568
0
    co->co_extra = new_co_extra;
1569
0
    return 0;
1570
0
}
1571
#endif
1572
1573
int
1574
PyUnstable_Code_GetExtra(PyObject *code, Py_ssize_t index, void **extra)
1575
0
{
1576
0
    if (!PyCode_Check(code)) {
1577
0
        PyErr_BadInternalCall();
1578
0
        return -1;
1579
0
    }
1580
1581
0
    PyCodeObject *co = (PyCodeObject *)code;
1582
0
    *extra = NULL;
1583
1584
0
    if (index < 0) {
1585
0
        return 0;
1586
0
    }
1587
1588
    // Lock-free read; pairs with release stores in SetExtra.
1589
0
    _PyCodeObjectExtra *co_extra = FT_ATOMIC_LOAD_PTR_ACQUIRE(co->co_extra);
1590
0
    if (co_extra != NULL && index < co_extra->ce_size) {
1591
0
        *extra = FT_ATOMIC_LOAD_PTR_ACQUIRE(co_extra->ce_extras[index]);
1592
0
    }
1593
1594
0
    return 0;
1595
0
}
1596
1597
1598
int
1599
PyUnstable_Code_SetExtra(PyObject *code, Py_ssize_t index, void *extra)
1600
0
{
1601
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
1602
1603
    // co_extra_user_count is monotonically increasing and published with
1604
    // release store in RequestCodeExtraIndex, so once an index is valid
1605
    // it stays valid.
1606
0
    Py_ssize_t user_count = FT_ATOMIC_LOAD_SSIZE_ACQUIRE(
1607
0
        interp->co_extra_user_count);
1608
1609
0
    if (!PyCode_Check(code) || index < 0 || index >= user_count) {
1610
0
        PyErr_BadInternalCall();
1611
0
        return -1;
1612
0
    }
1613
1614
0
    PyCodeObject *co = (PyCodeObject *)code;
1615
0
    int result = 0;
1616
0
    void *old_slot_value = NULL;
1617
1618
0
    Py_BEGIN_CRITICAL_SECTION(co);
1619
1620
0
    _PyCodeObjectExtra *old_co_extra = (_PyCodeObjectExtra *)co->co_extra;
1621
0
    Py_ssize_t old_ce_size = (old_co_extra == NULL)
1622
0
        ? 0 : old_co_extra->ce_size;
1623
1624
    // Fast path: slot already exists, update in place.
1625
0
    if (index < old_ce_size) {
1626
0
        old_slot_value = old_co_extra->ce_extras[index];
1627
0
        FT_ATOMIC_STORE_PTR_RELEASE(old_co_extra->ce_extras[index], extra);
1628
0
        goto done;
1629
0
    }
1630
1631
    // Slow path: buffer needs to grow.
1632
0
    Py_ssize_t new_ce_size = user_count;
1633
#ifdef Py_GIL_DISABLED
1634
    // FT build: allocate new buffer and swap; QSBR reclaims the old one.
1635
    result = code_extra_grow_ft(
1636
        co, old_co_extra, old_ce_size, new_ce_size, index, extra);
1637
#else
1638
    // GIL build: grow with realloc.
1639
0
    result = code_extra_grow_gil(
1640
0
        co, old_co_extra, old_ce_size, new_ce_size, index, extra);
1641
0
#endif
1642
1643
0
done:;
1644
0
    Py_END_CRITICAL_SECTION();
1645
0
    if (old_slot_value != NULL) {
1646
        // Free the old slot value if a free function was registered.
1647
        // The caller must ensure no other thread can still access the old
1648
        // value after this overwrite.
1649
0
        freefunc free_extra = interp->co_extra_freefuncs[index];
1650
0
        if (free_extra != NULL) {
1651
0
            free_extra(old_slot_value);
1652
0
        }
1653
0
    }
1654
1655
0
    return result;
1656
0
}
1657
1658
1659
/******************
1660
 * other PyCodeObject accessor functions
1661
 ******************/
1662
1663
static PyObject *
1664
get_cached_locals(PyCodeObject *co, PyObject **cached_field,
1665
    _PyLocals_Kind kind, int num)
1666
0
{
1667
0
    assert(cached_field != NULL);
1668
0
    assert(co->_co_cached != NULL);
1669
0
    PyObject *varnames = FT_ATOMIC_LOAD_PTR(*cached_field);
1670
0
    if (varnames != NULL) {
1671
0
        return Py_NewRef(varnames);
1672
0
    }
1673
1674
0
    Py_BEGIN_CRITICAL_SECTION(co);
1675
0
    varnames = *cached_field;
1676
0
    if (varnames == NULL) {
1677
0
        varnames = get_localsplus_names(co, kind, num);
1678
0
        if (varnames != NULL) {
1679
0
            FT_ATOMIC_STORE_PTR(*cached_field, varnames);
1680
0
        }
1681
0
    }
1682
0
    Py_END_CRITICAL_SECTION();
1683
0
    return Py_XNewRef(varnames);
1684
0
}
1685
1686
PyObject *
1687
_PyCode_GetVarnames(PyCodeObject *co)
1688
0
{
1689
0
    if (init_co_cached(co)) {
1690
0
        return NULL;
1691
0
    }
1692
0
    return get_cached_locals(co, &co->_co_cached->_co_varnames, CO_FAST_LOCAL, co->co_nlocals);
1693
0
}
1694
1695
PyObject *
1696
PyCode_GetVarnames(PyCodeObject *code)
1697
0
{
1698
0
    return _PyCode_GetVarnames(code);
1699
0
}
1700
1701
PyObject *
1702
_PyCode_GetCellvars(PyCodeObject *co)
1703
0
{
1704
0
    if (init_co_cached(co)) {
1705
0
        return NULL;
1706
0
    }
1707
0
    return get_cached_locals(co, &co->_co_cached->_co_cellvars, CO_FAST_CELL, co->co_ncellvars);
1708
0
}
1709
1710
PyObject *
1711
PyCode_GetCellvars(PyCodeObject *code)
1712
0
{
1713
0
    return _PyCode_GetCellvars(code);
1714
0
}
1715
1716
PyObject *
1717
_PyCode_GetFreevars(PyCodeObject *co)
1718
0
{
1719
0
    if (init_co_cached(co)) {
1720
0
        return NULL;
1721
0
    }
1722
0
    return get_cached_locals(co, &co->_co_cached->_co_freevars, CO_FAST_FREE, co->co_nfreevars);
1723
0
}
1724
1725
PyObject *
1726
PyCode_GetFreevars(PyCodeObject *code)
1727
0
{
1728
0
    return _PyCode_GetFreevars(code);
1729
0
}
1730
1731
1732
0
#define GET_OPARG(co, i, initial) (initial)
1733
// We may want to move these macros to pycore_opcode_utils.h
1734
// and use them in Python/bytecodes.c.
1735
#define LOAD_GLOBAL_NAME_INDEX(oparg) ((oparg)>>1)
1736
0
#define LOAD_ATTR_NAME_INDEX(oparg) ((oparg)>>1)
1737
1738
#ifndef Py_DEBUG
1739
0
#define GETITEM(v, i) PyTuple_GET_ITEM((v), (i))
1740
#else
1741
static inline PyObject *
1742
GETITEM(PyObject *v, Py_ssize_t i)
1743
{
1744
    assert(PyTuple_Check(v));
1745
    assert(i >= 0);
1746
    assert(i < PyTuple_GET_SIZE(v));
1747
    assert(PyTuple_GET_ITEM(v, i) != NULL);
1748
    return PyTuple_GET_ITEM(v, i);
1749
}
1750
#endif
1751
1752
static int
1753
identify_unbound_names(PyThreadState *tstate, PyCodeObject *co,
1754
                       PyObject *globalnames, PyObject *attrnames,
1755
                       PyObject *globalsns, PyObject *builtinsns,
1756
                       struct co_unbound_counts *counts, int *p_numdupes)
1757
0
{
1758
    // This function is inspired by inspect.getclosurevars().
1759
    // It would be nicer if we had something similar to co_localspluskinds,
1760
    // but for co_names.
1761
0
    assert(globalnames != NULL);
1762
0
    assert(PySet_Check(globalnames));
1763
0
    assert(PySet_GET_SIZE(globalnames) == 0 || counts != NULL);
1764
0
    assert(attrnames != NULL);
1765
0
    assert(PySet_Check(attrnames));
1766
0
    assert(PySet_GET_SIZE(attrnames) == 0 || counts != NULL);
1767
0
    assert(globalsns == NULL || PyAnyDict_Check(globalsns));
1768
0
    assert(builtinsns == NULL || PyDict_Check(builtinsns));
1769
0
    assert(counts == NULL || counts->total == 0);
1770
0
    struct co_unbound_counts unbound = {0};
1771
0
    int numdupes = 0;
1772
0
    Py_ssize_t len = Py_SIZE(co);
1773
0
    for (int i = 0; i < len; i += _PyInstruction_GetLength(co, i)) {
1774
0
        _Py_CODEUNIT inst = _Py_GetBaseCodeUnit(co, i);
1775
0
        if (inst.op.code == LOAD_ATTR) {
1776
0
            int oparg = GET_OPARG(co, i, inst.op.arg);
1777
0
            int index = LOAD_ATTR_NAME_INDEX(oparg);
1778
0
            PyObject *name = GETITEM(co->co_names, index);
1779
0
            if (PySet_Contains(attrnames, name)) {
1780
0
                if (_PyErr_Occurred(tstate)) {
1781
0
                    return -1;
1782
0
                }
1783
0
                continue;
1784
0
            }
1785
0
            unbound.total += 1;
1786
0
            unbound.numattrs += 1;
1787
0
            if (PySet_Add(attrnames, name) < 0) {
1788
0
                return -1;
1789
0
            }
1790
0
            if (PySet_Contains(globalnames, name)) {
1791
0
                if (_PyErr_Occurred(tstate)) {
1792
0
                    return -1;
1793
0
                }
1794
0
                numdupes += 1;
1795
0
            }
1796
0
        }
1797
0
        else if (inst.op.code == LOAD_GLOBAL) {
1798
0
            int oparg = GET_OPARG(co, i, inst.op.arg);
1799
0
            int index = LOAD_ATTR_NAME_INDEX(oparg);
1800
0
            PyObject *name = GETITEM(co->co_names, index);
1801
0
            if (PySet_Contains(globalnames, name)) {
1802
0
                if (_PyErr_Occurred(tstate)) {
1803
0
                    return -1;
1804
0
                }
1805
0
                continue;
1806
0
            }
1807
0
            unbound.total += 1;
1808
0
            unbound.globals.total += 1;
1809
0
            if (globalsns != NULL && PyDict_Contains(globalsns, name)) {
1810
0
                if (_PyErr_Occurred(tstate)) {
1811
0
                    return -1;
1812
0
                }
1813
0
                unbound.globals.numglobal += 1;
1814
0
            }
1815
0
            else if (builtinsns != NULL && PyDict_Contains(builtinsns, name)) {
1816
0
                if (_PyErr_Occurred(tstate)) {
1817
0
                    return -1;
1818
0
                }
1819
0
                unbound.globals.numbuiltin += 1;
1820
0
            }
1821
0
            else {
1822
0
                unbound.globals.numunknown += 1;
1823
0
            }
1824
0
            if (PySet_Add(globalnames, name) < 0) {
1825
0
                return -1;
1826
0
            }
1827
0
            if (PySet_Contains(attrnames, name)) {
1828
0
                if (_PyErr_Occurred(tstate)) {
1829
0
                    return -1;
1830
0
                }
1831
0
                numdupes += 1;
1832
0
            }
1833
0
        }
1834
0
    }
1835
0
    if (counts != NULL) {
1836
0
        *counts = unbound;
1837
0
    }
1838
0
    if (p_numdupes != NULL) {
1839
0
        *p_numdupes = numdupes;
1840
0
    }
1841
0
    return 0;
1842
0
}
1843
1844
1845
void
1846
_PyCode_GetVarCounts(PyCodeObject *co, _PyCode_var_counts_t *counts)
1847
0
{
1848
0
    assert(counts != NULL);
1849
1850
    // Count the locals, cells, and free vars.
1851
0
    struct co_locals_counts locals = {0};
1852
0
    int numfree = 0;
1853
0
    PyObject *kinds = co->co_localspluskinds;
1854
0
    Py_ssize_t numlocalplusfree = PyBytes_GET_SIZE(kinds);
1855
0
    for (int i = 0; i < numlocalplusfree; i++) {
1856
0
        _PyLocals_Kind kind = _PyLocals_GetKind(co->co_localspluskinds, i);
1857
0
        if (kind & CO_FAST_FREE) {
1858
0
            assert(!(kind & CO_FAST_LOCAL));
1859
0
            assert(!(kind & CO_FAST_HIDDEN));
1860
0
            assert(!(kind & CO_FAST_ARG));
1861
0
            numfree += 1;
1862
0
        }
1863
0
        else {
1864
            // Apparently not all non-free vars a CO_FAST_LOCAL.
1865
0
            assert(kind);
1866
0
            locals.total += 1;
1867
0
            if (kind & CO_FAST_ARG) {
1868
0
                locals.args.total += 1;
1869
0
                if (kind & CO_FAST_ARG_VAR) {
1870
0
                    if (kind & CO_FAST_ARG_POS) {
1871
0
                        assert(!(kind & CO_FAST_ARG_KW));
1872
0
                        assert(!locals.args.varargs);
1873
0
                        locals.args.varargs = 1;
1874
0
                    }
1875
0
                    else {
1876
0
                        assert(kind & CO_FAST_ARG_KW);
1877
0
                        assert(!locals.args.varkwargs);
1878
0
                        locals.args.varkwargs = 1;
1879
0
                    }
1880
0
                }
1881
0
                else if (kind & CO_FAST_ARG_POS) {
1882
0
                    if (kind & CO_FAST_ARG_KW) {
1883
0
                        locals.args.numposorkw += 1;
1884
0
                    }
1885
0
                    else {
1886
0
                        locals.args.numposonly += 1;
1887
0
                    }
1888
0
                }
1889
0
                else {
1890
0
                    assert(kind & CO_FAST_ARG_KW);
1891
0
                    locals.args.numkwonly += 1;
1892
0
                }
1893
0
                if (kind & CO_FAST_CELL) {
1894
0
                    locals.cells.total += 1;
1895
0
                    locals.cells.numargs += 1;
1896
0
                }
1897
                // Args are never hidden currently.
1898
0
                assert(!(kind & CO_FAST_HIDDEN));
1899
0
            }
1900
0
            else {
1901
0
                if (kind & CO_FAST_CELL) {
1902
0
                    locals.cells.total += 1;
1903
0
                    locals.cells.numothers += 1;
1904
0
                    if (kind & CO_FAST_HIDDEN) {
1905
0
                        locals.hidden.total += 1;
1906
0
                        locals.hidden.numcells += 1;
1907
0
                    }
1908
0
                }
1909
0
                else {
1910
0
                    locals.numpure += 1;
1911
0
                    if (kind & CO_FAST_HIDDEN) {
1912
0
                        locals.hidden.total += 1;
1913
0
                        locals.hidden.numpure += 1;
1914
0
                    }
1915
0
                }
1916
0
            }
1917
0
        }
1918
0
    }
1919
0
    assert(locals.args.total == (
1920
0
            co->co_argcount + co->co_kwonlyargcount
1921
0
            + !!(co->co_flags & CO_VARARGS)
1922
0
            + !!(co->co_flags & CO_VARKEYWORDS)));
1923
0
    assert(locals.args.numposonly == co->co_posonlyargcount);
1924
0
    assert(locals.args.numposonly + locals.args.numposorkw == co->co_argcount);
1925
0
    assert(locals.args.numkwonly == co->co_kwonlyargcount);
1926
0
    assert(locals.cells.total == co->co_ncellvars);
1927
0
    assert(locals.args.total + locals.numpure == co->co_nlocals);
1928
0
    assert(locals.total + locals.cells.numargs == co->co_nlocals + co->co_ncellvars);
1929
0
    assert(locals.total + numfree == co->co_nlocalsplus);
1930
0
    assert(numfree == co->co_nfreevars);
1931
1932
    // Get the unbound counts.
1933
0
    assert(PyTuple_GET_SIZE(co->co_names) >= 0);
1934
0
    assert(PyTuple_GET_SIZE(co->co_names) < INT_MAX);
1935
0
    int numunbound = (int)PyTuple_GET_SIZE(co->co_names);
1936
0
    struct co_unbound_counts unbound = {
1937
0
        .total = numunbound,
1938
        // numglobal and numattrs can be set later
1939
        // with _PyCode_SetUnboundVarCounts().
1940
0
        .numunknown = numunbound,
1941
0
    };
1942
1943
    // "Return" the result.
1944
0
    *counts = (_PyCode_var_counts_t){
1945
0
        .total = locals.total + numfree + unbound.total,
1946
0
        .locals = locals,
1947
0
        .numfree = numfree,
1948
0
        .unbound = unbound,
1949
0
    };
1950
0
}
1951
1952
int
1953
_PyCode_SetUnboundVarCounts(PyThreadState *tstate,
1954
                            PyCodeObject *co, _PyCode_var_counts_t *counts,
1955
                            PyObject *globalnames, PyObject *attrnames,
1956
                            PyObject *globalsns, PyObject *builtinsns)
1957
0
{
1958
0
    int res = -1;
1959
0
    PyObject *globalnames_owned = NULL;
1960
0
    PyObject *attrnames_owned = NULL;
1961
1962
    // Prep the name sets.
1963
0
    if (globalnames == NULL) {
1964
0
        globalnames_owned = PySet_New(NULL);
1965
0
        if (globalnames_owned == NULL) {
1966
0
            goto finally;
1967
0
        }
1968
0
        globalnames = globalnames_owned;
1969
0
    }
1970
0
    else if (!PySet_Check(globalnames)) {
1971
0
        _PyErr_Format(tstate, PyExc_TypeError,
1972
0
                     "expected a set for \"globalnames\", got %R", globalnames);
1973
0
        goto finally;
1974
0
    }
1975
0
    if (attrnames == NULL) {
1976
0
        attrnames_owned = PySet_New(NULL);
1977
0
        if (attrnames_owned == NULL) {
1978
0
            goto finally;
1979
0
        }
1980
0
        attrnames = attrnames_owned;
1981
0
    }
1982
0
    else if (!PySet_Check(attrnames)) {
1983
0
        _PyErr_Format(tstate, PyExc_TypeError,
1984
0
                     "expected a set for \"attrnames\", got %R", attrnames);
1985
0
        goto finally;
1986
0
    }
1987
1988
    // Fill in unbound.globals and unbound.numattrs.
1989
0
    struct co_unbound_counts unbound = {0};
1990
0
    int numdupes = 0;
1991
0
    Py_BEGIN_CRITICAL_SECTION(co);
1992
0
    res = identify_unbound_names(
1993
0
            tstate, co, globalnames, attrnames, globalsns, builtinsns,
1994
0
            &unbound, &numdupes);
1995
0
    Py_END_CRITICAL_SECTION();
1996
0
    if (res < 0) {
1997
0
        goto finally;
1998
0
    }
1999
0
    assert(unbound.numunknown == 0);
2000
0
    assert(unbound.total - numdupes <= counts->unbound.total);
2001
0
    assert(counts->unbound.numunknown == counts->unbound.total);
2002
    // There may be a name that is both a global and an attr.
2003
0
    int totalunbound = counts->unbound.total + numdupes;
2004
0
    unbound.numunknown = totalunbound - unbound.total;
2005
0
    unbound.total = totalunbound;
2006
0
    counts->unbound = unbound;
2007
0
    counts->total += numdupes;
2008
0
    res = 0;
2009
2010
0
finally:
2011
0
    Py_XDECREF(globalnames_owned);
2012
0
    Py_XDECREF(attrnames_owned);
2013
0
    return res;
2014
0
}
2015
2016
2017
int
2018
_PyCode_CheckNoInternalState(PyCodeObject *co, const char **p_errmsg)
2019
0
{
2020
0
    const char *errmsg = NULL;
2021
    // We don't worry about co_executors, co_instrumentation,
2022
    // or co_monitoring.  They are essentially ephemeral.
2023
0
    if (co->co_extra != NULL) {
2024
0
        errmsg = "only basic code objects are supported";
2025
0
    }
2026
2027
0
    if (errmsg != NULL) {
2028
0
        if (p_errmsg != NULL) {
2029
0
            *p_errmsg = errmsg;
2030
0
        }
2031
0
        return 0;
2032
0
    }
2033
0
    return 1;
2034
0
}
2035
2036
int
2037
_PyCode_CheckNoExternalState(PyCodeObject *co, _PyCode_var_counts_t *counts,
2038
                             const char **p_errmsg)
2039
0
{
2040
0
    const char *errmsg = NULL;
2041
0
    if (counts->numfree > 0) {  // It's a closure.
2042
0
        errmsg = "closures not supported";
2043
0
    }
2044
0
    else if (counts->unbound.globals.numglobal > 0) {
2045
0
        errmsg = "globals not supported";
2046
0
    }
2047
0
    else if (counts->unbound.globals.numbuiltin > 0
2048
0
             && counts->unbound.globals.numunknown > 0)
2049
0
    {
2050
0
        errmsg = "globals not supported";
2051
0
    }
2052
    // Otherwise we don't check counts.unbound.globals.numunknown since we can't
2053
    // distinguish beween globals and builtins here.
2054
2055
0
    if (errmsg != NULL) {
2056
0
        if (p_errmsg != NULL) {
2057
0
            *p_errmsg = errmsg;
2058
0
        }
2059
0
        return 0;
2060
0
    }
2061
0
    return 1;
2062
0
}
2063
2064
int
2065
_PyCode_VerifyStateless(PyThreadState *tstate,
2066
                        PyCodeObject *co, PyObject *globalnames,
2067
                        PyObject *globalsns, PyObject *builtinsns)
2068
0
{
2069
0
    const char *errmsg;
2070
0
   _PyCode_var_counts_t counts = {0};
2071
0
    _PyCode_GetVarCounts(co, &counts);
2072
0
    if (_PyCode_SetUnboundVarCounts(
2073
0
                            tstate, co, &counts, globalnames, NULL,
2074
0
                            globalsns, builtinsns) < 0)
2075
0
    {
2076
0
        return -1;
2077
0
    }
2078
    // We may consider relaxing the internal state constraints
2079
    // if it becomes a problem.
2080
0
    if (!_PyCode_CheckNoInternalState(co, &errmsg)) {
2081
0
        _PyErr_SetString(tstate, PyExc_ValueError, errmsg);
2082
0
        return -1;
2083
0
    }
2084
0
    if (builtinsns != NULL) {
2085
        // Make sure the next check will fail for globals,
2086
        // even if there aren't any builtins.
2087
0
        counts.unbound.globals.numbuiltin += 1;
2088
0
    }
2089
0
    if (!_PyCode_CheckNoExternalState(co, &counts, &errmsg)) {
2090
0
        _PyErr_SetString(tstate, PyExc_ValueError, errmsg);
2091
0
        return -1;
2092
0
    }
2093
    // Note that we don't check co->co_flags & CO_NESTED for anything here.
2094
0
    return 0;
2095
0
}
2096
2097
2098
int
2099
_PyCode_CheckPureFunction(PyCodeObject *co, const char **p_errmsg)
2100
0
{
2101
0
    const char *errmsg = NULL;
2102
0
    if (co->co_flags & CO_GENERATOR) {
2103
0
        errmsg = "generators not supported";
2104
0
    }
2105
0
    else if (co->co_flags & CO_COROUTINE) {
2106
0
        errmsg = "coroutines not supported";
2107
0
    }
2108
0
    else if (co->co_flags & CO_ITERABLE_COROUTINE) {
2109
0
        errmsg = "coroutines not supported";
2110
0
    }
2111
0
    else if (co->co_flags & CO_ASYNC_GENERATOR) {
2112
0
        errmsg = "generators not supported";
2113
0
    }
2114
2115
0
    if (errmsg != NULL) {
2116
0
        if (p_errmsg != NULL) {
2117
0
            *p_errmsg = errmsg;
2118
0
        }
2119
0
        return 0;
2120
0
    }
2121
0
    return 1;
2122
0
}
2123
2124
/* Here "value" means a non-None value, since a bare return is identical
2125
 * to returning None explicitly.  Likewise a missing return statement
2126
 * at the end of the function is turned into "return None". */
2127
static int
2128
code_returns_only_none(PyCodeObject *co)
2129
0
{
2130
0
    if (!_PyCode_CheckPureFunction(co, NULL)) {
2131
0
        return 0;
2132
0
    }
2133
0
    int len = (int)Py_SIZE(co);
2134
0
    assert(len > 0);
2135
2136
    // Look up None in co_consts.
2137
0
    Py_ssize_t nconsts = PyTuple_Size(co->co_consts);
2138
0
    int none_index = 0;
2139
0
    for (; none_index < nconsts; none_index++) {
2140
0
        if (PyTuple_GET_ITEM(co->co_consts, none_index) == Py_None) {
2141
0
            break;
2142
0
        }
2143
0
    }
2144
    /* We don't worry about EXTENDED_ARG for now. */
2145
0
    for (int i = 0; i < len; i += _PyInstruction_GetLength(co, i)) {
2146
0
        _Py_CODEUNIT inst = _Py_GetBaseCodeUnit(co, i);
2147
0
        if (!IS_RETURN_OPCODE(inst.op.code)) {
2148
0
            continue;
2149
0
        }
2150
0
        assert(i != 0);
2151
0
        _Py_CODEUNIT prev = _Py_GetBaseCodeUnit(co, i-1);
2152
0
        if (prev.op.code == LOAD_COMMON_CONSTANT &&
2153
0
            prev.op.arg == CONSTANT_NONE)
2154
0
        {
2155
0
            continue;
2156
0
        }
2157
0
        if (none_index < nconsts && prev.op.code == LOAD_CONST
2158
0
            && prev.op.arg == none_index)
2159
0
        {
2160
0
            continue;
2161
0
        }
2162
0
        return 0;
2163
0
    }
2164
0
    return 1;
2165
0
}
2166
2167
int
2168
_PyCode_ReturnsOnlyNone(PyCodeObject *co)
2169
0
{
2170
0
    int res;
2171
0
    Py_BEGIN_CRITICAL_SECTION(co);
2172
0
    res = code_returns_only_none(co);
2173
0
    Py_END_CRITICAL_SECTION();
2174
0
    return res;
2175
0
}
2176
2177
2178
#ifdef _Py_TIER2
2179
2180
static void
2181
clear_executors(PyCodeObject *co)
2182
{
2183
    assert(co->co_executors);
2184
    for (int i = 0; i < co->co_executors->size; i++) {
2185
        if (co->co_executors->executors[i]) {
2186
            _Py_ExecutorDetach(co->co_executors->executors[i]);
2187
            assert(co->co_executors->executors[i] == NULL);
2188
        }
2189
    }
2190
    PyMem_Free(co->co_executors);
2191
    co->co_executors = NULL;
2192
}
2193
2194
void
2195
_PyCode_Clear_Executors(PyCodeObject *code)
2196
{
2197
    clear_executors(code);
2198
}
2199
2200
#endif
2201
2202
static void
2203
deopt_code(PyCodeObject *code, _Py_CODEUNIT *instructions)
2204
0
{
2205
0
    Py_ssize_t len = Py_SIZE(code);
2206
0
    for (int i = 0; i < len; i++) {
2207
0
        _Py_CODEUNIT inst = _Py_GetBaseCodeUnit(code, i);
2208
0
        assert(inst.op.code < MIN_SPECIALIZED_OPCODE);
2209
0
        int caches = _PyOpcode_Caches[inst.op.code];
2210
0
        instructions[i] = inst;
2211
0
        for (int j = 1; j <= caches; j++) {
2212
0
            instructions[i+j].cache = 0;
2213
0
        }
2214
0
        i += caches;
2215
0
    }
2216
0
}
2217
2218
PyObject *
2219
_PyCode_GetCode(PyCodeObject *co)
2220
0
{
2221
0
    if (init_co_cached(co)) {
2222
0
        return NULL;
2223
0
    }
2224
2225
0
    _PyCoCached *cached = co->_co_cached;
2226
0
    PyObject *code = FT_ATOMIC_LOAD_PTR(cached->_co_code);
2227
0
    if (code != NULL) {
2228
0
        return Py_NewRef(code);
2229
0
    }
2230
2231
0
    Py_BEGIN_CRITICAL_SECTION(co);
2232
0
    code = cached->_co_code;
2233
0
    if (code == NULL) {
2234
0
        code = PyBytes_FromStringAndSize((const char *)_PyCode_CODE(co),
2235
0
                                         _PyCode_NBYTES(co));
2236
0
        if (code != NULL) {
2237
0
            deopt_code(co, (_Py_CODEUNIT *)PyBytes_AS_STRING(code));
2238
0
            assert(cached->_co_code == NULL);
2239
0
            FT_ATOMIC_STORE_PTR(cached->_co_code, code);
2240
0
        }
2241
0
    }
2242
0
    Py_END_CRITICAL_SECTION();
2243
0
    return Py_XNewRef(code);
2244
0
}
2245
2246
PyObject *
2247
PyCode_GetCode(PyCodeObject *co)
2248
0
{
2249
0
    return _PyCode_GetCode(co);
2250
0
}
2251
2252
/******************
2253
 * PyCode_Type
2254
 ******************/
2255
2256
/*[clinic input]
2257
class code "PyCodeObject *" "&PyCode_Type"
2258
[clinic start generated code]*/
2259
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=78aa5d576683bb4b]*/
2260
2261
/*[clinic input]
2262
@classmethod
2263
code.__new__ as code_new
2264
2265
    argcount: int
2266
    posonlyargcount: int
2267
    kwonlyargcount: int
2268
    nlocals: int
2269
    stacksize: int
2270
    flags: int
2271
    codestring as code: object(subclass_of="&PyBytes_Type")
2272
    constants as consts: object(subclass_of="&PyTuple_Type")
2273
    names: object(subclass_of="&PyTuple_Type")
2274
    varnames: object(subclass_of="&PyTuple_Type")
2275
    filename: unicode
2276
    name: unicode
2277
    qualname: unicode
2278
    firstlineno: int
2279
    linetable: object(subclass_of="&PyBytes_Type")
2280
    exceptiontable: object(subclass_of="&PyBytes_Type")
2281
    freevars: object(subclass_of="&PyTuple_Type", c_default="NULL") = ()
2282
    cellvars: object(subclass_of="&PyTuple_Type", c_default="NULL") = ()
2283
    /
2284
2285
Create a code object.  Not for the faint of heart.
2286
[clinic start generated code]*/
2287
2288
static PyObject *
2289
code_new_impl(PyTypeObject *type, int argcount, int posonlyargcount,
2290
              int kwonlyargcount, int nlocals, int stacksize, int flags,
2291
              PyObject *code, PyObject *consts, PyObject *names,
2292
              PyObject *varnames, PyObject *filename, PyObject *name,
2293
              PyObject *qualname, int firstlineno, PyObject *linetable,
2294
              PyObject *exceptiontable, PyObject *freevars,
2295
              PyObject *cellvars)
2296
/*[clinic end generated code: output=069fa20d299f9dda input=e31da3c41ad8064a]*/
2297
0
{
2298
0
    PyObject *co = NULL;
2299
0
    PyObject *ournames = NULL;
2300
0
    PyObject *ourvarnames = NULL;
2301
0
    PyObject *ourfreevars = NULL;
2302
0
    PyObject *ourcellvars = NULL;
2303
2304
0
    if (PySys_Audit("code.__new__", "OOOiiiiii",
2305
0
                    code, filename, name, argcount, posonlyargcount,
2306
0
                    kwonlyargcount, nlocals, stacksize, flags) < 0) {
2307
0
        goto cleanup;
2308
0
    }
2309
2310
0
    if (argcount < 0) {
2311
0
        PyErr_SetString(
2312
0
            PyExc_ValueError,
2313
0
            "code: argcount must not be negative");
2314
0
        goto cleanup;
2315
0
    }
2316
2317
0
    if (posonlyargcount < 0) {
2318
0
        PyErr_SetString(
2319
0
            PyExc_ValueError,
2320
0
            "code: posonlyargcount must not be negative");
2321
0
        goto cleanup;
2322
0
    }
2323
2324
0
    if (kwonlyargcount < 0) {
2325
0
        PyErr_SetString(
2326
0
            PyExc_ValueError,
2327
0
            "code: kwonlyargcount must not be negative");
2328
0
        goto cleanup;
2329
0
    }
2330
0
    if (nlocals < 0) {
2331
0
        PyErr_SetString(
2332
0
            PyExc_ValueError,
2333
0
            "code: nlocals must not be negative");
2334
0
        goto cleanup;
2335
0
    }
2336
2337
0
    ournames = validate_and_copy_tuple(names);
2338
0
    if (ournames == NULL)
2339
0
        goto cleanup;
2340
0
    ourvarnames = validate_and_copy_tuple(varnames);
2341
0
    if (ourvarnames == NULL)
2342
0
        goto cleanup;
2343
0
    if (freevars)
2344
0
        ourfreevars = validate_and_copy_tuple(freevars);
2345
0
    else
2346
0
        ourfreevars = PyTuple_New(0);
2347
0
    if (ourfreevars == NULL)
2348
0
        goto cleanup;
2349
0
    if (cellvars)
2350
0
        ourcellvars = validate_and_copy_tuple(cellvars);
2351
0
    else
2352
0
        ourcellvars = PyTuple_New(0);
2353
0
    if (ourcellvars == NULL)
2354
0
        goto cleanup;
2355
2356
0
    co = (PyObject *)PyCode_NewWithPosOnlyArgs(argcount, posonlyargcount,
2357
0
                                               kwonlyargcount,
2358
0
                                               nlocals, stacksize, flags,
2359
0
                                               code, consts, ournames,
2360
0
                                               ourvarnames, ourfreevars,
2361
0
                                               ourcellvars, filename,
2362
0
                                               name, qualname, firstlineno,
2363
0
                                               linetable,
2364
0
                                               exceptiontable
2365
0
                                              );
2366
0
  cleanup:
2367
0
    Py_XDECREF(ournames);
2368
0
    Py_XDECREF(ourvarnames);
2369
0
    Py_XDECREF(ourfreevars);
2370
0
    Py_XDECREF(ourcellvars);
2371
0
    return co;
2372
0
}
2373
2374
static void
2375
free_monitoring_data(_PyCoMonitoringData *data)
2376
57.2k
{
2377
57.2k
    if (data == NULL) {
2378
57.2k
        return;
2379
57.2k
    }
2380
0
    if (data->tools) {
2381
0
        PyMem_Free(data->tools);
2382
0
    }
2383
0
    if (data->lines) {
2384
0
        PyMem_Free(data->lines);
2385
0
    }
2386
0
    if (data->line_tools) {
2387
0
        PyMem_Free(data->line_tools);
2388
0
    }
2389
0
    if (data->per_instruction_opcodes) {
2390
0
        PyMem_Free(data->per_instruction_opcodes);
2391
0
    }
2392
0
    if (data->per_instruction_tools) {
2393
0
        PyMem_Free(data->per_instruction_tools);
2394
0
    }
2395
0
    PyMem_Free(data);
2396
0
}
2397
2398
static void
2399
code_dealloc(PyObject *self)
2400
57.2k
{
2401
57.2k
    PyThreadState *tstate = PyThreadState_GET();
2402
57.2k
    _Py_atomic_add_uint64(&tstate->interp->_code_object_generation, 1);
2403
57.2k
    PyCodeObject *co = _PyCodeObject_CAST(self);
2404
0
    _PyObject_ResurrectStart(self);
2405
57.2k
    notify_code_watchers(PY_CODE_EVENT_DESTROY, co);
2406
57.2k
    if (_PyObject_ResurrectEnd(self)) {
2407
0
        return;
2408
0
    }
2409
2410
#ifdef Py_GIL_DISABLED
2411
    PyObject_GC_UnTrack(co);
2412
#endif
2413
2414
57.2k
    _PyFunction_ClearCodeByVersion(co->co_version);
2415
57.2k
    if (co->co_extra != NULL) {
2416
0
        PyInterpreterState *interp = _PyInterpreterState_GET();
2417
0
        _PyCodeObjectExtra *co_extra = co->co_extra;
2418
2419
0
        for (Py_ssize_t i = 0; i < co_extra->ce_size; i++) {
2420
0
            freefunc free_extra = interp->co_extra_freefuncs[i];
2421
2422
0
            if (free_extra != NULL) {
2423
0
                free_extra(co_extra->ce_extras[i]);
2424
0
            }
2425
0
        }
2426
2427
0
        PyMem_Free(co_extra);
2428
0
    }
2429
#ifdef _Py_TIER2
2430
    if (co->co_executors != NULL) {
2431
        clear_executors(co);
2432
    }
2433
#endif
2434
2435
57.2k
    Py_XDECREF(co->co_consts);
2436
57.2k
    Py_XDECREF(co->co_names);
2437
57.2k
    Py_XDECREF(co->co_localsplusnames);
2438
57.2k
    Py_XDECREF(co->co_localspluskinds);
2439
57.2k
    Py_XDECREF(co->co_filename);
2440
57.2k
    Py_XDECREF(co->co_name);
2441
57.2k
    Py_XDECREF(co->co_qualname);
2442
57.2k
    Py_XDECREF(co->co_linetable);
2443
57.2k
    Py_XDECREF(co->co_exceptiontable);
2444
#ifdef Py_GIL_DISABLED
2445
    assert(co->_co_unique_id == _Py_INVALID_UNIQUE_ID);
2446
#endif
2447
57.2k
    if (co->_co_cached != NULL) {
2448
0
        Py_XDECREF(co->_co_cached->_co_code);
2449
0
        Py_XDECREF(co->_co_cached->_co_cellvars);
2450
0
        Py_XDECREF(co->_co_cached->_co_freevars);
2451
0
        Py_XDECREF(co->_co_cached->_co_varnames);
2452
0
        PyMem_Free(co->_co_cached);
2453
0
    }
2454
57.2k
    FT_CLEAR_WEAKREFS(self, co->co_weakreflist);
2455
57.2k
    free_monitoring_data(co->_co_monitoring);
2456
#ifdef Py_GIL_DISABLED
2457
    if (co->co_tlbc != NULL) {
2458
        // The first element always points to the mutable bytecode at the end of
2459
        // the code object, which will be freed when the code object is freed.
2460
        for (Py_ssize_t i = 1; i < co->co_tlbc->size; i++) {
2461
            char *entry = co->co_tlbc->entries[i];
2462
            if (entry != NULL) {
2463
                PyMem_Free(entry);
2464
            }
2465
        }
2466
        PyMem_Free(co->co_tlbc);
2467
    }
2468
#endif
2469
57.2k
    PyObject_Free(co);
2470
57.2k
}
2471
2472
#ifdef Py_GIL_DISABLED
2473
static int
2474
code_traverse(PyObject *self, visitproc visit, void *arg)
2475
{
2476
    PyCodeObject *co = _PyCodeObject_CAST(self);
2477
    Py_VISIT(co->co_consts);
2478
    return 0;
2479
}
2480
#endif
2481
2482
static PyObject *
2483
code_repr(PyObject *self)
2484
0
{
2485
0
    PyCodeObject *co = _PyCodeObject_CAST(self);
2486
0
    int lineno;
2487
0
    if (co->co_firstlineno != 0)
2488
0
        lineno = co->co_firstlineno;
2489
0
    else
2490
0
        lineno = -1;
2491
0
    if (co->co_filename && PyUnicode_Check(co->co_filename)) {
2492
0
        return PyUnicode_FromFormat(
2493
0
            "<code object %U at %p, file \"%U\", line %d>",
2494
0
            co->co_name, co, co->co_filename, lineno);
2495
0
    } else {
2496
0
        return PyUnicode_FromFormat(
2497
0
            "<code object %U at %p, file ???, line %d>",
2498
0
            co->co_name, co, lineno);
2499
0
    }
2500
0
}
2501
2502
static PyObject *
2503
code_richcompare(PyObject *self, PyObject *other, int op)
2504
3.88k
{
2505
3.88k
    PyCodeObject *co, *cp;
2506
3.88k
    int eq;
2507
3.88k
    PyObject *consts1, *consts2;
2508
3.88k
    PyObject *res;
2509
2510
3.88k
    if ((op != Py_EQ && op != Py_NE) ||
2511
3.88k
        !PyCode_Check(self) ||
2512
3.88k
        !PyCode_Check(other)) {
2513
0
        Py_RETURN_NOTIMPLEMENTED;
2514
0
    }
2515
2516
3.88k
    co = (PyCodeObject *)self;
2517
3.88k
    cp = (PyCodeObject *)other;
2518
2519
3.88k
    eq = PyObject_RichCompareBool(co->co_name, cp->co_name, Py_EQ);
2520
3.88k
    if (eq <= 0) goto unequal;
2521
3.88k
    eq = co->co_argcount == cp->co_argcount;
2522
3.88k
    if (!eq) goto unequal;
2523
3.88k
    eq = co->co_posonlyargcount == cp->co_posonlyargcount;
2524
3.88k
    if (!eq) goto unequal;
2525
3.88k
    eq = co->co_kwonlyargcount == cp->co_kwonlyargcount;
2526
3.88k
    if (!eq) goto unequal;
2527
3.88k
    eq = co->co_flags == cp->co_flags;
2528
3.88k
    if (!eq) goto unequal;
2529
3.88k
    eq = co->co_firstlineno == cp->co_firstlineno;
2530
3.88k
    if (!eq) goto unequal;
2531
3.88k
    eq = Py_SIZE(co) == Py_SIZE(cp);
2532
3.88k
    if (!eq) {
2533
0
        goto unequal;
2534
0
    }
2535
74.7k
    for (int i = 0; i < Py_SIZE(co); i++) {
2536
70.8k
        _Py_CODEUNIT co_instr = _Py_GetBaseCodeUnit(co, i);
2537
70.8k
        _Py_CODEUNIT cp_instr = _Py_GetBaseCodeUnit(cp, i);
2538
70.8k
        if (co_instr.cache != cp_instr.cache) {
2539
0
            goto unequal;
2540
0
        }
2541
70.8k
        i += _PyOpcode_Caches[co_instr.op.code];
2542
70.8k
    }
2543
2544
    /* compare constants */
2545
3.88k
    consts1 = _PyCode_ConstantKey(co->co_consts);
2546
3.88k
    if (!consts1)
2547
0
        return NULL;
2548
3.88k
    consts2 = _PyCode_ConstantKey(cp->co_consts);
2549
3.88k
    if (!consts2) {
2550
0
        Py_DECREF(consts1);
2551
0
        return NULL;
2552
0
    }
2553
3.88k
    eq = PyObject_RichCompareBool(consts1, consts2, Py_EQ);
2554
3.88k
    Py_DECREF(consts1);
2555
3.88k
    Py_DECREF(consts2);
2556
3.88k
    if (eq <= 0) goto unequal;
2557
2558
3.88k
    eq = PyObject_RichCompareBool(co->co_names, cp->co_names, Py_EQ);
2559
3.88k
    if (eq <= 0) goto unequal;
2560
3.88k
    eq = PyObject_RichCompareBool(co->co_localsplusnames,
2561
3.88k
                                  cp->co_localsplusnames, Py_EQ);
2562
3.88k
    if (eq <= 0) goto unequal;
2563
3.88k
    eq = PyObject_RichCompareBool(co->co_linetable, cp->co_linetable, Py_EQ);
2564
3.88k
    if (eq <= 0) {
2565
0
        goto unequal;
2566
0
    }
2567
3.88k
    eq = PyObject_RichCompareBool(co->co_exceptiontable,
2568
3.88k
                                  cp->co_exceptiontable, Py_EQ);
2569
3.88k
    if (eq <= 0) {
2570
0
        goto unequal;
2571
0
    }
2572
2573
3.88k
    if (op == Py_EQ)
2574
3.88k
        res = Py_True;
2575
0
    else
2576
0
        res = Py_False;
2577
3.88k
    goto done;
2578
2579
0
  unequal:
2580
0
    if (eq < 0)
2581
0
        return NULL;
2582
0
    if (op == Py_NE)
2583
0
        res = Py_True;
2584
0
    else
2585
0
        res = Py_False;
2586
2587
3.88k
  done:
2588
3.88k
    return Py_NewRef(res);
2589
0
}
2590
2591
static Py_hash_t
2592
code_hash(PyObject *self)
2593
208k
{
2594
208k
    PyCodeObject *co = _PyCodeObject_CAST(self);
2595
0
    Py_uhash_t uhash = 20221211;
2596
20.1M
    #define SCRAMBLE_IN(H) do {       \
2597
20.1M
        uhash ^= (Py_uhash_t)(H);     \
2598
20.1M
        uhash *= PyHASH_MULTIPLIER;  \
2599
20.1M
    } while (0)
2600
1.25M
    #define SCRAMBLE_IN_HASH(EXPR) do {     \
2601
1.25M
        Py_hash_t h = PyObject_Hash(EXPR);  \
2602
1.25M
        if (h == -1) {                      \
2603
0
            return -1;                      \
2604
0
        }                                   \
2605
1.25M
        SCRAMBLE_IN(h);                     \
2606
1.25M
    } while (0)
2607
2608
208k
    SCRAMBLE_IN_HASH(co->co_name);
2609
208k
    SCRAMBLE_IN_HASH(co->co_consts);
2610
208k
    SCRAMBLE_IN_HASH(co->co_names);
2611
208k
    SCRAMBLE_IN_HASH(co->co_localsplusnames);
2612
208k
    SCRAMBLE_IN_HASH(co->co_linetable);
2613
208k
    SCRAMBLE_IN_HASH(co->co_exceptiontable);
2614
208k
    SCRAMBLE_IN(co->co_argcount);
2615
208k
    SCRAMBLE_IN(co->co_posonlyargcount);
2616
208k
    SCRAMBLE_IN(co->co_kwonlyargcount);
2617
208k
    SCRAMBLE_IN(co->co_flags);
2618
208k
    SCRAMBLE_IN(co->co_firstlineno);
2619
208k
    SCRAMBLE_IN(Py_SIZE(co));
2620
9.01M
    for (int i = 0; i < Py_SIZE(co); i++) {
2621
8.80M
        _Py_CODEUNIT co_instr = _Py_GetBaseCodeUnit(co, i);
2622
8.80M
        SCRAMBLE_IN(co_instr.op.code);
2623
8.80M
        SCRAMBLE_IN(co_instr.op.arg);
2624
8.80M
        i += _PyOpcode_Caches[co_instr.op.code];
2625
8.80M
    }
2626
208k
    if ((Py_hash_t)uhash == -1) {
2627
0
        return -2;
2628
0
    }
2629
208k
    return (Py_hash_t)uhash;
2630
208k
}
2631
2632
2633
#define OFF(x) offsetof(PyCodeObject, x)
2634
2635
static PyMemberDef code_memberlist[] = {
2636
    {"co_argcount",        Py_T_INT,     OFF(co_argcount),        Py_READONLY},
2637
    {"co_posonlyargcount", Py_T_INT,     OFF(co_posonlyargcount), Py_READONLY},
2638
    {"co_kwonlyargcount",  Py_T_INT,     OFF(co_kwonlyargcount),  Py_READONLY},
2639
    {"co_stacksize",       Py_T_INT,     OFF(co_stacksize),       Py_READONLY},
2640
    {"co_flags",           Py_T_INT,     OFF(co_flags),           Py_READONLY},
2641
    {"co_nlocals",         Py_T_INT,     OFF(co_nlocals),         Py_READONLY},
2642
    {"co_consts",          _Py_T_OBJECT, OFF(co_consts),          Py_READONLY},
2643
    {"co_names",           _Py_T_OBJECT, OFF(co_names),           Py_READONLY},
2644
    {"co_filename",        _Py_T_OBJECT, OFF(co_filename),        Py_READONLY},
2645
    {"co_name",            _Py_T_OBJECT, OFF(co_name),            Py_READONLY},
2646
    {"co_qualname",        _Py_T_OBJECT, OFF(co_qualname),        Py_READONLY},
2647
    {"co_firstlineno",     Py_T_INT,     OFF(co_firstlineno),     Py_READONLY},
2648
    {"co_linetable",       _Py_T_OBJECT, OFF(co_linetable),       Py_READONLY},
2649
    {"co_exceptiontable",  _Py_T_OBJECT, OFF(co_exceptiontable),  Py_READONLY},
2650
    {NULL}      /* Sentinel */
2651
};
2652
2653
2654
static PyObject *
2655
code_getvarnames(PyObject *self, void *closure)
2656
0
{
2657
0
    PyCodeObject *code = _PyCodeObject_CAST(self);
2658
0
    return _PyCode_GetVarnames(code);
2659
0
}
2660
2661
static PyObject *
2662
code_getcellvars(PyObject *self, void *closure)
2663
0
{
2664
0
    PyCodeObject *code = _PyCodeObject_CAST(self);
2665
0
    return _PyCode_GetCellvars(code);
2666
0
}
2667
2668
static PyObject *
2669
code_getfreevars(PyObject *self, void *closure)
2670
0
{
2671
0
    PyCodeObject *code = _PyCodeObject_CAST(self);
2672
0
    return _PyCode_GetFreevars(code);
2673
0
}
2674
2675
static PyObject *
2676
code_getcodeadaptive(PyObject *self, void *closure)
2677
0
{
2678
0
    PyCodeObject *code = _PyCodeObject_CAST(self);
2679
0
    return PyBytes_FromStringAndSize(code->co_code_adaptive,
2680
0
                                     _PyCode_NBYTES(code));
2681
0
}
2682
2683
static PyObject *
2684
code_getcode(PyObject *self, void *closure)
2685
0
{
2686
0
    PyCodeObject *code = _PyCodeObject_CAST(self);
2687
0
    return _PyCode_GetCode(code);
2688
0
}
2689
2690
static PyGetSetDef code_getsetlist[] = {
2691
    {"_co_code_adaptive", code_getcodeadaptive, NULL, NULL},
2692
    // The following old names are kept for backward compatibility.
2693
    {"co_varnames",       code_getvarnames,     NULL, NULL},
2694
    {"co_cellvars",       code_getcellvars,     NULL, NULL},
2695
    {"co_freevars",       code_getfreevars,     NULL, NULL},
2696
    {"co_code",           code_getcode,         NULL, NULL},
2697
    {0}
2698
};
2699
2700
2701
static PyObject *
2702
code_sizeof(PyObject *self, PyObject *Py_UNUSED(args))
2703
0
{
2704
0
    PyCodeObject *co = _PyCodeObject_CAST(self);
2705
0
    size_t res = _PyObject_VAR_SIZE(Py_TYPE(co), Py_SIZE(co));
2706
0
    _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra*) co->co_extra;
2707
0
    if (co_extra != NULL) {
2708
0
        res += sizeof(_PyCodeObjectExtra);
2709
0
        res += ((size_t)co_extra->ce_size - 1) * sizeof(co_extra->ce_extras[0]);
2710
0
    }
2711
0
    return PyLong_FromSize_t(res);
2712
0
}
2713
2714
static PyObject *
2715
code_linesiterator(PyObject *self, PyObject *Py_UNUSED(args))
2716
0
{
2717
0
    PyCodeObject *code = _PyCodeObject_CAST(self);
2718
0
    return (PyObject *)new_linesiterator(code);
2719
0
}
2720
2721
static PyObject *
2722
code_branchesiterator(PyObject *self, PyObject *Py_UNUSED(args))
2723
0
{
2724
0
    PyCodeObject *code = _PyCodeObject_CAST(self);
2725
0
    return _PyInstrumentation_BranchesIterator(code);
2726
0
}
2727
2728
/*[clinic input]
2729
@permit_long_summary
2730
@text_signature "($self, /, **changes)"
2731
code.replace
2732
2733
    *
2734
    co_argcount: int(c_default="((PyCodeObject *)self)->co_argcount") = unchanged
2735
    co_posonlyargcount: int(c_default="((PyCodeObject *)self)->co_posonlyargcount") = unchanged
2736
    co_kwonlyargcount: int(c_default="((PyCodeObject *)self)->co_kwonlyargcount") = unchanged
2737
    co_nlocals: int(c_default="((PyCodeObject *)self)->co_nlocals") = unchanged
2738
    co_stacksize: int(c_default="((PyCodeObject *)self)->co_stacksize") = unchanged
2739
    co_flags: int(c_default="((PyCodeObject *)self)->co_flags") = unchanged
2740
    co_firstlineno: int(c_default="((PyCodeObject *)self)->co_firstlineno") = unchanged
2741
    co_code: object(subclass_of="&PyBytes_Type", c_default="NULL") = unchanged
2742
    co_consts: object(subclass_of="&PyTuple_Type", c_default="((PyCodeObject *)self)->co_consts") = unchanged
2743
    co_names: object(subclass_of="&PyTuple_Type", c_default="((PyCodeObject *)self)->co_names") = unchanged
2744
    co_varnames: object(subclass_of="&PyTuple_Type", c_default="NULL") = unchanged
2745
    co_freevars: object(subclass_of="&PyTuple_Type", c_default="NULL") = unchanged
2746
    co_cellvars: object(subclass_of="&PyTuple_Type", c_default="NULL") = unchanged
2747
    co_filename: unicode(c_default="((PyCodeObject *)self)->co_filename") = unchanged
2748
    co_name: unicode(c_default="((PyCodeObject *)self)->co_name") = unchanged
2749
    co_qualname: unicode(c_default="((PyCodeObject *)self)->co_qualname") = unchanged
2750
    co_linetable: object(subclass_of="&PyBytes_Type", c_default="((PyCodeObject *)self)->co_linetable") = unchanged
2751
    co_exceptiontable: object(subclass_of="&PyBytes_Type", c_default="((PyCodeObject *)self)->co_exceptiontable") = unchanged
2752
2753
Return a copy of the code object with new values for the specified fields.
2754
[clinic start generated code]*/
2755
2756
static PyObject *
2757
code_replace_impl(PyCodeObject *self, int co_argcount,
2758
                  int co_posonlyargcount, int co_kwonlyargcount,
2759
                  int co_nlocals, int co_stacksize, int co_flags,
2760
                  int co_firstlineno, PyObject *co_code, PyObject *co_consts,
2761
                  PyObject *co_names, PyObject *co_varnames,
2762
                  PyObject *co_freevars, PyObject *co_cellvars,
2763
                  PyObject *co_filename, PyObject *co_name,
2764
                  PyObject *co_qualname, PyObject *co_linetable,
2765
                  PyObject *co_exceptiontable)
2766
/*[clinic end generated code: output=e75c48a15def18b9 input=e944fdac8b456114]*/
2767
0
{
2768
0
#define CHECK_INT_ARG(ARG) \
2769
0
        if (ARG < 0) { \
2770
0
            PyErr_SetString(PyExc_ValueError, \
2771
0
                            #ARG " must be a positive integer"); \
2772
0
            return NULL; \
2773
0
        }
2774
2775
0
    CHECK_INT_ARG(co_argcount);
2776
0
    CHECK_INT_ARG(co_posonlyargcount);
2777
0
    CHECK_INT_ARG(co_kwonlyargcount);
2778
0
    CHECK_INT_ARG(co_nlocals);
2779
0
    CHECK_INT_ARG(co_stacksize);
2780
0
    CHECK_INT_ARG(co_flags);
2781
0
    CHECK_INT_ARG(co_firstlineno);
2782
2783
0
#undef CHECK_INT_ARG
2784
2785
0
    PyObject *code = NULL;
2786
0
    if (co_code == NULL) {
2787
0
        code = _PyCode_GetCode(self);
2788
0
        if (code == NULL) {
2789
0
            return NULL;
2790
0
        }
2791
0
        co_code = code;
2792
0
    }
2793
2794
0
    if (PySys_Audit("code.__new__", "OOOiiiiii",
2795
0
                    co_code, co_filename, co_name, co_argcount,
2796
0
                    co_posonlyargcount, co_kwonlyargcount, co_nlocals,
2797
0
                    co_stacksize, co_flags) < 0) {
2798
0
        Py_XDECREF(code);
2799
0
        return NULL;
2800
0
    }
2801
2802
0
    PyCodeObject *co = NULL;
2803
0
    PyObject *varnames = NULL;
2804
0
    PyObject *cellvars = NULL;
2805
0
    PyObject *freevars = NULL;
2806
0
    if (co_varnames == NULL) {
2807
0
        varnames = get_localsplus_names(self, CO_FAST_LOCAL, self->co_nlocals);
2808
0
        if (varnames == NULL) {
2809
0
            goto error;
2810
0
        }
2811
0
        co_varnames = varnames;
2812
0
    }
2813
0
    if (co_cellvars == NULL) {
2814
0
        cellvars = get_localsplus_names(self, CO_FAST_CELL, self->co_ncellvars);
2815
0
        if (cellvars == NULL) {
2816
0
            goto error;
2817
0
        }
2818
0
        co_cellvars = cellvars;
2819
0
    }
2820
0
    if (co_freevars == NULL) {
2821
0
        freevars = get_localsplus_names(self, CO_FAST_FREE, self->co_nfreevars);
2822
0
        if (freevars == NULL) {
2823
0
            goto error;
2824
0
        }
2825
0
        co_freevars = freevars;
2826
0
    }
2827
2828
0
    co = PyCode_NewWithPosOnlyArgs(
2829
0
        co_argcount, co_posonlyargcount, co_kwonlyargcount, co_nlocals,
2830
0
        co_stacksize, co_flags, co_code, co_consts, co_names,
2831
0
        co_varnames, co_freevars, co_cellvars, co_filename, co_name,
2832
0
        co_qualname, co_firstlineno,
2833
0
        co_linetable, co_exceptiontable);
2834
2835
0
error:
2836
0
    Py_XDECREF(code);
2837
0
    Py_XDECREF(varnames);
2838
0
    Py_XDECREF(cellvars);
2839
0
    Py_XDECREF(freevars);
2840
0
    return (PyObject *)co;
2841
0
}
2842
2843
/*[clinic input]
2844
code._varname_from_oparg
2845
2846
    oparg: int
2847
2848
(internal-only) Return the local variable name for the given oparg.
2849
2850
WARNING: this method is for internal use only and may change or go
2851
away.
2852
[clinic start generated code]*/
2853
2854
static PyObject *
2855
code__varname_from_oparg_impl(PyCodeObject *self, int oparg)
2856
/*[clinic end generated code: output=1fd1130413184206 input=6ba7d6df0d566463]*/
2857
0
{
2858
0
    PyObject *name = PyTuple_GetItem(self->co_localsplusnames, oparg);
2859
0
    if (name == NULL) {
2860
0
        return NULL;
2861
0
    }
2862
0
    return Py_NewRef(name);
2863
0
}
2864
2865
/* XXX code objects need to participate in GC? */
2866
2867
static struct PyMethodDef code_methods[] = {
2868
    {"__sizeof__", code_sizeof, METH_NOARGS},
2869
    {"co_lines", code_linesiterator, METH_NOARGS},
2870
    {"co_branches", code_branchesiterator, METH_NOARGS},
2871
    {"co_positions", code_positionsiterator, METH_NOARGS},
2872
    CODE_REPLACE_METHODDEF
2873
    CODE__VARNAME_FROM_OPARG_METHODDEF
2874
    {"__replace__", _PyCFunction_CAST(code_replace), METH_FASTCALL|METH_KEYWORDS,
2875
     PyDoc_STR("__replace__($self, /, **changes)\n--\n\nThe same as replace().")},
2876
    {NULL, NULL}                /* sentinel */
2877
};
2878
2879
2880
PyTypeObject PyCode_Type = {
2881
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
2882
    "code",
2883
    offsetof(PyCodeObject, co_code_adaptive),
2884
    sizeof(_Py_CODEUNIT),
2885
    code_dealloc,                       /* tp_dealloc */
2886
    0,                                  /* tp_vectorcall_offset */
2887
    0,                                  /* tp_getattr */
2888
    0,                                  /* tp_setattr */
2889
    0,                                  /* tp_as_async */
2890
    code_repr,                          /* tp_repr */
2891
    0,                                  /* tp_as_number */
2892
    0,                                  /* tp_as_sequence */
2893
    0,                                  /* tp_as_mapping */
2894
    code_hash,                          /* tp_hash */
2895
    0,                                  /* tp_call */
2896
    0,                                  /* tp_str */
2897
    PyObject_GenericGetAttr,            /* tp_getattro */
2898
    0,                                  /* tp_setattro */
2899
    0,                                  /* tp_as_buffer */
2900
#ifdef Py_GIL_DISABLED
2901
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
2902
#else
2903
    Py_TPFLAGS_DEFAULT,                 /* tp_flags */
2904
#endif
2905
    code_new__doc__,                    /* tp_doc */
2906
#ifdef Py_GIL_DISABLED
2907
    code_traverse,                      /* tp_traverse */
2908
#else
2909
    0,                                  /* tp_traverse */
2910
#endif
2911
    0,                                  /* tp_clear */
2912
    code_richcompare,                   /* tp_richcompare */
2913
    offsetof(PyCodeObject, co_weakreflist),     /* tp_weaklistoffset */
2914
    0,                                  /* tp_iter */
2915
    0,                                  /* tp_iternext */
2916
    code_methods,                       /* tp_methods */
2917
    code_memberlist,                    /* tp_members */
2918
    code_getsetlist,                    /* tp_getset */
2919
    0,                                  /* tp_base */
2920
    0,                                  /* tp_dict */
2921
    0,                                  /* tp_descr_get */
2922
    0,                                  /* tp_descr_set */
2923
    0,                                  /* tp_dictoffset */
2924
    0,                                  /* tp_init */
2925
    0,                                  /* tp_alloc */
2926
    code_new,                           /* tp_new */
2927
};
2928
2929
2930
/******************
2931
 * other API
2932
 ******************/
2933
2934
PyObject*
2935
_PyCode_ConstantKey(PyObject *op)
2936
117M
{
2937
117M
    PyObject *key;
2938
2939
    /* Py_None and Py_Ellipsis are singletons. */
2940
117M
    if (op == Py_None || op == Py_Ellipsis
2941
117M
       || PyLong_CheckExact(op)
2942
117M
       || PyUnicode_CheckExact(op)
2943
          /* code_richcompare() uses _PyCode_ConstantKey() internally */
2944
53.6M
       || PyCode_Check(op))
2945
63.8M
    {
2946
        /* Objects of these types are always different from object of other
2947
         * type and from tuples. */
2948
63.8M
        key = Py_NewRef(op);
2949
63.8M
    }
2950
53.5M
    else if (PyBool_Check(op) || PyBytes_CheckExact(op)) {
2951
        /* Make booleans different from integers 0 and 1.
2952
         * Avoid BytesWarning from comparing bytes with strings. */
2953
190k
        key = _PyTuple_FromPair((PyObject *)Py_TYPE(op), op);
2954
190k
    }
2955
53.3M
    else if (PyFloat_CheckExact(op)) {
2956
52.5M
        double d = PyFloat_AS_DOUBLE(op);
2957
        /* all we need is to make the tuple different in either the 0.0
2958
         * or -0.0 case from all others, just to avoid the "coercion".
2959
         */
2960
52.5M
        if (d == 0.0 && copysign(1.0, d) < 0.0)
2961
7.06k
            key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
2962
52.5M
        else
2963
52.5M
            key = _PyTuple_FromPair((PyObject *)Py_TYPE(op), op);
2964
52.5M
    }
2965
849k
    else if (PyComplex_CheckExact(op)) {
2966
289k
        Py_complex z;
2967
289k
        int real_negzero, imag_negzero;
2968
        /* For the complex case we must make complex(x, 0.)
2969
           different from complex(x, -0.) and complex(0., y)
2970
           different from complex(-0., y), for any x and y.
2971
           All four complex zeros must be distinguished.*/
2972
289k
        z = PyComplex_AsCComplex(op);
2973
289k
        real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
2974
289k
        imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
2975
        /* use True, False and None singleton as tags for the real and imag
2976
         * sign, to make tuples different */
2977
289k
        if (real_negzero && imag_negzero) {
2978
8.38k
            key = PyTuple_Pack(3, Py_TYPE(op), op, Py_True);
2979
8.38k
        }
2980
281k
        else if (imag_negzero) {
2981
9.98k
            key = PyTuple_Pack(3, Py_TYPE(op), op, Py_False);
2982
9.98k
        }
2983
271k
        else if (real_negzero) {
2984
12.0k
            key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
2985
12.0k
        }
2986
259k
        else {
2987
259k
            key = _PyTuple_FromPair((PyObject *)Py_TYPE(op), op);
2988
259k
        }
2989
289k
    }
2990
559k
    else if (PyTuple_CheckExact(op)) {
2991
546k
        Py_ssize_t i, len;
2992
546k
        PyObject *tuple;
2993
2994
546k
        len = PyTuple_GET_SIZE(op);
2995
546k
        tuple = PyTuple_New(len);
2996
546k
        if (tuple == NULL)
2997
0
            return NULL;
2998
2999
115M
        for (i=0; i < len; i++) {
3000
115M
            PyObject *item, *item_key;
3001
3002
115M
            item = PyTuple_GET_ITEM(op, i);
3003
0
            item_key = _PyCode_ConstantKey(item);
3004
115M
            if (item_key == NULL) {
3005
0
                Py_DECREF(tuple);
3006
0
                return NULL;
3007
0
            }
3008
3009
115M
            PyTuple_SET_ITEM(tuple, i, item_key);
3010
115M
        }
3011
3012
546k
        key = _PyTuple_FromPair(tuple, op);
3013
546k
        Py_DECREF(tuple);
3014
546k
    }
3015
12.7k
    else if (PyFrozenSet_CheckExact(op)) {
3016
5.43k
        Py_ssize_t pos = 0;
3017
5.43k
        PyObject *item;
3018
5.43k
        Py_hash_t hash;
3019
5.43k
        Py_ssize_t i, len;
3020
5.43k
        PyObject *tuple, *set;
3021
3022
5.43k
        len = PySet_GET_SIZE(op);
3023
5.43k
        tuple = PyTuple_New(len);
3024
5.43k
        if (tuple == NULL)
3025
0
            return NULL;
3026
3027
5.43k
        i = 0;
3028
29.5k
        while (_PySet_NextEntry(op, &pos, &item, &hash)) {
3029
24.1k
            PyObject *item_key;
3030
3031
24.1k
            item_key = _PyCode_ConstantKey(item);
3032
24.1k
            if (item_key == NULL) {
3033
0
                Py_DECREF(tuple);
3034
0
                return NULL;
3035
0
            }
3036
3037
24.1k
            assert(i < len);
3038
24.1k
            PyTuple_SET_ITEM(tuple, i, item_key);
3039
24.1k
            i++;
3040
24.1k
        }
3041
5.43k
        set = PyFrozenSet_New(tuple);
3042
5.43k
        Py_DECREF(tuple);
3043
5.43k
        if (set == NULL)
3044
0
            return NULL;
3045
3046
5.43k
        key = _PyTuple_FromPair(set, op);
3047
5.43k
        Py_DECREF(set);
3048
5.43k
        return key;
3049
5.43k
    }
3050
7.34k
    else if (PySlice_Check(op)) {
3051
7.34k
        PySliceObject *slice = (PySliceObject *)op;
3052
7.34k
        PyObject *start_key = NULL;
3053
7.34k
        PyObject *stop_key = NULL;
3054
7.34k
        PyObject *step_key = NULL;
3055
7.34k
        key = NULL;
3056
3057
7.34k
        start_key = _PyCode_ConstantKey(slice->start);
3058
7.34k
        if (start_key == NULL) {
3059
0
            goto slice_exit;
3060
0
        }
3061
3062
7.34k
        stop_key = _PyCode_ConstantKey(slice->stop);
3063
7.34k
        if (stop_key == NULL) {
3064
0
            goto slice_exit;
3065
0
        }
3066
3067
7.34k
        step_key = _PyCode_ConstantKey(slice->step);
3068
7.34k
        if (step_key == NULL) {
3069
0
            goto slice_exit;
3070
0
        }
3071
3072
7.34k
        PyObject *slice_key = PySlice_New(start_key, stop_key, step_key);
3073
7.34k
        if (slice_key == NULL) {
3074
0
            goto slice_exit;
3075
0
        }
3076
3077
7.34k
        key = _PyTuple_FromPair(slice_key, op);
3078
7.34k
        Py_DECREF(slice_key);
3079
7.34k
    slice_exit:
3080
7.34k
        Py_XDECREF(start_key);
3081
7.34k
        Py_XDECREF(stop_key);
3082
7.34k
        Py_XDECREF(step_key);
3083
7.34k
    }
3084
0
    else {
3085
        /* for other types, use the object identifier as a unique identifier
3086
         * to ensure that they are seen as unequal. */
3087
0
        PyObject *obj_id = PyLong_FromVoidPtr(op);
3088
0
        if (obj_id == NULL)
3089
0
            return NULL;
3090
3091
0
        key = _PyTuple_FromPair(obj_id, op);
3092
0
        Py_DECREF(obj_id);
3093
0
    }
3094
117M
    return key;
3095
117M
}
3096
3097
#ifdef Py_GIL_DISABLED
3098
static PyObject *
3099
intern_one_constant(PyObject *op)
3100
{
3101
    PyInterpreterState *interp = _PyInterpreterState_GET();
3102
    _Py_hashtable_t *consts = interp->code_state.constants;
3103
3104
    assert(!PyUnicode_CheckExact(op));  // strings are interned separately
3105
3106
    _Py_hashtable_entry_t *entry = _Py_hashtable_get_entry(consts, op);
3107
    if (entry == NULL) {
3108
        if (_Py_hashtable_set(consts, op, op) != 0) {
3109
            PyErr_NoMemory();
3110
            return NULL;
3111
        }
3112
3113
#ifdef Py_REF_DEBUG
3114
        Py_ssize_t refcnt = Py_REFCNT(op);
3115
        if (refcnt != 1) {
3116
            // Adjust the reftotal to account for the fact that we only
3117
            // restore a single reference in _PyCode_Fini.
3118
            _Py_AddRefTotal(_PyThreadState_GET(), -(refcnt - 1));
3119
        }
3120
#endif
3121
3122
        _Py_SetImmortal(op);
3123
        return op;
3124
    }
3125
3126
    assert(_Py_IsImmortal(entry->value));
3127
    return (PyObject *)entry->value;
3128
}
3129
3130
static int
3131
compare_constants(const void *key1, const void *key2)
3132
{
3133
    PyObject *op1 = (PyObject *)key1;
3134
    PyObject *op2 = (PyObject *)key2;
3135
    if (op1 == op2) {
3136
        return 1;
3137
    }
3138
    if (Py_TYPE(op1) != Py_TYPE(op2)) {
3139
        return 0;
3140
    }
3141
    // We compare container contents by identity because we have already
3142
    // internalized the items.
3143
    if (PyTuple_CheckExact(op1)) {
3144
        Py_ssize_t size = PyTuple_GET_SIZE(op1);
3145
        if (size != PyTuple_GET_SIZE(op2)) {
3146
            return 0;
3147
        }
3148
        for (Py_ssize_t i = 0; i < size; i++) {
3149
            if (PyTuple_GET_ITEM(op1, i) != PyTuple_GET_ITEM(op2, i)) {
3150
                return 0;
3151
            }
3152
        }
3153
        return 1;
3154
    }
3155
    else if (PyFrozenSet_CheckExact(op1)) {
3156
        if (PySet_GET_SIZE(op1) != PySet_GET_SIZE(op2)) {
3157
            return 0;
3158
        }
3159
        Py_ssize_t pos1 = 0, pos2 = 0;
3160
        PyObject *obj1, *obj2;
3161
        Py_hash_t hash1, hash2;
3162
        while ((_PySet_NextEntry(op1, &pos1, &obj1, &hash1)) &&
3163
               (_PySet_NextEntry(op2, &pos2, &obj2, &hash2)))
3164
        {
3165
            if (obj1 != obj2) {
3166
                return 0;
3167
            }
3168
        }
3169
        return 1;
3170
    }
3171
    else if (PySlice_Check(op1)) {
3172
        PySliceObject *s1 = (PySliceObject *)op1;
3173
        PySliceObject *s2 = (PySliceObject *)op2;
3174
        return (s1->start == s2->start &&
3175
                s1->stop  == s2->stop  &&
3176
                s1->step  == s2->step);
3177
    }
3178
    else if (PyBytes_CheckExact(op1) || PyLong_CheckExact(op1)) {
3179
        return PyObject_RichCompareBool(op1, op2, Py_EQ);
3180
    }
3181
    else if (PyFloat_CheckExact(op1)) {
3182
        // Ensure that, for example, +0.0 and -0.0 are distinct
3183
        double f1 = PyFloat_AS_DOUBLE(op1);
3184
        double f2 = PyFloat_AS_DOUBLE(op2);
3185
        return memcmp(&f1, &f2, sizeof(double)) == 0;
3186
    }
3187
    else if (PyComplex_CheckExact(op1)) {
3188
        Py_complex c1 = ((PyComplexObject *)op1)->cval;
3189
        Py_complex c2 = ((PyComplexObject *)op2)->cval;
3190
        return memcmp(&c1, &c2, sizeof(Py_complex)) == 0;
3191
    }
3192
    // gh-130851: Treat instances of unexpected types as distinct if they are
3193
    // not the same object.
3194
    return 0;
3195
}
3196
3197
static Py_uhash_t
3198
hash_const(const void *key)
3199
{
3200
    PyObject *op = (PyObject *)key;
3201
    if (PySlice_Check(op)) {
3202
        PySliceObject *s = (PySliceObject *)op;
3203
        PyObject *data[3] = { s->start, s->stop, s->step };
3204
        return Py_HashBuffer(&data, sizeof(data));
3205
    }
3206
    else if (PyTuple_CheckExact(op)) {
3207
        Py_ssize_t size = PyTuple_GET_SIZE(op);
3208
        PyObject **data = _PyTuple_ITEMS(op);
3209
        return Py_HashBuffer(data, sizeof(PyObject *) * size);
3210
    }
3211
    Py_hash_t h = PyObject_Hash(op);
3212
    if (h == -1) {
3213
        // gh-130851: Other than slice objects, every constant that the
3214
        // bytecode compiler generates is hashable. However, users can
3215
        // provide their own constants, when constructing code objects via
3216
        // types.CodeType(). If the user-provided constant is unhashable, we
3217
        // use the memory address of the object as a fallback hash value.
3218
        PyErr_Clear();
3219
        return (Py_uhash_t)(uintptr_t)key;
3220
    }
3221
    return (Py_uhash_t)h;
3222
}
3223
3224
static int
3225
clear_containers(_Py_hashtable_t *ht, const void *key, const void *value,
3226
                 void *user_data)
3227
{
3228
    // First clear containers to avoid recursive deallocation later on in
3229
    // destroy_key.
3230
    PyObject *op = (PyObject *)key;
3231
    if (PyTuple_CheckExact(op)) {
3232
        for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(op); i++) {
3233
            Py_CLEAR(_PyTuple_ITEMS(op)[i]);
3234
        }
3235
    }
3236
    else if (PySlice_Check(op)) {
3237
        PySliceObject *slice = (PySliceObject *)op;
3238
        Py_SETREF(slice->start, Py_None);
3239
        Py_SETREF(slice->stop, Py_None);
3240
        Py_SETREF(slice->step, Py_None);
3241
    }
3242
    else if (PyFrozenSet_CheckExact(op)) {
3243
        _PySet_ClearInternal((PySetObject *)op);
3244
    }
3245
    return 0;
3246
}
3247
3248
static void
3249
destroy_key(void *key)
3250
{
3251
    _Py_ClearImmortal(key);
3252
}
3253
#endif
3254
3255
PyStatus
3256
_PyCode_Init(PyInterpreterState *interp)
3257
21
{
3258
#ifdef Py_GIL_DISABLED
3259
    struct _py_code_state *state = &interp->code_state;
3260
    state->constants = _Py_hashtable_new_full(&hash_const, &compare_constants,
3261
                                              &destroy_key, NULL, NULL);
3262
    if (state->constants == NULL) {
3263
        return _PyStatus_NO_MEMORY();
3264
    }
3265
#endif
3266
21
    return _PyStatus_OK();
3267
21
}
3268
3269
void
3270
_PyCode_Fini(PyInterpreterState *interp)
3271
0
{
3272
#ifdef Py_GIL_DISABLED
3273
    // Free interned constants
3274
    struct _py_code_state *state = &interp->code_state;
3275
    if (state->constants) {
3276
        _Py_hashtable_foreach(state->constants, &clear_containers, NULL);
3277
        _Py_hashtable_destroy(state->constants);
3278
        state->constants = NULL;
3279
    }
3280
    _PyIndexPool_Fini(&interp->tlbc_indices);
3281
#endif
3282
0
}
3283
3284
#ifdef Py_GIL_DISABLED
3285
3286
// Thread-local bytecode (TLBC)
3287
//
3288
// Each thread specializes a thread-local copy of the bytecode, created on the
3289
// first RESUME, in free-threaded builds. All copies of the bytecode for a code
3290
// object are stored in the `co_tlbc` array. Threads reserve a globally unique
3291
// index identifying its copy of the bytecode in all `co_tlbc` arrays at thread
3292
// creation and release the index at thread destruction. The first entry in
3293
// every `co_tlbc` array always points to the "main" copy of the bytecode that
3294
// is stored at the end of the code object. This ensures that no bytecode is
3295
// copied for programs that do not use threads.
3296
//
3297
// Thread-local bytecode can be disabled at runtime by providing either `-X
3298
// tlbc=0` or `PYTHON_TLBC=0`. Disabling thread-local bytecode also disables
3299
// specialization. All threads share the main copy of the bytecode when
3300
// thread-local bytecode is disabled.
3301
//
3302
// Concurrent modifications to the bytecode made by the specializing
3303
// interpreter and instrumentation use atomics, with specialization taking care
3304
// not to overwrite an instruction that was instrumented concurrently.
3305
3306
int32_t
3307
_Py_ReserveTLBCIndex(PyInterpreterState *interp)
3308
{
3309
    if (interp->config.tlbc_enabled) {
3310
        return _PyIndexPool_AllocIndex(&interp->tlbc_indices);
3311
    }
3312
    // All threads share the main copy of the bytecode when TLBC is disabled
3313
    return 0;
3314
}
3315
3316
void
3317
_Py_UnreserveTLBCIndex(PyInterpreterState *interp, int32_t index)
3318
{
3319
    if (interp->config.tlbc_enabled) {
3320
        _PyIndexPool_FreeIndex(&interp->tlbc_indices, index);
3321
    }
3322
}
3323
3324
void
3325
_Py_ClearTLBCIndex(_PyThreadStateImpl *tstate)
3326
{
3327
    PyInterpreterState *interp = ((PyThreadState *)tstate)->interp;
3328
    _Py_UnreserveTLBCIndex(interp, tstate->tlbc_index);
3329
}
3330
3331
static _PyCodeArray *
3332
_PyCodeArray_New(Py_ssize_t size)
3333
{
3334
    _PyCodeArray *arr = PyMem_Calloc(
3335
        1, offsetof(_PyCodeArray, entries) + sizeof(void *) * size);
3336
    if (arr == NULL) {
3337
        PyErr_NoMemory();
3338
        return NULL;
3339
    }
3340
    arr->size = size;
3341
    return arr;
3342
}
3343
3344
// Get the underlying code unit, leaving instrumentation
3345
static _Py_CODEUNIT
3346
deopt_code_unit(PyCodeObject *code, int i)
3347
{
3348
    _Py_CODEUNIT *src_instr = _PyCode_CODE(code) + i;
3349
    _Py_CODEUNIT inst = {
3350
        .cache = FT_ATOMIC_LOAD_UINT16_RELAXED(*(uint16_t *)src_instr)};
3351
    int opcode = inst.op.code;
3352
    if (opcode < MIN_INSTRUMENTED_OPCODE) {
3353
        inst.op.code = _PyOpcode_Deopt[opcode];
3354
        assert(inst.op.code < MIN_SPECIALIZED_OPCODE);
3355
    }
3356
    // JIT should not be enabled with free-threading
3357
    assert(inst.op.code != ENTER_EXECUTOR);
3358
    return inst;
3359
}
3360
3361
static void
3362
copy_code(PyInterpreterState *interp, _Py_CODEUNIT *dst, PyCodeObject *co)
3363
{
3364
    int code_len = (int) Py_SIZE(co);
3365
    for (int i = 0; i < code_len; i += _PyInstruction_GetLength(co, i)) {
3366
        dst[i] = deopt_code_unit(co, i);
3367
    }
3368
    _PyCode_Quicken(dst, code_len, interp->opt_config.specialization_enabled, co->co_flags);
3369
}
3370
3371
static Py_ssize_t
3372
get_pow2_greater(Py_ssize_t initial, Py_ssize_t limit)
3373
{
3374
    // initial must be a power of two
3375
    assert(!(initial & (initial - 1)));
3376
    Py_ssize_t res = initial;
3377
    while (res && res < limit) {
3378
        res <<= 1;
3379
    }
3380
    return res;
3381
}
3382
3383
static _Py_CODEUNIT *
3384
create_tlbc_lock_held(PyInterpreterState *interp, PyCodeObject *co, Py_ssize_t idx)
3385
{
3386
    _PyCodeArray *tlbc = co->co_tlbc;
3387
    if (idx >= tlbc->size) {
3388
        Py_ssize_t new_size = get_pow2_greater(tlbc->size, idx + 1);
3389
        if (!new_size) {
3390
            PyErr_NoMemory();
3391
            return NULL;
3392
        }
3393
        _PyCodeArray *new_tlbc = _PyCodeArray_New(new_size);
3394
        if (new_tlbc == NULL) {
3395
            return NULL;
3396
        }
3397
        memcpy(new_tlbc->entries, tlbc->entries, tlbc->size * sizeof(void *));
3398
        _Py_atomic_store_ptr_release(&co->co_tlbc, new_tlbc);
3399
        _PyMem_FreeDelayed(tlbc, tlbc->size * sizeof(void *));
3400
        tlbc = new_tlbc;
3401
    }
3402
    char *bc = PyMem_Calloc(1, _PyCode_NBYTES(co));
3403
    if (bc == NULL) {
3404
        PyErr_NoMemory();
3405
        return NULL;
3406
    }
3407
    copy_code(interp, (_Py_CODEUNIT *) bc, co);
3408
    assert(tlbc->entries[idx] == NULL);
3409
    tlbc->entries[idx] = bc;
3410
    return (_Py_CODEUNIT *) bc;
3411
}
3412
3413
static _Py_CODEUNIT *
3414
get_tlbc_lock_held(PyCodeObject *co)
3415
{
3416
    _PyCodeArray *tlbc = co->co_tlbc;
3417
    _PyThreadStateImpl *tstate = (_PyThreadStateImpl *)PyThreadState_GET();
3418
    int32_t idx = tstate->tlbc_index;
3419
    if (idx < tlbc->size && tlbc->entries[idx] != NULL) {
3420
        return (_Py_CODEUNIT *)tlbc->entries[idx];
3421
    }
3422
    PyInterpreterState *interp = tstate->base.interp;
3423
    return create_tlbc_lock_held(interp, co, idx);
3424
}
3425
3426
_Py_CODEUNIT *
3427
_PyCode_GetTLBC(PyCodeObject *co)
3428
{
3429
    _Py_CODEUNIT *result;
3430
    Py_BEGIN_CRITICAL_SECTION(co);
3431
    result = get_tlbc_lock_held(co);
3432
    Py_END_CRITICAL_SECTION();
3433
    return result;
3434
}
3435
3436
// My kingdom for a bitset
3437
struct flag_set {
3438
    uint8_t *flags;
3439
    Py_ssize_t size;
3440
};
3441
3442
static inline int
3443
flag_is_set(struct flag_set *flags, Py_ssize_t idx)
3444
{
3445
    assert(idx >= 0);
3446
    return (idx < flags->size) && flags->flags[idx];
3447
}
3448
3449
// Set the flag for each tlbc index in use
3450
static int
3451
get_indices_in_use(PyInterpreterState *interp, struct flag_set *in_use)
3452
{
3453
    assert(interp->stoptheworld.world_stopped);
3454
    assert(in_use->flags == NULL);
3455
    int32_t max_index = 0;
3456
    _Py_FOR_EACH_TSTATE_BEGIN(interp, p) {
3457
        int32_t idx = ((_PyThreadStateImpl *) p)->tlbc_index;
3458
        if (idx > max_index) {
3459
            max_index = idx;
3460
        }
3461
    }
3462
    _Py_FOR_EACH_TSTATE_END(interp);
3463
    in_use->size = (size_t) max_index + 1;
3464
    in_use->flags = PyMem_Calloc(in_use->size, sizeof(*in_use->flags));
3465
    if (in_use->flags == NULL) {
3466
        return -1;
3467
    }
3468
    _Py_FOR_EACH_TSTATE_BEGIN(interp, p) {
3469
        in_use->flags[((_PyThreadStateImpl *) p)->tlbc_index] = 1;
3470
    }
3471
    _Py_FOR_EACH_TSTATE_END(interp);
3472
    return 0;
3473
}
3474
3475
struct get_code_args {
3476
    _PyObjectStack code_objs;
3477
    struct flag_set indices_in_use;
3478
    int err;
3479
};
3480
3481
static void
3482
clear_get_code_args(struct get_code_args *args)
3483
{
3484
    if (args->indices_in_use.flags != NULL) {
3485
        PyMem_Free(args->indices_in_use.flags);
3486
        args->indices_in_use.flags = NULL;
3487
    }
3488
    _PyObjectStack_Clear(&args->code_objs);
3489
}
3490
3491
static inline int
3492
is_bytecode_unused(_PyCodeArray *tlbc, Py_ssize_t idx,
3493
                   struct flag_set *indices_in_use)
3494
{
3495
    assert(idx > 0 && idx < tlbc->size);
3496
    return tlbc->entries[idx] != NULL && !flag_is_set(indices_in_use, idx);
3497
}
3498
3499
static int
3500
get_code_with_unused_tlbc(PyObject *obj, void *data)
3501
{
3502
    struct get_code_args *args = (struct get_code_args *) data;
3503
    if (!PyCode_Check(obj)) {
3504
        return 1;
3505
    }
3506
    PyCodeObject *co = (PyCodeObject *) obj;
3507
    _PyCodeArray *tlbc = co->co_tlbc;
3508
    // The first index always points at the main copy of the bytecode embedded
3509
    // in the code object.
3510
    for (Py_ssize_t i = 1; i < tlbc->size; i++) {
3511
        if (is_bytecode_unused(tlbc, i, &args->indices_in_use)) {
3512
            if (_PyObjectStack_Push(&args->code_objs, obj) < 0) {
3513
                args->err = -1;
3514
                return 0;
3515
            }
3516
            return 1;
3517
        }
3518
    }
3519
    return 1;
3520
}
3521
3522
static void
3523
free_unused_bytecode(PyCodeObject *co, struct flag_set *indices_in_use)
3524
{
3525
    _PyCodeArray *tlbc = co->co_tlbc;
3526
    // The first index always points at the main copy of the bytecode embedded
3527
    // in the code object.
3528
    for (Py_ssize_t i = 1; i < tlbc->size; i++) {
3529
        if (is_bytecode_unused(tlbc, i, indices_in_use)) {
3530
            PyMem_Free(tlbc->entries[i]);
3531
            tlbc->entries[i] = NULL;
3532
        }
3533
    }
3534
}
3535
3536
int
3537
_Py_ClearUnusedTLBC(PyInterpreterState *interp)
3538
{
3539
    struct get_code_args args = {
3540
        .code_objs = {NULL},
3541
        .indices_in_use = {NULL, 0},
3542
        .err = 0,
3543
    };
3544
    _PyEval_StopTheWorld(interp);
3545
    // Collect in-use tlbc indices
3546
    if (get_indices_in_use(interp, &args.indices_in_use) < 0) {
3547
        goto err;
3548
    }
3549
    // Collect code objects that have bytecode not in use by any thread
3550
    _PyGC_VisitObjectsWorldStopped(
3551
        interp, get_code_with_unused_tlbc, &args);
3552
    if (args.err < 0) {
3553
        goto err;
3554
    }
3555
    // Free unused bytecode. This must happen outside of gc_visit_heaps; it is
3556
    // unsafe to allocate or free any mimalloc managed memory when it's
3557
    // running.
3558
    PyObject *obj;
3559
    while ((obj = _PyObjectStack_Pop(&args.code_objs)) != NULL) {
3560
        free_unused_bytecode((PyCodeObject*) obj, &args.indices_in_use);
3561
    }
3562
    _PyEval_StartTheWorld(interp);
3563
    clear_get_code_args(&args);
3564
    return 0;
3565
3566
err:
3567
    _PyEval_StartTheWorld(interp);
3568
    clear_get_code_args(&args);
3569
    PyErr_NoMemory();
3570
    return -1;
3571
}
3572
3573
#endif