ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 0x02.Arena and Chunk
    0x.Heap Tutorial 2018. 3. 7. 17:34

    0x02. Arena and Chunk


    이번에는 아레나와 청크를 다뤄보겠다.

    Arena

    아레나는 malloc()에서 메모리 관리 부분을 포함한 영역을 뜻한다. MMAPPED 부분은 아레나에 포함이 되지 않는다.

    malloc.c의 struct malloc_state 구조체를 살펴보자면 아래와 같은데,

    struct malloc_state
    {
     /* Serialize access. */
     mutex_t mutex;

     /* Flags (formerly in max_fast). */
     int flags;

     /* Fastbins */
     mfastbinptr fastbinsY[NFASTBINS];

     /* Base of the topmost chunk -- not otherwise kept in a bin */
     mchunkptr top;

     /* The remainder from the most recent split of a small request */
     mchunkptr last_remainder;

     /* Normal bins packed as described above */
     mchunkptr bins[NBINS * 2 - 2];

     /* Bitmap of bins */
     unsigned int binmap[BINMAPSIZE];

     /* Linked list */
     struct malloc_state *next;

     /* Linked list for free arenas. Access to this field is serialized
        by free_list_lock in arena.c. */
     struct malloc_state *next_free;

     /* Number of threads attached to this arena. 0 if the arena is on
        the free list. Access to this field is serialized by
        free_list_lock in arena.c. */
     INTERNAL_SIZE_T attached_threads;

     /* Memory allocated from the system in this arena. */
     INTERNAL_SIZE_T system_mem;
     INTERNAL_SIZE_T max_system_mem;
    };

    이 구조체를 통해 Arena의 세부 정보들이 저장된다. 위의 구조체를 이용하여 청크들을 관리할 수 있는 것이다.

    main_arena는 struct_malloc state 구조체를 사용하는데 정의는 다음과 같다.

    static struct malloc_state main_arena =
    {
    .mutex = _LIBC_LOCK_INITIALIZER,
    .next = &main_arena,
    .attached_threads = 1
    };

    리눅스에서 arena에 대한 정보를 예제로 가져와보자면 아래와 같다.




    참고로 FastbinsY는 fastbin을 관리하고, bins는 그 외의 smallbin, largebin을 관리한다.

    Chunk

    기본적으로 청크는 할당된 청크, 할당해제된 청크, 탑 청크, 마지막으로 남은 청크로 나누어진다. 할당된 청크와 해제된 청크에 대한 설명은 가장 첫 포스팅인 ptmalloc2 부분에 있기 때문에 생략하고 Top chunk와 Last Remainder chunk 부분만 적기로 한다.

    Top Chunk는 아래나의 가장 앞부분에 위치한 청크를 뜻하는데, 그 어느 bin에도 속하지 않는다. 이 청크는 PREV_INUSE가 설정되어 있으며, 그 어떤 bin에도 할당할 만한 공간이 없을 경우에 할당을 해주는 청크이다. 청크의 할당 방법은 2가지로 나뉘는데 요청하는 청크의 크기가 Top chunk보다 클 경우와 작을 경우로 나뉜다.

    만약 Top Chunk보다 요구하는 크기가 작은 경우, 사용자가 요청하는 만큼만 Top Chunk에서 할당을 하고 나머지 부분을 남겨둔다(Remainder Chunk). 그리고 이 나머지 부분이 새로운 Top Chunk가 된다.

    반대로 사용자가 요청하는 청크의 크기가 Top Chunk를 초과하는 경우, sbrk(main arena) 또는 mmap(thread arena) syscall을 사용하여 Top Chunk의 크기를 늘린 다음에 할당을 진행한다.


    Last Remainder Chunk는 가장 최근의 할당에서 유저의 요청에 따라 청크의 사이즈만큼 할당한 부분이 아닌 나머지 부분을 일컫는다. 즉 80바이트를 예를 들었을 경우, 64바이트 만큼을 청크로 할당을 한다면 나머지 16바이트가 Last Remainder Chunk가 되는 것이다. 이 놈은 Unsorted bin에 추가가 되서 재 사용되거나 사라질 것이다.

    '0x.Heap Tutorial' 카테고리의 다른 글

    0x05.How2heap - fastbin_dup_into_stack  (0) 2018.03.12
    0x04.How2heap - fastbin_dup  (0) 2018.03.08
    0x03.How2heap - first_fit  (0) 2018.03.08
    0x01.Glibc Bins  (0) 2018.03.06
    0x00. glibc - ptmalloc2  (0) 2018.03.05

    댓글

Designed by Tistory.