Linux
為什麼同一程序的虛擬記憶體區域在每次執行時都不同?
我正在研究 Linux 中記憶體區域的虛擬記憶體映射。執行檔是一個簡單的計數程序。當程序的兩個實例執行時,以下是 顯示的映射
/proc/pid/maps
。堆、堆棧、vvar、vdso 等的位置在載入時似乎有一個隨機偏移。為什麼這樣做?實例 1:堆開始於
013f4000
00400000-00401000 r--p 00000000 08:16 3557412 <program-exe> 00401000-00480000 r-xp 00001000 08:16 3557412 <program-exe> 00480000-004a5000 r--p 00080000 08:16 3557412 <program-exe> 004a6000-004ac000 rw-p 000a5000 08:16 3557412 <program-exe> 004ac000-004ad000 rw-p 00000000 00:00 0 013f4000-01417000 rw-p 00000000 00:00 0 [heap] 7ffd98bd8000-7ffd98bf9000 rw-p 00000000 00:00 0 [stack] 7ffd98bfc000-7ffd98bff000 r--p 00000000 00:00 0 [vvar] 7ffd98bff000-7ffd98c00000 r-xp 00000000 00:00 0 [vdso] ffffffffff600000-ffffffffff601000 --xp 00000000 00:00 0 [vsyscall]
實例 2:堆開始於
013cc000
00400000-00401000 r--p 00000000 08:16 3557412 <program-exe> 00401000-00480000 r-xp 00001000 08:16 3557412 <program-exe> 00480000-004a5000 r--p 00080000 08:16 3557412 <program-exe> 004a6000-004ac000 rw-p 000a5000 08:16 3557412 <program-exe> 004ac000-004ad000 rw-p 00000000 00:00 0 013cc000-013ef000 rw-p 00000000 00:00 0 [heap] 7ffe3717d000-7ffe3719e000 rw-p 00000000 00:00 0 [stack] 7ffe371fa000-7ffe371fd000 r--p 00000000 00:00 0 [vvar] 7ffe371fd000-7ffe371fe000 r-xp 00000000 00:00 0 [vdso] ffffffffff600000-ffffffffff601000 --xp 00000000 00:00 0 [vsyscall]
這是稱為地址空間佈局隨機化 (ASLR) 的安全功能的結果。啟用 ASLR 後,核心將在隨機地址載入關鍵程序段。所有最近的 Linux 核心都預設啟用了 ASLR。ASLR 可以通過
/proc/sys/kernel/randomize_va_space
. 從proc 手冊頁:/proc/sys/kernel/randomize_va_space(自 Linux 2.6.12 起)為系統(在支持 ASLR 的架構上)選擇地址空間佈局隨機化 (ASLR) 策略。此文件支持三個值:
0 Turn ASLR off. This is the default for architectures that don't support ASLR, and when the kernel is booted with the norandmaps parameter. 1 Make the addresses of mmap(2) allocations, the stack, and the VDSO page randomized. Among other things, this means that shared libraries will be loaded at randomized addresses. The text segment of PIE-linked binaries will also be loaded at a randomized address. This value is the default if the kernel was configured with CONFIG_COM‐ PAT_BRK. 2 (Since Linux 2.6.25) Also support heap randomization. This value is the default if the kernel was not configured with CONFIG_COMPAT_BRK.
因此,要暫時禁用 ASLR,請以 root 身份執行以下命令:
echo 0 > /proc/sys/kernel/randomize_va_space
現在再次執行您的測試,您應該會發現兩個程序現在將具有相同的地址映射。