Coverage Report

Created: 2026-01-17 06:45

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