|
| 1 | +#include "nsolid_elf_utils.h" |
| 2 | +#include "nsolid_util.h" |
| 3 | + |
| 4 | +#include <fcntl.h> |
| 5 | +#include <libelf.h> |
| 6 | +#include <gelf.h> |
| 7 | +#include <unistd.h> |
| 8 | +#include <cstring> |
| 9 | +#include <map> |
| 10 | +#include "uv.h" |
| 11 | + |
| 12 | +namespace node { |
| 13 | +namespace nsolid { |
| 14 | +namespace elf_utils { |
| 15 | + |
| 16 | + |
| 17 | +int GetBuildId(const std::string& path, std::string* build_id) { |
| 18 | + static std::map<std::string, std::string> build_id_cache_; |
| 19 | + |
| 20 | + Elf* e; |
| 21 | + Elf_Scn* scn = nullptr; |
| 22 | + GElf_Shdr shdr; |
| 23 | + |
| 24 | + if (build_id_cache_.find(path) != build_id_cache_.end()) { |
| 25 | + *build_id = build_id_cache_[path]; |
| 26 | + return 0; |
| 27 | + } |
| 28 | + |
| 29 | + int ret; |
| 30 | + |
| 31 | + ret = 0; |
| 32 | + if (elf_version(EV_CURRENT) == EV_NONE) { |
| 33 | + return elf_errno(); |
| 34 | + } |
| 35 | + |
| 36 | + int fd = open(path.c_str(), O_RDONLY); |
| 37 | + if (fd < 0) { |
| 38 | + return -errno; |
| 39 | + } |
| 40 | + |
| 41 | + e = elf_begin(fd, ELF_C_READ, nullptr); |
| 42 | + if (!e) { |
| 43 | + ret = elf_errno(); |
| 44 | + goto error; |
| 45 | + } |
| 46 | + |
| 47 | + size_t shstrndx; |
| 48 | + if (elf_getshdrstrndx(e, &shstrndx) != 0) { |
| 49 | + ret = elf_errno(); |
| 50 | + goto end_error; |
| 51 | + } |
| 52 | + |
| 53 | + *build_id = std::string(""); |
| 54 | + while ((scn = elf_nextscn(e, scn)) != nullptr) { |
| 55 | + if (gelf_getshdr(scn, &shdr) != &shdr) { |
| 56 | + ret = elf_errno(); |
| 57 | + goto end_error; |
| 58 | + } |
| 59 | + |
| 60 | + char* name = elf_strptr(e, shstrndx, shdr.sh_name); |
| 61 | + if (name && strcmp(name, ".note.gnu.build-id") == 0) { |
| 62 | + Elf_Data* data = elf_getdata(scn, nullptr); |
| 63 | + if (data && data->d_size >= 16) { |
| 64 | + // ELF Note header: namesz(4), descsz(4), type(4) + name padding |
| 65 | + // Compute offset to build-id properly |
| 66 | + uint32_t* note = reinterpret_cast<uint32_t*>(data->d_buf); |
| 67 | + uint32_t namesz = note[0]; |
| 68 | + uint32_t descsz = note[1]; |
| 69 | + // Name starts at offset 12 |
| 70 | + // Descriptor (build-id) starts at next aligned offset |
| 71 | + size_t name_end = 12 + ((namesz + 3) & ~3); |
| 72 | + uint8_t* id = reinterpret_cast<uint8_t*>(data->d_buf) + name_end; |
| 73 | + *build_id = utils::buffer_to_hex(id, descsz); |
| 74 | + break; |
| 75 | + } |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + if (build_id->empty()) { |
| 80 | + ret = UV_ENOENT; |
| 81 | + } else { |
| 82 | + build_id_cache_[path] = *build_id; |
| 83 | + } |
| 84 | + |
| 85 | +end_error: |
| 86 | + elf_end(e); |
| 87 | + |
| 88 | +error: |
| 89 | + close(fd); |
| 90 | + |
| 91 | + return ret; |
| 92 | +} |
| 93 | + |
| 94 | +} // namespace elf_utils |
| 95 | +} // namespace nsolid |
| 96 | +} // namespace node |
| 97 | + |
0 commit comments