Profile

youngsouk

youngsouk

__libc_malloc함수 분석

mstate ar_ptr;
void *victim;

필요한 변수를 선언한다.

void *(*hook) (size_t, const void *)
    = atomic_forced_read (__malloc_hook);
  if (__builtin_expect (hook != NULL, 0))
    return (*hook)(bytes, RETURN_ADDRESS (0));

calloc때와 마찬가지로 더 공부한 뒤에 따로 설명하겠습니다, ㅠ.ㅠ

#if USE_TCACHE
  /* int_free also calls request2size, be careful to not pad twice.  */
  size_t tbytes;
  checked_request2size (bytes, tbytes);
  size_t tc_idx = csize2tidx (tbytes);

  MAYBE_INIT_TCACHE ();

  DIAG_PUSH_NEEDS_COMMENT;
  if (tc_idx < mp_.tcache_bins
      /*&& tc_idx < TCACHE_MAX_BINS*/ /* to appease gcc */
      && tcache
      && tcache->entries[tc_idx] != NULL)
    {
      return tcache_get (tc_idx);
    }
  DIAG_POP_NEEDS_COMMENT;
#endif

tcache를 사용하고, tcache에 청크가 남아있다면 tcache로부터 그 청크를 얻어온다.

 

tcache에 대한 자세한 것은 여길 참고해주세요

2019/08/08 - [힙(heap)] - tcache 분석

 

tcache 분석

/* We overlay this structure on the user-data portion of a chunk when the chunk is stored in the per-thread cache. */ typedef struct tcache_entry { struct tcache_entry *next; } tcache_entry; tcache_..

youngsouk-hack.tistory.com

  if (SINGLE_THREAD_P)
    {
      victim = _int_malloc (&main_arena, bytes);
      assert (!victim || chunk_is_mmapped (mem2chunk (victim)) ||
	      &main_arena == arena_for_chunk (mem2chunk (victim)));
      return victim;
    }

싱글 스레드면 __int_malloc을 실행하여 메모리를 할당해준다.

그리고 할당받은 주소, mmap으로 할당되었는지, 아레나는 정확한지 등의 보안 검사를 거친 후 반환해준다.

  arena_get (ar_ptr, bytes);

  victim = _int_malloc (ar_ptr, bytes);
  /* Retry with another arena only if we were able to find a usable arena
     before.  */
  if (!victim && ar_ptr != NULL)
    {
      LIBC_PROBE (memory_malloc_retry, 1, bytes);
      ar_ptr = arena_get_retry (ar_ptr, bytes);
      victim = _int_malloc (ar_ptr, bytes);
    }

  if (ar_ptr != NULL)
    __libc_lock_unlock (ar_ptr->mutex);
    assert (!victim || chunk_is_mmapped (mem2chunk (victim)) ||
          ar_ptr == arena_for_chunk (mem2chunk (victim)));
  return victim;
}

맞는 아레나를 얻어온다.

메모리를 할당한다.

잘못얻어왔으면 다시 시도

잘되었으면 잠금을 풀어준다.

위에서 봤던 보안검사를 하고 반환해준다.

'힙(heap) > glibc' 카테고리의 다른 글

_int_malloc 함수 분석 (1)  (0) 2019.08.09
__libc_free함수 분석  (0) 2019.08.09
__builtin_expect, likely, unlikely  (0) 2019.08.09
__libc_calloc 함수 분석  (0) 2019.08.09
tcache 분석  (0) 2019.08.08