GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_os.cc Lines: 187 213 87.8 %
Date: 2022-08-21 04:19:51 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
33
static void GetHostname(const FunctionCallbackInfo<Value>& args) {
62
33
  Environment* env = Environment::GetCurrent(args);
63
  char buf[UV_MAXHOSTNAMESIZE];
64
33
  size_t size = sizeof(buf);
65
33
  int r = uv_os_gethostname(buf, &size);
66
67
33
  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
99
  args.GetReturnValue().Set(
75
66
      String::NewFromUtf8(env->isolate(), buf).ToLocalChecked());
76
}
77
78
668
static void GetOSInformation(const FunctionCallbackInfo<Value>& args) {
79
668
  Environment* env = Environment::GetCurrent(args);
80
  uv_utsname_t info;
81
668
  int err = uv_os_uname(&info);
82
83
668
  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
668
    String::NewFromUtf8(env->isolate(), info.sysname).ToLocalChecked(),
92
668
    String::NewFromUtf8(env->isolate(), info.version).ToLocalChecked(),
93
668
    String::NewFromUtf8(env->isolate(), info.release).ToLocalChecked()
94
2672
  };
95
96
1336
  args.GetReturnValue().Set(Array::New(env->isolate(),
97
                                       osInformation,
98
                                       arraysize(osInformation)));
99
}
100
101
57
static void GetCPUInfo(const FunctionCallbackInfo<Value>& args) {
102
57
  Environment* env = Environment::GetCurrent(args);
103
57
  Isolate* isolate = env->isolate();
104
105
  uv_cpu_info_t* cpu_infos;
106
  int count;
107
108
57
  int err = uv_cpu_info(&cpu_infos, &count);
109
57
  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
57
  std::vector<Local<Value>> result;
117
57
  result.reserve(count * 7);
118
5073
  for (int i = 0; i < count; i++) {
119
5016
    uv_cpu_info_t* ci = cpu_infos + i;
120
5016
    result.emplace_back(OneByteString(isolate, ci->model));
121
5016
    result.emplace_back(Number::New(isolate, ci->speed));
122
    result.emplace_back(
123
5016
        Number::New(isolate, static_cast<double>(ci->cpu_times.user)));
124
    result.emplace_back(
125
5016
        Number::New(isolate, static_cast<double>(ci->cpu_times.nice)));
126
    result.emplace_back(
127
5016
        Number::New(isolate, static_cast<double>(ci->cpu_times.sys)));
128
    result.emplace_back(
129
5016
        Number::New(isolate, static_cast<double>(ci->cpu_times.idle)));
130
    result.emplace_back(
131
5016
        Number::New(isolate, static_cast<double>(ci->cpu_times.irq)));
132
  }
133
134
57
  uv_free_cpu_info(cpu_infos, count);
135
114
  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
128
static void GetTotalMemory(const FunctionCallbackInfo<Value>& args) {
146
128
  double amount = static_cast<double>(uv_get_total_memory());
147
128
  args.GetReturnValue().Set(amount);
148
128
}
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->Data());
165
1
  uv_loadavg(loadavg);
166
1
}
167
168
169
161
static void GetInterfaceAddresses(const FunctionCallbackInfo<Value>& args) {
170
161
  Environment* env = Environment::GetCurrent(args);
171
161
  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
161
  int err = uv_interface_addresses(&interfaces, &count);
180
181
161
  if (err == UV_ENOSYS)
182
    return args.GetReturnValue().SetUndefined();
183
184
161
  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
161
  Local<Value> no_scope_id = Integer::New(isolate, -1);
192
161
  std::vector<Local<Value>> result;
193
161
  result.reserve(count * 7);
194
805
  for (i = 0; i < count; i++) {
195
644
    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
644
    name = String::NewFromUtf8(isolate, raw_name).ToLocalChecked();
203
204
644
    snprintf(mac.data(),
205
             mac.size(),
206
             "%02x:%02x:%02x:%02x:%02x:%02x",
207
644
             static_cast<unsigned char>(interfaces[i].phys_addr[0]),
208
644
             static_cast<unsigned char>(interfaces[i].phys_addr[1]),
209
644
             static_cast<unsigned char>(interfaces[i].phys_addr[2]),
210
644
             static_cast<unsigned char>(interfaces[i].phys_addr[3]),
211
644
             static_cast<unsigned char>(interfaces[i].phys_addr[4]),
212
644
             static_cast<unsigned char>(interfaces[i].phys_addr[5]));
213
214
644
    if (interfaces[i].address.address4.sin_family == AF_INET) {
215
322
      uv_ip4_name(&interfaces[i].address.address4, ip, sizeof(ip));
216
322
      uv_ip4_name(&interfaces[i].netmask.netmask4, netmask, sizeof(netmask));
217
322
      family = env->ipv4_string();
218
322
    } else if (interfaces[i].address.address4.sin_family == AF_INET6) {
219
322
      uv_ip6_name(&interfaces[i].address.address6, ip, sizeof(ip));
220
322
      uv_ip6_name(&interfaces[i].netmask.netmask6, netmask, sizeof(netmask));
221
322
      family = env->ipv6_string();
222
    } else {
223
      strncpy(ip, "<unknown sa family>", INET6_ADDRSTRLEN);
224
      family = env->unknown_string();
225
    }
226
227
644
    result.emplace_back(name);
228
644
    result.emplace_back(OneByteString(isolate, ip));
229
644
    result.emplace_back(OneByteString(isolate, netmask));
230
644
    result.emplace_back(family);
231
644
    result.emplace_back(FIXED_ONE_BYTE_STRING(isolate, mac));
232
    result.emplace_back(
233
1288
        interfaces[i].is_internal ? True(isolate) : False(isolate));
234
644
    if (interfaces[i].address.address4.sin_family == AF_INET6) {
235
322
      uint32_t scopeid = interfaces[i].address.address6.sin6_scope_id;
236
322
      result.emplace_back(Integer::NewFromUnsigned(isolate, scopeid));
237
    } else {
238
322
      result.emplace_back(no_scope_id);
239
    }
240
  }
241
242
161
  uv_free_interface_addresses(interfaces, count);
243
322
  args.GetReturnValue().Set(Array::New(isolate, result.data(), result.size()));
244
}
245
246
247
303
static void GetHomeDirectory(const FunctionCallbackInfo<Value>& args) {
248
303
  Environment* env = Environment::GetCurrent(args);
249
  char buf[PATH_MAX];
250
251
303
  size_t len = sizeof(buf);
252
303
  const int err = uv_os_homedir(buf, &len);
253
254
303
  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
303
  Local<String> home = String::NewFromUtf8(env->isolate(),
261
                                           buf,
262
                                           NewStringType::kNormal,
263
606
                                           len).ToLocalChecked();
264
606
  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
669
void Initialize(Local<Object> target,
381
                Local<Value> unused,
382
                Local<Context> context,
383
                void* priv) {
384
669
  Environment* env = Environment::GetCurrent(context);
385
669
  SetMethod(context, target, "getHostname", GetHostname);
386
669
  SetMethod(context, target, "getLoadAvg", GetLoadAvg);
387
669
  SetMethod(context, target, "getUptime", GetUptime);
388
669
  SetMethod(context, target, "getTotalMem", GetTotalMemory);
389
669
  SetMethod(context, target, "getFreeMem", GetFreeMemory);
390
669
  SetMethod(context, target, "getCPUs", GetCPUInfo);
391
669
  SetMethod(context, target, "getInterfaceAddresses", GetInterfaceAddresses);
392
669
  SetMethod(context, target, "getHomeDirectory", GetHomeDirectory);
393
669
  SetMethod(context, target, "getUserInfo", GetUserInfo);
394
669
  SetMethod(context, target, "setPriority", SetPriority);
395
669
  SetMethod(context, target, "getPriority", GetPriority);
396
669
  SetMethod(context, target, "getOSInformation", GetOSInformation);
397
  target
398
669
      ->Set(context,
399
            FIXED_ONE_BYTE_STRING(env->isolate(), "isBigEndian"),
400
2007
            Boolean::New(env->isolate(), IsBigEndian()))
401
      .Check();
402
669
}
403
404
5357
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
405
5357
  registry->Register(GetHostname);
406
5357
  registry->Register(GetLoadAvg);
407
5357
  registry->Register(GetUptime);
408
5357
  registry->Register(GetTotalMemory);
409
5357
  registry->Register(GetFreeMemory);
410
5357
  registry->Register(GetCPUInfo);
411
5357
  registry->Register(GetInterfaceAddresses);
412
5357
  registry->Register(GetHomeDirectory);
413
5357
  registry->Register(GetUserInfo);
414
5357
  registry->Register(SetPriority);
415
5357
  registry->Register(GetPriority);
416
5357
  registry->Register(GetOSInformation);
417
5357
}
418
419
}  // namespace os
420
}  // namespace node
421
422
5429
NODE_MODULE_CONTEXT_AWARE_INTERNAL(os, node::os::Initialize)
423
5357
NODE_MODULE_EXTERNAL_REFERENCE(os, node::os::RegisterExternalReferences)