1 | /* |
2 | * Copyright 2016-present 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 | // Some helper functions for mallctl. |
18 | |
19 | #pragma once |
20 | |
21 | #include <folly/Likely.h> |
22 | #include <folly/memory/Malloc.h> |
23 | |
24 | #include <stdexcept> |
25 | |
26 | namespace folly { |
27 | |
28 | namespace detail { |
29 | |
30 | [[noreturn]] void handleMallctlError(const char* cmd, int err); |
31 | |
32 | template <typename T> |
33 | void mallctlHelper(const char* cmd, T* out, T* in) { |
34 | if (UNLIKELY(!usingJEMalloc())) { |
35 | throw std::logic_error("Calling mallctl when not using jemalloc." ); |
36 | } |
37 | |
38 | size_t outLen = sizeof(T); |
39 | int err = mallctl(cmd, out, out ? &outLen : nullptr, in, in ? sizeof(T) : 0); |
40 | if (UNLIKELY(err != 0)) { |
41 | handleMallctlError(cmd, err); |
42 | } |
43 | } |
44 | |
45 | } // namespace detail |
46 | |
47 | template <typename T> |
48 | void mallctlRead(const char* cmd, T* out) { |
49 | detail::mallctlHelper(cmd, out, static_cast<T*>(nullptr)); |
50 | } |
51 | |
52 | template <typename T> |
53 | void mallctlWrite(const char* cmd, T in) { |
54 | detail::mallctlHelper(cmd, static_cast<T*>(nullptr), &in); |
55 | } |
56 | |
57 | template <typename T> |
58 | void mallctlReadWrite(const char* cmd, T* out, T in) { |
59 | detail::mallctlHelper(cmd, out, &in); |
60 | } |
61 | |
62 | inline void mallctlCall(const char* cmd) { |
63 | // Use <unsigned> rather than <void> to avoid sizeof(void). |
64 | mallctlRead<unsigned>(cmd, nullptr); |
65 | } |
66 | |
67 | } // namespace folly |
68 | |