GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_os.cc Lines: 187 213 87.8 %
Date: 2022-02-20 04:14:12 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
576
static void GetOSInformation(const FunctionCallbackInfo<Value>& args) {
79
576
  Environment* env = Environment::GetCurrent(args);
80
  uv_utsname_t info;
81
576
  int err = uv_os_uname(&info);
82
83
576
  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
576
    String::NewFromUtf8(env->isolate(), info.sysname).ToLocalChecked(),
92
576
    String::NewFromUtf8(env->isolate(), info.version).ToLocalChecked(),
93
576
    String::NewFromUtf8(env->isolate(), info.release).ToLocalChecked()
94
2304
  };
95
96
1152
  args.GetReturnValue().Set(Array::New(env->isolate(),
97
                                       osInformation,
98
                                       arraysize(osInformation)));
99
}
100
101
18
static void GetCPUInfo(const FunctionCallbackInfo<Value>& args) {
102
18
  Environment* env = Environment::GetCurrent(args);
103
18
  Isolate* isolate = env->isolate();
104
105
  uv_cpu_info_t* cpu_infos;
106
  int count;
107
108
18
  int err = uv_cpu_info(&cpu_infos, &count);
109
18
  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
18
  std::vector<Local<Value>> result;
117
18
  result.reserve(count * 7);
118
1602
  for (int i = 0; i < count; i++) {
119
1584
    uv_cpu_info_t* ci = cpu_infos + i;
120
1584
    result.emplace_back(OneByteString(isolate, ci->model));
121
1584
    result.emplace_back(Number::New(isolate, ci->speed));
122
    result.emplace_back(
123
1584
        Number::New(isolate, static_cast<double>(ci->cpu_times.user)));
124
    result.emplace_back(
125
1584
        Number::New(isolate, static_cast<double>(ci->cpu_times.nice)));
126
    result.emplace_back(
127
1584
        Number::New(isolate, static_cast<double>(ci->cpu_times.sys)));
128
    result.emplace_back(
129
1584
        Number::New(isolate, static_cast<double>(ci->cpu_times.idle)));
130
    result.emplace_back(
131
1584
        Number::New(isolate, static_cast<double>(ci->cpu_times.irq)));
132
  }
133
134
18
  uv_free_cpu_info(cpu_infos, count);
135
36
  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
106
static void GetTotalMemory(const FunctionCallbackInfo<Value>& args) {
146
106
  double amount = static_cast<double>(uv_get_total_memory());
147
106
  args.GetReturnValue().Set(amount);
148
106
}
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
138
static void GetInterfaceAddresses(const FunctionCallbackInfo<Value>& args) {
170
138
  Environment* env = Environment::GetCurrent(args);
171
138
  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, family;
178
179
138
  int err = uv_interface_addresses(&interfaces, &count);
180
181
138
  if (err == UV_ENOSYS)
182
    return args.GetReturnValue().SetUndefined();
183
184
138
  if (err) {
185
    CHECK_GE(args.Length(), 1);
186
    env->CollectUVExceptionInfo(args[args.Length() - 1], errno,
187
                                "uv_interface_addresses");
188
    return args.GetReturnValue().SetUndefined();
189
  }
190
191
138
  Local<Value> no_scope_id = Integer::New(isolate, -1);
192
138
  std::vector<Local<Value>> result;
193
138
  result.reserve(count * 7);
194
690
  for (i = 0; i < count; i++) {
195
552
    const char* const raw_name = interfaces[i].name;
196
197
    // Use UTF-8 on both Windows and Unixes (While it may be true that UNIX
198
    // systems are somewhat encoding-agnostic here, it’s more than reasonable
199
    // to assume UTF8 as the default as well. It’s what people will expect if
200
    // they name the interface from any input that uses UTF-8, which should be
201
    // the most frequent case by far these days.)
202
552
    name = String::NewFromUtf8(isolate, raw_name).ToLocalChecked();
203
204
552
    snprintf(mac.data(),
205
             mac.size(),
206
             "%02x:%02x:%02x:%02x:%02x:%02x",
207
552
             static_cast<unsigned char>(interfaces[i].phys_addr[0]),
208
552
             static_cast<unsigned char>(interfaces[i].phys_addr[1]),
209
552
             static_cast<unsigned char>(interfaces[i].phys_addr[2]),
210
552
             static_cast<unsigned char>(interfaces[i].phys_addr[3]),
211
552
             static_cast<unsigned char>(interfaces[i].phys_addr[4]),
212
552
             static_cast<unsigned char>(interfaces[i].phys_addr[5]));
213
214
552
    if (interfaces[i].address.address4.sin_family == AF_INET) {
215
276
      uv_ip4_name(&interfaces[i].address.address4, ip, sizeof(ip));
216
276
      uv_ip4_name(&interfaces[i].netmask.netmask4, netmask, sizeof(netmask));
217
276
      family = env->ipv4_string();
218
276
    } else if (interfaces[i].address.address4.sin_family == AF_INET6) {
219
276
      uv_ip6_name(&interfaces[i].address.address6, ip, sizeof(ip));
220
276
      uv_ip6_name(&interfaces[i].netmask.netmask6, netmask, sizeof(netmask));
221
276
      family = env->ipv6_string();
222
    } else {
223
      strncpy(ip, "<unknown sa family>", INET6_ADDRSTRLEN);
224
      family = env->unknown_string();
225
    }
226
227
552
    result.emplace_back(name);
228
552
    result.emplace_back(OneByteString(isolate, ip));
229
552
    result.emplace_back(OneByteString(isolate, netmask));
230
552
    result.emplace_back(family);
231
552
    result.emplace_back(FIXED_ONE_BYTE_STRING(isolate, mac));
232
    result.emplace_back(
233
1104
        interfaces[i].is_internal ? True(isolate) : False(isolate));
234
552
    if (interfaces[i].address.address4.sin_family == AF_INET6) {
235
276
      uint32_t scopeid = interfaces[i].address.address6.sin6_scope_id;
236
276
      result.emplace_back(Integer::NewFromUnsigned(isolate, scopeid));
237
    } else {
238
276
      result.emplace_back(no_scope_id);
239
    }
240
  }
241
242
138
  uv_free_interface_addresses(interfaces, count);
243
276
  args.GetReturnValue().Set(Array::New(isolate, result.data(), result.size()));
244
}
245
246
247
297
static void GetHomeDirectory(const FunctionCallbackInfo<Value>& args) {
248
297
  Environment* env = Environment::GetCurrent(args);
249
  char buf[PATH_MAX];
250
251
297
  size_t len = sizeof(buf);
252
297
  const int err = uv_os_homedir(buf, &len);
253
254
297
  if (err) {
255
    CHECK_GE(args.Length(), 1);
256
    env->CollectUVExceptionInfo(args[args.Length() - 1], err, "uv_os_homedir");
257
    return args.GetReturnValue().SetUndefined();
258
  }
259
260
297
  Local<String> home = String::NewFromUtf8(env->isolate(),
261
                                           buf,
262
                                           NewStringType::kNormal,
263
594
                                           len).ToLocalChecked();
264
594
  args.GetReturnValue().Set(home);
265
}
266
267
268
3
static void GetUserInfo(const FunctionCallbackInfo<Value>& args) {
269
3
  Environment* env = Environment::GetCurrent(args);
270
  uv_passwd_t pwd;
271
  enum encoding encoding;
272
273
3
  if (args[0]->IsObject()) {
274
4
    Local<Object> options = args[0].As<Object>();
275
    MaybeLocal<Value> maybe_encoding = options->Get(env->context(),
276
4
                                                    env->encoding_string());
277
    Local<Value> encoding_opt;
278
2
    if (!maybe_encoding.ToLocal(&encoding_opt))
279
1
        return;
280
281
1
    encoding = ParseEncoding(env->isolate(), encoding_opt, UTF8);
282
  } else {
283
1
    encoding = UTF8;
284
  }
285
286
2
  const int err = uv_os_get_passwd(&pwd);
287
288
2
  if (err) {
289
    CHECK_GE(args.Length(), 2);
290
    env->CollectUVExceptionInfo(args[args.Length() - 1], err,
291
                                "uv_os_get_passwd");
292
    return args.GetReturnValue().SetUndefined();
293
  }
294
295
4
  auto free_passwd = OnScopeLeave([&]() { uv_os_free_passwd(&pwd); });
296
297
  Local<Value> error;
298
299
2
  Local<Value> uid = Number::New(env->isolate(), pwd.uid);
300
2
  Local<Value> gid = Number::New(env->isolate(), pwd.gid);
301
  MaybeLocal<Value> username = StringBytes::Encode(env->isolate(),
302
2
                                                   pwd.username,
303
                                                   encoding,
304
2
                                                   &error);
305
  MaybeLocal<Value> homedir = StringBytes::Encode(env->isolate(),
306
2
                                                  pwd.homedir,
307
                                                  encoding,
308
2
                                                  &error);
309
  MaybeLocal<Value> shell;
310
311
2
  if (pwd.shell == nullptr)
312
    shell = Null(env->isolate());
313
  else
314
2
    shell = StringBytes::Encode(env->isolate(), pwd.shell, encoding, &error);
315
316


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