stackcollect.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. #pragma once
  2. #include <library/cpp/containers/stack_vector/stack_vec.h>
  3. #include <library/cpp/cache/cache.h>
  4. #include <library/cpp/deprecated/atomic/atomic.h>
  5. #include <util/generic/noncopyable.h>
  6. #include <util/generic/ptr.h>
  7. #include <util/stream/output.h>
  8. namespace NAllocProfiler {
  9. struct TStats {
  10. intptr_t Allocs = 0;
  11. intptr_t Frees = 0;
  12. intptr_t CurrentSize = 0;
  13. void Clear()
  14. {
  15. Allocs = 0;
  16. Frees = 0;
  17. CurrentSize = 0;
  18. }
  19. void Alloc(size_t size)
  20. {
  21. AtomicIncrement(Allocs);
  22. AtomicAdd(CurrentSize, size);
  23. }
  24. void Free(size_t size)
  25. {
  26. AtomicIncrement(Frees);
  27. AtomicSub(CurrentSize, size);
  28. }
  29. };
  30. struct TAllocationInfo {
  31. int Tag;
  32. TStats Stats;
  33. TStackVec<void*, 64> Stack;
  34. void Clear() {
  35. Tag = 0;
  36. Stats.Clear();
  37. Stack.clear();
  38. }
  39. };
  40. class IAllocationStatsDumper {
  41. public:
  42. virtual ~IAllocationStatsDumper() = default;
  43. // Total stats
  44. virtual void DumpTotal(const TStats& total) = 0;
  45. // Stats for individual stack
  46. virtual void DumpEntry(const TAllocationInfo& allocInfo) = 0;
  47. // App-specific tag printer
  48. virtual TString FormatTag(int tag);
  49. // Size printer (e.g. "10KB", "100MB", "over 9000")
  50. virtual TString FormatSize(intptr_t sz);
  51. };
  52. // Default implementation
  53. class TAllocationStatsDumper: public IAllocationStatsDumper {
  54. public:
  55. explicit TAllocationStatsDumper(IOutputStream& out);
  56. void DumpTotal(const TStats& total) override;
  57. void DumpEntry(const TAllocationInfo& allocInfo) override;
  58. private:
  59. void FormatBackTrace(void* const* stack, size_t sz);
  60. private:
  61. struct TSymbol {
  62. const void* Address;
  63. TString Name;
  64. };
  65. size_t PrintedCount;
  66. IOutputStream& Out;
  67. TLFUCache<void*, TSymbol> SymbolCache;
  68. };
  69. ////////////////////////////////////////////////////////////////////////////////
  70. class TAllocationStackCollector: private TNonCopyable {
  71. private:
  72. class TImpl;
  73. THolder<TImpl> Impl;
  74. public:
  75. TAllocationStackCollector();
  76. ~TAllocationStackCollector();
  77. int Alloc(void** stack, size_t frameCount, int tag, size_t size);
  78. void Free(int stackId, size_t size);
  79. void Clear();
  80. void Dump(int count, IAllocationStatsDumper& out) const;
  81. };
  82. } // namespace NAllocProfiler