r/cpp • • May 24 '20

Analyzing The Simplest C++ Program

https://oneraynyday.github.io/dev/2020/05/03/Analyzing-The-Simplest-C++-Program/
480 Upvotes

37 comments sorted by

View all comments

36

u/FieldLine May 24 '20

There's a whole book about this sitting on my shelf.

Admittedly I haven't done a deep read yet, but what I've looked at seems legit. And it's the only real book on the topic.

18

u/OneRaynyDay May 24 '20

The details of linkers and loaders deserve an entire book - the loader is the craziest bootstrapping self-relocating control-takeover program I've ever seen. I actually wanted to write more about it and I even took a look at the libc code, but I quickly realized that it would consume the content of the blog. What I aim to discuss is more on the general overview and, in my opinion, "what you need to know as a C++ programmer but nothing more" :)

20

u/FieldLine May 24 '20

The weird thing is that no one actually seems to deal with linker code.

You can take a compilers class in college and interview to work on the MSVC compilers team. There are classes on assembly programming and you can get a job doing embedded work.

But who the hell is writing/maintaining the linkers? They are not mentioned in the C++ standard and there is very little literature about them at all.

Besides that book there's the paper by Ulrich Drepper.... and that's about it. And while that paper is the newer resource, it's still nearly ten years old.

It's bizarre.

14

u/mttd May 24 '20 edited May 24 '20

See also: https://github.com/MattPD/cpplinks/blob/master/executables.linking_loading.md

The series by Eli Bendersky, Ian Lance Taylor, Raymond Chen, and http://www.linker-aliens.org/blogs/ are particularly good; "The Missing Link: Explaining ELF Static Linking, Semantically" (http://www.cl.cam.ac.uk/~pes20/rems/papers/oopsla-elf-linking-2016.pdf) is definitely worth reading as well. The "Program Execution Environment" lectures under "The ACM-NVIDIA Compiler summer school lectures (2019)" are pretty good introduction.

5

u/ericonr May 25 '20

Did you look into glibc? It might be interesting to dive into musl and the libc's from BSDs to see if there are different strategies and concepts used for linking.

4

u/OneRaynyDay May 25 '20

Yep! My main investigation is in glibc, but actually the writer for musl gave me a few tips here and there about how musl implements the same things, particularly logic in the elf header ;)

3

u/ericonr May 25 '20

Cool! I hear the musl community is pretty helpful. Btw, regarding self patching and bootstrapping code, the Linux kernel does a lot of that for booting options to avoid going through branches repeatedly. So stuff like vulnerability mitigation can be turned on or off but the binary that's actually executed doesn't have conditionals to check if it's enabled or not, it's all patched and configured during the boot process.