Handle lack of weak symbols on some platforms
[folly.git] / folly / Malloc.h
1 /*
2  * Copyright 2013 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 #ifndef FOLLY_MALLOC_H_
21 #define FOLLY_MALLOC_H_
22
23 // If using fbstring from libstdc++, then just define stub code
24 // here to typedef the fbstring type into the folly namespace.
25 // This provides backwards compatibility for code that explicitly
26 // includes and uses fbstring.
27 #if defined(_GLIBCXX_USE_FB) && !defined(_LIBSTDCXX_FBSTRING)
28
29 #include "folly/detail/Malloc.h"
30
31 #include <string>
32 namespace folly {
33   using std::goodMallocSize;
34   using std::jemallocMinInPlaceExpandable;
35   using std::usingJEMalloc;
36   using std::smartRealloc;
37   using std::checkedMalloc;
38   using std::checkedCalloc;
39   using std::checkedRealloc;
40 }
41
42 #else // !defined(_GLIBCXX_USE_FB) || defined(_LIBSTDCXX_FBSTRING)
43
44 #ifdef _LIBSTDCXX_FBSTRING
45 #pragma GCC system_header
46 #include <bits/functexcept.h>
47 #define FOLLY_HAVE_MALLOC_H 1
48 #else
49 #include "folly/detail/Malloc.h"
50 #include "folly/Portability.h"
51 #include <stdexcept>
52 #endif
53
54 // for malloc_usable_size
55 // NOTE: FreeBSD 9 doesn't have malloc.h.  It's defitions
56 // are found in stdlib.h.
57 #if FOLLY_HAVE_MALLOC_H
58 #include <malloc.h>
59 #else
60 #include <stdlib.h>
61 #endif
62
63 #include <cassert>
64 #include <cstddef>
65 #include <cstdlib>
66 #include <cstring>
67
68 #include <new>
69
70 /**
71  * Define various ALLOCM_* macros normally provided by jemalloc.  We define
72  * them so that we don't have to include jemalloc.h, in case the program is
73  * built without jemalloc support.
74  */
75 #ifndef ALLOCM_SUCCESS
76
77 #define ALLOCM_SUCCESS 0
78 #define ALLOCM_ERR_OOM 1
79 #define ALLOCM_ERR_NOT_MOVED 2
80
81 #define ALLOCM_ZERO    64
82 #define ALLOCM_NO_MOVE 128
83
84 #define ALLOCM_LG_ALIGN(la) (la)
85
86 #if defined(JEMALLOC_MANGLE) && defined(JEMALLOC_EXPERIMENTAL)
87 #define rallocm je_rallocm
88 #define allocm je_allocm
89 #endif
90
91 #endif /* ALLOCM_SUCCESS */
92
93 #ifdef _LIBSTDCXX_FBSTRING
94 namespace std _GLIBCXX_VISIBILITY(default) {
95 _GLIBCXX_BEGIN_NAMESPACE_VERSION
96 #else
97 namespace folly {
98 #endif
99
100
101 /**
102  * Determine if we are using jemalloc or not.
103  */
104 inline bool usingJEMalloc() {
105   return rallocm != NULL;
106 }
107
108 /**
109  * For jemalloc's size classes, see
110  * http://www.canonware.com/download/jemalloc/jemalloc-latest/doc/jemalloc.html
111  */
112 inline size_t goodMallocSize(size_t minSize) {
113   if (!usingJEMalloc()) {
114     // Not using jemalloc - no smarts
115     return minSize;
116   }
117   if (minSize <= 64) {
118     // Choose smallest allocation to be 64 bytes - no tripping over
119     // cache line boundaries, and small string optimization takes care
120     // of short strings anyway.
121     return 64;
122   }
123   if (minSize <= 512) {
124     // Round up to the next multiple of 64; we don't want to trip over
125     // cache line boundaries.
126     return (minSize + 63) & ~size_t(63);
127   }
128   if (minSize <= 3840) {
129     // Round up to the next multiple of 256
130     return (minSize + 255) & ~size_t(255);
131   }
132   if (minSize <= 4072 * 1024) {
133     // Round up to the next multiple of 4KB
134     return (minSize + 4095) & ~size_t(4095);
135   }
136   // Holy Moly
137   // Round up to the next multiple of 4MB
138   return (minSize + 4194303) & ~size_t(4194303);
139 }
140
141 // We always request "good" sizes for allocation, so jemalloc can
142 // never grow in place small blocks; they're already occupied to the
143 // brim.  Blocks larger than or equal to 4096 bytes can in fact be
144 // expanded in place, and this constant reflects that.
145 static const size_t jemallocMinInPlaceExpandable = 4096;
146
147 /**
148  * Trivial wrappers around malloc, calloc, realloc that check for allocation
149  * failure and throw std::bad_alloc in that case.
150  */
151 inline void* checkedMalloc(size_t size) {
152   void* p = malloc(size);
153 #ifdef _LIBSTDCXX_FBSTRING
154   if (!p) std::__throw_bad_alloc();
155 #else
156   if (!p) throw std::bad_alloc();
157 #endif
158   return p;
159 }
160
161 inline void* checkedCalloc(size_t n, size_t size) {
162   void* p = calloc(n, size);
163 #ifdef _LIBSTDCXX_FBSTRING
164   if (!p) std::__throw_bad_alloc();
165 #else
166   if (!p) throw std::bad_alloc();
167 #endif
168   return p;
169 }
170
171 inline void* checkedRealloc(void* ptr, size_t size) {
172   void* p = realloc(ptr, size);
173 #ifdef _LIBSTDCXX_FBSTRING
174   if (!p) std::__throw_bad_alloc();
175 #else
176   if (!p) throw std::bad_alloc();
177 #endif
178   return p;
179 }
180
181 /**
182  * This function tries to reallocate a buffer of which only the first
183  * currentSize bytes are used. The problem with using realloc is that
184  * if currentSize is relatively small _and_ if realloc decides it
185  * needs to move the memory chunk to a new buffer, then realloc ends
186  * up copying data that is not used. It's impossible to hook into
187  * GNU's malloc to figure whether expansion will occur in-place or as
188  * a malloc-copy-free troika. (If an expand_in_place primitive would
189  * be available, smartRealloc would use it.) As things stand, this
190  * routine just tries to call realloc() (thus benefitting of potential
191  * copy-free coalescing) unless there's too much slack memory.
192  */
193 inline void* smartRealloc(void* p,
194                           const size_t currentSize,
195                           const size_t currentCapacity,
196                           const size_t newCapacity) {
197   assert(p);
198   assert(currentSize <= currentCapacity &&
199          currentCapacity < newCapacity);
200
201   if (usingJEMalloc()) {
202     // using jemalloc's API. Don't forget that jemalloc can never grow
203     // in place blocks smaller than 4096 bytes.
204     if (currentCapacity >= jemallocMinInPlaceExpandable &&
205         rallocm(&p, NULL, newCapacity, 0, ALLOCM_NO_MOVE) == ALLOCM_SUCCESS) {
206       // Managed to expand in place
207       return p;
208     }
209     // Cannot expand; must move
210     auto const result = checkedMalloc(newCapacity);
211     std::memcpy(result, p, currentSize);
212     free(p);
213     return result;
214   }
215
216   // No jemalloc no honey
217   auto const slack = currentCapacity - currentSize;
218   if (slack * 2 > currentSize) {
219     // Too much slack, malloc-copy-free cycle:
220     auto const result = checkedMalloc(newCapacity);
221     std::memcpy(result, p, currentSize);
222     free(p);
223     return result;
224   }
225   // If there's not too much slack, we realloc in hope of coalescing
226   return checkedRealloc(p, newCapacity);
227 }
228
229 #ifdef _LIBSTDCXX_FBSTRING
230 _GLIBCXX_END_NAMESPACE_VERSION
231 #endif
232
233 } // folly
234
235 #endif // !defined(_GLIBCXX_USE_FB) || defined(_LIBSTDCXX_FBSTRING)
236
237 #endif // FOLLY_MALLOC_H_