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: 181 190 95.3 %
Date: 2021-04-09 04:13:47 Branches: 76 104 73.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::DontDelete;
14
using v8::DontEnum;
15
using v8::EscapableHandleScope;
16
using v8::HandleScope;
17
using v8::Integer;
18
using v8::Isolate;
19
using v8::Just;
20
using v8::Local;
21
using v8::Maybe;
22
using v8::MaybeLocal;
23
using v8::Name;
24
using v8::NamedPropertyHandlerConfiguration;
25
using v8::NewStringType;
26
using v8::Nothing;
27
using v8::Object;
28
using v8::ObjectTemplate;
29
using v8::PropertyCallbackInfo;
30
using v8::PropertyHandlerFlags;
31
using v8::ReadOnly;
32
using v8::String;
33
using v8::Value;
34
35
8973
class RealEnvStore final : public KVStore {
36
 public:
37
  MaybeLocal<String> Get(Isolate* isolate, Local<String> key) const override;
38
  Maybe<std::string> Get(const char* key) const override;
39
  void Set(Isolate* isolate, Local<String> key, Local<String> value) override;
40
  int32_t Query(Isolate* isolate, Local<String> key) const override;
41
  int32_t Query(const char* key) const override;
42
  void Delete(Isolate* isolate, Local<String> key) override;
43
  Local<Array> Enumerate(Isolate* isolate) const override;
44
};
45
46
655
class MapKVStore final : public KVStore {
47
 public:
48
  MaybeLocal<String> Get(Isolate* isolate, Local<String> key) const override;
49
  Maybe<std::string> Get(const char* key) const override;
50
  void Set(Isolate* isolate, Local<String> key, Local<String> value) override;
51
  int32_t Query(Isolate* isolate, Local<String> key) const override;
52
  int32_t Query(const char* key) const override;
53
  void Delete(Isolate* isolate, Local<String> key) override;
54
  Local<Array> Enumerate(Isolate* isolate) const override;
55
56
  std::shared_ptr<KVStore> Clone(Isolate* isolate) const override;
57
58
645
  MapKVStore() = default;
59
10
  MapKVStore(const MapKVStore& other) : KVStore(), map_(other.map_) {}
60
61
 private:
62
  mutable Mutex mutex_;
63
  std::unordered_map<std::string, std::string> map_;
64
};
65
66
namespace per_process {
67
4757
Mutex env_var_mutex;
68
4757
std::shared_ptr<KVStore> system_environment = std::make_shared<RealEnvStore>();
69
}  // namespace per_process
70
71
template <typename T>
72
7787
void DateTimeConfigurationChangeNotification(Isolate* isolate, const T& key) {
73


7787
  if (key.length() == 2 && key[0] == 'T' && key[1] == 'Z') {
74
#ifdef __POSIX__
75
4
    tzset();
76
#else
77
    _tzset();
78
#endif
79
4
    auto constexpr time_zone_detection = Isolate::TimeZoneDetection::kRedetect;
80
4
    isolate->DateTimeConfigurationChangeNotification(time_zone_detection);
81
  }
82
7787
}
83
84
590590
Maybe<std::string> RealEnvStore::Get(const char* key) const {
85
1181180
  Mutex::ScopedLock lock(per_process::env_var_mutex);
86
87
590590
  size_t init_sz = 256;
88
1181180
  MaybeStackBuffer<char, 256> val;
89
590590
  int ret = uv_os_getenv(key, *val, &init_sz);
90
91
590590
  if (ret == UV_ENOBUFS) {
92
    // Buffer is not large enough, reallocate to the updated init_sz
93
    // and fetch env value again.
94
6154
    val.AllocateSufficientStorage(init_sz);
95
6154
    ret = uv_os_getenv(key, *val, &init_sz);
96
  }
97
98
590590
  if (ret >= 0) {  // Env key value fetch success.
99
529265
    return Just(std::string(*val, init_sz));
100
  }
101
102
61325
  return Nothing<std::string>();
103
}
104
105
590590
MaybeLocal<String> RealEnvStore::Get(Isolate* isolate,
106
                                     Local<String> property) const {
107
1181180
  node::Utf8Value key(isolate, property);
108
1181180
  Maybe<std::string> value = Get(*key);
109
110
590590
  if (value.IsJust()) {
111
529265
    std::string val = value.FromJust();
112
    return String::NewFromUtf8(
113
529265
        isolate, val.data(), NewStringType::kNormal, val.size());
114
  }
115
116
61325
  return MaybeLocal<String>();
117
}
118
119
6762
void RealEnvStore::Set(Isolate* isolate,
120
                       Local<String> property,
121
                       Local<String> value) {
122
13524
  Mutex::ScopedLock lock(per_process::env_var_mutex);
123
124
13524
  node::Utf8Value key(isolate, property);
125
13524
  node::Utf8Value val(isolate, value);
126
127
#ifdef _WIN32
128
  if (key.length() > 0 && key[0] == '=') return;
129
#endif
130
6762
  uv_os_setenv(*key, *val);
131
6762
  DateTimeConfigurationChangeNotification(isolate, key);
132
6762
}
133
134
643098
int32_t RealEnvStore::Query(const char* key) const {
135
1286196
  Mutex::ScopedLock lock(per_process::env_var_mutex);
136
137
  char val[2];
138
643098
  size_t init_sz = sizeof(val);
139
643098
  int ret = uv_os_getenv(key, val, &init_sz);
140
141
643098
  if (ret == UV_ENOENT) {
142
5718
    return -1;
143
  }
144
145
#ifdef _WIN32
146
  if (key[0] == '=') {
147
    return static_cast<int32_t>(ReadOnly) |
148
           static_cast<int32_t>(DontDelete) |
149
           static_cast<int32_t>(DontEnum);
150
  }
151
#endif
152
153
637380
  return 0;
154
}
155
156
643098
int32_t RealEnvStore::Query(Isolate* isolate, Local<String> property) const {
157
1286196
  node::Utf8Value key(isolate, property);
158
1286196
  return Query(*key);
159
}
160
161
1025
void RealEnvStore::Delete(Isolate* isolate, Local<String> property) {
162
2050
  Mutex::ScopedLock lock(per_process::env_var_mutex);
163
164
2050
  node::Utf8Value key(isolate, property);
165
1025
  uv_os_unsetenv(*key);
166
1025
  DateTimeConfigurationChangeNotification(isolate, key);
167
1025
}
168
169
7880
Local<Array> RealEnvStore::Enumerate(Isolate* isolate) const {
170
15760
  Mutex::ScopedLock lock(per_process::env_var_mutex);
171
  uv_env_item_t* items;
172
  int count;
173
174
23640
  auto cleanup = OnScopeLeave([&]() { uv_os_free_environ(items, count); });
175
7880
  CHECK_EQ(uv_os_environ(&items, &count), 0);
176
177
15760
  MaybeStackBuffer<Local<Value>, 256> env_v(count);
178
7880
  int env_v_index = 0;
179
568262
  for (int i = 0; i < count; i++) {
180
#ifdef _WIN32
181
    // If the key starts with '=' it is a hidden environment variable.
182
    if (items[i].name[0] == '=') continue;
183
#endif
184
560382
    MaybeLocal<String> str = String::NewFromUtf8(isolate, items[i].name);
185
560382
    if (str.IsEmpty()) {
186
      isolate->ThrowException(ERR_STRING_TOO_LONG(isolate));
187
      return Local<Array>();
188
    }
189
1120764
    env_v[env_v_index++] = str.ToLocalChecked();
190
  }
191
192
7880
  return Array::New(isolate, env_v.out(), env_v_index);
193
}
194
195
620
std::shared_ptr<KVStore> KVStore::Clone(Isolate* isolate) const {
196
1240
  HandleScope handle_scope(isolate);
197
620
  Local<Context> context = isolate->GetCurrentContext();
198
199
620
  std::shared_ptr<KVStore> copy = KVStore::CreateMapKVStore();
200
620
  Local<Array> keys = Enumerate(isolate);
201
620
  uint32_t keys_length = keys->Length();
202
44065
  for (uint32_t i = 0; i < keys_length; i++) {
203
86890
    Local<Value> key = keys->Get(context, i).ToLocalChecked();
204
86890
    CHECK(key->IsString());
205
43445
    copy->Set(isolate,
206
              key.As<String>(),
207
130335
              Get(isolate, key.As<String>()).ToLocalChecked());
208
  }
209
1240
  return copy;
210
}
211
212
30932
Maybe<std::string> MapKVStore::Get(const char* key) const {
213
61864
  Mutex::ScopedLock lock(mutex_);
214
30932
  auto it = map_.find(key);
215
61864
  return it == map_.end() ? Nothing<std::string>() : Just(it->second);
216
}
217
218
30472
MaybeLocal<String> MapKVStore::Get(Isolate* isolate, Local<String> key) const {
219
60944
  Utf8Value str(isolate, key);
220
60944
  Maybe<std::string> value = Get(*str);
221
32653
  if (value.IsNothing()) return Local<String>();
222
28291
  std::string val = value.FromJust();
223
  return String::NewFromUtf8(
224
28291
      isolate, val.data(), NewStringType::kNormal, val.size());
225
}
226
227
45065
void MapKVStore::Set(Isolate* isolate, Local<String> key, Local<String> value) {
228
90130
  Mutex::ScopedLock lock(mutex_);
229
90130
  Utf8Value key_str(isolate, key);
230
90130
  Utf8Value value_str(isolate, value);
231


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

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


20351
  if (env->options()->pending_deprecation && !value->IsString() &&
324

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

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

18961
NODE_MODULE_EXTERNAL_REFERENCE(env_var, node::RegisterEnvVarExternalReferences)