-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmodule.cc
More file actions
269 lines (233 loc) · 9.1 KB
/
module.cc
File metadata and controls
269 lines (233 loc) · 9.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
#include <chrono>
#include <future>
#include <mutex>
#include <node.h>
using namespace v8;
using namespace node;
using namespace std::chrono;
static const int kMaxStackFrames = 255;
// Structure to hold information for each thread/isolate
struct ThreadInfo {
// Thread name
std::string thread_name;
// Last time this thread was seen in milliseconds since epoch
milliseconds last_seen;
};
static std::mutex threads_mutex;
// Map to hold all registered threads and their information
static std::unordered_map<v8::Isolate *, ThreadInfo> threads = {};
// Structure to hold stack frame information
struct JsStackFrame {
std::string function_name;
std::string filename;
int lineno;
int colno;
};
// Type alias for a vector of JsStackFrame
using JsStackTrace = std::vector<JsStackFrame>;
// Function to be called when an isolate's execution is interrupted
static void ExecutionInterrupted(Isolate *isolate, void *data) {
auto promise = static_cast<std::promise<JsStackTrace> *>(data);
auto stack = StackTrace::CurrentStackTrace(isolate, kMaxStackFrames,
StackTrace::kDetailed);
JsStackTrace frames;
if (!stack.IsEmpty()) {
for (int i = 0; i < stack->GetFrameCount(); i++) {
auto frame = stack->GetFrame(isolate, i);
auto fn_name = frame->GetFunctionName();
std::string function_name;
if (frame->IsEval()) {
function_name = "[eval]";
} else if (fn_name.IsEmpty() || fn_name->Length() == 0) {
function_name = "?";
} else if (frame->IsConstructor()) {
function_name = "[constructor]";
} else {
v8::String::Utf8Value utf8_fn(isolate, fn_name);
function_name = *utf8_fn ? *utf8_fn : "?";
}
std::string filename;
auto script_name = frame->GetScriptName();
if (!script_name.IsEmpty()) {
v8::String::Utf8Value utf8_filename(isolate, script_name);
filename = *utf8_filename ? *utf8_filename : "<unknown>";
} else {
filename = "<unknown>";
}
int lineno = frame->GetLineNumber();
int colno = frame->GetColumn();
frames.push_back(JsStackFrame{function_name, filename, lineno, colno});
}
}
promise->set_value(frames);
}
// Function to capture the stack trace of a single isolate
JsStackTrace CaptureStackTrace(Isolate *isolate) {
std::promise<JsStackTrace> promise;
auto future = promise.get_future();
// The v8 isolate must be interrupted to capture the stack trace
// Execution resumes automatically after ExecutionInterrupted returns
isolate->RequestInterrupt(ExecutionInterrupted, &promise);
return future.get();
}
// Function to capture stack traces from all registered threads
void CaptureStackTraces(const FunctionCallbackInfo<Value> &args) {
auto capture_from_isolate = args.GetIsolate();
auto current_context = capture_from_isolate->GetCurrentContext();
using ThreadResult = std::tuple<std::string, JsStackTrace>;
std::vector<std::future<ThreadResult>> futures;
{
std::lock_guard<std::mutex> lock(threads_mutex);
for (auto [thread_isolate, thread_info] : threads) {
if (thread_isolate == capture_from_isolate)
continue;
auto thread_name = thread_info.thread_name;
futures.emplace_back(std::async(
std::launch::async,
[thread_name](Isolate *isolate) -> ThreadResult {
return std::make_tuple(thread_name, CaptureStackTrace(isolate));
},
thread_isolate));
}
}
Local<Object> result = Object::New(capture_from_isolate);
for (auto &future : futures) {
auto [thread_name, frames] = future.get();
auto key = String::NewFromUtf8(capture_from_isolate, thread_name.c_str(),
NewStringType::kNormal)
.ToLocalChecked();
Local<Array> jsFrames = Array::New(capture_from_isolate, frames.size());
for (size_t i = 0; i < frames.size(); ++i) {
const auto &f = frames[i];
Local<Object> frameObj = Object::New(capture_from_isolate);
frameObj
->Set(current_context,
String::NewFromUtf8(capture_from_isolate, "function",
NewStringType::kInternalized)
.ToLocalChecked(),
String::NewFromUtf8(capture_from_isolate,
f.function_name.c_str(),
NewStringType::kNormal)
.ToLocalChecked())
.Check();
frameObj
->Set(current_context,
String::NewFromUtf8(capture_from_isolate, "filename",
NewStringType::kInternalized)
.ToLocalChecked(),
String::NewFromUtf8(capture_from_isolate, f.filename.c_str(),
NewStringType::kNormal)
.ToLocalChecked())
.Check();
frameObj
->Set(current_context,
String::NewFromUtf8(capture_from_isolate, "lineno",
NewStringType::kInternalized)
.ToLocalChecked(),
Integer::New(capture_from_isolate, f.lineno))
.Check();
frameObj
->Set(current_context,
String::NewFromUtf8(capture_from_isolate, "colno",
NewStringType::kInternalized)
.ToLocalChecked(),
Integer::New(capture_from_isolate, f.colno))
.Check();
jsFrames->Set(current_context, static_cast<uint32_t>(i), frameObj)
.Check();
}
result->Set(current_context, key, jsFrames).Check();
}
args.GetReturnValue().Set(result);
}
// Cleanup function to remove the thread from the map when the isolate is
// destroyed
void Cleanup(void *arg) {
auto isolate = static_cast<Isolate *>(arg);
std::lock_guard<std::mutex> lock(threads_mutex);
threads.erase(isolate);
}
// Function to register a thread and update it's last seen time
void RegisterThread(const FunctionCallbackInfo<Value> &args) {
auto isolate = args.GetIsolate();
if (args.Length() != 1 || !args[0]->IsString()) {
isolate->ThrowException(Exception::Error(
String::NewFromUtf8(
isolate, "registerThread(name) requires a single name argument",
NewStringType::kInternalized)
.ToLocalChecked()));
return;
}
v8::String::Utf8Value utf8(isolate, args[0]);
std::string thread_name(*utf8 ? *utf8 : "");
{
std::lock_guard<std::mutex> lock(threads_mutex);
auto found = threads.find(isolate);
if (found == threads.end()) {
threads.emplace(isolate, ThreadInfo{thread_name, milliseconds::zero()});
// Register a cleanup hook to remove this thread when the isolate is
// destroyed
node::AddEnvironmentCleanupHook(isolate, Cleanup, isolate);
} else {
auto &thread_info = found->second;
thread_info.thread_name = thread_name;
thread_info.last_seen =
duration_cast<milliseconds>(system_clock::now().time_since_epoch());
}
}
}
// Function to get the last seen time of all registered threads
void GetThreadsLastSeen(const FunctionCallbackInfo<Value> &args) {
Isolate *isolate = args.GetIsolate();
Local<Object> result = Object::New(isolate);
milliseconds now =
duration_cast<milliseconds>(system_clock::now().time_since_epoch());
{
std::lock_guard<std::mutex> lock(threads_mutex);
for (const auto &[thread_isolate, info] : threads) {
if (info.last_seen == milliseconds::zero())
continue; // Skip threads that have not registered more than once
int64_t ms_since = (now - info.last_seen).count();
result
->Set(isolate->GetCurrentContext(),
String::NewFromUtf8(isolate, info.thread_name.c_str(),
NewStringType::kNormal)
.ToLocalChecked(),
Number::New(isolate, ms_since))
.Check();
}
}
args.GetReturnValue().Set(result);
}
extern "C" NODE_MODULE_EXPORT void
NODE_MODULE_INITIALIZER(Local<Object> exports, Local<Value> module,
Local<Context> context) {
auto isolate = context->GetIsolate();
exports
->Set(context,
String::NewFromUtf8(isolate, "captureStackTrace",
NewStringType::kInternalized)
.ToLocalChecked(),
FunctionTemplate::New(isolate, CaptureStackTraces)
->GetFunction(context)
.ToLocalChecked())
.Check();
exports
->Set(context,
String::NewFromUtf8(isolate, "registerThread",
NewStringType::kInternalized)
.ToLocalChecked(),
FunctionTemplate::New(isolate, RegisterThread)
->GetFunction(context)
.ToLocalChecked())
.Check();
exports
->Set(context,
String::NewFromUtf8(isolate, "getThreadsLastSeen",
NewStringType::kInternalized)
.ToLocalChecked(),
FunctionTemplate::New(isolate, GetThreadsLastSeen)
->GetFunction(context)
.ToLocalChecked())
.Check();
}