본문 바로가기

Heap analysis/glibc 2.26

(glibc 2.26) tcache_init

전체 코드는 아래와 같다

더보기
static void
tcache_init(void)
{
  mstate ar_ptr;
  void *victim = 0;
  const size_t bytes = sizeof (tcache_perthread_struct);

  if (tcache_shutting_down)
    return;

  arena_get (ar_ptr, bytes);
  victim = _int_malloc (ar_ptr, bytes);
  if (!victim && ar_ptr != NULL)
    {
      ar_ptr = arena_get_retry (ar_ptr, bytes);
      victim = _int_malloc (ar_ptr, bytes);
    }


  if (ar_ptr != NULL)
    __libc_lock_unlock (ar_ptr->mutex);

  /* In a low memory situation, we may not be able to allocate memory
     - in which case, we just keep trying later.  However, we
     typically do this very early, so either there is sufficient
     memory, or there isn't enough memory to do non-trivial
     allocations anyway.  */
  if (victim)
    {
      tcache = (tcache_perthread_struct *) victim;
      memset (tcache, 0, sizeof (tcache_perthread_struct));
    }

}

 

개지랄을하는 코드이다 

 

1. 변수 선언


  mstate ar_ptr;
  void *victim = 0;
  const size_t bytes = sizeof (tcache_perthread_struct);
  • ar_ptr : 아레나 주소 저장
  • victim : tcache_perthread_struct가 할당된 힙 주소 저장
  • bytes : tcache_perthread_struct의 size 값 저장

 

2. 검사 및 할당


  if (tcache_shutting_down)
    return;

  arena_get (ar_ptr, bytes);
  victim = _int_malloc (ar_ptr, bytes);
  if (!victim && ar_ptr != NULL)
    {
      ar_ptr = arena_get_retry (ar_ptr, bytes);
      victim = _int_malloc (ar_ptr, bytes);
    }


  if (ar_ptr != NULL)
    __libc_lock_unlock (ar_ptr->mutex);

malloc에서 청크를 할당 받기 위한 과정을 동일하게 수행한다 (여기서는 tcache_perthread_struct를 할당)

또한 malloc과 동일하게 실패하면 한번 더 시도한 뒤 mutex를 unlock한다

 

 

 

3. tcache에 할당 받은 주소 저장


  /* In a low memory situation, we may not be able to allocate memory
     - in which case, we just keep trying later.  However, we
     typically do this very early, so either there is sufficient
     memory, or there isn't enough memory to do non-trivial
     allocations anyway.  */
  if (victim)
    {
      tcache = (tcache_perthread_struct *) victim;
      memset (tcache, 0, sizeof (tcache_perthread_struct));
    }

tcache에 할당 받은 tcache_perthread_struct 크기의 주소(청크)를 저장한다

 

'Heap analysis > glibc 2.26' 카테고리의 다른 글

(glibc 2.26) _int_free  (0) 2022.05.02
(glibc 2.26) _int_malloc  (0) 2022.05.01
(glibc 2.26) tcache_put  (0) 2022.05.01
(glibc 2.26) tcache_get  (0) 2022.05.01
(glibc 2.26) malloc  (0) 2022.05.01