Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
allendowney
GitHub Repository: allendowney/cpython
Path: blob/main/Objects/frameobject.c
12 views
1
/* Frame object implementation */
2
3
#include "Python.h"
4
#include "pycore_ceval.h" // _PyEval_BuiltinsFromGlobals()
5
#include "pycore_code.h" // CO_FAST_LOCAL, etc.
6
#include "pycore_function.h" // _PyFunction_FromConstructor()
7
#include "pycore_moduleobject.h" // _PyModule_GetDict()
8
#include "pycore_object.h" // _PyObject_GC_UNTRACK()
9
#include "pycore_opcode.h" // _PyOpcode_Caches
10
11
#include "frameobject.h" // PyFrameObject
12
#include "pycore_frame.h"
13
#include "opcode.h" // EXTENDED_ARG
14
#include "structmember.h" // PyMemberDef
15
16
#define OFF(x) offsetof(PyFrameObject, x)
17
18
static PyMemberDef frame_memberlist[] = {
19
{"f_trace_lines", T_BOOL, OFF(f_trace_lines), 0},
20
{NULL} /* Sentinel */
21
};
22
23
24
static PyObject *
25
frame_getlocals(PyFrameObject *f, void *closure)
26
{
27
if (PyFrame_FastToLocalsWithError(f) < 0)
28
return NULL;
29
PyObject *locals = f->f_frame->f_locals;
30
return Py_NewRef(locals);
31
}
32
33
int
34
PyFrame_GetLineNumber(PyFrameObject *f)
35
{
36
assert(f != NULL);
37
if (f->f_lineno != 0) {
38
return f->f_lineno;
39
}
40
else {
41
return PyUnstable_InterpreterFrame_GetLine(f->f_frame);
42
}
43
}
44
45
static PyObject *
46
frame_getlineno(PyFrameObject *f, void *closure)
47
{
48
int lineno = PyFrame_GetLineNumber(f);
49
if (lineno < 0) {
50
Py_RETURN_NONE;
51
}
52
else {
53
return PyLong_FromLong(lineno);
54
}
55
}
56
57
static PyObject *
58
frame_getlasti(PyFrameObject *f, void *closure)
59
{
60
int lasti = _PyInterpreterFrame_LASTI(f->f_frame);
61
if (lasti < 0) {
62
return PyLong_FromLong(-1);
63
}
64
return PyLong_FromLong(lasti * sizeof(_Py_CODEUNIT));
65
}
66
67
static PyObject *
68
frame_getglobals(PyFrameObject *f, void *closure)
69
{
70
PyObject *globals = f->f_frame->f_globals;
71
if (globals == NULL) {
72
globals = Py_None;
73
}
74
return Py_NewRef(globals);
75
}
76
77
static PyObject *
78
frame_getbuiltins(PyFrameObject *f, void *closure)
79
{
80
PyObject *builtins = f->f_frame->f_builtins;
81
if (builtins == NULL) {
82
builtins = Py_None;
83
}
84
return Py_NewRef(builtins);
85
}
86
87
static PyObject *
88
frame_getcode(PyFrameObject *f, void *closure)
89
{
90
if (PySys_Audit("object.__getattr__", "Os", f, "f_code") < 0) {
91
return NULL;
92
}
93
return (PyObject *)PyFrame_GetCode(f);
94
}
95
96
static PyObject *
97
frame_getback(PyFrameObject *f, void *closure)
98
{
99
PyObject *res = (PyObject *)PyFrame_GetBack(f);
100
if (res == NULL) {
101
Py_RETURN_NONE;
102
}
103
return res;
104
}
105
106
static PyObject *
107
frame_gettrace_opcodes(PyFrameObject *f, void *closure)
108
{
109
PyObject *result = f->f_trace_opcodes ? Py_True : Py_False;
110
return Py_NewRef(result);
111
}
112
113
static int
114
frame_settrace_opcodes(PyFrameObject *f, PyObject* value, void *Py_UNUSED(ignored))
115
{
116
if (!PyBool_Check(value)) {
117
PyErr_SetString(PyExc_TypeError,
118
"attribute value type must be bool");
119
return -1;
120
}
121
if (value == Py_True) {
122
f->f_trace_opcodes = 1;
123
_PyInterpreterState_GET()->f_opcode_trace_set = true;
124
}
125
else {
126
f->f_trace_opcodes = 0;
127
}
128
return 0;
129
}
130
131
/* Model the evaluation stack, to determine which jumps
132
* are safe and how many values needs to be popped.
133
* The stack is modelled by a 64 integer, treating any
134
* stack that can't fit into 64 bits as "overflowed".
135
*/
136
137
typedef enum kind {
138
Iterator = 1,
139
Except = 2,
140
Object = 3,
141
Null = 4,
142
Lasti = 5,
143
} Kind;
144
145
static int
146
compatible_kind(Kind from, Kind to) {
147
if (to == 0) {
148
return 0;
149
}
150
if (to == Object) {
151
return from != Null;
152
}
153
if (to == Null) {
154
return 1;
155
}
156
return from == to;
157
}
158
159
#define BITS_PER_BLOCK 3
160
161
#define UNINITIALIZED -2
162
#define OVERFLOWED -1
163
164
#define MAX_STACK_ENTRIES (63/BITS_PER_BLOCK)
165
#define WILL_OVERFLOW (1ULL<<((MAX_STACK_ENTRIES-1)*BITS_PER_BLOCK))
166
167
#define EMPTY_STACK 0
168
169
static inline int64_t
170
push_value(int64_t stack, Kind kind)
171
{
172
if (((uint64_t)stack) >= WILL_OVERFLOW) {
173
return OVERFLOWED;
174
}
175
else {
176
return (stack << BITS_PER_BLOCK) | kind;
177
}
178
}
179
180
static inline int64_t
181
pop_value(int64_t stack)
182
{
183
return Py_ARITHMETIC_RIGHT_SHIFT(int64_t, stack, BITS_PER_BLOCK);
184
}
185
186
#define MASK ((1<<BITS_PER_BLOCK)-1)
187
188
static inline Kind
189
top_of_stack(int64_t stack)
190
{
191
return stack & MASK;
192
}
193
194
static inline Kind
195
peek(int64_t stack, int n)
196
{
197
assert(n >= 1);
198
return (stack>>(BITS_PER_BLOCK*(n-1))) & MASK;
199
}
200
201
static Kind
202
stack_swap(int64_t stack, int n)
203
{
204
assert(n >= 1);
205
Kind to_swap = peek(stack, n);
206
Kind top = top_of_stack(stack);
207
int shift = BITS_PER_BLOCK*(n-1);
208
int64_t replaced_low = (stack & ~(MASK << shift)) | (top << shift);
209
int64_t replaced_top = (replaced_low & ~MASK) | to_swap;
210
return replaced_top;
211
}
212
213
static int64_t
214
pop_to_level(int64_t stack, int level) {
215
if (level == 0) {
216
return EMPTY_STACK;
217
}
218
int64_t max_item = (1<<BITS_PER_BLOCK) - 1;
219
int64_t level_max_stack = max_item << ((level-1) * BITS_PER_BLOCK);
220
while (stack > level_max_stack) {
221
stack = pop_value(stack);
222
}
223
return stack;
224
}
225
226
#if 0
227
/* These functions are useful for debugging the stack marking code */
228
229
static char
230
tos_char(int64_t stack) {
231
switch(top_of_stack(stack)) {
232
case Iterator:
233
return 'I';
234
case Except:
235
return 'E';
236
case Object:
237
return 'O';
238
case Lasti:
239
return 'L';
240
case Null:
241
return 'N';
242
}
243
return '?';
244
}
245
246
static void
247
print_stack(int64_t stack) {
248
if (stack < 0) {
249
if (stack == UNINITIALIZED) {
250
printf("---");
251
}
252
else if (stack == OVERFLOWED) {
253
printf("OVERFLOWED");
254
}
255
else {
256
printf("??");
257
}
258
return;
259
}
260
while (stack) {
261
printf("%c", tos_char(stack));
262
stack = pop_value(stack);
263
}
264
}
265
266
static void
267
print_stacks(int64_t *stacks, int n) {
268
for (int i = 0; i < n; i++) {
269
printf("%d: ", i);
270
print_stack(stacks[i]);
271
printf("\n");
272
}
273
}
274
275
#endif
276
277
static int64_t *
278
mark_stacks(PyCodeObject *code_obj, int len)
279
{
280
PyObject *co_code = _PyCode_GetCode(code_obj);
281
if (co_code == NULL) {
282
return NULL;
283
}
284
_Py_CODEUNIT *code = (_Py_CODEUNIT *)PyBytes_AS_STRING(co_code);
285
int64_t *stacks = PyMem_New(int64_t, len+1);
286
int i, j, opcode;
287
288
if (stacks == NULL) {
289
PyErr_NoMemory();
290
Py_DECREF(co_code);
291
return NULL;
292
}
293
for (int i = 1; i <= len; i++) {
294
stacks[i] = UNINITIALIZED;
295
}
296
stacks[0] = EMPTY_STACK;
297
if (code_obj->co_flags & (CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR))
298
{
299
// Generators get sent None while starting:
300
stacks[0] = push_value(stacks[0], Object);
301
}
302
int todo = 1;
303
while (todo) {
304
todo = 0;
305
/* Scan instructions */
306
for (i = 0; i < len;) {
307
int64_t next_stack = stacks[i];
308
opcode = _Py_GetBaseOpcode(code_obj, i);
309
int oparg = 0;
310
while (opcode == EXTENDED_ARG) {
311
oparg = (oparg << 8) | code[i].op.arg;
312
i++;
313
opcode = _Py_GetBaseOpcode(code_obj, i);
314
stacks[i] = next_stack;
315
}
316
int next_i = i + _PyOpcode_Caches[opcode] + 1;
317
if (next_stack == UNINITIALIZED) {
318
i = next_i;
319
continue;
320
}
321
oparg = (oparg << 8) | code[i].op.arg;
322
switch (opcode) {
323
case POP_JUMP_IF_FALSE:
324
case POP_JUMP_IF_TRUE:
325
{
326
int64_t target_stack;
327
int j = next_i + oparg;
328
assert(j < len);
329
next_stack = pop_value(next_stack);
330
target_stack = next_stack;
331
assert(stacks[j] == UNINITIALIZED || stacks[j] == target_stack);
332
stacks[j] = target_stack;
333
stacks[next_i] = next_stack;
334
break;
335
}
336
case SEND:
337
j = oparg + i + INLINE_CACHE_ENTRIES_SEND + 1;
338
assert(j < len);
339
assert(stacks[j] == UNINITIALIZED || stacks[j] == next_stack);
340
stacks[j] = next_stack;
341
stacks[next_i] = next_stack;
342
break;
343
case JUMP_FORWARD:
344
j = oparg + i + 1;
345
assert(j < len);
346
assert(stacks[j] == UNINITIALIZED || stacks[j] == next_stack);
347
stacks[j] = next_stack;
348
break;
349
case JUMP_BACKWARD:
350
case JUMP_BACKWARD_NO_INTERRUPT:
351
j = next_i - oparg;
352
assert(j >= 0);
353
assert(j < len);
354
if (stacks[j] == UNINITIALIZED && j < i) {
355
todo = 1;
356
}
357
assert(stacks[j] == UNINITIALIZED || stacks[j] == next_stack);
358
stacks[j] = next_stack;
359
break;
360
case GET_ITER:
361
case GET_AITER:
362
next_stack = push_value(pop_value(next_stack), Iterator);
363
stacks[next_i] = next_stack;
364
break;
365
case FOR_ITER:
366
{
367
int64_t target_stack = push_value(next_stack, Object);
368
stacks[next_i] = target_stack;
369
j = oparg + 1 + INLINE_CACHE_ENTRIES_FOR_ITER + i;
370
assert(j < len);
371
assert(stacks[j] == UNINITIALIZED || stacks[j] == target_stack);
372
stacks[j] = target_stack;
373
break;
374
}
375
case END_ASYNC_FOR:
376
next_stack = pop_value(pop_value(next_stack));
377
stacks[next_i] = next_stack;
378
break;
379
case PUSH_EXC_INFO:
380
next_stack = push_value(next_stack, Except);
381
stacks[next_i] = next_stack;
382
break;
383
case POP_EXCEPT:
384
assert(top_of_stack(next_stack) == Except);
385
next_stack = pop_value(next_stack);
386
stacks[next_i] = next_stack;
387
break;
388
case RETURN_VALUE:
389
assert(pop_value(next_stack) == EMPTY_STACK);
390
assert(top_of_stack(next_stack) == Object);
391
break;
392
case RETURN_CONST:
393
break;
394
case RAISE_VARARGS:
395
break;
396
case RERAISE:
397
assert(top_of_stack(next_stack) == Except);
398
/* End of block */
399
break;
400
case PUSH_NULL:
401
next_stack = push_value(next_stack, Null);
402
stacks[next_i] = next_stack;
403
break;
404
case LOAD_GLOBAL:
405
{
406
int j = oparg;
407
if (j & 1) {
408
next_stack = push_value(next_stack, Null);
409
}
410
next_stack = push_value(next_stack, Object);
411
stacks[next_i] = next_stack;
412
break;
413
}
414
case LOAD_ATTR:
415
{
416
assert(top_of_stack(next_stack) == Object);
417
int j = oparg;
418
if (j & 1) {
419
next_stack = pop_value(next_stack);
420
next_stack = push_value(next_stack, Null);
421
next_stack = push_value(next_stack, Object);
422
}
423
stacks[next_i] = next_stack;
424
break;
425
}
426
case CALL:
427
{
428
int args = oparg;
429
for (int j = 0; j < args+2; j++) {
430
next_stack = pop_value(next_stack);
431
}
432
next_stack = push_value(next_stack, Object);
433
stacks[next_i] = next_stack;
434
break;
435
}
436
case SWAP:
437
{
438
int n = oparg;
439
next_stack = stack_swap(next_stack, n);
440
stacks[next_i] = next_stack;
441
break;
442
}
443
case COPY:
444
{
445
int n = oparg;
446
next_stack = push_value(next_stack, peek(next_stack, n));
447
stacks[next_i] = next_stack;
448
break;
449
}
450
case CACHE:
451
case RESERVED:
452
{
453
assert(0);
454
}
455
default:
456
{
457
int delta = PyCompile_OpcodeStackEffect(opcode, oparg);
458
assert(delta != PY_INVALID_STACK_EFFECT);
459
while (delta < 0) {
460
next_stack = pop_value(next_stack);
461
delta++;
462
}
463
while (delta > 0) {
464
next_stack = push_value(next_stack, Object);
465
delta--;
466
}
467
stacks[next_i] = next_stack;
468
}
469
}
470
i = next_i;
471
}
472
/* Scan exception table */
473
unsigned char *start = (unsigned char *)PyBytes_AS_STRING(code_obj->co_exceptiontable);
474
unsigned char *end = start + PyBytes_GET_SIZE(code_obj->co_exceptiontable);
475
unsigned char *scan = start;
476
while (scan < end) {
477
int start_offset, size, handler;
478
scan = parse_varint(scan, &start_offset);
479
assert(start_offset >= 0 && start_offset < len);
480
scan = parse_varint(scan, &size);
481
assert(size >= 0 && start_offset+size <= len);
482
scan = parse_varint(scan, &handler);
483
assert(handler >= 0 && handler < len);
484
int depth_and_lasti;
485
scan = parse_varint(scan, &depth_and_lasti);
486
int level = depth_and_lasti >> 1;
487
int lasti = depth_and_lasti & 1;
488
if (stacks[start_offset] != UNINITIALIZED) {
489
if (stacks[handler] == UNINITIALIZED) {
490
todo = 1;
491
uint64_t target_stack = pop_to_level(stacks[start_offset], level);
492
if (lasti) {
493
target_stack = push_value(target_stack, Lasti);
494
}
495
target_stack = push_value(target_stack, Except);
496
stacks[handler] = target_stack;
497
}
498
}
499
}
500
}
501
Py_DECREF(co_code);
502
return stacks;
503
}
504
505
static int
506
compatible_stack(int64_t from_stack, int64_t to_stack)
507
{
508
if (from_stack < 0 || to_stack < 0) {
509
return 0;
510
}
511
while(from_stack > to_stack) {
512
from_stack = pop_value(from_stack);
513
}
514
while(from_stack) {
515
Kind from_top = top_of_stack(from_stack);
516
Kind to_top = top_of_stack(to_stack);
517
if (!compatible_kind(from_top, to_top)) {
518
return 0;
519
}
520
from_stack = pop_value(from_stack);
521
to_stack = pop_value(to_stack);
522
}
523
return to_stack == 0;
524
}
525
526
static const char *
527
explain_incompatible_stack(int64_t to_stack)
528
{
529
assert(to_stack != 0);
530
if (to_stack == OVERFLOWED) {
531
return "stack is too deep to analyze";
532
}
533
if (to_stack == UNINITIALIZED) {
534
return "can't jump into an exception handler, or code may be unreachable";
535
}
536
Kind target_kind = top_of_stack(to_stack);
537
switch(target_kind) {
538
case Except:
539
return "can't jump into an 'except' block as there's no exception";
540
case Lasti:
541
return "can't jump into a re-raising block as there's no location";
542
case Object:
543
case Null:
544
return "incompatible stacks";
545
case Iterator:
546
return "can't jump into the body of a for loop";
547
default:
548
Py_UNREACHABLE();
549
}
550
}
551
552
static int *
553
marklines(PyCodeObject *code, int len)
554
{
555
PyCodeAddressRange bounds;
556
_PyCode_InitAddressRange(code, &bounds);
557
assert (bounds.ar_end == 0);
558
int last_line = -1;
559
560
int *linestarts = PyMem_New(int, len);
561
if (linestarts == NULL) {
562
return NULL;
563
}
564
for (int i = 0; i < len; i++) {
565
linestarts[i] = -1;
566
}
567
568
while (_PyLineTable_NextAddressRange(&bounds)) {
569
assert(bounds.ar_start / (int)sizeof(_Py_CODEUNIT) < len);
570
if (bounds.ar_line != last_line && bounds.ar_line != -1) {
571
linestarts[bounds.ar_start / sizeof(_Py_CODEUNIT)] = bounds.ar_line;
572
last_line = bounds.ar_line;
573
}
574
}
575
return linestarts;
576
}
577
578
static int
579
first_line_not_before(int *lines, int len, int line)
580
{
581
int result = INT_MAX;
582
for (int i = 0; i < len; i++) {
583
if (lines[i] < result && lines[i] >= line) {
584
result = lines[i];
585
}
586
}
587
if (result == INT_MAX) {
588
return -1;
589
}
590
return result;
591
}
592
593
static PyFrameState
594
_PyFrame_GetState(PyFrameObject *frame)
595
{
596
assert(!_PyFrame_IsIncomplete(frame->f_frame));
597
if (frame->f_frame->stacktop == 0) {
598
return FRAME_CLEARED;
599
}
600
switch(frame->f_frame->owner) {
601
case FRAME_OWNED_BY_GENERATOR:
602
{
603
PyGenObject *gen = _PyFrame_GetGenerator(frame->f_frame);
604
return gen->gi_frame_state;
605
}
606
case FRAME_OWNED_BY_THREAD:
607
{
608
if (_PyInterpreterFrame_LASTI(frame->f_frame) < 0) {
609
return FRAME_CREATED;
610
}
611
switch (frame->f_frame->prev_instr->op.code)
612
{
613
case COPY_FREE_VARS:
614
case MAKE_CELL:
615
case RETURN_GENERATOR:
616
/* Frame not fully initialized */
617
return FRAME_CREATED;
618
default:
619
return FRAME_EXECUTING;
620
}
621
}
622
case FRAME_OWNED_BY_FRAME_OBJECT:
623
return FRAME_COMPLETED;
624
}
625
Py_UNREACHABLE();
626
}
627
628
/* Setter for f_lineno - you can set f_lineno from within a trace function in
629
* order to jump to a given line of code, subject to some restrictions. Most
630
* lines are OK to jump to because they don't make any assumptions about the
631
* state of the stack (obvious because you could remove the line and the code
632
* would still work without any stack errors), but there are some constructs
633
* that limit jumping:
634
*
635
* o Any exception handlers.
636
* o 'for' and 'async for' loops can't be jumped into because the
637
* iterator needs to be on the stack.
638
* o Jumps cannot be made from within a trace function invoked with a
639
* 'return' or 'exception' event since the eval loop has been exited at
640
* that time.
641
*/
642
static int
643
frame_setlineno(PyFrameObject *f, PyObject* p_new_lineno, void *Py_UNUSED(ignored))
644
{
645
PyCodeObject *code = _PyFrame_GetCode(f->f_frame);
646
if (p_new_lineno == NULL) {
647
PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
648
return -1;
649
}
650
/* f_lineno must be an integer. */
651
if (!PyLong_CheckExact(p_new_lineno)) {
652
PyErr_SetString(PyExc_ValueError,
653
"lineno must be an integer");
654
return -1;
655
}
656
657
PyFrameState state = _PyFrame_GetState(f);
658
/*
659
* This code preserves the historical restrictions on
660
* setting the line number of a frame.
661
* Jumps are forbidden on a 'return' trace event (except after a yield).
662
* Jumps from 'call' trace events are also forbidden.
663
* In addition, jumps are forbidden when not tracing,
664
* as this is a debugging feature.
665
*/
666
int what_event = PyThreadState_GET()->what_event;
667
if (what_event < 0) {
668
PyErr_Format(PyExc_ValueError,
669
"f_lineno can only be set in a trace function");
670
return -1;
671
}
672
switch (what_event) {
673
case PY_MONITORING_EVENT_PY_RESUME:
674
case PY_MONITORING_EVENT_JUMP:
675
case PY_MONITORING_EVENT_BRANCH:
676
case PY_MONITORING_EVENT_LINE:
677
case PY_MONITORING_EVENT_PY_YIELD:
678
/* Setting f_lineno is allowed for the above events */
679
break;
680
case PY_MONITORING_EVENT_PY_START:
681
PyErr_Format(PyExc_ValueError,
682
"can't jump from the 'call' trace event of a new frame");
683
return -1;
684
case PY_MONITORING_EVENT_CALL:
685
case PY_MONITORING_EVENT_C_RETURN:
686
PyErr_SetString(PyExc_ValueError,
687
"can't jump during a call");
688
return -1;
689
case PY_MONITORING_EVENT_PY_RETURN:
690
case PY_MONITORING_EVENT_PY_UNWIND:
691
case PY_MONITORING_EVENT_PY_THROW:
692
case PY_MONITORING_EVENT_RAISE:
693
case PY_MONITORING_EVENT_C_RAISE:
694
case PY_MONITORING_EVENT_INSTRUCTION:
695
case PY_MONITORING_EVENT_EXCEPTION_HANDLED:
696
PyErr_Format(PyExc_ValueError,
697
"can only jump from a 'line' trace event");
698
return -1;
699
default:
700
PyErr_SetString(PyExc_SystemError,
701
"unexpected event type");
702
return -1;
703
}
704
705
int new_lineno;
706
707
/* Fail if the line falls outside the code block and
708
select first line with actual code. */
709
int overflow;
710
long l_new_lineno = PyLong_AsLongAndOverflow(p_new_lineno, &overflow);
711
if (overflow
712
#if SIZEOF_LONG > SIZEOF_INT
713
|| l_new_lineno > INT_MAX
714
|| l_new_lineno < INT_MIN
715
#endif
716
) {
717
PyErr_SetString(PyExc_ValueError,
718
"lineno out of range");
719
return -1;
720
}
721
new_lineno = (int)l_new_lineno;
722
723
if (new_lineno < code->co_firstlineno) {
724
PyErr_Format(PyExc_ValueError,
725
"line %d comes before the current code block",
726
new_lineno);
727
return -1;
728
}
729
730
/* PyCode_NewWithPosOnlyArgs limits co_code to be under INT_MAX so this
731
* should never overflow. */
732
int len = (int)Py_SIZE(code);
733
int *lines = marklines(code, len);
734
if (lines == NULL) {
735
return -1;
736
}
737
738
new_lineno = first_line_not_before(lines, len, new_lineno);
739
if (new_lineno < 0) {
740
PyErr_Format(PyExc_ValueError,
741
"line %d comes after the current code block",
742
(int)l_new_lineno);
743
PyMem_Free(lines);
744
return -1;
745
}
746
747
int64_t *stacks = mark_stacks(code, len);
748
if (stacks == NULL) {
749
PyMem_Free(lines);
750
return -1;
751
}
752
753
int64_t best_stack = OVERFLOWED;
754
int best_addr = -1;
755
int64_t start_stack = stacks[_PyInterpreterFrame_LASTI(f->f_frame)];
756
int err = -1;
757
const char *msg = "cannot find bytecode for specified line";
758
for (int i = 0; i < len; i++) {
759
if (lines[i] == new_lineno) {
760
int64_t target_stack = stacks[i];
761
if (compatible_stack(start_stack, target_stack)) {
762
err = 0;
763
if (target_stack > best_stack) {
764
best_stack = target_stack;
765
best_addr = i;
766
}
767
}
768
else if (err < 0) {
769
if (start_stack == OVERFLOWED) {
770
msg = "stack to deep to analyze";
771
}
772
else if (start_stack == UNINITIALIZED) {
773
msg = "can't jump from unreachable code";
774
}
775
else {
776
msg = explain_incompatible_stack(target_stack);
777
err = 1;
778
}
779
}
780
}
781
}
782
PyMem_Free(stacks);
783
PyMem_Free(lines);
784
if (err) {
785
PyErr_SetString(PyExc_ValueError, msg);
786
return -1;
787
}
788
// Populate any NULL locals that the compiler might have "proven" to exist
789
// in the new location. Rather than crashing or changing co_code, just bind
790
// None instead:
791
int unbound = 0;
792
for (int i = 0; i < code->co_nlocalsplus; i++) {
793
// Counting every unbound local is overly-cautious, but a full flow
794
// analysis (like we do in the compiler) is probably too expensive:
795
unbound += f->f_frame->localsplus[i] == NULL;
796
}
797
if (unbound) {
798
const char *e = "assigning None to %d unbound local%s";
799
const char *s = (unbound == 1) ? "" : "s";
800
if (PyErr_WarnFormat(PyExc_RuntimeWarning, 0, e, unbound, s)) {
801
return -1;
802
}
803
// Do this in a second pass to avoid writing a bunch of Nones when
804
// warnings are being treated as errors and the previous bit raises:
805
for (int i = 0; i < code->co_nlocalsplus; i++) {
806
if (f->f_frame->localsplus[i] == NULL) {
807
f->f_frame->localsplus[i] = Py_NewRef(Py_None);
808
unbound--;
809
}
810
}
811
assert(unbound == 0);
812
}
813
if (state == FRAME_SUSPENDED) {
814
/* Account for value popped by yield */
815
start_stack = pop_value(start_stack);
816
}
817
while (start_stack > best_stack) {
818
if (top_of_stack(start_stack) == Except) {
819
/* Pop exception stack as well as the evaluation stack */
820
PyThreadState *tstate = _PyThreadState_GET();
821
_PyErr_StackItem *exc_info = tstate->exc_info;
822
PyObject *value = exc_info->exc_value;
823
PyObject *exc = _PyFrame_StackPop(f->f_frame);
824
assert(PyExceptionInstance_Check(exc) || exc == Py_None);
825
exc_info->exc_value = exc;
826
Py_XDECREF(value);
827
}
828
else {
829
PyObject *v = _PyFrame_StackPop(f->f_frame);
830
Py_XDECREF(v);
831
}
832
start_stack = pop_value(start_stack);
833
}
834
/* Finally set the new lasti and return OK. */
835
f->f_lineno = 0;
836
f->f_frame->prev_instr = _PyCode_CODE(code) + best_addr;
837
return 0;
838
}
839
840
static PyObject *
841
frame_gettrace(PyFrameObject *f, void *closure)
842
{
843
PyObject* trace = f->f_trace;
844
if (trace == NULL)
845
trace = Py_None;
846
return Py_NewRef(trace);
847
}
848
849
static int
850
frame_settrace(PyFrameObject *f, PyObject* v, void *closure)
851
{
852
if (v == Py_None) {
853
v = NULL;
854
}
855
if (v != f->f_trace) {
856
Py_XSETREF(f->f_trace, Py_XNewRef(v));
857
}
858
return 0;
859
}
860
861
862
static PyGetSetDef frame_getsetlist[] = {
863
{"f_back", (getter)frame_getback, NULL, NULL},
864
{"f_locals", (getter)frame_getlocals, NULL, NULL},
865
{"f_lineno", (getter)frame_getlineno,
866
(setter)frame_setlineno, NULL},
867
{"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL},
868
{"f_lasti", (getter)frame_getlasti, NULL, NULL},
869
{"f_globals", (getter)frame_getglobals, NULL, NULL},
870
{"f_builtins", (getter)frame_getbuiltins, NULL, NULL},
871
{"f_code", (getter)frame_getcode, NULL, NULL},
872
{"f_trace_opcodes", (getter)frame_gettrace_opcodes, (setter)frame_settrace_opcodes, NULL},
873
{0}
874
};
875
876
static void
877
frame_dealloc(PyFrameObject *f)
878
{
879
/* It is the responsibility of the owning generator/coroutine
880
* to have cleared the generator pointer */
881
882
assert(f->f_frame->owner != FRAME_OWNED_BY_GENERATOR ||
883
_PyFrame_GetGenerator(f->f_frame)->gi_frame_state == FRAME_CLEARED);
884
885
if (_PyObject_GC_IS_TRACKED(f)) {
886
_PyObject_GC_UNTRACK(f);
887
}
888
889
Py_TRASHCAN_BEGIN(f, frame_dealloc);
890
PyObject *co = NULL;
891
892
/* Kill all local variables including specials, if we own them */
893
if (f->f_frame->owner == FRAME_OWNED_BY_FRAME_OBJECT) {
894
assert(f->f_frame == (_PyInterpreterFrame *)f->_f_frame_data);
895
_PyInterpreterFrame *frame = (_PyInterpreterFrame *)f->_f_frame_data;
896
/* Don't clear code object until the end */
897
co = frame->f_executable;
898
frame->f_executable = NULL;
899
Py_CLEAR(frame->f_funcobj);
900
Py_CLEAR(frame->f_locals);
901
PyObject **locals = _PyFrame_GetLocalsArray(frame);
902
for (int i = 0; i < frame->stacktop; i++) {
903
Py_CLEAR(locals[i]);
904
}
905
}
906
Py_CLEAR(f->f_back);
907
Py_CLEAR(f->f_trace);
908
PyObject_GC_Del(f);
909
Py_XDECREF(co);
910
Py_TRASHCAN_END;
911
}
912
913
static int
914
frame_traverse(PyFrameObject *f, visitproc visit, void *arg)
915
{
916
Py_VISIT(f->f_back);
917
Py_VISIT(f->f_trace);
918
if (f->f_frame->owner != FRAME_OWNED_BY_FRAME_OBJECT) {
919
return 0;
920
}
921
assert(f->f_frame->frame_obj == NULL);
922
return _PyFrame_Traverse(f->f_frame, visit, arg);
923
}
924
925
static int
926
frame_tp_clear(PyFrameObject *f)
927
{
928
Py_CLEAR(f->f_trace);
929
930
/* locals and stack */
931
PyObject **locals = _PyFrame_GetLocalsArray(f->f_frame);
932
assert(f->f_frame->stacktop >= 0);
933
for (int i = 0; i < f->f_frame->stacktop; i++) {
934
Py_CLEAR(locals[i]);
935
}
936
f->f_frame->stacktop = 0;
937
return 0;
938
}
939
940
static PyObject *
941
frame_clear(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
942
{
943
if (f->f_frame->owner == FRAME_OWNED_BY_GENERATOR) {
944
PyGenObject *gen = _PyFrame_GetGenerator(f->f_frame);
945
if (gen->gi_frame_state == FRAME_EXECUTING) {
946
goto running;
947
}
948
_PyGen_Finalize((PyObject *)gen);
949
}
950
else if (f->f_frame->owner == FRAME_OWNED_BY_THREAD) {
951
goto running;
952
}
953
else {
954
assert(f->f_frame->owner == FRAME_OWNED_BY_FRAME_OBJECT);
955
(void)frame_tp_clear(f);
956
}
957
Py_RETURN_NONE;
958
running:
959
PyErr_SetString(PyExc_RuntimeError,
960
"cannot clear an executing frame");
961
return NULL;
962
}
963
964
PyDoc_STRVAR(clear__doc__,
965
"F.clear(): clear most references held by the frame");
966
967
static PyObject *
968
frame_sizeof(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
969
{
970
Py_ssize_t res;
971
res = offsetof(PyFrameObject, _f_frame_data) + offsetof(_PyInterpreterFrame, localsplus);
972
PyCodeObject *code = _PyFrame_GetCode(f->f_frame);
973
res += _PyFrame_NumSlotsForCodeObject(code) * sizeof(PyObject *);
974
return PyLong_FromSsize_t(res);
975
}
976
977
PyDoc_STRVAR(sizeof__doc__,
978
"F.__sizeof__() -> size of F in memory, in bytes");
979
980
static PyObject *
981
frame_repr(PyFrameObject *f)
982
{
983
int lineno = PyFrame_GetLineNumber(f);
984
PyCodeObject *code = _PyFrame_GetCode(f->f_frame);
985
return PyUnicode_FromFormat(
986
"<frame at %p, file %R, line %d, code %S>",
987
f, code->co_filename, lineno, code->co_name);
988
}
989
990
static PyMethodDef frame_methods[] = {
991
{"clear", (PyCFunction)frame_clear, METH_NOARGS,
992
clear__doc__},
993
{"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS,
994
sizeof__doc__},
995
{NULL, NULL} /* sentinel */
996
};
997
998
PyTypeObject PyFrame_Type = {
999
PyVarObject_HEAD_INIT(&PyType_Type, 0)
1000
"frame",
1001
offsetof(PyFrameObject, _f_frame_data) +
1002
offsetof(_PyInterpreterFrame, localsplus),
1003
sizeof(PyObject *),
1004
(destructor)frame_dealloc, /* tp_dealloc */
1005
0, /* tp_vectorcall_offset */
1006
0, /* tp_getattr */
1007
0, /* tp_setattr */
1008
0, /* tp_as_async */
1009
(reprfunc)frame_repr, /* tp_repr */
1010
0, /* tp_as_number */
1011
0, /* tp_as_sequence */
1012
0, /* tp_as_mapping */
1013
0, /* tp_hash */
1014
0, /* tp_call */
1015
0, /* tp_str */
1016
PyObject_GenericGetAttr, /* tp_getattro */
1017
PyObject_GenericSetAttr, /* tp_setattro */
1018
0, /* tp_as_buffer */
1019
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
1020
0, /* tp_doc */
1021
(traverseproc)frame_traverse, /* tp_traverse */
1022
(inquiry)frame_tp_clear, /* tp_clear */
1023
0, /* tp_richcompare */
1024
0, /* tp_weaklistoffset */
1025
0, /* tp_iter */
1026
0, /* tp_iternext */
1027
frame_methods, /* tp_methods */
1028
frame_memberlist, /* tp_members */
1029
frame_getsetlist, /* tp_getset */
1030
0, /* tp_base */
1031
0, /* tp_dict */
1032
};
1033
1034
static void
1035
init_frame(_PyInterpreterFrame *frame, PyFunctionObject *func, PyObject *locals)
1036
{
1037
PyCodeObject *code = (PyCodeObject *)func->func_code;
1038
_PyFrame_Initialize(frame, (PyFunctionObject*)Py_NewRef(func),
1039
Py_XNewRef(locals), code, 0);
1040
frame->previous = NULL;
1041
}
1042
1043
PyFrameObject*
1044
_PyFrame_New_NoTrack(PyCodeObject *code)
1045
{
1046
CALL_STAT_INC(frame_objects_created);
1047
int slots = code->co_nlocalsplus + code->co_stacksize;
1048
PyFrameObject *f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type, slots);
1049
if (f == NULL) {
1050
return NULL;
1051
}
1052
f->f_back = NULL;
1053
f->f_trace = NULL;
1054
f->f_trace_lines = 1;
1055
f->f_trace_opcodes = 0;
1056
f->f_fast_as_locals = 0;
1057
f->f_lineno = 0;
1058
return f;
1059
}
1060
1061
/* Legacy API */
1062
PyFrameObject*
1063
PyFrame_New(PyThreadState *tstate, PyCodeObject *code,
1064
PyObject *globals, PyObject *locals)
1065
{
1066
PyObject *builtins = _PyEval_BuiltinsFromGlobals(tstate, globals); // borrowed ref
1067
if (builtins == NULL) {
1068
return NULL;
1069
}
1070
PyFrameConstructor desc = {
1071
.fc_globals = globals,
1072
.fc_builtins = builtins,
1073
.fc_name = code->co_name,
1074
.fc_qualname = code->co_name,
1075
.fc_code = (PyObject *)code,
1076
.fc_defaults = NULL,
1077
.fc_kwdefaults = NULL,
1078
.fc_closure = NULL
1079
};
1080
PyFunctionObject *func = _PyFunction_FromConstructor(&desc);
1081
if (func == NULL) {
1082
return NULL;
1083
}
1084
PyFrameObject *f = _PyFrame_New_NoTrack(code);
1085
if (f == NULL) {
1086
Py_DECREF(func);
1087
return NULL;
1088
}
1089
init_frame((_PyInterpreterFrame *)f->_f_frame_data, func, locals);
1090
f->f_frame = (_PyInterpreterFrame *)f->_f_frame_data;
1091
f->f_frame->owner = FRAME_OWNED_BY_FRAME_OBJECT;
1092
// This frame needs to be "complete", so pretend that the first RESUME ran:
1093
f->f_frame->prev_instr = _PyCode_CODE(code) + code->_co_firsttraceable;
1094
assert(!_PyFrame_IsIncomplete(f->f_frame));
1095
Py_DECREF(func);
1096
_PyObject_GC_TRACK(f);
1097
return f;
1098
}
1099
1100
static int
1101
_PyFrame_OpAlreadyRan(_PyInterpreterFrame *frame, int opcode, int oparg)
1102
{
1103
// This only works when opcode is a non-quickened form:
1104
assert(_PyOpcode_Deopt[opcode] == opcode);
1105
int check_oparg = 0;
1106
for (_Py_CODEUNIT *instruction = _PyCode_CODE(_PyFrame_GetCode(frame));
1107
instruction < frame->prev_instr; instruction++)
1108
{
1109
int check_opcode = _PyOpcode_Deopt[instruction->op.code];
1110
check_oparg |= instruction->op.arg;
1111
if (check_opcode == opcode && check_oparg == oparg) {
1112
return 1;
1113
}
1114
if (check_opcode == EXTENDED_ARG) {
1115
check_oparg <<= 8;
1116
}
1117
else {
1118
check_oparg = 0;
1119
}
1120
instruction += _PyOpcode_Caches[check_opcode];
1121
}
1122
return 0;
1123
}
1124
1125
1126
// Initialize frame free variables if needed
1127
static void
1128
frame_init_get_vars(_PyInterpreterFrame *frame)
1129
{
1130
// COPY_FREE_VARS has no quickened forms, so no need to use _PyOpcode_Deopt
1131
// here:
1132
PyCodeObject *co = _PyFrame_GetCode(frame);
1133
int lasti = _PyInterpreterFrame_LASTI(frame);
1134
if (!(lasti < 0 && _PyCode_CODE(co)->op.code == COPY_FREE_VARS
1135
&& PyFunction_Check(frame->f_funcobj)))
1136
{
1137
/* Free vars are initialized */
1138
return;
1139
}
1140
1141
/* Free vars have not been initialized -- Do that */
1142
PyObject *closure = ((PyFunctionObject *)frame->f_funcobj)->func_closure;
1143
int offset = PyCode_GetFirstFree(co);
1144
for (int i = 0; i < co->co_nfreevars; ++i) {
1145
PyObject *o = PyTuple_GET_ITEM(closure, i);
1146
frame->localsplus[offset + i] = Py_NewRef(o);
1147
}
1148
// COPY_FREE_VARS doesn't have inline CACHEs, either:
1149
frame->prev_instr = _PyCode_CODE(_PyFrame_GetCode(frame));
1150
}
1151
1152
1153
static int
1154
frame_get_var(_PyInterpreterFrame *frame, PyCodeObject *co, int i,
1155
PyObject **pvalue)
1156
{
1157
_PyLocals_Kind kind = _PyLocals_GetKind(co->co_localspluskinds, i);
1158
1159
/* If the namespace is unoptimized, then one of the
1160
following cases applies:
1161
1. It does not contain free variables, because it
1162
uses import * or is a top-level namespace.
1163
2. It is a class namespace.
1164
We don't want to accidentally copy free variables
1165
into the locals dict used by the class.
1166
*/
1167
if (kind & CO_FAST_FREE && !(co->co_flags & CO_OPTIMIZED)) {
1168
return 0;
1169
}
1170
1171
PyObject *value = frame->localsplus[i];
1172
if (frame->stacktop) {
1173
if (kind & CO_FAST_FREE) {
1174
// The cell was set by COPY_FREE_VARS.
1175
assert(value != NULL && PyCell_Check(value));
1176
value = PyCell_GET(value);
1177
}
1178
else if (kind & CO_FAST_CELL) {
1179
// Note that no *_DEREF ops can happen before MAKE_CELL
1180
// executes. So there's no need to duplicate the work
1181
// that MAKE_CELL would otherwise do later, if it hasn't
1182
// run yet.
1183
if (value != NULL) {
1184
if (PyCell_Check(value) &&
1185
_PyFrame_OpAlreadyRan(frame, MAKE_CELL, i)) {
1186
// (likely) MAKE_CELL must have executed already.
1187
value = PyCell_GET(value);
1188
}
1189
// (likely) Otherwise it is an arg (kind & CO_FAST_LOCAL),
1190
// with the initial value set when the frame was created...
1191
// (unlikely) ...or it was set to some initial value by
1192
// an earlier call to PyFrame_LocalsToFast().
1193
}
1194
}
1195
}
1196
else {
1197
assert(value == NULL);
1198
}
1199
*pvalue = value;
1200
return 1;
1201
}
1202
1203
int
1204
_PyFrame_FastToLocalsWithError(_PyInterpreterFrame *frame)
1205
{
1206
/* Merge fast locals into f->f_locals */
1207
PyObject *locals = frame->f_locals;
1208
if (locals == NULL) {
1209
locals = frame->f_locals = PyDict_New();
1210
if (locals == NULL) {
1211
return -1;
1212
}
1213
}
1214
1215
frame_init_get_vars(frame);
1216
1217
PyCodeObject *co = _PyFrame_GetCode(frame);
1218
for (int i = 0; i < co->co_nlocalsplus; i++) {
1219
PyObject *value; // borrowed reference
1220
if (!frame_get_var(frame, co, i, &value)) {
1221
continue;
1222
}
1223
1224
PyObject *name = PyTuple_GET_ITEM(co->co_localsplusnames, i);
1225
_PyLocals_Kind kind = _PyLocals_GetKind(co->co_localspluskinds, i);
1226
if (kind & CO_FAST_HIDDEN) {
1227
continue;
1228
}
1229
if (value == NULL) {
1230
if (PyObject_DelItem(locals, name) != 0) {
1231
if (PyErr_ExceptionMatches(PyExc_KeyError)) {
1232
PyErr_Clear();
1233
}
1234
else {
1235
return -1;
1236
}
1237
}
1238
}
1239
else {
1240
if (PyObject_SetItem(locals, name, value) != 0) {
1241
return -1;
1242
}
1243
}
1244
}
1245
return 0;
1246
}
1247
1248
1249
PyObject *
1250
PyFrame_GetVar(PyFrameObject *frame_obj, PyObject *name)
1251
{
1252
if (!PyUnicode_Check(name)) {
1253
PyErr_Format(PyExc_TypeError, "name must be str, not %s",
1254
Py_TYPE(name)->tp_name);
1255
return NULL;
1256
}
1257
1258
_PyInterpreterFrame *frame = frame_obj->f_frame;
1259
frame_init_get_vars(frame);
1260
1261
PyCodeObject *co = _PyFrame_GetCode(frame);
1262
for (int i = 0; i < co->co_nlocalsplus; i++) {
1263
PyObject *var_name = PyTuple_GET_ITEM(co->co_localsplusnames, i);
1264
if (!_PyUnicode_Equal(var_name, name)) {
1265
continue;
1266
}
1267
1268
PyObject *value; // borrowed reference
1269
if (!frame_get_var(frame, co, i, &value)) {
1270
break;
1271
}
1272
if (value == NULL) {
1273
break;
1274
}
1275
return Py_NewRef(value);
1276
}
1277
1278
PyErr_Format(PyExc_NameError, "variable %R does not exist", name);
1279
return NULL;
1280
}
1281
1282
1283
PyObject *
1284
PyFrame_GetVarString(PyFrameObject *frame, const char *name)
1285
{
1286
PyObject *name_obj = PyUnicode_FromString(name);
1287
if (name_obj == NULL) {
1288
return NULL;
1289
}
1290
PyObject *value = PyFrame_GetVar(frame, name_obj);
1291
Py_DECREF(name_obj);
1292
return value;
1293
}
1294
1295
1296
int
1297
PyFrame_FastToLocalsWithError(PyFrameObject *f)
1298
{
1299
assert(!_PyFrame_IsIncomplete(f->f_frame));
1300
if (f == NULL) {
1301
PyErr_BadInternalCall();
1302
return -1;
1303
}
1304
int err = _PyFrame_FastToLocalsWithError(f->f_frame);
1305
if (err == 0) {
1306
f->f_fast_as_locals = 1;
1307
}
1308
return err;
1309
}
1310
1311
void
1312
PyFrame_FastToLocals(PyFrameObject *f)
1313
{
1314
int res;
1315
assert(!_PyFrame_IsIncomplete(f->f_frame));
1316
assert(!PyErr_Occurred());
1317
1318
res = PyFrame_FastToLocalsWithError(f);
1319
if (res < 0)
1320
PyErr_Clear();
1321
}
1322
1323
void
1324
_PyFrame_LocalsToFast(_PyInterpreterFrame *frame, int clear)
1325
{
1326
/* Merge locals into fast locals */
1327
PyObject *locals;
1328
PyObject **fast;
1329
PyCodeObject *co;
1330
locals = frame->f_locals;
1331
if (locals == NULL) {
1332
return;
1333
}
1334
fast = _PyFrame_GetLocalsArray(frame);
1335
co = _PyFrame_GetCode(frame);
1336
1337
PyObject *exc = PyErr_GetRaisedException();
1338
for (int i = 0; i < co->co_nlocalsplus; i++) {
1339
_PyLocals_Kind kind = _PyLocals_GetKind(co->co_localspluskinds, i);
1340
1341
/* Same test as in PyFrame_FastToLocals() above. */
1342
if (kind & CO_FAST_FREE && !(co->co_flags & CO_OPTIMIZED)) {
1343
continue;
1344
}
1345
PyObject *name = PyTuple_GET_ITEM(co->co_localsplusnames, i);
1346
PyObject *value = PyObject_GetItem(locals, name);
1347
/* We only care about NULLs if clear is true. */
1348
if (value == NULL) {
1349
PyErr_Clear();
1350
if (!clear) {
1351
continue;
1352
}
1353
}
1354
PyObject *oldvalue = fast[i];
1355
PyObject *cell = NULL;
1356
if (kind == CO_FAST_FREE) {
1357
// The cell was set when the frame was created from
1358
// the function's closure.
1359
assert(oldvalue != NULL && PyCell_Check(oldvalue));
1360
cell = oldvalue;
1361
}
1362
else if (kind & CO_FAST_CELL && oldvalue != NULL) {
1363
/* Same test as in PyFrame_FastToLocals() above. */
1364
if (PyCell_Check(oldvalue) &&
1365
_PyFrame_OpAlreadyRan(frame, MAKE_CELL, i)) {
1366
// (likely) MAKE_CELL must have executed already.
1367
cell = oldvalue;
1368
}
1369
// (unlikely) Otherwise, it must have been set to some
1370
// initial value by an earlier call to PyFrame_LocalsToFast().
1371
}
1372
if (cell != NULL) {
1373
oldvalue = PyCell_GET(cell);
1374
if (value != oldvalue) {
1375
PyCell_SET(cell, Py_XNewRef(value));
1376
Py_XDECREF(oldvalue);
1377
}
1378
}
1379
else if (value != oldvalue) {
1380
if (value == NULL) {
1381
// Probably can't delete this, since the compiler's flow
1382
// analysis may have already "proven" that it exists here:
1383
const char *e = "assigning None to unbound local %R";
1384
if (PyErr_WarnFormat(PyExc_RuntimeWarning, 0, e, name)) {
1385
// It's okay if frame_obj is NULL, just try anyways:
1386
PyErr_WriteUnraisable((PyObject *)frame->frame_obj);
1387
}
1388
value = Py_NewRef(Py_None);
1389
}
1390
Py_XSETREF(fast[i], Py_NewRef(value));
1391
}
1392
Py_XDECREF(value);
1393
}
1394
PyErr_SetRaisedException(exc);
1395
}
1396
1397
void
1398
PyFrame_LocalsToFast(PyFrameObject *f, int clear)
1399
{
1400
assert(!_PyFrame_IsIncomplete(f->f_frame));
1401
if (f && f->f_fast_as_locals && _PyFrame_GetState(f) != FRAME_CLEARED) {
1402
_PyFrame_LocalsToFast(f->f_frame, clear);
1403
f->f_fast_as_locals = 0;
1404
}
1405
}
1406
1407
int
1408
_PyFrame_IsEntryFrame(PyFrameObject *frame)
1409
{
1410
assert(frame != NULL);
1411
_PyInterpreterFrame *f = frame->f_frame;
1412
assert(!_PyFrame_IsIncomplete(f));
1413
return f->previous && f->previous->owner == FRAME_OWNED_BY_CSTACK;
1414
}
1415
1416
PyCodeObject *
1417
PyFrame_GetCode(PyFrameObject *frame)
1418
{
1419
assert(frame != NULL);
1420
assert(!_PyFrame_IsIncomplete(frame->f_frame));
1421
PyCodeObject *code = _PyFrame_GetCode(frame->f_frame);
1422
assert(code != NULL);
1423
return (PyCodeObject*)Py_NewRef(code);
1424
}
1425
1426
1427
PyFrameObject*
1428
PyFrame_GetBack(PyFrameObject *frame)
1429
{
1430
assert(frame != NULL);
1431
assert(!_PyFrame_IsIncomplete(frame->f_frame));
1432
PyFrameObject *back = frame->f_back;
1433
if (back == NULL) {
1434
_PyInterpreterFrame *prev = frame->f_frame->previous;
1435
prev = _PyFrame_GetFirstComplete(prev);
1436
if (prev) {
1437
back = _PyFrame_GetFrameObject(prev);
1438
}
1439
}
1440
return (PyFrameObject*)Py_XNewRef(back);
1441
}
1442
1443
PyObject*
1444
PyFrame_GetLocals(PyFrameObject *frame)
1445
{
1446
assert(!_PyFrame_IsIncomplete(frame->f_frame));
1447
return frame_getlocals(frame, NULL);
1448
}
1449
1450
PyObject*
1451
PyFrame_GetGlobals(PyFrameObject *frame)
1452
{
1453
assert(!_PyFrame_IsIncomplete(frame->f_frame));
1454
return frame_getglobals(frame, NULL);
1455
}
1456
1457
PyObject*
1458
PyFrame_GetBuiltins(PyFrameObject *frame)
1459
{
1460
assert(!_PyFrame_IsIncomplete(frame->f_frame));
1461
return frame_getbuiltins(frame, NULL);
1462
}
1463
1464
int
1465
PyFrame_GetLasti(PyFrameObject *frame)
1466
{
1467
assert(!_PyFrame_IsIncomplete(frame->f_frame));
1468
int lasti = _PyInterpreterFrame_LASTI(frame->f_frame);
1469
if (lasti < 0) {
1470
return -1;
1471
}
1472
return lasti * sizeof(_Py_CODEUNIT);
1473
}
1474
1475
PyObject *
1476
PyFrame_GetGenerator(PyFrameObject *frame)
1477
{
1478
assert(!_PyFrame_IsIncomplete(frame->f_frame));
1479
if (frame->f_frame->owner != FRAME_OWNED_BY_GENERATOR) {
1480
return NULL;
1481
}
1482
PyGenObject *gen = _PyFrame_GetGenerator(frame->f_frame);
1483
return Py_NewRef(gen);
1484
}
1485
1486
PyObject*
1487
_PyEval_BuiltinsFromGlobals(PyThreadState *tstate, PyObject *globals)
1488
{
1489
PyObject *builtins = PyDict_GetItemWithError(globals, &_Py_ID(__builtins__));
1490
if (builtins) {
1491
if (PyModule_Check(builtins)) {
1492
builtins = _PyModule_GetDict(builtins);
1493
assert(builtins != NULL);
1494
}
1495
return builtins;
1496
}
1497
if (PyErr_Occurred()) {
1498
return NULL;
1499
}
1500
1501
return _PyEval_GetBuiltins(tstate);
1502
}
1503
1504