Daily Heap #5

juuun0·2022년 1월 27일
1

Heap-A-to-Z

목록 보기
5/10
post-thumbnail

malloc_state

malloc_state 구조체는 Heap의 구성 요소 중 "Arena" 가 정의되어 있는 구조체입니다. Main Arena의 경우 malloc_state 구조체를 main_arena 라는 이름의 전역 변수로 선언합니다.

아래는 glibc 2.23 기준 malloc_state의 선언부입니다.

struct malloc_state
{
  /* Serialize access.  */
  __libc_lock_define (, 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;
};

typedef struct malloc_state *mstate;

위에서 선언된 malloc_state 구조체를 사용하여 아래와 같이 main_arena의 선언을 진행합니다.

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

모든 항목에 대하여 정의를 진행하진 않고 필수 요소에 대해서만 정의된 것을 확인할 수 있습니다. 아래는 실제 프로그램 상에서 main_arena의 상태를 확인한 결과입니다.

gef➤  p &main_arena
$3 = (struct malloc_state *) 0x7f77938e9b20 <main_arena>
gef➤  p *(struct malloc_state *) 0x7f77938e9b20
$4 = {
  mutex = 0x0, 
  flags = 0x0, 
  fastbinsY = {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, 
  top = 0x0, 
  last_remainder = 0x0, 
  bins = {0x0 <repeats 254 times>}, 
  binmap = {0x0, 0x0, 0x0, 0x0}, 
  next = 0x7f77938e9b20 <main_arena>, 
  next_free = 0x0, 
  attached_threads = 0x1, 
  system_mem = 0x0, 
  max_system_mem = 0x0
}

실행 이후 추가적인 동작을 진행하지 않았기에 malloc.c 에서 정의된 이외에는 0x0의 값으로 초기화 되어있는 점을 확인할 수 있습니다.

profile
To be

0개의 댓글