summaryrefslogtreecommitdiff
path: root/klm/util/scoped.cc
blob: de1d9e9401d432c8ff639d1e21137a011e4c0d29 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include "util/scoped.hh"

#include <cstdlib>
#if !defined(_WIN32) && !defined(_WIN64)
#include <sys/mman.h>
#endif

namespace util {

MallocException::MallocException(std::size_t requested) throw() {
  *this << "for " << requested << " bytes ";
}

MallocException::~MallocException() throw() {}

namespace {
void *InspectAddr(void *addr, std::size_t requested, const char *func_name) {
  UTIL_THROW_IF_ARG(!addr && requested, MallocException, (requested), "in " << func_name);
  // These routines are often used for large chunks of memory where huge pages help.
#if MADV_HUGEPAGE
  madvise(addr, requested, MADV_HUGEPAGE);
#endif
  return addr;
}
} // namespace

void *MallocOrThrow(std::size_t requested) {
  return InspectAddr(std::malloc(requested), requested, "malloc");
}

void *CallocOrThrow(std::size_t requested) {
  return InspectAddr(std::calloc(1, requested), requested, "calloc");
}

void scoped_malloc::call_realloc(std::size_t requested) {
  p_ = InspectAddr(std::realloc(p_, requested), requested, "realloc");
}

} // namespace util