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

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

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

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

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

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

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

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