Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do memory addresses get assigned?

Consider the following CPU instruction which takes the memory at address 16777386 (decimal) and stores it in Register 1:

Move &0x010000AA, R1

Traditionally programs are translated to assembly (machine code) at compile time. (Let's ignore more complex modern systems like jitting).

However, if this address allocation is completed statically at compile time, how does the OS ensure that two processes do not use the same memory? (eg if you ran the same compiled program twice concurrently).

Question:

How, and when, does a program get its memory addresses assigned?

Virtual Memory:

I understand most (if not all) modern systems use Memory Management Units in hardware to allow for the use of virtual memory. The first few octets of an address space being used to reference which page. This would allow for memory protection if each process used different pages. However, if this is how memory protection is enforced, the original question still persists, only this time with how page numbers are assigned?

EDIT:

CPU:

One possibility is the CPU can handle memory protection by enforcing that a process id be assigned by the OS before executing memory based instructions. However, this is only speculation, and requires support in hardware by the CPU architecture, something I'm not sure RISC ISAs would be designed to do.

like image 244
James Avatar asked Oct 31 '22 13:10

James


1 Answers

With virtual memory each process has separate address space, so 0x010000AA in one process will refer to different value than in another process.

Address spaces are implemented with kernel-controlled page tables that processor uses to translate virtual page addresses to physical ones. Having two processes using the same address page number is not an issue, since the processes have separate page tables and physical memory mapped can be different.

Usually executable code and global variables will be mapped statically, stack will be mapped at random address (some exploits are more difficult that way) and dynamic allocation routines will use syscalls to map more pages.

like image 76
zch Avatar answered Nov 15 '22 12:11

zch