Coverage Report

Created: 2026-12-01 06:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Python/assemble.c
Line
Count
Source
1
#include "Python.h"
2
#include "pycore_code.h"            // write_location_entry_start()
3
#include "pycore_compile.h"
4
#include "pycore_instruction_sequence.h"
5
#include "pycore_opcode_utils.h"    // IS_BACKWARDS_JUMP_OPCODE
6
#include "pycore_opcode_metadata.h" // is_pseudo_target, _PyOpcode_Caches
7
#include "pycore_pystate.h"         // _PyInterpreterState_GET()
8
#include "pycore_symtable.h"        // _Py_SourceLocation
9
#include "pycore_tuple.h"           // _PyTuple_ITEMS()
10
#include "pycore_unicodeobject.h"   // _PyUnicode_InternImmortal()
11
12
#include <stdbool.h>
13
14
3.84k
#define DEFAULT_CODE_SIZE 128
15
3.84k
#define DEFAULT_LNOTAB_SIZE 16
16
3.84k
#define DEFAULT_CNOTAB_SIZE 32
17
18
#undef SUCCESS
19
#undef ERROR
20
269k
#define SUCCESS 0
21
3.84k
#define ERROR -1
22
23
#define RETURN_IF_ERROR(X)  \
24
279k
    if ((X) < 0) {          \
25
0
        return ERROR;       \
26
0
    }
27
28
typedef _Py_SourceLocation location;
29
typedef _PyInstruction instruction;
30
typedef _PyInstructionSequence instr_sequence;
31
32
static inline bool
33
same_location(location a, location b)
34
268k
{
35
268k
    return a.lineno == b.lineno &&
36
95.8k
           a.end_lineno == b.end_lineno &&
37
93.2k
           a.col_offset == b.col_offset &&
38
56.4k
           a.end_col_offset == b.end_col_offset;
39
268k
}
40
41
static int
42
instr_size(instruction *instr)
43
706k
{
44
706k
    int opcode = instr->i_opcode;
45
706k
    int oparg = instr->i_oparg;
46
706k
    assert(!IS_PSEUDO_INSTR(opcode));
47
706k
    assert(OPCODE_HAS_ARG(opcode) || oparg == 0);
48
706k
    int extended_args = (0xFFFFFF < oparg) + (0xFFFF < oparg) + (0xFF < oparg);
49
706k
    int caches = _PyOpcode_Caches[opcode];
50
706k
    return extended_args + 1 + caches;
51
706k
}
52
53
struct assembler {
54
    PyBytesWriter *a_bytecode_writer; /* writer containing bytecode */
55
    PyObject *a_bytecode;      /* bytes containing bytecode */
56
    int a_offset;              /* offset into bytecode */
57
    PyBytesWriter *a_except_table_writer; /* writer containing exception table */
58
    PyObject *a_except_table;  /* bytes containing exception table */
59
    int a_except_table_off;    /* offset into exception table */
60
    /* Location Info */
61
    int a_lineno;          /* lineno of last emitted instruction */
62
    PyBytesWriter *a_linetable_writer; /* writer containing location info */
63
    PyObject *a_linetable; /* bytes object containing location info */
64
    int a_location_off;    /* offset of last written location info frame */
65
};
66
67
static int
68
assemble_init(struct assembler *a, int firstlineno)
69
3.84k
{
70
3.84k
    memset(a, 0, sizeof(struct assembler));
71
3.84k
    a->a_lineno = firstlineno;
72
3.84k
    a->a_bytecode_writer = PyBytesWriter_Create(DEFAULT_CODE_SIZE);
73
3.84k
    if (a->a_bytecode_writer == NULL) {
74
0
        goto error;
75
0
    }
76
3.84k
    a->a_linetable_writer = PyBytesWriter_Create(DEFAULT_CNOTAB_SIZE);
77
3.84k
    if (a->a_linetable_writer == NULL) {
78
0
        goto error;
79
0
    }
80
3.84k
    a->a_except_table_writer = PyBytesWriter_Create(DEFAULT_LNOTAB_SIZE);
81
3.84k
    if (a->a_except_table_writer == NULL) {
82
0
        goto error;
83
0
    }
84
3.84k
    return SUCCESS;
85
0
error:
86
0
    PyBytesWriter_Discard(a->a_bytecode_writer);
87
0
    a->a_bytecode_writer = NULL;
88
0
    PyBytesWriter_Discard(a->a_linetable_writer);
89
0
    a->a_linetable_writer = NULL;
90
0
    PyBytesWriter_Discard(a->a_except_table_writer);
91
0
    a->a_except_table_writer = NULL;
92
0
    return ERROR;
93
3.84k
}
94
95
static void
96
assemble_free(struct assembler *a)
97
3.84k
{
98
3.84k
    PyBytesWriter_Discard(a->a_bytecode_writer);
99
3.84k
    PyBytesWriter_Discard(a->a_linetable_writer);
100
3.84k
    PyBytesWriter_Discard(a->a_except_table_writer);
101
3.84k
    Py_XDECREF(a->a_bytecode);
102
3.84k
    Py_XDECREF(a->a_linetable);
103
3.84k
    Py_XDECREF(a->a_except_table);
104
3.84k
}
105
106
static inline void
107
5.73k
write_except_byte(struct assembler *a, int byte) {
108
5.73k
    unsigned char *p = PyBytesWriter_GetData(a->a_except_table_writer);
109
5.73k
    p[a->a_except_table_off++] = byte;
110
5.73k
}
111
112
1.71k
#define CONTINUATION_BIT 64
113
114
static void
115
assemble_emit_exception_table_item(struct assembler *a, int value, int msb)
116
4.02k
{
117
4.02k
    assert ((msb | 128) == 128);
118
4.02k
    assert(value >= 0 && value < (1 << 30));
119
4.02k
    if (value >= 1 << 24) {
120
0
        write_except_byte(a, (value >> 24) | CONTINUATION_BIT | msb);
121
0
        msb = 0;
122
0
    }
123
4.02k
    if (value >= 1 << 18) {
124
0
        write_except_byte(a, ((value >> 18)&0x3f) | CONTINUATION_BIT | msb);
125
0
        msb = 0;
126
0
    }
127
4.02k
    if (value >= 1 << 12) {
128
0
        write_except_byte(a, ((value >> 12)&0x3f) | CONTINUATION_BIT | msb);
129
0
        msb = 0;
130
0
    }
131
4.02k
    if (value >= 1 << 6) {
132
1.71k
        write_except_byte(a, ((value >> 6)&0x3f) | CONTINUATION_BIT | msb);
133
1.71k
        msb = 0;
134
1.71k
    }
135
4.02k
    write_except_byte(a, (value&0x3f) | msb);
136
4.02k
}
137
138
/* See InternalDocs/exception_handling.md for details of layout */
139
1.00k
#define MAX_SIZE_OF_ENTRY 20
140
141
static int
142
assemble_emit_exception_table_entry(struct assembler *a, int start, int end,
143
                                    int handler_offset,
144
                                    _PyExceptHandlerInfo *handler)
145
1.00k
{
146
1.00k
    Py_ssize_t len = PyBytesWriter_GetSize(a->a_except_table_writer);
147
1.00k
    if (a->a_except_table_off + MAX_SIZE_OF_ENTRY >= len) {
148
363
        RETURN_IF_ERROR(PyBytesWriter_Resize(a->a_except_table_writer, len * 2));
149
363
    }
150
1.00k
    int size = end-start;
151
1.00k
    assert(end > start);
152
1.00k
    int target = handler_offset;
153
1.00k
    int depth = handler->h_startdepth - 1;
154
1.00k
    if (handler->h_preserve_lasti > 0) {
155
685
        depth -= 1;
156
685
    }
157
1.00k
    assert(depth >= 0);
158
1.00k
    int depth_lasti = (depth<<1) | handler->h_preserve_lasti;
159
1.00k
    assemble_emit_exception_table_item(a, start, (1<<7));
160
1.00k
    assemble_emit_exception_table_item(a, size, 0);
161
1.00k
    assemble_emit_exception_table_item(a, target, 0);
162
1.00k
    assemble_emit_exception_table_item(a, depth_lasti, 0);
163
1.00k
    return SUCCESS;
164
1.00k
}
165
166
static int
167
assemble_exception_table(struct assembler *a, instr_sequence *instrs)
168
3.84k
{
169
3.84k
    int ioffset = 0;
170
3.84k
    _PyExceptHandlerInfo handler;
171
3.84k
    handler.h_label = -1;
172
3.84k
    handler.h_startdepth = -1;
173
3.84k
    handler.h_preserve_lasti = -1;
174
3.84k
    int start = -1;
175
137k
    for (int i = 0; i < instrs->s_used; i++) {
176
134k
        instruction *instr = &instrs->s_instrs[i];
177
134k
        if (instr->i_except_handler_info.h_label != handler.h_label) {
178
1.70k
            if (handler.h_label >= 0) {
179
1.00k
                int handler_offset = instrs->s_instrs[handler.h_label].i_offset;
180
1.00k
                RETURN_IF_ERROR(
181
1.00k
                    assemble_emit_exception_table_entry(a, start, ioffset,
182
1.00k
                                                        handler_offset,
183
1.00k
                                                        &handler));
184
1.00k
            }
185
1.70k
            start = ioffset;
186
1.70k
            handler = instr->i_except_handler_info;
187
1.70k
        }
188
134k
        ioffset += instr_size(instr);
189
134k
    }
190
3.84k
    if (handler.h_label >= 0) {
191
0
        int handler_offset = instrs->s_instrs[handler.h_label].i_offset;
192
0
        RETURN_IF_ERROR(assemble_emit_exception_table_entry(a, start, ioffset,
193
0
                                                            handler_offset,
194
0
                                                            &handler));
195
0
    }
196
3.84k
    return SUCCESS;
197
3.84k
}
198
199
200
/* Code location emitting code. See locations.md for a description of the format. */
201
202
#define MSB 0x80
203
204
static void
205
write_location_byte(struct assembler* a, int val)
206
99.2k
{
207
99.2k
    uint8_t *linetable = PyBytesWriter_GetData(a->a_linetable_writer);
208
99.2k
    linetable[a->a_location_off] = val & 255;
209
99.2k
    a->a_location_off++;
210
99.2k
}
211
212
213
static uint8_t *
214
location_pointer(struct assembler* a)
215
225k
{
216
225k
    uint8_t *linetable = PyBytesWriter_GetData(a->a_linetable_writer);
217
225k
    return linetable + a->a_location_off;
218
225k
}
219
220
static void
221
write_location_first_byte(struct assembler* a, int code, int length)
222
101k
{
223
101k
    a->a_location_off += write_location_entry_start(
224
101k
        location_pointer(a), code, length);
225
101k
}
226
227
static void
228
write_location_varint(struct assembler* a, unsigned int val)
229
93.4k
{
230
93.4k
    uint8_t *ptr = location_pointer(a);
231
93.4k
    a->a_location_off += write_varint(ptr, val);
232
93.4k
}
233
234
235
static void
236
write_location_signed_varint(struct assembler* a, int val)
237
31.1k
{
238
31.1k
    uint8_t *ptr = location_pointer(a);
239
31.1k
    a->a_location_off += write_signed_varint(ptr, val);
240
31.1k
}
241
242
static void
243
write_location_info_short_form(struct assembler* a, int length, int column, int end_column)
244
37.2k
{
245
37.2k
    assert(length > 0 &&  length <= 8);
246
37.2k
    int column_low_bits = column & 7;
247
37.2k
    int column_group = column >> 3;
248
37.2k
    assert(column < 80);
249
37.2k
    assert(end_column >= column);
250
37.2k
    assert(end_column - column < 16);
251
37.2k
    write_location_first_byte(a, PY_CODE_LOCATION_INFO_SHORT0 + column_group, length);
252
37.2k
    write_location_byte(a, (column_low_bits << 4) | (end_column - column));
253
37.2k
}
254
255
static void
256
write_location_info_oneline_form(struct assembler* a, int length, int line_delta, int column, int end_column)
257
30.9k
{
258
30.9k
    assert(length > 0 &&  length <= 8);
259
30.9k
    assert(line_delta >= 0 && line_delta < 3);
260
30.9k
    assert(column < 128);
261
30.9k
    assert(end_column < 128);
262
30.9k
    write_location_first_byte(a, PY_CODE_LOCATION_INFO_ONE_LINE0 + line_delta, length);
263
30.9k
    write_location_byte(a, column);
264
30.9k
    write_location_byte(a, end_column);
265
30.9k
}
266
267
static void
268
write_location_info_long_form(struct assembler* a, location loc, int length)
269
31.1k
{
270
31.1k
    assert(length > 0 &&  length <= 8);
271
31.1k
    write_location_first_byte(a, PY_CODE_LOCATION_INFO_LONG, length);
272
31.1k
    write_location_signed_varint(a, loc.lineno - a->a_lineno);
273
31.1k
    assert(loc.end_lineno >= loc.lineno);
274
31.1k
    write_location_varint(a, loc.end_lineno - loc.lineno);
275
31.1k
    write_location_varint(a, loc.col_offset + 1);
276
31.1k
    write_location_varint(a, loc.end_col_offset + 1);
277
31.1k
}
278
279
static void
280
write_location_info_none(struct assembler* a, int length)
281
1.59k
{
282
1.59k
    write_location_first_byte(a, PY_CODE_LOCATION_INFO_NONE, length);
283
1.59k
}
284
285
static void
286
write_location_info_no_column(struct assembler* a, int length, int line_delta)
287
59
{
288
59
    write_location_first_byte(a, PY_CODE_LOCATION_INFO_NO_COLUMNS, length);
289
59
    write_location_signed_varint(a, line_delta);
290
59
}
291
292
101k
#define THEORETICAL_MAX_ENTRY_SIZE 25 /* 1 + 6 + 6 + 6 + 6 */
293
294
295
static int
296
write_location_info_entry(struct assembler* a, location loc, int isize)
297
101k
{
298
101k
    Py_ssize_t len = PyBytesWriter_GetSize(a->a_linetable_writer);
299
101k
    if (a->a_location_off + THEORETICAL_MAX_ENTRY_SIZE >= len) {
300
5.65k
        assert(len > THEORETICAL_MAX_ENTRY_SIZE);
301
5.65k
        RETURN_IF_ERROR(PyBytesWriter_Resize(a->a_linetable_writer, len * 2));
302
5.65k
    }
303
101k
    if (loc.lineno == NO_LOCATION.lineno) {
304
1.59k
        write_location_info_none(a, isize);
305
1.59k
        return SUCCESS;
306
1.59k
    }
307
99.4k
    int line_delta = loc.lineno - a->a_lineno;
308
99.4k
    int column = loc.col_offset;
309
99.4k
    int end_column = loc.end_col_offset;
310
99.4k
    if (column < 0 || end_column < 0) {
311
59
        if (loc.end_lineno == loc.lineno || loc.end_lineno < 0) {
312
59
            write_location_info_no_column(a, isize, line_delta);
313
59
            a->a_lineno = loc.lineno;
314
59
            return SUCCESS;
315
59
        }
316
59
    }
317
99.3k
    else if (loc.end_lineno == loc.lineno) {
318
84.1k
        if (line_delta == 0 && column < 80 && end_column - column < 16 && end_column >= column) {
319
37.2k
            write_location_info_short_form(a, isize, column, end_column);
320
37.2k
            return SUCCESS;
321
37.2k
        }
322
46.8k
        if (line_delta >= 0 && line_delta < 3 && column < 128 && end_column < 128) {
323
30.9k
            write_location_info_oneline_form(a, isize, line_delta, column, end_column);
324
30.9k
            a->a_lineno = loc.lineno;
325
30.9k
            return SUCCESS;
326
30.9k
        }
327
46.8k
    }
328
31.1k
    write_location_info_long_form(a, loc, isize);
329
31.1k
    a->a_lineno = loc.lineno;
330
31.1k
    return SUCCESS;
331
99.4k
}
332
333
static int
334
assemble_emit_location(struct assembler* a, location loc, int isize)
335
92.5k
{
336
92.5k
    if (isize == 0) {
337
2.76k
        return SUCCESS;
338
2.76k
    }
339
101k
    while (isize > 8) {
340
11.3k
        RETURN_IF_ERROR(write_location_info_entry(a, loc, 8));
341
11.3k
        isize -= 8;
342
11.3k
    }
343
89.7k
    return write_location_info_entry(a, loc, isize);
344
89.7k
}
345
346
static int
347
assemble_location_info(struct assembler *a, instr_sequence *instrs,
348
                       int firstlineno)
349
3.84k
{
350
3.84k
    a->a_lineno = firstlineno;
351
3.84k
    location loc = NO_LOCATION;
352
137k
    for (int i = instrs->s_used-1; i >= 0; i--) {
353
134k
        instruction *instr = &instrs->s_instrs[i];
354
134k
        if (same_location(instr->i_loc, NEXT_LOCATION)) {
355
0
            if (IS_TERMINATOR_OPCODE(instr->i_opcode)) {
356
0
                instr->i_loc = NO_LOCATION;
357
0
            }
358
0
            else {
359
0
                assert(i < instrs->s_used-1);
360
0
                instr->i_loc = instr[1].i_loc;
361
0
            }
362
0
        }
363
134k
    }
364
3.84k
    int size = 0;
365
137k
    for (int i = 0; i < instrs->s_used; i++) {
366
134k
        instruction *instr = &instrs->s_instrs[i];
367
134k
        if (!same_location(loc, instr->i_loc)) {
368
88.6k
                RETURN_IF_ERROR(assemble_emit_location(a, loc, size));
369
88.6k
                loc = instr->i_loc;
370
88.6k
                size = 0;
371
88.6k
        }
372
134k
        size += instr_size(instr);
373
134k
    }
374
3.84k
    RETURN_IF_ERROR(assemble_emit_location(a, loc, size));
375
3.84k
    return SUCCESS;
376
3.84k
}
377
378
static void
379
write_instr(_Py_CODEUNIT *codestr, instruction *instr, int ilen)
380
134k
{
381
134k
    int opcode = instr->i_opcode;
382
134k
    assert(!IS_PSEUDO_INSTR(opcode));
383
134k
    int oparg = instr->i_oparg;
384
134k
    assert(OPCODE_HAS_ARG(opcode) || oparg == 0);
385
134k
    int caches = _PyOpcode_Caches[opcode];
386
134k
    switch (ilen - caches) {
387
0
        case 4:
388
0
            codestr->op.code = EXTENDED_ARG;
389
0
            codestr->op.arg = (oparg >> 24) & 0xFF;
390
0
            codestr++;
391
0
            _Py_FALLTHROUGH;
392
0
        case 3:
393
0
            codestr->op.code = EXTENDED_ARG;
394
0
            codestr->op.arg = (oparg >> 16) & 0xFF;
395
0
            codestr++;
396
0
            _Py_FALLTHROUGH;
397
247
        case 2:
398
247
            codestr->op.code = EXTENDED_ARG;
399
247
            codestr->op.arg = (oparg >> 8) & 0xFF;
400
247
            codestr++;
401
247
            _Py_FALLTHROUGH;
402
134k
        case 1:
403
134k
            codestr->op.code = opcode;
404
134k
            codestr->op.arg = oparg & 0xFF;
405
134k
            codestr++;
406
134k
            break;
407
0
        default:
408
0
            Py_UNREACHABLE();
409
134k
    }
410
278k
    while (caches--) {
411
144k
        codestr->op.code = CACHE;
412
144k
        codestr->op.arg = 0;
413
144k
        codestr++;
414
144k
    }
415
134k
}
416
417
/* assemble_emit_instr()
418
   Extend the bytecode with a new instruction.
419
   Update lnotab if necessary.
420
*/
421
422
static int
423
assemble_emit_instr(struct assembler *a, instruction *instr)
424
134k
{
425
134k
    Py_ssize_t len = PyBytesWriter_GetSize(a->a_bytecode_writer);
426
134k
    _Py_CODEUNIT *code;
427
428
134k
    int size = instr_size(instr);
429
134k
    if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
430
1.84k
        if (len > PY_SSIZE_T_MAX / 2) {
431
0
            PyErr_NoMemory();
432
0
            return ERROR;
433
0
        }
434
1.84k
        RETURN_IF_ERROR(PyBytesWriter_Resize(a->a_bytecode_writer, len * 2));
435
1.84k
    }
436
134k
    code = (_Py_CODEUNIT *)PyBytesWriter_GetData(a->a_bytecode_writer) + a->a_offset;
437
134k
    a->a_offset += size;
438
134k
    write_instr(code, instr, size);
439
134k
    return SUCCESS;
440
134k
}
441
442
static int
443
assemble_emit(struct assembler *a, instr_sequence *instrs,
444
              int first_lineno, PyObject *const_cache)
445
3.84k
{
446
3.84k
    RETURN_IF_ERROR(assemble_init(a, first_lineno));
447
448
137k
    for (int i = 0; i < instrs->s_used; i++) {
449
134k
        instruction *instr = &instrs->s_instrs[i];
450
134k
        RETURN_IF_ERROR(assemble_emit_instr(a, instr));
451
134k
    }
452
453
3.84k
    RETURN_IF_ERROR(assemble_location_info(a, instrs, a->a_lineno));
454
455
3.84k
    RETURN_IF_ERROR(assemble_exception_table(a, instrs));
456
457
3.84k
    a->a_except_table = PyBytesWriter_FinishWithSize(a->a_except_table_writer,
458
3.84k
                                                     a->a_except_table_off);
459
3.84k
    a->a_except_table_writer = NULL;
460
3.84k
    if (a->a_except_table == NULL) {
461
0
        return ERROR;
462
0
    }
463
3.84k
    RETURN_IF_ERROR(_PyCompile_ConstCacheMergeOne(const_cache, &a->a_except_table));
464
465
3.84k
    a->a_linetable = PyBytesWriter_FinishWithSize(a->a_linetable_writer,
466
3.84k
                                                  a->a_location_off);
467
3.84k
    a->a_linetable_writer = NULL;
468
3.84k
    if (a->a_linetable == NULL) {
469
0
        return ERROR;
470
0
    }
471
3.84k
    RETURN_IF_ERROR(_PyCompile_ConstCacheMergeOne(const_cache, &a->a_linetable));
472
473
3.84k
    a->a_bytecode = PyBytesWriter_FinishWithSize(a->a_bytecode_writer,
474
3.84k
                                                 a->a_offset * sizeof(_Py_CODEUNIT));
475
3.84k
    a->a_bytecode_writer = NULL;
476
3.84k
    if (a->a_bytecode == NULL) {
477
0
        return ERROR;
478
0
    }
479
3.84k
    RETURN_IF_ERROR(_PyCompile_ConstCacheMergeOne(const_cache, &a->a_bytecode));
480
3.84k
    return SUCCESS;
481
3.84k
}
482
483
static PyObject *
484
dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
485
3.84k
{
486
3.84k
    PyObject *tuple, *k, *v;
487
3.84k
    Py_ssize_t pos = 0, size = PyDict_GET_SIZE(dict);
488
489
3.84k
    tuple = PyTuple_New(size);
490
3.84k
    if (tuple == NULL)
491
0
        return NULL;
492
22.6k
    while (PyDict_Next(dict, &pos, &k, &v)) {
493
18.7k
        Py_ssize_t i = PyLong_AsSsize_t(v);
494
18.7k
        if (i == -1 && PyErr_Occurred()) {
495
0
            Py_DECREF(tuple);
496
0
            return NULL;
497
0
        }
498
18.7k
        assert((i - offset) < size);
499
18.7k
        assert((i - offset) >= 0);
500
18.7k
        PyTuple_SET_ITEM(tuple, i - offset, Py_NewRef(k));
501
18.7k
    }
502
3.84k
    return tuple;
503
3.84k
}
504
505
// This is in codeobject.c.
506
extern void _Py_set_localsplus_info(int, PyObject *, unsigned char,
507
                                   PyObject *, PyObject *);
508
509
/* Intern the names in *tuple*, as _PyCode_New() does, before the tuple is
510
 * merged with the constant cache.
511
 *
512
 * The merge can replace the tuple by an equal tuple constant of another
513
 * code object, whose items _PyCode_New() then interns in place.  A string
514
 * of that constant would become the interned string or be replaced by it,
515
 * depending on whether an equal string was already interned in the process,
516
 * and so would the output of marshal for the same source.  Names which the
517
 * parser did not create, such as mangled private names or the identifiers
518
 * of an AST passed to compile(), may not be interned yet.
519
 */
520
static void
521
intern_names(PyObject *tuple)
522
7.69k
{
523
7.69k
    PyInterpreterState *interp = _PyInterpreterState_GET();
524
36.0k
    for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(tuple); i++) {
525
28.3k
        assert(PyUnicode_CheckExact(PyTuple_GET_ITEM(tuple, i)));
526
28.3k
        _PyUnicode_InternImmortal(interp, &_PyTuple_ITEMS(tuple)[i]);
527
28.3k
    }
528
7.69k
}
529
530
static int
531
compute_localsplus_info(_PyCompile_CodeUnitMetadata *umd, int nlocalsplus,
532
                        int flags, PyObject *names, PyObject *kinds)
533
3.84k
{
534
3.84k
    PyObject *k, *v;
535
3.84k
    Py_ssize_t pos = 0;
536
537
    // Set the locals kinds.  Arg vars fill the first portion of the list.
538
3.84k
    struct {
539
3.84k
        int count;
540
3.84k
        _PyLocals_Kind kind;
541
3.84k
    }  argvarkinds[6] = {
542
3.84k
        {(int)umd->u_posonlyargcount, CO_FAST_ARG_POS},
543
3.84k
        {(int)umd->u_argcount, CO_FAST_ARG_POS | CO_FAST_ARG_KW},
544
3.84k
        {(int)umd->u_kwonlyargcount, CO_FAST_ARG_KW},
545
3.84k
        {!!(flags & CO_VARARGS), CO_FAST_ARG_VAR | CO_FAST_ARG_POS},
546
3.84k
        {!!(flags & CO_VARKEYWORDS), CO_FAST_ARG_VAR | CO_FAST_ARG_KW},
547
3.84k
        {-1, 0},  // the remaining local vars
548
3.84k
    };
549
3.84k
    int max = 0;
550
26.9k
    for (int i = 0; i < 6; i++) {
551
23.0k
        max = argvarkinds[i].count < 0
552
23.0k
            ? INT_MAX
553
23.0k
            : max + argvarkinds[i].count;
554
31.6k
        while (pos < max && PyDict_Next(umd->u_varnames, &pos, &k, &v)) {
555
8.55k
            int offset = PyLong_AsInt(v);
556
8.55k
            if (offset == -1 && PyErr_Occurred()) {
557
0
                return ERROR;
558
0
            }
559
8.55k
            assert(offset >= 0);
560
8.55k
            assert(offset < nlocalsplus);
561
562
8.55k
            _PyLocals_Kind kind = CO_FAST_LOCAL | argvarkinds[i].kind;
563
564
8.55k
            if (umd->u_fasthidden != NULL) {
565
1
                int hidden = PySet_Contains(umd->u_fasthidden, k);
566
1
                RETURN_IF_ERROR(hidden);
567
1
                if (hidden) {
568
1
                    kind |= CO_FAST_HIDDEN;
569
1
                }
570
1
            }
571
572
8.55k
            int has_key = PyDict_Contains(umd->u_cellvars, k);
573
8.55k
            RETURN_IF_ERROR(has_key);
574
8.55k
            if (has_key) {
575
447
                kind |= CO_FAST_CELL;
576
447
            }
577
578
8.55k
            _Py_set_localsplus_info(offset, k, kind, names, kinds);
579
8.55k
        }
580
23.0k
    }
581
3.84k
    int nlocals = (int)PyDict_GET_SIZE(umd->u_varnames);
582
583
    // This counter mirrors the fix done in fix_cell_offsets().
584
3.84k
    int numdropped = 0, cellvar_offset = -1;
585
3.84k
    pos = 0;
586
4.66k
    while (PyDict_Next(umd->u_cellvars, &pos, &k, &v)) {
587
813
        int has_name = PyDict_Contains(umd->u_varnames, k);
588
813
        RETURN_IF_ERROR(has_name);
589
813
        if (has_name) {
590
            // Skip cells that are already covered by locals.
591
447
            numdropped += 1;
592
447
            continue;
593
447
        }
594
595
366
        cellvar_offset = PyLong_AsInt(v);
596
366
        if (cellvar_offset == -1 && PyErr_Occurred()) {
597
0
            return ERROR;
598
0
        }
599
366
        assert(cellvar_offset >= 0);
600
366
        cellvar_offset += nlocals - numdropped;
601
366
        assert(cellvar_offset < nlocalsplus);
602
366
        _Py_set_localsplus_info(cellvar_offset, k, CO_FAST_CELL, names, kinds);
603
366
    }
604
605
3.84k
    pos = 0;
606
4.51k
    while (PyDict_Next(umd->u_freevars, &pos, &k, &v)) {
607
672
        int offset = PyLong_AsInt(v);
608
672
        if (offset == -1 && PyErr_Occurred()) {
609
0
            return ERROR;
610
0
        }
611
672
        assert(offset >= 0);
612
672
        offset += nlocals - numdropped;
613
672
        assert(offset < nlocalsplus);
614
        /* XXX If the assertion below fails it is most likely because a freevar
615
           was added to u_freevars with the wrong index due to not taking into
616
           account cellvars already present, see gh-128632. */
617
672
        assert(offset > cellvar_offset);
618
672
        _Py_set_localsplus_info(offset, k, CO_FAST_FREE, names, kinds);
619
672
    }
620
3.84k
    return SUCCESS;
621
3.84k
}
622
623
static PyCodeObject *
624
makecode(_PyCompile_CodeUnitMetadata *umd, struct assembler *a, PyObject *const_cache,
625
         PyObject *constslist, int maxdepth, int nlocalsplus, int code_flags,
626
         PyObject *filename)
627
3.84k
{
628
3.84k
    PyCodeObject *co = NULL;
629
3.84k
    PyObject *names = NULL;
630
3.84k
    PyObject *consts = NULL;
631
3.84k
    PyObject *localsplusnames = NULL;
632
3.84k
    PyObject *localspluskinds = NULL;
633
3.84k
    names = dict_keys_inorder(umd->u_names, 0);
634
3.84k
    if (!names) {
635
0
        goto error;
636
0
    }
637
3.84k
    intern_names(names);
638
3.84k
    if (_PyCompile_ConstCacheMergeOne(const_cache, &names) < 0) {
639
0
        goto error;
640
0
    }
641
642
3.84k
    consts = PyList_AsTuple(constslist); /* PyCode_New requires a tuple */
643
3.84k
    if (consts == NULL) {
644
0
        goto error;
645
0
    }
646
3.84k
    if (_PyCompile_ConstCacheMergeOne(const_cache, &consts) < 0) {
647
0
        goto error;
648
0
    }
649
650
3.84k
    assert(umd->u_posonlyargcount < INT_MAX);
651
3.84k
    assert(umd->u_argcount < INT_MAX);
652
3.84k
    assert(umd->u_kwonlyargcount < INT_MAX);
653
3.84k
    int posonlyargcount = (int)umd->u_posonlyargcount;
654
3.84k
    int posorkwargcount = (int)umd->u_argcount;
655
3.84k
    assert(INT_MAX - posonlyargcount - posorkwargcount > 0);
656
3.84k
    int kwonlyargcount = (int)umd->u_kwonlyargcount;
657
658
3.84k
    localsplusnames = PyTuple_New(nlocalsplus);
659
3.84k
    if (localsplusnames == NULL) {
660
0
        goto error;
661
0
    }
662
3.84k
    localspluskinds = PyBytes_FromStringAndSize(NULL, nlocalsplus);
663
3.84k
    if (localspluskinds == NULL) {
664
0
        goto error;
665
0
    }
666
3.84k
    if (compute_localsplus_info(
667
3.84k
            umd, nlocalsplus, code_flags,
668
3.84k
            localsplusnames, localspluskinds) == ERROR)
669
0
    {
670
0
        goto error;
671
0
    }
672
673
3.84k
    struct _PyCodeConstructor con = {
674
3.84k
        .filename = filename,
675
3.84k
        .name = umd->u_name,
676
3.84k
        .qualname = umd->u_qualname ? umd->u_qualname : umd->u_name,
677
3.84k
        .flags = code_flags,
678
679
3.84k
        .code = a->a_bytecode,
680
3.84k
        .firstlineno = umd->u_firstlineno,
681
3.84k
        .linetable = a->a_linetable,
682
683
3.84k
        .consts = consts,
684
3.84k
        .names = names,
685
686
3.84k
        .localsplusnames = localsplusnames,
687
3.84k
        .localspluskinds = localspluskinds,
688
689
3.84k
        .argcount = posonlyargcount + posorkwargcount,
690
3.84k
        .posonlyargcount = posonlyargcount,
691
3.84k
        .kwonlyargcount = kwonlyargcount,
692
693
3.84k
        .stacksize = maxdepth,
694
695
3.84k
        .exceptiontable = a->a_except_table,
696
3.84k
    };
697
698
3.84k
   if (_PyCode_Validate(&con) < 0) {
699
0
        goto error;
700
0
    }
701
702
3.84k
    intern_names(localsplusnames);
703
3.84k
    if (_PyCompile_ConstCacheMergeOne(const_cache, &localsplusnames) < 0) {
704
0
        goto error;
705
0
    }
706
3.84k
    con.localsplusnames = localsplusnames;
707
708
3.84k
    co = _PyCode_New(&con);
709
3.84k
    if (co == NULL) {
710
0
        goto error;
711
0
    }
712
713
3.84k
error:
714
3.84k
    Py_XDECREF(names);
715
3.84k
    Py_XDECREF(consts);
716
3.84k
    Py_XDECREF(localsplusnames);
717
3.84k
    Py_XDECREF(localspluskinds);
718
3.84k
    return co;
719
3.84k
}
720
721
722
// The offset (in code units) of the END_SEND from the SEND in the `yield from` sequence.
723
0
#define END_SEND_OFFSET 6
724
725
static int
726
resolve_jump_offsets(instr_sequence *instrs)
727
3.84k
{
728
    /* Compute the size of each instruction and fixup jump args.
729
     * Replace instruction index with position in bytecode.
730
     */
731
732
137k
    for (int i = 0; i < instrs->s_used; i++) {
733
134k
        instruction *instr = &instrs->s_instrs[i];
734
134k
        if (OPCODE_HAS_JUMP(instr->i_opcode)) {
735
3.83k
            instr->i_target = instr->i_oparg;
736
3.83k
        }
737
134k
    }
738
739
3.84k
    int extended_arg_recompile;
740
741
3.91k
    do {
742
3.91k
        int totsize = 0;
743
153k
        for (int i = 0; i < instrs->s_used; i++) {
744
149k
            instruction *instr = &instrs->s_instrs[i];
745
149k
            instr->i_offset = totsize;
746
149k
            int isize = instr_size(instr);
747
149k
            totsize += isize;
748
149k
        }
749
3.91k
        extended_arg_recompile = 0;
750
751
3.91k
        int offset = 0;
752
153k
        for (int i = 0; i < instrs->s_used; i++) {
753
149k
            instruction *instr = &instrs->s_instrs[i];
754
149k
            int isize = instr_size(instr);
755
            /* jump offsets are computed relative to
756
             * the instruction pointer after fetching
757
             * the jump instruction.
758
             */
759
149k
            offset += isize;
760
149k
            if (OPCODE_HAS_JUMP(instr->i_opcode)) {
761
5.03k
                instruction *target = &instrs->s_instrs[instr->i_target];
762
5.03k
                instr->i_oparg = target->i_offset;
763
5.03k
                if (instr->i_opcode == END_ASYNC_FOR) {
764
                    // sys.monitoring needs to be able to find the matching END_SEND
765
                    // but the target is the SEND, so we adjust it here.
766
0
                    instr->i_oparg = offset - instr->i_oparg - END_SEND_OFFSET;
767
0
                }
768
5.03k
                else if (instr->i_oparg < offset) {
769
668
                    assert(IS_BACKWARDS_JUMP_OPCODE(instr->i_opcode));
770
668
                    instr->i_oparg = offset - instr->i_oparg;
771
668
                }
772
4.36k
                else {
773
4.36k
                    assert(!IS_BACKWARDS_JUMP_OPCODE(instr->i_opcode));
774
4.36k
                    instr->i_oparg = instr->i_oparg - offset;
775
4.36k
                }
776
5.03k
                if (instr_size(instr) != isize) {
777
347
                    extended_arg_recompile = 1;
778
347
                }
779
5.03k
            }
780
149k
        }
781
    /* XXX: This is an awful hack that could hurt performance, but
782
        on the bright side it should work until we come up
783
        with a better solution.
784
785
        The issue is that in the first loop instr_size() is
786
        called, and it requires i_oparg be set appropriately.
787
        There is a bootstrap problem because i_oparg is
788
        calculated in the second loop above.
789
790
        So we loop until we stop seeing new EXTENDED_ARGs.
791
        The only EXTENDED_ARGs that could be popping up are
792
        ones in jump instructions.  So this should converge
793
        fairly quickly.
794
    */
795
3.91k
    } while (extended_arg_recompile);
796
3.84k
    return SUCCESS;
797
3.84k
}
798
799
static int
800
resolve_unconditional_jumps(instr_sequence *instrs)
801
3.84k
{
802
    /* Resolve directions of unconditional jumps */
803
804
137k
    for (int i = 0; i < instrs->s_used; i++) {
805
134k
        instruction *instr = &instrs->s_instrs[i];
806
134k
        bool is_forward = (instr->i_oparg > i);
807
134k
        switch(instr->i_opcode) {
808
438
            case JUMP:
809
438
                assert(is_pseudo_target(JUMP, JUMP_FORWARD));
810
438
                assert(is_pseudo_target(JUMP, JUMP_BACKWARD));
811
438
                instr->i_opcode = is_forward ? JUMP_FORWARD : JUMP_BACKWARD;
812
438
                break;
813
343
            case JUMP_NO_INTERRUPT:
814
343
                assert(is_pseudo_target(JUMP_NO_INTERRUPT, JUMP_FORWARD));
815
343
                assert(is_pseudo_target(JUMP_NO_INTERRUPT, JUMP_BACKWARD_NO_INTERRUPT));
816
343
                instr->i_opcode = is_forward ?
817
240
                    JUMP_FORWARD : JUMP_BACKWARD_NO_INTERRUPT;
818
343
                break;
819
133k
            default:
820
133k
                if (OPCODE_HAS_JUMP(instr->i_opcode) &&
821
3.05k
                    IS_PSEUDO_INSTR(instr->i_opcode)) {
822
0
                    Py_UNREACHABLE();
823
0
                }
824
134k
        }
825
134k
    }
826
3.84k
    return SUCCESS;
827
3.84k
}
828
829
PyCodeObject *
830
_PyAssemble_MakeCodeObject(_PyCompile_CodeUnitMetadata *umd, PyObject *const_cache,
831
                           PyObject *consts, int maxdepth, instr_sequence *instrs,
832
                           int nlocalsplus, int code_flags, PyObject *filename)
833
3.84k
{
834
3.84k
    if (_PyInstructionSequence_ApplyLabelMap(instrs) < 0) {
835
0
        return NULL;
836
0
    }
837
3.84k
    if (resolve_unconditional_jumps(instrs) < 0) {
838
0
        return NULL;
839
0
    }
840
3.84k
    if (resolve_jump_offsets(instrs) < 0) {
841
0
        return NULL;
842
0
    }
843
3.84k
    PyCodeObject *co = NULL;
844
845
3.84k
    struct assembler a;
846
3.84k
    int res = assemble_emit(&a, instrs, umd->u_firstlineno, const_cache);
847
3.84k
    if (res == SUCCESS) {
848
3.84k
        co = makecode(umd, &a, const_cache, consts, maxdepth, nlocalsplus,
849
3.84k
                      code_flags, filename);
850
3.84k
    }
851
3.84k
    assemble_free(&a);
852
3.84k
    return co;
853
3.84k
}