Skip to content

Commit 9836254

Browse files
bajtosMylesBorins
authored andcommitted
inspector: enable async stack traces
Implement a special async_hooks listener that forwards information about async tasks to V8Inspector asyncTask* API, thus enabling DevTools feature "async stack traces". The feature is enabled only on 64bit platforms due to a technical limitation of V8 Inspector: inspector uses a pointer as a task id, while async_hooks use 64bit numbers as ids. To avoid performance penalty of async_hooks when not debugging, the new listener is enabled only when the process enters a debug mode: - When the process is started with `--inspect` or `--inspect-brk`, the listener is enabled immediately and async stack traces lead all the way to the first tick of the event loop. - When the debug mode is enabled via SIGUSR1 or `_debugProcess()`, the listener is enabled together with the debugger. As a result, only async operations started after the signal was received will be correctly observed and reported to V8 Inspector. For example, a `setInterval()` called in the first tick of the event will not be shown in the async stack trace when the callback is invoked. This behaviour is consistent with Chrome DevTools. Last but not least, this commit fixes handling of InspectorAgent's internal property `enabled_` to ensure it's set back to `false` after the debugger is deactivated (typically via `process._debugEnd()`). Fixes: #11370 PR-URL: #13870 Reviewed-by: Timothy Gu <[email protected]> Reviewed-by: Anna Henningsen <[email protected]>
1 parent e0dccd0 commit 9836254

17 files changed

+656
-17
lines changed

lib/internal/bootstrap_node.js

+2
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,8 @@
6262
if (global.__coverage__)
6363
NativeModule.require('internal/process/write-coverage').setup();
6464

65+
NativeModule.require('internal/inspector_async_hook').setup();
66+
6567
// Do not initialize channel in debugger agent, it deletes env variable
6668
// and the main thread won't see it.
6769
if (process.argv[1] !== '--debug-agent')

lib/internal/inspector_async_hook.js

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
'use strict';
2+
3+
const { createHook } = require('async_hooks');
4+
const inspector = process.binding('inspector');
5+
const config = process.binding('config');
6+
7+
if (!inspector || !inspector.asyncTaskScheduled) {
8+
exports.setup = function() {};
9+
return;
10+
}
11+
12+
const hook = createHook({
13+
init(asyncId, type, triggerAsyncId, resource) {
14+
// It's difficult to tell which tasks will be recurring and which won't,
15+
// therefore we mark all tasks as recurring. Based on the discussion
16+
// in https://github.com/nodejs/node/pull/13870#discussion_r124515293,
17+
// this should be fine as long as we call asyncTaskCanceled() too.
18+
const recurring = true;
19+
inspector.asyncTaskScheduled(type, asyncId, recurring);
20+
},
21+
22+
before(asyncId) {
23+
inspector.asyncTaskStarted(asyncId);
24+
},
25+
26+
after(asyncId) {
27+
inspector.asyncTaskFinished(asyncId);
28+
},
29+
30+
destroy(asyncId) {
31+
inspector.asyncTaskCanceled(asyncId);
32+
},
33+
});
34+
35+
function enable() {
36+
if (config.bits < 64) {
37+
// V8 Inspector stores task ids as (void*) pointers.
38+
// async_hooks store ids as 64bit numbers.
39+
// As a result, we cannot reliably translate async_hook ids to V8 async_task
40+
// ids on 32bit platforms.
41+
process.emitWarning(
42+
'Warning: Async stack traces in debugger are not available ' +
43+
`on ${config.bits}bit platforms. The feature is disabled.`,
44+
{
45+
code: 'INSPECTOR_ASYNC_STACK_TRACES_NOT_AVAILABLE',
46+
});
47+
} else {
48+
hook.enable();
49+
}
50+
}
51+
52+
function disable() {
53+
hook.disable();
54+
}
55+
56+
exports.setup = function() {
57+
inspector.registerAsyncHook(enable, disable);
58+
59+
if (inspector.isEnabled()) {
60+
// If the inspector was already enabled via --inspect or --inspect-brk,
61+
// the we need to enable the async hook immediately at startup.
62+
enable();
63+
}
64+
};

node.gyp

+1
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@
8888
'lib/internal/freelist.js',
8989
'lib/internal/fs.js',
9090
'lib/internal/http.js',
91+
'lib/internal/inspector_async_hook.js',
9192
'lib/internal/linkedlist.js',
9293
'lib/internal/net.js',
9394
'lib/internal/module.js',

src/inspector_agent.cc

+164-1
Original file line numberDiff line numberDiff line change
@@ -23,20 +23,27 @@
2323
namespace node {
2424
namespace inspector {
2525
namespace {
26+
27+
using node::FatalError;
28+
2629
using v8::Array;
30+
using v8::Boolean;
2731
using v8::Context;
2832
using v8::External;
2933
using v8::Function;
3034
using v8::FunctionCallbackInfo;
3135
using v8::HandleScope;
36+
using v8::Integer;
3237
using v8::Isolate;
3338
using v8::Local;
3439
using v8::Maybe;
3540
using v8::MaybeLocal;
41+
using v8::Name;
3642
using v8::NewStringType;
3743
using v8::Object;
3844
using v8::Persistent;
3945
using v8::String;
46+
using v8::Undefined;
4047
using v8::Value;
4148

4249
using v8_inspector::StringBuffer;
@@ -613,6 +620,28 @@ class NodeInspectorClient : public V8InspectorClient {
613620
timers_.erase(data);
614621
}
615622

623+
// Async stack traces instrumentation.
624+
void AsyncTaskScheduled(const StringView& task_name, void* task,
625+
bool recurring) {
626+
client_->asyncTaskScheduled(task_name, task, recurring);
627+
}
628+
629+
void AsyncTaskCanceled(void* task) {
630+
client_->asyncTaskCanceled(task);
631+
}
632+
633+
void AsyncTaskStarted(void* task) {
634+
client_->asyncTaskStarted(task);
635+
}
636+
637+
void AsyncTaskFinished(void* task) {
638+
client_->asyncTaskFinished(task);
639+
}
640+
641+
void AllAsyncTasksCanceled() {
642+
client_->allAsyncTasksCanceled();
643+
}
644+
616645
private:
617646
node::Environment* env_;
618647
node::NodePlatform* platform_;
@@ -673,9 +702,21 @@ bool Agent::StartIoThread(bool wait_for_connect) {
673702
}
674703

675704
v8::Isolate* isolate = parent_env_->isolate();
705+
HandleScope handle_scope(isolate);
706+
707+
// Enable tracking of async stack traces
708+
if (!enable_async_hook_function_.IsEmpty()) {
709+
Local<Function> enable_fn = enable_async_hook_function_.Get(isolate);
710+
auto context = parent_env_->context();
711+
auto result = enable_fn->Call(context, Undefined(isolate), 0, nullptr);
712+
if (result.IsEmpty()) {
713+
FatalError(
714+
"node::InspectorAgent::StartIoThread",
715+
"Cannot enable Inspector's AsyncHook, please report this.");
716+
}
717+
}
676718

677719
// Send message to enable debug in workers
678-
HandleScope handle_scope(isolate);
679720
Local<Object> process_object = parent_env_->process_object();
680721
Local<Value> emit_fn =
681722
process_object->Get(FIXED_ONE_BYTE_STRING(isolate, "emit"));
@@ -714,10 +755,40 @@ void Agent::Stop() {
714755
if (io_ != nullptr) {
715756
io_->Stop();
716757
io_.reset();
758+
enabled_ = false;
759+
}
760+
761+
v8::Isolate* isolate = parent_env_->isolate();
762+
HandleScope handle_scope(isolate);
763+
764+
// Disable tracking of async stack traces
765+
if (!disable_async_hook_function_.IsEmpty()) {
766+
Local<Function> disable_fn = disable_async_hook_function_.Get(isolate);
767+
auto result = disable_fn->Call(parent_env_->context(),
768+
Undefined(parent_env_->isolate()), 0, nullptr);
769+
if (result.IsEmpty()) {
770+
FatalError(
771+
"node::InspectorAgent::Stop",
772+
"Cannot disable Inspector's AsyncHook, please report this.");
773+
}
717774
}
718775
}
719776

720777
void Agent::Connect(InspectorSessionDelegate* delegate) {
778+
if (!enabled_) {
779+
// Enable tracking of async stack traces
780+
v8::Isolate* isolate = parent_env_->isolate();
781+
HandleScope handle_scope(isolate);
782+
auto context = parent_env_->context();
783+
Local<Function> enable_fn = enable_async_hook_function_.Get(isolate);
784+
auto result = enable_fn->Call(context, Undefined(isolate), 0, nullptr);
785+
if (result.IsEmpty()) {
786+
FatalError(
787+
"node::InspectorAgent::Connect",
788+
"Cannot enable Inspector's AsyncHook, please report this.");
789+
}
790+
}
791+
721792
enabled_ = true;
722793
client_->connectFrontend(delegate);
723794
}
@@ -770,6 +841,34 @@ void Agent::PauseOnNextJavascriptStatement(const std::string& reason) {
770841
channel->schedulePauseOnNextStatement(reason);
771842
}
772843

844+
void Agent::RegisterAsyncHook(Isolate* isolate,
845+
v8::Local<v8::Function> enable_function,
846+
v8::Local<v8::Function> disable_function) {
847+
enable_async_hook_function_.Reset(isolate, enable_function);
848+
disable_async_hook_function_.Reset(isolate, disable_function);
849+
}
850+
851+
void Agent::AsyncTaskScheduled(const StringView& task_name, void* task,
852+
bool recurring) {
853+
client_->AsyncTaskScheduled(task_name, task, recurring);
854+
}
855+
856+
void Agent::AsyncTaskCanceled(void* task) {
857+
client_->AsyncTaskCanceled(task);
858+
}
859+
860+
void Agent::AsyncTaskStarted(void* task) {
861+
client_->AsyncTaskStarted(task);
862+
}
863+
864+
void Agent::AsyncTaskFinished(void* task) {
865+
client_->AsyncTaskFinished(task);
866+
}
867+
868+
void Agent::AllAsyncTasksCanceled() {
869+
client_->AllAsyncTasksCanceled();
870+
}
871+
773872
void Open(const FunctionCallbackInfo<Value>& args) {
774873
Environment* env = Environment::GetCurrent(args);
775874
inspector::Agent* agent = env->inspector_agent();
@@ -807,6 +906,59 @@ void Url(const FunctionCallbackInfo<Value>& args) {
807906
args.GetReturnValue().Set(OneByteString(env->isolate(), url.c_str()));
808907
}
809908

909+
static void* GetAsyncTask(int64_t asyncId) {
910+
// The inspector assumes that when other clients use its asyncTask* API,
911+
// they use real pointers, or at least something aligned like real pointer.
912+
// In general it means that our task_id should always be even.
913+
//
914+
// On 32bit platforms, the 64bit asyncId would get truncated when converted
915+
// to a 32bit pointer. However, the javascript part will never enable
916+
// the async_hook on 32bit platforms, therefore the truncation will never
917+
// happen in practice.
918+
return reinterpret_cast<void*>(asyncId << 1);
919+
}
920+
921+
template<void (Agent::*asyncTaskFn)(void*)>
922+
static void InvokeAsyncTaskFnWithId(const FunctionCallbackInfo<Value>& args) {
923+
Environment* env = Environment::GetCurrent(args);
924+
CHECK(args[0]->IsNumber());
925+
int64_t task_id = args[0]->IntegerValue(env->context()).FromJust();
926+
(env->inspector_agent()->*asyncTaskFn)(GetAsyncTask(task_id));
927+
}
928+
929+
static void AsyncTaskScheduledWrapper(const FunctionCallbackInfo<Value>& args) {
930+
Environment* env = Environment::GetCurrent(args);
931+
932+
CHECK(args[0]->IsString());
933+
Local<String> task_name = args[0].As<String>();
934+
String::Value task_name_value(task_name);
935+
StringView task_name_view(*task_name_value, task_name_value.length());
936+
937+
CHECK(args[1]->IsNumber());
938+
int64_t task_id = args[1]->IntegerValue(env->context()).FromJust();
939+
void* task = GetAsyncTask(task_id);
940+
941+
CHECK(args[2]->IsBoolean());
942+
bool recurring = args[2]->BooleanValue(env->context()).FromJust();
943+
944+
env->inspector_agent()->AsyncTaskScheduled(task_name_view, task, recurring);
945+
}
946+
947+
static void RegisterAsyncHookWrapper(const FunctionCallbackInfo<Value>& args) {
948+
Environment* env = Environment::GetCurrent(args);
949+
950+
CHECK(args[0]->IsFunction());
951+
v8::Local<v8::Function> enable_function = args[0].As<Function>();
952+
CHECK(args[1]->IsFunction());
953+
v8::Local<v8::Function> disable_function = args[1].As<Function>();
954+
env->inspector_agent()->RegisterAsyncHook(env->isolate(),
955+
enable_function, disable_function);
956+
}
957+
958+
static void IsEnabled(const FunctionCallbackInfo<Value>& args) {
959+
Environment* env = Environment::GetCurrent(args);
960+
args.GetReturnValue().Set(env->inspector_agent()->enabled());
961+
}
810962

811963
// static
812964
void Agent::InitInspector(Local<Object> target, Local<Value> unused,
@@ -827,6 +979,17 @@ void Agent::InitInspector(Local<Object> target, Local<Value> unused,
827979
env->SetMethod(target, "connect", ConnectJSBindingsSession);
828980
env->SetMethod(target, "open", Open);
829981
env->SetMethod(target, "url", Url);
982+
983+
env->SetMethod(target, "asyncTaskScheduled", AsyncTaskScheduledWrapper);
984+
env->SetMethod(target, "asyncTaskCanceled",
985+
InvokeAsyncTaskFnWithId<&Agent::AsyncTaskCanceled>);
986+
env->SetMethod(target, "asyncTaskStarted",
987+
InvokeAsyncTaskFnWithId<&Agent::AsyncTaskStarted>);
988+
env->SetMethod(target, "asyncTaskFinished",
989+
InvokeAsyncTaskFnWithId<&Agent::AsyncTaskFinished>);
990+
991+
env->SetMethod(target, "registerAsyncHook", RegisterAsyncHookWrapper);
992+
env->SetMethod(target, "isEnabled", IsEnabled);
830993
}
831994

832995
void Agent::RequestIoThreadStart() {

src/inspector_agent.h

+16-11
Original file line numberDiff line numberDiff line change
@@ -17,17 +17,7 @@ class Environment;
1717
class NodePlatform;
1818
} // namespace node
1919

20-
namespace v8 {
21-
class Context;
22-
template <typename V>
23-
class FunctionCallbackInfo;
24-
template<typename T>
25-
class Local;
26-
class Message;
27-
class Object;
28-
class Platform;
29-
class Value;
30-
} // namespace v8
20+
#include "v8.h"
3121

3222
namespace v8_inspector {
3323
class StringView;
@@ -68,6 +58,18 @@ class Agent {
6858
void FatalException(v8::Local<v8::Value> error,
6959
v8::Local<v8::Message> message);
7060

61+
// Async stack traces instrumentation.
62+
void AsyncTaskScheduled(const v8_inspector::StringView& taskName, void* task,
63+
bool recurring);
64+
void AsyncTaskCanceled(void* task);
65+
void AsyncTaskStarted(void* task);
66+
void AsyncTaskFinished(void* task);
67+
void AllAsyncTasksCanceled();
68+
69+
void RegisterAsyncHook(v8::Isolate* isolate,
70+
v8::Local<v8::Function> enable_function,
71+
v8::Local<v8::Function> disable_function);
72+
7173
// These methods are called by the WS protocol and JS binding to create
7274
// inspector sessions. The inspector responds by using the delegate to send
7375
// messages back.
@@ -108,6 +110,9 @@ class Agent {
108110
std::string path_;
109111
DebugOptions debug_options_;
110112
int next_context_number_;
113+
114+
v8::Persistent<v8::Function> enable_async_hook_function_;
115+
v8::Persistent<v8::Function> disable_async_hook_function_;
111116
};
112117

113118
} // namespace inspector

src/node_config.cc

+14
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ using v8::Boolean;
1212
using v8::Context;
1313
using v8::Integer;
1414
using v8::Local;
15+
using v8::Number;
1516
using v8::Object;
1617
using v8::ReadOnly;
1718
using v8::String;
@@ -29,6 +30,15 @@ using v8::Value;
2930
True(env->isolate()), ReadOnly).FromJust(); \
3031
} while (0)
3132

33+
#define READONLY_PROPERTY(obj, name, value) \
34+
do { \
35+
obj->DefineOwnProperty(env->context(), \
36+
OneByteString(env->isolate(), name), \
37+
value, \
38+
ReadOnly).FromJust(); \
39+
} while (0)
40+
41+
3242
static void InitConfig(Local<Object> target,
3343
Local<Value> unused,
3444
Local<Context> context) {
@@ -90,6 +100,10 @@ static void InitConfig(Local<Object> target,
90100

91101
if (config_expose_http2)
92102
READONLY_BOOLEAN_PROPERTY("exposeHTTP2");
103+
104+
READONLY_PROPERTY(target,
105+
"bits",
106+
Number::New(env->isolate(), 8 * sizeof(intptr_t)));
93107
} // InitConfig
94108

95109
} // namespace node

0 commit comments

Comments
 (0)