10张图22段代码,万字长文带你搞懂虚拟内存模型和Malloc内部原理

云计算 虚拟化 存储软件
我们会通过/proc文件系统找到正在运行的进程的字符串所在的虚拟内存地址,并通过更改此内存地址的内容来更改字符串内容,使你更深入了解虚拟内存这个概念!

 [[351558]]

本文转载自微信公众号「程序喵大人」,作者程序喵大人 。转载本文请联系程序喵大人公众号。

摊牌了,不装了,其实我是程序喵辛苦工作一天还要回家编辑公众号到大半夜的老婆,希望各位大哥能踊跃转发,完成我一千阅读量的KPI(梦想),谢谢!

咳咳,有点跑题,以下是程序喵的废话,麻烦给个面子划到最后点击在看或者赞,证明我比程序喵人气高,谢谢! 

通过/proc文件系统探究虚拟内存

我们会通过/proc文件系统找到正在运行的进程的字符串所在的虚拟内存地址,并通过更改此内存地址的内容来更改字符串内容,使你更深入了解虚拟内存这个概念!这之前先介绍下虚拟内存的定义!

虚拟内存

虚拟内存是一种实现在计算机软硬件之间的内存管理技术,它将程序使用到的内存地址(虚拟地址)映射到计算机内存中的物理地址,虚拟内存使得应用程序从繁琐的管理内存空间任务中解放出来,提高了内存隔离带来的安全性,虚拟内存地址通常是连续的地址空间,由操作系统的内存管理模块控制,在触发缺页中断时利用分页技术将实际的物理内存分配给虚拟内存,而且64位机器虚拟内存的空间大小远超出实际物理内存的大小,使得进程可以使用比物理内存大小更多的内存空间。

在深入研究虚拟内存前,有几个关键点:

  • 每个进程都有它自己的虚拟内存
  • 虚拟内存的大小取决于系统的体系结构
  • 不同操作管理有着不同的管理虚拟内存的方式,但大多数操作系统的虚拟内存结构如下图:

 

virtual_memory.png

上图并不是特别详细的内存管理图,高地址其实还有内核空间等等,但这不是这篇文章的主题。从图中可以看到高地址存储着命令行参数和环境变量,之后是栈空间、堆空间和可执行程序,其中栈空间向下延申,堆空间向上增长,堆空间需要使用malloc分配,是动态分配的内存的一部分。

首先通过一个简单的C程序探究虚拟内存。

  1. #include <stdlib.h> 
  2. #include <stdio.h> 
  3. #include <string.h> 
  4.  
  5. /** 
  6.  * main - 使用strdup创建一个字符串的拷贝,strdup内部会使用malloc分配空间, 
  7.  * 返回新空间的地址,这段地址空间需要外部自行使用free释放 
  8.  * 
  9.  * Return: EXIT_FAILURE if malloc failed. Otherwise EXIT_SUCCESS 
  10.  */ 
  11. int main(void) 
  12.     char *s; 
  13.  
  14.     s = strdup("test_memory"); 
  15.     if (s == NULL
  16.     { 
  17.         fprintf(stderr, "Can't allocate mem with malloc\n"); 
  18.         return (EXIT_FAILURE); 
  19.     } 
  20.     printf("%p\n", (void *)s); 
  21.     return (EXIT_SUCCESS); 
  22.  
  23. 编译运行:gcc -Wall -Wextra -pedantic -Werror main.c -o test; ./test 
  24. 输出:0x88f010 

我的机器是64位机器,进程的虚拟内存高地址为0xffffffffffffffff, 低地址为0x0,而0x88f010远小于0xffffffffffffffff,因此大概可以推断出被复制的字符串的地址(堆地址)是在内存低地址附近,具体可以通过/proc文件系统验证.

ls /proc目录可以看到好多文件,这里主要关注/proc/[pid]/mem和/proc/[pid]/maps

mem & maps

  1. man proc 
  2.  
  3. /proc/[pid]/mem 
  4.     This file can be used to access the pages of a process's memory through open(2), read(2), and lseek(2). 
  5.  
  6. /proc/[pid]/maps 
  7.     A  file containing the currently mapped memory regions and their access permissions. 
  8.           See mmap(2) for some further information about memory mappings. 
  9.  
  10.               The format of the file is
  11.  
  12.        address           perms offset  dev   inode       pathname 
  13.        00400000-00452000 r-xp 00000000 08:02 173521      /usr/bin/dbus-daemon 
  14.        00651000-00652000 r--p 00051000 08:02 173521      /usr/bin/dbus-daemon 
  15.        00652000-00655000 rw-p 00052000 08:02 173521      /usr/bin/dbus-daemon 
  16.        00e03000-00e24000 rw-p 00000000 00:00 0           [heap] 
  17.        00e24000-011f7000 rw-p 00000000 00:00 0           [heap] 
  18.        ... 
  19.        35b1800000-35b1820000 r-xp 00000000 08:02 135522  /usr/lib64/ld-2.15.so 
  20.        35b1a1f000-35b1a20000 r--p 0001f000 08:02 135522  /usr/lib64/ld-2.15.so 
  21.        35b1a20000-35b1a21000 rw-p 00020000 08:02 135522  /usr/lib64/ld-2.15.so 
  22.        35b1a21000-35b1a22000 rw-p 00000000 00:00 0 
  23.        35b1c00000-35b1dac000 r-xp 00000000 08:02 135870  /usr/lib64/libc-2.15.so 
  24.        35b1dac000-35b1fac000 ---p 001ac000 08:02 135870  /usr/lib64/libc-2.15.so 
  25.        35b1fac000-35b1fb0000 r--p 001ac000 08:02 135870  /usr/lib64/libc-2.15.so 
  26.        35b1fb0000-35b1fb2000 rw-p 001b0000 08:02 135870  /usr/lib64/libc-2.15.so 
  27.        ... 
  28.        f2c6ff8c000-7f2c7078c000 rw-p 00000000 00:00 0    [stack:986] 
  29.        ... 
  30.        7fffb2c0d000-7fffb2c2e000 rw-p 00000000 00:00 0   [stack] 
  31.        7fffb2d48000-7fffb2d49000 r-xp 00000000 00:00 0   [vdso] 
  32.  
  33.               The address field is the address space in the process that the mapping occupies. 
  34.           The perms field is a set of permissions: 
  35.  
  36.                    r = read 
  37.                    w = write 
  38.                    x = execute 
  39.                    s = shared 
  40.                    p = private (copy on write) 
  41.  
  42.               The offset field is the offset into the file/whatever; 
  43.           dev is the device (major:minor); inode is the inode on that device.   0  indicates 
  44.               that no inode is associated with the memory region, 
  45.           as would be the case with BSS (uninitialized data). 
  46.  
  47.               The  pathname field will usually be the file that is backing the mapping. 
  48.           For ELF files, you can easily coordinate with the offset field 
  49.               by looking at the Offset field in the ELF program headers (readelf -l). 
  50.  
  51.               There are additional helpful pseudo-paths: 
  52.  
  53.                    [stack] 
  54.                           The initial process's (also known as the main thread's) stack. 
  55.  
  56.                    [stack:<tid>] (since Linux 3.4) 
  57.                           A thread's stack (where the <tid> is a thread ID). 
  58.               It corresponds to the /proc/[pid]/task/[tid]/ path. 
  59.  
  60.                    [vdso] The virtual dynamically linked shared object. 
  61.  
  62.                    [heap] The process's heap. 
  63.  
  64.               If the pathname field is blank, this is an anonymous mapping as obtained via the mmap(2) function
  65.           There is no easy  way  to  coordinate 
  66.               this back to a process's source, short of running it through gdb(1), strace(1), or similar. 
  67.  
  68.               Under Linux 2.0 there is no field giving pathname. 

通过mem文件可以访问和修改整个进程的内存页,通过maps可以看到进程当前已映射的内存区域,有地址和访问权限偏移量等,从maps中可以看到堆空间是在低地址而栈空间是在高地址. 从maps中可以看到heap的访问权限是rw,即可写,所以可以通过堆地址找到上个示例程序中字符串的地址,并通过修改mem文件对应地址的内容,就可以修改字符串的内容啦,程序:

  1. #include <stdlib.h> 
  2. #include <stdio.h> 
  3. #include <string.h> 
  4. #include <unistd.h> 
  5.  
  6. /**               
  7.  * main - uses strdup to create a new string, loops forever-ever 
  8.  *                 
  9.  * Return: EXIT_FAILURE if malloc failed. Other never returns 
  10.  */ 
  11. int main(void) 
  12.      char *s; 
  13.      unsigned long int i; 
  14.  
  15.      s = strdup("test_memory"); 
  16.      if (s == NULL
  17.      { 
  18.           fprintf(stderr, "Can't allocate mem with malloc\n"); 
  19.           return (EXIT_FAILURE); 
  20.      } 
  21.      i = 0; 
  22.      while (s) 
  23.      { 
  24.           printf("[%lu] %s (%p)\n", i, s, (void *)s); 
  25.           sleep(1); 
  26.           i++; 
  27.      } 
  28.      return (EXIT_SUCCESS); 
  29. 编译运行:gcc -Wall -Wextra -pedantic -Werror main.c -o loop; ./loop 
  30. 输出: 
  31. [0] test_memory (0x21dc010) 
  32. [1] test_memory (0x21dc010) 
  33. [2] test_memory (0x21dc010) 
  34. [3] test_memory (0x21dc010) 
  35. [4] test_memory (0x21dc010) 
  36. [5] test_memory (0x21dc010) 
  37. [6] test_memory (0x21dc010) 
  38. ... 

这里可以写一个脚本通过/proc文件系统找到字符串所在位置并修改其内容,相应的输出也会更改。

首先找到进程的进程号

  1. ps aux | grep ./loop | grep -v grep 
  2. zjucad    2542  0.0  0.0   4352   636 pts/3    S+   12:28   0:00 ./loop 

2542即为loop程序的进程号,cat /proc/2542/maps得到

  1. 00400000-00401000 r-xp 00000000 08:01 811716                             /home/zjucad/wangzhiqiang/loop 
  2. 00600000-00601000 r--p 00000000 08:01 811716                             /home/zjucad/wangzhiqiang/loop 
  3. 00601000-00602000 rw-p 00001000 08:01 811716                             /home/zjucad/wangzhiqiang/loop 
  4. 021dc000-021fd000 rw-p 00000000 00:00 0                                  [heap] 
  5. 7f2adae2a000-7f2adafea000 r-xp 00000000 08:01 8661324                    /lib/x86_64-linux-gnu/libc-2.23.so 
  6. 7f2adafea000-7f2adb1ea000 ---p 001c0000 08:01 8661324                    /lib/x86_64-linux-gnu/libc-2.23.so 
  7. 7f2adb1ea000-7f2adb1ee000 r--p 001c0000 08:01 8661324                    /lib/x86_64-linux-gnu/libc-2.23.so 
  8. 7f2adb1ee000-7f2adb1f0000 rw-p 001c4000 08:01 8661324                    /lib/x86_64-linux-gnu/libc-2.23.so 
  9. 7f2adb1f0000-7f2adb1f4000 rw-p 00000000 00:00 0 
  10. 7f2adb1f4000-7f2adb21a000 r-xp 00000000 08:01 8661310                    /lib/x86_64-linux-gnu/ld-2.23.so 
  11. 7f2adb3fa000-7f2adb3fd000 rw-p 00000000 00:00 0 
  12. 7f2adb419000-7f2adb41a000 r--p 00025000 08:01 8661310                    /lib/x86_64-linux-gnu/ld-2.23.so 
  13. 7f2adb41a000-7f2adb41b000 rw-p 00026000 08:01 8661310                    /lib/x86_64-linux-gnu/ld-2.23.so 
  14. 7f2adb41b000-7f2adb41c000 rw-p 00000000 00:00 0 
  15. 7ffd51bb3000-7ffd51bd4000 rw-p 00000000 00:00 0                          [stack] 
  16. 7ffd51bdd000-7ffd51be0000 r--p 00000000 00:00 0                          [vvar] 
  17. 7ffd51be0000-7ffd51be2000 r-xp 00000000 00:00 0                          [vdso] 
  18. ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall] 

看见堆地址范围021dc000-021fd000,并且可读可写,而且021dc000<0x21dc010<021fd000,这就可以确认字符串的地址在堆中,在堆中的索引是0x10(至于为什么是0x10,后面会讲到),这时可以通过mem文件到0x21dc010地址修改内容,字符串输出的内容也会随之更改,这里通过python脚本实现此功能。

  1. #!/usr/bin/env python3 
  2. '''              
  3. Locates and replaces the first occurrence of a string in the heap 
  4. of a process     
  5.  
  6. Usage: ./read_write_heap.py PID search_string replace_by_string 
  7. Where:            
  8. - PID is the pid of the target process 
  9. - search_string is the ASCII string you are looking to overwrite 
  10. - replace_by_string is the ASCII string you want to replace 
  11.   search_string with 
  12. ''
  13.  
  14. import sys 
  15.  
  16. def print_usage_and_exit(): 
  17.     print('Usage: {} pid search write'.format(sys.argv[0])) 
  18.     sys.exit(1) 
  19.  
  20. check usage   
  21. if len(sys.argv) != 4: 
  22.     print_usage_and_exit() 
  23.  
  24. # get the pid from args 
  25. pid = int(sys.argv[1]) 
  26. if pid <= 0: 
  27.     print_usage_and_exit() 
  28. search_string = str(sys.argv[2]) 
  29. if search_string  == ""
  30.     print_usage_and_exit() 
  31. write_string = str(sys.argv[3]) 
  32. if search_string  == ""
  33.     print_usage_and_exit() 
  34.  
  35. open the maps and mem files of the process 
  36. maps_filename = "/proc/{}/maps".format(pid) 
  37. print("[*] maps: {}".format(maps_filename)) 
  38. mem_filename = "/proc/{}/mem".format(pid) 
  39. print("[*] mem: {}".format(mem_filename)) 
  40.  
  41. # try opening the maps file 
  42. try: 
  43.     maps_file = open('/proc/{}/maps'.format(pid), 'r'
  44. except IOError as e: 
  45.     print("[ERROR] Can not open file {}:".format(maps_filename)) 
  46.     print("        I/O error({}): {}".format(e.errno, e.strerror)) 
  47.     sys.exit(1) 
  48.  
  49. for line in maps_file: 
  50.     sline = line.split(' '
  51.     # check if we found the heap 
  52.     if sline[-1][:-1] != "[heap]"
  53.         continue 
  54.     print("[*] Found [heap]:"
  55.  
  56.     # parse line 
  57.     addr = sline[0] 
  58.     perm = sline[1] 
  59.     offset = sline[2] 
  60.     device = sline[3] 
  61.     inode = sline[4] 
  62.     pathname = sline[-1][:-1] 
  63.     print("\tpathname = {}".format(pathname)) 
  64.     print("\taddresses = {}".format(addr)) 
  65.     print("\tpermisions = {}".format(perm)) 
  66.     print("\toffset = {}".format(offset)) 
  67.     print("\tinode = {}".format(inode)) 
  68.  
  69.     # check if there is read and write permission 
  70.     if perm[0] != 'r' or perm[1] != 'w'
  71.         print("[*] {} does not have read/write permission".format(pathname)) 
  72.         maps_file.close() 
  73.         exit(0) 
  74.  
  75.     # get start and end of the heap in the virtual memory 
  76.     addr = addr.split("-"
  77.     if len(addr) != 2: # never trust anyone, not even your OS :) 
  78.         print("[*] Wrong addr format"
  79.         maps_file.close() 
  80.         exit(1) 
  81.     addr_start = int(addr[0], 16) 
  82.     addr_end = int(addr[1], 16) 
  83.     print("\tAddr start [{:x}] | end [{:x}]".format(addr_start, addr_end)) 
  84.  
  85.     # open and read mem 
  86.     try: 
  87.         mem_file = open(mem_filename, 'rb+'
  88.     except IOError as e: 
  89.         print("[ERROR] Can not open file {}:".format(mem_filename)) 
  90.         print("        I/O error({}): {}".format(e.errno, e.strerror)) 
  91.         maps_file.close() 
  92.         exit(1) 
  93.  
  94.     # read heap   
  95.     mem_file.seek(addr_start) 
  96.     heap = mem_file.read(addr_end - addr_start) 
  97.  
  98.     # find string 
  99.     try: 
  100.         i = heap.index(bytes(search_string, "ASCII")) 
  101.     except Exception: 
  102.         print("Can't find '{}'".format(search_string)) 
  103.         maps_file.close() 
  104.         mem_file.close() 
  105.         exit(0) 
  106.     print("[*] Found '{}' at {:x}".format(search_string, i)) 
  107.  
  108.     # write the new string 
  109.     print("[*] Writing '{}' at {:x}".format(write_string, addr_start + i)) 
  110.     mem_file.seek(addr_start + i) 
  111.     mem_file.write(bytes(write_string, "ASCII")) 
  112.  
  113.     # close files 
  114.     maps_file.close() 
  115.     mem_file.close() 
  116.  
  117.     # there is only one heap in our example 
  118.     break 

运行这个Python脚本

  1. zjucad@zjucad-ONDA-H110-MINI-V3-01:~/wangzhiqiang$ sudo ./loop.py 2542 test_memory test_hello 
  2. [*] maps: /proc/2542/maps 
  3. [*] mem: /proc/2542/mem 
  4. [*] Found [heap]: 
  5.         pathname = [heap] 
  6.         addresses = 021dc000-021fd000 
  7.         permisions = rw-p 
  8.         offset = 00000000 
  9.         inode = 0 
  10.         Addr start [21dc000] | end [21fd000] 
  11. [*] Found 'test_memory' at 10 
  12. [*] Writing 'test_hello' at 21dc010 

同时字符串输出的内容也已更改

  1. [633] test_memory (0x21dc010) 
  2. [634] test_memory (0x21dc010) 
  3. [635] test_memory (0x21dc010) 
  4. [636] test_memory (0x21dc010) 
  5. [637] test_memory (0x21dc010) 
  6. [638] test_memory (0x21dc010) 
  7. [639] test_memory (0x21dc010) 
  8. [640] test_helloy (0x21dc010) 
  9. [641] test_helloy (0x21dc010) 
  10. [642] test_helloy (0x21dc010) 
  11. [643] test_helloy (0x21dc010) 
  12. [644] test_helloy (0x21dc010) 
  13. [645] test_helloy (0x21dc010) 

实验成功。

通过实践画出虚拟内存空间分布图

再列出内存空间分布图

 

基本上每个人或多或少都了解虚拟内存的空间分布,那如何验证它呢,下面会提到。

堆栈空间

首先验证栈空间的位置,我们都知道C中局部变量是存储在栈空间的,malloc分配的内存是存储在堆空间,所以可以通过打印出局部变量地址和malloc的返回内存地址的方式来验证堆栈空间在整个虚拟空间中的位置。

  1. #include <stdlib.h> 
  2. #include <stdio.h> 
  3. #include <string.h> 
  4.  
  5. /** 
  6.  * main - print locations of various elements 
  7.  * 
  8.  * Return: EXIT_FAILURE if something failed. Otherwise EXIT_SUCCESS 
  9.  */ 
  10. int main(void) 
  11.     int a; 
  12.     void *p; 
  13.  
  14.     printf("Address of a: %p\n", (void *)&a); 
  15.     p = malloc(98); 
  16.     if (p == NULL
  17.     { 
  18.         fprintf(stderr, "Can't malloc\n"); 
  19.         return (EXIT_FAILURE); 
  20.     } 
  21.     printf("Allocated space in the heap: %p\n", p); 
  22.     return (EXIT_SUCCESS); 
  23. 编译运行:gcc -Wall -Wextra -pedantic -Werror main.c -o test; ./test 
  24. 输出: 
  25. Address of a: 0x7ffedde9c7fc 
  26. Allocated space in the heap: 0x55ca5b360670 

通过结果可以看出堆地址空间在栈地址空间下面,整理如图:

 

可执行程序

可执行程序也在虚拟内存中,可以通过打印main函数的地址,并与堆栈地址相比较,即可知道可执行程序地址相对于堆栈地址的分布。

  1. #include <stdlib.h> 
  2. #include <stdio.h> 
  3. #include <string.h> 
  4.  
  5. /** 
  6.  * main - print locations of various elements 
  7.  * 
  8.  * Return: EXIT_FAILURE if something failed. Otherwise EXIT_SUCCESS 
  9.  */ 
  10. int main(void) 
  11.     int a; 
  12.     void *p; 
  13.  
  14.     printf("Address of a: %p\n", (void *)&a); 
  15.     p = malloc(98); 
  16.     if (p == NULL
  17.     { 
  18.         fprintf(stderr, "Can't malloc\n"); 
  19.         return (EXIT_FAILURE); 
  20.     } 
  21.     printf("Allocated space in the heap: %p\n", p); 
  22.     printf("Address of function main: %p\n", (void *)main); 
  23.     return (EXIT_SUCCESS); 
  24. 编译运行:gcc main.c -o test; ./test 
  25. 输出: 
  26. Address of a: 0x7ffed846de2c 
  27. Allocated space in the heap: 0x561b9ee8c670 
  28. Address of function main: 0x561b9deb378a 

由于main(0x561b9deb378a) < heap(0x561b9ee8c670) < (0x7ffed846de2c),可以画出分布图如下:

virtual_memory_stack_heap_executable.png 

命令行参数和环境变量

程序入口main函数可以携带参数:

  • 第一个参数(argc): 命令行参数的个数
  • 第二个参数(argv): 指向命令行参数数组的指针
  • 第三个参数(env): 指向环境变量数组的指针

通过程序可以看见这些元素在虚拟内存中的位置:

  1. #include <stdlib.h> 
  2. #include <stdio.h> 
  3. #include <string.h> 
  4.  
  5. /** 
  6.  * main - print locations of various elements 
  7.  * 
  8.  * Return: EXIT_FAILURE if something failed. Otherwise EXIT_SUCCESS 
  9.  */ 
  10. int main(int ac, char **av, char **env) 
  11.         int a; 
  12.         void *p; 
  13.         int i; 
  14.  
  15.         printf("Address of a: %p\n", (void *)&a); 
  16.         p = malloc(98); 
  17.         if (p == NULL
  18.         { 
  19.                 fprintf(stderr, "Can't malloc\n"); 
  20.                 return (EXIT_FAILURE); 
  21.         } 
  22.         printf("Allocated space in the heap: %p\n", p); 
  23.         printf("Address of function main: %p\n", (void *)main); 
  24.         printf("First bytes of the main function:\n\t"); 
  25.         for (i = 0; i < 15; i++) 
  26.         { 
  27.                 printf("%02x ", ((unsigned char *)main)[i]); 
  28.         } 
  29.         printf("\n"); 
  30.         printf("Address of the array of arguments: %p\n", (void *)av); 
  31.         printf("Addresses of the arguments:\n\t"); 
  32.         for (i = 0; i < ac; i++) 
  33.         { 
  34.                 printf("[%s]:%p ", av[i], av[i]); 
  35.         } 
  36.         printf("\n"); 
  37.         printf("Address of the array of environment variables: %p\n", (void *)env); 
  38.     printf("Address of the first environment variable: %p\n", (void *)(env[0])); 
  39.         return (EXIT_SUCCESS); 
  40. 编译运行:gcc main.c -o test; ./test nihao hello 
  41. 输出: 
  42. Address of a: 0x7ffcc154a748 
  43. Allocated space in the heap: 0x559bd1bee670 
  44. Address of function main: 0x559bd09807ca 
  45. First bytes of the main function
  46.         55 48 89 e5 48 83 ec 40 89 7d dc 48 89 75 d0 
  47. Address of the array of arguments: 0x7ffcc154a848 
  48. Addresses of the arguments: 
  49.         [./test]:0x7ffcc154b94f [nihao]:0x7ffcc154b956 [hello]:0x7ffcc154b95c 
  50. Address of the array of environment variables: 0x7ffcc154a868 
  51. Address of the first environment variable: 0x7ffcc154b962 

结果如下:

main(0x559bd09807ca) < heap(0x559bd1bee670) < stack(0x7ffcc154a748) < argv(0x7ffcc154a848) < env(0x7ffcc154a868) < arguments(0x7ffcc154b94f->0x7ffcc154b95c + 6)(6为hello+1('\0')) < env first(0x7ffcc154b962)

可以看出所有的命令行参数都是相邻的,并且紧接着就是环境变量。

argv和env数组地址是相邻的吗

上例中argv有4个元素,命令行中有三个参数,还有一个NULL指向标记数组的末尾,每个指针是8字节,8*4=32, argv(0x7ffcc154a848) + 32(0x20) = env(0x7ffcc154a868),所以argv和env数组指针是相邻的.

命令行参数地址紧随环境变量地址之后吗

首先需要获取环境变量数组的大小,环境变量数组是以NULL结束的,所以可以遍历env数组,检查是否为NULL,获取数组大小,代码如下:

  1. #include <stdlib.h> 
  2. #include <stdio.h> 
  3. #include <string.h> 
  4.  
  5. /**                                                                                                       
  6.  * main - print locations of various elements                                                             
  7.  *                                                                                                        
  8.  * Return: EXIT_FAILURE if something failed. Otherwise EXIT_SUCCESS                                       
  9.  */ 
  10. int main(int ac, char **av, char **env) 
  11.      int a; 
  12.      void *p; 
  13.      int i; 
  14.      int size
  15.  
  16.      printf("Address of a: %p\n", (void *)&a); 
  17.      p = malloc(98); 
  18.      if (p == NULL
  19.      { 
  20.           fprintf(stderr, "Can't malloc\n"); 
  21.           return (EXIT_FAILURE); 
  22.      } 
  23.      printf("Allocated space in the heap: %p\n", p); 
  24.      printf("Address of function main: %p\n", (void *)main); 
  25.      printf("First bytes of the main function:\n\t"); 
  26.      for (i = 0; i < 15; i++) 
  27.      { 
  28.           printf("%02x ", ((unsigned char *)main)[i]); 
  29.      } 
  30.      printf("\n"); 
  31.      printf("Address of the array of arguments: %p\n", (void *)av); 
  32.      printf("Addresses of the arguments:\n\t"); 
  33.      for (i = 0; i < ac; i++) 
  34.      { 
  35.           printf("[%s]:%p ", av[i], av[i]); 
  36.      } 
  37.      printf("\n"); 
  38.      printf("Address of the array of environment variables: %p\n", (void *)env); 
  39.      printf("Address of the first environment variables:\n"); 
  40.      for (i = 0; i < 3; i++) 
  41.      { 
  42.           printf("\t[%p]:\"%s\"\n", env[i], env[i]); 
  43.      } 
  44.      /* size of the env array */ 
  45.      i = 0; 
  46.      while (env[i] != NULL
  47.      { 
  48.           i++; 
  49.      } 
  50.      i++; /* the NULL pointer */ 
  51.      size = i * sizeof(char *); 
  52.      printf("Size of the array env: %d elements -> %d bytes (0x%x)\n", i, sizesize); 
  53.      return (EXIT_SUCCESS); 
  54.  
  55. 编译运行:gcc main.c -o test; ./test nihao hello 
  56. 输出: 
  57. Address of a: 0x7ffd5ebadff4 
  58. Allocated space in the heap: 0x562ba4e13670 
  59. Address of function main: 0x562ba2f1881a 
  60. First bytes of the main function
  61.         55 48 89 e5 48 83 ec 40 89 7d dc 48 89 75 d0 
  62. Address of the array of arguments: 0x7ffd5ebae0f8 
  63. Addresses of the arguments: 
  64.         [./test]:0x7ffd5ebae94f [nihao]:0x7ffd5ebae956 [hello]:0x7ffd5ebae95c 
  65. Address of the array of environment variables: 0x7ffd5ebae118 
  66. Address of the first environment variables: 
  67.         [0x7ffd5ebae962]:"LS_COLORS=rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=00:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.zst=01;31:*.tzst=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.wim=01;31:*.swm=01;31:*.dwm=01;31:*.esd=01;31:*.jpg=01;35:*.jpeg=01;35:*.mjpg=01;35:*.mjpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.m4a=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.oga=00;36:*.opus=00;36:*.spx=00;36:*.xspf=00;36:" 
  68.         [0x7ffd5ebaef4e]:"HOSTNAME=3e8650948c0c" 
  69.         [0x7ffd5ebaef64]:"OLDPWD=/" 
  70. Size of the array env: 11 elements -> 88 bytes (0x58) 
  71.  
  72. 运算结果如下: 
  73. root@3e8650948c0c:/ubuntu# bc 
  74. bc 1.07.1 
  75. Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006, 2008, 2012-2017 Free Software Foundation, Inc. 
  76. This is free software with ABSOLUTELY NO WARRANTY. 
  77. For details type `warranty'. 
  78. obase=16 
  79. ibase=16 
  80. 58+7ffd5ebae118 
  81. (standard_in) 3: syntax error 
  82. 58+7FFD5EBAE118 
  83. 7FFD5EBAE170 
  84. quit 
  85. 通过结果可知7FFD5EBAE170 != 0x7 

通过结果可知7FFD5EBAE170 != 0x7ffd5ebae94f,所以命令行参数地址不是紧随环境变量地址之后。

截至目前画出图表如下:

 

栈内存真的向下增长吗

可以通过调用函数来确认,如果真的是向下增长,那么调用函数的地址应该高于被调用函数地址, 代码如下:

  1. #include <stdlib.h> 
  2. #include <stdio.h> 
  3. #include <string.h> 
  4.  
  5. void f(void) 
  6.      int a; 
  7.      int b; 
  8.      int c; 
  9.  
  10.      a = 98; 
  11.      b = 1024; 
  12.      c = a * b; 
  13.      printf("[f] a = %d, b = %d, c = a * b = %d\n", a, b, c); 
  14.      printf("[f] Adresses of a: %p, b = %p, c = %p\n", (void *)&a, (void *)&b, (void *)&c); 
  15.  
  16. int main(int ac, char **av, char **env) 
  17.      int a; 
  18.      void *p; 
  19.      int i; 
  20.      int size
  21.  
  22.      printf("Address of a: %p\n", (void *)&a); 
  23.      p = malloc(98); 
  24.      if (p == NULL
  25.      { 
  26.           fprintf(stderr, "Can't malloc\n"); 
  27.           return (EXIT_FAILURE); 
  28.      } 
  29.      printf("Allocated space in the heap: %p\n", p); 
  30.      printf("Address of function main: %p\n", (void *)main); 
  31.      f(); 
  32.      return (EXIT_SUCCESS); 
  33. 编译运行:gcc main.c -o test; ./test 
  34. 输出: 
  35. Address of a: 0x7ffefc75083c 
  36. Allocated space in the heap: 0x564d46318670 
  37. Address of function main: 0x564d45b9880e 
  38. [f] a = 98, b = 1024, c = a * b = 100352 
  39. [f] Adresses of a: 0x7ffefc7507ec, b = 0x7ffefc7507f0, c = 0x7ffefc7507f4 

结果可知: f{a} 0x7ffefc7507ec < main{a} 0x7ffefc75083c

可画图如下:

 

其实也可以写一个简单的代码,通过查看/proc文件系统中map内容来查看内存分布,这里就不举例啦。

堆内存(malloc)

malloc

malloc是常用的动态分配内存的函数,malloc申请的内存分配在堆中,注意malloc是glibc函数,不是系统调用。

man malloc:

  1. [...] allocate dynamic memory[...] 
  2. void *malloc(size_t size); 
  3. [...] 
  4. The malloc() function allocates size bytes and returns a pointer to the allocated memory. 

不调用malloc,就不会有堆空间[heap]

看一段不调用malloc的代码

  1. #include <stdlib.h> 
  2. #include <stdio.h> 
  3.  
  4. /** 
  5.  * main - do nothing 
  6.  * 
  7.  * Return: EXIT_FAILURE if something failed. Otherwise EXIT_SUCCESS 
  8.  */ 
  9. int main(void) 
  10.     getchar(); 
  11.     return (EXIT_SUCCESS); 
  12. 编译运行:gcc test.c -o 2; ./2 
  13. step 1 : ps aux | grep \ \./2$ 
  14. 输出: 
  15. zjucad    3023  0.0  0.0   4352   788 pts/3    S+   13:58   0:00 ./2 
  16. step 2 : /proc/3023/maps 
  17. 输出: 
  18. 00400000-00401000 r-xp 00000000 08:01 811723                             /home/zjucad/wangzhiqiang/2 
  19. 00600000-00601000 r--p 00000000 08:01 811723                             /home/zjucad/wangzhiqiang/2 
  20. 00601000-00602000 rw-p 00001000 08:01 811723                             /home/zjucad/wangzhiqiang/2 
  21. 007a4000-007c5000 rw-p 00000000 00:00 0                                  [heap] 
  22. 7f954ca02000-7f954cbc2000 r-xp 00000000 08:01 8661324                    /lib/x86_64-linux-gnu/libc-2.23.so 
  23. 7f954cbc2000-7f954cdc2000 ---p 001c0000 08:01 8661324                    /lib/x86_64-linux-gnu/libc-2.23.so 
  24. 7f954cdc2000-7f954cdc6000 r--p 001c0000 08:01 8661324                    /lib/x86_64-linux-gnu/libc-2.23.so 
  25. 7f954cdc6000-7f954cdc8000 rw-p 001c4000 08:01 8661324                    /lib/x86_64-linux-gnu/libc-2.23.so 
  26. 7f954cdc8000-7f954cdcc000 rw-p 00000000 00:00 0 
  27. 7f954cdcc000-7f954cdf2000 r-xp 00000000 08:01 8661310                    /lib/x86_64-linux-gnu/ld-2.23.so 
  28. 7f954cfd2000-7f954cfd5000 rw-p 00000000 00:00 0 
  29. 7f954cff1000-7f954cff2000 r--p 00025000 08:01 8661310                    /lib/x86_64-linux-gnu/ld-2.23.so 
  30. 7f954cff2000-7f954cff3000 rw-p 00026000 08:01 8661310                    /lib/x86_64-linux-gnu/ld-2.23.so 
  31. 7f954cff3000-7f954cff4000 rw-p 00000000 00:00 0 
  32. 7ffed68a1000-7ffed68c2000 rw-p 00000000 00:00 0                          [stack] 
  33. 7ffed690e000-7ffed6911000 r--p 00000000 00:00 0                          [vvar] 
  34. 7ffed6911000-7ffed6913000 r-xp 00000000 00:00 0                          [vdso] 
  35. ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall] 

可以看到,如果不调用malloc,maps中就没有[heap]

下面运行一个带有malloc的程序

  1. #include <stdio.h> 
  2. #include <stdlib.h> 
  3.  
  4. /** 
  5.  * main - prints the malloc returned address 
  6.  * 
  7.  * Return: EXIT_FAILURE if something failed. Otherwise EXIT_SUCCESS 
  8.  */ 
  9. int main(void) 
  10.     void *p; 
  11.  
  12.     p = malloc(1); 
  13.     printf("%p\n", p); 
  14.     getchar(); 
  15.     return (EXIT_SUCCESS); 
  16. 编译运行:gcc test.c -o 3; ./3 
  17. 输出:0xcc7010 
  18. 验证步骤及输出: 
  19. zjucad@zjucad-ONDA-H110-MINI-V3-01:~/wangzhiqiang$ ps aux | grep \ \./3$ 
  20. zjucad    3113  0.0  0.0   4352   644 pts/3    S+   14:06   0:00 ./3 
  21. zjucad@zjucad-ONDA-H110-MINI-V3-01:~/wangzhiqiang$ cat /proc/3113/maps 
  22. 00400000-00401000 r-xp 00000000 08:01 811726                             /home/zjucad/wangzhiqiang/3 
  23. 00600000-00601000 r--p 00000000 08:01 811726                             /home/zjucad/wangzhiqiang/3 
  24. 00601000-00602000 rw-p 00001000 08:01 811726                             /home/zjucad/wangzhiqiang/3 
  25. 00cc7000-00ce8000 rw-p 00000000 00:00 0                                  [heap] 
  26. 7fc7e9128000-7fc7e92e8000 r-xp 00000000 08:01 8661324                    /lib/x86_64-linux-gnu/libc-2.23.so 
  27. 7fc7e92e8000-7fc7e94e8000 ---p 001c0000 08:01 8661324                    /lib/x86_64-linux-gnu/libc-2.23.so 
  28. 7fc7e94e8000-7fc7e94ec000 r--p 001c0000 08:01 8661324                    /lib/x86_64-linux-gnu/libc-2.23.so 
  29. 7fc7e94ec000-7fc7e94ee000 rw-p 001c4000 08:01 8661324                    /lib/x86_64-linux-gnu/libc-2.23.so 
  30. 7fc7e94ee000-7fc7e94f2000 rw-p 00000000 00:00 0 
  31. 7fc7e94f2000-7fc7e9518000 r-xp 00000000 08:01 8661310                    /lib/x86_64-linux-gnu/ld-2.23.so 
  32. 7fc7e96f8000-7fc7e96fb000 rw-p 00000000 00:00 0 
  33. 7fc7e9717000-7fc7e9718000 r--p 00025000 08:01 8661310                    /lib/x86_64-linux-gnu/ld-2.23.so 
  34. 7fc7e9718000-7fc7e9719000 rw-p 00026000 08:01 8661310                    /lib/x86_64-linux-gnu/ld-2.23.so 
  35. 7fc7e9719000-7fc7e971a000 rw-p 00000000 00:00 0 
  36. 7ffc91c18000-7ffc91c39000 rw-p 00000000 00:00 0                          [stack] 
  37. 7ffc91d5f000-7ffc91d62000 r--p 00000000 00:00 0                          [vvar] 
  38. 7ffc91d62000-7ffc91d64000 r-xp 00000000 00:00 0                          [vdso] 
  39. ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall] 

程序中带有malloc,那maps中就有[heap]段,并且malloc返回的地址在heap的地址段中,但是返回的地址却不再heap的最开始地址上,相差了0x10字节,为什么呢?看下面:

strace, brk, sbrk

malloc不是系统调用,它是一个正常函数,它必须调用某些系统调用才可以操作堆内存,通过使用strace工具可以追踪进程的系统调用和信号,为了确认系统调用是malloc产生的,所以在malloc前后添加write系统调用方便定位问题。

  1. #include <stdio.h> 
  2. #include <stdlib.h> 
  3. #include <unistd.h> 
  4.  
  5. /** 
  6.  * main - let's find out which syscall malloc is using 
  7.  * 
  8.  * Return: EXIT_FAILURE if something failed. Otherwise EXIT_SUCCESS 
  9.  */ 
  10. int main(void) 
  11.     void *p; 
  12.  
  13.     write(1, "BEFORE MALLOC\n", 14); 
  14.     p = malloc(1); 
  15.     write(1, "AFTER MALLOC\n", 13); 
  16.     printf("%p\n", p); 
  17.     getchar(); 
  18.     return (EXIT_SUCCESS); 
  19. 编译运行:gcc test.c -o 4 
  20. zjucad@zjucad-ONDA-H110-MINI-V3-01:~/wangzhiqiang$ strace ./4 
  21. execve("./4", ["./4"], [/* 34 vars */]) = 0 
  22. brk(NULL)                               = 0x781000 
  23. access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory) 
  24. access("/etc/ld.so.preload", R_OK)      = -1 ENOENT (No such file or directory) 
  25. open("/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3 
  26. fstat(3, {st_mode=S_IFREG|0644, st_size=111450, ...}) = 0 
  27. mmap(NULL, 111450, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7f37720fa000 
  28. close(3)                                = 0 
  29. access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory) 
  30. open("/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3 
  31. read(3, "\177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0P\t\2\0\0\0\0\0"..., 832) = 832 
  32. fstat(3, {st_mode=S_IFREG|0755, st_size=1868984, ...}) = 0 
  33. mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f37720f9000 
  34. mmap(NULL, 3971488, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f3771b27000 
  35. mprotect(0x7f3771ce7000, 2097152, PROT_NONE) = 0 
  36. mmap(0x7f3771ee7000, 24576, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1c0000) = 0x7f3771ee7000 
  37. mmap(0x7f3771eed000, 14752, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7f3771eed000 
  38. close(3)                                = 0 
  39. mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f37720f8000 
  40. mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f37720f7000 
  41. arch_prctl(ARCH_SET_FS, 0x7f37720f8700) = 0 
  42. mprotect(0x7f3771ee7000, 16384, PROT_READ) = 0 
  43. mprotect(0x600000, 4096, PROT_READ)     = 0 
  44. mprotect(0x7f3772116000, 4096, PROT_READ) = 0 
  45. munmap(0x7f37720fa000, 111450)          = 0 
  46. write(1, "BEFORE MALLOC\n", 14BEFORE MALLOC 
  47. )         = 14 
  48. brk(NULL)                               = 0x781000 
  49. brk(0x7a2000)                           = 0x7a2000 
  50. write(1, "AFTER MALLOC\n", 13AFTER MALLOC 
  51. )          = 13 
  52. fstat(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 3), ...}) = 0 
  53. write(1, "0x781010\n", 90x781010 
  54. )               = 9 
  55. fstat(0, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 3), ...}) = 0 

最后几行的输出可知,malloc主要调用brk系统调用来操作堆内存。

  1. man brk 
  2. ... 
  3.        int brk(void *addr); 
  4.        void *sbrk(intptr_t increment); 
  5. ... 
  6. DESCRIPTION 
  7.        brk() and sbrk() change the location of the program  break,  which  defines 
  8.        the end of the process's data segment (i.e., the program break is the first 
  9.        location after the end of the uninitialized data segment).  Increasing  the 
  10.        program  break has the effect of allocating memory to the process; decreas‐ 
  11.        ing the break deallocates memory. 
  12.  
  13.        brk() sets the end of the data segment to the value specified by addr, when 
  14.        that  value  is  reasonable,  the system has enough memory, and the process 
  15.        does not exceed its maximum data size (see setrlimit(2)). 
  16.  
  17.        sbrk() increments the program's data space  by  increment  bytes.   Calling 
  18.        sbrk()  with  an increment of 0 can be used to find the current location of 
  19.        the program break. 

程序中断是虚拟内存中程序数据段结束后的第一个位置的地址,malloc通过调用brk或者sbrk,增加程序中断的值就可以创建新空间来动态分配内存,首次调用brk会返回当前程序中断的地址,第二次调用brk也会返回程序中断的地址,可以发现第二次brk返回地址大于第一次brk返回地址,brk就是通过增加程序中断地址的方式来分配内存,可以看出现在的堆地址范围是0x781000-0x7a2000,通过cat /proc/[pid]/maps也可以验证,此处就不贴上实际验证的结果啦。

多次malloc

如果多次malloc会出现什么现象呢,代码如下:

  1. #include <stdio.h> 
  2. #include <stdlib.h> 
  3. #include <unistd.h> 
  4.  
  5. /** 
  6.  * main - many calls to malloc 
  7.  * 
  8.  * Return: EXIT_FAILURE if something failed. Otherwise EXIT_SUCCESS 
  9.  */ 
  10. int main(void) 
  11.     void *p; 
  12.  
  13.     write(1, "BEFORE MALLOC #0\n", 17); 
  14.     p = malloc(1024); 
  15.     write(1, "AFTER MALLOC #0\n", 16); 
  16.     printf("%p\n", p); 
  17.  
  18.     write(1, "BEFORE MALLOC #1\n", 17); 
  19.     p = malloc(1024); 
  20.     write(1, "AFTER MALLOC #1\n", 16); 
  21.     printf("%p\n", p); 
  22.  
  23.     write(1, "BEFORE MALLOC #2\n", 17); 
  24.     p = malloc(1024); 
  25.     write(1, "AFTER MALLOC #2\n", 16); 
  26.     printf("%p\n", p); 
  27.  
  28.     write(1, "BEFORE MALLOC #3\n", 17); 
  29.     p = malloc(1024); 
  30.     write(1, "AFTER MALLOC #3\n", 16); 
  31.     printf("%p\n", p); 
  32.  
  33.     getchar(); 
  34.     return (EXIT_SUCCESS); 
  35. 编译运行:gcc test.c -o 5; strace ./5 
  36. 摘要输出结果如下: 
  37. write(1, "BEFORE MALLOC #0\n", 17BEFORE MALLOC #0 
  38. )      = 17 
  39. brk(NULL)                               = 0x561605c7a000 
  40. brk(0x561605c9b000)                     = 0x561605c9b000 
  41. write(1, "AFTER MALLOC #0\n", 16AFTER MALLOC #0 
  42. )       = 16 
  43. fstat(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 0), ...}) = 0 
  44. write(1, "0x561605c7a260\n", 150x561605c7a260 
  45. )        = 15 
  46. write(1, "BEFORE MALLOC #1\n", 17BEFORE MALLOC #1 
  47. )      = 17 
  48. write(1, "AFTER MALLOC #1\n", 16AFTER MALLOC #1 
  49. )       = 16 
  50. write(1, "0x561605c7aa80\n", 150x561605c7aa80 
  51. )        = 15 
  52. write(1, "BEFORE MALLOC #2\n", 17BEFORE MALLOC #2 
  53. )      = 17 
  54. write(1, "AFTER MALLOC #2\n", 16AFTER MALLOC #2 
  55. )       = 16 
  56. write(1, "0x561605c7ae90\n", 150x561605c7ae90 
  57. )        = 15 
  58. write(1, "BEFORE MALLOC #3\n", 17BEFORE MALLOC #3 
  59. )      = 17 
  60. write(1, "AFTER MALLOC #3\n", 16AFTER MALLOC #3 
  61. )       = 16 
  62. write(1, "0x561605c7b2a0\n", 150x561605c7b2a0 
  63. )        = 15 
  64. fstat(0, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 0), ...}) = 0 

可以发现并不是每次调用malloc都会触发brk系统调用,首次调用malloc,内部会通过brk系统调用更改程序中断地址,分配出一大块内存空间,后续再调用malloc,malloc内部会优先使用之前分配出来的内存空间,直到内部内存空间已经不够再次分配给外部时才会再次触发brk系统调用。

0x10 那丢失的16字节是什么

上面分析可以看见程序第一次调用malloc返回的地址并不是heap段的首地址,而是相差了0x10个字节,那这16个字节究竟是什么,可以通过程序打印出这前16个字节的内容。

  1. 编译运行:gcc test.c -o test;./test 
  2. 输出: 
  3. 0x5589436ce260 
  4. bytes at 0x5589436ce250: 
  5. 00 00 00 00 00 00 00 00 11 04 00 00 00 00 00 00 
  6. 0x5589436cea80 
  7. bytes at 0x5589436cea70: 
  8. 00 00 00 00 00 00 00 00 11 08 00 00 00 00 00 00 
  9. 0x5589436cf290 
  10. bytes at 0x5589436cf280: 
  11. 00 00 00 00 00 00 00 00 11 0c 00 00 00 00 00 00 
  12. 0x5589436cfea0 
  13. bytes at 0x5589436cfe90: 
  14. 00 00 00 00 00 00 00 00 11 10 00 00 00 00 00 00 
  15. 0x5589436d0eb0 
  16. bytes at 0x5589436d0ea0: 
  17. 00 00 00 00 00 00 00 00 11 14 00 00 00 00 00 00 
  18. 0x5589436d22c0 
  19. bytes at 0x5589436d22b0: 
  20. 00 00 00 00 00 00 00 00 11 18 00 00 00 00 00 00 
  21. 0x5589436d3ad0 
  22. bytes at 0x5589436d3ac0: 
  23. 00 00 00 00 00 00 00 00 11 1c 00 00 00 00 00 00 
  24. 0x5589436d56e0 
  25. bytes at 0x5589436d56d0: 
  26. 00 00 00 00 00 00 00 00 11 20 00 00 00 00 00 00 
  27. 0x5589436d76f0 
  28. bytes at 0x5589436d76e0: 
  29. 00 00 00 00 00 00 00 00 11 24 00 00 00 00 00 00 
  30. 0x5589436d9b00 
  31. bytes at 0x5589436d9af0: 
  32. 00 00 00 00 00 00 00 00 11 28 00 00 00 00 00 00 

可以看出规律:这16个字节相当于malloc出来的地址的头,包含一些信息,目前可以看出它包括已经分配的地址空间的大小,第一次malloc申请了0x400(1024)字节,可以发现11 04 00 00 00 00 00 00大于0x400(1024),这8个字节表示数字 0x 00 00 00 00 00 00 04 11 = 0x400(1024) + 0x10(头的大小16) + 1(后面会说明它的含义),可以发现每次调用malloc,这前8个字节代表的含义都是malloc字节数+16+1。

可以猜测,malloc内部会把这前16个字节强转成某种数据结构,数据结构包含某些信息,最主要的是已经分配的字节数,尽管我们不了解具体结构,但是也可以通过代码操作这16个字节验证我们上面总结的规律是否正确,注意代码中不调用free释放内存。

  1. #include <stdio.h> 
  2. #include <stdlib.h> 
  3. #include <unistd.h> 
  4.  
  5. /**                                                                 
  6.  * pmem - print mem                                                 
  7.  * @p: memory address to start printing from                        
  8.  * @bytes: number of bytes to print                                 
  9.  *                                                                  
  10.  * Return: nothing 
  11.  */ 
  12. void pmem(void *p, unsigned int bytes) 
  13.     unsigned char *ptr; 
  14.     unsigned int i; 
  15.  
  16.     ptr = (unsigned char *)p; 
  17.     for (i = 0; i < bytes; i++) 
  18.     { 
  19.         if (i != 0) 
  20.         { 
  21.             printf(" "); 
  22.         } 
  23.         printf("%02x", *(ptr + i)); 
  24.     } 
  25.     printf("\n"); 
  26.  
  27. /** 
  28.  * main - confirm the source code 
  29.  * 
  30.  * Return: EXIT_FAILURE if something failed. Otherwise EXIT_SUCCESS 
  31.  */ 
  32. int main(void) 
  33.     void *p; 
  34.     int i; 
  35.     size_t size_of_the_chunk; 
  36.     size_t size_of_the_previous_chunk; 
  37.     void *chunks[10]; 
  38.  
  39.     for (i = 0; i < 10; i++) 
  40.     { 
  41.         p = malloc(1024 * (i + 1)); 
  42.         chunks[i] = (void *)((char *)p - 0x10); 
  43.         printf("%p\n", p); 
  44.     } 
  45.     free((char *)(chunks[3]) + 0x10); 
  46.     free((char *)(chunks[7]) + 0x10); 
  47.     for (i = 0; i < 10; i++) 
  48.     { 
  49.         p = chunks[i]; 
  50.         printf("chunks[%d]: ", i); 
  51.         pmem(p, 0x10); 
  52.         size_of_the_chunk = *((size_t *)((char *)p + 8)) - 1; 
  53.         size_of_the_previous_chunk = *((size_t *)((char *)p)); 
  54.         printf("chunks[%d]: %p, size = %li, prev = %li\n"
  55.               i, p, size_of_the_chunk, size_of_the_previous_chunk); 
  56.     } 
  57.     return (EXIT_SUCCESS); 
  58. 编译运行输出: 
  59. root@3e8650948c0c:/ubuntu# gcc test.c -o test 
  60. root@3e8650948c0c:/ubuntu# ./test 
  61. 0x559721de4260 
  62. 0x559721de4a80 
  63. 0x559721de5290 
  64. 0x559721de5ea0 
  65. 0x559721de6eb0 
  66. 0x559721de82c0 
  67. 0x559721de9ad0 
  68. 0x559721deb6e0 
  69. 0x559721ded6f0 
  70. 0x559721defb00 
  71. chunks[0]: 00 00 00 00 00 00 00 00 11 04 00 00 00 00 00 00 
  72. chunks[0]: 0x559721de4250, size = 1040, prev = 0 
  73. chunks[1]: 00 00 00 00 00 00 00 00 11 08 00 00 00 00 00 00 
  74. chunks[1]: 0x559721de4a70, size = 2064, prev = 0 
  75. chunks[2]: 00 00 00 00 00 00 00 00 11 0c 00 00 00 00 00 00 
  76. chunks[2]: 0x559721de5280, size = 3088, prev = 0 
  77. chunks[3]: 00 00 00 00 00 00 00 00 11 10 00 00 00 00 00 00 
  78. chunks[3]: 0x559721de5e90, size = 4112, prev = 0 
  79. chunks[4]: 10 10 00 00 00 00 00 00 10 14 00 00 00 00 00 00 
  80. chunks[4]: 0x559721de6ea0, size = 5135, prev = 4112 
  81. chunks[5]: 00 00 00 00 00 00 00 00 11 18 00 00 00 00 00 00 
  82. chunks[5]: 0x559721de82b0, size = 6160, prev = 0 
  83. chunks[6]: 00 00 00 00 00 00 00 00 11 1c 00 00 00 00 00 00 
  84. chunks[6]: 0x559721de9ac0, size = 7184, prev = 0 
  85. chunks[7]: 00 00 00 00 00 00 00 00 11 20 00 00 00 00 00 00 
  86. chunks[7]: 0x559721deb6d0, size = 8208, prev = 0 
  87. chunks[8]: 10 20 00 00 00 00 00 00 10 24 00 00 00 00 00 00 
  88. chunks[8]: 0x559721ded6e0, size = 9231, prev = 8208 
  89. chunks[9]: 00 00 00 00 00 00 00 00 11 28 00 00 00 00 00 00 
  90. chunks[9]: 0x559721defaf0, size = 10256, prev = 0 

结果可以看出,malloc返回的地址往前的16个字节可以表示已经分配的内存大小, 如图:

 

注意上述是没有调用free释放内存的结果,然而malloc只用了8个字节表示已经分配的内存大小,那么另外8个字节被用来表示什么含义呢,看下malloc函数的注释:

  1. 1055 /* 
  2. 1056       malloc_chunk details: 
  3. 1057     
  4. 1058        (The following includes lightly edited explanations by Colin Plumb.) 
  5. 1059     
  6. 1060        Chunks of memory are maintained using a `boundary tag' method as 
  7. 1061        described in e.g., Knuth or Standish.  (See the paper by Paul 
  8. 1062        Wilson ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a 
  9. 1063        survey of such techniques.)  Sizes of free chunks are stored both 
  10. 1064        in the front of each chunk and at the end.  This makes 
  11. 1065        consolidating fragmented chunks into bigger chunks very fast.  The 
  12. 1066        size fields also hold bits representing whether chunks are free or 
  13. 1067        in use. 
  14. 1068     
  15. 1069        An allocated chunk looks like this: 
  16. 1070     
  17. 1071     
  18. 1072        chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 
  19. 1073                |             Size of previous chunk, if unallocated (P clear)  | 
  20. 1074                +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 
  21. 1075                |             Size of chunk, in bytes                     |A|M|P| 
  22. 1076          mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 
  23. 1077                |             User data starts here...                          . 
  24. 1078                .                                                               . 
  25. 1079                .             (malloc_usable_size() bytes)                      . 
  26. 1080                .                                                               | 
  27. 1081    nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 
  28. 1082                |             (size of chunk, but used for application data)    | 
  29. 1083                +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 
  30. 1084                |             Size of next chunk, in bytes                |A|0|1| 
  31. 1085                +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 
  32. 1086     
  33. 1087        Where "chunk" is the front of the chunk for the purpose of most of 
  34. 1088        the malloc code, but "mem" is the pointer that is returned to the 
  35. 1089        user.  "Nextchunk" is the beginning of the next contiguous chunk. 

可以看出这16字节有两个含义,前8个字节表示之前的空间有多少没有被分配的字节大小,后8个字节表示当前malloc已经分配的字节大小,通过一段调用free的代码查看:

  1. #include <stdio.h> 
  2. #include <stdlib.h> 
  3. #include <unistd.h> 
  4.  
  5. /**                                                                                             
  6.  * pmem - print mem                                                                             
  7.  * @p: memory address to start printing from                                                    
  8.  * @bytes: number of bytes to print                                                             
  9.  *                                                                                              
  10.  * Return: nothing                                                                              
  11.  */ 
  12. void pmem(void *p, unsigned int bytes) 
  13.     unsigned char *ptr; 
  14.     unsigned int i; 
  15.  
  16.     ptr = (unsigned char *)p; 
  17.     for (i = 0; i < bytes; i++) 
  18.     { 
  19.         if (i != 0) 
  20.         { 
  21.             printf(" "); 
  22.         } 
  23.         printf("%02x", *(ptr + i)); 
  24.     } 
  25.     printf("\n"); 
  26.  
  27. /** 
  28.  * main - confirm the source code 
  29.  * 
  30.  * Return: EXIT_FAILURE if something failed. Otherwise EXIT_SUCCESS 
  31.  */ 
  32. int main(void) 
  33.     void *p; 
  34.     int i; 
  35.     size_t size_of_the_chunk; 
  36.     size_t size_of_the_previous_chunk; 
  37.     void *chunks[10]; 
  38.  
  39.     for (i = 0; i < 10; i++) 
  40.     { 
  41.         p = malloc(1024 * (i + 1)); 
  42.         chunks[i] = (void *)((char *)p - 0x10); 
  43.         printf("%p\n", p); 
  44.     } 
  45.     free((char *)(chunks[3]) + 0x10); 
  46.     free((char *)(chunks[7]) + 0x10); 
  47.     for (i = 0; i < 10; i++) 
  48.     { 
  49.         p = chunks[i]; 
  50.         printf("chunks[%d]: ", i); 
  51.         pmem(p, 0x10); 
  52.         size_of_the_chunk = *((size_t *)((char *)p + 8)) - 1; 
  53.         size_of_the_previous_chunk = *((size_t *)((char *)p)); 
  54.         printf("chunks[%d]: %p, size = %li, prev = %li\n"
  55.               i, p, size_of_the_chunk, size_of_the_previous_chunk); 
  56.     } 
  57.     return (EXIT_SUCCESS); 
  58.  
  59. 编译运行输出: 
  60. root@3e8650948c0c:/ubuntu# gcc test.c -o test 
  61. root@3e8650948c0c:/ubuntu# ./test 
  62. 0x55fbebf20260 
  63. 0x55fbebf20a80 
  64. 0x55fbebf21290 
  65. 0x55fbebf21ea0 
  66. 0x55fbebf22eb0 
  67. 0x55fbebf242c0 
  68. 0x55fbebf25ad0 
  69. 0x55fbebf276e0 
  70. 0x55fbebf296f0 
  71. 0x55fbebf2bb00 
  72. chunks[0]: 00 00 00 00 00 00 00 00 11 04 00 00 00 00 00 00 
  73. chunks[0]: 0x55fbebf20250, size = 1040, prev = 0 
  74. chunks[1]: 00 00 00 00 00 00 00 00 11 08 00 00 00 00 00 00 
  75. chunks[1]: 0x55fbebf20a70, size = 2064, prev = 0 
  76. chunks[2]: 00 00 00 00 00 00 00 00 11 0c 00 00 00 00 00 00 
  77. chunks[2]: 0x55fbebf21280, size = 3088, prev = 0 
  78. chunks[3]: 00 00 00 00 00 00 00 00 11 10 00 00 00 00 00 00 
  79. chunks[3]: 0x55fbebf21e90, size = 4112, prev = 0 
  80. chunks[4]: 10 10 00 00 00 00 00 00 10 14 00 00 00 00 00 00 
  81. chunks[4]: 0x55fbebf22ea0, size = 5135, prev = 4112 
  82. chunks[5]: 00 00 00 00 00 00 00 00 11 18 00 00 00 00 00 00 
  83. chunks[5]: 0x55fbebf242b0, size = 6160, prev = 0 
  84. chunks[6]: 00 00 00 00 00 00 00 00 11 1c 00 00 00 00 00 00 
  85. chunks[6]: 0x55fbebf25ac0, size = 7184, prev = 0 
  86. chunks[7]: 00 00 00 00 00 00 00 00 11 20 00 00 00 00 00 00 
  87. chunks[7]: 0x55fbebf276d0, size = 8208, prev = 0 
  88. chunks[8]: 10 20 00 00 00 00 00 00 10 24 00 00 00 00 00 00 
  89. chunks[8]: 0x55fbebf296e0, size = 9231, prev = 8208 
  90. chunks[9]: 00 00 00 00 00 00 00 00 11 28 00 00 00 00 00 00 
  91. chunks[9]: 0x55fbebf2baf0, size = 10256, prev = 0 

程序代码通过free释放了3和7数据块的空间,所以4和8的前8个字节已经不全是0啦,和其它不同,它们表示之前数据块没有被分配的大小,也可以注意到4和8块的后8个字节不像其它块一样需要加1啦,可以得出结论,malloc通过是否加1来作为前一个数据块是否已经分配的标志,加1表示前一个数据块已经分配。所以之前的程序代码可以修改为如下形式:

  1. #include <stdio.h> 
  2. #include <stdlib.h> 
  3. #include <unistd.h> 
  4.  
  5. /**                                                                                             
  6.  * pmem - print mem                                                                             
  7.  * @p: memory address to start printing from                                                    
  8.  * @bytes: number of bytes to print                                                             
  9.  *                                                                                              
  10.  * Return: nothing                                                                              
  11.  */ 
  12. void pmem(void *p, unsigned int bytes) 
  13.     unsigned char *ptr; 
  14.     unsigned int i; 
  15.  
  16.     ptr = (unsigned char *)p; 
  17.     for (i = 0; i < bytes; i++) 
  18.     { 
  19.         if (i != 0) 
  20.         { 
  21.             printf(" "); 
  22.         } 
  23.         printf("%02x", *(ptr + i)); 
  24.     } 
  25.     printf("\n"); 
  26.  
  27. /** 
  28.  * main - updating with correct checks 
  29.  * 
  30.  * Return: EXIT_FAILURE if something failed. Otherwise EXIT_SUCCESS 
  31.  */ 
  32. int main(void) 
  33.     void *p; 
  34.     int i; 
  35.     size_t size_of_the_chunk; 
  36.     size_t size_of_the_previous_chunk; 
  37.     void *chunks[10]; 
  38.     char prev_used; 
  39.  
  40.     for (i = 0; i < 10; i++) 
  41.     { 
  42.         p = malloc(1024 * (i + 1)); 
  43.         chunks[i] = (void *)((char *)p - 0x10); 
  44.     } 
  45.     free((char *)(chunks[3]) + 0x10); 
  46.     free((char *)(chunks[7]) + 0x10); 
  47.     for (i = 0; i < 10; i++) 
  48.     { 
  49.         p = chunks[i]; 
  50.         printf("chunks[%d]: ", i); 
  51.         pmem(p, 0x10); 
  52.         size_of_the_chunk = *((size_t *)((char *)p + 8)); 
  53.         prev_used = size_of_the_chunk & 1; 
  54.         size_of_the_chunk -= prev_used; 
  55.         size_of_the_previous_chunk = *((size_t *)((char *)p)); 
  56.         printf("chunks[%d]: %p, size = %li, prev (%s) = %li\n"
  57.               i, p, size_of_the_chunk, 
  58.               (prev_used? "allocated""unallocated"), size_of_the_previous_chunk); 
  59.     } 
  60.     return (EXIT_SUCCESS); 
  61. 编译运行输出: 
  62. root@3e8650948c0c:/ubuntu# gcc test.c -o test 
  63. root@3e8650948c0c:/ubuntu# ./test 
  64. chunks[0]: 00 00 00 00 00 00 00 00 11 04 00 00 00 00 00 00 
  65. chunks[0]: 0x56254f888250, size = 1040, prev (allocated) = 0 
  66. chunks[1]: 00 00 00 00 00 00 00 00 11 08 00 00 00 00 00 00 
  67. chunks[1]: 0x56254f888660, size = 2064, prev (allocated) = 0 
  68. chunks[2]: 00 00 00 00 00 00 00 00 11 0c 00 00 00 00 00 00 
  69. chunks[2]: 0x56254f888e70, size = 3088, prev (allocated) = 0 
  70. chunks[3]: 00 00 00 00 00 00 00 00 11 04 00 00 00 00 00 00 
  71. chunks[3]: 0x56254f889a80, size = 1040, prev (allocated) = 0 
  72. chunks[4]: 00 0c 00 00 00 00 00 00 10 14 00 00 00 00 00 00 
  73. chunks[4]: 0x56254f88aa90, size = 5136, prev (unallocated) = 3072 
  74. chunks[5]: 00 00 00 00 00 00 00 00 11 18 00 00 00 00 00 00 
  75. chunks[5]: 0x56254f88bea0, size = 6160, prev (allocated) = 0 
  76. chunks[6]: 00 00 00 00 00 00 00 00 11 1c 00 00 00 00 00 00 
  77. chunks[6]: 0x56254f88d6b0, size = 7184, prev (allocated) = 0 
  78. chunks[7]: 00 00 00 00 00 00 00 00 11 20 00 00 00 00 00 00 
  79. chunks[7]: 0x56254f88f2c0, size = 8208, prev (allocated) = 0 
  80. chunks[8]: 10 20 00 00 00 00 00 00 10 24 00 00 00 00 00 00 
  81. chunks[8]: 0x56254f8912d0, size = 9232, prev (unallocated) = 8208 
  82. chunks[9]: 00 00 00 00 00 00 00 00 11 28 00 00 00 00 00 00 
  83. chunks[9]: 0x56254f8936e0, size = 10256, prev (allocated) = 0 

堆空间是向上增长吗?

通过代码验证:

  1. #include <stdio.h> 
  2. #include <stdlib.h> 
  3. #include <unistd.h> 
  4.  
  5. /** 
  6.  * main - moving the program break 
  7.  * 
  8.  * Return: EXIT_FAILURE if something failed. Otherwise EXIT_SUCCESS 
  9.  */ 
  10. int main(void) 
  11.     int i; 
  12.  
  13.     write(1, "START\n", 6); 
  14.     malloc(1); 
  15.     getchar(); 
  16.     write(1, "LOOP\n", 5); 
  17.     for (i = 0; i < 0x25000 / 1024; i++) 
  18.     { 
  19.         malloc(1024); 
  20.     } 
  21.     write(1, "END\n", 4); 
  22.     getchar(); 
  23.     return (EXIT_SUCCESS); 
  24. 编译运行部分摘要输出: 
  25. root@3e8650948c0c:/ubuntu# gcc test.c -o test 
  26. root@3e8650948c0c:/ubuntu# strace ./test 
  27. execve("./test", ["./test"], 0x7ffe0d7cbd80 /* 10 vars */) = 0 
  28. brk(NULL)                               = 0x555a2428f000 
  29. access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory) 
  30. access("/etc/ld.so.preload", R_OK)      = -1 ENOENT (No such file or directory) 
  31. openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3 
  32. fstat(3, {st_mode=S_IFREG|0644, st_size=13722, ...}) = 0 
  33. mmap(NULL, 13722, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7f6423455000 
  34. close(3)                                = 0 
  35. access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory) 
  36. openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3 
  37. read(3, "\177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\260\34\2\0\0\0\0\0"..., 832) = 832 
  38. fstat(3, {st_mode=S_IFREG|0755, st_size=2030544, ...}) = 0 
  39. mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f6423453000 
  40. mmap(NULL, 4131552, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f6422e41000 
  41. mprotect(0x7f6423028000, 2097152, PROT_NONE) = 0 
  42. mmap(0x7f6423228000, 24576, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1e7000) = 0x7f6423228000 
  43. mmap(0x7f642322e000, 15072, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7f642322e000 
  44. close(3)                                = 0 
  45. arch_prctl(ARCH_SET_FS, 0x7f64234544c0) = 0 
  46. mprotect(0x7f6423228000, 16384, PROT_READ) = 0 
  47. mprotect(0x555a22f5f000, 4096, PROT_READ) = 0 
  48. mprotect(0x7f6423459000, 4096, PROT_READ) = 0 
  49. munmap(0x7f6423455000, 13722)           = 0 
  50. write(1, "START\n", 6START 
  51. )                  = 6 
  52. brk(NULL)                               = 0x555a2428f000 
  53. brk(0x555a242b0000)                     = 0x555a242b0000 
  54. fstat(0, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 0), ...}) = 0 
  55. read(0, 
  56. "\n", 1024)                     = 1 
  57. write(1, "LOOP\n", 5LOOP 
  58. )                   = 5 
  59. brk(0x555a242d1000)                     = 0x555a242d1000 
  60. brk(0x555a242f2000)                     = 0x555a242f2000 
  61. brk(0x555a24313000)                     = 0x555a24313000 
  62. brk(0x555a24334000)                     = 0x555a24334000 
  63. brk(0x555a24355000)                     = 0x555a24355000 
  64. brk(0x555a24376000)                     = 0x555a24376000 
  65. brk(0x555a24397000)                     = 0x555a24397000 
  66. brk(0x555a243b8000)                     = 0x555a243b8000 
  67. brk(0x555a243d9000)                     = 0x555a243d9000 
  68. brk(0x555a243fa000)                     = 0x555a243fa000 

可以看出堆空间是向上增长的。

随机化地址空间布局

从开始到现在运行了好多个进程,通过查看对应进程的maps,发现每个进程的heap的起始地址和可执行程序的结束地址都不紧邻,而且差距还每次都不相同。

  1. [3718]: 01195000 – 00602000 = b93000 
  2. [3834]: 024d6000 – 00602000 = 1ed4000 
  3. [4014]: 00e70000 – 00602000 = 86e000 
  4. [4172]: 01314000 – 00602000 = d12000 
  5. [7972]: 00901000 – 00602000 = 2ff000 

可以看出这个差值是随机的,查看fs/binfmt_elf.c源代码

  1. if ((current->flags & PF_RANDOMIZE) && (randomize_va_space > 1)) { 
  2.                 current->mm->brk = current->mm->start_brk = 
  3.                         arch_randomize_brk(current->mm); 
  4. #ifdef compat_brk_randomized 
  5.                 current->brk_randomized = 1; 
  6. #endif 
  7.         } 
  8. // current->mm->brk是当前进程程序中断的地址 

arch_randomize_brk函数在arch/x86/kernel/process.c中

  1. unsigned long arch_randomize_brk(struct mm_struct *mm) 
  2.         unsigned long range_end = mm->brk + 0x02000000; 
  3.         return randomize_range(mm->brk, range_end, 0) ? : mm->brk; 

randomize_range函数在drivers/char/random.c中

  1. /* 
  2.  * randomize_range() returns a start address such that 
  3.  * 
  4.  *    [...... <range> .....] 
  5.  *  start                  end 
  6.  * 
  7.  * a <range> with size "len" starting at the return value is inside in the 
  8.  * area defined by [start, end], but is otherwise randomized. 
  9.  */ 
  10. unsigned long 
  11. randomize_range(unsigned long start, unsigned long end, unsigned long len) 
  12.         unsigned long range = end - len - start; 
  13.  
  14.         if (end <= start + len) 
  15.                 return 0; 
  16.         return PAGE_ALIGN(get_random_int() % range + start); 

可以看出上面所说的这个差值其实就是0-0x02000000中的一个随机数,这种技术称为ASLR(Address Space Layout Randomisation),是一种计算机安全技术,随机安排虚拟内存中堆栈空间的位置,可以有效防止黑客攻击。通过以上分析,可以画出内存分布图如下:

 

malloc(0)发生了什么?

当调用malloc(0)会发生什么,代码如下:

  1. #include <stdio.h> 
  2. #include <stdlib.h> 
  3. #include <unistd.h> 
  4.  
  5. /**                                                                                             
  6.  * pmem - print mem                                                                             
  7.  * @p: memory address to start printing from                                                    
  8.  * @bytes: number of bytes to print                                                             
  9.  *                                                                                              
  10.  * Return: nothing                                                                              
  11.  */ 
  12. void pmem(void *p, unsigned int bytes) 
  13.     unsigned char *ptr; 
  14.     unsigned int i; 
  15.  
  16.     ptr = (unsigned char *)p; 
  17.     for (i = 0; i < bytes; i++) 
  18.     { 
  19.         if (i != 0) 
  20.         { 
  21.             printf(" "); 
  22.         } 
  23.         printf("%02x", *(ptr + i)); 
  24.     } 
  25.     printf("\n"); 
  26.  
  27. /** 
  28.  * main - moving the program break 
  29.  * 
  30.  * Return: EXIT_FAILURE if something failed. Otherwise EXIT_SUCCESS 
  31.  */ 
  32. int main(void) 
  33.     void *p; 
  34.     size_t size_of_the_chunk; 
  35.     char prev_used; 
  36.  
  37.     p = malloc(0); 
  38.     printf("%p\n", p); 
  39.     pmem((char *)p - 0x10, 0x10); 
  40.     size_of_the_chunk = *((size_t *)((char *)p - 8)); 
  41.     prev_used = size_of_the_chunk & 1; 
  42.     size_of_the_chunk -= prev_used; 
  43.     printf("chunk size = %li bytes\n", size_of_the_chunk); 
  44.     return (EXIT_SUCCESS); 
  45. 编译运行输出如下: 
  46. root@3e8650948c0c:/ubuntu# gcc test.c -o test 
  47. root@3e8650948c0c:/ubuntu# ./test 
  48. 0x564ece64b260 
  49. 00 00 00 00 00 00 00 00 21 00 00 00 00 00 00 00 
  50. chunk size = 32 bytes 

可以看出malloc(0)实际使用了32个字节,其中包括我们之前说的16个字节头部,然而有时候malloc(0)可能会有不同的结果输出,也有可能会返回NULL。

  1. man malloc 
  2. NULL may also be returned by a successful call to malloc() with a size of zero 

操作环境

  1. 示例代码主要在两种环境下跑过:  
  2. ubuntu 16.04  
  3. gcc (Ubuntu 7.4.0-1ubuntu1~16.04~ppa1) 7.4.0  
  4.   
  5. ubuntu 18.04 docker  
  6. gcc (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0  

本文是从这一系列文章翻译并结合自己理解提炼出来的,代码都自己实践过,有时间的也可以直接阅读英文原链接

Hack The Virtual Memory: C strings & /proc  

Hack the Virtual Memory: drawing the VM diagram 

Hack the Virtual Memory: malloc, the heap & the program break 

 

责任编辑:武晓燕 来源: 程序喵大人
相关推荐

2022-07-19 16:03:14

KubernetesLinux

2022-09-06 08:02:40

死锁顺序锁轮询锁

2022-09-14 09:01:55

shell可视化

2020-07-09 07:54:35

ThreadPoolE线程池

2021-10-18 11:58:56

负载均衡虚拟机

2021-01-19 05:49:44

DNS协议

2021-02-26 05:17:38

计算机网络二进制

2023-12-04 08:10:34

Spring循环依赖

2020-07-15 08:57:40

HTTPSTCP协议

2020-11-16 10:47:14

FreeRTOS应用嵌入式

2020-07-01 08:10:34

JVM 内存

2021-06-07 15:49:51

AI 数据人工智能

2024-03-07 18:11:39

Golang采集链接

2022-10-10 08:35:17

kafka工作机制消息发送

2023-06-12 08:49:12

RocketMQ消费逻辑

2021-08-26 05:02:50

分布式设计

2024-01-11 09:53:31

面试C++

2022-09-08 10:14:29

人脸识别算法

2024-01-05 08:30:26

自动驾驶算法

2022-07-15 16:31:49

Postman测试
点赞
收藏

51CTO技术栈公众号