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-08-17 22:13:26 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
8456
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
560
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
557
  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
4460
Mutex env_var_mutex;
65
4460
std::shared_ptr<KVStore> system_environment = std::make_shared<RealEnvStore>();
66
}  // namespace per_process
67
68
template <typename T>
69
7103
void DateTimeConfigurationChangeNotification(Isolate* isolate, const T& key) {
70


7103
  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
7103
}
80
81
551925
Maybe<std::string> RealEnvStore::Get(const char* key) const {
82
1103850
  Mutex::ScopedLock lock(per_process::env_var_mutex);
83
84
551925
  size_t init_sz = 256;
85
1103850
  MaybeStackBuffer<char, 256> val;
86
551925
  int ret = uv_os_getenv(key, *val, &init_sz);
87
88
551925
  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
551925
  if (ret >= 0) {  // Env key value fetch success.
96
498477
    return v8::Just(std::string(*val, init_sz));
97
  }
98
99
53448
  return v8::Nothing<std::string>();
100
}
101
102
551925
MaybeLocal<String> RealEnvStore::Get(Isolate* isolate,
103
                                     Local<String> property) const {
104
1103850
  node::Utf8Value key(isolate, property);
105
1103850
  Maybe<std::string> value = Get(*key);
106
107
551925
  if (value.IsJust()) {
108
498477
    std::string val = value.FromJust();
109
    return String::NewFromUtf8(
110
498477
        isolate, val.data(), NewStringType::kNormal, val.size());
111
  }
112
113
53448
  return MaybeLocal<String>();
114
}
115
116
6329
void RealEnvStore::Set(Isolate* isolate,
117
                       Local<String> property,
118
                       Local<String> value) {
119
12658
  Mutex::ScopedLock lock(per_process::env_var_mutex);
120
121
12658
  node::Utf8Value key(isolate, property);
122
12658
  node::Utf8Value val(isolate, value);
123
124
#ifdef _WIN32
125
  if (key.length() > 0 && key[0] == '=') return;
126
#endif
127
6329
  uv_os_setenv(*key, *val);
128
6329
  DateTimeConfigurationChangeNotification(isolate, key);
129
6329
}
130
131
632319
int32_t RealEnvStore::Query(const char* key) const {
132
1264638
  Mutex::ScopedLock lock(per_process::env_var_mutex);
133
134
  char val[2];
135
632319
  size_t init_sz = sizeof(val);
136
632319
  int ret = uv_os_getenv(key, val, &init_sz);
137
138
632319
  if (ret == UV_ENOENT) {
139
5861
    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
626458
  return 0;
151
}
152
153
632319
int32_t RealEnvStore::Query(Isolate* isolate, Local<String> property) const {
154
1264638
  node::Utf8Value key(isolate, property);
155
1264638
  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
7601
Local<Array> RealEnvStore::Enumerate(Isolate* isolate) const {
167
15202
  Mutex::ScopedLock lock(per_process::env_var_mutex);
168
  uv_env_item_t* items;
169
  int count;
170
171
22803
  auto cleanup = OnScopeLeave([&]() { uv_os_free_environ(items, count); });
172
7601
  CHECK_EQ(uv_os_environ(&items, &count), 0);
173
174
15202
  MaybeStackBuffer<Local<Value>, 256> env_v(count);
175
7601
  int env_v_index = 0;
176
555867
  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
548266
    MaybeLocal<String> str = String::NewFromUtf8(isolate, items[i].name);
184
548266
    if (str.IsEmpty()) {
185
      isolate->ThrowException(ERR_STRING_TOO_LONG(isolate));
186
      return Local<Array>();
187
    }
188
1096532
    env_v[env_v_index++] = str.ToLocalChecked();
189
  }
190
191
7601
  return Array::New(isolate, env_v.out(), env_v_index);
192
}
193
194
533
std::shared_ptr<KVStore> KVStore::Clone(v8::Isolate* isolate) const {
195
1066
  HandleScope handle_scope(isolate);
196
533
  Local<Context> context = isolate->GetCurrentContext();
197
198
533
  std::shared_ptr<KVStore> copy = KVStore::CreateMapKVStore();
199
533
  Local<Array> keys = Enumerate(isolate);
200
533
  uint32_t keys_length = keys->Length();
201
38415
  for (uint32_t i = 0; i < keys_length; i++) {
202
75764
    Local<Value> key = keys->Get(context, i).ToLocalChecked();
203
75764
    CHECK(key->IsString());
204
37882
    copy->Set(isolate,
205
              key.As<String>(),
206
113646
              Get(isolate, key.As<String>()).ToLocalChecked());
207
  }
208
1066
  return copy;
209
}
210
211
30204
Maybe<std::string> MapKVStore::Get(const char* key) const {
212
60409
  Mutex::ScopedLock lock(mutex_);
213
30205
  auto it = map_.find(key);
214
60409
  return it == map_.end() ? v8::Nothing<std::string>() : v8::Just(it->second);
215
}
216
217
30032
MaybeLocal<String> MapKVStore::Get(Isolate* isolate, Local<String> key) const {
218
60065
  Utf8Value str(isolate, key);
219
60066
  Maybe<std::string> value = Get(*str);
220
31835
  if (value.IsNothing()) return Local<String>();
221
28231
  std::string val = value.FromJust();
222
  return String::NewFromUtf8(
223
28231
      isolate, val.data(), NewStringType::kNormal, val.size());
224
}
225
226
39524
void MapKVStore::Set(Isolate* isolate, Local<String> key, Local<String> value) {
227
79048
  Mutex::ScopedLock lock(mutex_);
228
79048
  Utf8Value key_str(isolate, key);
229
79048
  Utf8Value value_str(isolate, value);
230


39524
  if (*key_str != nullptr && key_str.length() > 0 && *value_str != nullptr) {
231
79048
    map_[std::string(*key_str, key_str.length())] =
232
118572
        std::string(*value_str, value_str.length());
233
  }
234
39524
}
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
557
std::shared_ptr<KVStore> KVStore::CreateMapKVStore() {
270
557
  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
532651
static void EnvGetter(Local<Name> property,
300
                      const PropertyCallbackInfo<Value>& info) {
301
532651
  Environment* env = Environment::GetCurrent(info);
302
532651
  CHECK(env->has_run_bootstrapping_code());
303
532652
  if (property->IsSymbol()) {
304
16044
    return info.GetReturnValue().SetUndefined();
305
  }
306
1049260
  CHECK(property->IsString());
307
  MaybeLocal<String> value_string =
308
1049260
      env->env_vars()->Get(env->isolate(), property.As<String>());
309
524629
  if (!value_string.IsEmpty()) {
310
958256
    info.GetReturnValue().Set(value_string.ToLocalChecked());
311
  }
312
}
313
314
6337
static void EnvSetter(Local<Name> property,
315
                      Local<Value> value,
316
                      const PropertyCallbackInfo<Value>& info) {
317
6337
  Environment* env = Environment::GetCurrent(info);
318
6337
  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


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

19014
      !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

31684
  if (!property->ToString(env->context()).ToLocal(&key) ||
339
25345
      !value->ToString(env->context()).ToLocal(&value_string)) {
340
2
    return;
341
  }
342
343
6335
  env->env_vars()->Set(env->isolate(), key, value_string);
344
345
  // Whether it worked or not, always return value.
346
12670
  info.GetReturnValue().Set(value);
347
}
348
349
685181
static void EnvQuery(Local<Name> property,
350
                     const PropertyCallbackInfo<Integer>& info) {
351
685181
  Environment* env = Environment::GetCurrent(info);
352
685181
  CHECK(env->has_run_bootstrapping_code());
353
1370362
  if (property->IsString()) {
354
1370360
    int32_t rc = env->env_vars()->Query(env->isolate(), property.As<String>());
355
2043094
    if (rc != -1) info.GetReturnValue().Set(rc);
356
  }
357
685181
}
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
7788
static void EnvEnumerator(const PropertyCallbackInfo<Array>& info) {
373
7788
  Environment* env = Environment::GetCurrent(info);
374
7788
  CHECK(env->has_run_bootstrapping_code());
375
376
23364
  info.GetReturnValue().Set(
377
15576
      env->env_vars()->Enumerate(env->isolate()));
378
7788
}
379
380
387
MaybeLocal<Object> CreateEnvVarProxy(Local<Context> context, Isolate* isolate) {
381
387
  EscapableHandleScope scope(isolate);
382
387
  Local<ObjectTemplate> env_proxy_template = ObjectTemplate::New(isolate);
383
1161
  env_proxy_template->SetHandler(NamedPropertyHandlerConfiguration(
384
      EnvGetter, EnvSetter, EnvQuery, EnvDeleter, EnvEnumerator, Local<Value>(),
385
387
      PropertyHandlerFlags::kHasNoSideEffect));
386
774
  return scope.EscapeMaybe(env_proxy_template->NewInstance(context));
387
}
388
389
4390
void RegisterEnvVarExternalReferences(ExternalReferenceRegistry* registry) {
390
4390
  registry->Register(EnvGetter);
391
4390
  registry->Register(EnvSetter);
392
4390
  registry->Register(EnvQuery);
393
4390
  registry->Register(EnvDeleter);
394
4390
  registry->Register(EnvEnumerator);
395
4390
}
396
}  // namespace node
397
398

17770
NODE_MODULE_EXTERNAL_REFERENCE(env_var, node::RegisterEnvVarExternalReferences)