UnboundedQueue: Use alignas instead of FOLLY_ALIGNED
[folly.git] / folly / memory / Malloc.h
1 /*
2  * Copyright 2017 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
22 #include <folly/CPortability.h>
23 #include <folly/portability/Config.h>
24
25 /**
26  * Define various MALLOCX_* macros normally provided by jemalloc.  We define
27  * them so that we don't have to include jemalloc.h, in case the program is
28  * built without jemalloc support.
29  */
30 #if (defined(USE_JEMALLOC) || defined(FOLLY_USE_JEMALLOC)) && !FOLLY_SANITIZE
31 // We have JEMalloc, so use it.
32 # include <jemalloc/jemalloc.h>
33 #else
34 # ifndef MALLOCX_LG_ALIGN
35 #  define MALLOCX_LG_ALIGN(la) (la)
36 # endif
37 # ifndef MALLOCX_ZERO
38 #  define MALLOCX_ZERO (static_cast<int>(0x40))
39 # endif
40 #endif
41
42 // If using fbstring from libstdc++ (see comment in FBString.h), then
43 // just define stub code here to typedef the fbstring type into the
44 // folly namespace.
45 // This provides backwards compatibility for code that explicitly
46 // includes and uses fbstring.
47 #if defined(_GLIBCXX_USE_FB) && !defined(_LIBSTDCXX_FBSTRING)
48
49 #include <folly/memory/detail/MallocImpl.h>
50 #include <folly/portability/BitsFunctexcept.h>
51
52 #include <string>
53
54 namespace folly {
55   using std::goodMallocSize;
56   using std::jemallocMinInPlaceExpandable;
57   using std::usingJEMalloc;
58   using std::smartRealloc;
59   using std::checkedMalloc;
60   using std::checkedCalloc;
61   using std::checkedRealloc;
62 }
63
64 #else // !defined(_GLIBCXX_USE_FB) || defined(_LIBSTDCXX_FBSTRING)
65
66 #ifdef _LIBSTDCXX_FBSTRING
67 #pragma GCC system_header
68
69 /**
70  * Declare *allocx() and mallctl*() as weak symbols. These will be provided by
71  * jemalloc if we are using jemalloc, or will be nullptr if we are using another
72  * malloc implementation.
73  */
74 extern "C" void* mallocx(size_t, int)
75 __attribute__((__weak__));
76 extern "C" void* rallocx(void*, size_t, int)
77 __attribute__((__weak__));
78 extern "C" size_t xallocx(void*, size_t, size_t, int)
79 __attribute__((__weak__));
80 extern "C" size_t sallocx(const void*, int)
81 __attribute__((__weak__));
82 extern "C" void dallocx(void*, int)
83 __attribute__((__weak__));
84 extern "C" void sdallocx(void*, size_t, int)
85 __attribute__((__weak__));
86 extern "C" size_t nallocx(size_t, int)
87 __attribute__((__weak__));
88 extern "C" int mallctl(const char*, void*, size_t*, void*, size_t)
89 __attribute__((__weak__));
90 extern "C" int mallctlnametomib(const char*, size_t*, size_t*)
91 __attribute__((__weak__));
92 extern "C" int mallctlbymib(const size_t*, size_t, void*, size_t*, void*,
93                             size_t)
94 __attribute__((__weak__));
95
96 #include <bits/functexcept.h>
97
98 #define FOLLY_HAVE_MALLOC_H 1
99
100 #else // !defined(_LIBSTDCXX_FBSTRING)
101
102 #include <folly/memory/detail/MallocImpl.h> /* nolint */
103 #include <folly/portability/BitsFunctexcept.h> /* nolint */
104
105 #endif
106
107 // for malloc_usable_size
108 // NOTE: FreeBSD 9 doesn't have malloc.h.  Its definitions
109 // are found in stdlib.h.
110 #if FOLLY_HAVE_MALLOC_H
111 #include <malloc.h>
112 #else
113 #include <stdlib.h>
114 #endif
115
116 #include <cassert>
117 #include <cstddef>
118 #include <cstdint>
119 #include <cstdlib>
120 #include <cstring>
121
122 #include <atomic>
123 #include <new>
124
125 #ifdef _LIBSTDCXX_FBSTRING
126 namespace std _GLIBCXX_VISIBILITY(default) {
127 _GLIBCXX_BEGIN_NAMESPACE_VERSION
128 #else
129 namespace folly {
130 #endif
131
132 // Cannot depend on Portability.h when _LIBSTDCXX_FBSTRING.
133 #if defined(__GNUC__)
134 #define FOLLY_MALLOC_NOINLINE __attribute__((__noinline__))
135 #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL) >= 40900
136 // This is for checked malloc-like functions (returns non-null pointer
137 // which cannot alias any outstanding pointer).
138 #define FOLLY_MALLOC_CHECKED_MALLOC                     \
139   __attribute__((__returns_nonnull__, __malloc__))
140 #else
141 #define FOLLY_MALLOC_CHECKED_MALLOC __attribute__((__malloc__))
142 #endif
143 #else
144 #define FOLLY_MALLOC_NOINLINE
145 #define FOLLY_MALLOC_CHECKED_MALLOC
146 #endif
147
148 #include <folly/CPortability.h>
149 /**
150  * Determine if we are using jemalloc or not.
151  */
152 #if defined(USE_JEMALLOC) && !FOLLY_SANITIZE
153   inline bool usingJEMalloc() noexcept {
154     return true;
155   }
156 #else
157 FOLLY_MALLOC_NOINLINE inline bool usingJEMalloc() noexcept {
158   // Checking for rallocx != nullptr is not sufficient; we may be in a
159   // dlopen()ed module that depends on libjemalloc, so rallocx is resolved, but
160   // the main program might be using a different memory allocator.
161   // How do we determine that we're using jemalloc? In the hackiest
162   // way possible. We allocate memory using malloc() and see if the
163   // per-thread counter of allocated memory increases. This makes me
164   // feel dirty inside. Also note that this requires jemalloc to have
165   // been compiled with --enable-stats.
166   static const bool result = [] () noexcept {
167     // Some platforms (*cough* OSX *cough*) require weak symbol checks to be
168     // in the form if (mallctl != nullptr). Not if (mallctl) or if (!mallctl)
169     // (!!). http://goo.gl/xpmctm
170     if (mallocx == nullptr || rallocx == nullptr || xallocx == nullptr
171         || sallocx == nullptr || dallocx == nullptr || sdallocx == nullptr
172         || nallocx == nullptr || mallctl == nullptr
173         || mallctlnametomib == nullptr || mallctlbymib == nullptr) {
174       return false;
175     }
176
177     // "volatile" because gcc optimizes out the reads from *counter, because
178     // it "knows" malloc doesn't modify global state...
179     /* nolint */ volatile uint64_t* counter;
180     size_t counterLen = sizeof(uint64_t*);
181
182     if (mallctl("thread.allocatedp", static_cast<void*>(&counter), &counterLen,
183                 nullptr, 0) != 0) {
184       return false;
185     }
186
187     if (counterLen != sizeof(uint64_t*)) {
188       return false;
189     }
190
191     uint64_t origAllocated = *counter;
192
193     static const void* volatile ptr = malloc(1);
194     if (!ptr) {
195       // wtf, failing to allocate 1 byte
196       return false;
197     }
198
199     return (origAllocated != *counter);
200   }();
201
202   return result;
203 }
204 #endif
205
206 inline size_t goodMallocSize(size_t minSize) noexcept {
207   if (minSize == 0) {
208     return 0;
209   }
210
211   if (!usingJEMalloc()) {
212     // Not using jemalloc - no smarts
213     return minSize;
214   }
215
216   return nallocx(minSize, 0);
217 }
218
219 // We always request "good" sizes for allocation, so jemalloc can
220 // never grow in place small blocks; they're already occupied to the
221 // brim.  Blocks larger than or equal to 4096 bytes can in fact be
222 // expanded in place, and this constant reflects that.
223 static const size_t jemallocMinInPlaceExpandable = 4096;
224
225 /**
226  * Trivial wrappers around malloc, calloc, realloc that check for allocation
227  * failure and throw std::bad_alloc in that case.
228  */
229 inline void* checkedMalloc(size_t size) {
230   void* p = malloc(size);
231   if (!p) {
232     std::__throw_bad_alloc();
233   }
234   return p;
235 }
236
237 inline void* checkedCalloc(size_t n, size_t size) {
238   void* p = calloc(n, size);
239   if (!p) {
240     std::__throw_bad_alloc();
241   }
242   return p;
243 }
244
245 inline void* checkedRealloc(void* ptr, size_t size) {
246   void* p = realloc(ptr, size);
247   if (!p) {
248     std::__throw_bad_alloc();
249   }
250   return p;
251 }
252
253 /**
254  * This function tries to reallocate a buffer of which only the first
255  * currentSize bytes are used. The problem with using realloc is that
256  * if currentSize is relatively small _and_ if realloc decides it
257  * needs to move the memory chunk to a new buffer, then realloc ends
258  * up copying data that is not used. It's generally not a win to try
259  * to hook in to realloc() behavior to avoid copies - at least in
260  * jemalloc, realloc() almost always ends up doing a copy, because
261  * there is little fragmentation / slack space to take advantage of.
262  */
263 FOLLY_MALLOC_CHECKED_MALLOC FOLLY_MALLOC_NOINLINE inline void* smartRealloc(
264     void* p,
265     const size_t currentSize,
266     const size_t currentCapacity,
267     const size_t newCapacity) {
268   assert(p);
269   assert(currentSize <= currentCapacity &&
270          currentCapacity < newCapacity);
271
272   auto const slack = currentCapacity - currentSize;
273   if (slack * 2 > currentSize) {
274     // Too much slack, malloc-copy-free cycle:
275     auto const result = checkedMalloc(newCapacity);
276     std::memcpy(result, p, currentSize);
277     free(p);
278     return result;
279   }
280   // If there's not too much slack, we realloc in hope of coalescing
281   return checkedRealloc(p, newCapacity);
282 }
283
284 #ifdef _LIBSTDCXX_FBSTRING
285 _GLIBCXX_END_NAMESPACE_VERSION
286 #endif
287
288 } // namespace folly
289
290 #endif // !defined(_GLIBCXX_USE_FB) || defined(_LIBSTDCXX_FBSTRING)