Skip to content

Commit

Permalink
src: print backtrace on fatal error
Browse files Browse the repository at this point in the history
Print a C backtrace on fatal errors to make it easier to debug issues
like nodejs#6727.
  • Loading branch information
bnoordhuis committed May 13, 2016
1 parent ae17883 commit cd737bb
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 0 deletions.
2 changes: 2 additions & 0 deletions node.gyp
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,7 @@

[ 'OS=="win"', {
'sources': [
'src/backtrace_win32.cc',
'src/res/node.rc',
],
'defines!': [
Expand All @@ -416,6 +417,7 @@
'libraries': [ '-lpsapi.lib' ]
}, { # POSIX
'defines': [ '__POSIX__' ],
'sources': [ 'src/backtrace_posix.cc' ],
}],
[ 'OS=="mac"', {
# linking Corefoundation is needed since certain OSX debugging tools
Expand Down
36 changes: 36 additions & 0 deletions src/backtrace_posix.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#include "node.h"

#include <cxxabi.h>
#include <dlfcn.h>
#include <execinfo.h>
#include <stdio.h>

namespace node {

void DumpBacktrace(FILE* fp) {
void* frames[256];
const int size = backtrace(frames, arraysize(frames));
if (size <= 0) {
return;
}
for (int i = 1; i < size; i += 1) {
const void* frame = frames[i];
fprintf(fp, "%2d: ", i);
Dl_info info;
const bool have_info = dladdr(frame, &info);
if (!have_info || info.dli_sname == nullptr) {
fprintf(fp, "%p", frame);
} else if (char* demangled = abi::__cxa_demangle(info.dli_sname, 0, 0, 0)) {
fprintf(fp, "%s", demangled);
free(demangled);
} else {
fprintf(fp, "%s", info.dli_sname);
}
if (have_info && info.dli_fname != nullptr) {
fprintf(fp, " [%s]", info.dli_fname);
}
fprintf(fp, "\n");
}
}

} // namespace node
8 changes: 8 additions & 0 deletions src/backtrace_win32.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#include "node.h"

namespace node {

void DumpBacktrace(FILE* fp) {
}

} // namespace node
1 change: 1 addition & 0 deletions src/node.cc
Original file line number Diff line number Diff line change
Expand Up @@ -2383,6 +2383,7 @@ static void OnFatalError(const char* location, const char* message) {
} else {
PrintErrorString("FATAL ERROR: %s\n", message);
}
DumpBacktrace(stderr);
fflush(stderr);
ABORT();
}
Expand Down
3 changes: 3 additions & 0 deletions src/node_internals.h
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include "uv.h"
#include "v8.h"

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

Expand Down Expand Up @@ -132,6 +133,8 @@ void AppendExceptionLine(Environment* env,
v8::Local<v8::Value> er,
v8::Local<v8::Message> message);

void DumpBacktrace(FILE* fp);

NO_RETURN void FatalError(const char* location, const char* message);

v8::Local<v8::Value> BuildStatsObject(Environment* env, const uv_stat_t* s);
Expand Down

0 comments on commit cd737bb

Please sign in to comment.