Add is_valid_elf() to build-id.c and declare it in build-id.h so that multiple perf subsystems can verify ELF magic without duplicating the check. The helper opens the file, reads the first SELFMAG (4) bytes, and compares them against ELFMAG using memcmp().
Both <elf.h> and <fcntl.h> are already included in build-id.c, so no new dependencies are added. Reported-by: Narendra Nalli <[email protected]> Reported-by: Vijay Puliyala <[email protected]> Signed-off-by: Athira Rajeev <[email protected]> --- tools/perf/util/build-id.c | 14 ++++++++++++++ tools/perf/util/build-id.h | 2 ++ 2 files changed, 16 insertions(+) diff --git a/tools/perf/util/build-id.c b/tools/perf/util/build-id.c index eb95ab90f974..28b6b3f8d5d3 100644 --- a/tools/perf/util/build-id.c +++ b/tools/perf/util/build-id.c @@ -43,6 +43,20 @@ static bool no_buildid_cache; +bool is_valid_elf(const char *filename) +{ + unsigned char magic[SELFMAG]; + int fd = open(filename, O_RDONLY); + bool valid = false; + + if (fd < 0) + return false; + if (read(fd, magic, sizeof(magic)) == (ssize_t)sizeof(magic)) + valid = (memcmp(magic, ELFMAG, SELFMAG) == 0); + close(fd); + return valid; +} + static int mark_dso_hit_callback(struct callchain_cursor_node *node, void *data __maybe_unused) { struct map *map = node->ms.map; diff --git a/tools/perf/util/build-id.h b/tools/perf/util/build-id.h index 73bad90b06f9..dd5b4e3a4d3e 100644 --- a/tools/perf/util/build-id.h +++ b/tools/perf/util/build-id.h @@ -76,4 +76,6 @@ extern char buildid_dir[]; void set_buildid_dir(const char *dir); void disable_buildid_cache(void); +bool is_valid_elf(const char *filename); + #endif -- 2.43.0
