1.1. mheap
1.1.1. mheap_t
- first_free_elt_uoffset_by_bin: User offsets for head of doubly-linked list of free objects of this size.
- non_empty_free_elt_heads: Bitmap of non-empty free list bins.
- n_elts: Number of allocated objects.
- max_size: Maximum size (in bytes) this heap is allowed to grow to.
1.1.2. mheap_elt_t
- prev_n_user_data: Number of mheap_size_t words of user data in previous object. Used to find mheap_elt_t for previous object.
- prev_is_free: Set if previous object is free.
- n_user_data: Number of mheap_size_t words of user data that follow this object.
- is_free: Set if this object is on free list (and therefore following free_elt is valid).
-
user_data: For allocated objects: user data follows.
User data is allocated in units of typeof (user_data[0]).
-
free_elt: For free objects, offsets of next and previous free objects of this size;
~0 means end of doubly-linked list.
This is stored in user data (guaranteed to be at least 8 bytes) but only for free objects.
1.1.3. mheap_alloc函數過程
從虛拟記憶體空間映射一塊size大的記憶體(am = 0x7ffff3a0ff54)
mmap_addr = mmap(0, size, PROT_READ | PROT_WRITE, flags, -1, 0);
-
将mmap_addr指針和頁大小對其(av = 0x7ffff3a10000)
return (addr + mheap_page_size - 1) & ~(mheap_page_size - 1);
-
從對齊頁的位置往前減去mheap_t的空間(ah = 0x7ffff3a0f860)
ah = vec_aligned_header(v, sizeof (mheap_t), 16);
- 再往後n個page,(ah + page = 0x7ffff3a10860)得到真正的mheap開始的位置【這邊類似于補運算,在申請的空間内跳過page_size - mheap_size 的空間】
-
(ah < am)
ah += mheap_page_size; // 這樣可以保證mheap的其實位置在申請的空間内,且一定對其與page
-
最後計算出vector的偏移
v = mheap_vector (h); // h + sizeof(mheap_t + vec_header_t)
-
vector區域可以存放的資料大小為
size = am + memory_size - v;
1.1.4. 從mheap中申請記憶體
void * mheap_get_aligned(void *v, uword n_user_data_bytes, uword align, uword align_offset, uword * offset_return)
/* Search free lists for object with given size and alignment. */ static uword mheap_get_search_free_list(void *v, uword *n_user_bytes_arg, uword align, uword align_offset)
/* Find bin for objects with size at least n_user_data_bytes. */ always_inline uword user_data_size_to_bin_index(uword n_user_data_bytes)
根據使用者請求object的size and alignment找到合适的bin(small_bin or large_bin),再從bin中找到合适的free elt
這裡所有的操作都是基于數組的形式,elt間的雙向連結清單也是以數組的形式實作的