Coverage Report

Created: 2026-10-31 06:21

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