Coverage Report

Created: 2026-02-26 06:53

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