Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a loader in operating system work? [closed]

I know that a loader is a program which loads a program to the Main Memory. So,how does this actually works? What happens exactly? Actually when a loader loads a program, an entry in PCB is created and the program is put in a job pool. How the executable codes of a program are copied to the main memory? In simple how to load the codes of a file to the main memory using C or C++ ?

like image 912
prog481 Avatar asked Sep 21 '15 06:09

prog481


1 Answers

This largely depends on the operating system. What I will write here is Linux specific, but the similar things happens on other operating systems.

First, the fork() call is initiated, effectively creating new process (and appropriate PCB entry). The next step is calling exec system call which will do the hard work. I'll assume that we're talking about ELF executables here.

In that case, after recognizing that this is the ELF executable (by inspecting magic number) exec will call load_elf_binary (http://lxr.free-electrons.com/source/fs/binfmt_elf.c#L664)

The argument struct linux_binprm *bprm that is passed to this function contains all the metadata about binary (already filled by exec) such is executable name, environment info, etc. (http://lxr.free-electrons.com/source/include/linux/binfmts.h#L14)

The ELF program loading is a complex task, and it requires understanding of the ELF format.

The very good resource on this can be found here

In a nutshell, these are interesting steps that kernel is performing:

  • checks the elf headers to find if there's an program interpreter specified for this binary (ld.so is used for dynamically linking the required libraries, peforms the relocations, calls initialization functions for the linked libraries).

  • Setup the new executable environment (setup the the new credentials, mark the point of no return, for example)

  • Setup the memory layout (like randomize the stack) and map the pages from executable to memory

  • Calls start_thread and starts either program or the interpreter (ld.so)

Good document on understanding of elf with interpreters can be found here

Resources:

  • https://www.cs.stevens.edu/~jschauma/631/elf.html
  • http://www.skyfree.org/linux/references/ELF_Format.pdf
  • https://stackoverflow.com/a/31394861/133707
  • http://s.eresi-project.org/inc/articles/elf-rtld.txt
like image 185
Nemanja Boric Avatar answered Sep 21 '22 23:09

Nemanja Boric