GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/node_env_var.cc Lines: 179 190 94.2 %
Date: 2020-09-06 22:14:11 Branches: 75 104 72.1 %

Line Branch Exec Source
1
#include "debug_utils-inl.h"
2
#include "env-inl.h"
3
#include "node_errors.h"
4
#include "node_external_reference.h"
5
#include "node_process.h"
6
7
#include <time.h>  // tzset(), _tzset()
8
9
namespace node {
10
using v8::Array;
11
using v8::Boolean;
12
using v8::Context;
13
using v8::EscapableHandleScope;
14
using v8::HandleScope;
15
using v8::Integer;
16
using v8::Isolate;
17
using v8::Just;
18
using v8::Local;
19
using v8::Maybe;
20
using v8::MaybeLocal;
21
using v8::Name;
22
using v8::NamedPropertyHandlerConfiguration;
23
using v8::NewStringType;
24
using v8::Nothing;
25
using v8::Object;
26
using v8::ObjectTemplate;
27
using v8::PropertyCallbackInfo;
28
using v8::PropertyHandlerFlags;
29
using v8::String;
30
using v8::Value;
31
32
8479
class RealEnvStore final : public KVStore {
33
 public:
34
  MaybeLocal<String> Get(Isolate* isolate, Local<String> key) const override;
35
  Maybe<std::string> Get(const char* key) const override;
36
  void Set(Isolate* isolate, Local<String> key, Local<String> value) override;
37
  int32_t Query(Isolate* isolate, Local<String> key) const override;
38
  int32_t Query(const char* key) const override;
39
  void Delete(Isolate* isolate, Local<String> key) override;
40
  Local<Array> Enumerate(Isolate* isolate) const override;
41
};
42
43
626
class MapKVStore final : public KVStore {
44
 public:
45
  MaybeLocal<String> Get(Isolate* isolate, Local<String> key) const override;
46
  Maybe<std::string> Get(const char* key) const override;
47
  void Set(Isolate* isolate, Local<String> key, Local<String> value) override;
48
  int32_t Query(Isolate* isolate, Local<String> key) const override;
49
  int32_t Query(const char* key) const override;
50
  void Delete(Isolate* isolate, Local<String> key) override;
51
  Local<Array> Enumerate(Isolate* isolate) const override;
52
53
  std::shared_ptr<KVStore> Clone(Isolate* isolate) const override;
54
55
622
  MapKVStore() = default;
56
7
  MapKVStore(const MapKVStore& other) : KVStore(), map_(other.map_) {}
57
58
 private:
59
  mutable Mutex mutex_;
60
  std::unordered_map<std::string, std::string> map_;
61
};
62
63
namespace per_process {
64
4473
Mutex env_var_mutex;
65
4473
std::shared_ptr<KVStore> system_environment = std::make_shared<RealEnvStore>();
66
}  // namespace per_process
67
68
template <typename T>
69
7118
void DateTimeConfigurationChangeNotification(Isolate* isolate, const T& key) {
70


7118
  if (key.length() == 2 && key[0] == 'T' && key[1] == 'Z') {
71
#ifdef __POSIX__
72
4
    tzset();
73
#else
74
    _tzset();
75
#endif
76
4
    auto constexpr time_zone_detection = Isolate::TimeZoneDetection::kRedetect;
77
4
    isolate->DateTimeConfigurationChangeNotification(time_zone_detection);
78
  }
79
7118
}
80
81
557845
Maybe<std::string> RealEnvStore::Get(const char* key) const {
82
1115690
  Mutex::ScopedLock lock(per_process::env_var_mutex);
83
84
557845
  size_t init_sz = 256;
85
1115690
  MaybeStackBuffer<char, 256> val;
86
557845
  int ret = uv_os_getenv(key, *val, &init_sz);
87
88
557845
  if (ret == UV_ENOBUFS) {
89
    // Buffer is not large enough, reallocate to the updated init_sz
90
    // and fetch env value again.
91
    val.AllocateSufficientStorage(init_sz);
92
    ret = uv_os_getenv(key, *val, &init_sz);
93
  }
94
95
557845
  if (ret >= 0) {  // Env key value fetch success.
96
504193
    return v8::Just(std::string(*val, init_sz));
97
  }
98
99
53652
  return v8::Nothing<std::string>();
100
}
101
102
557845
MaybeLocal<String> RealEnvStore::Get(Isolate* isolate,
103
                                     Local<String> property) const {
104
1115690
  node::Utf8Value key(isolate, property);
105
1115690
  Maybe<std::string> value = Get(*key);
106
107
557845
  if (value.IsJust()) {
108
504193
    std::string val = value.FromJust();
109
    return String::NewFromUtf8(
110
504193
        isolate, val.data(), NewStringType::kNormal, val.size());
111
  }
112
113
53652
  return MaybeLocal<String>();
114
}
115
116
6344
void RealEnvStore::Set(Isolate* isolate,
117
                       Local<String> property,
118
                       Local<String> value) {
119
12688
  Mutex::ScopedLock lock(per_process::env_var_mutex);
120
121
12688
  node::Utf8Value key(isolate, property);
122
12688
  node::Utf8Value val(isolate, value);
123
124
#ifdef _WIN32
125
  if (key.length() > 0 && key[0] == '=') return;
126
#endif
127
6344
  uv_os_setenv(*key, *val);
128
6344
  DateTimeConfigurationChangeNotification(isolate, key);
129
6344
}
130
131
632542
int32_t RealEnvStore::Query(const char* key) const {
132
1265084
  Mutex::ScopedLock lock(per_process::env_var_mutex);
133
134
  char val[2];
135
632542
  size_t init_sz = sizeof(val);
136
632542
  int ret = uv_os_getenv(key, val, &init_sz);
137
138
632542
  if (ret == UV_ENOENT) {
139
5871
    return -1;
140
  }
141
142
#ifdef _WIN32
143
  if (key[0] == '=') {
144
    return static_cast<int32_t>(v8::ReadOnly) |
145
           static_cast<int32_t>(v8::DontDelete) |
146
           static_cast<int32_t>(v8::DontEnum);
147
  }
148
#endif
149
150
626671
  return 0;
151
}
152
153
632542
int32_t RealEnvStore::Query(Isolate* isolate, Local<String> property) const {
154
1265084
  node::Utf8Value key(isolate, property);
155
1265084
  return Query(*key);
156
}
157
158
774
void RealEnvStore::Delete(Isolate* isolate, Local<String> property) {
159
1548
  Mutex::ScopedLock lock(per_process::env_var_mutex);
160
161
1548
  node::Utf8Value key(isolate, property);
162
774
  uv_os_unsetenv(*key);
163
774
  DateTimeConfigurationChangeNotification(isolate, key);
164
774
}
165
166
7668
Local<Array> RealEnvStore::Enumerate(Isolate* isolate) const {
167
15336
  Mutex::ScopedLock lock(per_process::env_var_mutex);
168
  uv_env_item_t* items;
169
  int count;
170
171
23004
  auto cleanup = OnScopeLeave([&]() { uv_os_free_environ(items, count); });
172
7668
  CHECK_EQ(uv_os_environ(&items, &count), 0);
173
174
15336
  MaybeStackBuffer<Local<Value>, 256> env_v(count);
175
7668
  int env_v_index = 0;
176
560691
  for (int i = 0; i < count; i++) {
177
#ifdef _WIN32
178
    // If the key starts with '=' it is a hidden environment variable.
179
    // The '\0' check is a workaround for the bug behind
180
    // https://github.com/libuv/libuv/pull/2473 and can be removed later.
181
    if (items[i].name[0] == '=' || items[i].name[0] == '\0') continue;
182
#endif
183
553023
    MaybeLocal<String> str = String::NewFromUtf8(isolate, items[i].name);
184
553023
    if (str.IsEmpty()) {
185
      isolate->ThrowException(ERR_STRING_TOO_LONG(isolate));
186
      return Local<Array>();
187
    }
188
1106046
    env_v[env_v_index++] = str.ToLocalChecked();
189
  }
190
191
7668
  return Array::New(isolate, env_v.out(), env_v_index);
192
}
193
194
598
std::shared_ptr<KVStore> KVStore::Clone(v8::Isolate* isolate) const {
195
1196
  HandleScope handle_scope(isolate);
196
598
  Local<Context> context = isolate->GetCurrentContext();
197
198
598
  std::shared_ptr<KVStore> copy = KVStore::CreateMapKVStore();
199
598
  Local<Array> keys = Enumerate(isolate);
200
598
  uint32_t keys_length = keys->Length();
201
43095
  for (uint32_t i = 0; i < keys_length; i++) {
202
84994
    Local<Value> key = keys->Get(context, i).ToLocalChecked();
203
84994
    CHECK(key->IsString());
204
42497
    copy->Set(isolate,
205
              key.As<String>(),
206
127491
              Get(isolate, key.As<String>()).ToLocalChecked());
207
  }
208
1196
  return copy;
209
}
210
211
31131
Maybe<std::string> MapKVStore::Get(const char* key) const {
212
62262
  Mutex::ScopedLock lock(mutex_);
213
31131
  auto it = map_.find(key);
214
62262
  return it == map_.end() ? v8::Nothing<std::string>() : v8::Just(it->second);
215
}
216
217
30734
MaybeLocal<String> MapKVStore::Get(Isolate* isolate, Local<String> key) const {
218
61469
  Utf8Value str(isolate, key);
219
61470
  Maybe<std::string> value = Get(*str);
220
32802
  if (value.IsNothing()) return Local<String>();
221
28668
  std::string val = value.FromJust();
222
  return String::NewFromUtf8(
223
28668
      isolate, val.data(), NewStringType::kNormal, val.size());
224
}
225
226
44139
void MapKVStore::Set(Isolate* isolate, Local<String> key, Local<String> value) {
227
88278
  Mutex::ScopedLock lock(mutex_);
228
88278
  Utf8Value key_str(isolate, key);
229
88278
  Utf8Value value_str(isolate, value);
230


44139
  if (*key_str != nullptr && key_str.length() > 0 && *value_str != nullptr) {
231
88278
    map_[std::string(*key_str, key_str.length())] =
232
132417
        std::string(*value_str, value_str.length());
233
  }
234
44139
}
235
236
52861
int32_t MapKVStore::Query(const char* key) const {
237
105722
  Mutex::ScopedLock lock(mutex_);
238
105722
  return map_.find(key) == map_.end() ? -1 : 0;
239
}
240
241
52861
int32_t MapKVStore::Query(Isolate* isolate, Local<String> key) const {
242
105722
  Utf8Value str(isolate, key);
243
105722
  return Query(*str);
244
}
245
246
void MapKVStore::Delete(Isolate* isolate, Local<String> key) {
247
  Mutex::ScopedLock lock(mutex_);
248
  Utf8Value str(isolate, key);
249
  map_.erase(std::string(*str, str.length()));
250
}
251
252
720
Local<Array> MapKVStore::Enumerate(Isolate* isolate) const {
253
1440
  Mutex::ScopedLock lock(mutex_);
254
1440
  std::vector<Local<Value>> values;
255
720
  values.reserve(map_.size());
256
53003
  for (const auto& pair : map_) {
257
    values.emplace_back(
258
104566
        String::NewFromUtf8(isolate, pair.first.data(),
259
52283
                            NewStringType::kNormal, pair.first.size())
260
52283
            .ToLocalChecked());
261
  }
262
1440
  return Array::New(isolate, values.data(), values.size());
263
}
264
265
7
std::shared_ptr<KVStore> MapKVStore::Clone(Isolate* isolate) const {
266
7
  return std::make_shared<MapKVStore>(*this);
267
}
268
269
622
std::shared_ptr<KVStore> KVStore::CreateMapKVStore() {
270
622
  return std::make_shared<MapKVStore>();
271
}
272
273
24
Maybe<bool> KVStore::AssignFromObject(Local<Context> context,
274
                                      Local<Object> entries) {
275
24
  Isolate* isolate = context->GetIsolate();
276
48
  HandleScope handle_scope(isolate);
277
  Local<Array> keys;
278
48
  if (!entries->GetOwnPropertyNames(context).ToLocal(&keys))
279
    return Nothing<bool>();
280
24
  uint32_t keys_length = keys->Length();
281
1660
  for (uint32_t i = 0; i < keys_length; i++) {
282
    Local<Value> key;
283
3272
    if (!keys->Get(context, i).ToLocal(&key))
284
      return Nothing<bool>();
285
3272
    if (!key->IsString()) continue;
286
287
    Local<Value> value;
288
    Local<String> value_string;
289

6544
    if (!entries->Get(context, key).ToLocal(&value) ||
290
4908
        !value->ToString(context).ToLocal(&value_string)) {
291
      return Nothing<bool>();
292
    }
293
294
3272
    Set(isolate, key.As<String>(), value_string);
295
  }
296
24
  return Just(true);
297
}
298
299
534291
static void EnvGetter(Local<Name> property,
300
                      const PropertyCallbackInfo<Value>& info) {
301
534291
  Environment* env = Environment::GetCurrent(info);
302
534291
  CHECK(env->has_run_bootstrapping_code());
303
534291
  if (property->IsSymbol()) {
304
16044
    return info.GetReturnValue().SetUndefined();
305
  }
306
1052538
  CHECK(property->IsString());
307
  MaybeLocal<String> value_string =
308
1052538
      env->env_vars()->Get(env->isolate(), property.As<String>());
309
526269
  if (!value_string.IsEmpty()) {
310
960908
    info.GetReturnValue().Set(value_string.ToLocalChecked());
311
  }
312
}
313
314
6352
static void EnvSetter(Local<Name> property,
315
                      Local<Value> value,
316
                      const PropertyCallbackInfo<Value>& info) {
317
6352
  Environment* env = Environment::GetCurrent(info);
318
6352
  CHECK(env->has_run_bootstrapping_code());
319
  // calling env->EmitProcessEnvWarning() sets a variable indicating that
320
  // warnings have been emitted. It should be called last after other
321
  // conditions leading to a warning have been met.
322


19093
  if (env->options()->pending_deprecation && !value->IsString() &&
323

19059
      !value->IsNumber() && !value->IsBoolean() &&
324
1
      env->EmitProcessEnvWarning()) {
325
2
    if (ProcessEmitDeprecationWarning(
326
            env,
327
            "Assigning any value other than a string, number, or boolean to a "
328
            "process.env property is deprecated. Please make sure to convert "
329
            "the "
330
            "value to a string before setting process.env with it.",
331
            "DEP0104")
332
            .IsNothing())
333
2
      return;
334
  }
335
336
  Local<String> key;
337
  Local<String> value_string;
338

31759
  if (!property->ToString(env->context()).ToLocal(&key) ||
339
25405
      !value->ToString(env->context()).ToLocal(&value_string)) {
340
2
    return;
341
  }
342
343
6350
  env->env_vars()->Set(env->isolate(), key, value_string);
344
345
  // Whether it worked or not, always return value.
346
12700
  info.GetReturnValue().Set(value);
347
}
348
349
685404
static void EnvQuery(Local<Name> property,
350
                     const PropertyCallbackInfo<Integer>& info) {
351
685404
  Environment* env = Environment::GetCurrent(info);
352
685404
  CHECK(env->has_run_bootstrapping_code());
353
1370808
  if (property->IsString()) {
354
1370806
    int32_t rc = env->env_vars()->Query(env->isolate(), property.As<String>());
355
2043743
    if (rc != -1) info.GetReturnValue().Set(rc);
356
  }
357
685404
}
358
359
775
static void EnvDeleter(Local<Name> property,
360
                       const PropertyCallbackInfo<Boolean>& info) {
361
775
  Environment* env = Environment::GetCurrent(info);
362
775
  CHECK(env->has_run_bootstrapping_code());
363
1550
  if (property->IsString()) {
364
1548
    env->env_vars()->Delete(env->isolate(), property.As<String>());
365
  }
366
367
  // process.env never has non-configurable properties, so always
368
  // return true like the tc39 delete operator.
369
1550
  info.GetReturnValue().Set(true);
370
775
}
371
372
7790
static void EnvEnumerator(const PropertyCallbackInfo<Array>& info) {
373
7790
  Environment* env = Environment::GetCurrent(info);
374
7790
  CHECK(env->has_run_bootstrapping_code());
375
376
23370
  info.GetReturnValue().Set(
377
15580
      env->env_vars()->Enumerate(env->isolate()));
378
7790
}
379
380
453
MaybeLocal<Object> CreateEnvVarProxy(Local<Context> context, Isolate* isolate) {
381
453
  EscapableHandleScope scope(isolate);
382
453
  Local<ObjectTemplate> env_proxy_template = ObjectTemplate::New(isolate);
383
1359
  env_proxy_template->SetHandler(NamedPropertyHandlerConfiguration(
384
      EnvGetter, EnvSetter, EnvQuery, EnvDeleter, EnvEnumerator, Local<Value>(),
385
453
      PropertyHandlerFlags::kHasNoSideEffect));
386
906
  return scope.EscapeMaybe(env_proxy_template->NewInstance(context));
387
}
388
389
4403
void RegisterEnvVarExternalReferences(ExternalReferenceRegistry* registry) {
390
4403
  registry->Register(EnvGetter);
391
4403
  registry->Register(EnvSetter);
392
4403
  registry->Register(EnvQuery);
393
4403
  registry->Register(EnvDeleter);
394
4403
  registry->Register(EnvEnumerator);
395
4403
}
396
}  // namespace node
397
398

17822
NODE_MODULE_EXTERNAL_REFERENCE(env_var, node::RegisterEnvVarExternalReferences)