glue.h raw

   1  #ifndef MALLOC_GLUE_H
   2  #define MALLOC_GLUE_H
   3  
   4  #include <stdint.h>
   5  #include <sys/mman.h>
   6  #include <pthread.h>
   7  #include <unistd.h>
   8  #include <elf.h>
   9  #include <string.h>
  10  #include "atomic.h"
  11  #include "syscall.h"
  12  #include "libc.h"
  13  #include "lock.h"
  14  #include "dynlink.h"
  15  
  16  // use macros to appropriately namespace these.
  17  #define size_classes __malloc_size_classes
  18  #define ctx __malloc_context
  19  #define alloc_meta __malloc_alloc_meta
  20  #define is_allzero __malloc_allzerop
  21  #define dump_heap __dump_heap
  22  
  23  #define malloc __libc_malloc_impl
  24  #define realloc __libc_realloc
  25  #define free __libc_free
  26  
  27  #if USE_REAL_ASSERT
  28  #include <assert.h>
  29  #else
  30  #undef assert
  31  #define assert(x) do { if (!(x)) a_crash(); } while(0)
  32  #endif
  33  
  34  #define brk(p) ((uintptr_t)__syscall(SYS_brk, p))
  35  
  36  #define mmap __mmap
  37  #define madvise __madvise
  38  #define mremap __mremap
  39  
  40  #define DISABLE_ALIGNED_ALLOC (__malloc_replaced && !__aligned_alloc_replaced)
  41  
  42  static inline uint64_t get_random_secret()
  43  {
  44  	uint64_t secret = (uintptr_t)&secret * 1103515245;
  45  	for (size_t i=0; libc.auxv[i]; i+=2)
  46  		if (libc.auxv[i]==AT_RANDOM)
  47  			memcpy(&secret, (char *)libc.auxv[i+1]+8, sizeof secret);
  48  	return secret;
  49  }
  50  
  51  #ifndef PAGESIZE
  52  #define PAGESIZE PAGE_SIZE
  53  #endif
  54  
  55  #define MT (libc.need_locks)
  56  
  57  #define RDLOCK_IS_EXCLUSIVE 1
  58  
  59  __attribute__((__visibility__("hidden")))
  60  extern int __malloc_lock[1];
  61  
  62  #define LOCK_OBJ_DEF \
  63  int __malloc_lock[1]; \
  64  void __malloc_atfork(int who) { malloc_atfork(who); }
  65  
  66  static inline void rdlock()
  67  {
  68  	if (MT) LOCK(__malloc_lock);
  69  }
  70  static inline void wrlock()
  71  {
  72  	if (MT) LOCK(__malloc_lock);
  73  }
  74  static inline void unlock()
  75  {
  76  	UNLOCK(__malloc_lock);
  77  }
  78  static inline void upgradelock()
  79  {
  80  }
  81  static inline void resetlock()
  82  {
  83  	__malloc_lock[0] = 0;
  84  }
  85  
  86  static inline void malloc_atfork(int who)
  87  {
  88  	if (who<0) rdlock();
  89  	else if (who>0) resetlock();
  90  	else unlock();
  91  }
  92  
  93  #endif
  94