Skip to content

Commit dc2d5e9

Browse files
committed
process: start coverage collection before bootstrap
This patch moves the dispatch of `Profiler.takePreciseCoverage` to a point before the bootstrap scripts are run to ensure that we can collect coverage data for all the scripts run after the inspector agent is ready. Before this patch `lib/internal/bootstrap/primordials.js` was not covered by `make coverage`, after this patch it is.
1 parent b44131a commit dc2d5e9

8 files changed

Lines changed: 200 additions & 57 deletions

File tree

lib/internal/bootstrap/loaders.js

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -311,18 +311,5 @@ NativeModule.prototype.compile = function() {
311311
}
312312
};
313313

314-
// Coverage must be turned on early, so that we can collect
315-
// it for Node.js' own internal libraries.
316-
if (process.env.NODE_V8_COVERAGE) {
317-
if (internalBinding('config').hasInspector) {
318-
const coverage =
319-
NativeModule.require('internal/coverage-gen/with_profiler');
320-
// Inform the profiler to start collecting coverage
321-
coverage.startCoverageCollection();
322-
} else {
323-
process._rawDebug('NODE_V8_COVERAGE cannot be used without inspector');
324-
}
325-
}
326-
327314
// This will be passed to internal/bootstrap/node.js.
328315
return loaderExports;

lib/internal/coverage-gen/with_profiler.js

Lines changed: 4 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,9 @@
33
// Implements coverage collection exposed by the `NODE_V8_COVERAGE`
44
// environment variable which can also be used in the user land.
55

6-
let coverageConnection = null;
76
let coverageDirectory;
87

98
function writeCoverage() {
10-
if (!coverageConnection && coverageDirectory) {
11-
return;
12-
}
13-
149
const { join } = require('path');
1510
const { mkdirSync, writeFileSync } = require('fs');
1611
const { threadId } = require('internal/worker');
@@ -28,21 +23,12 @@ function writeCoverage() {
2823
const target = join(coverageDirectory, filename);
2924
try {
3025
disableAllAsyncHooks();
31-
let msg;
32-
coverageConnection._coverageCallback = function(_msg) {
33-
msg = _msg;
34-
};
35-
coverageConnection.dispatch(JSON.stringify({
36-
id: 3,
37-
method: 'Profiler.takePreciseCoverage'
38-
}));
39-
const coverageInfo = JSON.parse(msg).result;
40-
writeFileSync(target, JSON.stringify(coverageInfo));
26+
internalBinding('coverage').end((msg) => {
27+
const coverageInfo = JSON.parse(msg).result;
28+
writeFileSync(target, JSON.stringify(coverageInfo));
29+
});
4130
} catch (err) {
4231
console.error(err);
43-
} finally {
44-
coverageConnection.disconnect();
45-
coverageConnection = null;
4632
}
4733
}
4834

@@ -52,33 +38,11 @@ function disableAllAsyncHooks() {
5238
hooks_array.forEach((hook) => { hook.disable(); });
5339
}
5440

55-
function startCoverageCollection() {
56-
const { Connection } = internalBinding('inspector');
57-
coverageConnection = new Connection((res) => {
58-
if (coverageConnection._coverageCallback) {
59-
coverageConnection._coverageCallback(res);
60-
}
61-
});
62-
coverageConnection.dispatch(JSON.stringify({
63-
id: 1,
64-
method: 'Profiler.enable'
65-
}));
66-
coverageConnection.dispatch(JSON.stringify({
67-
id: 2,
68-
method: 'Profiler.startPreciseCoverage',
69-
params: {
70-
callCount: true,
71-
detailed: true
72-
}
73-
}));
74-
}
75-
7641
function setCoverageDirectory(dir) {
7742
coverageDirectory = dir;
7843
}
7944

8045
module.exports = {
81-
startCoverageCollection,
8246
writeCoverage,
8347
setCoverageDirectory
8448
};

src/env.h

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -329,6 +329,7 @@ constexpr size_t kFsStatsBufferLength = kFsStatsFieldsNumber * 2;
329329
V(async_wrap_ctor_template, v8::FunctionTemplate) \
330330
V(async_wrap_object_ctor_template, v8::FunctionTemplate) \
331331
V(buffer_prototype_object, v8::Object) \
332+
V(coverage_connection, v8::Object) \
332333
V(context, v8::Context) \
333334
V(crypto_key_object_constructor, v8::Function) \
334335
V(domain_callback, v8::Function) \
@@ -363,6 +364,7 @@ constexpr size_t kFsStatsBufferLength = kFsStatsFieldsNumber * 2;
363364
V(message_port, v8::Object) \
364365
V(message_port_constructor_template, v8::FunctionTemplate) \
365366
V(native_module_require, v8::Function) \
367+
V(on_coverage_message_function, v8::Function) \
366368
V(performance_entry_callback, v8::Function) \
367369
V(performance_entry_template, v8::Function) \
368370
V(pipe_constructor_template, v8::FunctionTemplate) \
@@ -447,9 +449,10 @@ struct ContextInfo {
447449

448450
// Listing the AsyncWrap provider types first enables us to cast directly
449451
// from a provider type to a debug category.
450-
#define DEBUG_CATEGORY_NAMES(V) \
451-
NODE_ASYNC_PROVIDER_TYPES(V) \
452-
V(INSPECTOR_SERVER)
452+
#define DEBUG_CATEGORY_NAMES(V) \
453+
NODE_ASYNC_PROVIDER_TYPES(V) \
454+
V(INSPECTOR_SERVER) \
455+
V(COVERAGE)
453456

454457
enum class DebugCategory {
455458
#define V(name) name,

src/inspector/node_inspector.gypi

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545
'../../src/inspector_io.cc',
4646
'../../src/inspector_agent.h',
4747
'../../src/inspector_io.h',
48+
'../../src/inspector_coverage.cc',
4849
'../../src/inspector_js_api.cc',
4950
'../../src/inspector_socket.cc',
5051
'../../src/inspector_socket.h',

src/inspector_coverage.cc

Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
#include "base_object-inl.h"
2+
#include "debug_utils.h"
3+
#include "inspector_agent.h"
4+
#include "node_internals.h"
5+
#include "v8-inspector.h"
6+
7+
namespace node {
8+
namespace coverage {
9+
10+
using v8::Context;
11+
using v8::Function;
12+
using v8::FunctionCallbackInfo;
13+
using v8::HandleScope;
14+
using v8::Isolate;
15+
using v8::Local;
16+
using v8::MaybeLocal;
17+
using v8::NewStringType;
18+
using v8::Object;
19+
using v8::ObjectTemplate;
20+
using v8::String;
21+
using v8::Value;
22+
23+
using v8_inspector::StringBuffer;
24+
using v8_inspector::StringView;
25+
26+
std::unique_ptr<StringBuffer> ToProtocolString(Isolate* isolate,
27+
Local<Value> value) {
28+
TwoByteValue buffer(isolate, value);
29+
return StringBuffer::create(StringView(*buffer, buffer.length()));
30+
}
31+
32+
class V8CoverageConnection : public BaseObject {
33+
public:
34+
class V8CoverageSessionDelegate : public inspector::InspectorSessionDelegate {
35+
public:
36+
explicit V8CoverageSessionDelegate(V8CoverageConnection* connection)
37+
: connection_(connection) {}
38+
39+
void SendMessageToFrontend(
40+
const v8_inspector::StringView& message) override {
41+
Environment* env = connection_->env_;
42+
Debug(env,
43+
DebugCategory::COVERAGE,
44+
"Sending message to frontend, ending = %s\n",
45+
connection_->ending_ ? "true" : "false");
46+
if (!connection_->ending_) {
47+
return;
48+
}
49+
Isolate* isolate = env->isolate();
50+
Local<Context> context = env->context();
51+
52+
HandleScope handle_scope(isolate);
53+
Context::Scope context_scope(env->context());
54+
MaybeLocal<String> v8string =
55+
String::NewFromTwoByte(isolate,
56+
message.characters16(),
57+
NewStringType::kNormal,
58+
message.length());
59+
Local<Value> result = v8string.ToLocalChecked().As<Value>();
60+
Local<Function> fn = connection_->env_->on_coverage_message_function();
61+
CHECK(!fn.IsEmpty());
62+
USE(fn->Call(context, v8::Null(isolate), 1, &result));
63+
}
64+
65+
private:
66+
V8CoverageConnection* connection_;
67+
};
68+
69+
SET_MEMORY_INFO_NAME(V8CoverageConnection)
70+
SET_SELF_SIZE(V8CoverageConnection)
71+
72+
void MemoryInfo(MemoryTracker* tracker) const override {
73+
tracker->TrackFieldWithSize(
74+
"session", sizeof(*session_), "InspectorSession");
75+
}
76+
77+
explicit V8CoverageConnection(Environment* env)
78+
: BaseObject(env, env->coverage_connection()),
79+
env_(env),
80+
session_(nullptr),
81+
ending_(false) {
82+
inspector::Agent* inspector = env->inspector_agent();
83+
std::unique_ptr<inspector::InspectorSession> session =
84+
inspector->Connect(std::unique_ptr<V8CoverageSessionDelegate>(
85+
new V8CoverageSessionDelegate(this)),
86+
false);
87+
session_.reset(session.release());
88+
MakeWeak();
89+
}
90+
91+
void Start() {
92+
Debug(env_,
93+
DebugCategory::COVERAGE,
94+
"Sending Profiler.startPreciseCoverage\n");
95+
Isolate* isolate = env_->isolate();
96+
Local<Value> enable = FIXED_ONE_BYTE_STRING(
97+
isolate, "{\"id\": 1, \"method\": \"Profiler.enable\"}");
98+
Local<Value> start = FIXED_ONE_BYTE_STRING(
99+
isolate,
100+
"{"
101+
"\"id\": 2,"
102+
"\"method\": \"Profiler.startPreciseCoverage\","
103+
"\"params\": {\"callCount\": true, \"detailed\": true}"
104+
"}");
105+
session_->Dispatch(ToProtocolString(isolate, enable)->string());
106+
session_->Dispatch(ToProtocolString(isolate, start)->string());
107+
}
108+
109+
void End() {
110+
Debug(env_,
111+
DebugCategory::COVERAGE,
112+
"Sending Profiler.takePreciseCoverage\n");
113+
Isolate* isolate = env_->isolate();
114+
Local<Value> end =
115+
FIXED_ONE_BYTE_STRING(isolate,
116+
"{"
117+
"\"id\": 3,"
118+
"\"method\": \"Profiler.takePreciseCoverage\""
119+
"}");
120+
ending_ = true;
121+
session_->Dispatch(ToProtocolString(isolate, end)->string());
122+
}
123+
124+
friend class V8CoverageSessionDelegate;
125+
126+
private:
127+
Environment* env_;
128+
std::unique_ptr<inspector::InspectorSession> session_;
129+
bool ending_;
130+
};
131+
132+
bool StartCoverageCollection(Environment* env) {
133+
HandleScope scope(env->isolate());
134+
135+
Local<ObjectTemplate> t = ObjectTemplate::New(env->isolate());
136+
t->SetInternalFieldCount(1);
137+
Local<Object> obj;
138+
if (!t->NewInstance(env->context()).ToLocal(&obj)) {
139+
return false;
140+
}
141+
142+
obj->SetAlignedPointerInInternalField(0, nullptr);
143+
144+
CHECK(env->coverage_connection().IsEmpty());
145+
env->set_coverage_connection(obj);
146+
V8CoverageConnection* connection = new V8CoverageConnection(env);
147+
connection->Start();
148+
return true;
149+
}
150+
151+
static void EndCoverageCollection(const FunctionCallbackInfo<Value>& args) {
152+
Environment* env = Environment::GetCurrent(args);
153+
CHECK(args[0]->IsFunction());
154+
Debug(env, DebugCategory::COVERAGE, "Ending coverage collection\n");
155+
env->set_on_coverage_message_function(args[0].As<Function>());
156+
V8CoverageConnection* connection =
157+
Unwrap<V8CoverageConnection>(env->coverage_connection());
158+
CHECK_NOT_NULL(connection);
159+
connection->End();
160+
}
161+
162+
static void Initialize(Local<Object> target,
163+
Local<Value> unused,
164+
Local<Context> context,
165+
void* priv) {
166+
Environment* env = Environment::GetCurrent(context);
167+
env->SetMethod(target, "end", EndCoverageCollection);
168+
}
169+
} // namespace coverage
170+
} // namespace node
171+
172+
NODE_MODULE_CONTEXT_AWARE_INTERNAL(coverage, node::coverage::Initialize)

src/node.cc

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
2020
// USE OR OTHER DEALINGS IN THE SOFTWARE.
2121

22+
#include "debug_utils.h"
2223
#include "node_binding.h"
2324
#include "node_buffer.h"
2425
#include "node_constants.h"
@@ -230,6 +231,18 @@ MaybeLocal<Value> RunBootstrapping(Environment* env) {
230231
Isolate* isolate = env->isolate();
231232
Local<Context> context = env->context();
232233

234+
std::string coverage;
235+
bool rc = credentials::SafeGetenv("NODE_V8_COVERAGE", &coverage);
236+
if (rc && !coverage.empty()) {
237+
#if HAVE_INSPECTOR
238+
if (!coverage::StartCoverageCollection(env)) {
239+
return MaybeLocal<Value>();
240+
}
241+
#else
242+
fprintf(stderr, 'NODE_V8_COVERAGE cannot be used without inspector');
243+
#endif // HAVE_INSPECTOR
244+
}
245+
233246
// Add a reference to the global object
234247
Local<Object> global = context->Global();
235248

src/node_binding.cc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
V(cares_wrap) \
3434
V(config) \
3535
V(contextify) \
36+
V(coverage) \
3637
V(credentials) \
3738
V(domain) \
3839
V(fs) \

src/node_internals.h

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -269,7 +269,9 @@ void DefineZlibConstants(v8::Local<v8::Object> target);
269269
v8::MaybeLocal<v8::Value> RunBootstrapping(Environment* env);
270270
v8::MaybeLocal<v8::Value> StartExecution(Environment* env,
271271
const char* main_script_id);
272-
272+
namespace coverage {
273+
bool StartCoverageCollection(Environment* env);
274+
}
273275
} // namespace node
274276

275277
#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS

0 commit comments

Comments
 (0)