Coverage Report

Created: 2026-12-01 06:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Python/remote_debug.h
Line
Count
Source
1
/*
2
IMPORTANT: This header file is full of static functions that are not exported.
3
4
The reason is that we don't want to export these functions to the Python API
5
and they can be used both for the interpreter and some shared libraries. The
6
reason we don't want to export them is to avoid having them participating in
7
return-oriented programming attacks.
8
9
If you need to add a new function ensure that is declared 'static'.
10
*/
11
12
#ifdef __cplusplus
13
extern "C" {
14
#endif
15
16
#ifdef __clang__
17
    #define UNUSED __attribute__((unused))
18
#elif defined(__GNUC__)
19
    #define UNUSED __attribute__((unused))
20
#elif defined(_MSC_VER)
21
    #define UNUSED __pragma(warning(suppress: 4505))
22
#else
23
    #define UNUSED
24
#endif
25
26
#if !defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
27
#  error "this header requires Py_BUILD_CORE or Py_BUILD_CORE_MODULE define"
28
#endif
29
30
#include "pyconfig.h"
31
#include "internal/pycore_ceval.h"
32
33
#ifdef __linux__
34
#    include <elf.h>
35
#    include <sys/uio.h>
36
#    include <sys/ptrace.h>
37
#    include <sys/wait.h>
38
#    include <dirent.h>
39
#    if INTPTR_MAX == INT64_MAX
40
0
#        define Elf_Ehdr Elf64_Ehdr
41
0
#        define Elf_Shdr Elf64_Shdr
42
0
#        define Elf_Phdr Elf64_Phdr
43
#    else
44
#        define Elf_Ehdr Elf32_Ehdr
45
#        define Elf_Shdr Elf32_Shdr
46
#        define Elf_Phdr Elf32_Phdr
47
#    endif
48
#    include <sys/mman.h>
49
50
// PTRACE options - define if not available
51
#    ifndef PTRACE_SEIZE
52
#        define PTRACE_SEIZE 0x4206
53
#    endif
54
#    ifndef PTRACE_INTERRUPT
55
#        define PTRACE_INTERRUPT 0x4207
56
#    endif
57
#    ifndef PTRACE_EVENT_STOP
58
#        define PTRACE_EVENT_STOP 128
59
#    endif
60
#endif
61
62
#if defined(__APPLE__) && defined(TARGET_OS_OSX) && TARGET_OS_OSX
63
#  include <mach-o/dyld_images.h>
64
#  include <mach-o/loader.h>
65
#  include <mach/error.h>
66
#  include <mach/mach.h>
67
#  include <mach/mach_vm.h>
68
#  include <mach/task_info.h>
69
#  include <mach/thread_act.h>
70
#endif
71
72
#ifdef MS_WINDOWS
73
    // Windows includes and definitions
74
#include <windows.h>
75
#include <psapi.h>
76
#include <tlhelp32.h>
77
#endif
78
79
#include <errno.h>
80
#include <fcntl.h>
81
#include <stddef.h>
82
#include <stdint.h>
83
#include <stdio.h>
84
#include <stdlib.h>
85
#include <string.h>
86
#ifndef MS_WINDOWS
87
#include <sys/param.h>
88
#include <sys/stat.h>
89
#include <sys/types.h>
90
#include <unistd.h>
91
#endif
92
93
#ifndef HAVE_PROCESS_VM_READV
94
#    define HAVE_PROCESS_VM_READV 0
95
#endif
96
97
static inline int
98
_Py_RemoteDebug_HasPermissionError(void)
99
0
{
100
0
    return PyErr_Occurred()
101
0
        && PyErr_ExceptionMatches(PyExc_PermissionError);
102
0
}
103
104
static inline int
105
_Py_RemoteDebug_IsFatalReadError(void)
106
0
{
107
0
    return _Py_RemoteDebug_HasPermissionError()
108
0
        || PyErr_ExceptionMatches(PyExc_MemoryError)
109
0
        || PyErr_ExceptionMatches(PyExc_ProcessLookupError)
110
0
        || (PyErr_Occurred() && !PyErr_ExceptionMatches(PyExc_Exception));
111
0
}
112
113
#define _set_debug_exception_cause(exception, format, ...) \
114
0
    do { \
115
0
        if (!_Py_RemoteDebug_IsFatalReadError()) { \
116
0
            PyThreadState *tstate = _PyThreadState_GET(); \
117
0
            if (!_PyErr_Occurred(tstate)) { \
118
0
                _PyErr_Format(tstate, exception, format, ##__VA_ARGS__); \
119
0
            } else { \
120
0
                _PyErr_FormatFromCause(exception, format, ##__VA_ARGS__); \
121
0
            } \
122
0
        } \
123
0
    } while (0)
124
125
#define _set_debug_oserror_from_errno(err, format, ...) \
126
    do { \
127
        errno = (err); \
128
        PyErr_SetFromErrno(PyExc_OSError); \
129
        _set_debug_exception_cause(PyExc_OSError, format, ##__VA_ARGS__); \
130
    } while (0)
131
132
#define _set_debug_oserror_from_errno_with_filename(err, filename, format, ...) \
133
0
    do { \
134
0
        errno = (err); \
135
0
        PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename); \
136
0
        _set_debug_exception_cause(PyExc_OSError, format, ##__VA_ARGS__); \
137
0
    } while (0)
138
139
static inline size_t
140
0
get_page_size(void) {
141
0
    size_t page_size = 0;
142
0
    if (page_size == 0) {
143
#ifdef MS_WINDOWS
144
        SYSTEM_INFO si;
145
        GetSystemInfo(&si);
146
        page_size = si.dwPageSize;
147
#else
148
0
        long n = sysconf(_SC_PAGESIZE);
149
0
        page_size = (n > 0) ? (size_t)n : 4096;
150
0
#endif
151
0
    }
152
0
    return page_size;
153
0
}
154
155
typedef struct page_cache_entry {
156
    uintptr_t page_addr; // page-aligned base address
157
    char *data;
158
} page_cache_entry_t;
159
160
0
#define MAX_PAGES 1024
161
162
// Define a platform-independent process handle structure
163
typedef struct {
164
    pid_t pid;
165
#if defined(__APPLE__) && defined(TARGET_OS_OSX) && TARGET_OS_OSX
166
    mach_port_t task;
167
#elif defined(MS_WINDOWS)
168
    HANDLE hProcess;
169
#elif defined(__linux__)
170
    int memfd;
171
#endif
172
    page_cache_entry_t pages[MAX_PAGES];
173
    int page_cache_count;
174
    Py_ssize_t page_size;
175
} proc_handle_t;
176
177
// Forward declaration for use in validation function
178
static int
179
_Py_RemoteDebug_ReadRemoteMemory(proc_handle_t *handle, uintptr_t remote_address, size_t len, void* dst);
180
181
// Optional callback to validate a candidate section address found during
182
// memory map searches. Returns 1 if the address is valid, 0 to skip it.
183
// This allows callers to filter out duplicate/stale mappings (e.g. from
184
// ctypes dlopen) whose sections were never initialized.
185
typedef int (*section_validator_t)(proc_handle_t *handle, uintptr_t address);
186
187
// Validate that a candidate address starts with _Py_Debug_Cookie.
188
UNUSED static int
189
_Py_RemoteDebug_ValidatePyRuntimeCookie(proc_handle_t *handle, uintptr_t address)
190
0
{
191
0
    if (address == 0) {
192
0
        return 0;
193
0
    }
194
0
    char buf[sizeof(_Py_Debug_Cookie) - 1];
195
0
    if (_Py_RemoteDebug_ReadRemoteMemory(handle, address, sizeof(buf), buf) != 0) {
196
0
        if (!_Py_RemoteDebug_IsFatalReadError()) {
197
0
            PyErr_Clear();
198
0
        }
199
0
        return 0;
200
0
    }
201
0
    return memcmp(buf, _Py_Debug_Cookie, sizeof(buf)) == 0;
202
0
}
203
204
static void
205
_Py_RemoteDebug_FreePageCache(proc_handle_t *handle)
206
0
{
207
0
    for (int i = 0; i < MAX_PAGES; i++) {
208
0
        if (handle->pages[i].data) {
209
0
            PyMem_RawFree(handle->pages[i].data);
210
0
        }
211
0
        handle->pages[i].data = NULL;
212
0
    }
213
0
    handle->page_cache_count = 0;
214
0
}
215
216
UNUSED static void
217
_Py_RemoteDebug_ClearCache(proc_handle_t *handle)
218
0
{
219
0
    handle->page_cache_count = 0;
220
0
}
221
222
#if defined(__APPLE__) && defined(TARGET_OS_OSX) && TARGET_OS_OSX
223
static mach_port_t pid_to_task(pid_t pid);
224
#endif
225
226
// Initialize the process handle
227
UNUSED static int
228
0
_Py_RemoteDebug_InitProcHandle(proc_handle_t *handle, pid_t pid) {
229
0
    handle->pid = 0;
230
#if defined(__APPLE__) && defined(TARGET_OS_OSX) && TARGET_OS_OSX
231
    handle->task = 0;
232
#elif defined(MS_WINDOWS)
233
    handle->hProcess = NULL;
234
#elif defined(__linux__)
235
    handle->memfd = -1;
236
0
#endif
237
0
    handle->page_size = get_page_size();
238
0
    handle->page_cache_count = 0;
239
0
    for (int i = 0; i < MAX_PAGES; i++) {
240
0
        handle->pages[i].data = NULL;
241
0
    }
242
243
0
    handle->pid = pid;
244
#if defined(__APPLE__) && defined(TARGET_OS_OSX) && TARGET_OS_OSX
245
    handle->task = pid_to_task(handle->pid);
246
    if (handle->task == 0) {
247
        _set_debug_exception_cause(PyExc_RuntimeError, "Failed to initialize macOS process handle");
248
        return -1;
249
    }
250
#elif defined(MS_WINDOWS)
251
    handle->hProcess = OpenProcess(
252
        PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_VM_OPERATION | PROCESS_QUERY_INFORMATION | PROCESS_SUSPEND_RESUME,
253
        FALSE, pid);
254
    if (handle->hProcess == NULL) {
255
        DWORD error = GetLastError();
256
        PyErr_SetFromWindowsErr(error);
257
        _set_debug_exception_cause(PyExc_RuntimeError, "Failed to initialize Windows process handle");
258
        return -1;
259
    }
260
#endif
261
0
    return 0;
262
0
}
263
264
// Clean up the process handle
265
UNUSED static void
266
0
_Py_RemoteDebug_CleanupProcHandle(proc_handle_t *handle) {
267
#ifdef MS_WINDOWS
268
    if (handle->hProcess != NULL) {
269
        CloseHandle(handle->hProcess);
270
        handle->hProcess = NULL;
271
    }
272
#elif defined(__APPLE__) && defined(TARGET_OS_OSX) && TARGET_OS_OSX
273
    if (handle->task != MACH_PORT_NULL) {
274
        mach_port_deallocate(mach_task_self(), handle->task);
275
        handle->task = MACH_PORT_NULL;
276
    }
277
#elif defined(__linux__)
278
0
    if (handle->memfd != -1) {
279
0
        close(handle->memfd);
280
0
        handle->memfd = -1;
281
0
    }
282
0
#endif
283
0
    handle->pid = 0;
284
0
    _Py_RemoteDebug_FreePageCache(handle);
285
0
}
286
287
#if defined(__APPLE__) && defined(TARGET_OS_OSX) && TARGET_OS_OSX
288
289
enum {
290
    MACHO_NAME_SIZE = 16,
291
    MACHO_MAX_LOAD_COMMAND_BYTES = 16 * 1024 * 1024,
292
    DYLD_MAX_IMAGE_COUNT = 65536,
293
};
294
295
/* These 64-bit little-endian layouts work on both arm64 and x86_64 (Rosetta). */
296
static_assert(sizeof(uintptr_t) == sizeof(uint64_t), "64-bit macOS required");
297
298
static uintptr_t
299
macho_section_address(const void *image, size_t image_size,
300
                      uintptr_t base, const char *name)
301
{
302
    struct mach_header_64 header;
303
    if (image_size < sizeof(header)) {
304
        return 0;
305
    }
306
    memcpy(&header, image, sizeof(header));
307
    if (header.magic != MH_MAGIC_64 ||
308
        header.sizeofcmds > image_size - sizeof(header))
309
    {
310
        return 0;
311
    }
312
313
    const unsigned char *cursor = (const unsigned char *)image + sizeof(header);
314
    size_t remaining = header.sizeofcmds;
315
    uint64_t header_address = 0, section_address = 0;
316
    int have_header = 0, have_section = 0;
317
    for (uint32_t index = 0; index < header.ncmds; index++) {
318
        struct load_command command;
319
        if (remaining < sizeof(command)) {
320
            return 0;
321
        }
322
        memcpy(&command, cursor, sizeof(command));
323
        size_t command_size = command.cmdsize;
324
        if (command_size < sizeof(command) || command_size > remaining) {
325
            return 0;
326
        }
327
        if (command.cmd == LC_SEGMENT_64) {
328
            struct segment_command_64 segment;
329
            if (command_size < sizeof(segment)) {
330
                return 0;
331
            }
332
            memcpy(&segment, cursor, sizeof(segment));
333
            if (segment.nsects >
334
                (command_size - sizeof(segment)) / sizeof(struct section_64))
335
            {
336
                return 0;
337
            }
338
            /* __PAGEZERO has no file contents and does not define the slide. */
339
            if (segment.fileoff == 0 && segment.filesize != 0) {
340
                header_address = segment.vmaddr;
341
                have_header = 1;
342
            }
343
            if (strncmp(segment.segname, "__DATA", MACHO_NAME_SIZE) == 0) {
344
                const unsigned char *record = cursor + sizeof(segment);
345
                for (uint32_t item = 0; item < segment.nsects;
346
                     item++, record += sizeof(struct section_64))
347
                {
348
                    struct section_64 section;
349
                    memcpy(&section, record, sizeof(section));
350
                    if (strncmp(section.sectname, name, MACHO_NAME_SIZE) == 0) {
351
                        section_address = section.addr;
352
                        have_section = 1;
353
                    }
354
                }
355
            }
356
        }
357
        cursor += command_size;
358
        remaining -= command_size;
359
    }
360
    if (!have_header || !have_section || section_address < header_address ||
361
        section_address - header_address > UINTPTR_MAX - base)
362
    {
363
        return 0;
364
    }
365
    return base + (uintptr_t)(section_address - header_address);
366
}
367
368
static uintptr_t
369
search_section_in_memory(proc_handle_t *handle, uintptr_t base,
370
                         const char *section)
371
{
372
    /* Most images fit in one read. Stay within the smallest macOS page size. */
373
    unsigned char prefix[4096];
374
    size_t prefix_size = sizeof(prefix) - base % sizeof(prefix);
375
    struct mach_header_64 header;
376
    if (prefix_size < sizeof(header) ||
377
        _Py_RemoteDebug_ReadRemoteMemory(handle, base, prefix_size, prefix) < 0)
378
    {
379
        if (_Py_RemoteDebug_IsFatalReadError()) {
380
            return 0;
381
        }
382
        PyErr_Clear();
383
        prefix_size = sizeof(header);
384
        if (_Py_RemoteDebug_ReadRemoteMemory(handle, base, prefix_size, prefix) < 0) {
385
            return 0;
386
        }
387
    }
388
    memcpy(&header, prefix, sizeof(header));
389
    if (header.magic != MH_MAGIC_64 ||
390
        header.sizeofcmds > MACHO_MAX_LOAD_COMMAND_BYTES)
391
    {
392
        return 0;
393
    }
394
    size_t size = sizeof(header) + header.sizeofcmds;
395
    if (base > UINTPTR_MAX - size) {
396
        return 0;
397
    }
398
    if (size <= prefix_size) {
399
        return macho_section_address(prefix, size, base, section);
400
    }
401
    unsigned char *image = PyMem_Malloc(size);
402
    if (image == NULL) {
403
        PyErr_NoMemory();
404
        return 0;
405
    }
406
    memcpy(image, prefix, prefix_size);
407
    uintptr_t result = 0;
408
    if (_Py_RemoteDebug_ReadRemoteMemory(handle, base + prefix_size,
409
                                        size - prefix_size, image + prefix_size) == 0)
410
    {
411
        result = macho_section_address(image, size, base, section);
412
    }
413
    PyMem_Free(image);
414
    return result;
415
}
416
417
static mach_port_t
418
pid_to_task(pid_t pid)
419
{
420
    mach_port_t task;
421
    kern_return_t result;
422
423
    result = task_for_pid(mach_task_self(), pid, &task);
424
    if (result != KERN_SUCCESS) {
425
        PyErr_Format(PyExc_PermissionError,
426
            "Cannot get task port for PID %d (kern_return_t: %d). "
427
            "This typically requires running as root or having the 'com.apple.system-task-ports' entitlement.",
428
            pid, result);
429
        return 0;
430
    }
431
    return task;
432
}
433
434
static int
435
read_dyld_image_metadata(proc_handle_t *handle, struct dyld_all_image_infos *images)
436
{
437
    task_dyld_info_data_t info = {0};
438
    mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT;
439
    kern_return_t status = task_info(handle->task, TASK_DYLD_INFO,
440
                                    (task_info_t)&info, &count);
441
    if (status != KERN_SUCCESS) {
442
        PyErr_Format(status == KERN_PROTECTION_FAILURE
443
                     ? PyExc_PermissionError : PyExc_RuntimeError,
444
                     "Cannot read dyld information for PID %d (Mach error %d)",
445
                     handle->pid, status);
446
        return -1;
447
    }
448
    if (count < TASK_DYLD_INFO_COUNT ||
449
        info.all_image_info_format != TASK_DYLD_ALL_IMAGE_INFO_64)
450
    {
451
        PyErr_SetString(PyExc_RuntimeError, "Unsupported dyld image-info format");
452
        return -1;
453
    }
454
    size_t uuid_end = offsetof(struct dyld_all_image_infos, uuidArray) +
455
                      sizeof(images->uuidArray);
456
    size_t size = (size_t)Py_MIN(info.all_image_info_size, uuid_end);
457
    if (size < offsetof(struct dyld_all_image_infos, infoArray) +
458
               sizeof(images->infoArray) ||
459
        info.all_image_info_addr > UINTPTR_MAX - size)
460
    {
461
        PyErr_SetString(PyExc_RuntimeError, "Invalid dyld image information");
462
        return -1;
463
    }
464
    if (_Py_RemoteDebug_ReadRemoteMemory(handle, info.all_image_info_addr,
465
                                        size, images) < 0)
466
    {
467
        return -1;
468
    }
469
    /* The UUID array was added in version 8 of dyld_all_image_infos. */
470
    if (images->version < 8 || size < uuid_end) {
471
        images->uuidArray = NULL;
472
        images->uuidArrayCount = 0;
473
    }
474
    return 0;
475
}
476
477
static uintptr_t
478
search_memory_regions_for_section(proc_handle_t *handle, const char *section,
479
                                  section_validator_t validator)
480
{
481
    mach_vm_address_t address = 0;
482
    while (1) {
483
        mach_vm_size_t size = 0;
484
        vm_region_basic_info_data_64_t region;
485
        mach_msg_type_number_t count = VM_REGION_BASIC_INFO_COUNT_64;
486
        mach_port_t object = MACH_PORT_NULL;
487
        kern_return_t status = mach_vm_region(
488
            handle->task, &address, &size, VM_REGION_BASIC_INFO_64,
489
            (vm_region_info_t)&region, &count, &object);
490
        if (object != MACH_PORT_NULL) {
491
            mach_port_deallocate(mach_task_self(), object);
492
        }
493
        if (status == KERN_INVALID_ADDRESS) {
494
            return 0;
495
        }
496
        if (status != KERN_SUCCESS) {
497
            PyErr_Format(status == KERN_PROTECTION_FAILURE
498
                         ? PyExc_PermissionError : PyExc_RuntimeError,
499
                         "Cannot read memory regions for PID %d (Mach error %d)",
500
                         handle->pid, status);
501
            return 0;
502
        }
503
        vm_prot_t required = VM_PROT_READ | VM_PROT_EXECUTE;
504
        if ((region.protection & required) == required) {
505
            uintptr_t candidate = search_section_in_memory(handle, address, section);
506
            if (candidate != 0 && (validator == NULL || validator(handle, candidate))) {
507
                return candidate;
508
            }
509
            if (_Py_RemoteDebug_IsFatalReadError()) {
510
                return 0;
511
            }
512
            PyErr_Clear();
513
        }
514
        if (size == 0 || size > UINT64_MAX - address) {
515
            return 0;
516
        }
517
        address += size;
518
    }
519
}
520
521
static uintptr_t
522
search_dyld_image_array(proc_handle_t *handle, uintptr_t array_address,
523
                        size_t count, size_t record_size,
524
                        const char *section, section_validator_t validator)
525
{
526
    if (array_address == 0 || count == 0 || count > DYLD_MAX_IMAGE_COUNT ||
527
        array_address > UINTPTR_MAX - count * record_size)
528
    {
529
        return 0;
530
    }
531
    size_t size = count * record_size;
532
    unsigned char *images = PyMem_Malloc(size);
533
    if (images == NULL) {
534
        PyErr_NoMemory();
535
        return 0;
536
    }
537
    uintptr_t result = 0;
538
    if (_Py_RemoteDebug_ReadRemoteMemory(handle, array_address, size, images) < 0) {
539
        goto done;
540
    }
541
    for (size_t index = 0; index < count; index++) {
542
        /* Both dyld_image_info and dyld_uuid_info begin with imageLoadAddress. */
543
        uintptr_t address;
544
        memcpy(&address, images + index * record_size, sizeof(address));
545
        if (address == 0) {
546
            continue;
547
        }
548
        uintptr_t candidate = search_section_in_memory(handle, address, section);
549
        if (candidate != 0 && (validator == NULL || validator(handle, candidate))) {
550
            result = candidate;
551
            break;
552
        }
553
        if (_Py_RemoteDebug_IsFatalReadError()) {
554
            break;
555
        }
556
        /* A library can unload after the image list is read. */
557
        PyErr_Clear();
558
    }
559
done:
560
    PyMem_Free(images);
561
    if (!_Py_RemoteDebug_IsFatalReadError()) {
562
        PyErr_Clear();
563
    }
564
    return result;
565
}
566
567
static uintptr_t
568
search_loaded_images_for_section(proc_handle_t *handle, const char *section,
569
                                 section_validator_t validator)
570
{
571
    struct dyld_all_image_infos images = {0};
572
    if (read_dyld_image_metadata(handle, &images) == 0) {
573
        /* Python is normally outside the shared cache: try the shorter list. */
574
        uintptr_t result = search_dyld_image_array(
575
            handle, (uintptr_t)images.uuidArray, images.uuidArrayCount,
576
            sizeof(struct dyld_uuid_info), section, validator);
577
        if (result != 0 || _Py_RemoteDebug_IsFatalReadError()) {
578
            return result;
579
        }
580
        result = search_dyld_image_array(
581
            handle, (uintptr_t)images.infoArray, images.infoArrayCount,
582
            sizeof(struct dyld_image_info), section, validator);
583
        if (result != 0 || _Py_RemoteDebug_IsFatalReadError()) {
584
            return result;
585
        }
586
    }
587
    if (_Py_RemoteDebug_IsFatalReadError()) {
588
        return 0;
589
    }
590
    /* dyld can leave both lists unavailable while a stopped target is loading
591
       a library. Treat copied lists as hints and fall back to mapped images. */
592
    PyErr_Clear();
593
    return search_memory_regions_for_section(handle, section, validator);
594
}
595
596
#endif // (__APPLE__ && defined(TARGET_OS_OSX) && TARGET_OS_OSX)
597
598
#if defined(__linux__) && HAVE_PROCESS_VM_READV
599
static uintptr_t
600
search_elf_file_for_section(
601
        proc_handle_t *handle,
602
        const char* secname,
603
        uintptr_t start_address,
604
        const char *elf_file)
605
0
{
606
0
    if (start_address == 0) {
607
0
        return 0;
608
0
    }
609
610
0
    uintptr_t result = 0;
611
0
    void* file_memory = NULL;
612
613
0
    int fd = open(elf_file, O_RDONLY);
614
0
    if (fd < 0) {
615
0
        int err = errno;
616
0
        _set_debug_oserror_from_errno_with_filename(err, elf_file,
617
0
            "Cannot open ELF file '%s' for section '%s' search: %s",
618
0
            elf_file, secname, strerror(err));
619
0
        goto exit;
620
0
    }
621
622
0
    struct stat file_stats;
623
0
    if (fstat(fd, &file_stats) != 0) {
624
0
        int err = errno;
625
0
        _set_debug_oserror_from_errno_with_filename(err, elf_file,
626
0
            "Cannot get file size for ELF file '%s' during section '%s' search: %s",
627
0
            elf_file, secname, strerror(err));
628
0
        goto exit;
629
0
    }
630
631
0
    file_memory = mmap(NULL, file_stats.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
632
0
    if (file_memory == MAP_FAILED) {
633
0
        int err = errno;
634
0
        _set_debug_oserror_from_errno_with_filename(err, elf_file,
635
0
            "Cannot memory map ELF file '%s' (size: %lld bytes) for section '%s' search: %s",
636
0
            elf_file, (long long)file_stats.st_size, secname, strerror(err));
637
0
        file_memory = NULL;
638
0
        goto exit;
639
0
    }
640
641
0
    Elf_Ehdr* elf_header = (Elf_Ehdr*)file_memory;
642
643
    // Validate ELF header
644
0
    if (elf_header->e_shstrndx >= elf_header->e_shnum) {
645
0
        PyErr_Format(PyExc_RuntimeError,
646
0
            "Invalid ELF file '%s': string table index %u >= section count %u",
647
0
            elf_file, elf_header->e_shstrndx, elf_header->e_shnum);
648
0
        goto exit;
649
0
    }
650
651
0
    Elf_Shdr* section_header_table = (Elf_Shdr*)(file_memory + elf_header->e_shoff);
652
653
0
    Elf_Shdr* shstrtab_section = &section_header_table[elf_header->e_shstrndx];
654
0
    char* shstrtab = (char*)(file_memory + shstrtab_section->sh_offset);
655
656
0
    Elf_Shdr* section = NULL;
657
0
    for (int i = 0; i < elf_header->e_shnum; i++) {
658
0
        char* this_sec_name = shstrtab + section_header_table[i].sh_name;
659
        // Move 1 character to account for the leading "."
660
0
        this_sec_name += 1;
661
0
        if (strcmp(secname, this_sec_name) == 0) {
662
0
            section = &section_header_table[i];
663
0
            break;
664
0
        }
665
0
    }
666
667
0
    if (section == NULL) {
668
0
        goto exit;
669
0
    }
670
671
0
    Elf_Phdr* program_header_table = (Elf_Phdr*)(file_memory + elf_header->e_phoff);
672
    // Find the first PT_LOAD segment
673
0
    Elf_Phdr* first_load_segment = NULL;
674
0
    for (int i = 0; i < elf_header->e_phnum; i++) {
675
0
        if (program_header_table[i].p_type == PT_LOAD) {
676
0
            first_load_segment = &program_header_table[i];
677
0
            break;
678
0
        }
679
0
    }
680
681
0
    if (first_load_segment == NULL) {
682
0
        PyErr_Format(PyExc_RuntimeError,
683
0
            "No PT_LOAD segment found in ELF file '%s' (%u program headers examined)",
684
0
            elf_file, elf_header->e_phnum);
685
0
        goto exit;
686
0
    }
687
688
0
    uintptr_t elf_load_addr = first_load_segment->p_vaddr
689
0
        - (first_load_segment->p_vaddr % first_load_segment->p_align);
690
0
    result = start_address + (uintptr_t)section->sh_addr - elf_load_addr;
691
692
0
exit:
693
0
    if (file_memory != NULL) {
694
0
        if (munmap(file_memory, file_stats.st_size) != 0) {
695
0
            if (!PyErr_Occurred()) {
696
0
                int err = errno;
697
0
                _set_debug_oserror_from_errno_with_filename(err, elf_file,
698
0
                    "Failed to unmap ELF file '%s' (size: %lld bytes): %s",
699
0
                    elf_file, (long long)file_stats.st_size, strerror(err));
700
0
            }
701
0
            result = 0;
702
0
        }
703
0
    }
704
0
    if (fd >= 0 && close(fd) != 0) {
705
0
        if (!PyErr_Occurred()) {
706
0
            int err = errno;
707
0
            _set_debug_oserror_from_errno_with_filename(err, elf_file,
708
0
                "Failed to close ELF file '%s': %s",
709
0
                elf_file, strerror(err));
710
0
        }
711
0
        result = 0;
712
0
    }
713
0
    return result;
714
0
}
715
716
static const char *
717
find_debug_cookie(const char *buffer, size_t len)
718
0
{
719
0
    const char *cookie = _Py_Debug_Cookie;
720
0
    const size_t cookie_len = sizeof(_Py_Debug_Cookie) - 1;
721
0
    if (len < cookie_len) {
722
0
        return NULL;
723
0
    }
724
725
0
    size_t pos = 0;
726
0
    size_t last = len - cookie_len;
727
0
    while (pos <= last) {
728
0
        const char *candidate = memchr(
729
0
            buffer + pos, cookie[0], last - pos + 1);
730
0
        if (candidate == NULL) {
731
0
            return NULL;
732
0
        }
733
0
        pos = (size_t)(candidate - buffer);
734
0
        if (memcmp(candidate, cookie, cookie_len) == 0) {
735
0
            return candidate;
736
0
        }
737
0
        pos++;
738
0
    }
739
0
    return NULL;
740
0
}
741
742
static int
743
linux_map_path_is_deleted(const char *path)
744
0
{
745
0
    static const char deleted_suffix[] = " (deleted)";
746
0
    size_t path_len = strlen(path);
747
0
    size_t suffix_len = sizeof(deleted_suffix) - 1;
748
0
    return path_len >= suffix_len
749
0
        && strcmp(path + path_len - suffix_len, deleted_suffix) == 0;
750
0
}
751
752
static int
753
linux_map_perms_are_readwrite(const char *perms)
754
0
{
755
0
    return perms[0] == 'r' && perms[1] == 'w';
756
0
}
757
758
static uintptr_t
759
scan_linux_mapping_for_pyruntime_cookie(
760
        proc_handle_t *handle,
761
        uintptr_t start,
762
        uintptr_t end)
763
0
{
764
0
    if (end <= start) {
765
0
        return 0;
766
0
    }
767
768
0
    const size_t cookie_len = sizeof(_Py_Debug_Cookie) - 1;
769
0
    const size_t overlap = cookie_len - 1;
770
0
    const size_t chunk_size = 1024 * 1024;
771
0
    char *buffer = PyMem_Malloc(chunk_size);
772
0
    if (buffer == NULL) {
773
0
        PyErr_NoMemory();
774
0
        _set_debug_exception_cause(PyExc_MemoryError,
775
0
            "Cannot allocate memory while scanning PID %d for PyRuntime cookie",
776
0
            handle->pid);
777
0
        return 0;
778
0
    }
779
780
0
    uintptr_t retval = 0;
781
0
    uintptr_t mapping_size = end - start;
782
0
    uintptr_t offset = 0;
783
0
    while (offset < mapping_size) {
784
0
        uintptr_t remaining = mapping_size - offset;
785
0
        size_t wanted = remaining > chunk_size
786
0
            ? chunk_size : (size_t)remaining;
787
0
        if (_Py_RemoteDebug_ReadRemoteMemory(
788
0
                handle, start + offset, wanted, buffer) < 0) {
789
0
            if (_Py_RemoteDebug_HasPermissionError()) {
790
0
                goto exit;
791
0
            }
792
            // A candidate mapping can disappear or contain unreadable holes while
793
            // the target process keeps running. Treat those as non-matches and
794
            // keep scanning other candidate mappings.
795
0
            PyErr_Clear();
796
0
        }
797
0
        else {
798
0
            const char *hit = find_debug_cookie(buffer, wanted);
799
0
            if (hit != NULL) {
800
0
                retval = start + offset + (uintptr_t)(hit - buffer);
801
0
                goto exit;
802
0
            }
803
0
        }
804
805
0
        if (wanted <= overlap) {
806
0
            break;
807
0
        }
808
0
        offset += wanted - overlap;
809
0
    }
810
811
0
exit:
812
0
    PyMem_Free(buffer);
813
0
    return retval;
814
0
}
815
816
static uintptr_t
817
search_linux_map_for_section(proc_handle_t *handle, const char* secname, const char* substr,
818
                             section_validator_t validator)
819
0
{
820
0
    char maps_file_path[64];
821
0
    sprintf(maps_file_path, "/proc/%d/maps", handle->pid);
822
823
0
    FILE* maps_file = fopen(maps_file_path, "r");
824
0
    if (maps_file == NULL) {
825
0
        int err = errno;
826
0
        _set_debug_oserror_from_errno_with_filename(err, maps_file_path,
827
0
            "Cannot open process memory map file '%s' for PID %d section search: %s",
828
0
            maps_file_path, handle->pid, strerror(err));
829
0
        return 0;
830
0
    }
831
832
0
    size_t linelen = 0;
833
0
    size_t linesz = PATH_MAX;
834
0
    char *line = PyMem_Malloc(linesz);
835
0
    if (!line) {
836
0
        fclose(maps_file);
837
0
        _set_debug_exception_cause(PyExc_MemoryError,
838
0
            "Cannot allocate memory for reading process map file '%s'",
839
0
            maps_file_path);
840
0
        return 0;
841
0
    }
842
843
0
    uintptr_t retval = 0;
844
845
0
    while (fgets(line + linelen, linesz - linelen, maps_file) != NULL) {
846
0
        linelen = strlen(line);
847
0
        if (line[linelen - 1] != '\n') {
848
            // Read a partial line: realloc and keep reading where we left off.
849
            // Note that even the last line will be terminated by a newline.
850
0
            linesz *= 2;
851
0
            char *biggerline = PyMem_Realloc(line, linesz);
852
0
            if (!biggerline) {
853
0
                PyMem_Free(line);
854
0
                fclose(maps_file);
855
0
                _set_debug_exception_cause(PyExc_MemoryError,
856
0
                    "Cannot reallocate memory while reading process map file '%s' (attempted size: %zu)",
857
0
                    maps_file_path, linesz);
858
0
                return 0;
859
0
            }
860
0
            line = biggerline;
861
0
            continue;
862
0
        }
863
864
        // Read a full line: strip the newline
865
0
        line[linelen - 1] = '\0';
866
        // and prepare to read the next line into the start of the buffer.
867
0
        linelen = 0;
868
869
0
        unsigned long start = 0;
870
0
        unsigned long end = 0;
871
0
        int path_pos = 0;
872
0
        char perms[5] = "";
873
0
        int fields = sscanf(line, "%lx-%lx %4s %*s %*s %*s %n",
874
0
                            &start, &end, perms, &path_pos);
875
876
0
        if (fields < 3 || !path_pos) {
877
            // Line didn't match our format string.  This shouldn't be
878
            // possible, but let's be defensive and skip the line.
879
0
            continue;
880
0
        }
881
882
0
        const char *path = line + path_pos;
883
0
        if (path[0] == '\0') {
884
0
            continue;
885
0
        }
886
0
        if (path[0] == '[' && path[strlen(path)-1] == ']') {
887
            // Skip [heap], [stack], [anon:cpython:pymalloc], etc.
888
0
            continue;
889
0
        }
890
891
0
        const char *filename = strrchr(path, '/');
892
0
        if (filename) {
893
0
            filename++;  // Move past the '/'
894
0
        } else {
895
0
            filename = path;  // No directories, or an empty string
896
0
        }
897
898
0
        if (strstr(filename, substr)) {
899
0
            int deleted_pyruntime_mapping =
900
0
                strcmp(secname, "PyRuntime") == 0
901
0
                && linux_map_path_is_deleted(path);
902
0
            if (deleted_pyruntime_mapping
903
0
                && linux_map_perms_are_readwrite(perms)) {
904
0
                PyErr_Clear();
905
0
                retval = scan_linux_mapping_for_pyruntime_cookie(
906
0
                    handle, (uintptr_t)start, (uintptr_t)end);
907
0
            }
908
0
            if (!deleted_pyruntime_mapping
909
0
                && retval == 0 && !PyErr_Occurred()) {
910
0
                PyErr_Clear();
911
0
                retval = search_elf_file_for_section(
912
0
                    handle, secname, start, path);
913
0
            }
914
0
            if (retval) {
915
0
                if (validator == NULL || validator(handle, retval)) {
916
0
                    break;
917
0
                }
918
0
                if (_Py_RemoteDebug_HasPermissionError()) {
919
0
                    retval = 0;
920
0
                    break;
921
0
                }
922
0
            }
923
0
            else if (_Py_RemoteDebug_HasPermissionError()) {
924
0
                break;
925
0
            }
926
0
            retval = 0;
927
0
        }
928
0
    }
929
930
0
    if (retval == 0 && !PyErr_Occurred() && ferror(maps_file)) {
931
0
        int err = errno;
932
0
        _set_debug_oserror_from_errno_with_filename(err, maps_file_path,
933
0
            "Failed to read process map file '%s' for PID %d section search: %s",
934
0
            maps_file_path, handle->pid, strerror(err));
935
0
    }
936
937
0
    PyMem_Free(line);
938
0
    if (fclose(maps_file) != 0) {
939
0
        if (!PyErr_Occurred()) {
940
0
            int err = errno;
941
0
            _set_debug_oserror_from_errno_with_filename(err, maps_file_path,
942
0
                "Failed to close process map file '%s': %s",
943
0
                maps_file_path, strerror(err));
944
0
        }
945
0
        retval = 0;
946
0
    }
947
948
0
    return retval;
949
0
}
950
951
952
#endif // __linux__
953
954
#ifdef MS_WINDOWS
955
956
static int is_process_alive(HANDLE hProcess) {
957
    DWORD exitCode;
958
    if (GetExitCodeProcess(hProcess, &exitCode)) {
959
        return exitCode == STILL_ACTIVE;
960
    }
961
    return 0;
962
}
963
964
static void* analyze_pe(const wchar_t* mod_path, BYTE* remote_base, const char* secname) {
965
    HANDLE hFile = CreateFileW(mod_path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
966
    if (hFile == INVALID_HANDLE_VALUE) {
967
        DWORD error = GetLastError();
968
        PyErr_SetFromWindowsErr(error);
969
        _set_debug_exception_cause(PyExc_OSError,
970
            "Cannot open PE file for section '%s' analysis (error %lu)",
971
            secname, error);
972
        return NULL;
973
    }
974
975
    HANDLE hMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, 0);
976
    if (!hMap) {
977
        DWORD error = GetLastError();
978
        PyErr_SetFromWindowsErr(error);
979
        _set_debug_exception_cause(PyExc_OSError,
980
            "Cannot create file mapping for PE file section '%s' analysis (error %lu)",
981
            secname, error);
982
        CloseHandle(hFile);
983
        return NULL;
984
    }
985
986
    BYTE* mapView = (BYTE*)MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0);
987
    if (!mapView) {
988
        DWORD error = GetLastError();
989
        PyErr_SetFromWindowsErr(error);
990
        _set_debug_exception_cause(PyExc_OSError,
991
            "Cannot map view of PE file for section '%s' analysis (error %lu)",
992
            secname, error);
993
        CloseHandle(hMap);
994
        CloseHandle(hFile);
995
        return NULL;
996
    }
997
998
    IMAGE_DOS_HEADER* pDOSHeader = (IMAGE_DOS_HEADER*)mapView;
999
    if (pDOSHeader->e_magic != IMAGE_DOS_SIGNATURE) {
1000
        PyErr_Format(PyExc_RuntimeError,
1001
            "Invalid DOS signature (0x%x) in PE file for section '%s' analysis (expected 0x%x)",
1002
            pDOSHeader->e_magic, secname, IMAGE_DOS_SIGNATURE);
1003
        UnmapViewOfFile(mapView);
1004
        CloseHandle(hMap);
1005
        CloseHandle(hFile);
1006
        return NULL;
1007
    }
1008
1009
    IMAGE_NT_HEADERS* pNTHeaders = (IMAGE_NT_HEADERS*)(mapView + pDOSHeader->e_lfanew);
1010
    if (pNTHeaders->Signature != IMAGE_NT_SIGNATURE) {
1011
        PyErr_Format(PyExc_RuntimeError,
1012
            "Invalid NT signature (0x%lx) in PE file for section '%s' analysis (expected 0x%lx)",
1013
            pNTHeaders->Signature, secname, IMAGE_NT_SIGNATURE);
1014
        UnmapViewOfFile(mapView);
1015
        CloseHandle(hMap);
1016
        CloseHandle(hFile);
1017
        return NULL;
1018
    }
1019
1020
    IMAGE_SECTION_HEADER* pSection_header = (IMAGE_SECTION_HEADER*)(mapView + pDOSHeader->e_lfanew + sizeof(IMAGE_NT_HEADERS));
1021
    void* runtime_addr = NULL;
1022
1023
    for (int i = 0; i < pNTHeaders->FileHeader.NumberOfSections; i++) {
1024
        const char* name = (const char*)pSection_header[i].Name;
1025
        if (strncmp(name, secname, IMAGE_SIZEOF_SHORT_NAME) == 0) {
1026
            runtime_addr = remote_base + pSection_header[i].VirtualAddress;
1027
            break;
1028
        }
1029
    }
1030
1031
    UnmapViewOfFile(mapView);
1032
    CloseHandle(hMap);
1033
    CloseHandle(hFile);
1034
1035
    return runtime_addr;
1036
}
1037
1038
1039
static uintptr_t
1040
search_windows_map_for_section(proc_handle_t* handle, const char* secname, const wchar_t* substr,
1041
                               section_validator_t validator) {
1042
    HANDLE hProcSnap;
1043
    do {
1044
        hProcSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, handle->pid);
1045
    } while (hProcSnap == INVALID_HANDLE_VALUE && GetLastError() == ERROR_BAD_LENGTH);
1046
1047
    if (hProcSnap == INVALID_HANDLE_VALUE) {
1048
        DWORD error = GetLastError();
1049
        PyErr_SetFromWindowsErr(error);
1050
        _set_debug_exception_cause(PyExc_OSError,
1051
            "Unable to create module snapshot for PID %d section '%s' "
1052
            "search (error %lu). Check permissions or PID validity",
1053
            handle->pid, secname, error);
1054
        return 0;
1055
    }
1056
1057
    MODULEENTRY32W moduleEntry;
1058
    moduleEntry.dwSize = sizeof(moduleEntry);
1059
    void* runtime_addr = NULL;
1060
1061
    if (!Module32FirstW(hProcSnap, &moduleEntry)) {
1062
        DWORD error = GetLastError();
1063
        PyErr_SetFromWindowsErr(error);
1064
        _set_debug_exception_cause(PyExc_OSError,
1065
            "Unable to enumerate modules for PID %d section '%s' "
1066
            "search (error %lu)",
1067
            handle->pid, secname, error);
1068
        CloseHandle(hProcSnap);
1069
        return 0;
1070
    }
1071
1072
    do {
1073
        // Look for either python executable or DLL
1074
        if (wcsstr(moduleEntry.szModule, substr)) {
1075
            PyErr_Clear();
1076
            void *candidate = analyze_pe(moduleEntry.szExePath, moduleEntry.modBaseAddr, secname);
1077
            if (candidate != NULL) {
1078
                if (validator == NULL || validator(handle, (uintptr_t)candidate)) {
1079
                    runtime_addr = candidate;
1080
                    break;
1081
                }
1082
                if (_Py_RemoteDebug_HasPermissionError()) {
1083
                    break;
1084
                }
1085
            }
1086
            else if (_Py_RemoteDebug_HasPermissionError()) {
1087
                break;
1088
            }
1089
        }
1090
    } while (Module32NextW(hProcSnap, &moduleEntry));
1091
1092
    if (runtime_addr == NULL && !PyErr_Occurred()) {
1093
        DWORD error = GetLastError();
1094
        if (error != ERROR_NO_MORE_FILES) {
1095
            PyErr_SetFromWindowsErr(error);
1096
            _set_debug_exception_cause(PyExc_OSError,
1097
                "Module enumeration failed for PID %d section '%s' "
1098
                "search (error %lu)",
1099
                handle->pid, secname, error);
1100
        }
1101
    }
1102
1103
    CloseHandle(hProcSnap);
1104
1105
    return (uintptr_t)runtime_addr;
1106
}
1107
1108
#endif // MS_WINDOWS
1109
1110
// Get the PyRuntime section address for any platform
1111
UNUSED static uintptr_t
1112
_Py_RemoteDebug_GetPyRuntimeAddress(proc_handle_t* handle)
1113
0
{
1114
0
    uintptr_t address;
1115
1116
#ifdef MS_WINDOWS
1117
    // On Windows, search for 'python' in executable or DLL
1118
    address = search_windows_map_for_section(handle, "PyRuntime", L"python",
1119
                                             _Py_RemoteDebug_ValidatePyRuntimeCookie);
1120
    if (address == 0) {
1121
        if (!_Py_RemoteDebug_HasPermissionError()) {
1122
            // Error out: 'python' substring covers both executable and DLL
1123
            PyObject *exc = PyErr_GetRaisedException();
1124
            PyErr_Format(PyExc_RuntimeError,
1125
                "Failed to find the PyRuntime section in process %d on Windows platform",
1126
                handle->pid);
1127
            _PyErr_ChainExceptions1(exc);
1128
        }
1129
    }
1130
#elif defined(__linux__) && HAVE_PROCESS_VM_READV
1131
    // On Linux, search for 'python' in executable or DLL
1132
0
    address = search_linux_map_for_section(handle, "PyRuntime", "python",
1133
0
                                           _Py_RemoteDebug_ValidatePyRuntimeCookie);
1134
0
    if (address == 0) {
1135
0
        if (!_Py_RemoteDebug_HasPermissionError()) {
1136
            // Error out: 'python' substring covers both executable and DLL
1137
0
            PyObject *exc = PyErr_GetRaisedException();
1138
0
            PyErr_Format(PyExc_RuntimeError,
1139
0
                "Failed to find the PyRuntime section in process %d on Linux platform",
1140
0
                handle->pid);
1141
0
            _PyErr_ChainExceptions1(exc);
1142
0
        }
1143
0
    }
1144
#elif defined(__APPLE__) && defined(TARGET_OS_OSX) && TARGET_OS_OSX
1145
    address = search_loaded_images_for_section(
1146
        handle, "PyRuntime", _Py_RemoteDebug_ValidatePyRuntimeCookie);
1147
    if (address == 0) {
1148
        if (!_Py_RemoteDebug_HasPermissionError()) {
1149
            PyObject *exc = PyErr_GetRaisedException();
1150
            PyErr_Format(PyExc_RuntimeError,
1151
                "Failed to find the PyRuntime section in process %d "
1152
                "on macOS platform",
1153
                handle->pid);
1154
            _PyErr_ChainExceptions1(exc);
1155
        }
1156
    }
1157
#else
1158
    _set_debug_exception_cause(PyExc_RuntimeError,
1159
        "Reading the PyRuntime section is not supported on this platform");
1160
    return 0;
1161
#endif
1162
1163
0
    return address;
1164
0
}
1165
1166
#if defined(__linux__) && HAVE_PROCESS_VM_READV
1167
1168
static int
1169
open_proc_mem_fd(proc_handle_t *handle)
1170
0
{
1171
0
    char mem_file_path[64];
1172
0
    sprintf(mem_file_path, "/proc/%d/mem", handle->pid);
1173
1174
0
    handle->memfd = open(mem_file_path, O_RDWR);
1175
0
    if (handle->memfd == -1) {
1176
0
        int err = errno;
1177
0
        _set_debug_oserror_from_errno_with_filename(err, mem_file_path,
1178
0
            "failed to open file %s: %s", mem_file_path, strerror(err));
1179
0
        return -1;
1180
0
    }
1181
0
    return 0;
1182
0
}
1183
1184
// Why is pwritev not guarded? Except on Android API level 23 (no longer
1185
// supported), HAVE_PROCESS_VM_READV is sufficient.
1186
static int
1187
read_remote_memory_fallback(proc_handle_t *handle, uintptr_t remote_address, size_t len, void* dst)
1188
0
{
1189
0
    if (len == 0) {
1190
0
        return 0;
1191
0
    }
1192
0
    if (handle->memfd == -1) {
1193
0
        if (open_proc_mem_fd(handle) < 0) {
1194
0
            return -1;
1195
0
        }
1196
0
    }
1197
1198
0
    struct iovec local[1];
1199
0
    Py_ssize_t result = 0;
1200
0
    Py_ssize_t read_bytes = 0;
1201
1202
0
    do {
1203
0
        local[0].iov_base = (char*)dst + result;
1204
0
        local[0].iov_len = len - result;
1205
0
        off_t offset = remote_address + result;
1206
1207
0
        read_bytes = preadv(handle->memfd, local, 1, offset);
1208
0
        if (read_bytes < 0) {
1209
0
            int err = errno;
1210
0
            errno = err;
1211
0
            PyErr_SetFromErrno(PyExc_OSError);
1212
0
            _set_debug_exception_cause(PyExc_OSError,
1213
0
                "preadv failed for PID %d at address 0x%lx "
1214
0
                "(size %zu, partial read %zd bytes): %s",
1215
0
                handle->pid, remote_address + result, len - result, result, strerror(err));
1216
0
            return -1;
1217
0
        }
1218
1219
0
        if (read_bytes == 0) {
1220
0
            PyErr_Format(PyExc_OSError,
1221
0
                "preadv returned 0 bytes for PID %d at address 0x%lx "
1222
0
                "(size %zu, partial read %zd bytes)",
1223
0
                handle->pid, remote_address + result, len - result, result);
1224
0
            return -1;
1225
0
        }
1226
0
        result += read_bytes;
1227
0
    } while ((size_t)read_bytes != local[0].iov_len);
1228
0
    return 0;
1229
0
}
1230
1231
#endif // __linux__
1232
1233
// Platform-independent memory read function
1234
static int
1235
_Py_RemoteDebug_ReadRemoteMemory(proc_handle_t *handle, uintptr_t remote_address, size_t len, void* dst)
1236
0
{
1237
0
    if (len == 0) {
1238
0
        return 0;
1239
0
    }
1240
#ifdef MS_WINDOWS
1241
    SIZE_T read_bytes = 0;
1242
    SIZE_T result = 0;
1243
    do {
1244
        if (!ReadProcessMemory(handle->hProcess, (LPCVOID)(remote_address + result), (char*)dst + result, len - result, &read_bytes)) {
1245
            DWORD error = GetLastError();
1246
            // Check if the process is still alive: we need to be able to tell our caller
1247
            // that the process is dead and not just that the read failed.
1248
            if (!is_process_alive(handle->hProcess)) {
1249
                _set_errno(ESRCH);
1250
                PyErr_SetFromErrno(PyExc_OSError);
1251
                return -1;
1252
            }
1253
            PyErr_SetFromWindowsErr(error);
1254
            _set_debug_exception_cause(PyExc_OSError,
1255
                "ReadProcessMemory failed for PID %d at address 0x%lx "
1256
                "(size %zu, partial read %zu bytes): Windows error %lu",
1257
                handle->pid, remote_address + result, len - result, result, error);
1258
            return -1;
1259
        }
1260
        if (read_bytes == 0) {
1261
            PyErr_Format(PyExc_OSError,
1262
                "ReadProcessMemory returned 0 bytes for PID %d at address 0x%lx "
1263
                "(size %zu, partial read %zu bytes)",
1264
                handle->pid, remote_address + result, len - result, result);
1265
            return -1;
1266
        }
1267
        result += read_bytes;
1268
    } while (result < len);
1269
    return 0;
1270
#elif defined(__linux__) && HAVE_PROCESS_VM_READV
1271
0
    if (handle->memfd != -1) {
1272
0
        return read_remote_memory_fallback(handle, remote_address, len, dst);
1273
0
    }
1274
0
    struct iovec local[1];
1275
0
    struct iovec remote[1];
1276
0
    Py_ssize_t result = 0;
1277
0
    Py_ssize_t read_bytes = 0;
1278
1279
0
    do {
1280
0
        local[0].iov_base = (char*)dst + result;
1281
0
        local[0].iov_len = len - result;
1282
0
        remote[0].iov_base = (void*)(remote_address + result);
1283
0
        remote[0].iov_len = len - result;
1284
1285
0
        read_bytes = process_vm_readv(handle->pid, local, 1, remote, 1, 0);
1286
0
        if (read_bytes < 0) {
1287
0
            int err = errno;
1288
0
            if (err == ENOSYS) {
1289
0
                return read_remote_memory_fallback(handle, remote_address, len, dst);
1290
0
            }
1291
0
            errno = err;
1292
0
            PyErr_SetFromErrno(PyExc_OSError);
1293
0
            if (err == ESRCH) {
1294
0
                return -1;
1295
0
            }
1296
0
            _set_debug_exception_cause(PyExc_OSError,
1297
0
                "process_vm_readv failed for PID %d at address 0x%lx "
1298
0
                "(size %zu, partial read %zd bytes): %s",
1299
0
                handle->pid, remote_address + result, len - result, result, strerror(err));
1300
0
            return -1;
1301
0
        }
1302
1303
0
        if (read_bytes == 0) {
1304
0
            PyErr_Format(PyExc_OSError,
1305
0
                "process_vm_readv returned 0 bytes for PID %d at address 0x%lx "
1306
0
                "(size %zu, partial read %zd bytes)",
1307
0
                handle->pid, remote_address + result, len - result, result);
1308
0
            return -1;
1309
0
        }
1310
0
        result += read_bytes;
1311
0
    } while ((size_t)read_bytes != local[0].iov_len);
1312
0
    return 0;
1313
#elif defined(__APPLE__) && defined(TARGET_OS_OSX) && TARGET_OS_OSX
1314
    mach_vm_size_t bytes_read = 0;
1315
    kern_return_t kr = mach_vm_read_overwrite(
1316
        handle->task,
1317
        (mach_vm_address_t)remote_address,
1318
        len,
1319
        (mach_vm_address_t)dst,
1320
        &bytes_read);
1321
1322
    if (kr != KERN_SUCCESS) {
1323
        switch (err_get_code(kr)) {
1324
        case KERN_PROTECTION_FAILURE:
1325
            PyErr_Format(PyExc_PermissionError,
1326
                "Memory protection failure reading from PID %d at address "
1327
                "0x%lx (size %zu): insufficient permissions",
1328
                handle->pid, remote_address, len);
1329
            break;
1330
        case KERN_INVALID_ARGUMENT: {
1331
            // Perform a task_info check to see if the invalid argument is due
1332
            // to the process being terminated
1333
            task_basic_info_data_t task_basic_info;
1334
            mach_msg_type_number_t task_info_count = TASK_BASIC_INFO_COUNT;
1335
            kern_return_t task_valid_check = task_info(handle->task, TASK_BASIC_INFO,
1336
                                                        (task_info_t)&task_basic_info,
1337
                                                        &task_info_count);
1338
            if (task_valid_check == KERN_INVALID_ARGUMENT) {
1339
                PyErr_Format(PyExc_ProcessLookupError,
1340
                    "Process %d is no longer accessible (process terminated)",
1341
                    handle->pid);
1342
            } else {
1343
                PyErr_Format(PyExc_ValueError,
1344
                    "Invalid argument to mach_vm_read_overwrite for PID %d at "
1345
                    "address 0x%lx (size %zu) - check memory permissions",
1346
                    handle->pid, remote_address, len);
1347
            }
1348
            break;
1349
        }
1350
        case KERN_NO_SPACE:
1351
        case KERN_MEMORY_ERROR:
1352
            PyErr_Format(PyExc_ProcessLookupError,
1353
                "Process %d memory space no longer available (process terminated)",
1354
                handle->pid);
1355
            break;
1356
        default:
1357
            PyErr_Format(PyExc_RuntimeError,
1358
                "mach_vm_read_overwrite failed for PID %d at address 0x%lx "
1359
                "(size %zu): kern_return_t %d",
1360
                handle->pid, remote_address, len, kr);
1361
        }
1362
        return -1;
1363
    }
1364
    if (bytes_read != (mach_vm_size_t)len) {
1365
        PyErr_Format(PyExc_OSError,
1366
            "mach_vm_read_overwrite read %llu of %zu bytes for PID %d at "
1367
            "address 0x%lx",
1368
            (unsigned long long)bytes_read, len, handle->pid, remote_address);
1369
        return -1;
1370
    }
1371
    return 0;
1372
#else
1373
    Py_UNREACHABLE();
1374
#endif
1375
0
}
1376
1377
#if defined(__linux__) && HAVE_PROCESS_VM_READV
1378
// Fallback write using /proc/pid/mem
1379
static int
1380
_Py_RemoteDebug_WriteRemoteMemoryFallback(proc_handle_t *handle, uintptr_t remote_address, size_t len, const void* src)
1381
0
{
1382
0
    if (len == 0) {
1383
0
        return 0;
1384
0
    }
1385
0
    if (handle->memfd == -1) {
1386
0
        if (open_proc_mem_fd(handle) < 0) {
1387
0
            return -1;
1388
0
        }
1389
0
    }
1390
1391
0
    struct iovec local[1];
1392
0
    Py_ssize_t result = 0;
1393
0
    Py_ssize_t written = 0;
1394
1395
0
    do {
1396
0
        local[0].iov_base = (char*)src + result;
1397
0
        local[0].iov_len = len - result;
1398
0
        off_t offset = remote_address + result;
1399
1400
0
        written = pwritev(handle->memfd, local, 1, offset);
1401
0
        if (written < 0) {
1402
0
            int err = errno;
1403
0
            errno = err;
1404
0
            PyErr_SetFromErrno(PyExc_OSError);
1405
0
            return -1;
1406
0
        }
1407
1408
0
        if (written == 0) {
1409
0
            PyErr_Format(PyExc_OSError,
1410
0
                "pwritev wrote 0 bytes for PID %d at address 0x%lx "
1411
0
                "(size %zu, partial write %zd bytes)",
1412
0
                handle->pid, remote_address + result, len - result, result);
1413
0
            return -1;
1414
0
        }
1415
0
        result += written;
1416
0
    } while ((size_t)written != local[0].iov_len);
1417
0
    return 0;
1418
0
}
1419
#endif // __linux__
1420
1421
// Platform-independent memory write function
1422
UNUSED static int
1423
_Py_RemoteDebug_WriteRemoteMemory(proc_handle_t *handle, uintptr_t remote_address, size_t len, const void* src)
1424
0
{
1425
0
    if (len == 0) {
1426
0
        return 0;
1427
0
    }
1428
#ifdef MS_WINDOWS
1429
    SIZE_T written = 0;
1430
    SIZE_T result = 0;
1431
    do {
1432
        if (!WriteProcessMemory(handle->hProcess, (LPVOID)(remote_address + result), (const char*)src + result, len - result, &written)) {
1433
            DWORD error = GetLastError();
1434
            PyErr_SetFromWindowsErr(error);
1435
            _set_debug_exception_cause(PyExc_OSError,
1436
                "WriteProcessMemory failed for PID %d at address 0x%lx "
1437
                "(size %zu, partial write %zu bytes): Windows error %lu",
1438
                handle->pid, remote_address + result, len - result, result, error);
1439
            return -1;
1440
        }
1441
        if (written == 0) {
1442
            PyErr_Format(PyExc_OSError,
1443
                "WriteProcessMemory wrote 0 bytes for PID %d at address 0x%lx "
1444
                "(size %zu, partial write %zu bytes)",
1445
                handle->pid, remote_address + result, len - result, result);
1446
            return -1;
1447
        }
1448
        result += written;
1449
    } while (result < len);
1450
    return 0;
1451
#elif defined(__linux__) && HAVE_PROCESS_VM_READV
1452
0
    if (handle->memfd != -1) {
1453
0
        return _Py_RemoteDebug_WriteRemoteMemoryFallback(handle, remote_address, len, src);
1454
0
    }
1455
0
    struct iovec local[1];
1456
0
    struct iovec remote[1];
1457
0
    Py_ssize_t result = 0;
1458
0
    Py_ssize_t written = 0;
1459
1460
0
    do {
1461
0
        local[0].iov_base = (void*)((char*)src + result);
1462
0
        local[0].iov_len = len - result;
1463
0
        remote[0].iov_base = (void*)((char*)remote_address + result);
1464
0
        remote[0].iov_len = len - result;
1465
1466
0
        written = process_vm_writev(handle->pid, local, 1, remote, 1, 0);
1467
0
        if (written < 0) {
1468
0
            int err = errno;
1469
0
            if (err == ENOSYS) {
1470
0
                return _Py_RemoteDebug_WriteRemoteMemoryFallback(handle, remote_address, len, src);
1471
0
            }
1472
0
            errno = err;
1473
0
            PyErr_SetFromErrno(PyExc_OSError);
1474
0
            _set_debug_exception_cause(PyExc_OSError,
1475
0
                "process_vm_writev failed for PID %d at address 0x%lx "
1476
0
                "(size %zu, partial write %zd bytes): %s",
1477
0
                handle->pid, remote_address + result, len - result, result, strerror(err));
1478
0
            return -1;
1479
0
        }
1480
1481
0
        if (written == 0) {
1482
0
            PyErr_Format(PyExc_OSError,
1483
0
                "process_vm_writev wrote 0 bytes for PID %d at address 0x%lx "
1484
0
                "(size %zu, partial write %zd bytes)",
1485
0
                handle->pid, remote_address + result, len - result, result);
1486
0
            return -1;
1487
0
        }
1488
0
        result += written;
1489
0
    } while ((size_t)written != local[0].iov_len);
1490
0
    return 0;
1491
#elif defined(__APPLE__) && defined(TARGET_OS_OSX) && TARGET_OS_OSX
1492
    kern_return_t kr = mach_vm_write(
1493
        handle->task,
1494
        (mach_vm_address_t)remote_address,
1495
        (vm_offset_t)src,
1496
        (mach_msg_type_number_t)len);
1497
1498
    if (kr != KERN_SUCCESS) {
1499
        switch (kr) {
1500
        case KERN_PROTECTION_FAILURE:
1501
            PyErr_SetString(PyExc_PermissionError, "Not enough permissions to write memory");
1502
            break;
1503
        case KERN_INVALID_ARGUMENT:
1504
            PyErr_SetString(PyExc_PermissionError, "Invalid argument to mach_vm_write");
1505
            break;
1506
        default:
1507
            PyErr_Format(PyExc_RuntimeError, "Unknown error writing memory: %d", (int)kr);
1508
        }
1509
        return -1;
1510
    }
1511
    return 0;
1512
#else
1513
    Py_UNREACHABLE();
1514
#endif
1515
0
}
1516
1517
UNUSED static int
1518
_Py_RemoteDebug_PagedReadRemoteMemory(proc_handle_t *handle,
1519
                                      uintptr_t addr,
1520
                                      size_t size,
1521
                                      void *out)
1522
0
{
1523
0
    size_t page_size = handle->page_size;
1524
0
    uintptr_t page_base = addr & ~(page_size - 1);
1525
0
    size_t offset_in_page = addr - page_base;
1526
0
1527
0
    if (offset_in_page + size > page_size) {
1528
0
        return _Py_RemoteDebug_ReadRemoteMemory(handle, addr, size, out);
1529
0
    }
1530
0
1531
0
    // Search only the pages used since the last clear. The cache is cleared
1532
0
    // between profiler samples, so entries are packed at the front.
1533
0
    for (int i = 0; i < handle->page_cache_count; i++) {
1534
0
        page_cache_entry_t *entry = &handle->pages[i];
1535
0
        if (entry->page_addr == page_base) {
1536
0
            memcpy(out, entry->data + offset_in_page, size);
1537
0
            return 0;
1538
0
        }
1539
0
    }
1540
0
1541
0
    if (handle->page_cache_count < MAX_PAGES) {
1542
0
        page_cache_entry_t *entry = &handle->pages[handle->page_cache_count];
1543
0
        if (entry->data == NULL) {
1544
0
            entry->data = PyMem_RawMalloc(page_size);
1545
0
            if (entry->data == NULL) {
1546
0
                PyErr_NoMemory();
1547
0
                _set_debug_exception_cause(PyExc_MemoryError,
1548
0
                    "Cannot allocate %zu bytes for page cache entry "
1549
0
                    "during read from PID %d at address 0x%lx",
1550
0
                    page_size, handle->pid, addr);
1551
0
                return -1;
1552
0
            }
1553
0
        }
1554
0
1555
0
        if (_Py_RemoteDebug_ReadRemoteMemory(handle, page_base, page_size, entry->data) < 0) {
1556
0
            // Try to just copy the exact amount as a fallback
1557
0
            PyErr_Clear();
1558
0
            goto fallback;
1559
0
        }
1560
0
1561
0
        entry->page_addr = page_base;
1562
0
        handle->page_cache_count++;
1563
0
        memcpy(out, entry->data + offset_in_page, size);
1564
0
        return 0;
1565
0
    }
1566
0
1567
0
fallback:
1568
0
    // Cache full — fallback to uncached read
1569
0
    return _Py_RemoteDebug_ReadRemoteMemory(handle, addr, size, out);
1570
0
}
1571
1572
typedef struct {
1573
    uintptr_t remote_addr;
1574
    void *local_buf;
1575
    size_t size;
1576
} _Py_RemoteReadSegment;
1577
1578
#define _PY_REMOTE_DEBUG_MAX_BATCHED_SEGMENTS 4
1579
1580
// Batched read of multiple remote regions in a single syscall when supported.
1581
// Returns total bytes read (>= 0) on success, -1 if batched reads are
1582
// unavailable or the syscall failed. Callers compare the return value against
1583
// cumulative segment sizes to determine which segments were fully populated.
1584
UNUSED static Py_ssize_t
1585
_Py_RemoteDebug_BatchedReadRemoteMemory(
1586
    proc_handle_t *handle,
1587
    const _Py_RemoteReadSegment *segments,
1588
    int nsegs)
1589
0
{
1590
0
#if defined(__linux__) && HAVE_PROCESS_VM_READV
1591
0
    if (handle->memfd == -1
1592
0
        && nsegs > 0
1593
0
        && nsegs <= _PY_REMOTE_DEBUG_MAX_BATCHED_SEGMENTS) {
1594
0
        struct iovec local[_PY_REMOTE_DEBUG_MAX_BATCHED_SEGMENTS];
1595
0
        struct iovec remote[_PY_REMOTE_DEBUG_MAX_BATCHED_SEGMENTS];
1596
0
        for (int i = 0; i < nsegs; i++) {
1597
0
            local[i].iov_base = segments[i].local_buf;
1598
0
            local[i].iov_len = segments[i].size;
1599
0
            remote[i].iov_base = (void *)segments[i].remote_addr;
1600
0
            remote[i].iov_len = segments[i].size;
1601
0
        }
1602
0
        ssize_t nread = process_vm_readv(handle->pid, local, nsegs, remote, nsegs, 0);
1603
0
        if (nread >= 0) {
1604
0
            return (Py_ssize_t)nread;
1605
0
        }
1606
0
    }
1607
0
#else
1608
0
    (void)handle;
1609
0
    (void)segments;
1610
0
    (void)nsegs;
1611
0
#endif
1612
0
    return -1;
1613
0
}
1614
1615
UNUSED static int
1616
_Py_RemoteDebug_ReadDebugOffsets(
1617
    proc_handle_t *handle,
1618
    uintptr_t *runtime_start_address,
1619
    _Py_DebugOffsets* debug_offsets
1620
0
) {
1621
0
    *runtime_start_address = _Py_RemoteDebug_GetPyRuntimeAddress(handle);
1622
0
    if (!*runtime_start_address) {
1623
0
        if (!PyErr_Occurred()) {
1624
0
            PyErr_Format(PyExc_RuntimeError,
1625
0
                "Failed to locate PyRuntime address for PID %d",
1626
0
                handle->pid);
1627
0
        }
1628
0
        return -1;
1629
0
    }
1630
0
    size_t size = sizeof(struct _Py_DebugOffsets);
1631
0
    if (0 != _Py_RemoteDebug_ReadRemoteMemory(handle, *runtime_start_address, size, debug_offsets)) {
1632
0
        _set_debug_exception_cause(PyExc_RuntimeError, "Failed to read debug offsets structure from remote process");
1633
0
        return -1;
1634
0
    }
1635
0
    return 0;
1636
0
}
1637
1638
#ifdef __cplusplus
1639
}
1640
#endif