MallctlHelper.h 1.7 KB

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