Coverage Report

Created: 2026-01-09 06:26

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Objects/frameobject.c
Line
Count
Source
1
/* Frame object implementation */
2
3
#include "Python.h"
4
#include "pycore_cell.h"          // PyCell_GetRef()
5
#include "pycore_ceval.h"         // _PyEval_SetOpcodeTrace()
6
#include "pycore_code.h"          // CO_FAST_LOCAL
7
#include "pycore_dict.h"          // _PyDict_LoadBuiltinsFromGlobals()
8
#include "pycore_frame.h"         // PyFrameObject
9
#include "pycore_function.h"      // _PyFunction_FromConstructor()
10
#include "pycore_genobject.h"     // _PyGen_GetGeneratorFromFrame()
11
#include "pycore_interpframe.h"   // _PyFrame_GetLocalsArray()
12
#include "pycore_modsupport.h"    // _PyArg_CheckPositional()
13
#include "pycore_object.h"        // _PyObject_GC_UNTRACK()
14
#include "pycore_opcode_metadata.h" // _PyOpcode_Caches
15
#include "pycore_optimizer.h"     // _Py_Executors_InvalidateDependency()
16
#include "pycore_unicodeobject.h" // _PyUnicode_Equal()
17
18
#include "frameobject.h"          // PyFrameLocalsProxyObject
19
#include "opcode.h"               // EXTENDED_ARG
20
21
#include "clinic/frameobject.c.h"
22
23
24
#define PyFrameObject_CAST(op)  \
25
55.0M
    (assert(PyObject_TypeCheck((op), &PyFrame_Type)), (PyFrameObject *)(op))
26
27
#define PyFrameLocalsProxyObject_CAST(op)                           \
28
28
    (                                                               \
29
28
        assert(PyObject_TypeCheck((op), &PyFrameLocalsProxy_Type)), \
30
28
        (PyFrameLocalsProxyObject *)(op)                            \
31
28
    )
32
33
#define OFF(x) offsetof(PyFrameObject, x)
34
35
/*[clinic input]
36
class frame "PyFrameObject *" "&PyFrame_Type"
37
[clinic start generated code]*/
38
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=2d1dbf2e06cf351f]*/
39
40
41
// Returns new reference or NULL
42
static PyObject *
43
framelocalsproxy_getval(_PyInterpreterFrame *frame, PyCodeObject *co, int i)
44
40
{
45
40
    _PyStackRef *fast = _PyFrame_GetLocalsArray(frame);
46
40
    _PyLocals_Kind kind = _PyLocals_GetKind(co->co_localspluskinds, i);
47
48
40
    PyObject *value = PyStackRef_AsPyObjectBorrow(fast[i]);
49
40
    PyObject *cell = NULL;
50
51
40
    if (value == NULL) {
52
40
        return NULL;
53
40
    }
54
55
0
    if (kind == CO_FAST_FREE || kind & CO_FAST_CELL) {
56
        // The cell was set when the frame was created from
57
        // the function's closure.
58
        // GH-128396: With PEP 709, it's possible to have a fast variable in
59
        // an inlined comprehension that has the same name as the cell variable
60
        // in the frame, where the `kind` obtained from frame can not guarantee
61
        // that the variable is a cell.
62
        // If the variable is not a cell, we are okay with it and we can simply
63
        // return the value.
64
0
        if (PyCell_Check(value)) {
65
0
            cell = value;
66
0
        }
67
0
    }
68
69
0
    if (cell != NULL) {
70
0
        value = PyCell_GetRef((PyCellObject *)cell);
71
0
    }
72
0
    else {
73
0
        Py_XINCREF(value);
74
0
    }
75
76
0
    if (value == NULL) {
77
0
        return NULL;
78
0
    }
79
80
0
    return value;
81
0
}
82
83
static bool
84
framelocalsproxy_hasval(_PyInterpreterFrame *frame, PyCodeObject *co, int i)
85
40
{
86
40
    PyObject *value = framelocalsproxy_getval(frame, co, i);
87
40
    if (value == NULL) {
88
40
        return false;
89
40
    }
90
0
    Py_DECREF(value);
91
0
    return true;
92
40
}
93
94
static int
95
framelocalsproxy_getkeyindex(PyFrameObject *frame, PyObject *key, bool read, PyObject **value_ptr)
96
0
{
97
    /*
98
     * Returns -2 (!) if an error occurred; exception will be set.
99
     * Returns the fast locals index of the key on success:
100
     *   - if read == true, returns the index if the value is not NULL
101
     *   - if read == false, returns the index if the value is not hidden
102
     * Otherwise returns -1.
103
     *
104
     * If read == true and value_ptr is not NULL, *value_ptr is set to
105
     * the value of the key if it is found (with a new reference).
106
     */
107
108
    // value_ptr should only be given if we are reading the value
109
0
    assert(read || value_ptr == NULL);
110
111
0
    PyCodeObject *co = _PyFrame_GetCode(frame->f_frame);
112
113
    // Ensure that the key is hashable.
114
0
    Py_hash_t key_hash = PyObject_Hash(key);
115
0
    if (key_hash == -1) {
116
0
        return -2;
117
0
    }
118
119
0
    bool found = false;
120
121
    // We do 2 loops here because it's highly possible the key is interned
122
    // and we can do a pointer comparison.
123
0
    for (int i = 0; i < co->co_nlocalsplus; i++) {
124
0
        PyObject *name = PyTuple_GET_ITEM(co->co_localsplusnames, i);
125
0
        if (name == key) {
126
0
            if (read) {
127
0
                PyObject *value = framelocalsproxy_getval(frame->f_frame, co, i);
128
0
                if (value != NULL) {
129
0
                    if (value_ptr != NULL) {
130
0
                        *value_ptr = value;
131
0
                    }
132
0
                    else {
133
0
                        Py_DECREF(value);
134
0
                    }
135
0
                    return i;
136
0
                }
137
0
            } else {
138
0
                if (!(_PyLocals_GetKind(co->co_localspluskinds, i) & CO_FAST_HIDDEN)) {
139
0
                    return i;
140
0
                }
141
0
            }
142
0
            found = true;
143
0
        }
144
0
    }
145
0
    if (found) {
146
        // This is an attempt to read an unset local variable or
147
        // write to a variable that is hidden from regular write operations
148
0
        return -1;
149
0
    }
150
    // This is unlikely, but we need to make sure. This means the key
151
    // is not interned.
152
0
    for (int i = 0; i < co->co_nlocalsplus; i++) {
153
0
        PyObject *name = PyTuple_GET_ITEM(co->co_localsplusnames, i);
154
0
        Py_hash_t name_hash = PyObject_Hash(name);
155
0
        assert(name_hash != -1);  // keys are exact unicode
156
0
        if (name_hash != key_hash) {
157
0
            continue;
158
0
        }
159
0
        int same = PyObject_RichCompareBool(name, key, Py_EQ);
160
0
        if (same < 0) {
161
0
            return -2;
162
0
        }
163
0
        if (same) {
164
0
            if (read) {
165
0
                PyObject *value = framelocalsproxy_getval(frame->f_frame, co, i);
166
0
                if (value != NULL) {
167
0
                    if (value_ptr != NULL) {
168
0
                        *value_ptr = value;
169
0
                    }
170
0
                    else {
171
0
                        Py_DECREF(value);
172
0
                    }
173
0
                    return i;
174
0
                }
175
0
            } else {
176
0
                if (!(_PyLocals_GetKind(co->co_localspluskinds, i) & CO_FAST_HIDDEN)) {
177
0
                    return i;
178
0
                }
179
0
            }
180
0
        }
181
0
    }
182
183
0
    return -1;
184
0
}
185
186
static PyObject *
187
framelocalsproxy_getitem(PyObject *self, PyObject *key)
188
0
{
189
0
    PyFrameObject *frame = PyFrameLocalsProxyObject_CAST(self)->frame;
190
0
    PyObject *value = NULL;
191
192
0
    int i = framelocalsproxy_getkeyindex(frame, key, true, &value);
193
0
    if (i == -2) {
194
0
        return NULL;
195
0
    }
196
0
    if (i >= 0) {
197
0
        assert(value != NULL);
198
0
        return value;
199
0
    }
200
0
    assert(value == NULL);
201
202
    // Okay not in the fast locals, try extra locals
203
204
0
    PyObject *extra = frame->f_extra_locals;
205
0
    if (extra != NULL) {
206
0
        if (PyDict_GetItemRef(extra, key, &value) < 0) {
207
0
            return NULL;
208
0
        }
209
0
        if (value != NULL) {
210
0
            return value;
211
0
        }
212
0
    }
213
214
0
    PyErr_Format(PyExc_KeyError, "local variable '%R' is not defined", key);
215
0
    return NULL;
216
0
}
217
218
static int
219
add_overwritten_fast_local(PyFrameObject *frame, PyObject *obj)
220
0
{
221
0
    Py_ssize_t new_size;
222
0
    if (frame->f_overwritten_fast_locals == NULL) {
223
0
        new_size = 1;
224
0
    }
225
0
    else {
226
0
        Py_ssize_t size = PyTuple_Size(frame->f_overwritten_fast_locals);
227
0
        if (size == -1) {
228
0
            return -1;
229
0
        }
230
0
        new_size = size + 1;
231
0
    }
232
0
    PyObject *new_tuple = PyTuple_New(new_size);
233
0
    if (new_tuple == NULL) {
234
0
        return -1;
235
0
    }
236
0
    for (Py_ssize_t i = 0; i < new_size - 1; i++) {
237
0
        PyObject *o = PyTuple_GET_ITEM(frame->f_overwritten_fast_locals, i);
238
0
        PyTuple_SET_ITEM(new_tuple, i, Py_NewRef(o));
239
0
    }
240
0
    PyTuple_SET_ITEM(new_tuple, new_size - 1, Py_NewRef(obj));
241
0
    Py_XSETREF(frame->f_overwritten_fast_locals, new_tuple);
242
0
    return 0;
243
0
}
244
245
static int
246
framelocalsproxy_setitem(PyObject *self, PyObject *key, PyObject *value)
247
0
{
248
    /* Merge locals into fast locals */
249
0
    PyFrameObject *frame = PyFrameLocalsProxyObject_CAST(self)->frame;
250
0
    _PyStackRef *fast = _PyFrame_GetLocalsArray(frame->f_frame);
251
0
    PyCodeObject *co = _PyFrame_GetCode(frame->f_frame);
252
253
0
    int i = framelocalsproxy_getkeyindex(frame, key, false, NULL);
254
0
    if (i == -2) {
255
0
        return -1;
256
0
    }
257
0
    if (i >= 0) {
258
0
        if (value == NULL) {
259
0
            PyErr_SetString(PyExc_ValueError, "cannot remove local variables from FrameLocalsProxy");
260
0
            return -1;
261
0
        }
262
263
#if _Py_TIER2
264
        _Py_Executors_InvalidateDependency(_PyInterpreterState_GET(), co, 1);
265
        _PyJit_Tracer_InvalidateDependency(_PyThreadState_GET(), co);
266
#endif
267
268
0
        _PyLocals_Kind kind = _PyLocals_GetKind(co->co_localspluskinds, i);
269
0
        _PyStackRef oldvalue = fast[i];
270
0
        PyObject *cell = NULL;
271
0
        if (kind == CO_FAST_FREE) {
272
            // The cell was set when the frame was created from
273
            // the function's closure.
274
0
            assert(!PyStackRef_IsNull(oldvalue) && PyCell_Check(PyStackRef_AsPyObjectBorrow(oldvalue)));
275
0
            cell = PyStackRef_AsPyObjectBorrow(oldvalue);
276
0
        } else if (kind & CO_FAST_CELL && !PyStackRef_IsNull(oldvalue)) {
277
0
            PyObject *as_obj = PyStackRef_AsPyObjectBorrow(oldvalue);
278
0
            if (PyCell_Check(as_obj)) {
279
0
                cell = as_obj;
280
0
            }
281
0
        }
282
0
        if (cell != NULL) {
283
0
            Py_XINCREF(value);
284
0
            PyCell_SetTakeRef((PyCellObject *)cell, value);
285
0
        } else if (value != PyStackRef_AsPyObjectBorrow(oldvalue)) {
286
0
            PyObject *old_obj = PyStackRef_AsPyObjectBorrow(fast[i]);
287
0
            if (old_obj != NULL && !_Py_IsImmortal(old_obj)) {
288
0
                if (add_overwritten_fast_local(frame, old_obj) < 0) {
289
0
                    return -1;
290
0
                }
291
0
                PyStackRef_CLOSE(fast[i]);
292
0
            }
293
0
            fast[i] = PyStackRef_FromPyObjectNew(value);
294
0
        }
295
0
        return 0;
296
0
    }
297
298
    // Okay not in the fast locals, try extra locals
299
300
0
    PyObject *extra = frame->f_extra_locals;
301
302
0
    if (extra == NULL) {
303
0
        if (value == NULL) {
304
0
            _PyErr_SetKeyError(key);
305
0
            return -1;
306
0
        }
307
0
        extra = PyDict_New();
308
0
        if (extra == NULL) {
309
0
            return -1;
310
0
        }
311
0
        frame->f_extra_locals = extra;
312
0
    }
313
314
0
    assert(PyDict_Check(extra));
315
316
0
    if (value == NULL) {
317
0
        return PyDict_DelItem(extra, key);
318
0
    } else {
319
0
        return PyDict_SetItem(extra, key, value);
320
0
    }
321
0
}
322
323
static int
324
framelocalsproxy_merge(PyObject* self, PyObject* other)
325
0
{
326
0
    if (!PyDict_Check(other) && !PyFrameLocalsProxy_Check(other)) {
327
0
        return -1;
328
0
    }
329
330
0
    PyObject *keys = PyMapping_Keys(other);
331
0
    if (keys == NULL) {
332
0
        return -1;
333
0
    }
334
335
0
    PyObject *iter = PyObject_GetIter(keys);
336
0
    Py_DECREF(keys);
337
0
    if (iter == NULL) {
338
0
        return -1;
339
0
    }
340
341
0
    PyObject *key = NULL;
342
0
    PyObject *value = NULL;
343
344
0
    while ((key = PyIter_Next(iter)) != NULL) {
345
0
        value = PyObject_GetItem(other, key);
346
0
        if (value == NULL) {
347
0
            Py_DECREF(key);
348
0
            Py_DECREF(iter);
349
0
            return -1;
350
0
        }
351
352
0
        if (framelocalsproxy_setitem(self, key, value) < 0) {
353
0
            Py_DECREF(key);
354
0
            Py_DECREF(value);
355
0
            Py_DECREF(iter);
356
0
            return -1;
357
0
        }
358
359
0
        Py_DECREF(key);
360
0
        Py_DECREF(value);
361
0
    }
362
363
0
    Py_DECREF(iter);
364
365
0
    if (PyErr_Occurred()) {
366
0
        return -1;
367
0
    }
368
369
0
    return 0;
370
0
}
371
372
static PyObject *
373
framelocalsproxy_keys(PyObject *self, PyObject *Py_UNUSED(ignored))
374
0
{
375
0
    PyFrameObject *frame = PyFrameLocalsProxyObject_CAST(self)->frame;
376
0
    PyCodeObject *co = _PyFrame_GetCode(frame->f_frame);
377
0
    PyObject *names = PyList_New(0);
378
0
    if (names == NULL) {
379
0
        return NULL;
380
0
    }
381
382
0
    for (int i = 0; i < co->co_nlocalsplus; i++) {
383
0
        if (framelocalsproxy_hasval(frame->f_frame, co, i)) {
384
0
            PyObject *name = PyTuple_GET_ITEM(co->co_localsplusnames, i);
385
0
            if (PyList_Append(names, name) < 0) {
386
0
                Py_DECREF(names);
387
0
                return NULL;
388
0
            }
389
0
        }
390
0
    }
391
392
    // Iterate through the extra locals
393
0
    if (frame->f_extra_locals) {
394
0
        assert(PyDict_Check(frame->f_extra_locals));
395
396
0
        Py_ssize_t i = 0;
397
0
        PyObject *key = NULL;
398
0
        PyObject *value = NULL;
399
400
0
        while (PyDict_Next(frame->f_extra_locals, &i, &key, &value)) {
401
0
            if (PyList_Append(names, key) < 0) {
402
0
                Py_DECREF(names);
403
0
                return NULL;
404
0
            }
405
0
        }
406
0
    }
407
408
0
    return names;
409
0
}
410
411
static void
412
framelocalsproxy_dealloc(PyObject *self)
413
28
{
414
28
    PyFrameLocalsProxyObject *proxy = PyFrameLocalsProxyObject_CAST(self);
415
28
    PyObject_GC_UnTrack(self);
416
28
    Py_CLEAR(proxy->frame);
417
28
    Py_TYPE(self)->tp_free(self);
418
28
}
419
420
static PyObject *
421
framelocalsproxy_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
422
28
{
423
28
    if (PyTuple_GET_SIZE(args) != 1) {
424
0
        PyErr_Format(PyExc_TypeError,
425
0
                     "FrameLocalsProxy expected 1 argument, got %zd",
426
0
                     PyTuple_GET_SIZE(args));
427
0
        return NULL;
428
0
    }
429
28
    PyObject *item = PyTuple_GET_ITEM(args, 0);
430
431
28
    if (!PyFrame_Check(item)) {
432
0
        PyErr_Format(PyExc_TypeError, "expect frame, not %T", item);
433
0
        return NULL;
434
0
    }
435
28
    PyFrameObject *frame = (PyFrameObject*)item;
436
437
28
    if (kwds != NULL && PyDict_Size(kwds) != 0) {
438
0
        PyErr_SetString(PyExc_TypeError,
439
0
                        "FrameLocalsProxy takes no keyword arguments");
440
0
        return 0;
441
0
    }
442
443
28
    PyFrameLocalsProxyObject *self = (PyFrameLocalsProxyObject *)type->tp_alloc(type, 0);
444
28
    if (self == NULL) {
445
0
        return NULL;
446
0
    }
447
448
28
    ((PyFrameLocalsProxyObject*)self)->frame = (PyFrameObject*)Py_NewRef(frame);
449
450
28
    return (PyObject *)self;
451
28
}
452
453
static int
454
framelocalsproxy_tp_clear(PyObject *self)
455
0
{
456
0
    PyFrameLocalsProxyObject *proxy = PyFrameLocalsProxyObject_CAST(self);
457
0
    Py_CLEAR(proxy->frame);
458
0
    return 0;
459
0
}
460
461
static int
462
framelocalsproxy_visit(PyObject *self, visitproc visit, void *arg)
463
0
{
464
0
    PyFrameLocalsProxyObject *proxy = PyFrameLocalsProxyObject_CAST(self);
465
0
    Py_VISIT(proxy->frame);
466
0
    return 0;
467
0
}
468
469
static PyObject *
470
framelocalsproxy_iter(PyObject *self)
471
0
{
472
0
    PyObject* keys = framelocalsproxy_keys(self, NULL);
473
0
    if (keys == NULL) {
474
0
        return NULL;
475
0
    }
476
477
0
    PyObject* iter = PyObject_GetIter(keys);
478
0
    Py_XDECREF(keys);
479
480
0
    return iter;
481
0
}
482
483
static PyObject *
484
framelocalsproxy_richcompare(PyObject *lhs, PyObject *rhs, int op)
485
0
{
486
0
    PyFrameLocalsProxyObject *self = PyFrameLocalsProxyObject_CAST(lhs);
487
0
    if (PyFrameLocalsProxy_Check(rhs)) {
488
0
        PyFrameLocalsProxyObject *other = (PyFrameLocalsProxyObject *)rhs;
489
0
        bool result = self->frame == other->frame;
490
0
        if (op == Py_EQ) {
491
0
            return PyBool_FromLong(result);
492
0
        } else if (op == Py_NE) {
493
0
            return PyBool_FromLong(!result);
494
0
        }
495
0
    } else if (PyDict_Check(rhs)) {
496
0
        PyObject *dct = PyDict_New();
497
0
        if (dct == NULL) {
498
0
            return NULL;
499
0
        }
500
501
0
        if (PyDict_Update(dct, lhs) < 0) {
502
0
            Py_DECREF(dct);
503
0
            return NULL;
504
0
        }
505
506
0
        PyObject *result = PyObject_RichCompare(dct, rhs, op);
507
0
        Py_DECREF(dct);
508
0
        return result;
509
0
    }
510
511
0
    Py_RETURN_NOTIMPLEMENTED;
512
0
}
513
514
static PyObject *
515
framelocalsproxy_repr(PyObject *self)
516
0
{
517
0
    int i = Py_ReprEnter(self);
518
0
    if (i != 0) {
519
0
        return i > 0 ? PyUnicode_FromString("{...}") : NULL;
520
0
    }
521
522
0
    PyObject *dct = PyDict_New();
523
0
    if (dct == NULL) {
524
0
        Py_ReprLeave(self);
525
0
        return NULL;
526
0
    }
527
528
0
    if (PyDict_Update(dct, self) < 0) {
529
0
        Py_DECREF(dct);
530
0
        Py_ReprLeave(self);
531
0
        return NULL;
532
0
    }
533
534
0
    PyObject *repr = PyObject_Repr(dct);
535
0
    Py_DECREF(dct);
536
537
0
    Py_ReprLeave(self);
538
539
0
    return repr;
540
0
}
541
542
static PyObject*
543
framelocalsproxy_or(PyObject *self, PyObject *other)
544
0
{
545
0
    if (!PyDict_Check(other) && !PyFrameLocalsProxy_Check(other)) {
546
0
        Py_RETURN_NOTIMPLEMENTED;
547
0
    }
548
549
0
    PyObject *result = PyDict_New();
550
0
    if (result == NULL) {
551
0
        return NULL;
552
0
    }
553
554
0
    if (PyDict_Update(result, self) < 0) {
555
0
        Py_DECREF(result);
556
0
        return NULL;
557
0
    }
558
559
0
    if (PyDict_Update(result, other) < 0) {
560
0
        Py_DECREF(result);
561
0
        return NULL;
562
0
    }
563
564
0
    return result;
565
0
}
566
567
static PyObject*
568
framelocalsproxy_inplace_or(PyObject *self, PyObject *other)
569
0
{
570
0
    if (!PyDict_Check(other) && !PyFrameLocalsProxy_Check(other)) {
571
0
        Py_RETURN_NOTIMPLEMENTED;
572
0
    }
573
574
0
    if (framelocalsproxy_merge(self, other) < 0) {
575
0
        Py_RETURN_NOTIMPLEMENTED;
576
0
    }
577
578
0
    return Py_NewRef(self);
579
0
}
580
581
static PyObject *
582
framelocalsproxy_values(PyObject *self, PyObject *Py_UNUSED(ignored))
583
0
{
584
0
    PyFrameObject *frame = PyFrameLocalsProxyObject_CAST(self)->frame;
585
0
    PyCodeObject *co = _PyFrame_GetCode(frame->f_frame);
586
0
    PyObject *values = PyList_New(0);
587
0
    if (values == NULL) {
588
0
        return NULL;
589
0
    }
590
591
0
    for (int i = 0; i < co->co_nlocalsplus; i++) {
592
0
        PyObject *value = framelocalsproxy_getval(frame->f_frame, co, i);
593
0
        if (value) {
594
0
            if (PyList_Append(values, value) < 0) {
595
0
                Py_DECREF(values);
596
0
                Py_DECREF(value);
597
0
                return NULL;
598
0
            }
599
0
            Py_DECREF(value);
600
0
        }
601
0
    }
602
603
    // Iterate through the extra locals
604
0
    if (frame->f_extra_locals) {
605
0
        Py_ssize_t j = 0;
606
0
        PyObject *key = NULL;
607
0
        PyObject *value = NULL;
608
0
        while (PyDict_Next(frame->f_extra_locals, &j, &key, &value)) {
609
0
            if (PyList_Append(values, value) < 0) {
610
0
                Py_DECREF(values);
611
0
                return NULL;
612
0
            }
613
0
        }
614
0
    }
615
616
0
    return values;
617
0
}
618
619
static PyObject *
620
framelocalsproxy_items(PyObject *self, PyObject *Py_UNUSED(ignored))
621
0
{
622
0
    PyFrameObject *frame = PyFrameLocalsProxyObject_CAST(self)->frame;
623
0
    PyCodeObject *co = _PyFrame_GetCode(frame->f_frame);
624
0
    PyObject *items = PyList_New(0);
625
0
    if (items == NULL) {
626
0
        return NULL;
627
0
    }
628
629
0
    for (int i = 0; i < co->co_nlocalsplus; i++) {
630
0
        PyObject *name = PyTuple_GET_ITEM(co->co_localsplusnames, i);
631
0
        PyObject *value = framelocalsproxy_getval(frame->f_frame, co, i);
632
633
0
        if (value) {
634
0
            PyObject *pair = PyTuple_Pack(2, name, value);
635
0
            if (pair == NULL) {
636
0
                Py_DECREF(items);
637
0
                Py_DECREF(value);
638
0
                return NULL;
639
0
            }
640
641
0
            if (PyList_Append(items, pair) < 0) {
642
0
                Py_DECREF(items);
643
0
                Py_DECREF(pair);
644
0
                Py_DECREF(value);
645
0
                return NULL;
646
0
            }
647
648
0
            Py_DECREF(pair);
649
0
            Py_DECREF(value);
650
0
        }
651
0
    }
652
653
    // Iterate through the extra locals
654
0
    if (frame->f_extra_locals) {
655
0
        Py_ssize_t j = 0;
656
0
        PyObject *key = NULL;
657
0
        PyObject *value = NULL;
658
0
        while (PyDict_Next(frame->f_extra_locals, &j, &key, &value)) {
659
0
            PyObject *pair = PyTuple_Pack(2, key, value);
660
0
            if (pair == NULL) {
661
0
                Py_DECREF(items);
662
0
                return NULL;
663
0
            }
664
665
0
            if (PyList_Append(items, pair) < 0) {
666
0
                Py_DECREF(items);
667
0
                Py_DECREF(pair);
668
0
                return NULL;
669
0
            }
670
671
0
            Py_DECREF(pair);
672
0
        }
673
0
    }
674
675
0
    return items;
676
0
}
677
678
static Py_ssize_t
679
framelocalsproxy_length(PyObject *self)
680
0
{
681
0
    PyFrameObject *frame = PyFrameLocalsProxyObject_CAST(self)->frame;
682
0
    PyCodeObject *co = _PyFrame_GetCode(frame->f_frame);
683
0
    Py_ssize_t size = 0;
684
685
0
    if (frame->f_extra_locals != NULL) {
686
0
        assert(PyDict_Check(frame->f_extra_locals));
687
0
        size += PyDict_Size(frame->f_extra_locals);
688
0
    }
689
690
0
    for (int i = 0; i < co->co_nlocalsplus; i++) {
691
0
        if (framelocalsproxy_hasval(frame->f_frame, co, i)) {
692
0
            size++;
693
0
        }
694
0
    }
695
0
    return size;
696
0
}
697
698
static int
699
framelocalsproxy_contains(PyObject *self, PyObject *key)
700
0
{
701
0
    PyFrameObject *frame = PyFrameLocalsProxyObject_CAST(self)->frame;
702
703
0
    int i = framelocalsproxy_getkeyindex(frame, key, true, NULL);
704
0
    if (i == -2) {
705
0
        return -1;
706
0
    }
707
0
    if (i >= 0) {
708
0
        return 1;
709
0
    }
710
711
0
    PyObject *extra = frame->f_extra_locals;
712
0
    if (extra != NULL) {
713
0
        return PyDict_Contains(extra, key);
714
0
    }
715
716
0
    return 0;
717
0
}
718
719
static PyObject* framelocalsproxy___contains__(PyObject *self, PyObject *key)
720
0
{
721
0
    int result = framelocalsproxy_contains(self, key);
722
0
    if (result < 0) {
723
0
        return NULL;
724
0
    }
725
0
    return PyBool_FromLong(result);
726
0
}
727
728
static PyObject*
729
framelocalsproxy_update(PyObject *self, PyObject *other)
730
0
{
731
0
    if (framelocalsproxy_merge(self, other) < 0) {
732
0
        PyErr_SetString(PyExc_TypeError, "update() argument must be dict or another FrameLocalsProxy");
733
0
        return NULL;
734
0
    }
735
736
0
    Py_RETURN_NONE;
737
0
}
738
739
static PyObject*
740
framelocalsproxy_get(PyObject* self, PyObject *const *args, Py_ssize_t nargs)
741
0
{
742
0
    if (nargs < 1 || nargs > 2) {
743
0
        PyErr_SetString(PyExc_TypeError, "get expected 1 or 2 arguments");
744
0
        return NULL;
745
0
    }
746
747
0
    PyObject *key = args[0];
748
0
    PyObject *default_value = Py_None;
749
750
0
    if (nargs == 2) {
751
0
        default_value = args[1];
752
0
    }
753
754
0
    PyObject *result = framelocalsproxy_getitem(self, key);
755
756
0
    if (result == NULL) {
757
0
        if (PyErr_ExceptionMatches(PyExc_KeyError)) {
758
0
            PyErr_Clear();
759
0
            return Py_XNewRef(default_value);
760
0
        }
761
0
        return NULL;
762
0
    }
763
764
0
    return result;
765
0
}
766
767
static PyObject*
768
framelocalsproxy_setdefault(PyObject* self, PyObject *const *args, Py_ssize_t nargs)
769
0
{
770
0
    if (nargs < 1 || nargs > 2) {
771
0
        PyErr_SetString(PyExc_TypeError, "setdefault expected 1 or 2 arguments");
772
0
        return NULL;
773
0
    }
774
775
0
    PyObject *key = args[0];
776
0
    PyObject *default_value = Py_None;
777
778
0
    if (nargs == 2) {
779
0
        default_value = args[1];
780
0
    }
781
782
0
    PyObject *result = framelocalsproxy_getitem(self, key);
783
784
0
    if (result == NULL) {
785
0
        if (PyErr_ExceptionMatches(PyExc_KeyError)) {
786
0
            PyErr_Clear();
787
0
            if (framelocalsproxy_setitem(self, key, default_value) < 0) {
788
0
                return NULL;
789
0
            }
790
0
            return Py_XNewRef(default_value);
791
0
        }
792
0
        return NULL;
793
0
    }
794
795
0
    return result;
796
0
}
797
798
static PyObject*
799
framelocalsproxy_pop(PyObject* self, PyObject *const *args, Py_ssize_t nargs)
800
0
{
801
0
    if (!_PyArg_CheckPositional("pop", nargs, 1, 2)) {
802
0
        return NULL;
803
0
    }
804
805
0
    PyObject *key = args[0];
806
0
    PyObject *default_value = NULL;
807
808
0
    if (nargs == 2) {
809
0
        default_value = args[1];
810
0
    }
811
812
0
    PyFrameObject *frame = PyFrameLocalsProxyObject_CAST(self)->frame;
813
814
0
    int i = framelocalsproxy_getkeyindex(frame, key, false, NULL);
815
0
    if (i == -2) {
816
0
        return NULL;
817
0
    }
818
819
0
    if (i >= 0) {
820
0
        PyErr_SetString(PyExc_ValueError, "cannot remove local variables from FrameLocalsProxy");
821
0
        return NULL;
822
0
    }
823
824
0
    PyObject *result = NULL;
825
826
0
    if (frame->f_extra_locals == NULL) {
827
0
        if (default_value != NULL) {
828
0
            return Py_XNewRef(default_value);
829
0
        } else {
830
0
            _PyErr_SetKeyError(key);
831
0
            return NULL;
832
0
        }
833
0
    }
834
835
0
    if (PyDict_Pop(frame->f_extra_locals, key, &result) < 0) {
836
0
        return NULL;
837
0
    }
838
839
0
    if (result == NULL) {
840
0
        if (default_value != NULL) {
841
0
            return Py_XNewRef(default_value);
842
0
        } else {
843
0
            _PyErr_SetKeyError(key);
844
0
            return NULL;
845
0
        }
846
0
    }
847
848
0
    return result;
849
0
}
850
851
static PyObject*
852
framelocalsproxy_copy(PyObject *self, PyObject *Py_UNUSED(ignored))
853
0
{
854
0
    PyObject* result = PyDict_New();
855
856
0
    if (result == NULL) {
857
0
        return NULL;
858
0
    }
859
860
0
    if (PyDict_Update(result, self) < 0) {
861
0
        Py_DECREF(result);
862
0
        return NULL;
863
0
    }
864
865
0
    return result;
866
0
}
867
868
static PyObject*
869
framelocalsproxy_reversed(PyObject *self, PyObject *Py_UNUSED(ignored))
870
0
{
871
0
    PyObject *result = framelocalsproxy_keys(self, NULL);
872
873
0
    if (result == NULL) {
874
0
        return NULL;
875
0
    }
876
877
0
    if (PyList_Reverse(result) < 0) {
878
0
        Py_DECREF(result);
879
0
        return NULL;
880
0
    }
881
0
    return result;
882
0
}
883
884
static PyNumberMethods framelocalsproxy_as_number = {
885
    .nb_or = framelocalsproxy_or,
886
    .nb_inplace_or = framelocalsproxy_inplace_or,
887
};
888
889
static PySequenceMethods framelocalsproxy_as_sequence = {
890
    .sq_contains = framelocalsproxy_contains,
891
};
892
893
static PyMappingMethods framelocalsproxy_as_mapping = {
894
    .mp_length = framelocalsproxy_length,
895
    .mp_subscript = framelocalsproxy_getitem,
896
    .mp_ass_subscript = framelocalsproxy_setitem,
897
};
898
899
static PyMethodDef framelocalsproxy_methods[] = {
900
    {"__contains__", framelocalsproxy___contains__, METH_O | METH_COEXIST, NULL},
901
    {"__getitem__", framelocalsproxy_getitem, METH_O | METH_COEXIST, NULL},
902
    {"update", framelocalsproxy_update, METH_O, NULL},
903
    {"__reversed__", framelocalsproxy_reversed, METH_NOARGS, NULL},
904
    {"copy", framelocalsproxy_copy, METH_NOARGS, NULL},
905
    {"keys", framelocalsproxy_keys, METH_NOARGS, NULL},
906
    {"values", framelocalsproxy_values, METH_NOARGS, NULL},
907
    {"items", _PyCFunction_CAST(framelocalsproxy_items), METH_NOARGS, NULL},
908
    {"get", _PyCFunction_CAST(framelocalsproxy_get), METH_FASTCALL, NULL},
909
    {"pop", _PyCFunction_CAST(framelocalsproxy_pop), METH_FASTCALL, NULL},
910
    {
911
        "setdefault",
912
        _PyCFunction_CAST(framelocalsproxy_setdefault),
913
        METH_FASTCALL,
914
        NULL
915
    },
916
    {NULL, NULL}   /* sentinel */
917
};
918
919
PyDoc_STRVAR(framelocalsproxy_doc,
920
"FrameLocalsProxy($frame)\n"
921
"--\n"
922
"\n"
923
"Create a write-through view of the locals dictionary for a frame.\n"
924
"\n"
925
"  frame\n"
926
"    the frame object to wrap.");
927
928
PyTypeObject PyFrameLocalsProxy_Type = {
929
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
930
    .tp_name = "FrameLocalsProxy",
931
    .tp_basicsize = sizeof(PyFrameLocalsProxyObject),
932
    .tp_dealloc = framelocalsproxy_dealloc,
933
    .tp_repr = &framelocalsproxy_repr,
934
    .tp_as_number = &framelocalsproxy_as_number,
935
    .tp_as_sequence = &framelocalsproxy_as_sequence,
936
    .tp_as_mapping = &framelocalsproxy_as_mapping,
937
    .tp_getattro = PyObject_GenericGetAttr,
938
    .tp_setattro = PyObject_GenericSetAttr,
939
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_MAPPING,
940
    .tp_traverse = framelocalsproxy_visit,
941
    .tp_clear = framelocalsproxy_tp_clear,
942
    .tp_richcompare = framelocalsproxy_richcompare,
943
    .tp_iter = framelocalsproxy_iter,
944
    .tp_methods = framelocalsproxy_methods,
945
    .tp_alloc = PyType_GenericAlloc,
946
    .tp_new = framelocalsproxy_new,
947
    .tp_free = PyObject_GC_Del,
948
    .tp_doc = framelocalsproxy_doc,
949
};
950
951
PyObject *
952
_PyFrameLocalsProxy_New(PyFrameObject *frame)
953
28
{
954
28
    PyObject* args = PyTuple_Pack(1, frame);
955
28
    if (args == NULL) {
956
0
        return NULL;
957
0
    }
958
959
28
    PyObject* proxy = framelocalsproxy_new(&PyFrameLocalsProxy_Type, args, NULL);
960
28
    Py_DECREF(args);
961
28
    return proxy;
962
28
}
963
964
static PyMemberDef frame_memberlist[] = {
965
    {"f_trace_lines",   Py_T_BOOL,         OFF(f_trace_lines), 0},
966
    {NULL}      /* Sentinel */
967
};
968
969
/*[clinic input]
970
@critical_section
971
@getter
972
frame.f_locals as frame_locals
973
974
Return the mapping used by the frame to look up local variables.
975
[clinic start generated code]*/
976
977
static PyObject *
978
frame_locals_get_impl(PyFrameObject *self)
979
/*[clinic end generated code: output=b4ace8bb4cae71f4 input=7bd444d0dc8ddf44]*/
980
28
{
981
28
    assert(!_PyFrame_IsIncomplete(self->f_frame));
982
983
28
    PyCodeObject *co = _PyFrame_GetCode(self->f_frame);
984
985
28
    if (!(co->co_flags & CO_OPTIMIZED) && !_PyFrame_HasHiddenLocals(self->f_frame)) {
986
0
        if (self->f_frame->f_locals == NULL) {
987
            // We found cases when f_locals is NULL for non-optimized code.
988
            // We fill the f_locals with an empty dict to avoid crash until
989
            // we find the root cause.
990
0
            self->f_frame->f_locals = PyDict_New();
991
0
            if (self->f_frame->f_locals == NULL) {
992
0
                return NULL;
993
0
            }
994
0
        }
995
0
        return Py_NewRef(self->f_frame->f_locals);
996
0
    }
997
998
28
    return _PyFrameLocalsProxy_New(self);
999
28
}
1000
1001
int
1002
PyFrame_GetLineNumber(PyFrameObject *f)
1003
1.20M
{
1004
1.20M
    assert(f != NULL);
1005
1.20M
    if (f->f_lineno == -1) {
1006
        // We should calculate it once. If we can't get the line number,
1007
        // set f->f_lineno to 0.
1008
0
        f->f_lineno = PyUnstable_InterpreterFrame_GetLine(f->f_frame);
1009
0
        if (f->f_lineno < 0) {
1010
0
            f->f_lineno = 0;
1011
0
            return -1;
1012
0
        }
1013
0
    }
1014
1015
1.20M
    if (f->f_lineno > 0) {
1016
0
        return f->f_lineno;
1017
0
    }
1018
1.20M
    return PyUnstable_InterpreterFrame_GetLine(f->f_frame);
1019
1.20M
}
1020
1021
/*[clinic input]
1022
@critical_section
1023
@getter
1024
frame.f_lineno as frame_lineno
1025
1026
Return the current line number in the frame.
1027
[clinic start generated code]*/
1028
1029
static PyObject *
1030
frame_lineno_get_impl(PyFrameObject *self)
1031
/*[clinic end generated code: output=70f35de5ac7ad630 input=87b9ec648b742936]*/
1032
0
{
1033
0
    int lineno = PyFrame_GetLineNumber(self);
1034
0
    if (lineno < 0) {
1035
0
        Py_RETURN_NONE;
1036
0
    }
1037
0
    return PyLong_FromLong(lineno);
1038
0
}
1039
1040
/*[clinic input]
1041
@critical_section
1042
@getter
1043
frame.f_lasti as frame_lasti
1044
1045
Return the index of the last attempted instruction in the frame.
1046
[clinic start generated code]*/
1047
1048
static PyObject *
1049
frame_lasti_get_impl(PyFrameObject *self)
1050
/*[clinic end generated code: output=03275b4f0327d1a2 input=0225ed49cb1fbeeb]*/
1051
0
{
1052
0
    int lasti = _PyInterpreterFrame_LASTI(self->f_frame);
1053
0
    if (lasti < 0) {
1054
0
        return PyLong_FromLong(-1);
1055
0
    }
1056
0
    return PyLong_FromLong(lasti * sizeof(_Py_CODEUNIT));
1057
0
}
1058
1059
/*[clinic input]
1060
@critical_section
1061
@getter
1062
frame.f_globals as frame_globals
1063
1064
Return the global variables in the frame.
1065
[clinic start generated code]*/
1066
1067
static PyObject *
1068
frame_globals_get_impl(PyFrameObject *self)
1069
/*[clinic end generated code: output=7758788c32885528 input=7fff7241357d314d]*/
1070
0
{
1071
0
    PyObject *globals = self->f_frame->f_globals;
1072
0
    if (globals == NULL) {
1073
0
        globals = Py_None;
1074
0
    }
1075
0
    return Py_NewRef(globals);
1076
0
}
1077
1078
/*[clinic input]
1079
@critical_section
1080
@getter
1081
frame.f_builtins as frame_builtins
1082
1083
Return the built-in variables in the frame.
1084
[clinic start generated code]*/
1085
1086
static PyObject *
1087
frame_builtins_get_impl(PyFrameObject *self)
1088
/*[clinic end generated code: output=45362faa6d42c702 input=27c696d6ffcad2c7]*/
1089
0
{
1090
0
    PyObject *builtins = self->f_frame->f_builtins;
1091
0
    if (builtins == NULL) {
1092
0
        builtins = Py_None;
1093
0
    }
1094
0
    return Py_NewRef(builtins);
1095
0
}
1096
1097
/*[clinic input]
1098
@getter
1099
frame.f_code as frame_code
1100
1101
Return the code object being executed in this frame.
1102
[clinic start generated code]*/
1103
1104
static PyObject *
1105
frame_code_get_impl(PyFrameObject *self)
1106
/*[clinic end generated code: output=a5ed6207395a8cef input=e127e7098c124816]*/
1107
0
{
1108
0
    if (PySys_Audit("object.__getattr__", "Os", self, "f_code") < 0) {
1109
0
        return NULL;
1110
0
    }
1111
0
    return (PyObject *)PyFrame_GetCode(self);
1112
0
}
1113
1114
/*[clinic input]
1115
@critical_section
1116
@getter
1117
frame.f_back as frame_back
1118
[clinic start generated code]*/
1119
1120
static PyObject *
1121
frame_back_get_impl(PyFrameObject *self)
1122
/*[clinic end generated code: output=3a84c22a55a63c79 input=9e528570d0e1f44a]*/
1123
0
{
1124
0
    PyObject *res = (PyObject *)PyFrame_GetBack(self);
1125
0
    if (res == NULL) {
1126
0
        Py_RETURN_NONE;
1127
0
    }
1128
0
    return res;
1129
0
}
1130
1131
/*[clinic input]
1132
@critical_section
1133
@getter
1134
frame.f_trace_opcodes as frame_trace_opcodes
1135
1136
Return True if opcode tracing is enabled, False otherwise.
1137
[clinic start generated code]*/
1138
1139
static PyObject *
1140
frame_trace_opcodes_get_impl(PyFrameObject *self)
1141
/*[clinic end generated code: output=53ff41d09cc32e87 input=4eb91dc88e04677a]*/
1142
0
{
1143
0
    return self->f_trace_opcodes ? Py_True : Py_False;
1144
0
}
1145
1146
/*[clinic input]
1147
@critical_section
1148
@setter
1149
frame.f_trace_opcodes as frame_trace_opcodes
1150
[clinic start generated code]*/
1151
1152
static int
1153
frame_trace_opcodes_set_impl(PyFrameObject *self, PyObject *value)
1154
/*[clinic end generated code: output=92619da2bfccd449 input=7e286eea3c0333ff]*/
1155
0
{
1156
0
    if (!PyBool_Check(value)) {
1157
0
        PyErr_SetString(PyExc_TypeError,
1158
0
                        "attribute value type must be bool");
1159
0
        return -1;
1160
0
    }
1161
0
    if (value == Py_True) {
1162
0
        self->f_trace_opcodes = 1;
1163
0
        if (self->f_trace) {
1164
0
            return _PyEval_SetOpcodeTrace(self, true);
1165
0
        }
1166
0
    }
1167
0
    else {
1168
0
        self->f_trace_opcodes = 0;
1169
0
        return _PyEval_SetOpcodeTrace(self, false);
1170
0
    }
1171
0
    return 0;
1172
0
}
1173
1174
/* Model the evaluation stack, to determine which jumps
1175
 * are safe and how many values needs to be popped.
1176
 * The stack is modelled by a 64 integer, treating any
1177
 * stack that can't fit into 64 bits as "overflowed".
1178
 */
1179
1180
typedef enum kind {
1181
    Iterator = 1,
1182
    Except = 2,
1183
    Object = 3,
1184
    Null = 4,
1185
    Lasti = 5,
1186
} Kind;
1187
1188
static int
1189
0
compatible_kind(Kind from, Kind to) {
1190
0
    if (to == 0) {
1191
0
        return 0;
1192
0
    }
1193
0
    if (to == Object) {
1194
0
        return from != Null;
1195
0
    }
1196
0
    if (to == Null) {
1197
0
        return 1;
1198
0
    }
1199
0
    return from == to;
1200
0
}
1201
1202
0
#define BITS_PER_BLOCK 3
1203
1204
0
#define UNINITIALIZED -2
1205
0
#define OVERFLOWED -1
1206
1207
0
#define MAX_STACK_ENTRIES (63/BITS_PER_BLOCK)
1208
0
#define WILL_OVERFLOW (1ULL<<((MAX_STACK_ENTRIES-1)*BITS_PER_BLOCK))
1209
1210
0
#define EMPTY_STACK 0
1211
1212
static inline int64_t
1213
push_value(int64_t stack, Kind kind)
1214
0
{
1215
0
    if (((uint64_t)stack) >= WILL_OVERFLOW) {
1216
0
        return OVERFLOWED;
1217
0
    }
1218
0
    else {
1219
0
        return (stack << BITS_PER_BLOCK) | kind;
1220
0
    }
1221
0
}
1222
1223
static inline int64_t
1224
pop_value(int64_t stack)
1225
0
{
1226
0
    return Py_ARITHMETIC_RIGHT_SHIFT(int64_t, stack, BITS_PER_BLOCK);
1227
0
}
1228
1229
0
#define MASK ((1<<BITS_PER_BLOCK)-1)
1230
1231
static inline Kind
1232
top_of_stack(int64_t stack)
1233
0
{
1234
0
    return stack & MASK;
1235
0
}
1236
1237
static inline Kind
1238
peek(int64_t stack, int n)
1239
0
{
1240
0
    assert(n >= 1);
1241
0
    return (stack>>(BITS_PER_BLOCK*(n-1))) & MASK;
1242
0
}
1243
1244
static Kind
1245
stack_swap(int64_t stack, int n)
1246
0
{
1247
0
    assert(n >= 1);
1248
0
    Kind to_swap = peek(stack, n);
1249
0
    Kind top = top_of_stack(stack);
1250
0
    int shift = BITS_PER_BLOCK*(n-1);
1251
0
    int64_t replaced_low = (stack & ~(MASK << shift)) | (top << shift);
1252
0
    int64_t replaced_top = (replaced_low & ~MASK) | to_swap;
1253
0
    return replaced_top;
1254
0
}
1255
1256
static int64_t
1257
0
pop_to_level(int64_t stack, int level) {
1258
0
    if (level == 0) {
1259
0
        return EMPTY_STACK;
1260
0
    }
1261
0
    int64_t max_item = (1<<BITS_PER_BLOCK) - 1;
1262
0
    int64_t level_max_stack = max_item << ((level-1) * BITS_PER_BLOCK);
1263
0
    while (stack > level_max_stack) {
1264
0
        stack = pop_value(stack);
1265
0
    }
1266
0
    return stack;
1267
0
}
1268
1269
#if 0
1270
/* These functions are useful for debugging the stack marking code */
1271
1272
static char
1273
tos_char(int64_t stack) {
1274
    switch(top_of_stack(stack)) {
1275
        case Iterator:
1276
            return 'I';
1277
        case Except:
1278
            return 'E';
1279
        case Object:
1280
            return 'O';
1281
        case Lasti:
1282
            return 'L';
1283
        case Null:
1284
            return 'N';
1285
    }
1286
    return '?';
1287
}
1288
1289
static void
1290
print_stack(int64_t stack) {
1291
    if (stack < 0) {
1292
        if (stack == UNINITIALIZED) {
1293
            printf("---");
1294
        }
1295
        else if (stack == OVERFLOWED) {
1296
            printf("OVERFLOWED");
1297
        }
1298
        else {
1299
            printf("??");
1300
        }
1301
        return;
1302
    }
1303
    while (stack) {
1304
        printf("%c", tos_char(stack));
1305
        stack = pop_value(stack);
1306
    }
1307
}
1308
1309
static void
1310
print_stacks(int64_t *stacks, int n) {
1311
    for (int i = 0; i < n; i++) {
1312
        printf("%d: ", i);
1313
        print_stack(stacks[i]);
1314
        printf("\n");
1315
    }
1316
}
1317
1318
#endif
1319
1320
static int64_t *
1321
mark_stacks(PyCodeObject *code_obj, int len)
1322
0
{
1323
0
    PyObject *co_code = _PyCode_GetCode(code_obj);
1324
0
    if (co_code == NULL) {
1325
0
        return NULL;
1326
0
    }
1327
0
    int64_t *stacks = PyMem_New(int64_t, len+1);
1328
1329
0
    if (stacks == NULL) {
1330
0
        PyErr_NoMemory();
1331
0
        Py_DECREF(co_code);
1332
0
        return NULL;
1333
0
    }
1334
0
    for (int i = 1; i <= len; i++) {
1335
0
        stacks[i] = UNINITIALIZED;
1336
0
    }
1337
0
    stacks[0] = EMPTY_STACK;
1338
0
    int todo = 1;
1339
0
    while (todo) {
1340
0
        todo = 0;
1341
        /* Scan instructions */
1342
0
        for (int i = 0; i < len;) {
1343
0
            int j;
1344
0
            int64_t next_stack = stacks[i];
1345
0
            _Py_CODEUNIT inst = _Py_GetBaseCodeUnit(code_obj, i);
1346
0
            int opcode = inst.op.code;
1347
0
            int oparg = 0;
1348
0
            while (opcode == EXTENDED_ARG) {
1349
0
                oparg = (oparg << 8) | inst.op.arg;
1350
0
                i++;
1351
0
                inst = _Py_GetBaseCodeUnit(code_obj, i);
1352
0
                opcode = inst.op.code;
1353
0
                stacks[i] = next_stack;
1354
0
            }
1355
0
            oparg = (oparg << 8) | inst.op.arg;
1356
0
            int next_i = i + _PyOpcode_Caches[opcode] + 1;
1357
0
            if (next_stack == UNINITIALIZED) {
1358
0
                i = next_i;
1359
0
                continue;
1360
0
            }
1361
0
            switch (opcode) {
1362
0
                case POP_JUMP_IF_FALSE:
1363
0
                case POP_JUMP_IF_TRUE:
1364
0
                case POP_JUMP_IF_NONE:
1365
0
                case POP_JUMP_IF_NOT_NONE:
1366
0
                {
1367
0
                    int64_t target_stack;
1368
0
                    j = next_i + oparg;
1369
0
                    assert(j < len);
1370
0
                    next_stack = pop_value(next_stack);
1371
0
                    target_stack = next_stack;
1372
0
                    assert(stacks[j] == UNINITIALIZED || stacks[j] == target_stack);
1373
0
                    stacks[j] = target_stack;
1374
0
                    stacks[next_i] = next_stack;
1375
0
                    break;
1376
0
                }
1377
0
                case SEND:
1378
0
                    j = oparg + i + INLINE_CACHE_ENTRIES_SEND + 1;
1379
0
                    assert(j < len);
1380
0
                    assert(stacks[j] == UNINITIALIZED || stacks[j] == next_stack);
1381
0
                    stacks[j] = next_stack;
1382
0
                    stacks[next_i] = next_stack;
1383
0
                    break;
1384
0
                case JUMP_FORWARD:
1385
0
                    j = oparg + i + 1;
1386
0
                    assert(j < len);
1387
0
                    assert(stacks[j] == UNINITIALIZED || stacks[j] == next_stack);
1388
0
                    stacks[j] = next_stack;
1389
0
                    break;
1390
0
                case JUMP_BACKWARD:
1391
0
                case JUMP_BACKWARD_NO_INTERRUPT:
1392
0
                    j = next_i - oparg;
1393
0
                    assert(j >= 0);
1394
0
                    assert(j < len);
1395
0
                    if (stacks[j] == UNINITIALIZED && j < i) {
1396
0
                        todo = 1;
1397
0
                    }
1398
0
                    assert(stacks[j] == UNINITIALIZED || stacks[j] == next_stack);
1399
0
                    stacks[j] = next_stack;
1400
0
                    break;
1401
0
                case GET_ITER:
1402
0
                    next_stack = push_value(pop_value(next_stack), Iterator);
1403
0
                    next_stack = push_value(next_stack, Iterator);
1404
0
                    stacks[next_i] = next_stack;
1405
0
                    break;
1406
0
                case GET_AITER:
1407
0
                    next_stack = push_value(pop_value(next_stack), Iterator);
1408
0
                    stacks[next_i] = next_stack;
1409
0
                    break;
1410
0
                case FOR_ITER:
1411
0
                {
1412
0
                    int64_t target_stack = push_value(next_stack, Object);
1413
0
                    stacks[next_i] = target_stack;
1414
0
                    j = oparg + 1 + INLINE_CACHE_ENTRIES_FOR_ITER + i;
1415
0
                    assert(j < len);
1416
0
                    assert(stacks[j] == UNINITIALIZED || stacks[j] == target_stack);
1417
0
                    stacks[j] = target_stack;
1418
0
                    break;
1419
0
                }
1420
0
                case END_ASYNC_FOR:
1421
0
                    next_stack = pop_value(pop_value(next_stack));
1422
0
                    stacks[next_i] = next_stack;
1423
0
                    break;
1424
0
                case PUSH_EXC_INFO:
1425
0
                    next_stack = push_value(next_stack, Except);
1426
0
                    stacks[next_i] = next_stack;
1427
0
                    break;
1428
0
                case POP_EXCEPT:
1429
0
                    assert(top_of_stack(next_stack) == Except);
1430
0
                    next_stack = pop_value(next_stack);
1431
0
                    stacks[next_i] = next_stack;
1432
0
                    break;
1433
0
                case RETURN_VALUE:
1434
0
                    assert(pop_value(next_stack) == EMPTY_STACK);
1435
0
                    assert(top_of_stack(next_stack) == Object);
1436
0
                    break;
1437
0
                case RAISE_VARARGS:
1438
0
                    break;
1439
0
                case RERAISE:
1440
0
                    assert(top_of_stack(next_stack) == Except);
1441
                    /* End of block */
1442
0
                    break;
1443
0
                case PUSH_NULL:
1444
0
                    next_stack = push_value(next_stack, Null);
1445
0
                    stacks[next_i] = next_stack;
1446
0
                    break;
1447
0
                case LOAD_GLOBAL:
1448
0
                {
1449
0
                    int j = oparg;
1450
0
                    next_stack = push_value(next_stack, Object);
1451
0
                    if (j & 1) {
1452
0
                        next_stack = push_value(next_stack, Null);
1453
0
                    }
1454
0
                    stacks[next_i] = next_stack;
1455
0
                    break;
1456
0
                }
1457
0
                case LOAD_ATTR:
1458
0
                {
1459
0
                    assert(top_of_stack(next_stack) == Object);
1460
0
                    int j = oparg;
1461
0
                    if (j & 1) {
1462
0
                        next_stack = pop_value(next_stack);
1463
0
                        next_stack = push_value(next_stack, Object);
1464
0
                        next_stack = push_value(next_stack, Null);
1465
0
                    }
1466
0
                    stacks[next_i] = next_stack;
1467
0
                    break;
1468
0
                }
1469
0
                case SWAP:
1470
0
                {
1471
0
                    int n = oparg;
1472
0
                    next_stack = stack_swap(next_stack, n);
1473
0
                    stacks[next_i] = next_stack;
1474
0
                    break;
1475
0
                }
1476
0
                case COPY:
1477
0
                {
1478
0
                    int n = oparg;
1479
0
                    next_stack = push_value(next_stack, peek(next_stack, n));
1480
0
                    stacks[next_i] = next_stack;
1481
0
                    break;
1482
0
                }
1483
0
                case CACHE:
1484
0
                case RESERVED:
1485
0
                {
1486
0
                    assert(0);
1487
0
                }
1488
0
                default:
1489
0
                {
1490
0
                    int delta = PyCompile_OpcodeStackEffect(opcode, oparg);
1491
0
                    assert(delta != PY_INVALID_STACK_EFFECT);
1492
0
                    while (delta < 0) {
1493
0
                        next_stack = pop_value(next_stack);
1494
0
                        delta++;
1495
0
                    }
1496
0
                    while (delta > 0) {
1497
0
                        next_stack = push_value(next_stack, Object);
1498
0
                        delta--;
1499
0
                    }
1500
0
                    stacks[next_i] = next_stack;
1501
0
                }
1502
0
            }
1503
0
            i = next_i;
1504
0
        }
1505
        /* Scan exception table */
1506
0
        unsigned char *start = (unsigned char *)PyBytes_AS_STRING(code_obj->co_exceptiontable);
1507
0
        unsigned char *end = start + PyBytes_GET_SIZE(code_obj->co_exceptiontable);
1508
0
        unsigned char *scan = start;
1509
0
        while (scan < end) {
1510
0
            int start_offset, size, handler;
1511
0
            scan = parse_varint(scan, &start_offset);
1512
0
            assert(start_offset >= 0 && start_offset < len);
1513
0
            scan = parse_varint(scan, &size);
1514
0
            assert(size >= 0 && start_offset+size <= len);
1515
0
            scan = parse_varint(scan, &handler);
1516
0
            assert(handler >= 0 && handler < len);
1517
0
            int depth_and_lasti;
1518
0
            scan = parse_varint(scan, &depth_and_lasti);
1519
0
            int level = depth_and_lasti >> 1;
1520
0
            int lasti = depth_and_lasti & 1;
1521
0
            if (stacks[start_offset] != UNINITIALIZED) {
1522
0
                if (stacks[handler] == UNINITIALIZED) {
1523
0
                    todo = 1;
1524
0
                    uint64_t target_stack = pop_to_level(stacks[start_offset], level);
1525
0
                    if (lasti) {
1526
0
                        target_stack = push_value(target_stack, Lasti);
1527
0
                    }
1528
0
                    target_stack = push_value(target_stack, Except);
1529
0
                    stacks[handler] = target_stack;
1530
0
                }
1531
0
            }
1532
0
        }
1533
0
    }
1534
0
    Py_DECREF(co_code);
1535
0
    return stacks;
1536
0
}
1537
1538
static int
1539
compatible_stack(int64_t from_stack, int64_t to_stack)
1540
0
{
1541
0
    if (from_stack < 0 || to_stack < 0) {
1542
0
        return 0;
1543
0
    }
1544
0
    while(from_stack > to_stack) {
1545
0
        from_stack = pop_value(from_stack);
1546
0
    }
1547
0
    while(from_stack) {
1548
0
        Kind from_top = top_of_stack(from_stack);
1549
0
        Kind to_top = top_of_stack(to_stack);
1550
0
        if (!compatible_kind(from_top, to_top)) {
1551
0
            return 0;
1552
0
        }
1553
0
        from_stack = pop_value(from_stack);
1554
0
        to_stack = pop_value(to_stack);
1555
0
    }
1556
0
    return to_stack == 0;
1557
0
}
1558
1559
static const char *
1560
explain_incompatible_stack(int64_t to_stack)
1561
0
{
1562
0
    assert(to_stack != 0);
1563
0
    if (to_stack == OVERFLOWED) {
1564
0
        return "stack is too deep to analyze";
1565
0
    }
1566
0
    if (to_stack == UNINITIALIZED) {
1567
0
        return "can't jump into an exception handler, or code may be unreachable";
1568
0
    }
1569
0
    Kind target_kind = top_of_stack(to_stack);
1570
0
    switch(target_kind) {
1571
0
        case Except:
1572
0
            return "can't jump into an 'except' block as there's no exception";
1573
0
        case Lasti:
1574
0
            return "can't jump into a re-raising block as there's no location";
1575
0
        case Object:
1576
0
        case Null:
1577
0
            return "incompatible stacks";
1578
0
        case Iterator:
1579
0
            return "can't jump into the body of a for loop";
1580
0
        default:
1581
0
            Py_UNREACHABLE();
1582
0
    }
1583
0
}
1584
1585
static int *
1586
marklines(PyCodeObject *code, int len)
1587
0
{
1588
0
    PyCodeAddressRange bounds;
1589
0
    _PyCode_InitAddressRange(code, &bounds);
1590
0
    assert (bounds.ar_end == 0);
1591
0
    int last_line = -1;
1592
1593
0
    int *linestarts = PyMem_New(int, len);
1594
0
    if (linestarts == NULL) {
1595
0
        return NULL;
1596
0
    }
1597
0
    for (int i = 0; i < len; i++) {
1598
0
        linestarts[i] = -1;
1599
0
    }
1600
1601
0
    while (_PyLineTable_NextAddressRange(&bounds)) {
1602
0
        assert(bounds.ar_start / (int)sizeof(_Py_CODEUNIT) < len);
1603
0
        if (bounds.ar_line != last_line && bounds.ar_line != -1) {
1604
0
            linestarts[bounds.ar_start / sizeof(_Py_CODEUNIT)] = bounds.ar_line;
1605
0
            last_line = bounds.ar_line;
1606
0
        }
1607
0
    }
1608
0
    return linestarts;
1609
0
}
1610
1611
static int
1612
first_line_not_before(int *lines, int len, int line)
1613
0
{
1614
0
    int result = INT_MAX;
1615
0
    for (int i = 0; i < len; i++) {
1616
0
        if (lines[i] < result && lines[i] >= line) {
1617
0
            result = lines[i];
1618
0
        }
1619
0
    }
1620
0
    if (result == INT_MAX) {
1621
0
        return -1;
1622
0
    }
1623
0
    return result;
1624
0
}
1625
1626
static bool frame_is_suspended(PyFrameObject *frame)
1627
0
{
1628
0
    assert(!_PyFrame_IsIncomplete(frame->f_frame));
1629
0
    if (frame->f_frame->owner == FRAME_OWNED_BY_GENERATOR) {
1630
0
        PyGenObject *gen = _PyGen_GetGeneratorFromFrame(frame->f_frame);
1631
0
        return FRAME_STATE_SUSPENDED(gen->gi_frame_state);
1632
0
    }
1633
0
    return false;
1634
0
}
1635
1636
/* Setter for f_lineno - you can set f_lineno from within a trace function in
1637
 * order to jump to a given line of code, subject to some restrictions.  Most
1638
 * lines are OK to jump to because they don't make any assumptions about the
1639
 * state of the stack (obvious because you could remove the line and the code
1640
 * would still work without any stack errors), but there are some constructs
1641
 * that limit jumping:
1642
 *
1643
 *  o Any exception handlers.
1644
 *  o 'for' and 'async for' loops can't be jumped into because the
1645
 *    iterator needs to be on the stack.
1646
 *  o Jumps cannot be made from within a trace function invoked with a
1647
 *    'return' or 'exception' event since the eval loop has been exited at
1648
 *    that time.
1649
 */
1650
/*[clinic input]
1651
@critical_section
1652
@setter
1653
frame.f_lineno as frame_lineno
1654
[clinic start generated code]*/
1655
1656
static int
1657
frame_lineno_set_impl(PyFrameObject *self, PyObject *value)
1658
/*[clinic end generated code: output=e64c86ff6be64292 input=36ed3c896b27fb91]*/
1659
0
{
1660
0
    PyCodeObject *code = _PyFrame_GetCode(self->f_frame);
1661
0
    if (value == NULL) {
1662
0
        PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
1663
0
        return -1;
1664
0
    }
1665
    /* f_lineno must be an integer. */
1666
0
    if (!PyLong_CheckExact(value)) {
1667
0
        PyErr_SetString(PyExc_ValueError,
1668
0
                        "lineno must be an integer");
1669
0
        return -1;
1670
0
    }
1671
1672
0
    bool is_suspended = frame_is_suspended(self);
1673
    /*
1674
     * This code preserves the historical restrictions on
1675
     * setting the line number of a frame.
1676
     * Jumps are forbidden on a 'return' trace event (except after a yield).
1677
     * Jumps from 'call' trace events are also forbidden.
1678
     * In addition, jumps are forbidden when not tracing,
1679
     * as this is a debugging feature.
1680
     */
1681
0
    int what_event = PyThreadState_GET()->what_event;
1682
0
    if (what_event < 0) {
1683
0
        PyErr_Format(PyExc_ValueError,
1684
0
                    "f_lineno can only be set in a trace function");
1685
0
        return -1;
1686
0
    }
1687
0
    switch (what_event) {
1688
0
        case PY_MONITORING_EVENT_PY_RESUME:
1689
0
        case PY_MONITORING_EVENT_JUMP:
1690
0
        case PY_MONITORING_EVENT_BRANCH:
1691
0
        case PY_MONITORING_EVENT_BRANCH_LEFT:
1692
0
        case PY_MONITORING_EVENT_BRANCH_RIGHT:
1693
0
        case PY_MONITORING_EVENT_LINE:
1694
0
        case PY_MONITORING_EVENT_PY_YIELD:
1695
            /* Setting f_lineno is allowed for the above events */
1696
0
            break;
1697
0
        case PY_MONITORING_EVENT_PY_START:
1698
0
            PyErr_Format(PyExc_ValueError,
1699
0
                     "can't jump from the 'call' trace event of a new frame");
1700
0
            return -1;
1701
0
        case PY_MONITORING_EVENT_CALL:
1702
0
        case PY_MONITORING_EVENT_C_RETURN:
1703
0
            PyErr_SetString(PyExc_ValueError,
1704
0
                "can't jump during a call");
1705
0
            return -1;
1706
0
        case PY_MONITORING_EVENT_PY_RETURN:
1707
0
        case PY_MONITORING_EVENT_PY_UNWIND:
1708
0
        case PY_MONITORING_EVENT_PY_THROW:
1709
0
        case PY_MONITORING_EVENT_RAISE:
1710
0
        case PY_MONITORING_EVENT_C_RAISE:
1711
0
        case PY_MONITORING_EVENT_INSTRUCTION:
1712
0
        case PY_MONITORING_EVENT_EXCEPTION_HANDLED:
1713
0
            PyErr_Format(PyExc_ValueError,
1714
0
                "can only jump from a 'line' trace event");
1715
0
            return -1;
1716
0
        default:
1717
0
            PyErr_SetString(PyExc_SystemError,
1718
0
                "unexpected event type");
1719
0
            return -1;
1720
0
    }
1721
1722
0
    int new_lineno;
1723
1724
    /* Fail if the line falls outside the code block and
1725
        select first line with actual code. */
1726
0
    int overflow;
1727
0
    long l_new_lineno = PyLong_AsLongAndOverflow(value, &overflow);
1728
0
    if (overflow
1729
0
#if SIZEOF_LONG > SIZEOF_INT
1730
0
        || l_new_lineno > INT_MAX
1731
0
        || l_new_lineno < INT_MIN
1732
0
#endif
1733
0
    ) {
1734
0
        PyErr_SetString(PyExc_ValueError,
1735
0
                        "lineno out of range");
1736
0
        return -1;
1737
0
    }
1738
0
    new_lineno = (int)l_new_lineno;
1739
1740
0
    if (new_lineno < code->co_firstlineno) {
1741
0
        PyErr_Format(PyExc_ValueError,
1742
0
                    "line %d comes before the current code block",
1743
0
                    new_lineno);
1744
0
        return -1;
1745
0
    }
1746
1747
    /* PyCode_NewWithPosOnlyArgs limits co_code to be under INT_MAX so this
1748
     * should never overflow. */
1749
0
    int len = (int)Py_SIZE(code);
1750
0
    int *lines = marklines(code, len);
1751
0
    if (lines == NULL) {
1752
0
        return -1;
1753
0
    }
1754
1755
0
    new_lineno = first_line_not_before(lines, len, new_lineno);
1756
0
    if (new_lineno < 0) {
1757
0
        PyErr_Format(PyExc_ValueError,
1758
0
                    "line %d comes after the current code block",
1759
0
                    (int)l_new_lineno);
1760
0
        PyMem_Free(lines);
1761
0
        return -1;
1762
0
    }
1763
1764
0
    int64_t *stacks = mark_stacks(code, len);
1765
0
    if (stacks == NULL) {
1766
0
        PyMem_Free(lines);
1767
0
        return -1;
1768
0
    }
1769
1770
0
    int64_t best_stack = OVERFLOWED;
1771
0
    int best_addr = -1;
1772
0
    int64_t start_stack = stacks[_PyInterpreterFrame_LASTI(self->f_frame)];
1773
0
    int err = -1;
1774
0
    const char *msg = "cannot find bytecode for specified line";
1775
0
    for (int i = 0; i < len; i++) {
1776
0
        if (lines[i] == new_lineno) {
1777
0
            int64_t target_stack = stacks[i];
1778
0
            if (compatible_stack(start_stack, target_stack)) {
1779
0
                err = 0;
1780
0
                if (target_stack > best_stack) {
1781
0
                    best_stack = target_stack;
1782
0
                    best_addr = i;
1783
0
                }
1784
0
            }
1785
0
            else if (err < 0) {
1786
0
                if (start_stack == OVERFLOWED) {
1787
0
                    msg = "stack to deep to analyze";
1788
0
                }
1789
0
                else if (start_stack == UNINITIALIZED) {
1790
0
                    msg = "can't jump from unreachable code";
1791
0
                }
1792
0
                else {
1793
0
                    msg = explain_incompatible_stack(target_stack);
1794
0
                    err = 1;
1795
0
                }
1796
0
            }
1797
0
        }
1798
0
    }
1799
0
    PyMem_Free(stacks);
1800
0
    PyMem_Free(lines);
1801
0
    if (err) {
1802
0
        PyErr_SetString(PyExc_ValueError, msg);
1803
0
        return -1;
1804
0
    }
1805
    // Populate any NULL locals that the compiler might have "proven" to exist
1806
    // in the new location. Rather than crashing or changing co_code, just bind
1807
    // None instead:
1808
0
    int unbound = 0;
1809
0
    for (int i = 0; i < code->co_nlocalsplus; i++) {
1810
        // Counting every unbound local is overly-cautious, but a full flow
1811
        // analysis (like we do in the compiler) is probably too expensive:
1812
0
        unbound += PyStackRef_IsNull(self->f_frame->localsplus[i]);
1813
0
    }
1814
0
    if (unbound) {
1815
0
        const char *e = "assigning None to %d unbound local%s";
1816
0
        const char *s = (unbound == 1) ? "" : "s";
1817
0
        if (PyErr_WarnFormat(PyExc_RuntimeWarning, 0, e, unbound, s)) {
1818
0
            return -1;
1819
0
        }
1820
        // Do this in a second pass to avoid writing a bunch of Nones when
1821
        // warnings are being treated as errors and the previous bit raises:
1822
0
        for (int i = 0; i < code->co_nlocalsplus; i++) {
1823
0
            if (PyStackRef_IsNull(self->f_frame->localsplus[i])) {
1824
0
                self->f_frame->localsplus[i] = PyStackRef_None;
1825
0
                unbound--;
1826
0
            }
1827
0
        }
1828
0
        assert(unbound == 0);
1829
0
    }
1830
0
    if (is_suspended) {
1831
        /* Account for value popped by yield */
1832
0
        start_stack = pop_value(start_stack);
1833
0
    }
1834
0
    while (start_stack > best_stack) {
1835
0
        _PyStackRef popped = _PyFrame_StackPop(self->f_frame);
1836
0
        if (top_of_stack(start_stack) == Except) {
1837
            /* Pop exception stack as well as the evaluation stack */
1838
0
            PyObject *exc = PyStackRef_AsPyObjectBorrow(popped);
1839
0
            assert(PyExceptionInstance_Check(exc) || exc == Py_None);
1840
0
            PyThreadState *tstate = _PyThreadState_GET();
1841
0
            Py_XSETREF(tstate->exc_info->exc_value, exc == Py_None ? NULL : exc);
1842
0
        }
1843
0
        else {
1844
0
            PyStackRef_XCLOSE(popped);
1845
0
        }
1846
0
        start_stack = pop_value(start_stack);
1847
0
    }
1848
    /* Finally set the new lasti and return OK. */
1849
0
    self->f_lineno = 0;
1850
0
    self->f_frame->instr_ptr = _PyFrame_GetBytecode(self->f_frame) + best_addr;
1851
0
    return 0;
1852
0
}
1853
1854
/*[clinic input]
1855
@permit_long_summary
1856
@critical_section
1857
@getter
1858
frame.f_trace as frame_trace
1859
1860
Return the trace function for this frame, or None if no trace function is set.
1861
[clinic start generated code]*/
1862
1863
static PyObject *
1864
frame_trace_get_impl(PyFrameObject *self)
1865
/*[clinic end generated code: output=5475cbfce07826cd input=e4eacf2c68cac577]*/
1866
0
{
1867
0
    PyObject* trace = self->f_trace;
1868
0
    if (trace == NULL) {
1869
0
        trace = Py_None;
1870
0
    }
1871
0
    return Py_NewRef(trace);
1872
0
}
1873
1874
/*[clinic input]
1875
@permit_long_summary
1876
@critical_section
1877
@setter
1878
frame.f_trace as frame_trace
1879
[clinic start generated code]*/
1880
1881
static int
1882
frame_trace_set_impl(PyFrameObject *self, PyObject *value)
1883
/*[clinic end generated code: output=d6fe08335cf76ae4 input=e57380734815dac5]*/
1884
0
{
1885
0
    if (value == Py_None) {
1886
0
        value = NULL;
1887
0
    }
1888
0
    if (value != self->f_trace) {
1889
0
        Py_XSETREF(self->f_trace, Py_XNewRef(value));
1890
0
        if (value != NULL && self->f_trace_opcodes) {
1891
0
            return _PyEval_SetOpcodeTrace(self, true);
1892
0
        }
1893
0
    }
1894
0
    return 0;
1895
0
}
1896
1897
/*[clinic input]
1898
@critical_section
1899
@getter
1900
frame.f_generator as frame_generator
1901
1902
Return the generator or coroutine associated with this frame, or None.
1903
[clinic start generated code]*/
1904
1905
static PyObject *
1906
frame_generator_get_impl(PyFrameObject *self)
1907
/*[clinic end generated code: output=97aeb2392562e55b input=00a2bd008b239ab0]*/
1908
0
{
1909
0
    if (self->f_frame->owner == FRAME_OWNED_BY_GENERATOR) {
1910
0
        PyObject *gen = (PyObject *)_PyGen_GetGeneratorFromFrame(self->f_frame);
1911
0
        return Py_NewRef(gen);
1912
0
    }
1913
0
    Py_RETURN_NONE;
1914
0
}
1915
1916
1917
static PyGetSetDef frame_getsetlist[] = {
1918
    FRAME_BACK_GETSETDEF
1919
    FRAME_LOCALS_GETSETDEF
1920
    FRAME_LINENO_GETSETDEF
1921
    FRAME_TRACE_GETSETDEF
1922
    FRAME_LASTI_GETSETDEF
1923
    FRAME_GLOBALS_GETSETDEF
1924
    FRAME_BUILTINS_GETSETDEF
1925
    FRAME_CODE_GETSETDEF
1926
    FRAME_TRACE_OPCODES_GETSETDEF
1927
    FRAME_GENERATOR_GETSETDEF
1928
    {0}
1929
};
1930
1931
static void
1932
frame_dealloc(PyObject *op)
1933
54.9M
{
1934
    /* It is the responsibility of the owning generator/coroutine
1935
     * to have cleared the generator pointer */
1936
54.9M
    PyFrameObject *f = PyFrameObject_CAST(op);
1937
54.9M
    if (_PyObject_GC_IS_TRACKED(f)) {
1938
36.9M
        _PyObject_GC_UNTRACK(f);
1939
36.9M
    }
1940
1941
    /* GH-106092: If f->f_frame was on the stack and we reached the maximum
1942
     * nesting depth for deallocations, the trashcan may have delayed this
1943
     * deallocation until after f->f_frame is freed. Avoid dereferencing
1944
     * f->f_frame unless we know it still points to valid memory. */
1945
54.9M
    _PyInterpreterFrame *frame = (_PyInterpreterFrame *)f->_f_frame_data;
1946
1947
    /* Kill all local variables including specials, if we own them */
1948
54.9M
    if (f->f_frame == frame && frame->owner == FRAME_OWNED_BY_FRAME_OBJECT) {
1949
36.9M
        PyStackRef_CLEAR(frame->f_executable);
1950
36.9M
        PyStackRef_CLEAR(frame->f_funcobj);
1951
36.9M
        Py_CLEAR(frame->f_locals);
1952
36.9M
        _PyStackRef *locals = _PyFrame_GetLocalsArray(frame);
1953
36.9M
        _PyStackRef *sp = frame->stackpointer;
1954
211M
        while (sp > locals) {
1955
174M
            sp--;
1956
174M
            PyStackRef_CLEAR(*sp);
1957
174M
        }
1958
36.9M
    }
1959
54.9M
    Py_CLEAR(f->f_back);
1960
54.9M
    Py_CLEAR(f->f_trace);
1961
54.9M
    Py_CLEAR(f->f_extra_locals);
1962
54.9M
    Py_CLEAR(f->f_locals_cache);
1963
54.9M
    Py_CLEAR(f->f_overwritten_fast_locals);
1964
54.9M
    PyObject_GC_Del(f);
1965
54.9M
}
1966
1967
static int
1968
frame_traverse(PyObject *op, visitproc visit, void *arg)
1969
57.5k
{
1970
57.5k
    PyFrameObject *f = PyFrameObject_CAST(op);
1971
57.5k
    Py_VISIT(f->f_back);
1972
57.5k
    Py_VISIT(f->f_trace);
1973
57.5k
    Py_VISIT(f->f_extra_locals);
1974
57.5k
    Py_VISIT(f->f_locals_cache);
1975
57.5k
    Py_VISIT(f->f_overwritten_fast_locals);
1976
57.5k
    if (f->f_frame->owner != FRAME_OWNED_BY_FRAME_OBJECT) {
1977
0
        return 0;
1978
0
    }
1979
57.5k
    assert(f->f_frame->frame_obj == NULL);
1980
57.5k
    return _PyFrame_Traverse(f->f_frame, visit, arg);
1981
57.5k
}
1982
1983
static int
1984
frame_tp_clear(PyObject *op)
1985
0
{
1986
0
    PyFrameObject *f = PyFrameObject_CAST(op);
1987
0
    Py_CLEAR(f->f_trace);
1988
0
    Py_CLEAR(f->f_extra_locals);
1989
0
    Py_CLEAR(f->f_locals_cache);
1990
0
    Py_CLEAR(f->f_overwritten_fast_locals);
1991
1992
    /* locals and stack */
1993
0
    _PyStackRef *locals = _PyFrame_GetLocalsArray(f->f_frame);
1994
0
    _PyStackRef *sp = f->f_frame->stackpointer;
1995
0
    assert(sp >= locals);
1996
0
    while (sp > locals) {
1997
0
        sp--;
1998
0
        PyStackRef_CLEAR(*sp);
1999
0
    }
2000
0
    f->f_frame->stackpointer = locals;
2001
0
    Py_CLEAR(f->f_frame->f_locals);
2002
0
    return 0;
2003
0
}
2004
2005
/*[clinic input]
2006
@critical_section
2007
frame.clear
2008
2009
Clear all references held by the frame.
2010
[clinic start generated code]*/
2011
2012
static PyObject *
2013
frame_clear_impl(PyFrameObject *self)
2014
/*[clinic end generated code: output=864c662f16e9bfcc input=c358f9cff5f9b681]*/
2015
0
{
2016
0
    if (self->f_frame->owner == FRAME_OWNED_BY_GENERATOR) {
2017
0
        PyGenObject *gen = _PyGen_GetGeneratorFromFrame(self->f_frame);
2018
0
        if (_PyGen_ClearFrame(gen) < 0) {
2019
0
            return NULL;
2020
0
        }
2021
0
    }
2022
0
    else if (self->f_frame->owner == FRAME_OWNED_BY_THREAD) {
2023
0
        PyErr_SetString(PyExc_RuntimeError,
2024
0
                        "cannot clear an executing frame");
2025
0
        return NULL;
2026
0
    }
2027
0
    else {
2028
0
        assert(self->f_frame->owner == FRAME_OWNED_BY_FRAME_OBJECT);
2029
0
        (void)frame_tp_clear((PyObject *)self);
2030
0
    }
2031
0
    Py_RETURN_NONE;
2032
0
}
2033
2034
/*[clinic input]
2035
@critical_section
2036
frame.__sizeof__
2037
2038
Return the size of the frame in memory, in bytes.
2039
[clinic start generated code]*/
2040
2041
static PyObject *
2042
frame___sizeof___impl(PyFrameObject *self)
2043
/*[clinic end generated code: output=82948688e81078e2 input=908f90a83e73131d]*/
2044
0
{
2045
0
    Py_ssize_t res;
2046
0
    res = offsetof(PyFrameObject, _f_frame_data) + offsetof(_PyInterpreterFrame, localsplus);
2047
0
    PyCodeObject *code = _PyFrame_GetCode(self->f_frame);
2048
0
    res += _PyFrame_NumSlotsForCodeObject(code) * sizeof(PyObject *);
2049
0
    return PyLong_FromSsize_t(res);
2050
0
}
2051
2052
static PyObject *
2053
frame_repr(PyObject *op)
2054
0
{
2055
0
    PyFrameObject *f = PyFrameObject_CAST(op);
2056
0
    int lineno = PyFrame_GetLineNumber(f);
2057
0
    PyCodeObject *code = _PyFrame_GetCode(f->f_frame);
2058
0
    return PyUnicode_FromFormat(
2059
0
        "<frame at %p, file %R, line %d, code %S>",
2060
0
        f, code->co_filename, lineno, code->co_name);
2061
0
}
2062
2063
static PyMethodDef frame_methods[] = {
2064
    FRAME_CLEAR_METHODDEF
2065
    FRAME___SIZEOF___METHODDEF
2066
    {NULL, NULL}  /* sentinel */
2067
};
2068
2069
PyTypeObject PyFrame_Type = {
2070
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
2071
    "frame",
2072
    offsetof(PyFrameObject, _f_frame_data) +
2073
    offsetof(_PyInterpreterFrame, localsplus),
2074
    sizeof(PyObject *),
2075
    frame_dealloc,                              /* tp_dealloc */
2076
    0,                                          /* tp_vectorcall_offset */
2077
    0,                                          /* tp_getattr */
2078
    0,                                          /* tp_setattr */
2079
    0,                                          /* tp_as_async */
2080
    frame_repr,                                 /* tp_repr */
2081
    0,                                          /* tp_as_number */
2082
    0,                                          /* tp_as_sequence */
2083
    0,                                          /* tp_as_mapping */
2084
    0,                                          /* tp_hash */
2085
    0,                                          /* tp_call */
2086
    0,                                          /* tp_str */
2087
    PyObject_GenericGetAttr,                    /* tp_getattro */
2088
    PyObject_GenericSetAttr,                    /* tp_setattro */
2089
    0,                                          /* tp_as_buffer */
2090
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2091
    0,                                          /* tp_doc */
2092
    frame_traverse,                             /* tp_traverse */
2093
    frame_tp_clear,                             /* tp_clear */
2094
    0,                                          /* tp_richcompare */
2095
    0,                                          /* tp_weaklistoffset */
2096
    0,                                          /* tp_iter */
2097
    0,                                          /* tp_iternext */
2098
    frame_methods,                              /* tp_methods */
2099
    frame_memberlist,                           /* tp_members */
2100
    frame_getsetlist,                           /* tp_getset */
2101
    0,                                          /* tp_base */
2102
    0,                                          /* tp_dict */
2103
};
2104
2105
static void
2106
init_frame(PyThreadState *tstate, _PyInterpreterFrame *frame,
2107
           PyFunctionObject *func, PyObject *locals)
2108
135
{
2109
135
    PyCodeObject *code = (PyCodeObject *)func->func_code;
2110
135
    _PyFrame_Initialize(tstate, frame, PyStackRef_FromPyObjectNew(func),
2111
135
                        Py_XNewRef(locals), code, 0, NULL);
2112
135
}
2113
2114
PyFrameObject*
2115
_PyFrame_New_NoTrack(PyCodeObject *code)
2116
54.9M
{
2117
54.9M
    CALL_STAT_INC(frame_objects_created);
2118
54.9M
    int slots = code->co_nlocalsplus + code->co_stacksize;
2119
54.9M
    PyFrameObject *f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type, slots);
2120
54.9M
    if (f == NULL) {
2121
0
        return NULL;
2122
0
    }
2123
54.9M
    f->f_back = NULL;
2124
54.9M
    f->f_trace = NULL;
2125
54.9M
    f->f_trace_lines = 1;
2126
54.9M
    f->f_trace_opcodes = 0;
2127
54.9M
    f->f_lineno = 0;
2128
54.9M
    f->f_extra_locals = NULL;
2129
54.9M
    f->f_locals_cache = NULL;
2130
54.9M
    f->f_overwritten_fast_locals = NULL;
2131
54.9M
    return f;
2132
54.9M
}
2133
2134
/* Legacy API */
2135
PyFrameObject*
2136
PyFrame_New(PyThreadState *tstate, PyCodeObject *code,
2137
            PyObject *globals, PyObject *locals)
2138
135
{
2139
135
    PyObject *builtins = _PyDict_LoadBuiltinsFromGlobals(globals);
2140
135
    if (builtins == NULL) {
2141
0
        return NULL;
2142
0
    }
2143
135
    PyFrameConstructor desc = {
2144
135
        .fc_globals = globals,
2145
135
        .fc_builtins = builtins,
2146
135
        .fc_name = code->co_name,
2147
135
        .fc_qualname = code->co_name,
2148
135
        .fc_code = (PyObject *)code,
2149
135
        .fc_defaults = NULL,
2150
135
        .fc_kwdefaults = NULL,
2151
135
        .fc_closure = NULL
2152
135
    };
2153
135
    PyFunctionObject *func = _PyFunction_FromConstructor(&desc);
2154
135
    _Py_DECREF_BUILTINS(builtins);
2155
135
    if (func == NULL) {
2156
0
        return NULL;
2157
0
    }
2158
135
    PyFrameObject *f = _PyFrame_New_NoTrack(code);
2159
135
    if (f == NULL) {
2160
0
        Py_DECREF(func);
2161
0
        return NULL;
2162
0
    }
2163
135
    init_frame(tstate, (_PyInterpreterFrame *)f->_f_frame_data, func, locals);
2164
135
    f->f_frame = (_PyInterpreterFrame *)f->_f_frame_data;
2165
135
    f->f_frame->owner = FRAME_OWNED_BY_FRAME_OBJECT;
2166
    // This frame needs to be "complete", so pretend that the first RESUME ran:
2167
135
    f->f_frame->instr_ptr = _PyCode_CODE(code) + code->_co_firsttraceable + 1;
2168
135
    assert(!_PyFrame_IsIncomplete(f->f_frame));
2169
135
    Py_DECREF(func);
2170
135
    _PyObject_GC_TRACK(f);
2171
135
    return f;
2172
135
}
2173
2174
// Initialize frame free variables if needed
2175
static void
2176
frame_init_get_vars(_PyInterpreterFrame *frame)
2177
0
{
2178
    // COPY_FREE_VARS has no quickened forms, so no need to use _PyOpcode_Deopt
2179
    // here:
2180
0
    PyCodeObject *co = _PyFrame_GetCode(frame);
2181
0
    int lasti = _PyInterpreterFrame_LASTI(frame);
2182
0
    if (!(lasti < 0
2183
0
          && _PyFrame_GetBytecode(frame)->op.code == COPY_FREE_VARS
2184
0
          && PyStackRef_FunctionCheck(frame->f_funcobj)))
2185
0
    {
2186
        /* Free vars are initialized */
2187
0
        return;
2188
0
    }
2189
2190
    /* Free vars have not been initialized -- Do that */
2191
0
    PyFunctionObject *func = _PyFrame_GetFunction(frame);
2192
0
    PyObject *closure = func->func_closure;
2193
0
    int offset = PyUnstable_Code_GetFirstFree(co);
2194
0
    for (int i = 0; i < co->co_nfreevars; ++i) {
2195
0
        PyObject *o = PyTuple_GET_ITEM(closure, i);
2196
0
        frame->localsplus[offset + i] = PyStackRef_FromPyObjectNew(o);
2197
0
    }
2198
    // COPY_FREE_VARS doesn't have inline CACHEs, either:
2199
0
    frame->instr_ptr = _PyFrame_GetBytecode(frame);
2200
0
}
2201
2202
2203
static int
2204
frame_get_var(_PyInterpreterFrame *frame, PyCodeObject *co, int i,
2205
              PyObject **pvalue)
2206
0
{
2207
0
    _PyLocals_Kind kind = _PyLocals_GetKind(co->co_localspluskinds, i);
2208
2209
    /* If the namespace is unoptimized, then one of the
2210
       following cases applies:
2211
       1. It does not contain free variables, because it
2212
          uses import * or is a top-level namespace.
2213
       2. It is a class namespace.
2214
       We don't want to accidentally copy free variables
2215
       into the locals dict used by the class.
2216
    */
2217
0
    if (kind & CO_FAST_FREE && !(co->co_flags & CO_OPTIMIZED)) {
2218
0
        return 0;
2219
0
    }
2220
2221
0
    PyObject *value = NULL;
2222
0
    if (frame->stackpointer == NULL || frame->stackpointer > frame->localsplus + i) {
2223
0
        value = PyStackRef_AsPyObjectBorrow(frame->localsplus[i]);
2224
0
        if (kind & CO_FAST_FREE) {
2225
            // The cell was set by COPY_FREE_VARS.
2226
0
            assert(value != NULL && PyCell_Check(value));
2227
0
            value = PyCell_GetRef((PyCellObject *)value);
2228
0
        }
2229
0
        else if (kind & CO_FAST_CELL) {
2230
0
            if (value != NULL) {
2231
0
                if (PyCell_Check(value)) {
2232
0
                    assert(!_PyFrame_IsIncomplete(frame));
2233
0
                    value = PyCell_GetRef((PyCellObject *)value);
2234
0
                }
2235
0
                else {
2236
                    // (likely) Otherwise it is an arg (kind & CO_FAST_LOCAL),
2237
                    // with the initial value set when the frame was created...
2238
                    // (unlikely) ...or it was set via the f_locals proxy.
2239
0
                    Py_INCREF(value);
2240
0
                }
2241
0
            }
2242
0
        }
2243
0
        else {
2244
0
            Py_XINCREF(value);
2245
0
        }
2246
0
    }
2247
0
    *pvalue = value;
2248
0
    return 1;
2249
0
}
2250
2251
2252
bool
2253
_PyFrame_HasHiddenLocals(_PyInterpreterFrame *frame)
2254
270
{
2255
    /*
2256
     * This function returns if there are hidden locals introduced by PEP 709,
2257
     * which are the isolated fast locals for inline comprehensions
2258
     */
2259
270
    PyCodeObject* co = _PyFrame_GetCode(frame);
2260
2261
310
    for (int i = 0; i < co->co_nlocalsplus; i++) {
2262
40
        _PyLocals_Kind kind = _PyLocals_GetKind(co->co_localspluskinds, i);
2263
2264
40
        if (kind & CO_FAST_HIDDEN) {
2265
40
            if (framelocalsproxy_hasval(frame, co, i)) {
2266
0
                return true;
2267
0
            }
2268
40
        }
2269
40
    }
2270
2271
270
    return false;
2272
270
}
2273
2274
2275
PyObject *
2276
_PyFrame_GetLocals(_PyInterpreterFrame *frame)
2277
270
{
2278
    // We should try to avoid creating the FrameObject if possible.
2279
    // So we check if the frame is a module or class level scope
2280
270
    PyCodeObject *co = _PyFrame_GetCode(frame);
2281
2282
270
    if (!(co->co_flags & CO_OPTIMIZED) && !_PyFrame_HasHiddenLocals(frame)) {
2283
270
        if (frame->f_locals == NULL) {
2284
            // We found cases when f_locals is NULL for non-optimized code.
2285
            // We fill the f_locals with an empty dict to avoid crash until
2286
            // we find the root cause.
2287
0
            frame->f_locals = PyDict_New();
2288
0
            if (frame->f_locals == NULL) {
2289
0
                return NULL;
2290
0
            }
2291
0
        }
2292
270
        return Py_NewRef(frame->f_locals);
2293
270
    }
2294
2295
0
    PyFrameObject* f = _PyFrame_GetFrameObject(frame);
2296
2297
0
    return _PyFrameLocalsProxy_New(f);
2298
270
}
2299
2300
2301
PyObject *
2302
PyFrame_GetVar(PyFrameObject *frame_obj, PyObject *name)
2303
0
{
2304
0
    if (!PyUnicode_Check(name)) {
2305
0
        PyErr_Format(PyExc_TypeError, "name must be str, not %s",
2306
0
                     Py_TYPE(name)->tp_name);
2307
0
        return NULL;
2308
0
    }
2309
2310
0
    _PyInterpreterFrame *frame = frame_obj->f_frame;
2311
0
    frame_init_get_vars(frame);
2312
2313
0
    PyCodeObject *co = _PyFrame_GetCode(frame);
2314
0
    for (int i = 0; i < co->co_nlocalsplus; i++) {
2315
0
        PyObject *var_name = PyTuple_GET_ITEM(co->co_localsplusnames, i);
2316
0
        if (!_PyUnicode_Equal(var_name, name)) {
2317
0
            continue;
2318
0
        }
2319
2320
0
        PyObject *value;
2321
0
        if (!frame_get_var(frame, co, i, &value)) {
2322
0
            break;
2323
0
        }
2324
0
        if (value == NULL) {
2325
0
            break;
2326
0
        }
2327
0
        return value;
2328
0
    }
2329
2330
0
    PyErr_Format(PyExc_NameError, "variable %R does not exist", name);
2331
0
    return NULL;
2332
0
}
2333
2334
2335
PyObject *
2336
PyFrame_GetVarString(PyFrameObject *frame, const char *name)
2337
0
{
2338
0
    PyObject *name_obj = PyUnicode_FromString(name);
2339
0
    if (name_obj == NULL) {
2340
0
        return NULL;
2341
0
    }
2342
0
    PyObject *value = PyFrame_GetVar(frame, name_obj);
2343
0
    Py_DECREF(name_obj);
2344
0
    return value;
2345
0
}
2346
2347
2348
int
2349
PyFrame_FastToLocalsWithError(PyFrameObject *f)
2350
0
{
2351
    // Nothing to do here, as f_locals is now a write-through proxy in
2352
    // optimized frames. Soft-deprecated, since there's no maintenance hassle.
2353
0
    return 0;
2354
0
}
2355
2356
void
2357
PyFrame_FastToLocals(PyFrameObject *f)
2358
0
{
2359
    // Nothing to do here, as f_locals is now a write-through proxy in
2360
    // optimized frames. Soft-deprecated, since there's no maintenance hassle.
2361
0
    return;
2362
0
}
2363
2364
void
2365
PyFrame_LocalsToFast(PyFrameObject *f, int clear)
2366
0
{
2367
    // Nothing to do here, as f_locals is now a write-through proxy in
2368
    // optimized frames. Soft-deprecated, since there's no maintenance hassle.
2369
0
    return;
2370
0
}
2371
2372
int
2373
_PyFrame_IsEntryFrame(PyFrameObject *frame)
2374
0
{
2375
0
    assert(frame != NULL);
2376
0
    _PyInterpreterFrame *f = frame->f_frame;
2377
0
    assert(!_PyFrame_IsIncomplete(f));
2378
0
    return f->previous && f->previous->owner == FRAME_OWNED_BY_INTERPRETER;
2379
0
}
2380
2381
PyCodeObject *
2382
PyFrame_GetCode(PyFrameObject *frame)
2383
19.7M
{
2384
19.7M
    assert(frame != NULL);
2385
19.7M
    PyObject *code;
2386
19.7M
    Py_BEGIN_CRITICAL_SECTION(frame);
2387
19.7M
    assert(!_PyFrame_IsIncomplete(frame->f_frame));
2388
19.7M
    code = Py_NewRef(_PyFrame_GetCode(frame->f_frame));
2389
19.7M
    Py_END_CRITICAL_SECTION();
2390
19.7M
    return (PyCodeObject *)code;
2391
19.7M
}
2392
2393
2394
PyFrameObject*
2395
PyFrame_GetBack(PyFrameObject *frame)
2396
18.5M
{
2397
18.5M
    assert(frame != NULL);
2398
18.5M
    assert(!_PyFrame_IsIncomplete(frame->f_frame));
2399
18.5M
    PyFrameObject *back = frame->f_back;
2400
18.5M
    if (back == NULL) {
2401
18.5M
        _PyInterpreterFrame *prev = frame->f_frame->previous;
2402
18.5M
        prev = _PyFrame_GetFirstComplete(prev);
2403
18.5M
        if (prev) {
2404
18.5M
            back = _PyFrame_GetFrameObject(prev);
2405
18.5M
        }
2406
18.5M
    }
2407
18.5M
    return (PyFrameObject*)Py_XNewRef(back);
2408
18.5M
}
2409
2410
PyObject*
2411
PyFrame_GetLocals(PyFrameObject *frame)
2412
0
{
2413
0
    assert(!_PyFrame_IsIncomplete(frame->f_frame));
2414
0
    return frame_locals_get((PyObject *)frame, NULL);
2415
0
}
2416
2417
PyObject*
2418
PyFrame_GetGlobals(PyFrameObject *frame)
2419
0
{
2420
0
    assert(!_PyFrame_IsIncomplete(frame->f_frame));
2421
0
    return frame_globals_get((PyObject *)frame, NULL);
2422
0
}
2423
2424
PyObject*
2425
PyFrame_GetBuiltins(PyFrameObject *frame)
2426
0
{
2427
0
    assert(!_PyFrame_IsIncomplete(frame->f_frame));
2428
0
    return frame_builtins_get((PyObject *)frame, NULL);
2429
0
}
2430
2431
int
2432
PyFrame_GetLasti(PyFrameObject *frame)
2433
0
{
2434
0
    int ret;
2435
0
    Py_BEGIN_CRITICAL_SECTION(frame);
2436
0
    assert(!_PyFrame_IsIncomplete(frame->f_frame));
2437
0
    int lasti = _PyInterpreterFrame_LASTI(frame->f_frame);
2438
0
    ret = lasti < 0 ? -1 : lasti * (int)sizeof(_Py_CODEUNIT);
2439
0
    Py_END_CRITICAL_SECTION();
2440
0
    return ret;
2441
0
}
2442
2443
PyObject *
2444
PyFrame_GetGenerator(PyFrameObject *frame)
2445
0
{
2446
0
    assert(!_PyFrame_IsIncomplete(frame->f_frame));
2447
    return frame_generator_get((PyObject *)frame, NULL);
2448
0
}