slub object 内存布局
我在 https://blog.csdn.net/wowricky/article/details/83218126 介紹了一種內存池,它的實現類似于linux 中打開slub_debug (1. make menuconfig: Kenel hacking -> Memory Debugging, 2. comand line中傳入slub_debug=PZU) 時slub 對象池。
首先我們先看一下slub_debug沒有打開時的 slub obj 所占memory layout,預期如下:
為了查看slub obj 內存布局,我寫了一個kernle module, code上傳至github: https://github.com/greenricky/slub_debug 摘抄主要的代碼片段如下:
void print_mem_detail(char *addr, int head_size, int buf_size,int foot_size)
{if(NULL==addr || head_size<0 || buf_size<0 || foot_size<0)return;printk("---Ahead %d bytes---\n", head_size);print_layout(addr-head_size, head_size);printk("---Buf %d bytes---\n", buf_size);print_layout(addr, buf_size);printk("---Footer %d bytes---\n", foot_size);print_layout(addr+buf_size, foot_size);
}static int __init my_test_init(void)
{printk("greenricky: init\n");buf = kmalloc(mem_size, GFP_KERNEL);printk("===============kmalloc=================\n");print_mem_detail(buf, head_size, mem_size, foot_size);memset(buf, 0x57, mem_size); printk("\n===============memset buf to 0x57======\n");print_mem_detail(buf, head_size, mem_size, foot_size);kfree(buf);printk("\n===============free buf====================\n");print_mem_detail(buf, head_size, mem_size, foot_size);return 0;
}
思路如下:
- 申請n個bytes大小的內存,
- 打印剛剛分配出的內存布局;(obj 前head_size個 bytes + obj + obj 后foot_size個 bytes);
- 打印memset obj 后的內存布局;
- 打印free obj 后的內存布局;
在下例中我們實際申請48個bytes的內存,通過查看內核給我們分配是kmalloc-64 obj. 下圖是剛剛kmalloc后的內存布局,還沒有用memset進行賦值。
# insmod slub.ko head_size=64 mem_size=48 foot_size=64
===============kmalloc=================
---Ahead 64 bytes---
ee598300: 05 47 c2 ee 14 ec c0 ee 14 ec c0 ee c4 1d 03 c0
ee598310: 00 00 00 00 70 58 7b c0 00 a0 eb ee 0c a0 eb ee
ee598320: 00 00 00 00 00 00 00 00 00 00 00 00 4c 52 23 c0
ee598330: 00 a0 eb ee 00 00 00 00 00 00 00 00 00 00 00 00
---Buf 48 bytes---
ee598340: 80 83 59 ee 65 73 74 5f 69 6e 69 74 20 5b 73 6c
ee598350: 75 62 5d 00 00 00 00 00 00 00 00 00 00 00 00 00
ee598360: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
---Footer 64 bytes---
ee598370: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
ee598380: c0 83 59 ee 00 00 00 00 00 00 00 00 00 00 00 00
ee598390: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
ee5983a0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
通過上述打印出來的內存布局來看,我們申請的內存起始地址0xee598340, 結束地址是0xee59837f, 長度為64bytes.
請關注一點,內存區域起始地址的前4個bytes是FP- free pointer, 也就是指向下一個可用object 地址,這里是0xee598380, 而0xee598380正好是我們申請到的內存區域的結束地址的后一個byte。我們繼續觀察0xee598380 開始這段內存,起始的4個bytes是0xee5983c0, 也就是下一個可用object的地址。
為了更好的理解上述內存布局,截圖注釋如下:
本例中object size為48 bytes (前4個bytes存儲的是FP), obj align 長度為16bytes。
本章介紹的是slub_debug 關閉情況下的內存布局,下一章我們介紹slub_debug 打開情況下的內存布局,好戲才剛剛開始。
總結
以上是生活随笔為你收集整理的slub object 内存布局的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 为什么深圳的理发店剪一次这么贵?
- 下一篇: 3GPP组织和协议概述