Async-signal-safe: scan /proc/self/maps via raw read() for the mapping containing `addr`. Returns its base (0 if not found); dladdr is unreliable on stripped i386.
| 328 | // Async-signal-safe: scan /proc/self/maps via raw read() for the mapping containing |
| 329 | // `addr`. Returns its base (0 if not found); dladdr is unreliable on stripped i386. |
| 330 | static uintptr_t ResolveModule(uintptr_t addr, char* nameOut, size_t nameCap) |
| 331 | { |
| 332 | if (nameCap) nameOut[0] = '\0'; |
| 333 | int fd = open("/proc/self/maps", O_RDONLY | O_CLOEXEC); |
| 334 | if (fd < 0) return 0; |
| 335 | char buf[8192]; |
| 336 | char line[512]; |
| 337 | size_t lineLen = 0; |
| 338 | uintptr_t result = 0; |
| 339 | ssize_t n; |
| 340 | bool done = false; |
| 341 | while (!done && (n = read(fd, buf, sizeof(buf))) > 0) { |
| 342 | for (ssize_t i = 0; i < n; ++i) { |
| 343 | char c = buf[i]; |
| 344 | if (c != '\n') { |
| 345 | if (lineLen < sizeof(line) - 1) line[lineLen++] = c; |
| 346 | continue; |
| 347 | } |
| 348 | line[lineLen] = '\0'; |
| 349 | // Parse "start-end perms ... path" |
| 350 | uintptr_t start = 0, e = 0; |
| 351 | const char* p = line; |
| 352 | while (*p && *p != '-') { start = start * 16 + (*p <= '9' ? *p - '0' : (*p | 0x20) - 'a' + 10); ++p; } |
| 353 | if (*p == '-') ++p; |
| 354 | while (*p && *p != ' ') { e = e * 16 + (*p <= '9' ? *p - '0' : (*p | 0x20) - 'a' + 10); ++p; } |
| 355 | if (addr >= start && addr < e) { |
| 356 | // path is the last token after the final space |
| 357 | const char* path = line; |
| 358 | for (const char* q = line; *q; ++q) if (*q == ' ' && q[1] && q[1] != ' ') path = q + 1; |
| 359 | const char* slash = path; |
| 360 | for (const char* q = path; *q; ++q) if (*q == '/') slash = q + 1; |
| 361 | size_t j = 0; |
| 362 | if (*slash && *slash != ' ') |
| 363 | for (; slash[j] && j < nameCap - 1; ++j) nameOut[j] = slash[j]; |
| 364 | nameOut[j] = '\0'; |
| 365 | result = start; |
| 366 | done = true; |
| 367 | break; |
| 368 | } |
| 369 | lineLen = 0; |
| 370 | } |
| 371 | } |
| 372 | close(fd); |
| 373 | return result; |
| 374 | } |
| 375 | |
| 376 | static void WriteFrame(uintptr_t retAddr) |
| 377 | { |