The Linux x86 Journey to main()

Source Node: 1414783

Have you ever had a program crash before your main function executes? it is rare, but it can happen. When it does, you need to understand what happens behind the scenes between the time the operating system starts your program and your first line of code in main executes. Luckily [Patrick Horgan] has a tutorial about the subject that’s very detailed. It doesn’t cover statically linked libraries but, as he points out, if you understand what he does cover, that’s easy to figure out on your own.

The operating system, it turns out, knows nothing about main. It does, however, know about a symbol called _start. Your runtime library provides this. That code contains some stack manipulation and eventually calls __libc_start_main which is also provided by the library.

From there, you wind up with some trickery to manage the program’s environment and more library calls such as __libc_init_first and __libc_init do some more setup work. You’d think that would get you close, but there’s plenty more to do including setting up for at_exit and thunking for position-independent code, not to mention dynamically linked libraries.

This is one of those topics it will seem like you don’t really need until you do. Even if you use another language to generate executables, they all have to follow these steps somewhere. Granted, for many languages the startup is static and unlikely to require you to debug it, but it is still good to know what’s going on under the hood.

If you want a quick Linux assembly tutorial, have at it. If you prefer to shovel your assembly into a C source code file, you can do that, too.

Source: https://hackaday.com/2021/11/05/the-linux-x86-journey-to-main/

Time Stamp:

More from Hackaday