运行程序时会发生什么? [英] What happens when you run a program?
问题描述
我想在这里收集在Windows,Linux和OSX上运行可执行文件时发生的情况.特别是,我想确切地了解操作的顺序:我的猜测是可执行文件格式(PE,ELF或Mach-O)是由内核加载的(但我忽略了 ELF (可执行和可链接格式)及其含义),然后有了可以解析引用的动态链接器,然后先运行可执行文件的__init
部分,然后运行主文件,然后运行__fini
,然后完成程序,但是我确信它非常粗糙,并且可能是错误的.
I would like to collect here what happens when you run an executable on Windows, Linux and OSX. In particular, I would like to understand exactly the order of the operations: my guess is that the executable file format (PE, ELF or Mach-O) is loaded by the kernel (but I ignore the various sections of the ELF(Executable and Linkable Format) and their meaning), and then you have the dynamic linker that resolves the references, then the __init
part of the executable is run, then the main, then the __fini
, and then the program is completed, but I am sure it's very rough, and probably wrong.
编辑:现在的问题是CW.我正在为Linux加油.如果有人想对Win和OSX做同样的事情,那就太好了.
Edit: the question is now CW. I am filling up for linux. If anyone wants to do the same for Win and OSX it would be great.
推荐答案
这当然是非常抽象的级别!
This is just at a very high and abstract level of course!
Executable - No Shared Libary:
Client request to run application
->Shell informs kernel to run binary
->Kernel allocates memory from the pool to fit the binary image into
->Kernel loads binary into memory
->Kernel jumps to specific memory address
->Kernel starts processing the machine code located at this location
->If machine code has stop
->Kernel releases memory back to pool
Executable - Shared Library
Client request to run application
->Shell informs kernel to run binary
->Kernel allocates memory from the pool to fit the binary image into
->Kernel loads binary into memory
->Kernel jumps to specific memory address
->Kernel starts processing the machine code located at this location
->Kernel pushes current location into an execution stack
->Kernel jumps out of current memory to a shared memory location
->Kernel executes code from this shared memory location
->Kernel pops back the last memory location and jumps to that address
->If machine code has stop
->Kernel releases memory back to pool
JavaScript/.NET/Perl/Python/PHP/Ruby (Interpretted Languages)
Client request to run application
->Shell informs kernel to run binary
->Kernel has a hook that recognises binary images needs a JIT
->Kernel calls JIT
->JIT loads the code and jumps to a specific address
->JIT reads the code and compiles the instruction into the
machine code that the interpretter is running on
->Interpretture passes machine code to the kernel
->kernel executes the required instruction
->JIT then increments the program counter
->If code has a stop
->Jit releases application from its memory pool
正如routeNpingme所说,寄存器设置在CPU内部,魔术就发生了!
As routeNpingme says, registers are set inside the CPU and the magic happens!
更新:是的,我今天不能正确讲话!
Update: Yeah, I cant speell properly today!
这篇关于运行程序时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!