GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/node_native_module.cc Lines: 96 102 94.1 %
Date: 2021-05-02 04:12:27 Branches: 42 50 84.0 %

Line Branch Exec Source
1
#include "node_native_module.h"
2
#include "util-inl.h"
3
4
namespace node {
5
namespace native_module {
6
7
using v8::Context;
8
using v8::EscapableHandleScope;
9
using v8::Function;
10
using v8::Isolate;
11
using v8::Local;
12
using v8::MaybeLocal;
13
using v8::Object;
14
using v8::ScriptCompiler;
15
using v8::ScriptOrigin;
16
using v8::String;
17
18
4829
NativeModuleLoader NativeModuleLoader::instance_;
19
20
4829
NativeModuleLoader::NativeModuleLoader() : config_(GetConfig()) {
21
4829
  LoadJavaScriptSource();
22
4829
}
23
24
400751
NativeModuleLoader* NativeModuleLoader::GetInstance() {
25
400751
  return &instance_;
26
}
27
28
15
bool NativeModuleLoader::Exists(const char* id) {
29
15
  return source_.find(id) != source_.end();
30
}
31
32
15
bool NativeModuleLoader::Add(const char* id, const UnionBytes& source) {
33
15
  if (Exists(id)) {
34
    return false;
35
  }
36
15
  source_.emplace(id, source);
37
15
  return true;
38
}
39
40
33
Local<Object> NativeModuleLoader::GetSourceObject(Local<Context> context) {
41
33
  Isolate* isolate = context->GetIsolate();
42
33
  Local<Object> out = Object::New(isolate);
43
8646
  for (auto const& x : source_) {
44
8613
    Local<String> key = OneByteString(isolate, x.first.c_str(), x.first.size());
45
25839
    out->Set(context, key, x.second.ToStringChecked(isolate)).FromJust();
46
  }
47
33
  return out;
48
}
49
50
494
Local<String> NativeModuleLoader::GetConfigString(Isolate* isolate) {
51
494
  return config_.ToStringChecked(isolate);
52
}
53
54
469
std::vector<std::string> NativeModuleLoader::GetModuleIds() {
55
469
  std::vector<std::string> ids;
56
469
  ids.reserve(source_.size());
57
122894
  for (auto const& x : source_) {
58
122396
    ids.emplace_back(x.first);
59
  }
60
469
  return ids;
61
}
62
63
2090
void NativeModuleLoader::InitializeModuleCategories() {
64
2090
  if (module_categories_.is_initialized) {
65
    DCHECK(!module_categories_.can_be_required.empty());
66
2081
    return;
67
  }
68
69
  std::vector<std::string> prefixes = {
70
#if !HAVE_OPENSSL
71
    "internal/crypto/",
72
#endif  // !HAVE_OPENSSL
73
74
    "internal/bootstrap/",
75
    "internal/per_context/",
76
    "internal/deps/",
77
    "internal/main/"
78
18
  };
79
80
  module_categories_.can_be_required.emplace(
81
9
      "internal/deps/cjs-module-lexer/lexer");
82
83
63
  module_categories_.cannot_be_required = std::set<std::string> {
84
#if !HAVE_INSPECTOR
85
      "inspector",
86
      "internal/util/inspector",
87
#endif  // !HAVE_INSPECTOR
88
89
#if !NODE_USE_V8_PLATFORM || !defined(NODE_HAVE_I18N_SUPPORT)
90
      "trace_events",
91
#endif  // !NODE_USE_V8_PLATFORM
92
93
#if !HAVE_OPENSSL
94
      "crypto",
95
      "crypto/promises",
96
      "https",
97
      "http2",
98
      "tls",
99
      "_tls_common",
100
      "_tls_wrap",
101
      "internal/tls",
102
      "internal/http2/core",
103
      "internal/http2/compat",
104
      "internal/policy/manifest",
105
      "internal/process/policy",
106
      "internal/streams/lazy_transform",
107
#endif  // !HAVE_OPENSSL
108
      "sys",  // Deprecated.
109
      "wasi",  // Experimental.
110
      "internal/test/binding",
111
      "internal/v8_prof_polyfill",
112
      "internal/v8_prof_processor",
113
54
  };
114
115
2358
  for (auto const& x : source_) {
116
2349
    const std::string& id = x.first;
117
11745
    for (auto const& prefix : prefixes) {
118
9396
      if (prefix.length() > id.length()) {
119
3060
        continue;
120
      }
121

6687
      if (id.find(prefix) == 0 &&
122
351
          module_categories_.can_be_required.count(id) == 0) {
123
342
        module_categories_.cannot_be_required.emplace(id);
124
      }
125
    }
126
  }
127
128
2358
  for (auto const& x : source_) {
129
2349
    const std::string& id = x.first;
130
2349
    if (0 == module_categories_.cannot_be_required.count(id)) {
131
1962
      module_categories_.can_be_required.emplace(id);
132
    }
133
  }
134
135
9
  module_categories_.is_initialized = true;
136
}
137
138
1
const std::set<std::string>& NativeModuleLoader::GetCannotBeRequired() {
139
1
  InitializeModuleCategories();
140
1
  return module_categories_.cannot_be_required;
141
}
142
143
2089
const std::set<std::string>& NativeModuleLoader::GetCanBeRequired() {
144
2089
  InitializeModuleCategories();
145
2089
  return module_categories_.can_be_required;
146
}
147
148
2088
bool NativeModuleLoader::CanBeRequired(const char* id) {
149
2088
  return GetCanBeRequired().count(id) == 1;
150
}
151
152
bool NativeModuleLoader::CannotBeRequired(const char* id) {
153
  return GetCannotBeRequired().count(id) == 1;
154
}
155
156
4761
NativeModuleCacheMap* NativeModuleLoader::code_cache() {
157
4761
  return &code_cache_;
158
}
159
160
1744
ScriptCompiler::CachedData* NativeModuleLoader::GetCodeCache(
161
    const char* id) const {
162
3488
  Mutex::ScopedLock lock(code_cache_mutex_);
163
1744
  const auto it = code_cache_.find(id);
164
1744
  if (it == code_cache_.end()) {
165
    // The module has not been compiled before.
166
    return nullptr;
167
  }
168
1744
  return it->second.get();
169
}
170
171
386867
MaybeLocal<Function> NativeModuleLoader::CompileAsModule(
172
    Local<Context> context,
173
    const char* id,
174
    NativeModuleLoader::Result* result) {
175
386867
  Isolate* isolate = context->GetIsolate();
176
  std::vector<Local<String>> parameters = {
177
      FIXED_ONE_BYTE_STRING(isolate, "exports"),
178
      FIXED_ONE_BYTE_STRING(isolate, "require"),
179
      FIXED_ONE_BYTE_STRING(isolate, "module"),
180
      FIXED_ONE_BYTE_STRING(isolate, "process"),
181
      FIXED_ONE_BYTE_STRING(isolate, "internalBinding"),
182
773772
      FIXED_ONE_BYTE_STRING(isolate, "primordials")};
183
773767
  return LookupAndCompile(context, id, &parameters, result);
184
}
185
186
#ifdef NODE_BUILTIN_MODULES_PATH
187
static std::string OnDiskFileName(const char* id) {
188
  std::string filename = NODE_BUILTIN_MODULES_PATH;
189
  filename += "/";
190
191
  if (strncmp(id, "internal/deps", strlen("internal/deps")) == 0) {
192
    id += strlen("internal/");
193
  } else {
194
    filename += "lib/";
195
  }
196
  filename += id;
197
  filename += ".js";
198
199
  return filename;
200
}
201
#endif  // NODE_BUILTIN_MODULES_PATH
202
203
396732
MaybeLocal<String> NativeModuleLoader::LoadBuiltinModuleSource(Isolate* isolate,
204
                                                               const char* id) {
205
#ifdef NODE_BUILTIN_MODULES_PATH
206
  std::string filename = OnDiskFileName(id);
207
208
  uv_fs_t req;
209
  uv_file file =
210
      uv_fs_open(nullptr, &req, filename.c_str(), O_RDONLY, 0, nullptr);
211
  CHECK_GE(req.result, 0);
212
  uv_fs_req_cleanup(&req);
213
214
  auto defer_close = OnScopeLeave([file]() {
215
    uv_fs_t close_req;
216
    CHECK_EQ(0, uv_fs_close(nullptr, &close_req, file, nullptr));
217
    uv_fs_req_cleanup(&close_req);
218
  });
219
220
  std::string contents;
221
  char buffer[4096];
222
  uv_buf_t buf = uv_buf_init(buffer, sizeof(buffer));
223
224
  while (true) {
225
    const int r =
226
        uv_fs_read(nullptr, &req, file, &buf, 1, contents.length(), nullptr);
227
    CHECK_GE(req.result, 0);
228
    uv_fs_req_cleanup(&req);
229
    if (r <= 0) {
230
      break;
231
    }
232
    contents.append(buf.base, r);
233
  }
234
235
  return String::NewFromUtf8(
236
      isolate, contents.c_str(), v8::NewStringType::kNormal, contents.length());
237
#else
238
396732
  const auto source_it = source_.find(id);
239
396742
  CHECK_NE(source_it, source_.end());
240
793459
  return source_it->second.ToStringChecked(isolate);
241
#endif  // NODE_BUILTIN_MODULES_PATH
242
}
243
244
// Returns Local<Function> of the compiled module if return_code_cache
245
// is false (we are only compiling the function).
246
// Otherwise return a Local<Object> containing the cache.
247
396717
MaybeLocal<Function> NativeModuleLoader::LookupAndCompile(
248
    Local<Context> context,
249
    const char* id,
250
    std::vector<Local<String>>* parameters,
251
    NativeModuleLoader::Result* result) {
252
396717
  Isolate* isolate = context->GetIsolate();
253
396723
  EscapableHandleScope scope(isolate);
254
255
  Local<String> source;
256
793459
  if (!LoadBuiltinModuleSource(isolate, id).ToLocal(&source)) {
257
    return {};
258
  }
259
260
793488
  std::string filename_s = std::string("node:") + id;
261
  Local<String> filename =
262
396739
      OneByteString(isolate, filename_s.c_str(), filename_s.size());
263
396736
  ScriptOrigin origin(isolate, filename, 0, 0, true);
264
265
396736
  ScriptCompiler::CachedData* cached_data = nullptr;
266
  {
267
    // Note: The lock here should not extend into the
268
    // `CompileFunctionInContext()` call below, because this function may
269
    // recurse if there is a syntax error during bootstrap (because the fatal
270
    // exception handler is invoked, which may load built-in modules).
271
793493
    Mutex::ScopedLock lock(code_cache_mutex_);
272
396757
    auto cache_it = code_cache_.find(id);
273
396757
    if (cache_it != code_cache_.end()) {
274
      // Transfer ownership to ScriptCompiler::Source later.
275
381415
      cached_data = cache_it->second.release();
276
381415
      code_cache_.erase(cache_it);
277
    }
278
  }
279
280
396755
  const bool has_cache = cached_data != nullptr;
281
  ScriptCompiler::CompileOptions options =
282
396755
      has_cache ? ScriptCompiler::kConsumeCodeCache
283
396755
                : ScriptCompiler::kEagerCompile;
284
  ScriptCompiler::Source script_source(source, origin, cached_data);
285
286
  MaybeLocal<Function> maybe_fun =
287
      ScriptCompiler::CompileFunctionInContext(context,
288
                                               &script_source,
289
                                               parameters->size(),
290
                                               parameters->data(),
291
                                               0,
292
                                               nullptr,
293
396755
                                               options);
294
295
  // This could fail when there are early errors in the native modules,
296
  // e.g. the syntax errors
297
  Local<Function> fun;
298
396751
  if (!maybe_fun.ToLocal(&fun)) {
299
    // In the case of early errors, v8 is already capable of
300
    // decorating the stack for us - note that we use CompileFunctionInContext
301
    // so there is no need to worry about wrappers.
302
    return MaybeLocal<Function>();
303
  }
304
305
  // XXX(joyeecheung): this bookkeeping is not exactly accurate because
306
  // it only starts after the Environment is created, so the per_context.js
307
  // will never be in any of these two sets, but the two sets are only for
308
  // testing anyway.
309
310
778160
  *result = (has_cache && !script_source.GetCachedData()->rejected)
311
769083
                ? Result::kWithCache
312
                : Result::kWithoutCache;
313
  // Generate new cache for next compilation
314
  std::unique_ptr<ScriptCompiler::CachedData> new_cached_data(
315
793508
      ScriptCompiler::CreateCodeCacheForFunction(fun));
316
396734
  CHECK_NOT_NULL(new_cached_data);
317
318
  {
319
793496
    Mutex::ScopedLock lock(code_cache_mutex_);
320
    // The old entry should've been erased by now so we can just emplace.
321
    // If another thread did the same thing in the meantime, that should not
322
    // be an issue.
323
396757
    code_cache_.emplace(id, std::move(new_cached_data));
324
  }
325
326
396757
  return scope.Escape(fun);
327
}
328
329
}  // namespace native_module
330

14487
}  // namespace node