GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_os.cc Lines: 187 213 87.8 %
Date: 2022-06-12 04:16:28 Branches: 44 96 45.8 %

Line Branch Exec Source
1
// Copyright Joyent, Inc. and other Node contributors.
2
//
3
// Permission is hereby granted, free of charge, to any person obtaining a
4
// copy of this software and associated documentation files (the
5
// "Software"), to deal in the Software without restriction, including
6
// without limitation the rights to use, copy, modify, merge, publish,
7
// distribute, sublicense, and/or sell copies of the Software, and to permit
8
// persons to whom the Software is furnished to do so, subject to the
9
// following conditions:
10
//
11
// The above copyright notice and this permission notice shall be included
12
// in all copies or substantial portions of the Software.
13
//
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
#include "env-inl.h"
23
#include "node_external_reference.h"
24
#include "string_bytes.h"
25
26
#ifdef __MINGW32__
27
# include <io.h>
28
#endif  // __MINGW32__
29
30
#ifdef __POSIX__
31
# include <unistd.h>        // gethostname, sysconf
32
# include <climits>         // PATH_MAX on Solaris.
33
#endif  // __POSIX__
34
35
#include <array>
36
#include <cerrno>
37
#include <cstring>
38
39
namespace node {
40
namespace os {
41
42
using v8::Array;
43
using v8::ArrayBuffer;
44
using v8::Boolean;
45
using v8::Context;
46
using v8::Float64Array;
47
using v8::FunctionCallbackInfo;
48
using v8::Int32;
49
using v8::Integer;
50
using v8::Isolate;
51
using v8::Local;
52
using v8::MaybeLocal;
53
using v8::NewStringType;
54
using v8::Null;
55
using v8::Number;
56
using v8::Object;
57
using v8::String;
58
using v8::Value;
59
60
61
32
static void GetHostname(const FunctionCallbackInfo<Value>& args) {
62
32
  Environment* env = Environment::GetCurrent(args);
63
  char buf[UV_MAXHOSTNAMESIZE];
64
32
  size_t size = sizeof(buf);
65
32
  int r = uv_os_gethostname(buf, &size);
66
67
32
  if (r != 0) {
68
    CHECK_GE(args.Length(), 1);
69
    env->CollectUVExceptionInfo(args[args.Length() - 1], r,
70
                                "uv_os_gethostname");
71
    return args.GetReturnValue().SetUndefined();
72
  }
73
74
96
  args.GetReturnValue().Set(
75
64
      String::NewFromUtf8(env->isolate(), buf).ToLocalChecked());
76
}
77
78
620
static void GetOSInformation(const FunctionCallbackInfo<Value>& args) {
79
620
  Environment* env = Environment::GetCurrent(args);
80
  uv_utsname_t info;
81
620
  int err = uv_os_uname(&info);
82
83
620
  if (err != 0) {
84
    CHECK_GE(args.Length(), 1);
85
    env->CollectUVExceptionInfo(args[args.Length() - 1], err, "uv_os_uname");
86
    return args.GetReturnValue().SetUndefined();
87
  }
88
89
  // [sysname, version, release]
90
  Local<Value> osInformation[] = {
91
620
    String::NewFromUtf8(env->isolate(), info.sysname).ToLocalChecked(),
92
620
    String::NewFromUtf8(env->isolate(), info.version).ToLocalChecked(),
93
620
    String::NewFromUtf8(env->isolate(), info.release).ToLocalChecked()
94
2480
  };
95
96
1240
  args.GetReturnValue().Set(Array::New(env->isolate(),
97
                                       osInformation,
98
                                       arraysize(osInformation)));
99
}
100
101
26
static void GetCPUInfo(const FunctionCallbackInfo<Value>& args) {
102
26
  Environment* env = Environment::GetCurrent(args);
103
26
  Isolate* isolate = env->isolate();
104
105
  uv_cpu_info_t* cpu_infos;
106
  int count;
107
108
26
  int err = uv_cpu_info(&cpu_infos, &count);
109
26
  if (err)
110
    return;
111
112
  // It's faster to create an array packed with all the data and
113
  // assemble them into objects in JS than to call Object::Set() repeatedly
114
  // The array is in the format
115
  // [model, speed, (5 entries of cpu_times), model2, speed2, ...]
116
26
  std::vector<Local<Value>> result;
117
26
  result.reserve(count * 7);
118
2314
  for (int i = 0; i < count; i++) {
119
2288
    uv_cpu_info_t* ci = cpu_infos + i;
120
2288
    result.emplace_back(OneByteString(isolate, ci->model));
121
2288
    result.emplace_back(Number::New(isolate, ci->speed));
122
    result.emplace_back(
123
2288
        Number::New(isolate, static_cast<double>(ci->cpu_times.user)));
124
    result.emplace_back(
125
2288
        Number::New(isolate, static_cast<double>(ci->cpu_times.nice)));
126
    result.emplace_back(
127
2288
        Number::New(isolate, static_cast<double>(ci->cpu_times.sys)));
128
    result.emplace_back(
129
2288
        Number::New(isolate, static_cast<double>(ci->cpu_times.idle)));
130
    result.emplace_back(
131
2288
        Number::New(isolate, static_cast<double>(ci->cpu_times.irq)));
132
  }
133
134
26
  uv_free_cpu_info(cpu_infos, count);
135
52
  args.GetReturnValue().Set(Array::New(isolate, result.data(), result.size()));
136
}
137
138
139
3
static void GetFreeMemory(const FunctionCallbackInfo<Value>& args) {
140
3
  double amount = static_cast<double>(uv_get_free_memory());
141
3
  args.GetReturnValue().Set(amount);
142
3
}
143
144
145
115
static void GetTotalMemory(const FunctionCallbackInfo<Value>& args) {
146
115
  double amount = static_cast<double>(uv_get_total_memory());
147
115
  args.GetReturnValue().Set(amount);
148
115
}
149
150
151
3
static void GetUptime(const FunctionCallbackInfo<Value>& args) {
152
  double uptime;
153
3
  int err = uv_uptime(&uptime);
154
3
  if (err == 0)
155
6
    args.GetReturnValue().Set(uptime);
156
3
}
157
158
159
1
static void GetLoadAvg(const FunctionCallbackInfo<Value>& args) {
160
1
  CHECK(args[0]->IsFloat64Array());
161
2
  Local<Float64Array> array = args[0].As<Float64Array>();
162
1
  CHECK_EQ(array->Length(), 3);
163
1
  Local<ArrayBuffer> ab = array->Buffer();
164
1
  double* loadavg = static_cast<double*>(ab->GetBackingStore()->Data());
165
1
  uv_loadavg(loadavg);
166
1
}
167
168
169
148
static void GetInterfaceAddresses(const FunctionCallbackInfo<Value>& args) {
170
148
  Environment* env = Environment::GetCurrent(args);
171
148
  Isolate* isolate = env->isolate();
172
  uv_interface_address_t* interfaces;
173
  int count, i;
174
  char ip[INET6_ADDRSTRLEN];
175
  char netmask[INET6_ADDRSTRLEN];
176
  std::array<char, 18> mac;
177
  Local<String> name;
178
  Local<Integer> family;
179
180
148
  int err = uv_interface_addresses(&interfaces, &count);
181
182
148
  if (err == UV_ENOSYS)
183
    return args.GetReturnValue().SetUndefined();
184
185
148
  if (err) {
186
    CHECK_GE(args.Length(), 1);
187
    env->CollectUVExceptionInfo(args[args.Length() - 1], errno,
188
                                "uv_interface_addresses");
189
    return args.GetReturnValue().SetUndefined();
190
  }
191
192
148
  Local<Value> no_scope_id = Integer::New(isolate, -1);
193
148
  std::vector<Local<Value>> result;
194
148
  result.reserve(count * 7);
195
740
  for (i = 0; i < count; i++) {
196
592
    const char* const raw_name = interfaces[i].name;
197
198
    // Use UTF-8 on both Windows and Unixes (While it may be true that UNIX
199
    // systems are somewhat encoding-agnostic here, it’s more than reasonable
200
    // to assume UTF8 as the default as well. It’s what people will expect if
201
    // they name the interface from any input that uses UTF-8, which should be
202
    // the most frequent case by far these days.)
203
592
    name = String::NewFromUtf8(isolate, raw_name).ToLocalChecked();
204
205
592
    snprintf(mac.data(),
206
             mac.size(),
207
             "%02x:%02x:%02x:%02x:%02x:%02x",
208
592
             static_cast<unsigned char>(interfaces[i].phys_addr[0]),
209
592
             static_cast<unsigned char>(interfaces[i].phys_addr[1]),
210
592
             static_cast<unsigned char>(interfaces[i].phys_addr[2]),
211
592
             static_cast<unsigned char>(interfaces[i].phys_addr[3]),
212
592
             static_cast<unsigned char>(interfaces[i].phys_addr[4]),
213
592
             static_cast<unsigned char>(interfaces[i].phys_addr[5]));
214
215
592
    if (interfaces[i].address.address4.sin_family == AF_INET) {
216
296
      uv_ip4_name(&interfaces[i].address.address4, ip, sizeof(ip));
217
296
      uv_ip4_name(&interfaces[i].netmask.netmask4, netmask, sizeof(netmask));
218
296
      family = Integer::New(env->isolate(), 4);
219
296
    } else if (interfaces[i].address.address4.sin_family == AF_INET6) {
220
296
      uv_ip6_name(&interfaces[i].address.address6, ip, sizeof(ip));
221
296
      uv_ip6_name(&interfaces[i].netmask.netmask6, netmask, sizeof(netmask));
222
296
      family = Integer::New(env->isolate(), 6);
223
    } else {
224
      strncpy(ip, "<unknown sa family>", INET6_ADDRSTRLEN);
225
      family = Integer::New(env->isolate(), 0);
226
    }
227
228
592
    result.emplace_back(name);
229
592
    result.emplace_back(OneByteString(isolate, ip));
230
592
    result.emplace_back(OneByteString(isolate, netmask));
231
592
    result.emplace_back(family);
232
592
    result.emplace_back(FIXED_ONE_BYTE_STRING(isolate, mac));
233
    result.emplace_back(
234
1184
        interfaces[i].is_internal ? True(isolate) : False(isolate));
235
592
    if (interfaces[i].address.address4.sin_family == AF_INET6) {
236
296
      uint32_t scopeid = interfaces[i].address.address6.sin6_scope_id;
237
296
      result.emplace_back(Integer::NewFromUnsigned(isolate, scopeid));
238
    } else {
239
296
      result.emplace_back(no_scope_id);
240
    }
241
  }
242
243
148
  uv_free_interface_addresses(interfaces, count);
244
296
  args.GetReturnValue().Set(Array::New(isolate, result.data(), result.size()));
245
}
246
247
248
300
static void GetHomeDirectory(const FunctionCallbackInfo<Value>& args) {
249
300
  Environment* env = Environment::GetCurrent(args);
250
  char buf[PATH_MAX];
251
252
300
  size_t len = sizeof(buf);
253
300
  const int err = uv_os_homedir(buf, &len);
254
255
300
  if (err) {
256
    CHECK_GE(args.Length(), 1);
257
    env->CollectUVExceptionInfo(args[args.Length() - 1], err, "uv_os_homedir");
258
    return args.GetReturnValue().SetUndefined();
259
  }
260
261
300
  Local<String> home = String::NewFromUtf8(env->isolate(),
262
                                           buf,
263
                                           NewStringType::kNormal,
264
600
                                           len).ToLocalChecked();
265
600
  args.GetReturnValue().Set(home);
266
}
267
268
269
3
static void GetUserInfo(const FunctionCallbackInfo<Value>& args) {
270
3
  Environment* env = Environment::GetCurrent(args);
271
  uv_passwd_t pwd;
272
  enum encoding encoding;
273
274
3
  if (args[0]->IsObject()) {
275
4
    Local<Object> options = args[0].As<Object>();
276
    MaybeLocal<Value> maybe_encoding = options->Get(env->context(),
277
4
                                                    env->encoding_string());
278
    Local<Value> encoding_opt;
279
2
    if (!maybe_encoding.ToLocal(&encoding_opt))
280
1
        return;
281
282
1
    encoding = ParseEncoding(env->isolate(), encoding_opt, UTF8);
283
  } else {
284
1
    encoding = UTF8;
285
  }
286
287
2
  const int err = uv_os_get_passwd(&pwd);
288
289
2
  if (err) {
290
    CHECK_GE(args.Length(), 2);
291
    env->CollectUVExceptionInfo(args[args.Length() - 1], err,
292
                                "uv_os_get_passwd");
293
    return args.GetReturnValue().SetUndefined();
294
  }
295
296
4
  auto free_passwd = OnScopeLeave([&]() { uv_os_free_passwd(&pwd); });
297
298
  Local<Value> error;
299
300
2
  Local<Value> uid = Number::New(env->isolate(), pwd.uid);
301
2
  Local<Value> gid = Number::New(env->isolate(), pwd.gid);
302
  MaybeLocal<Value> username = StringBytes::Encode(env->isolate(),
303
2
                                                   pwd.username,
304
                                                   encoding,
305
2
                                                   &error);
306
  MaybeLocal<Value> homedir = StringBytes::Encode(env->isolate(),
307
2
                                                  pwd.homedir,
308
                                                  encoding,
309
2
                                                  &error);
310
  MaybeLocal<Value> shell;
311
312
2
  if (pwd.shell == nullptr)
313
    shell = Null(env->isolate());
314
  else
315
2
    shell = StringBytes::Encode(env->isolate(), pwd.shell, encoding, &error);
316
317


6
  if (username.IsEmpty() || homedir.IsEmpty() || shell.IsEmpty()) {
318
    CHECK(!error.IsEmpty());
319
    env->isolate()->ThrowException(error);
320
    return;
321
  }
322
323
2
  Local<Object> entry = Object::New(env->isolate());
324
325
6
  entry->Set(env->context(), env->uid_string(), uid).Check();
326
6
  entry->Set(env->context(), env->gid_string(), gid).Check();
327
2
  entry->Set(env->context(),
328
             env->username_string(),
329
8
             username.ToLocalChecked()).Check();
330
2
  entry->Set(env->context(),
331
             env->homedir_string(),
332
8
             homedir.ToLocalChecked()).Check();
333
2
  entry->Set(env->context(),
334
             env->shell_string(),
335
8
             shell.ToLocalChecked()).Check();
336
337
4
  args.GetReturnValue().Set(entry);
338
}
339
340
341
80
static void SetPriority(const FunctionCallbackInfo<Value>& args) {
342
80
  Environment* env = Environment::GetCurrent(args);
343
344
80
  CHECK_EQ(args.Length(), 3);
345
80
  CHECK(args[0]->IsInt32());
346
80
  CHECK(args[1]->IsInt32());
347
348
160
  const int pid = args[0].As<Int32>()->Value();
349
160
  const int priority = args[1].As<Int32>()->Value();
350
80
  const int err = uv_os_setpriority(pid, priority);
351
352
80
  if (err) {
353
20
    CHECK(args[2]->IsObject());
354
20
    env->CollectUVExceptionInfo(args[2], err, "uv_os_setpriority");
355
  }
356
357
80
  args.GetReturnValue().Set(err);
358
80
}
359
360
361
60
static void GetPriority(const FunctionCallbackInfo<Value>& args) {
362
60
  Environment* env = Environment::GetCurrent(args);
363
364
60
  CHECK_EQ(args.Length(), 2);
365
60
  CHECK(args[0]->IsInt32());
366
367
120
  const int pid = args[0].As<Int32>()->Value();
368
  int priority;
369
60
  const int err = uv_os_getpriority(pid, &priority);
370
371
60
  if (err) {
372
    CHECK(args[1]->IsObject());
373
    env->CollectUVExceptionInfo(args[1], err, "uv_os_getpriority");
374
    return;
375
  }
376
377
120
  args.GetReturnValue().Set(priority);
378
}
379
380
381
621
void Initialize(Local<Object> target,
382
                Local<Value> unused,
383
                Local<Context> context,
384
                void* priv) {
385
621
  Environment* env = Environment::GetCurrent(context);
386
621
  env->SetMethod(target, "getHostname", GetHostname);
387
621
  env->SetMethod(target, "getLoadAvg", GetLoadAvg);
388
621
  env->SetMethod(target, "getUptime", GetUptime);
389
621
  env->SetMethod(target, "getTotalMem", GetTotalMemory);
390
621
  env->SetMethod(target, "getFreeMem", GetFreeMemory);
391
621
  env->SetMethod(target, "getCPUs", GetCPUInfo);
392
621
  env->SetMethod(target, "getInterfaceAddresses", GetInterfaceAddresses);
393
621
  env->SetMethod(target, "getHomeDirectory", GetHomeDirectory);
394
621
  env->SetMethod(target, "getUserInfo", GetUserInfo);
395
621
  env->SetMethod(target, "setPriority", SetPriority);
396
621
  env->SetMethod(target, "getPriority", GetPriority);
397
621
  env->SetMethod(target, "getOSInformation", GetOSInformation);
398
621
  target->Set(env->context(),
399
              FIXED_ONE_BYTE_STRING(env->isolate(), "isBigEndian"),
400
1863
              Boolean::New(env->isolate(), IsBigEndian())).Check();
401
621
}
402
403
5205
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
404
5205
  registry->Register(GetHostname);
405
5205
  registry->Register(GetLoadAvg);
406
5205
  registry->Register(GetUptime);
407
5205
  registry->Register(GetTotalMemory);
408
5205
  registry->Register(GetFreeMemory);
409
5205
  registry->Register(GetCPUInfo);
410
5205
  registry->Register(GetInterfaceAddresses);
411
5205
  registry->Register(GetHomeDirectory);
412
5205
  registry->Register(GetUserInfo);
413
5205
  registry->Register(SetPriority);
414
5205
  registry->Register(GetPriority);
415
5205
  registry->Register(GetOSInformation);
416
5205
}
417
418
}  // namespace os
419
}  // namespace node
420
421
5273
NODE_MODULE_CONTEXT_AWARE_INTERNAL(os, node::os::Initialize)
422
5205
NODE_MODULE_EXTERNAL_REFERENCE(os, node::os::RegisterExternalReferences)