Coverage Report

Created: 2025-11-24 06:11

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