77a96d9a294e6a5eba8923e9e49c92ccf3ea6033
[folly.git] / folly / Malloc.cpp
1 /*
2  * Copyright 2014 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 #include "folly/Malloc.h"
18
19 namespace folly {
20
21 // How do we determine that we're using jemalloc?
22 // In the hackiest way possible. We allocate memory using malloc() and see if
23 // the per-thread counter of allocated memory increases. This makes me feel
24 // dirty inside. Also note that this requires jemalloc to have been compiled
25 // with --enable-stats.
26 bool usingJEMallocSlow() {
27   // Some platforms (*cough* OSX *cough*) require weak symbol checks to be
28   // in the form if (mallctl != NULL). Not if (mallctl) or if (!mallctl) (!!).
29   // http://goo.gl/xpmctm
30   if (allocm == nullptr || rallocm == nullptr || mallctl == nullptr) {
31     return false;
32   }
33
34   // "volatile" because gcc optimizes out the reads from *counter, because
35   // it "knows" malloc doesn't modify global state...
36   volatile uint64_t* counter;
37   size_t counterLen = sizeof(uint64_t*);
38
39   if (mallctl("thread.allocatedp", static_cast<void*>(&counter), &counterLen,
40               nullptr, 0) != 0) {
41     return false;
42   }
43
44   if (counterLen != sizeof(uint64_t*)) {
45     return false;
46   }
47
48   uint64_t origAllocated = *counter;
49
50   void* ptr = malloc(1);
51   if (!ptr) {
52     // wtf, failing to allocate 1 byte
53     return false;
54   }
55   free(ptr);
56
57   return (origAllocated != *counter);
58 }
59
60 }  // namespaces
61