GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_dir.cc Lines: 161 181 89.0 %
Date: 2021-09-15 04:12:31 Branches: 47 100 47.0 %

Line Branch Exec Source
1
#include "node_dir.h"
2
#include "node_external_reference.h"
3
#include "node_file-inl.h"
4
#include "node_process-inl.h"
5
#include "memory_tracker-inl.h"
6
#include "util.h"
7
8
#include "tracing/trace_event.h"
9
10
#include "string_bytes.h"
11
12
#include <fcntl.h>
13
#include <sys/types.h>
14
#include <sys/stat.h>
15
#include <cstring>
16
#include <cerrno>
17
#include <climits>
18
19
#include <memory>
20
21
namespace node {
22
23
namespace fs_dir {
24
25
using fs::FSReqAfterScope;
26
using fs::FSReqBase;
27
using fs::FSReqWrapSync;
28
using fs::GetReqWrap;
29
30
using v8::Array;
31
using v8::Context;
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::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
26
DirHandle::DirHandle(Environment* env, Local<Object> obj, uv_dir_t* dir)
59
    : AsyncWrap(env, obj, AsyncWrap::PROVIDER_DIRHANDLE),
60
26
      dir_(dir) {
61
26
  MakeWeak();
62
63
26
  dir_->nentries = 0;
64
26
  dir_->dirents = nullptr;
65
26
}
66
67
26
DirHandle* DirHandle::New(Environment* env, uv_dir_t* dir) {
68
  Local<Object> obj;
69
26
  if (!env->dir_instance_template()
70
26
          ->NewInstance(env->context())
71
26
          .ToLocal(&obj)) {
72
    return nullptr;
73
  }
74
75
26
  return new DirHandle(env, obj, dir);
76
}
77
78
void DirHandle::New(const FunctionCallbackInfo<Value>& args) {
79
  CHECK(args.IsConstructCall());
80
}
81
82
104
DirHandle::~DirHandle() {
83
52
  CHECK(!closing_);  // We should not be deleting while explicitly closing!
84
52
  GCClose();         // Close synchronously and emit warning
85
52
  CHECK(closed_);    // We have to be closed at the point
86
104
}
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
26
inline void DirHandle::GCClose() {
97
26
  if (closed_) return;
98
  uv_fs_t req;
99
12
  int ret = uv_fs_closedir(nullptr, &req, dir_, nullptr);
100
12
  uv_fs_req_cleanup(&req);
101
12
  closing_ = false;
102
12
  closed_ = true;
103
104
  struct err_detail { int ret; };
105
106
12
  err_detail detail { ret };
107
108
12
  if (ret < 0) {
109
    // Do not unref this
110
    env()->SetImmediate([detail](Environment* env) {
111
      const char* msg = "Closing directory handle on garbage collection failed";
112
      // This exception will end up being fatal for the process because
113
      // it is being thrown from within the SetImmediate handler and
114
      // there is no JS stack to bubble it to. In other words, tearing
115
      // down the process is the only reasonable thing we can do here.
116
      HandleScope handle_scope(env->isolate());
117
      env->ThrowUVException(detail.ret, "close", msg);
118
    });
119
    return;
120
  }
121
122
  // If the close was successful, we still want to emit a process warning
123
  // to notify that the file descriptor was gc'd. We want to be noisy about
124
  // this because not explicitly closing the DirHandle is a bug.
125
126
12
  env()->SetImmediate([](Environment* env) {
127
    ProcessEmitWarning(env,
128
6
                       "Closing directory handle on garbage collection");
129
6
  }, CallbackFlags::kUnrefed);
130
}
131
132
9
void AfterClose(uv_fs_t* req) {
133
9
  FSReqBase* req_wrap = FSReqBase::from_req(req);
134
18
  FSReqAfterScope after(req_wrap, req);
135
136
9
  if (after.Proceed())
137
18
    req_wrap->Resolve(Undefined(req_wrap->env()->isolate()));
138
9
}
139
140
14
void DirHandle::Close(const FunctionCallbackInfo<Value>& args) {
141
14
  Environment* env = Environment::GetCurrent(args);
142
143
14
  const int argc = args.Length();
144
14
  CHECK_GE(argc, 1);
145
146
  DirHandle* dir;
147
14
  ASSIGN_OR_RETURN_UNWRAP(&dir, args.Holder());
148
149
14
  dir->closing_ = false;
150
14
  dir->closed_ = true;
151
152
14
  FSReqBase* req_wrap_async = GetReqWrap(args, 0);
153
14
  if (req_wrap_async != nullptr) {  // close(req)
154
9
    AsyncCall(env, req_wrap_async, args, "closedir", UTF8, AfterClose,
155
              uv_fs_closedir, dir->dir());
156
  } else {  // close(undefined, ctx)
157
5
    CHECK_EQ(argc, 2);
158
10
    FSReqWrapSync req_wrap_sync;
159

5
    FS_DIR_SYNC_TRACE_BEGIN(closedir);
160
10
    SyncCall(env, args[1], &req_wrap_sync, "closedir", uv_fs_closedir,
161
             dir->dir());
162

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

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

3
    FS_DIR_SYNC_TRACE_END(readdir);
268
3
    if (err < 0) {
269
      return;  // syscall failed, no need to continue, error info is in ctx
270
    }
271
272
3
    if (req_wrap_sync.req.result == 0) {
273
      // Done
274
1
      Local<Value> done = Null(isolate);
275
1
      args.GetReturnValue().Set(done);
276
1
      return;
277
    }
278
279
2
    CHECK_GE(req_wrap_sync.req.result, 0);
280
281
    Local<Value> error;
282
    Local<Array> js_array;
283
2
    if (!DirentListToArray(env,
284
2
                           dir->dir()->dirents,
285
2
                           static_cast<int>(req_wrap_sync.req.result),
286
                           encoding,
287
2
                           &error)
288
2
             .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
12
  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
28
static void OpenDir(const FunctionCallbackInfo<Value>& args) {
315
28
  Environment* env = Environment::GetCurrent(args);
316
28
  Isolate* isolate = env->isolate();
317
318
28
  const int argc = args.Length();
319
28
  CHECK_GE(argc, 3);
320
321
28
  BufferValue path(isolate, args[0]);
322
28
  CHECK_NOT_NULL(*path);
323
324
28
  const enum encoding encoding = ParseEncoding(isolate, args[1], UTF8);
325
326
28
  FSReqBase* req_wrap_async = GetReqWrap(args, 2);
327
28
  if (req_wrap_async != nullptr) {  // openDir(path, encoding, req)
328
12
    AsyncCall(env, req_wrap_async, args, "opendir", encoding, AfterOpenDir,
329
              uv_fs_opendir, *path);
330
  } else {  // openDir(path, encoding, undefined, ctx)
331
16
    CHECK_EQ(argc, 4);
332
16
    FSReqWrapSync req_wrap_sync;
333

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

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