1

I need to get the size of a C/C++ executable at runtime in code. Unfortunately I cannot use /proc/self/exe as it's restricted on the target system.

jestro
  • 2,524
  • 4
  • 27
  • 46
  • Isnt the exe path given in the first argument to main? Can you get size from there? – pacukluka May 13 '20 at 02:56
  • https://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe?rq=1 may help – Nate Eldredge May 13 '20 at 02:58
  • 1
    Does [`dl_iterate_phdr`](http://man7.org/linux/man-pages/man3/dl_iterate_phdr.3.html) help? – o11c May 13 '20 at 03:05
  • From experimenting, casting `info->dlpi_addr` to `ElfW(Ehdr)*` and calculating the end of the section headers is usually the end of the file. Of course, it's not *guaranteed* that section headers will be the last meaningful thing in the file, and there could always be some trailing junk ... – o11c May 13 '20 at 04:32
  • dl_iterate_phdr seems to do the trick! – jestro May 14 '20 at 21:24

3 Answers3

1

Actually, it's a lot simpler than my attempt in the comments. The executable is simply:

(const char *)getauxval(AT_EXECFN)

That said, you should always try to open /proc/self/exe first since the executable may have been deleted/moved/replaced while running.

o11c
  • 15,265
  • 4
  • 50
  • 75
0

First string in argv should be path used to run the executable. You can use std::filesystem::file_size to get the size.

In an exceptional case, where the command is a plain basename without a path separator, you need to search for it from the directories in the $PATH env variable.

eerorika
  • 232,697
  • 12
  • 197
  • 326
0

dl_iterate_phdr

https://linux.die.net/man/3/dl_iterate_phdr

This solved it! Thanks @o11c!

jestro
  • 2,524
  • 4
  • 27
  • 46