folly: Symbolizer: don't allocate from function which is supposed to be signal safe
[folly.git] / folly / experimental / symbolizer / Symbolizer.h
index 4c30fa79b898df3e8b82e9365a38a48b362a9c4f..d8060330fb9559f27640adf893507fb2661ab8f0 100644 (file)
 #ifndef FOLLY_EXPERIMENTAL_SYMBOLIZER_SYMBOLIZER_H_
 #define FOLLY_EXPERIMENTAL_SYMBOLIZER_SYMBOLIZER_H_
 
+#include <array>
 #include <cstdint>
+#include <memory>
 #include <string>
-#include <unordered_map>
 
 #include <folly/FBString.h>
 #include <folly/Range.h>
@@ -39,14 +40,13 @@ class Symbolizer;
  * Frame information: symbol name and location.
  */
 struct SymbolizedFrame {
-  SymbolizedFrame() : found(false), name(nullptr) { }
+  SymbolizedFrame() { }
 
   void set(const std::shared_ptr<ElfFile>& file, uintptr_t address);
   void clear() { *this = SymbolizedFrame(); }
 
-  bool isSignalFrame;
-  bool found;
-  const char* name;
+  bool found = false;
+  const char* name = nullptr;
   Dwarf::LocationInfo location;
 
   /**
@@ -61,9 +61,9 @@ struct SymbolizedFrame {
 
 template <size_t N>
 struct FrameArray {
-  FrameArray() : frameCount(0) { }
+  FrameArray() { }
 
-  size_t frameCount;
+  size_t frameCount = 0;
   uintptr_t addresses[N];
   SymbolizedFrame frames[N];
 };
@@ -131,7 +131,7 @@ class Symbolizer {
   }
 
  private:
-  ElfCacheBase* cache_;
+  ElfCacheBase* const cache_ = nullptr;
 };
 
 /**
@@ -206,7 +206,8 @@ class SymbolizePrinter {
     COLOR_IF_TTY = 1 << 3,
   };
 
-  enum Color { DEFAULT, RED, GREEN, YELLOW, BLUE, CYAN, WHITE, PURPLE };
+  // NOTE: enum values used as indexes in kColorMap.
+  enum Color { DEFAULT, RED, GREEN, YELLOW, BLUE, CYAN, WHITE, PURPLE, NUM };
   void color(Color c);
 
  protected:
@@ -221,6 +222,17 @@ class SymbolizePrinter {
  private:
   void printTerse(uintptr_t address, const SymbolizedFrame& frame);
   virtual void doPrint(StringPiece sp) = 0;
+
+  static constexpr std::array<const char*, Color::NUM> kColorMap = {{
+      "\x1B[0m",
+      "\x1B[31m",
+      "\x1B[32m",
+      "\x1B[33m",
+      "\x1B[34m",
+      "\x1B[36m",
+      "\x1B[37m",
+      "\x1B[35m",
+  }};
 };
 
 /**
@@ -248,7 +260,7 @@ class FDSymbolizePrinter : public SymbolizePrinter {
  private:
   void doPrint(StringPiece sp) override;
 
-  int fd_;
+  const int fd_;
   std::unique_ptr<IOBuf> buffer_;
 };
 
@@ -261,7 +273,7 @@ class FILESymbolizePrinter : public SymbolizePrinter {
   explicit FILESymbolizePrinter(FILE* file, int options=0);
  private:
   void doPrint(StringPiece sp) override;
-  FILE* file_;
+  FILE* const file_ = nullptr;
 };
 
 /**