Coverage Report

Created: 2025-08-26 06:26

/src/cpython/Python/perf_jit_trampoline.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Python Perf Trampoline Support - JIT Dump Implementation
3
 *
4
 * This file implements the perf jitdump API for Python's performance profiling
5
 * integration. It allows perf (Linux performance analysis tool) to understand
6
 * and profile dynamically generated Python bytecode by creating JIT dump files
7
 * that perf can inject into its analysis.
8
 *
9
 *
10
 * IMPORTANT: This file exports specific callback functions that are part of
11
 * Python's internal API. Do not modify the function signatures or behavior
12
 * of exported functions without coordinating with the Python core team.
13
 *
14
 * Usually the binary and libraries are mapped in separate region like below:
15
 *
16
 *   address ->
17
 *    --+---------------------+--//--+---------------------+--
18
 *      | .text | .data | ... |      | .text | .data | ... |
19
 *    --+---------------------+--//--+---------------------+--
20
 *          myprog                      libc.so
21
 *
22
 * So it'd be easy and straight-forward to find a mapped binary or library from an
23
 * address.
24
 *
25
 * But for JIT code, the code arena only cares about the code section. But the
26
 * resulting DSOs (which is generated by perf inject -j) contain ELF headers and
27
 * unwind info too. Then it'd generate following address space with synthesized
28
 * MMAP events. Let's say it has a sample between address B and C.
29
 *
30
 *                                                sample
31
 *                                                  |
32
 *   address ->                         A       B   v   C
33
 *   ---------------------------------------------------------------------------------------------------
34
 *   /tmp/jitted-PID-0.so   | (headers) | .text | unwind info |
35
 *   /tmp/jitted-PID-1.so           | (headers) | .text | unwind info |
36
 *   /tmp/jitted-PID-2.so                   | (headers) | .text | unwind info |
37
 *     ...
38
 *   ---------------------------------------------------------------------------------------------------
39
 *
40
 * If it only maps the .text section, it'd find the jitted-PID-1.so but cannot see
41
 * the unwind info. If it maps both .text section and unwind sections, the sample
42
 * could be mapped to either jitted-PID-0.so or jitted-PID-1.so and it's confusing
43
 * which one is right. So to make perf happy we have non-overlapping ranges for each
44
 * DSO:
45
 *
46
 *   address ->
47
 *   -------------------------------------------------------------------------------------------------------
48
 *   /tmp/jitted-PID-0.so   | (headers) | .text | unwind info |
49
 *   /tmp/jitted-PID-1.so                         | (headers) | .text | unwind info |
50
 *   /tmp/jitted-PID-2.so                                               | (headers) | .text | unwind info |
51
 *     ...
52
 *   -------------------------------------------------------------------------------------------------------
53
 *
54
 * As the trampolines are constant, we add a constant padding but in general the padding needs to have the
55
 * size of the unwind info rounded to 16 bytes. In general, for our trampolines this is 0x50
56
 */
57
58
59
60
#include "Python.h"
61
#include "pycore_ceval.h"         // _PyPerf_Callbacks
62
#include "pycore_frame.h"
63
#include "pycore_interp.h"
64
#include "pycore_runtime.h"       // _PyRuntime
65
66
#ifdef PY_HAVE_PERF_TRAMPOLINE
67
68
/* Standard library includes for perf jitdump implementation */
69
#if defined(__linux__)
70
#  include <elf.h>                // ELF architecture constants
71
#endif
72
#include <fcntl.h>                // File control operations
73
#include <stdio.h>                // Standard I/O operations
74
#include <stdlib.h>               // Standard library functions
75
#include <sys/mman.h>             // Memory mapping functions (mmap)
76
#include <sys/types.h>            // System data types
77
#include <unistd.h>               // System calls (sysconf, getpid)
78
#include <sys/time.h>             // Time functions (gettimeofday)
79
#if defined(__linux__)
80
#  include <sys/syscall.h>        // System call interface
81
#endif
82
83
// =============================================================================
84
//                           CONSTANTS AND CONFIGURATION
85
// =============================================================================
86
87
/*
88
 * Memory layout considerations for perf jitdump:
89
 *
90
 * Perf expects non-overlapping memory regions for each JIT-compiled function.
91
 * When perf processes the jitdump file, it creates synthetic DSO (Dynamic
92
 * Shared Object) files that contain:
93
 * - ELF headers
94
 * - .text section (actual machine code)
95
 * - Unwind information (for stack traces)
96
 *
97
 * To ensure proper address space layout, we add padding between code regions.
98
 * This prevents address conflicts when perf maps the synthesized DSOs.
99
 *
100
 * Memory layout example:
101
 * /tmp/jitted-PID-0.so: [headers][.text][unwind_info][padding]
102
 * /tmp/jitted-PID-1.so:                                       [headers][.text][unwind_info][padding]
103
 *
104
 * The padding size is now calculated automatically during initialization
105
 * based on the actual unwind information requirements.
106
 */
107
108
109
/* These constants are defined inside <elf.h>, which we can't use outside of linux. */
110
#if !defined(__linux__)
111
#  if defined(__i386__) || defined(_M_IX86)
112
#    define EM_386      3
113
#  elif defined(__arm__) || defined(_M_ARM)
114
#    define EM_ARM      40
115
#  elif defined(__x86_64__) || defined(_M_X64)
116
#    define EM_X86_64   62
117
#  elif defined(__aarch64__)
118
#    define EM_AARCH64  183
119
#  elif defined(__riscv)
120
#    define EM_RISCV    243
121
#  endif
122
#endif
123
124
/* Convenient access to the global trampoline API state */
125
0
#define trampoline_api _PyRuntime.ceval.perf.trampoline_api
126
127
/* Type aliases for clarity and portability */
128
typedef uint64_t uword;                    // Word-sized unsigned integer
129
typedef const char* CodeComments;          // Code comment strings
130
131
/* Memory size constants */
132
0
#define MB (1024 * 1024)                   // 1 Megabyte for buffer sizing
133
134
// =============================================================================
135
//                        ARCHITECTURE-SPECIFIC DEFINITIONS
136
// =============================================================================
137
138
/*
139
 * Returns the ELF machine architecture constant for the current platform.
140
 * This is required for the jitdump header to correctly identify the target
141
 * architecture for perf processing.
142
 *
143
 */
144
0
static uint64_t GetElfMachineArchitecture(void) {
145
0
#if defined(__x86_64__) || defined(_M_X64)
146
0
    return EM_X86_64;
147
#elif defined(__i386__) || defined(_M_IX86)
148
    return EM_386;
149
#elif defined(__aarch64__)
150
    return EM_AARCH64;
151
#elif defined(__arm__) || defined(_M_ARM)
152
    return EM_ARM;
153
#elif defined(__riscv)
154
    return EM_RISCV;
155
#else
156
    Py_UNREACHABLE();  // Unsupported architecture - should never reach here
157
    return 0;
158
#endif
159
0
}
160
161
// =============================================================================
162
//                           PERF JITDUMP DATA STRUCTURES
163
// =============================================================================
164
165
/*
166
 * Perf jitdump file format structures
167
 *
168
 * These structures define the binary format that perf expects for JIT dump files.
169
 * The format is documented in the Linux perf tools source code and must match
170
 * exactly for proper perf integration.
171
 */
172
173
/*
174
 * Jitdump file header - written once at the beginning of each jitdump file
175
 * Contains metadata about the process and jitdump format version
176
 */
177
typedef struct {
178
    uint32_t magic;              // Magic number (0x4A695444 = "JiTD")
179
    uint32_t version;            // Jitdump format version (currently 1)
180
    uint32_t size;               // Size of this header structure
181
    uint32_t elf_mach_target;    // Target architecture (from GetElfMachineArchitecture)
182
    uint32_t reserved;           // Reserved field (must be 0)
183
    uint32_t process_id;         // Process ID of the JIT compiler
184
    uint64_t time_stamp;         // Timestamp when jitdump was created
185
    uint64_t flags;              // Feature flags (currently unused)
186
} Header;
187
188
/*
189
 * Perf event types supported by the jitdump format
190
 * Each event type has a corresponding structure format
191
 */
192
enum PerfEvent {
193
    PerfLoad = 0,           // Code load event (new JIT function)
194
    PerfMove = 1,           // Code move event (function relocated)
195
    PerfDebugInfo = 2,      // Debug information event
196
    PerfClose = 3,          // JIT session close event
197
    PerfUnwindingInfo = 4   // Stack unwinding information event
198
};
199
200
/*
201
 * Base event structure - common header for all perf events
202
 * Every event in the jitdump file starts with this structure
203
 */
204
struct BaseEvent {
205
    uint32_t event;         // Event type (from PerfEvent enum)
206
    uint32_t size;          // Total size of this event including payload
207
    uint64_t time_stamp;    // Timestamp when event occurred
208
};
209
210
/*
211
 * Code load event - indicates a new JIT-compiled function is available
212
 * This is the most important event type for Python profiling
213
 */
214
typedef struct {
215
    struct BaseEvent base;   // Common event header
216
    uint32_t process_id;     // Process ID where code was generated
217
#if defined(__APPLE__)
218
    uint64_t thread_id;      // Thread ID where code was generated
219
#else
220
    uint32_t thread_id;      // Thread ID where code was generated
221
#endif
222
    uint64_t vma;            // Virtual memory address where code is loaded
223
    uint64_t code_address;   // Address of the actual machine code
224
    uint64_t code_size;      // Size of the machine code in bytes
225
    uint64_t code_id;        // Unique identifier for this code region
226
    /* Followed by:
227
     * - null-terminated function name string
228
     * - raw machine code bytes
229
     */
230
} CodeLoadEvent;
231
232
/*
233
 * Code unwinding information event - provides DWARF data for stack traces
234
 * Essential for proper stack unwinding during profiling
235
 */
236
typedef struct {
237
    struct BaseEvent base;      // Common event header
238
    uint64_t unwind_data_size;  // Size of the unwinding data
239
    uint64_t eh_frame_hdr_size; // Size of the EH frame header
240
    uint64_t mapped_size;       // Total mapped size (with padding)
241
    /* Followed by:
242
     * - EH frame header
243
     * - DWARF unwinding information
244
     * - Padding to alignment boundary
245
     */
246
} CodeUnwindingInfoEvent;
247
248
// =============================================================================
249
//                              GLOBAL STATE MANAGEMENT
250
// =============================================================================
251
252
/*
253
 * Global state for the perf jitdump implementation
254
 *
255
 * This structure maintains all the state needed for generating jitdump files.
256
 * It's designed as a singleton since there's typically only one jitdump file
257
 * per Python process.
258
 */
259
typedef struct {
260
    FILE* perf_map;          // File handle for the jitdump file
261
    PyThread_type_lock map_lock;  // Thread synchronization lock
262
    void* mapped_buffer;     // Memory-mapped region (signals perf we're active)
263
    size_t mapped_size;      // Size of the mapped region
264
    int code_id;             // Counter for unique code region identifiers
265
} PerfMapJitState;
266
267
/* Global singleton instance */
268
static PerfMapJitState perf_jit_map_state;
269
270
// =============================================================================
271
//                              TIME UTILITIES
272
// =============================================================================
273
274
/* Time conversion constant */
275
static const intptr_t nanoseconds_per_second = 1000000000;
276
277
/*
278
 * Get current monotonic time in nanoseconds
279
 *
280
 * Monotonic time is preferred for event timestamps because it's not affected
281
 * by system clock adjustments. This ensures consistent timing relationships
282
 * between events even if the system clock is changed.
283
 *
284
 * Returns: Current monotonic time in nanoseconds since an arbitrary epoch
285
 */
286
0
static int64_t get_current_monotonic_ticks(void) {
287
0
    struct timespec ts;
288
0
    if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {
289
0
        Py_UNREACHABLE();  // Should never fail on supported systems
290
0
        return 0;
291
0
    }
292
293
    /* Convert to nanoseconds for maximum precision */
294
0
    int64_t result = ts.tv_sec;
295
0
    result *= nanoseconds_per_second;
296
0
    result += ts.tv_nsec;
297
0
    return result;
298
0
}
299
300
/*
301
 * Get current wall clock time in microseconds
302
 *
303
 * Used for the jitdump file header timestamp. Unlike monotonic time,
304
 * this represents actual wall clock time that can be correlated with
305
 * other system events.
306
 *
307
 * Returns: Current time in microseconds since Unix epoch
308
 */
309
0
static int64_t get_current_time_microseconds(void) {
310
0
    struct timeval tv;
311
0
    if (gettimeofday(&tv, NULL) < 0) {
312
0
        Py_UNREACHABLE();  // Should never fail on supported systems
313
0
        return 0;
314
0
    }
315
0
    return ((int64_t)(tv.tv_sec) * 1000000) + tv.tv_usec;
316
0
}
317
318
// =============================================================================
319
//                              UTILITY FUNCTIONS
320
// =============================================================================
321
322
/*
323
 * Round up a value to the next multiple of a given number
324
 *
325
 * This is essential for maintaining proper alignment requirements in the
326
 * jitdump format. Many structures need to be aligned to specific boundaries
327
 * (typically 8 or 16 bytes) for efficient processing by perf.
328
 *
329
 * Args:
330
 *   value: The value to round up
331
 *   multiple: The multiple to round up to
332
 *
333
 * Returns: The smallest value >= input that is a multiple of 'multiple'
334
 */
335
0
static size_t round_up(int64_t value, int64_t multiple) {
336
0
    if (multiple == 0) {
337
0
        return value;  // Avoid division by zero
338
0
    }
339
340
0
    int64_t remainder = value % multiple;
341
0
    if (remainder == 0) {
342
0
        return value;  // Already aligned
343
0
    }
344
345
    /* Calculate how much to add to reach the next multiple */
346
0
    int64_t difference = multiple - remainder;
347
0
    int64_t rounded_up_value = value + difference;
348
349
0
    return rounded_up_value;
350
0
}
351
352
// =============================================================================
353
//                              FILE I/O UTILITIES
354
// =============================================================================
355
356
/*
357
 * Write data to the jitdump file with error handling
358
 *
359
 * This function ensures that all data is written to the file, handling
360
 * partial writes that can occur with large buffers or when the system
361
 * is under load.
362
 *
363
 * Args:
364
 *   buffer: Pointer to data to write
365
 *   size: Number of bytes to write
366
 */
367
0
static void perf_map_jit_write_fully(const void* buffer, size_t size) {
368
0
    FILE* out_file = perf_jit_map_state.perf_map;
369
0
    const char* ptr = (const char*)(buffer);
370
371
0
    while (size > 0) {
372
0
        const size_t written = fwrite(ptr, 1, size, out_file);
373
0
        if (written == 0) {
374
0
            Py_UNREACHABLE();  // Write failure - should be very rare
375
0
            break;
376
0
        }
377
0
        size -= written;
378
0
        ptr += written;
379
0
    }
380
0
}
381
382
/*
383
 * Write the jitdump file header
384
 *
385
 * The header must be written exactly once at the beginning of each jitdump
386
 * file. It provides metadata that perf uses to parse the rest of the file.
387
 *
388
 * Args:
389
 *   pid: Process ID to include in the header
390
 *   out_file: File handle to write to (currently unused, uses global state)
391
 */
392
0
static void perf_map_jit_write_header(int pid, FILE* out_file) {
393
0
    Header header;
394
395
    /* Initialize header with required values */
396
0
    header.magic = 0x4A695444;                    // "JiTD" magic number
397
0
    header.version = 1;                           // Current jitdump version
398
0
    header.size = sizeof(Header);                 // Header size for validation
399
0
    header.elf_mach_target = GetElfMachineArchitecture();  // Target architecture
400
0
    header.process_id = pid;                      // Process identifier
401
0
    header.time_stamp = get_current_time_microseconds();   // Creation time
402
0
    header.flags = 0;                             // No special flags currently used
403
404
0
    perf_map_jit_write_fully(&header, sizeof(header));
405
0
}
406
407
// =============================================================================
408
//                              DWARF CONSTANTS AND UTILITIES
409
// =============================================================================
410
411
/*
412
 * DWARF (Debug With Arbitrary Record Formats) constants
413
 *
414
 * DWARF is a debugging data format used to provide stack unwinding information.
415
 * These constants define the various encoding types and opcodes used in
416
 * DWARF Call Frame Information (CFI) records.
417
 */
418
419
/* DWARF Call Frame Information version */
420
#define DWRF_CIE_VERSION 1
421
422
/* DWARF CFA (Call Frame Address) opcodes */
423
enum {
424
    DWRF_CFA_nop = 0x0,                    // No operation
425
    DWRF_CFA_offset_extended = 0x5,        // Extended offset instruction
426
    DWRF_CFA_def_cfa = 0xc,               // Define CFA rule
427
    DWRF_CFA_def_cfa_register = 0xd,      // Define CFA register
428
    DWRF_CFA_def_cfa_offset = 0xe,        // Define CFA offset
429
    DWRF_CFA_offset_extended_sf = 0x11,   // Extended signed offset
430
    DWRF_CFA_advance_loc = 0x40,          // Advance location counter
431
    DWRF_CFA_offset = 0x80,               // Simple offset instruction
432
    DWRF_CFA_restore = 0xc0               // Restore register
433
};
434
435
/* DWARF Exception Handling pointer encodings */
436
enum {
437
    DWRF_EH_PE_absptr = 0x00,             // Absolute pointer
438
    DWRF_EH_PE_omit = 0xff,               // Omitted value
439
440
    /* Data type encodings */
441
    DWRF_EH_PE_uleb128 = 0x01,            // Unsigned LEB128
442
    DWRF_EH_PE_udata2 = 0x02,             // Unsigned 2-byte
443
    DWRF_EH_PE_udata4 = 0x03,             // Unsigned 4-byte
444
    DWRF_EH_PE_udata8 = 0x04,             // Unsigned 8-byte
445
    DWRF_EH_PE_sleb128 = 0x09,            // Signed LEB128
446
    DWRF_EH_PE_sdata2 = 0x0a,             // Signed 2-byte
447
    DWRF_EH_PE_sdata4 = 0x0b,             // Signed 4-byte
448
    DWRF_EH_PE_sdata8 = 0x0c,             // Signed 8-byte
449
    DWRF_EH_PE_signed = 0x08,             // Signed flag
450
451
    /* Reference type encodings */
452
    DWRF_EH_PE_pcrel = 0x10,              // PC-relative
453
    DWRF_EH_PE_textrel = 0x20,            // Text-relative
454
    DWRF_EH_PE_datarel = 0x30,            // Data-relative
455
    DWRF_EH_PE_funcrel = 0x40,            // Function-relative
456
    DWRF_EH_PE_aligned = 0x50,            // Aligned
457
    DWRF_EH_PE_indirect = 0x80            // Indirect
458
};
459
460
/* Additional DWARF constants for debug information */
461
enum { DWRF_TAG_compile_unit = 0x11 };
462
enum { DWRF_children_no = 0, DWRF_children_yes = 1 };
463
enum {
464
    DWRF_AT_name = 0x03,         // Name attribute
465
    DWRF_AT_stmt_list = 0x10,    // Statement list
466
    DWRF_AT_low_pc = 0x11,       // Low PC address
467
    DWRF_AT_high_pc = 0x12       // High PC address
468
};
469
enum {
470
    DWRF_FORM_addr = 0x01,       // Address form
471
    DWRF_FORM_data4 = 0x06,      // 4-byte data
472
    DWRF_FORM_string = 0x08      // String form
473
};
474
475
/* Line number program opcodes */
476
enum {
477
    DWRF_LNS_extended_op = 0,    // Extended opcode
478
    DWRF_LNS_copy = 1,           // Copy operation
479
    DWRF_LNS_advance_pc = 2,     // Advance program counter
480
    DWRF_LNS_advance_line = 3    // Advance line number
481
};
482
483
/* Line number extended opcodes */
484
enum {
485
    DWRF_LNE_end_sequence = 1,   // End of sequence
486
    DWRF_LNE_set_address = 2     // Set address
487
};
488
489
/*
490
 * Architecture-specific DWARF register numbers
491
 *
492
 * These constants define the register numbering scheme used by DWARF
493
 * for each supported architecture. The numbers must match the ABI
494
 * specification for proper stack unwinding.
495
 */
496
enum {
497
#ifdef __x86_64__
498
    /* x86_64 register numbering (note: order is defined by x86_64 ABI) */
499
    DWRF_REG_AX,    // RAX
500
    DWRF_REG_DX,    // RDX
501
    DWRF_REG_CX,    // RCX
502
    DWRF_REG_BX,    // RBX
503
    DWRF_REG_SI,    // RSI
504
    DWRF_REG_DI,    // RDI
505
    DWRF_REG_BP,    // RBP
506
    DWRF_REG_SP,    // RSP
507
    DWRF_REG_8,     // R8
508
    DWRF_REG_9,     // R9
509
    DWRF_REG_10,    // R10
510
    DWRF_REG_11,    // R11
511
    DWRF_REG_12,    // R12
512
    DWRF_REG_13,    // R13
513
    DWRF_REG_14,    // R14
514
    DWRF_REG_15,    // R15
515
    DWRF_REG_RA,    // Return address (RIP)
516
#elif defined(__aarch64__) && defined(__AARCH64EL__) && !defined(__ILP32__)
517
    /* AArch64 register numbering */
518
    DWRF_REG_FP = 29,  // Frame Pointer
519
    DWRF_REG_RA = 30,  // Link register (return address)
520
    DWRF_REG_SP = 31,  // Stack pointer
521
#else
522
#    error "Unsupported target architecture"
523
#endif
524
};
525
526
/* DWARF encoding constants used in EH frame headers */
527
static const uint8_t DwarfUData4 = 0x03;     // Unsigned 4-byte data
528
static const uint8_t DwarfSData4 = 0x0b;     // Signed 4-byte data
529
static const uint8_t DwarfPcRel = 0x10;      // PC-relative encoding
530
static const uint8_t DwarfDataRel = 0x30;    // Data-relative encoding
531
532
// =============================================================================
533
//                              ELF OBJECT CONTEXT
534
// =============================================================================
535
536
/*
537
 * Context for building ELF/DWARF structures
538
 *
539
 * This structure maintains state while constructing DWARF unwind information.
540
 * It acts as a simple buffer manager with pointers to track current position
541
 * and important landmarks within the buffer.
542
 */
543
typedef struct ELFObjectContext {
544
    uint8_t* p;            // Current write position in buffer
545
    uint8_t* startp;       // Start of buffer (for offset calculations)
546
    uint8_t* eh_frame_p;   // Start of EH frame data (for relative offsets)
547
    uint8_t* fde_p;        // Start of FDE data (for PC-relative calculations)
548
    uint32_t code_size;    // Size of the code being described
549
} ELFObjectContext;
550
551
/*
552
 * EH Frame Header structure for DWARF unwinding
553
 *
554
 * This structure provides metadata about the DWARF unwinding information
555
 * that follows. It's required by the perf jitdump format to enable proper
556
 * stack unwinding during profiling.
557
 */
558
typedef struct {
559
    unsigned char version;           // EH frame version (always 1)
560
    unsigned char eh_frame_ptr_enc;  // Encoding of EH frame pointer
561
    unsigned char fde_count_enc;     // Encoding of FDE count
562
    unsigned char table_enc;         // Encoding of table entries
563
    int32_t eh_frame_ptr;           // Pointer to EH frame data
564
    int32_t eh_fde_count;           // Number of FDEs (Frame Description Entries)
565
    int32_t from;                   // Start address of code range
566
    int32_t to;                     // End address of code range
567
} EhFrameHeader;
568
569
// =============================================================================
570
//                              DWARF GENERATION UTILITIES
571
// =============================================================================
572
573
/*
574
 * Append a null-terminated string to the ELF context buffer
575
 *
576
 * Args:
577
 *   ctx: ELF object context
578
 *   str: String to append (must be null-terminated)
579
 *
580
 * Returns: Offset from start of buffer where string was written
581
 */
582
0
static uint32_t elfctx_append_string(ELFObjectContext* ctx, const char* str) {
583
0
    uint8_t* p = ctx->p;
584
0
    uint32_t ofs = (uint32_t)(p - ctx->startp);
585
586
    /* Copy string including null terminator */
587
0
    do {
588
0
        *p++ = (uint8_t)*str;
589
0
    } while (*str++);
590
591
0
    ctx->p = p;
592
0
    return ofs;
593
0
}
594
595
/*
596
 * Append a SLEB128 (Signed Little Endian Base 128) value
597
 *
598
 * SLEB128 is a variable-length encoding used extensively in DWARF.
599
 * It efficiently encodes small numbers in fewer bytes.
600
 *
601
 * Args:
602
 *   ctx: ELF object context
603
 *   v: Signed value to encode
604
 */
605
0
static void elfctx_append_sleb128(ELFObjectContext* ctx, int32_t v) {
606
0
    uint8_t* p = ctx->p;
607
608
    /* Encode 7 bits at a time, with continuation bit in MSB */
609
0
    for (; (uint32_t)(v + 0x40) >= 0x80; v >>= 7) {
610
0
        *p++ = (uint8_t)((v & 0x7f) | 0x80);  // Set continuation bit
611
0
    }
612
0
    *p++ = (uint8_t)(v & 0x7f);  // Final byte without continuation bit
613
614
0
    ctx->p = p;
615
0
}
616
617
/*
618
 * Append a ULEB128 (Unsigned Little Endian Base 128) value
619
 *
620
 * Similar to SLEB128 but for unsigned values.
621
 *
622
 * Args:
623
 *   ctx: ELF object context
624
 *   v: Unsigned value to encode
625
 */
626
0
static void elfctx_append_uleb128(ELFObjectContext* ctx, uint32_t v) {
627
0
    uint8_t* p = ctx->p;
628
629
    /* Encode 7 bits at a time, with continuation bit in MSB */
630
0
    for (; v >= 0x80; v >>= 7) {
631
0
        *p++ = (char)((v & 0x7f) | 0x80);  // Set continuation bit
632
0
    }
633
0
    *p++ = (char)v;  // Final byte without continuation bit
634
635
0
    ctx->p = p;
636
0
}
637
638
/*
639
 * Macros for generating DWARF structures
640
 *
641
 * These macros provide a convenient way to write various data types
642
 * to the DWARF buffer while automatically advancing the pointer.
643
 */
644
#define DWRF_U8(x) (*p++ = (x))                                    // Write unsigned 8-bit
645
#define DWRF_I8(x) (*(int8_t*)p = (x), p++)                       // Write signed 8-bit
646
#define DWRF_U16(x) (*(uint16_t*)p = (x), p += 2)                 // Write unsigned 16-bit
647
#define DWRF_U32(x) (*(uint32_t*)p = (x), p += 4)                 // Write unsigned 32-bit
648
#define DWRF_ADDR(x) (*(uintptr_t*)p = (x), p += sizeof(uintptr_t)) // Write address
649
#define DWRF_UV(x) (ctx->p = p, elfctx_append_uleb128(ctx, (x)), p = ctx->p) // Write ULEB128
650
#define DWRF_SV(x) (ctx->p = p, elfctx_append_sleb128(ctx, (x)), p = ctx->p) // Write SLEB128
651
#define DWRF_STR(str) (ctx->p = p, elfctx_append_string(ctx, (str)), p = ctx->p) // Write string
652
653
/* Align to specified boundary with NOP instructions */
654
#define DWRF_ALIGNNOP(s)                                          \
655
    while ((uintptr_t)p & ((s)-1)) {                              \
656
        *p++ = DWRF_CFA_nop;                                       \
657
    }
658
659
/* Write a DWARF section with automatic size calculation */
660
#define DWRF_SECTION(name, stmt)                                  \
661
0
    {                                                             \
662
0
        uint32_t* szp_##name = (uint32_t*)p;                      \
663
0
        p += 4;                                                   \
664
0
        stmt;                                                     \
665
0
        *szp_##name = (uint32_t)((p - (uint8_t*)szp_##name) - 4); \
666
0
    }
667
668
// =============================================================================
669
//                              DWARF EH FRAME GENERATION
670
// =============================================================================
671
672
static void elf_init_ehframe(ELFObjectContext* ctx);
673
674
/*
675
 * Initialize DWARF .eh_frame section for a code region
676
 *
677
 * The .eh_frame section contains Call Frame Information (CFI) that describes
678
 * how to unwind the stack at any point in the code. This is essential for
679
 * proper profiling as it allows perf to generate accurate call graphs.
680
 *
681
 * The function generates two main components:
682
 * 1. CIE (Common Information Entry) - describes calling conventions
683
 * 2. FDE (Frame Description Entry) - describes specific function unwinding
684
 *
685
 * Args:
686
 *   ctx: ELF object context containing code size and buffer pointers
687
 */
688
0
static size_t calculate_eh_frame_size(void) {
689
    /* Calculate the EH frame size for the trampoline function */
690
0
    extern void *_Py_trampoline_func_start;
691
0
    extern void *_Py_trampoline_func_end;
692
693
0
    size_t code_size = (char*)&_Py_trampoline_func_end - (char*)&_Py_trampoline_func_start;
694
695
0
    ELFObjectContext ctx;
696
0
    char buffer[1024];  // Buffer for DWARF data (1KB should be sufficient)
697
0
    ctx.code_size = code_size;
698
0
    ctx.startp = ctx.p = (uint8_t*)buffer;
699
0
    ctx.fde_p = NULL;
700
701
0
    elf_init_ehframe(&ctx);
702
0
    return ctx.p - ctx.startp;
703
0
}
704
705
0
static void elf_init_ehframe(ELFObjectContext* ctx) {
706
0
    uint8_t* p = ctx->p;
707
0
    uint8_t* framep = p;  // Remember start of frame data
708
709
    /*
710
    * DWARF Unwind Table for Trampoline Function
711
    *
712
    * This section defines DWARF Call Frame Information (CFI) using encoded macros
713
    * like `DWRF_U8`, `DWRF_UV`, and `DWRF_SECTION` to describe how the trampoline function
714
    * preserves and restores registers. This is used by profiling tools (e.g., `perf`)
715
    * and debuggers for stack unwinding in JIT-compiled code.
716
    *
717
    * -------------------------------------------------
718
    * TO REGENERATE THIS TABLE FROM GCC OBJECTS:
719
    * -------------------------------------------------
720
    *
721
    * 1. Create a trampoline source file (e.g., `trampoline.c`):
722
    *
723
    *      #include <Python.h>
724
    *      typedef PyObject* (*py_evaluator)(void*, void*, int);
725
    *      PyObject* trampoline(void *ts, void *f, int throwflag, py_evaluator evaluator) {
726
    *          return evaluator(ts, f, throwflag);
727
    *      }
728
    *
729
    * 2. Compile to an object file with frame pointer preservation:
730
    *
731
    *      gcc trampoline.c -I. -I./Include -O2 -fno-omit-frame-pointer -mno-omit-leaf-frame-pointer -c
732
    *
733
    * 3. Extract DWARF unwind info from the object file:
734
    *
735
    *      readelf -w trampoline.o
736
    *
737
    *    Example output from `.eh_frame`:
738
    *
739
    *      00000000 CIE
740
    *        Version:               1
741
    *        Augmentation:          "zR"
742
    *        Code alignment factor: 4
743
    *        Data alignment factor: -8
744
    *        Return address column: 30
745
    *        DW_CFA_def_cfa: r31 (sp) ofs 0
746
    *
747
    *      00000014 FDE cie=00000000 pc=0..14
748
    *        DW_CFA_advance_loc: 4
749
    *        DW_CFA_def_cfa_offset: 16
750
    *        DW_CFA_offset: r29 at cfa-16
751
    *        DW_CFA_offset: r30 at cfa-8
752
    *        DW_CFA_advance_loc: 12
753
    *        DW_CFA_restore: r30
754
    *        DW_CFA_restore: r29
755
    *        DW_CFA_def_cfa_offset: 0
756
    *
757
    * -- These values can be verified by comparing with `readelf -w` or `llvm-dwarfdump --eh-frame`.
758
    *
759
    * ----------------------------------
760
    * HOW TO TRANSLATE TO DWRF_* MACROS:
761
    * ----------------------------------
762
    *
763
    * After compiling your trampoline with:
764
    *
765
    *     gcc trampoline.c -I. -I./Include -O2 -fno-omit-frame-pointer -mno-omit-leaf-frame-pointer -c
766
    *
767
    * run:
768
    *
769
    *     readelf -w trampoline.o
770
    *
771
    * to inspect the generated `.eh_frame` data. You will see two main components:
772
    *
773
    *     1. A CIE (Common Information Entry): shared configuration used by all FDEs.
774
    *     2. An FDE (Frame Description Entry): function-specific unwind instructions.
775
    *
776
    * ---------------------
777
    * Translating the CIE:
778
    * ---------------------
779
    * From `readelf -w`, you might see:
780
    *
781
    *   00000000 0000000000000010 00000000 CIE
782
    *     Version:               1
783
    *     Augmentation:          "zR"
784
    *     Code alignment factor: 4
785
    *     Data alignment factor: -8
786
    *     Return address column: 30
787
    *     Augmentation data:     1b
788
    *     DW_CFA_def_cfa: r31 (sp) ofs 0
789
    *
790
    * Map this to:
791
    *
792
    *     DWRF_SECTION(CIE,
793
    *         DWRF_U32(0);                             // CIE ID (always 0 for CIEs)
794
    *         DWRF_U8(DWRF_CIE_VERSION);              // Version: 1
795
    *         DWRF_STR("zR");                         // Augmentation string "zR"
796
    *         DWRF_UV(4);                             // Code alignment factor = 4
797
    *         DWRF_SV(-8);                            // Data alignment factor = -8
798
    *         DWRF_U8(DWRF_REG_RA);                   // Return address register (e.g., x30 = 30)
799
    *         DWRF_UV(1);                             // Augmentation data length = 1
800
    *         DWRF_U8(DWRF_EH_PE_pcrel | DWRF_EH_PE_sdata4); // Encoding for FDE pointers
801
    *
802
    *         DWRF_U8(DWRF_CFA_def_cfa);              // DW_CFA_def_cfa
803
    *         DWRF_UV(DWRF_REG_SP);                   // Register: SP (r31)
804
    *         DWRF_UV(0);                             // Offset = 0
805
    *
806
    *         DWRF_ALIGNNOP(sizeof(uintptr_t));       // Align to pointer size boundary
807
    *     )
808
    *
809
    * Notes:
810
    *   - Use `DWRF_UV` for unsigned LEB128, `DWRF_SV` for signed LEB128.
811
    *   - `DWRF_REG_RA` and `DWRF_REG_SP` are architecture-defined constants.
812
    *
813
    * ---------------------
814
    * Translating the FDE:
815
    * ---------------------
816
    * From `readelf -w`:
817
    *
818
    *   00000014 0000000000000020 00000018 FDE cie=00000000 pc=0000000000000000..0000000000000014
819
    *     DW_CFA_advance_loc: 4
820
    *     DW_CFA_def_cfa_offset: 16
821
    *     DW_CFA_offset: r29 at cfa-16
822
    *     DW_CFA_offset: r30 at cfa-8
823
    *     DW_CFA_advance_loc: 12
824
    *     DW_CFA_restore: r30
825
    *     DW_CFA_restore: r29
826
    *     DW_CFA_def_cfa_offset: 0
827
    *
828
    * Map the FDE header and instructions to:
829
    *
830
    *     DWRF_SECTION(FDE,
831
    *         DWRF_U32((uint32_t)(p - framep));       // Offset to CIE (relative from here)
832
    *         DWRF_U32(pc_relative_offset);           // PC-relative location of the code (calculated dynamically)
833
    *         DWRF_U32(ctx->code_size);               // Code range covered by this FDE
834
    *         DWRF_U8(0);                             // Augmentation data length (none)
835
    *
836
    *         DWRF_U8(DWRF_CFA_advance_loc | 1);      // Advance location by 1 unit (1 * 4 = 4 bytes)
837
    *         DWRF_U8(DWRF_CFA_def_cfa_offset);       // CFA = SP + 16
838
    *         DWRF_UV(16);
839
    *
840
    *         DWRF_U8(DWRF_CFA_offset | DWRF_REG_FP); // Save x29 (frame pointer)
841
    *         DWRF_UV(2);                             // At offset 2 * 8 = 16 bytes
842
    *
843
    *         DWRF_U8(DWRF_CFA_offset | DWRF_REG_RA); // Save x30 (return address)
844
    *         DWRF_UV(1);                             // At offset 1 * 8 = 8 bytes
845
    *
846
    *         DWRF_U8(DWRF_CFA_advance_loc | 3);      // Advance location by 3 units (3 * 4 = 12 bytes)
847
    *
848
    *         DWRF_U8(DWRF_CFA_offset | DWRF_REG_RA); // Restore x30
849
    *         DWRF_U8(DWRF_CFA_offset | DWRF_REG_FP); // Restore x29
850
    *
851
    *         DWRF_U8(DWRF_CFA_def_cfa_offset);       // CFA = SP
852
    *         DWRF_UV(0);
853
    *     )
854
    *
855
    * To regenerate:
856
    *   1. Get the `code alignment factor`, `data alignment factor`, and `RA column` from the CIE.
857
    *   2. Note the range of the function from the FDE's `pc=...` line and map it to the JIT code as
858
    *      the code is in a different address space every time.
859
    *   3. For each `DW_CFA_*` entry, use the corresponding `DWRF_*` macro:
860
    *        - `DW_CFA_def_cfa_offset`     → DWRF_U8(DWRF_CFA_def_cfa_offset), DWRF_UV(value)
861
    *        - `DW_CFA_offset: rX`         → DWRF_U8(DWRF_CFA_offset | reg), DWRF_UV(offset)
862
    *        - `DW_CFA_restore: rX`        → DWRF_U8(DWRF_CFA_offset | reg) // restore is same as reusing offset
863
    *        - `DW_CFA_advance_loc: N`     → DWRF_U8(DWRF_CFA_advance_loc | (N / code_alignment_factor))
864
    *   4. Use `DWRF_REG_FP`, `DWRF_REG_RA`, etc., for register numbers.
865
    *   5. Use `sizeof(uintptr_t)` (typically 8) for pointer size calculations and alignment.
866
    */
867
868
    /*
869
     * Emit DWARF EH CIE (Common Information Entry)
870
     *
871
     * The CIE describes the calling conventions and basic unwinding rules
872
     * that apply to all functions in this compilation unit.
873
     */
874
0
    DWRF_SECTION(CIE,
875
0
        DWRF_U32(0);                           // CIE ID (0 indicates this is a CIE)
876
0
        DWRF_U8(DWRF_CIE_VERSION);            // CIE version (1)
877
0
        DWRF_STR("zR");                       // Augmentation string ("zR" = has LSDA)
878
0
#ifdef __x86_64__
879
0
        DWRF_UV(1);                           // Code alignment factor (x86_64: 1 byte)
880
#elif defined(__aarch64__) && defined(__AARCH64EL__) && !defined(__ILP32__)
881
        DWRF_UV(4);                           // Code alignment factor (AArch64: 4 bytes per instruction)
882
#endif
883
0
        DWRF_SV(-(int64_t)sizeof(uintptr_t)); // Data alignment factor (negative)
884
0
        DWRF_U8(DWRF_REG_RA);                 // Return address register number
885
0
        DWRF_UV(1);                           // Augmentation data length
886
0
        DWRF_U8(DWRF_EH_PE_pcrel | DWRF_EH_PE_sdata4); // FDE pointer encoding
887
888
        /* Initial CFI instructions - describe default calling convention */
889
0
#ifdef __x86_64__
890
        /* x86_64 initial CFI state */
891
0
        DWRF_U8(DWRF_CFA_def_cfa);            // Define CFA (Call Frame Address)
892
0
        DWRF_UV(DWRF_REG_SP);                 // CFA = SP register
893
0
        DWRF_UV(sizeof(uintptr_t));           // CFA = SP + pointer_size
894
0
        DWRF_U8(DWRF_CFA_offset|DWRF_REG_RA); // Return address is saved
895
0
        DWRF_UV(1);                           // At offset 1 from CFA
896
#elif defined(__aarch64__) && defined(__AARCH64EL__) && !defined(__ILP32__)
897
        /* AArch64 initial CFI state */
898
        DWRF_U8(DWRF_CFA_def_cfa);            // Define CFA (Call Frame Address)
899
        DWRF_UV(DWRF_REG_SP);                 // CFA = SP register
900
        DWRF_UV(0);                           // CFA = SP + 0 (AArch64 starts with offset 0)
901
        // No initial register saves in AArch64 CIE
902
#endif
903
0
        DWRF_ALIGNNOP(sizeof(uintptr_t));     // Align to pointer boundary
904
0
    )
905
906
0
    ctx->eh_frame_p = p;  // Remember start of FDE data
907
908
    /*
909
     * Emit DWARF EH FDE (Frame Description Entry)
910
     *
911
     * The FDE describes unwinding information specific to this function.
912
     * It references the CIE and provides function-specific CFI instructions.
913
     *
914
     * The PC-relative offset is calculated after the entire EH frame is built
915
     * to ensure accurate positioning relative to the synthesized DSO layout.
916
     */
917
0
    DWRF_SECTION(FDE,
918
0
        DWRF_U32((uint32_t)(p - framep));     // Offset to CIE (backwards reference)
919
0
        ctx->fde_p = p;                        // Remember where PC offset field is located for later calculation
920
0
        DWRF_U32(0);                           // Placeholder for PC-relative offset (calculated at end of elf_init_ehframe)
921
0
        DWRF_U32(ctx->code_size);             // Address range covered by this FDE (code length)
922
0
        DWRF_U8(0);                           // Augmentation data length (none)
923
924
        /*
925
         * Architecture-specific CFI instructions
926
         *
927
         * These instructions describe how registers are saved and restored
928
         * during function calls. Each architecture has different calling
929
         * conventions and register usage patterns.
930
         */
931
0
#ifdef __x86_64__
932
        /* x86_64 calling convention unwinding rules with frame pointer */
933
#  if defined(__CET__) && (__CET__ & 1)
934
        DWRF_U8(DWRF_CFA_advance_loc | 4);    // Advance past endbr64 (4 bytes)
935
#  endif
936
0
        DWRF_U8(DWRF_CFA_advance_loc | 1);    // Advance past push %rbp (1 byte)
937
0
        DWRF_U8(DWRF_CFA_def_cfa_offset);     // def_cfa_offset 16
938
0
        DWRF_UV(16);                          // New offset: SP + 16
939
0
        DWRF_U8(DWRF_CFA_offset | DWRF_REG_BP); // offset r6 at cfa-16
940
0
        DWRF_UV(2);                           // Offset factor: 2 * 8 = 16 bytes
941
0
        DWRF_U8(DWRF_CFA_advance_loc | 3);    // Advance past mov %rsp,%rbp (3 bytes)
942
0
        DWRF_U8(DWRF_CFA_def_cfa_register);   // def_cfa_register r6
943
0
        DWRF_UV(DWRF_REG_BP);                 // Use base pointer register
944
0
        DWRF_U8(DWRF_CFA_advance_loc | 3);    // Advance past call *%rcx (2 bytes) + pop %rbp (1 byte) = 3
945
0
        DWRF_U8(DWRF_CFA_def_cfa);            // def_cfa r7 ofs 8
946
0
        DWRF_UV(DWRF_REG_SP);                 // Use stack pointer register
947
0
        DWRF_UV(8);                           // New offset: SP + 8
948
#elif defined(__aarch64__) && defined(__AARCH64EL__) && !defined(__ILP32__)
949
        /* AArch64 calling convention unwinding rules */
950
        DWRF_U8(DWRF_CFA_advance_loc | 1);        // Advance by 1 instruction (4 bytes)
951
        DWRF_U8(DWRF_CFA_def_cfa_offset);         // CFA = SP + 16
952
        DWRF_UV(16);                              // Stack pointer moved by 16 bytes
953
        DWRF_U8(DWRF_CFA_offset | DWRF_REG_FP);   // x29 (frame pointer) saved
954
        DWRF_UV(2);                               // At CFA-16 (2 * 8 = 16 bytes from CFA)
955
        DWRF_U8(DWRF_CFA_offset | DWRF_REG_RA);   // x30 (link register) saved
956
        DWRF_UV(1);                               // At CFA-8 (1 * 8 = 8 bytes from CFA)
957
        DWRF_U8(DWRF_CFA_advance_loc | 3);        // Advance by 3 instructions (12 bytes)
958
        DWRF_U8(DWRF_CFA_restore | DWRF_REG_RA);  // Restore x30 - NO DWRF_UV() after this!
959
        DWRF_U8(DWRF_CFA_restore | DWRF_REG_FP);  // Restore x29 - NO DWRF_UV() after this!
960
        DWRF_U8(DWRF_CFA_def_cfa_offset);         // CFA = SP + 0 (stack restored)
961
        DWRF_UV(0);                               // Back to original stack position
962
#else
963
#    error "Unsupported target architecture"
964
#endif
965
966
0
        DWRF_ALIGNNOP(sizeof(uintptr_t));     // Align to pointer boundary
967
0
    )
968
969
0
    ctx->p = p;  // Update context pointer to end of generated data
970
971
    /* Calculate and update the PC-relative offset in the FDE
972
     *
973
     * When perf processes the jitdump, it creates a synthesized DSO with this layout:
974
     *
975
     *     Synthesized DSO Memory Layout:
976
     *     ┌─────────────────────────────────────────────────────────────┐ < code_start
977
     *     │                        Code Section                         │
978
     *     │                    (round_up(code_size, 8) bytes)           │
979
     *     ├─────────────────────────────────────────────────────────────┤ < start of EH frame data
980
     *     │                      EH Frame Data                          │
981
     *     │  ┌─────────────────────────────────────────────────────┐    │
982
     *     │  │                 CIE data                            │    │
983
     *     │  └─────────────────────────────────────────────────────┘    │
984
     *     │  ┌─────────────────────────────────────────────────────┐    │
985
     *     │  │ FDE Header:                                         │    │
986
     *     │  │   - CIE offset (4 bytes)                            │    │
987
     *     │  │   - PC offset (4 bytes) <─ fde_offset_in_frame ─────┼────┼─> points to code_start
988
     *     │  │   - address range (4 bytes)                         │    │   (this specific field)
989
     *     │  │ CFI Instructions...                                 │    │
990
     *     │  └─────────────────────────────────────────────────────┘    │
991
     *     ├─────────────────────────────────────────────────────────────┤ < reference_point
992
     *     │                    EhFrameHeader                            │
993
     *     │                 (navigation metadata)                       │
994
     *     └─────────────────────────────────────────────────────────────┘
995
     *
996
     * The PC offset field in the FDE must contain the distance from itself to code_start:
997
     *
998
     *   distance = code_start - fde_pc_field
999
     *
1000
     * Where:
1001
     *   fde_pc_field_location = reference_point - eh_frame_size + fde_offset_in_frame
1002
     *   code_start_location = reference_point - eh_frame_size - round_up(code_size, 8)
1003
     *
1004
     * Therefore:
1005
     *   distance = code_start_location - fde_pc_field_location
1006
     *            = (ref - eh_frame_size - rounded_code_size) - (ref - eh_frame_size + fde_offset_in_frame)
1007
     *            = -rounded_code_size - fde_offset_in_frame
1008
     *            = -(round_up(code_size, 8) + fde_offset_in_frame)
1009
     *
1010
     * Note: fde_offset_in_frame is the offset from EH frame start to the PC offset field,
1011
     *
1012
     */
1013
0
    if (ctx->fde_p != NULL) {
1014
0
        int32_t fde_offset_in_frame = (ctx->fde_p - ctx->startp);
1015
0
        int32_t rounded_code_size = round_up(ctx->code_size, 8);
1016
0
        int32_t pc_relative_offset = -(rounded_code_size + fde_offset_in_frame);
1017
1018
1019
        // Update the PC-relative offset in the FDE
1020
0
        *(int32_t*)ctx->fde_p = pc_relative_offset;
1021
0
    }
1022
0
}
1023
1024
// =============================================================================
1025
//                              JITDUMP INITIALIZATION
1026
// =============================================================================
1027
1028
/*
1029
 * Initialize the perf jitdump interface
1030
 *
1031
 * This function sets up everything needed to generate jitdump files:
1032
 * 1. Creates the jitdump file with a unique name
1033
 * 2. Maps the first page to signal perf that we're using the interface
1034
 * 3. Writes the jitdump header
1035
 * 4. Initializes synchronization primitives
1036
 *
1037
 * The memory mapping is crucial - perf detects jitdump files by scanning
1038
 * for processes that have mapped files matching the pattern /tmp/jit-*.dump
1039
 *
1040
 * Returns: Pointer to initialized state, or NULL on failure
1041
 */
1042
0
static void* perf_map_jit_init(void) {
1043
0
    char filename[100];
1044
0
    int pid = getpid();
1045
1046
    /* Create unique filename based on process ID */
1047
0
    snprintf(filename, sizeof(filename) - 1, "/tmp/jit-%d.dump", pid);
1048
1049
    /* Create/open the jitdump file with appropriate permissions */
1050
0
    const int fd = open(filename, O_CREAT | O_TRUNC | O_RDWR, 0666);
1051
0
    if (fd == -1) {
1052
0
        return NULL;  // Failed to create file
1053
0
    }
1054
1055
    /* Get system page size for memory mapping */
1056
0
    const long page_size = sysconf(_SC_PAGESIZE);
1057
0
    if (page_size == -1) {
1058
0
        close(fd);
1059
0
        return NULL;  // Failed to get page size
1060
0
    }
1061
1062
#if defined(__APPLE__)
1063
    // On macOS, samply uses a preload to find jitdumps and this mmap can be slow.
1064
    perf_jit_map_state.mapped_buffer = NULL;
1065
#else
1066
    /*
1067
     * Map the first page of the jitdump file
1068
     *
1069
     * This memory mapping serves as a signal to perf that this process
1070
     * is generating JIT code. Perf scans /proc/.../maps looking for mapped
1071
     * files that match the jitdump naming pattern.
1072
     *
1073
     * The mapping must be PROT_READ | PROT_EXEC to be detected by perf.
1074
     */
1075
0
    perf_jit_map_state.mapped_buffer = mmap(
1076
0
        NULL,                    // Let kernel choose address
1077
0
        page_size,               // Map one page
1078
0
        PROT_READ | PROT_EXEC,   // Read and execute permissions (required by perf)
1079
0
        MAP_PRIVATE,             // Private mapping
1080
0
        fd,                      // File descriptor
1081
0
        0                        // Offset 0 (first page)
1082
0
    );
1083
1084
0
    if (perf_jit_map_state.mapped_buffer == NULL) {
1085
0
        close(fd);
1086
0
        return NULL;  // Memory mapping failed
1087
0
    }
1088
0
#endif
1089
1090
0
    perf_jit_map_state.mapped_size = page_size;
1091
1092
    /* Convert file descriptor to FILE* for easier I/O operations */
1093
0
    perf_jit_map_state.perf_map = fdopen(fd, "w+");
1094
0
    if (perf_jit_map_state.perf_map == NULL) {
1095
0
        close(fd);
1096
0
        return NULL;  // Failed to create FILE*
1097
0
    }
1098
1099
    /*
1100
     * Set up file buffering for better performance
1101
     *
1102
     * We use a large buffer (2MB) because jitdump files can be written
1103
     * frequently during program execution. Buffering reduces system call
1104
     * overhead and improves overall performance.
1105
     */
1106
0
    setvbuf(perf_jit_map_state.perf_map, NULL, _IOFBF, 2 * MB);
1107
1108
    /* Write the jitdump file header */
1109
0
    perf_map_jit_write_header(pid, perf_jit_map_state.perf_map);
1110
1111
    /*
1112
     * Initialize thread synchronization lock
1113
     *
1114
     * Multiple threads may attempt to write to the jitdump file
1115
     * simultaneously. This lock ensures thread-safe access to the
1116
     * global jitdump state.
1117
     */
1118
0
    perf_jit_map_state.map_lock = PyThread_allocate_lock();
1119
0
    if (perf_jit_map_state.map_lock == NULL) {
1120
0
        fclose(perf_jit_map_state.perf_map);
1121
0
        return NULL;  // Failed to create lock
1122
0
    }
1123
1124
    /* Initialize code ID counter */
1125
0
    perf_jit_map_state.code_id = 0;
1126
1127
    /* Calculate padding size based on actual unwind info requirements */
1128
0
    size_t eh_frame_size = calculate_eh_frame_size();
1129
0
    size_t unwind_data_size = sizeof(EhFrameHeader) + eh_frame_size;
1130
0
    trampoline_api.code_padding = round_up(unwind_data_size, 16);
1131
0
    trampoline_api.code_alignment = 32;
1132
1133
0
    return &perf_jit_map_state;
1134
0
}
1135
1136
// =============================================================================
1137
//                              MAIN JITDUMP ENTRY WRITING
1138
// =============================================================================
1139
1140
/*
1141
 * Write a complete jitdump entry for a Python function
1142
 *
1143
 * This is the main function called by Python's trampoline system whenever
1144
 * a new piece of JIT-compiled code needs to be recorded. It writes both
1145
 * the unwinding information and the code load event to the jitdump file.
1146
 *
1147
 * The function performs these steps:
1148
 * 1. Initialize jitdump system if not already done
1149
 * 2. Extract function name and filename from Python code object
1150
 * 3. Generate DWARF unwinding information
1151
 * 4. Write unwinding info event to jitdump file
1152
 * 5. Write code load event to jitdump file
1153
 *
1154
 * Args:
1155
 *   state: Jitdump state (currently unused, uses global state)
1156
 *   code_addr: Address where the compiled code resides
1157
 *   code_size: Size of the compiled code in bytes
1158
 *   co: Python code object containing metadata
1159
 *
1160
 * IMPORTANT: This function signature is part of Python's internal API
1161
 * and must not be changed without coordinating with core Python development.
1162
 */
1163
static void perf_map_jit_write_entry(void *state, const void *code_addr,
1164
                                    unsigned int code_size, PyCodeObject *co)
1165
0
{
1166
    /* Initialize jitdump system on first use */
1167
0
    if (perf_jit_map_state.perf_map == NULL) {
1168
0
        void* ret = perf_map_jit_init();
1169
0
        if(ret == NULL){
1170
0
            return;  // Initialization failed, silently abort
1171
0
        }
1172
0
    }
1173
1174
    /*
1175
     * Extract function information from Python code object
1176
     *
1177
     * We create a human-readable function name by combining the qualified
1178
     * name (includes class/module context) with the filename. This helps
1179
     * developers identify functions in perf reports.
1180
     */
1181
0
    const char *entry = "";
1182
0
    if (co->co_qualname != NULL) {
1183
0
        entry = PyUnicode_AsUTF8(co->co_qualname);
1184
0
    }
1185
1186
0
    const char *filename = "";
1187
0
    if (co->co_filename != NULL) {
1188
0
        filename = PyUnicode_AsUTF8(co->co_filename);
1189
0
    }
1190
1191
    /*
1192
     * Create formatted function name for perf display
1193
     *
1194
     * Format: "py::<function_name>:<filename>"
1195
     * The "py::" prefix helps identify Python functions in mixed-language
1196
     * profiles (e.g., when profiling C extensions alongside Python code).
1197
     */
1198
0
    size_t perf_map_entry_size = snprintf(NULL, 0, "py::%s:%s", entry, filename) + 1;
1199
0
    char* perf_map_entry = (char*) PyMem_RawMalloc(perf_map_entry_size);
1200
0
    if (perf_map_entry == NULL) {
1201
0
        return;  // Memory allocation failed
1202
0
    }
1203
0
    snprintf(perf_map_entry, perf_map_entry_size, "py::%s:%s", entry, filename);
1204
1205
0
    const size_t name_length = strlen(perf_map_entry);
1206
0
    uword base = (uword)code_addr;
1207
0
    uword size = code_size;
1208
1209
    /*
1210
     * Generate DWARF unwinding information
1211
     *
1212
     * DWARF data is essential for proper stack unwinding during profiling.
1213
     * Without it, perf cannot generate accurate call graphs, especially
1214
     * in optimized code where frame pointers may be omitted.
1215
     */
1216
0
    ELFObjectContext ctx;
1217
0
    char buffer[1024];  // Buffer for DWARF data (1KB should be sufficient)
1218
0
    ctx.code_size = code_size;
1219
0
    ctx.startp = ctx.p = (uint8_t*)buffer;
1220
0
    ctx.fde_p = NULL;  // Initialize to NULL, will be set when FDE is written
1221
1222
    /* Generate EH frame (Exception Handling frame) data */
1223
0
    elf_init_ehframe(&ctx);
1224
0
    int eh_frame_size = ctx.p - ctx.startp;
1225
1226
    /*
1227
     * Write Code Unwinding Information Event
1228
     *
1229
     * This event must be written before the code load event to ensure
1230
     * perf has the unwinding information available when it processes
1231
     * the code region.
1232
     */
1233
0
    CodeUnwindingInfoEvent ev2;
1234
0
    ev2.base.event = PerfUnwindingInfo;
1235
0
    ev2.base.time_stamp = get_current_monotonic_ticks();
1236
0
    ev2.unwind_data_size = sizeof(EhFrameHeader) + eh_frame_size;
1237
1238
    /* Verify we don't exceed our padding budget */
1239
0
    assert(ev2.unwind_data_size <= (uint64_t)trampoline_api.code_padding);
1240
1241
0
    ev2.eh_frame_hdr_size = sizeof(EhFrameHeader);
1242
0
    ev2.mapped_size = round_up(ev2.unwind_data_size, 16);  // 16-byte alignment
1243
1244
    /* Calculate total event size with padding */
1245
0
    int content_size = sizeof(ev2) + sizeof(EhFrameHeader) + eh_frame_size;
1246
0
    int padding_size = round_up(content_size, 8) - content_size;  // 8-byte align
1247
0
    ev2.base.size = content_size + padding_size;
1248
1249
    /* Write the unwinding info event header */
1250
0
    perf_map_jit_write_fully(&ev2, sizeof(ev2));
1251
1252
    /*
1253
     * Write EH Frame Header
1254
     *
1255
     * The EH frame header provides metadata about the DWARF unwinding
1256
     * information that follows. It includes pointers and counts that
1257
     * help perf navigate the unwinding data efficiently.
1258
     */
1259
0
    EhFrameHeader f;
1260
0
    f.version = 1;
1261
0
    f.eh_frame_ptr_enc = DwarfSData4 | DwarfPcRel;  // PC-relative signed 4-byte
1262
0
    f.fde_count_enc = DwarfUData4;                  // Unsigned 4-byte count
1263
0
    f.table_enc = DwarfSData4 | DwarfDataRel;       // Data-relative signed 4-byte
1264
1265
    /* Calculate relative offsets for EH frame navigation */
1266
0
    f.eh_frame_ptr = -(eh_frame_size + 4 * sizeof(unsigned char));
1267
0
    f.eh_fde_count = 1;  // We generate exactly one FDE per function
1268
0
    f.from = -(round_up(code_size, 8) + eh_frame_size);
1269
1270
0
    int cie_size = ctx.eh_frame_p - ctx.startp;
1271
0
    f.to = -(eh_frame_size - cie_size);
1272
1273
    /* Write EH frame data and header */
1274
0
    perf_map_jit_write_fully(ctx.startp, eh_frame_size);
1275
0
    perf_map_jit_write_fully(&f, sizeof(f));
1276
1277
    /* Write padding to maintain alignment */
1278
0
    char padding_bytes[] = "\0\0\0\0\0\0\0\0";
1279
0
    perf_map_jit_write_fully(&padding_bytes, padding_size);
1280
1281
    /*
1282
     * Write Code Load Event
1283
     *
1284
     * This event tells perf about the new code region. It includes:
1285
     * - Memory addresses and sizes
1286
     * - Process and thread identification
1287
     * - Function name for symbol resolution
1288
     * - The actual machine code bytes
1289
     */
1290
0
    CodeLoadEvent ev;
1291
0
    ev.base.event = PerfLoad;
1292
0
    ev.base.size = sizeof(ev) + (name_length+1) + size;
1293
0
    ev.base.time_stamp = get_current_monotonic_ticks();
1294
0
    ev.process_id = getpid();
1295
#if defined(__APPLE__)
1296
    pthread_threadid_np(NULL, &ev.thread_id);
1297
#else
1298
0
    ev.thread_id = syscall(SYS_gettid);  // Get thread ID via system call
1299
0
#endif
1300
0
    ev.vma = base;                       // Virtual memory address
1301
0
    ev.code_address = base;              // Same as VMA for our use case
1302
0
    ev.code_size = size;
1303
1304
    /* Assign unique code ID and increment counter */
1305
0
    perf_jit_map_state.code_id += 1;
1306
0
    ev.code_id = perf_jit_map_state.code_id;
1307
1308
    /* Write code load event and associated data */
1309
0
    perf_map_jit_write_fully(&ev, sizeof(ev));
1310
0
    perf_map_jit_write_fully(perf_map_entry, name_length+1);  // Include null terminator
1311
0
    perf_map_jit_write_fully((void*)(base), size);           // Copy actual machine code
1312
1313
    /* Clean up allocated memory */
1314
0
    PyMem_RawFree(perf_map_entry);
1315
0
}
1316
1317
// =============================================================================
1318
//                              CLEANUP AND FINALIZATION
1319
// =============================================================================
1320
1321
/*
1322
 * Finalize and cleanup the perf jitdump system
1323
 *
1324
 * This function is called when Python is shutting down or when the
1325
 * perf trampoline system is being disabled. It ensures all resources
1326
 * are properly released and all buffered data is flushed to disk.
1327
 *
1328
 * Args:
1329
 *   state: Jitdump state (currently unused, uses global state)
1330
 *
1331
 * Returns: 0 on success
1332
 *
1333
 * IMPORTANT: This function signature is part of Python's internal API
1334
 * and must not be changed without coordinating with core Python development.
1335
 */
1336
0
static int perf_map_jit_fini(void* state) {
1337
    /*
1338
     * Close jitdump file with proper synchronization
1339
     *
1340
     * We need to acquire the lock to ensure no other threads are
1341
     * writing to the file when we close it. This prevents corruption
1342
     * and ensures all data is properly flushed.
1343
     */
1344
0
    if (perf_jit_map_state.perf_map != NULL) {
1345
0
        PyThread_acquire_lock(perf_jit_map_state.map_lock, 1);
1346
0
        fclose(perf_jit_map_state.perf_map);  // This also flushes buffers
1347
0
        PyThread_release_lock(perf_jit_map_state.map_lock);
1348
1349
        /* Clean up synchronization primitive */
1350
0
        PyThread_free_lock(perf_jit_map_state.map_lock);
1351
0
        perf_jit_map_state.perf_map = NULL;
1352
0
    }
1353
1354
    /*
1355
     * Unmap the memory region
1356
     *
1357
     * This removes the signal to perf that we were generating JIT code.
1358
     * After this point, perf will no longer detect this process as
1359
     * having JIT capabilities.
1360
     */
1361
0
    if (perf_jit_map_state.mapped_buffer != NULL) {
1362
0
        munmap(perf_jit_map_state.mapped_buffer, perf_jit_map_state.mapped_size);
1363
0
        perf_jit_map_state.mapped_buffer = NULL;
1364
0
    }
1365
1366
    /* Clear global state reference */
1367
0
    trampoline_api.state = NULL;
1368
1369
0
    return 0;  // Success
1370
0
}
1371
1372
// =============================================================================
1373
//                              PUBLIC API EXPORT
1374
// =============================================================================
1375
1376
/*
1377
 * Python Perf Callbacks Structure
1378
 *
1379
 * This structure defines the callback interface that Python's trampoline
1380
 * system uses to integrate with perf profiling. It contains function
1381
 * pointers for initialization, event writing, and cleanup.
1382
 *
1383
 * CRITICAL: This structure and its contents are part of Python's internal
1384
 * API. The function signatures and behavior must remain stable to maintain
1385
 * compatibility with the Python interpreter's perf integration system.
1386
 *
1387
 * Used by: Python's _PyPerf_Callbacks system in pycore_ceval.h
1388
 */
1389
_PyPerf_Callbacks _Py_perfmap_jit_callbacks = {
1390
    &perf_map_jit_init,        // Initialization function
1391
    &perf_map_jit_write_entry, // Event writing function
1392
    &perf_map_jit_fini,        // Cleanup function
1393
};
1394
1395
#endif /* PY_HAVE_PERF_TRAMPOLINE */