Skip to content

Instantly share code, notes, and snippets.

@pnf
Created February 20, 2026 20:36
Show Gist options
  • Select an option

  • Save pnf/06cbf61a1b6d2b5e3ff93e9d7e8c420d to your computer and use it in GitHub Desktop.

Select an option

Save pnf/06cbf61a1b6d2b5e3ff93e9d7e8c420d to your computer and use it in GitHub Desktop.
// fast_core_read.c
#define _GNU_SOURCE
#include <dlfcn.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdint.h>
static ssize_t (*real_pread)(int fd, void *buf, size_t count, off_t offset) = NULL;
static int core_fd = -1;
static void *mapped = MAP_FAILED;
static size_t mapped_size = 0;
__attribute__((constructor))
static void init(void) {
real_pread = dlsym(RTLD_NEXT, "pread");
}
static void try_mmap_fd(int fd) {
struct stat st;
if (fstat(fd, &st) < 0) return;
if (st.st_size < 1024 * 1024) return; // ignore small files
// Check ELF magic + core type
unsigned char hdr[18];
ssize_t n = real_pread(fd, hdr, sizeof(hdr), 0);
if (n < (ssize_t)sizeof(hdr)) return;
// ELF magic: 0x7f 'E' 'L' 'F'
if (memcmp(hdr, "\x7f""ELF", 4) != 0) return;
// e_type at offset 16 (2 bytes LE): ET_CORE = 4
uint16_t e_type = hdr[16] | (hdr[17] << 8);
if (e_type != 4) return;
mapped = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
if (mapped == MAP_FAILED) return;
// Advise the kernel we'll be reading sequentially (mostly)
madvise(mapped, st.st_size, MADV_SEQUENTIAL);
mapped_size = st.st_size;
core_fd = fd;
fprintf(stderr, "[fast_core_read] mmap'd core fd=%d, size=%zu MB\n",
fd, mapped_size / (1024 * 1024));
}
ssize_t pread(int fd, void *buf, size_t count, off_t offset) {
if (!real_pread) init();
// Lazily detect the core file fd
if (core_fd == -1 && mapped == MAP_FAILED) {
try_mmap_fd(fd);
}
if (fd == core_fd && mapped != MAP_FAILED) {
// Bounds check
if (offset < 0 || (size_t)offset >= mapped_size) return 0;
if ((size_t)offset + count > mapped_size) {
count = mapped_size - offset;
}
memcpy(buf, (char *)mapped + offset, count);
return count;
}
return real_pread(fd, buf, count, offset);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment