操作系统中的加载程序如何工作? [英] How does a loader in operating system work?

查看:100
本文介绍了操作系统中的加载程序如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道加载程序是将程序加载到主存储器的程序.那么,这实际上如何工作?到底会发生什么?实际上,当加载程序加载程序时,会在PCB中创建一个条目,并将该程序放入作业池中.程序的可执行代码如何复制到主存储器?简单地说,如何使用C或C ++将文件的代码加载到主存储器中?

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

推荐答案

这在很大程度上取决于操作系统.我将在这里写的是特定于Linux的,但是类似的事情也会在其他操作系统上发生.

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

首先,启动fork()调用,有效地创建新的过程(和适当的PCB条目).下一步是调用exec系统调用,它将完成艰苦的工作.我假设我们在这里谈论ELF可执行文件.

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.

在那种情况下,在确认这是ELF可执行文件(通过检查幻数)后,exec将调用load_elf_binary(

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)

传递给此函数的参数struct linux_binprm *bprm包含有关二进制文件(已由exec填充)的所有元数据,例如可执行文件名称,环境信息等(

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)

加载ELF程序是一项复杂的任务,需要了解ELF格式.

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

可以在此处

简而言之,这些是内核正在执行的有趣步骤:

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

  • 检查elf头文件,以查找是否为此二进制文件指定了程序解释器(ld.so用于动态链接所需的库,执行重定位,为链接的库调用初始化函数).

  • 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

调用start_thread并启动程序或解释器(ld.so)

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

可以在此处

资源:

  • 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

这篇关于操作系统中的加载程序如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆