今天自己直接進入帶debug symbol的程序進行分析所以會有截圖emem
1.編譯一個帶有debug symbol的執行檔
在gcc命令中代入-g即可,然後使用gdb調試既可以看到,記得還要在載入symbol文件就可以了主要是爲了學習一些在堆塊上的分配限制規則
2.進入libc
這裏先給出我寫的測試源碼很簡單師傅們可以忽略
#include<stdio.h>
int main()
{
void *chunk1,*chunk2,*chunk3;
chunk1=malloc(20);
chunk2=malloc(30);
free(chunk1);
return 0;
}
首先我們到malloc的地方顯示進入__libc_malloc(byte)
將__malloc_hook放入hook然後判斷__malloc_hook是否爲空不是空則調用返回是空的話就會到主分配區main_arena去尋找大小符合內存
初始時一般都爲空然後就是昨天所說的關於分配哦內存與鎖的操作的最後分配成功會返回指針指向memery
在給上結構源碼
_int_malloc (mstate av, size_t bytes) { │
INTERNAL_SIZE_T nb; /* normalized request size */
unsigned int idx; /* associated bin index */
mbinptr bin; /* associated bin */ mchunkptr victim; /* inspected/selected chunk */ INTERNAL_SIZE_T size; /* its size */ int victim_index; /* its bin index */ mchunkptr remainder; /* remainder from a split */ unsigned long remainder_size; /* its size */
unsigned int block; /* bit map traverser */ unsigned int bit; /* bit map traverser */
unsigned int map; /* current word of binmap */
mchunkptr fwd; /* misc temp for linking */
mchunkptr bck; /* misc temp for linking */
checked_request2size (bytes, nb);這個函數用來計算分配實際的大小通常會比使用者所分配的要大分配時會對齊
if ((unsigned long)(nb) <= (unsigned long)(get_max_fast ()))
{ idx = fastbin_index(nb);
mfastbinptr* fb = &fastbin (av, idx);
#ifdef ATOMIC_FASTBINS
mchunkptr pp = *fb;
do
{
victim = pp;
if (victim == NULL)
break; }
85
while ((pp = catomic_compare_and_exchange_val_acq (fb, victim->fd, victim)) != victim);
#else victim = *fb;
#endif if (victim != 0)
{ if (__builtin_expect (fastbin_index (chunksize (victim)) != idx, 0))
{
errstr = "malloc(): memory corruption (fast)";
errout:
malloc_printerr (check_action, errstr, chunk2mem (victim));
return NULL;
} #ifndef ATOMIC_FASTBINS
*fb = victim->fd; #endif
check_remalloced_chunk(av, victim, nb);
void *p = chunk2mem(victim);
if (__builtin_expect (perturb_byte, 0))
alloc_perturb (p, bytes); return p;
} }
這裏是判斷size符合哪一種bin的大小好像全部檢查了一遍
首先是fastbin的檢查如果沒有開啓優化的話就很簡單首先就會根據大小獲得所屬fastbin的index根據index獲得所需空閒鏈表的頭指針然後將頭指針main_arena中的一塊作爲洗衣歌chunk的頭部fastbin大小的chunk的insues位爲一也就是不會發生unlink操作不會與chunk合併(正常情況下)
在這裏我們發現fastbin似乎沒有對trunk的size對齊做處理只是檢查了是否存在size與是否屬於fastbin index我們可以通過僞造size字段造成
got hackjk和覆寫malloc_hook寫到棧上完成棧溢出等一些列地址寫的操作
師傅們可能寫的有點不好見諒-------