malloc_stats.cc 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. #ifndef ROCKSDB_LITE
  11. #include <memory>
  12. #include <string.h>
  13. #include "port/jemalloc_helper.h"
  14. namespace ROCKSDB_NAMESPACE {
  15. #ifdef ROCKSDB_JEMALLOC
  16. typedef struct {
  17. char* cur;
  18. char* end;
  19. } MallocStatus;
  20. static void GetJemallocStatus(void* mstat_arg, const char* status) {
  21. MallocStatus* mstat = reinterpret_cast<MallocStatus*>(mstat_arg);
  22. size_t status_len = status ? strlen(status) : 0;
  23. size_t buf_size = (size_t)(mstat->end - mstat->cur);
  24. if (!status_len || status_len > buf_size) {
  25. return;
  26. }
  27. snprintf(mstat->cur, buf_size, "%s", status);
  28. mstat->cur += status_len;
  29. }
  30. void DumpMallocStats(std::string* stats) {
  31. if (!HasJemalloc()) {
  32. return;
  33. }
  34. MallocStatus mstat;
  35. const unsigned int kMallocStatusLen = 1000000;
  36. std::unique_ptr<char[]> buf{new char[kMallocStatusLen + 1]};
  37. mstat.cur = buf.get();
  38. mstat.end = buf.get() + kMallocStatusLen;
  39. malloc_stats_print(GetJemallocStatus, &mstat, "");
  40. stats->append(buf.get());
  41. }
  42. #else
  43. void DumpMallocStats(std::string*) {}
  44. #endif // ROCKSDB_JEMALLOC
  45. } // namespace ROCKSDB_NAMESPACE
  46. #endif // !ROCKSDB_LITE