This source file includes following definitions.
- CheckAddressBits
- ranval
- raninit
- GetRandomAddrHint
- AllocWithMmap
- SetChildAllocator
- InitSystemAllocators
- TCMalloc_SystemAlloc
- TCMalloc_SystemAddGuard
- TCMalloc_SystemRelease
- TCMalloc_SystemCommit
#include <config.h>
#include <errno.h>                      
#include <fcntl.h>                      
#include <stddef.h>                     
#if defined HAVE_STDINT_H
#include <stdint.h>                     
#elif defined HAVE_INTTYPES_H
#include <inttypes.h>
#else
#include <sys/types.h>
#endif
#ifdef HAVE_MMAP
#include <sys/mman.h>                   
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>                     
#endif
#include <new>                          
#include <gperftools/malloc_extension.h>
#include "base/basictypes.h"
#include "base/commandlineflags.h"
#include "base/spinlock.h"              
#include "common.h"
#include "internal_logging.h"
#ifndef MAP_ANONYMOUS
# define MAP_ANONYMOUS MAP_ANON
#endif
#if !defined(MADV_FREE) && defined(MADV_DONTNEED)
# define MADV_FREE  MADV_DONTNEED
#endif
#if defined(__sun) && defined(__SVR4)
# include <sys/types.h>    
  extern "C" { extern int madvise(caddr_t, size_t, int); }
#endif
#ifdef NDEBUG
static const bool kDebugMode = false;
#else
static const bool kDebugMode = true;
#endif
using tcmalloc::kLog;
using tcmalloc::Log;
namespace {
template <int ADDRESS_BITS> bool CheckAddressBits(uintptr_t ptr) {
  return (ptr >> ADDRESS_BITS) == 0;
}
template <> bool CheckAddressBits<8 * sizeof(void*)>(uintptr_t ptr) {
  return true;
}
#if (defined(OS_LINUX) || defined(OS_CHROMEOS)) && defined(__x86_64__)
#define ASLR_IS_SUPPORTED
#endif
#if defined(ASLR_IS_SUPPORTED)
typedef uint32_t u4;
struct ranctx {
  u4 a;
  u4 b;
  u4 c;
  u4 d;
};
#define rot(x,k) (((x)<<(k))|((x)>>(32-(k))))
u4 ranval(ranctx* x) {
  
  u4 e = x->a - rot(x->b, 27);
  x->a = x->b ^ rot(x->c, 17);
  x->b = x->c + x->d;
  x->c = x->d + e;
  x->d = e + x->a;
  return x->d;
}
void raninit(ranctx* x, u4 seed) {
  u4 i;
  x->a = 0xf1ea5eed;
  x->b = x->c = x->d = seed;
  for (i = 0; i < 20; ++i) {
    (void) ranval(x);
  }
}
const uint64_t kRandomAddressMask = 0x3ffffffff000ULL;
#endif  
void* GetRandomAddrHint() {
#if !defined(ASLR_IS_SUPPORTED)
  return NULL;
#else
  
  
  
  
  
  static ranctx ctx;
  static bool initialized = false;
  if (!initialized) {
    initialized = true;
    
    
    
    volatile char c;
    
    
    uint32_t seed = (reinterpret_cast<uint64_t>(&c) >> 32) ^
                    reinterpret_cast<uint64_t>(&c);
    int urandom_fd = open("/dev/urandom", O_RDONLY);
    if (urandom_fd >= 0) {
      ssize_t len;
      len = read(urandom_fd, &seed, sizeof(seed));
      ASSERT(len == sizeof(seed));
      int ret = close(urandom_fd);
      ASSERT(ret == 0);
    }
    raninit(&ctx, seed);
  }
  uint64_t random_address = (static_cast<uint64_t>(ranval(&ctx)) << 32) |
                            ranval(&ctx);
  
  random_address &= kRandomAddressMask;
  return reinterpret_cast<void*>(random_address);
#endif  
}
void* AllocWithMmap(size_t length, bool is_aslr_enabled) {
  
  static void* address_hint = NULL;
#if defined(ASLR_IS_SUPPORTED)
  if (is_aslr_enabled &&
      (!address_hint ||
       reinterpret_cast<uint64_t>(address_hint) & ~kRandomAddressMask)) {
    address_hint = GetRandomAddrHint();
  }
#endif  
  
  void* result = mmap(address_hint, length, PROT_READ|PROT_WRITE,
                      MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
#if defined(ASLR_IS_SUPPORTED)
  if (result == address_hint) {
    
    
    
    
    
    
    
    address_hint = static_cast<char*>(result) + length;
  } else {
    
    
    address_hint = NULL;
  }
#endif  
  return result;
}
}  
COMPILE_ASSERT(kAddressBits <= 8 * sizeof(void*),
               address_bits_larger_than_pointer_size);
union MemoryAligner {
  void*  p;
  double d;
  size_t s;
} CACHELINE_ALIGNED;
static SpinLock spinlock(SpinLock::LINKER_INITIALIZED);
#if defined(HAVE_MMAP) || defined(MADV_FREE)
#ifdef HAVE_GETPAGESIZE
static size_t pagesize = 0;
#endif
#endif
SysAllocator* sys_alloc = NULL;
DEFINE_int32(malloc_devmem_start,
             EnvToInt("TCMALLOC_DEVMEM_START", 0),
             "Physical memory starting location in MB for /dev/mem allocation."
             "  Setting this to 0 disables /dev/mem allocation");
DEFINE_int32(malloc_devmem_limit,
             EnvToInt("TCMALLOC_DEVMEM_LIMIT", 0),
             "Physical memory limit location in MB for /dev/mem allocation."
             "  Setting this to 0 means no limit.");
DEFINE_bool(malloc_skip_sbrk,
            EnvToBool("TCMALLOC_SKIP_SBRK", false),
            "Whether sbrk can be used to obtain memory.");
DEFINE_bool(malloc_skip_mmap,
            EnvToBool("TCMALLOC_SKIP_MMAP", false),
            "Whether mmap can be used to obtain memory.");
DEFINE_bool(malloc_random_allocator,
#if defined(ASLR_IS_SUPPORTED)
            EnvToBool("TCMALLOC_ASLR", true),
#else
            EnvToBool("TCMALLOC_ASLR", false),
#endif
            "Whether to randomize the address space via mmap().");
class SbrkSysAllocator : public SysAllocator {
public:
  SbrkSysAllocator() : SysAllocator() {
  }
  void* Alloc(size_t size, size_t *actual_size, size_t alignment);
};
static char sbrk_space[sizeof(SbrkSysAllocator)];
class MmapSysAllocator : public SysAllocator {
public:
  MmapSysAllocator() : SysAllocator() {
  }
  void* Alloc(size_t size, size_t *actual_size, size_t alignment);
};
static char mmap_space[sizeof(MmapSysAllocator)];
class DevMemSysAllocator : public SysAllocator {
public:
  DevMemSysAllocator() : SysAllocator() {
  }
  void* Alloc(size_t size, size_t *actual_size, size_t alignment);
};
class DefaultSysAllocator : public SysAllocator {
 public:
  DefaultSysAllocator() : SysAllocator() {
    for (int i = 0; i < kMaxAllocators; i++) {
      failed_[i] = true;
      allocs_[i] = NULL;
      names_[i] = NULL;
    }
  }
  void SetChildAllocator(SysAllocator* alloc, unsigned int index,
                         const char* name) {
    if (index < kMaxAllocators && alloc != NULL) {
      allocs_[index] = alloc;
      failed_[index] = false;
      names_[index] = name;
    }
  }
  void* Alloc(size_t size, size_t *actual_size, size_t alignment);
 private:
  static const int kMaxAllocators = 2;
  bool failed_[kMaxAllocators];
  SysAllocator* allocs_[kMaxAllocators];
  const char* names_[kMaxAllocators];
};
static char default_space[sizeof(DefaultSysAllocator)];
static const char sbrk_name[] = "SbrkSysAllocator";
static const char mmap_name[] = "MmapSysAllocator";
void* SbrkSysAllocator::Alloc(size_t size, size_t *actual_size,
                              size_t alignment) {
#ifndef HAVE_SBRK
  return NULL;
#else
  
  
  
  
  
  
  if (FLAGS_malloc_skip_sbrk) {
    return NULL;
  }
  
  
  if (static_cast<ptrdiff_t>(size + alignment) < 0) return NULL;
  
  
  size = ((size + alignment - 1) / alignment) * alignment;
  
  
  if (actual_size) {
    *actual_size = size;
  }
  
  
  
  
  
  
  
  if (reinterpret_cast<intptr_t>(sbrk(0)) + size < size) {
    return NULL;
  }
  void* result = sbrk(size);
  if (result == reinterpret_cast<void*>(-1)) {
    return NULL;
  }
  
  uintptr_t ptr = reinterpret_cast<uintptr_t>(result);
  if ((ptr & (alignment-1)) == 0)  return result;
  
  size_t extra = alignment - (ptr & (alignment-1));
  void* r2 = sbrk(extra);
  if (reinterpret_cast<uintptr_t>(r2) == (ptr + size)) {
    
    return reinterpret_cast<void*>(ptr + extra);
  }
  
  
  result = sbrk(size + alignment - 1);
  if (result == reinterpret_cast<void*>(-1)) {
    return NULL;
  }
  ptr = reinterpret_cast<uintptr_t>(result);
  if ((ptr & (alignment-1)) != 0) {
    ptr += alignment - (ptr & (alignment-1));
  }
  return reinterpret_cast<void*>(ptr);
#endif  
}
void* MmapSysAllocator::Alloc(size_t size, size_t *actual_size,
                              size_t alignment) {
#ifndef HAVE_MMAP
  return NULL;
#else
  
  
  
  
  
  
  if (FLAGS_malloc_skip_mmap) {
    return NULL;
  }
  
  if (pagesize == 0) pagesize = getpagesize();
  if (alignment < pagesize) alignment = pagesize;
  size_t aligned_size = ((size + alignment - 1) / alignment) * alignment;
  if (aligned_size < size) {
    return NULL;
  }
  size = aligned_size;
  
  
  if (actual_size) {
    *actual_size = size;
  }
  
  size_t extra = 0;
  if (alignment > pagesize) {
    extra = alignment - pagesize;
  }
  
  
  
  
  void* result = AllocWithMmap(size + extra, FLAGS_malloc_random_allocator);
  if (result == reinterpret_cast<void*>(MAP_FAILED)) {
    return NULL;
  }
  
  uintptr_t ptr = reinterpret_cast<uintptr_t>(result);
  size_t adjust = 0;
  if ((ptr & (alignment - 1)) != 0) {
    adjust = alignment - (ptr & (alignment - 1));
  }
  
  if (adjust > 0) {
    munmap(reinterpret_cast<void*>(ptr), adjust);
  }
  if (adjust < extra) {
    munmap(reinterpret_cast<void*>(ptr + adjust + size), extra - adjust);
  }
  ptr += adjust;
  return reinterpret_cast<void*>(ptr);
#endif  
}
void* DevMemSysAllocator::Alloc(size_t size, size_t *actual_size,
                                size_t alignment) {
#ifndef HAVE_MMAP
  return NULL;
#else
  static bool initialized = false;
  static off_t physmem_base;  
  static off_t physmem_limit; 
  static int physmem_fd;      
  
  
  
  
  if (FLAGS_malloc_devmem_start == 0) {
    
    
    return NULL;
  }
  if (!initialized) {
    physmem_fd = open("/dev/mem", O_RDWR);
    if (physmem_fd < 0) {
      return NULL;
    }
    physmem_base = FLAGS_malloc_devmem_start*1024LL*1024LL;
    physmem_limit = FLAGS_malloc_devmem_limit*1024LL*1024LL;
    initialized = true;
  }
  
  if (pagesize == 0) pagesize = getpagesize();
  if (alignment < pagesize) alignment = pagesize;
  size_t aligned_size = ((size + alignment - 1) / alignment) * alignment;
  if (aligned_size < size) {
    return NULL;
  }
  size = aligned_size;
  
  
  if (actual_size) {
    *actual_size = size;
  }
  
  size_t extra = 0;
  if (alignment > pagesize) {
    extra = alignment - pagesize;
  }
  
  if (physmem_limit != 0 &&
      ((size + extra) > (physmem_limit - physmem_base))) {
    return NULL;
  }
  
  
  
  
  void *result = mmap(0, size + extra, PROT_WRITE|PROT_READ,
                      MAP_SHARED, physmem_fd, physmem_base);
  if (result == reinterpret_cast<void*>(MAP_FAILED)) {
    return NULL;
  }
  uintptr_t ptr = reinterpret_cast<uintptr_t>(result);
  
  size_t adjust = 0;
  if ((ptr & (alignment - 1)) != 0) {
    adjust = alignment - (ptr & (alignment - 1));
  }
  
  if (adjust > 0) {
    munmap(reinterpret_cast<void*>(ptr), adjust);
  }
  if (adjust < extra) {
    munmap(reinterpret_cast<void*>(ptr + adjust + size), extra - adjust);
  }
  ptr += adjust;
  physmem_base += adjust + size;
  return reinterpret_cast<void*>(ptr);
#endif  
}
void* DefaultSysAllocator::Alloc(size_t size, size_t *actual_size,
                                 size_t alignment) {
  for (int i = 0; i < kMaxAllocators; i++) {
    if (!failed_[i] && allocs_[i] != NULL) {
      void* result = allocs_[i]->Alloc(size, actual_size, alignment);
      if (result != NULL) {
        return result;
      }
      failed_[i] = true;
    }
  }
  
  
  for (int i = 0; i < kMaxAllocators; i++) {
    failed_[i] = false;
  }
  return NULL;
}
static bool system_alloc_inited = false;
void InitSystemAllocators(void) {
  MmapSysAllocator *mmap = new (mmap_space) MmapSysAllocator();
  SbrkSysAllocator *sbrk = new (sbrk_space) SbrkSysAllocator();
  
  
  
  
  
  
  
  DefaultSysAllocator *sdef = new (default_space) DefaultSysAllocator();
  
  
#if defined(ASLR_IS_SUPPORTED)
  
  sdef->SetChildAllocator(mmap, 0, mmap_name);
#else
  if (kDebugMode && sizeof(void*) > 4) {
    sdef->SetChildAllocator(mmap, 0, mmap_name);
    sdef->SetChildAllocator(sbrk, 1, sbrk_name);
  } else {
    sdef->SetChildAllocator(sbrk, 0, sbrk_name);
    sdef->SetChildAllocator(mmap, 1, mmap_name);
  }
#endif  
  sys_alloc = sdef;
}
void* TCMalloc_SystemAlloc(size_t size, size_t *actual_size,
                           size_t alignment) {
  
  if (size + alignment < size) return NULL;
  SpinLockHolder lock_holder(&spinlock);
  if (!system_alloc_inited) {
    InitSystemAllocators();
    system_alloc_inited = true;
  }
  
  if (alignment < sizeof(MemoryAligner)) alignment = sizeof(MemoryAligner);
  void* result = sys_alloc->Alloc(size, actual_size, alignment);
  if (result != NULL) {
    if (actual_size) {
      CheckAddressBits<kAddressBits>(
          reinterpret_cast<uintptr_t>(result) + *actual_size - 1);
    } else {
      CheckAddressBits<kAddressBits>(
          reinterpret_cast<uintptr_t>(result) + size - 1);
    }
  }
  return result;
}
size_t TCMalloc_SystemAddGuard(void* start, size_t size) {
#ifdef HAVE_GETPAGESIZE
  if (pagesize == 0)
    pagesize = getpagesize();
  if (size < pagesize || (reinterpret_cast<size_t>(start) % pagesize) != 0)
    return 0;
  if (!mprotect(start, pagesize, PROT_NONE))
    return pagesize;
#endif
  return 0;
}
void TCMalloc_SystemRelease(void* start, size_t length) {
#ifdef MADV_FREE
  if (FLAGS_malloc_devmem_start) {
    
    
    return;
  }
  if (pagesize == 0) pagesize = getpagesize();
  const size_t pagemask = pagesize - 1;
  size_t new_start = reinterpret_cast<size_t>(start);
  size_t end = new_start + length;
  size_t new_end = end;
  
  
  new_start = (new_start + pagesize - 1) & ~pagemask;
  new_end = new_end & ~pagemask;
  ASSERT((new_start & pagemask) == 0);
  ASSERT((new_end & pagemask) == 0);
  ASSERT(new_start >= reinterpret_cast<size_t>(start));
  ASSERT(new_end <= end);
  if (new_end > new_start) {
    
    
    while (madvise(reinterpret_cast<char*>(new_start), new_end - new_start,
                   MADV_FREE) == -1 &&
           errno == EAGAIN) {
      
    }
  }
#endif
}
void TCMalloc_SystemCommit(void* start, size_t length) {
  
  
  
}