Make Malloc.h self-contained again
[folly.git] / folly / Malloc.h
1 /*
2  * Copyright 2016 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 // Functions to provide smarter use of jemalloc, if jemalloc is being used.
18 // http://www.canonware.com/download/jemalloc/jemalloc-latest/doc/jemalloc.html
19
20 #pragma once
21 #define FOLLY_MALLOC_H_
22
23 /**
24  * Define various MALLOCX_* macros normally provided by jemalloc.  We define
25  * them so that we don't have to include jemalloc.h, in case the program is
26  * built without jemalloc support.
27  */
28 #ifndef MALLOCX_LG_ALIGN
29 #define MALLOCX_LG_ALIGN(la) (la)
30 #endif
31 #ifndef MALLOCX_ZERO
32 #define MALLOCX_ZERO (static_cast<int>(0x40))
33 #endif
34
35 // If using fbstring from libstdc++ (see comment in FBString.h), then
36 // just define stub code here to typedef the fbstring type into the
37 // folly namespace.
38 // This provides backwards compatibility for code that explicitly
39 // includes and uses fbstring.
40 #if defined(_GLIBCXX_USE_FB) && !defined(_LIBSTDCXX_FBSTRING)
41
42 #include <folly/detail/Malloc.h>
43 #include <folly/portability/BitsFunctexcept.h>
44
45 #include <string>
46
47 namespace folly {
48   using std::goodMallocSize;
49   using std::jemallocMinInPlaceExpandable;
50   using std::usingJEMalloc;
51   using std::smartRealloc;
52   using std::checkedMalloc;
53   using std::checkedCalloc;
54   using std::checkedRealloc;
55 }
56
57 #else // !defined(_GLIBCXX_USE_FB) || defined(_LIBSTDCXX_FBSTRING)
58
59 #ifdef _LIBSTDCXX_FBSTRING
60 #pragma GCC system_header
61
62 /**
63  * Declare *allocx() and mallctl*() as weak symbols. These will be provided by
64  * jemalloc if we are using jemalloc, or will be NULL if we are using another
65  * malloc implementation.
66  */
67 extern "C" void* mallocx(size_t, int)
68 __attribute__((__weak__));
69 extern "C" void* rallocx(void*, size_t, int)
70 __attribute__((__weak__));
71 extern "C" size_t xallocx(void*, size_t, size_t, int)
72 __attribute__((__weak__));
73 extern "C" size_t sallocx(const void*, int)
74 __attribute__((__weak__));
75 extern "C" void dallocx(void*, int)
76 __attribute__((__weak__));
77 extern "C" void sdallocx(void*, size_t, int)
78 __attribute__((__weak__));
79 extern "C" size_t nallocx(size_t, int)
80 __attribute__((__weak__));
81 extern "C" int mallctl(const char*, void*, size_t*, void*, size_t)
82 __attribute__((__weak__));
83 extern "C" int mallctlnametomib(const char*, size_t*, size_t*)
84 __attribute__((__weak__));
85 extern "C" int mallctlbymib(const size_t*, size_t, void*, size_t*, void*,
86                             size_t)
87 __attribute__((__weak__));
88
89 #include <bits/functexcept.h>
90
91 #define FOLLY_HAVE_MALLOC_H 1
92
93 #else // !defined(_LIBSTDCXX_FBSTRING)
94
95 #include <folly/detail/Malloc.h> /* nolint */
96 #include <folly/portability/BitsFunctexcept.h> /* nolint */
97
98 #endif
99
100 // for malloc_usable_size
101 // NOTE: FreeBSD 9 doesn't have malloc.h.  Its definitions
102 // are found in stdlib.h.
103 #if FOLLY_HAVE_MALLOC_H
104 #include <malloc.h>
105 #else
106 #include <stdlib.h>
107 #endif
108
109 #include <cassert>
110 #include <cstddef>
111 #include <cstdint>
112 #include <cstdlib>
113 #include <cstring>
114
115 #include <new>
116
117 #ifdef _LIBSTDCXX_FBSTRING
118 namespace std _GLIBCXX_VISIBILITY(default) {
119 _GLIBCXX_BEGIN_NAMESPACE_VERSION
120 #else
121 namespace folly {
122 #endif
123
124 // Cannot depend on Portability.h when _LIBSTDCXX_FBSTRING.
125 // Disabled for nvcc because it fails on attributes on lambdas.
126 #if defined(__GNUC__) && !defined(__NVCC__)
127 #define FOLLY_MALLOC_NOINLINE __attribute__((__noinline__))
128 #else
129 #define FOLLY_MALLOC_NOINLINE
130 #endif
131
132 /**
133  * Determine if we are using jemalloc or not.
134  */
135 inline bool usingJEMalloc() noexcept {
136   // Checking for rallocx != NULL is not sufficient; we may be in a dlopen()ed
137   // module that depends on libjemalloc, so rallocx is resolved, but the main
138   // program might be using a different memory allocator.
139   // How do we determine that we're using jemalloc? In the hackiest
140   // way possible. We allocate memory using malloc() and see if the
141   // per-thread counter of allocated memory increases. This makes me
142   // feel dirty inside. Also note that this requires jemalloc to have
143   // been compiled with --enable-stats.
144   static const bool result = [] () FOLLY_MALLOC_NOINLINE noexcept {
145     // Some platforms (*cough* OSX *cough*) require weak symbol checks to be
146     // in the form if (mallctl != nullptr). Not if (mallctl) or if (!mallctl)
147     // (!!). http://goo.gl/xpmctm
148     if (mallocx == nullptr || rallocx == nullptr || xallocx == nullptr
149         || sallocx == nullptr || dallocx == nullptr || sdallocx == nullptr
150         || nallocx == nullptr || mallctl == nullptr
151         || mallctlnametomib == nullptr || mallctlbymib == nullptr) {
152       return false;
153     }
154
155     // "volatile" because gcc optimizes out the reads from *counter, because
156     // it "knows" malloc doesn't modify global state...
157     /* nolint */ volatile uint64_t* counter;
158     size_t counterLen = sizeof(uint64_t*);
159
160     if (mallctl("thread.allocatedp", static_cast<void*>(&counter), &counterLen,
161                 nullptr, 0) != 0) {
162       return false;
163     }
164
165     if (counterLen != sizeof(uint64_t*)) {
166       return false;
167     }
168
169     uint64_t origAllocated = *counter;
170
171     // Static because otherwise clever compilers will find out that
172     // the ptr is not used and does not escape the scope, so they will
173     // just optimize away the malloc.
174     static void* ptr = malloc(1);
175     if (!ptr) {
176       // wtf, failing to allocate 1 byte
177       return false;
178     }
179
180     return (origAllocated != *counter);
181   }();
182
183   return result;
184 }
185
186 inline size_t goodMallocSize(size_t minSize) noexcept {
187   if (minSize == 0) {
188     return 0;
189   }
190
191   if (!usingJEMalloc()) {
192     // Not using jemalloc - no smarts
193     return minSize;
194   }
195
196   return nallocx(minSize, 0);
197 }
198
199 // We always request "good" sizes for allocation, so jemalloc can
200 // never grow in place small blocks; they're already occupied to the
201 // brim.  Blocks larger than or equal to 4096 bytes can in fact be
202 // expanded in place, and this constant reflects that.
203 static const size_t jemallocMinInPlaceExpandable = 4096;
204
205 /**
206  * Trivial wrappers around malloc, calloc, realloc that check for allocation
207  * failure and throw std::bad_alloc in that case.
208  */
209 inline void* checkedMalloc(size_t size) {
210   void* p = malloc(size);
211   if (!p) std::__throw_bad_alloc();
212   return p;
213 }
214
215 inline void* checkedCalloc(size_t n, size_t size) {
216   void* p = calloc(n, size);
217   if (!p) std::__throw_bad_alloc();
218   return p;
219 }
220
221 inline void* checkedRealloc(void* ptr, size_t size) {
222   void* p = realloc(ptr, size);
223   if (!p) std::__throw_bad_alloc();
224   return p;
225 }
226
227 /**
228  * This function tries to reallocate a buffer of which only the first
229  * currentSize bytes are used. The problem with using realloc is that
230  * if currentSize is relatively small _and_ if realloc decides it
231  * needs to move the memory chunk to a new buffer, then realloc ends
232  * up copying data that is not used. It's impossible to hook into
233  * GNU's malloc to figure whether expansion will occur in-place or as
234  * a malloc-copy-free troika. (If an expand_in_place primitive would
235  * be available, smartRealloc would use it.) As things stand, this
236  * routine just tries to call realloc() (thus benefitting of potential
237  * copy-free coalescing) unless there's too much slack memory.
238  */
239 inline void* smartRealloc(void* p,
240                           const size_t currentSize,
241                           const size_t currentCapacity,
242                           const size_t newCapacity) {
243   assert(p);
244   assert(currentSize <= currentCapacity &&
245          currentCapacity < newCapacity);
246
247   if (usingJEMalloc()) {
248     // using jemalloc's API. Don't forget that jemalloc can never grow
249     // in place blocks smaller than 4096 bytes.
250     //
251     // NB: newCapacity may not be precisely equal to a jemalloc size class,
252     // i.e. newCapacity is not guaranteed to be the result of a
253     // goodMallocSize() call, therefore xallocx() may return more than
254     // newCapacity bytes of space.  Use >= rather than == to check whether
255     // xallocx() successfully expanded in place.
256     if (currentCapacity >= jemallocMinInPlaceExpandable &&
257         xallocx(p, newCapacity, 0, 0) >= newCapacity) {
258       // Managed to expand in place
259       return p;
260     }
261     // Cannot expand; must move
262     auto const result = checkedMalloc(newCapacity);
263     std::memcpy(result, p, currentSize);
264     free(p);
265     return result;
266   }
267
268   // No jemalloc no honey
269   auto const slack = currentCapacity - currentSize;
270   if (slack * 2 > currentSize) {
271     // Too much slack, malloc-copy-free cycle:
272     auto const result = checkedMalloc(newCapacity);
273     std::memcpy(result, p, currentSize);
274     free(p);
275     return result;
276   }
277   // If there's not too much slack, we realloc in hope of coalescing
278   return checkedRealloc(p, newCapacity);
279 }
280
281 #ifdef _LIBSTDCXX_FBSTRING
282 _GLIBCXX_END_NAMESPACE_VERSION
283 #endif
284
285 } // folly
286
287 #endif // !defined(_GLIBCXX_USE_FB) || defined(_LIBSTDCXX_FBSTRING)