Add async-signal-safe flavor of demangle
authorTudor Bosman <tudorb@fb.com>
Wed, 27 Nov 2013 16:56:01 +0000 (08:56 -0800)
committerJordan DeLong <jdelong@fb.com>
Fri, 20 Dec 2013 21:03:55 +0000 (13:03 -0800)
Summary: To be used in the new fatal signal handler.

Test Plan: test added

Reviewed By: lucian@fb.com

FB internal diff: D1076169

@override-unit-failures

folly/String.cpp
folly/String.h
folly/test/StringTest.cpp

index aae439fc1616d6037093b867ca94627bf448aa31..44b6a783369ddfbdc0060841ea89226f4e35404d 100644 (file)
 #include <glog/logging.h>
 
 #undef FOLLY_DEMANGLE
 #include <glog/logging.h>
 
 #undef FOLLY_DEMANGLE
+
 #if defined(__GNUG__) && __GNUG__ >= 4
 # include <cxxabi.h>
 # define FOLLY_DEMANGLE 1
 #if defined(__GNUG__) && __GNUG__ >= 4
 # include <cxxabi.h>
 # define FOLLY_DEMANGLE 1
+
+// From libiberty
+//
+// TODO(tudorb): Detect this with autoconf for the open-source version.
+//
+// __attribute__((weak)) doesn't work, because cplus_demangle_v3_callback
+// is exported by an object file in libiberty.a, and the ELF spec says
+// "The link editor does not extract archive members to resolve undefined weak
+// symbols" (but, interestingly enough, will resolve undefined weak symbols
+// with definitions from archive members that were extracted in order to
+// resolve an undefined global (strong) symbol)
+extern "C" int cplus_demangle_v3_callback(
+    const char* mangled,
+    int options,  // We use DMGL_PARAMS | DMGL_TYPES, aka 0x11
+    void (*callback)(const char*, size_t, void*),
+    void* arg);
+
 #endif
 
 namespace folly {
 #endif
 
 namespace folly {
@@ -264,6 +282,21 @@ fbstring errnoStr(int err) {
   return result;
 }
 
   return result;
 }
 
+namespace {
+
+// glibc doesn't have strlcpy
+size_t my_strlcpy(char* dest, const char* src, size_t size) {
+  size_t len = strlen(src);
+  if (size != 0) {
+    size_t n = std::min(len, size - 1);  // always null terminate!
+    memcpy(dest, src, n);
+    dest[n] = '\0';
+  }
+  return len;
+}
+
+}  // namespace
+
 #ifdef FOLLY_DEMANGLE
 
 fbstring demangle(const char* name) {
 #ifdef FOLLY_DEMANGLE
 
 fbstring demangle(const char* name) {
@@ -279,12 +312,56 @@ fbstring demangle(const char* name) {
   return fbstring(demangled, strlen(demangled), len, AcquireMallocatedString());
 }
 
   return fbstring(demangled, strlen(demangled), len, AcquireMallocatedString());
 }
 
+namespace {
+
+struct DemangleBuf {
+  char* dest;
+  size_t remaining;
+  size_t total;
+};
+
+void demangleCallback(const char* str, size_t size, void* p) {
+  DemangleBuf* buf = static_cast<DemangleBuf*>(p);
+  size_t n = std::min(buf->remaining, size);
+  memcpy(buf->dest, str, n);
+  buf->dest += n;
+  buf->remaining -= n;
+  buf->total += size;
+}
+
+}  // namespace
+
+size_t demangle(const char* name, char* out, size_t outSize) {
+  DemangleBuf dbuf;
+  dbuf.dest = out;
+  dbuf.remaining = outSize ? outSize - 1 : 0;   // leave room for null term
+  dbuf.total = 0;
+
+  // Unlike most library functions, this returns 1 on success and 0 on failure
+  int status = cplus_demangle_v3_callback(
+      name,
+      0x11,  // DMGL_PARAMS | DMGL_TYPES
+      demangleCallback,
+      &dbuf);
+  if (status == 0) {  // failed, return original
+    return my_strlcpy(out, name, outSize);
+  }
+  if (outSize != 0) {
+    *dbuf.dest = '\0';
+  }
+  return dbuf.total;
+}
+
 #else
 
 fbstring demangle(const char* name) {
   return name;
 }
 
 #else
 
 fbstring demangle(const char* name) {
   return name;
 }
 
+size_t demangle(const char* name, char* out, size_t outSize) {
+  return my_strlcpy(out, name, outSize);
+}
+
 #endif
 #undef FOLLY_DEMANGLE
 
 #endif
 #undef FOLLY_DEMANGLE
 
index d706a03215b2f3b121fe9d2a664c4eaba618d3c9..da93cd265d106a296e60a651aad59cd1cfb16bfd 100644 (file)
@@ -322,13 +322,36 @@ fbstring errnoStr(int err);
  *
  * Use for debugging -- do not rely on demangle() returning anything useful.
  *
  *
  * Use for debugging -- do not rely on demangle() returning anything useful.
  *
- * This function may allocate memory (and therefore throw).
+ * This function may allocate memory (and therefore throw std::bad_alloc).
  */
 fbstring demangle(const char* name);
 inline fbstring demangle(const std::type_info& type) {
   return demangle(type.name());
 }
 
  */
 fbstring demangle(const char* name);
 inline fbstring demangle(const std::type_info& type) {
   return demangle(type.name());
 }
 
+/**
+ * Return the demangled (prettyfied) version of a C++ type in a user-provided
+ * buffer.
+ *
+ * The semantics are the same as for snprintf or strlcpy: bufSize is the size
+ * of the buffer, the string is always null-terminated, and the return value is
+ * the number of characters (not including the null terminator) that would have
+ * been written if the buffer was big enough. (So a return value >= bufSize
+ * indicates that the output was truncated)
+ *
+ * This function does not allocate memory and is async-signal-safe.
+ *
+ * Note that the underlying function for the fbstring-returning demangle is
+ * somewhat standard (abi::__cxa_demangle, which uses malloc), the underlying
+ * function for this version is less so (cplus_demangle_v3_callback from
+ * libiberty), so it is possible for the fbstring version to work, while this
+ * version returns the original, mangled name.
+ */
+size_t demangle(const char* name, char* buf, size_t bufSize);
+inline size_t demangle(const std::type_info& type, char* buf, size_t bufSize) {
+  return demangle(type.name(), buf, bufSize);
+}
+
 /**
  * Debug string for an exception: include type and what().
  */
 /**
  * Debug string for an exception: include type and what().
  */
index c48c4059c8d65b6cfee1350c8bd23d73eb42eece..54547b5a674c92531140f1a2059052f1c6abe945 100644 (file)
@@ -464,8 +464,23 @@ struct ThisIsAVeryLongStructureName {
 }  // namespace folly_test
 
 TEST(System, demangle) {
 }  // namespace folly_test
 
 TEST(System, demangle) {
-  EXPECT_EQ("folly_test::ThisIsAVeryLongStructureName",
-            demangle(typeid(folly_test::ThisIsAVeryLongStructureName)));
+  char expected[] = "folly_test::ThisIsAVeryLongStructureName";
+  EXPECT_STREQ(
+      expected,
+      demangle(typeid(folly_test::ThisIsAVeryLongStructureName)).c_str());
+
+  {
+    char buf[sizeof(expected)];
+    EXPECT_EQ(sizeof(expected) - 1,
+              demangle(typeid(folly_test::ThisIsAVeryLongStructureName),
+                       buf, sizeof(buf)));
+    EXPECT_STREQ(expected, buf);
+
+    EXPECT_EQ(sizeof(expected) - 1,
+              demangle(typeid(folly_test::ThisIsAVeryLongStructureName),
+                       buf, 11));
+    EXPECT_STREQ("folly_test", buf);
+  }
 }
 
 namespace {
 }
 
 namespace {