GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/node_dir.cc Lines: 160 181 88.4 %
Date: 2020-05-27 22:15:15 Branches: 61 116 52.6 %

Line Branch Exec Source
1
#include "node_dir.h"
2
#include "node_file-inl.h"
3
#include "node_process.h"
4
#include "memory_tracker-inl.h"
5
#include "util.h"
6
7
#include "tracing/trace_event.h"
8
9
#include "string_bytes.h"
10
11
#include <fcntl.h>
12
#include <sys/types.h>
13
#include <sys/stat.h>
14
#include <cstring>
15
#include <cerrno>
16
#include <climits>
17
18
#include <memory>
19
20
namespace node {
21
22
namespace fs_dir {
23
24
using fs::FSReqAfterScope;
25
using fs::FSReqBase;
26
using fs::FSReqWrapSync;
27
using fs::GetReqWrap;
28
29
using v8::Array;
30
using v8::Context;
31
using v8::Function;
32
using v8::FunctionCallbackInfo;
33
using v8::FunctionTemplate;
34
using v8::HandleScope;
35
using v8::Integer;
36
using v8::Isolate;
37
using v8::Local;
38
using v8::MaybeLocal;
39
using v8::Null;
40
using v8::Number;
41
using v8::Object;
42
using v8::ObjectTemplate;
43
using v8::String;
44
using v8::Value;
45
46
#define TRACE_NAME(name) "fs_dir.sync." #name
47
#define GET_TRACE_ENABLED                                                      \
48
  (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED                                 \
49
  (TRACING_CATEGORY_NODE2(fs_dir, sync)) != 0)
50
#define FS_DIR_SYNC_TRACE_BEGIN(syscall, ...)                                  \
51
  if (GET_TRACE_ENABLED)                                                       \
52
  TRACE_EVENT_BEGIN(TRACING_CATEGORY_NODE2(fs_dir, sync), TRACE_NAME(syscall), \
53
  ##__VA_ARGS__);
54
#define FS_DIR_SYNC_TRACE_END(syscall, ...)                                    \
55
  if (GET_TRACE_ENABLED)                                                       \
56
  TRACE_EVENT_END(TRACING_CATEGORY_NODE2(fs_dir, sync), TRACE_NAME(syscall),   \
57
  ##__VA_ARGS__);
58
59
23
DirHandle::DirHandle(Environment* env, Local<Object> obj, uv_dir_t* dir)
60
    : AsyncWrap(env, obj, AsyncWrap::PROVIDER_DIRHANDLE),
61
23
      dir_(dir) {
62
23
  MakeWeak();
63
64
23
  dir_->nentries = 0;
65
23
  dir_->dirents = nullptr;
66
23
}
67
68
23
DirHandle* DirHandle::New(Environment* env, uv_dir_t* dir) {
69
  Local<Object> obj;
70
69
  if (!env->dir_instance_template()
71
69
          ->NewInstance(env->context())
72
23
          .ToLocal(&obj)) {
73
    return nullptr;
74
  }
75
76
23
  return new DirHandle(env, obj, dir);
77
}
78
79
void DirHandle::New(const FunctionCallbackInfo<Value>& args) {
80
  CHECK(args.IsConstructCall());
81
}
82
83
69
DirHandle::~DirHandle() {
84
23
  CHECK(!closing_);  // We should not be deleting while explicitly closing!
85
23
  GCClose();         // Close synchronously and emit warning
86
23
  CHECK(closed_);    // We have to be closed at the point
87
46
}
88
89
void DirHandle::MemoryInfo(MemoryTracker* tracker) const {
90
  tracker->TrackFieldWithSize("dir", sizeof(*dir_));
91
}
92
93
// Close the directory handle if it hasn't already been closed. A process
94
// warning will be emitted using a SetImmediate to avoid calling back to
95
// JS during GC. If closing the fd fails at this point, a fatal exception
96
// will crash the process immediately.
97
23
inline void DirHandle::GCClose() {
98
35
  if (closed_) return;
99
  uv_fs_t req;
100
11
  int ret = uv_fs_closedir(nullptr, &req, dir_, nullptr);
101
11
  uv_fs_req_cleanup(&req);
102
11
  closing_ = false;
103
11
  closed_ = true;
104
105
  struct err_detail { int ret; };
106
107
11
  err_detail detail { ret };
108
109
11
  if (ret < 0) {
110
    // Do not unref this
111
    env()->SetImmediate([detail](Environment* env) {
112
      char msg[70];
113
      snprintf(msg, arraysize(msg),
114
              "Closing directory handle on garbage collection failed");
115
      // This exception will end up being fatal for the process because
116
      // it is being thrown from within the SetImmediate handler and
117
      // there is no JS stack to bubble it to. In other words, tearing
118
      // down the process is the only reasonable thing we can do here.
119
      HandleScope handle_scope(env->isolate());
120
      env->ThrowUVException(detail.ret, "close", msg);
121
    });
122
    return;
123
  }
124
125
  // If the close was successful, we still want to emit a process warning
126
  // to notify that the file descriptor was gc'd. We want to be noisy about
127
  // this because not explicitly closing the DirHandle is a bug.
128
129
33
  env()->SetImmediate([](Environment* env) {
130
    ProcessEmitWarning(env,
131
11
                       "Closing directory handle on garbage collection");
132
22
  }, CallbackFlags::kUnrefed);
133
}
134
135
9
void AfterClose(uv_fs_t* req) {
136
9
  FSReqBase* req_wrap = FSReqBase::from_req(req);
137
18
  FSReqAfterScope after(req_wrap, req);
138
139
9
  if (after.Proceed())
140
18
    req_wrap->Resolve(Undefined(req_wrap->env()->isolate()));
141
9
}
142
143
12
void DirHandle::Close(const FunctionCallbackInfo<Value>& args) {
144
12
  Environment* env = Environment::GetCurrent(args);
145
146
12
  const int argc = args.Length();
147
12
  CHECK_GE(argc, 1);
148
149
  DirHandle* dir;
150
12
  ASSIGN_OR_RETURN_UNWRAP(&dir, args.Holder());
151
152
12
  dir->closing_ = false;
153
12
  dir->closed_ = true;
154
155
12
  FSReqBase* req_wrap_async = GetReqWrap(args, 0);
156
12
  if (req_wrap_async != nullptr) {  // close(req)
157
9
    AsyncCall(env, req_wrap_async, args, "closedir", UTF8, AfterClose,
158
9
              uv_fs_closedir, dir->dir());
159
  } else {  // close(undefined, ctx)
160
3
    CHECK_EQ(argc, 2);
161
6
    FSReqWrapSync req_wrap_sync;
162

3
    FS_DIR_SYNC_TRACE_BEGIN(closedir);
163
3
    SyncCall(env, args[1], &req_wrap_sync, "closedir", uv_fs_closedir,
164
3
             dir->dir());
165

3
    FS_DIR_SYNC_TRACE_END(closedir);
166
  }
167
}
168
169
11
static MaybeLocal<Array> DirentListToArray(
170
    Environment* env,
171
    uv_dirent_t* ents,
172
    int num,
173
    enum encoding encoding,
174
    Local<Value>* err_out) {
175
22
  MaybeStackBuffer<Local<Value>, 64> entries(num * 2);
176
177
  // Return an array of all read filenames.
178
11
  int j = 0;
179
66
  for (int i = 0; i < num; i++) {
180
    Local<Value> filename;
181
    Local<Value> error;
182
55
    const size_t namelen = strlen(ents[i].name);
183
110
    if (!StringBytes::Encode(env->isolate(),
184
55
                             ents[i].name,
185
                             namelen,
186
                             encoding,
187
110
                             &error).ToLocal(&filename)) {
188
      *err_out = error;
189
      return MaybeLocal<Array>();
190
    }
191
192
55
    entries[j++] = filename;
193
110
    entries[j++] = Integer::New(env->isolate(), ents[i].type);
194
  }
195
196
22
  return Array::New(env->isolate(), entries.out(), j);
197
}
198
199
11
static void AfterDirRead(uv_fs_t* req) {
200
20
  BaseObjectPtr<FSReqBase> req_wrap { FSReqBase::from_req(req) };
201
20
  FSReqAfterScope after(req_wrap.get(), req);
202
203
11
  if (!after.Proceed()) {
204
    return;
205
  }
206
207
11
  Environment* env = req_wrap->env();
208
11
  Isolate* isolate = env->isolate();
209
210
11
  if (req->result == 0) {
211
    // Done
212
    Local<Value> done = Null(isolate);
213
2
    after.Clear();
214
2
    req_wrap->Resolve(done);
215
2
    return;
216
  }
217
218
9
  uv_dir_t* dir = static_cast<uv_dir_t*>(req->ptr);
219
220
  Local<Value> error;
221
  Local<Array> js_array;
222
18
  if (!DirentListToArray(env,
223
                         dir->dirents,
224
9
                         req->result,
225
                         req_wrap->encoding(),
226
27
                         &error).ToLocal(&js_array)) {
227
    // Clear libuv resources *before* delivering results to JS land because
228
    // that can schedule another operation on the same uv_dir_t. Ditto below.
229
    after.Clear();
230
    return req_wrap->Reject(error);
231
  }
232
233
9
  after.Clear();
234
18
  req_wrap->Resolve(js_array);
235
}
236
237
238
14
void DirHandle::Read(const FunctionCallbackInfo<Value>& args) {
239
14
  Environment* env = Environment::GetCurrent(args);
240
14
  Isolate* isolate = env->isolate();
241
242
14
  const int argc = args.Length();
243
14
  CHECK_GE(argc, 3);
244
245
14
  const enum encoding encoding = ParseEncoding(isolate, args[0], UTF8);
246
247
  DirHandle* dir;
248
15
  ASSIGN_OR_RETURN_UNWRAP(&dir, args.Holder());
249
250
28
  CHECK(args[1]->IsNumber());
251
42
  uint64_t buffer_size = args[1].As<Number>()->Value();
252
253
14
  if (buffer_size != dir->dirents_.size()) {
254
11
    dir->dirents_.resize(buffer_size);
255
11
    dir->dir_->nentries = buffer_size;
256
11
    dir->dir_->dirents = dir->dirents_.data();
257
  }
258
259
14
  FSReqBase* req_wrap_async = GetReqWrap(args, 2);
260
14
  if (req_wrap_async != nullptr) {  // dir.read(encoding, bufferSize, req)
261
11
    AsyncCall(env, req_wrap_async, args, "readdir", encoding,
262
11
              AfterDirRead, uv_fs_readdir, dir->dir());
263
  } else {  // dir.read(encoding, bufferSize, undefined, ctx)
264
3
    CHECK_EQ(argc, 4);
265
5
    FSReqWrapSync req_wrap_sync;
266

3
    FS_DIR_SYNC_TRACE_BEGIN(readdir);
267
3
    int err = SyncCall(env, args[3], &req_wrap_sync, "readdir", uv_fs_readdir,
268
3
                       dir->dir());
269

3
    FS_DIR_SYNC_TRACE_END(readdir);
270
3
    if (err < 0) {
271
      return;  // syscall failed, no need to continue, error info is in ctx
272
    }
273
274
3
    if (req_wrap_sync.req.result == 0) {
275
      // Done
276
      Local<Value> done = Null(isolate);
277
2
      args.GetReturnValue().Set(done);
278
1
      return;
279
    }
280
281
2
    CHECK_GE(req_wrap_sync.req.result, 0);
282
283
    Local<Value> error;
284
    Local<Array> js_array;
285
4
    if (!DirentListToArray(env,
286
2
                           dir->dir()->dirents,
287
2
                           req_wrap_sync.req.result,
288
                           encoding,
289
6
                           &error).ToLocal(&js_array)) {
290
      Local<Object> ctx = args[2].As<Object>();
291
      USE(ctx->Set(env->context(), env->error_string(), error));
292
      return;
293
    }
294
295
4
    args.GetReturnValue().Set(js_array);
296
  }
297
}
298
299
12
void AfterOpenDir(uv_fs_t* req) {
300
12
  FSReqBase* req_wrap = FSReqBase::from_req(req);
301
23
  FSReqAfterScope after(req_wrap, req);
302
303
12
  if (!after.Proceed()) {
304
1
    return;
305
  }
306
307
11
  Environment* env = req_wrap->env();
308
309
11
  uv_dir_t* dir = static_cast<uv_dir_t*>(req->ptr);
310
11
  DirHandle* handle = DirHandle::New(env, dir);
311
312
22
  req_wrap->Resolve(handle->object().As<Value>());
313
}
314
315
25
static void OpenDir(const FunctionCallbackInfo<Value>& args) {
316
25
  Environment* env = Environment::GetCurrent(args);
317
25
  Isolate* isolate = env->isolate();
318
319
25
  const int argc = args.Length();
320
25
  CHECK_GE(argc, 3);
321
322
49
  BufferValue path(isolate, args[0]);
323
25
  CHECK_NOT_NULL(*path);
324
325
25
  const enum encoding encoding = ParseEncoding(isolate, args[1], UTF8);
326
327
25
  FSReqBase* req_wrap_async = GetReqWrap(args, 2);
328
25
  if (req_wrap_async != nullptr) {  // openDir(path, encoding, req)
329
12
    AsyncCall(env, req_wrap_async, args, "opendir", encoding, AfterOpenDir,
330
12
              uv_fs_opendir, *path);
331
  } else {  // openDir(path, encoding, undefined, ctx)
332
13
    CHECK_EQ(argc, 4);
333
25
    FSReqWrapSync req_wrap_sync;
334

13
    FS_DIR_SYNC_TRACE_BEGIN(opendir);
335
13
    int result = SyncCall(env, args[3], &req_wrap_sync, "opendir",
336
13
                          uv_fs_opendir, *path);
337

13
    FS_DIR_SYNC_TRACE_END(opendir);
338
13
    if (result < 0) {
339
1
      return;  // syscall failed, no need to continue, error info is in ctx
340
    }
341
342
12
    uv_fs_t* req = &req_wrap_sync.req;
343
12
    uv_dir_t* dir = static_cast<uv_dir_t*>(req->ptr);
344
12
    DirHandle* handle = DirHandle::New(env, dir);
345
346
36
    args.GetReturnValue().Set(handle->object().As<Value>());
347
  }
348
}
349
350
4568
void Initialize(Local<Object> target,
351
                Local<Value> unused,
352
                Local<Context> context,
353
                void* priv) {
354
4568
  Environment* env = Environment::GetCurrent(context);
355
4568
  Isolate* isolate = env->isolate();
356
357
4568
  env->SetMethod(target, "opendir", OpenDir);
358
359
  // Create FunctionTemplate for DirHandle
360
4568
  Local<FunctionTemplate> dir = env->NewFunctionTemplate(DirHandle::New);
361
9136
  dir->Inherit(AsyncWrap::GetConstructorTemplate(env));
362
4568
  env->SetProtoMethod(dir, "read", DirHandle::Read);
363
4568
  env->SetProtoMethod(dir, "close", DirHandle::Close);
364
4568
  Local<ObjectTemplate> dirt = dir->InstanceTemplate();
365
4568
  dirt->SetInternalFieldCount(DirHandle::kInternalFieldCount);
366
  Local<String> handleString =
367
4568
       FIXED_ONE_BYTE_STRING(isolate, "DirHandle");
368
4568
  dir->SetClassName(handleString);
369
  target
370
9136
      ->Set(context, handleString,
371
18272
            dir->GetFunction(env->context()).ToLocalChecked())
372
      .FromJust();
373
4568
  env->set_dir_instance_template(dirt);
374
4568
}
375
376
}  // namespace fs_dir
377
378
}  // end namespace node
379
380

17303
NODE_MODULE_CONTEXT_AWARE_INTERNAL(fs_dir, node::fs_dir::Initialize)