π What is a Loader?
A Loader is a part of the Operating System responsible for:
Loading an executable file (machine code) from storage into main memory (RAM) and preparing it for execution by the CPU.
Without the loader, compiled code would just sit on diskβnever executed.
π§ Responsibilities of a Loader
| Task | Description |
|---|---|
| π§Ύ Loads program into RAM | Reads the binary executable from disk into memory. |
| πΊοΈ Allocates memory | Allocates memory for code, data, stack, and heap sections. |
| π§ Sets up the program counter | Initializes CPU registers, especially PC (Program Counter) to point to main(). |
| π Handles linking (in some systems) | Resolves addresses of external symbols (functions/libraries). |
| π¦ Initializes environment | Prepares runtime environment: args, env variables, etc. |
| βΆοΈ Starts execution | Hands control to the entry point of the program (like _start or main) |
π Where Does the Loader Fit?
[Source Code] β [Compiler] β [Executable File (.exe/.out)]
β
[Loader (OS)]
β
[Program in RAM, Ready to Run]
π§© Loader vs Linker (Often Confused)
| Feature | Loader | Linker |
|---|---|---|
| π¦ Purpose | Loads program into memory | Combines multiple object files into a single executable |
| π§ When? | At runtime | At compile time (static) or load time (dynamic) |
| π Input | Executable file (e.g., ELF, PE) | Object files (.o, .obj) |
| π§ Resolves addresses? | Yes, if dynamic linking | Yes, during linking phase |
π§ͺ Real-World Examples
| OS | Loader Component |
|---|---|
| Linux | ld-linux.so, execve() syscall |
| Windows | Windows PE Loader |
| Unix | exec, fork, ld.so |
| Embedded | Bootloaders (like U-Boot) do this job at power-on |
π Types of Loading (Interview-Level Detail)
| Type | Description |
|---|---|
| Absolute Loading | Load program at a fixed address. Rare today. |
| Relocatable Loading | Load at any memory address. Relocation logic adjusts addresses. |
| Dynamic Loading | Load parts of the program (like libraries) only when needed, not at startup. |
π§ Interview-Ready Definition:
A Loader is a system program in the OS that loads an executable into memory, sets up the runtime environment, resolves addresses (if needed), and starts execution by transferring control to the programβs entry point.