malloc_stats.cc 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
  2. // This source code is licensed under both the GPLv2 (found in the
  3. // COPYING file in the root directory) and Apache 2.0 License
  4. // (found in the LICENSE.Apache file in the root directory).
  5. //
  6. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  7. // Use of this source code is governed by a BSD-style license that can be
  8. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  9. #include "db/malloc_stats.h"
  10. #include <cstring>
  11. #include <memory>
  12. #include "port/jemalloc_helper.h"
  13. namespace ROCKSDB_NAMESPACE {
  14. #ifdef ROCKSDB_JEMALLOC
  15. struct MallocStatus {
  16. char* cur;
  17. char* end;
  18. };
  19. static void GetJemallocStatus(void* mstat_arg, const char* status) {
  20. MallocStatus* mstat = static_cast<MallocStatus*>(mstat_arg);
  21. size_t status_len = status ? strlen(status) : 0;
  22. size_t buf_size = (size_t)(mstat->end - mstat->cur);
  23. if (!status_len || status_len > buf_size) {
  24. return;
  25. }
  26. snprintf(mstat->cur, buf_size, "%s", status);
  27. mstat->cur += status_len;
  28. }
  29. void DumpMallocStats(std::string* stats) {
  30. if (!HasJemalloc()) {
  31. return;
  32. }
  33. MallocStatus mstat;
  34. const unsigned int kMallocStatusLen = 1000000;
  35. std::unique_ptr<char[]> buf{new char[kMallocStatusLen + 1]};
  36. mstat.cur = buf.get();
  37. mstat.end = buf.get() + kMallocStatusLen;
  38. malloc_stats_print(GetJemallocStatus, &mstat, "");
  39. stats->append(buf.get());
  40. }
  41. #else
  42. void DumpMallocStats(std::string*) {}
  43. #endif // ROCKSDB_JEMALLOC
  44. } // namespace ROCKSDB_NAMESPACE