How does a loader in operating system work? [close

2019-07-02 15:26发布

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++ ?

1条回答
成全新的幸福
2楼-- · 2019-07-02 16:29

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:

查看更多
登录 后发表回答