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: 109 189 57.7 %
Date: 2021-02-19 04:08:54 Branches: 35 104 33.7 %

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
240
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
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
  MapKVStore() = default;
59
  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
122
Mutex env_var_mutex;
68
122
std::shared_ptr<KVStore> system_environment = std::make_shared<RealEnvStore>();
69
}  // namespace per_process
70
71
template <typename T>
72
524
void DateTimeConfigurationChangeNotification(Isolate* isolate, const T& key) {
73


524
  if (key.length() == 2 && key[0] == 'T' && key[1] == 'Z') {
74
#ifdef __POSIX__
75
    tzset();
76
#else
77
    _tzset();
78
#endif
79
    auto constexpr time_zone_detection = Isolate::TimeZoneDetection::kRedetect;
80
    isolate->DateTimeConfigurationChangeNotification(time_zone_detection);
81
  }
82
524
}
83
84
69668
Maybe<std::string> RealEnvStore::Get(const char* key) const {
85
139336
  Mutex::ScopedLock lock(per_process::env_var_mutex);
86
87
69668
  size_t init_sz = 256;
88
139336
  MaybeStackBuffer<char, 256> val;
89
69668
  int ret = uv_os_getenv(key, *val, &init_sz);
90
91
69668
  if (ret == UV_ENOBUFS) {
92
    // Buffer is not large enough, reallocate to the updated init_sz
93
    // and fetch env value again.
94
649
    val.AllocateSufficientStorage(init_sz);
95
649
    ret = uv_os_getenv(key, *val, &init_sz);
96
  }
97
98
69668
  if (ret >= 0) {  // Env key value fetch success.
99
65888
    return Just(std::string(*val, init_sz));
100
  }
101
102
3780
  return Nothing<std::string>();
103
}
104
105
69668
MaybeLocal<String> RealEnvStore::Get(Isolate* isolate,
106
                                     Local<String> property) const {
107
139336
  node::Utf8Value key(isolate, property);
108
139336
  Maybe<std::string> value = Get(*key);
109
110
69668
  if (value.IsJust()) {
111
65888
    std::string val = value.FromJust();
112
    return String::NewFromUtf8(
113
65888
        isolate, val.data(), NewStringType::kNormal, val.size());
114
  }
115
116
3780
  return MaybeLocal<String>();
117
}
118
119
522
void RealEnvStore::Set(Isolate* isolate,
120
                       Local<String> property,
121
                       Local<String> value) {
122
1044
  Mutex::ScopedLock lock(per_process::env_var_mutex);
123
124
1044
  node::Utf8Value key(isolate, property);
125
1044
  node::Utf8Value val(isolate, value);
126
127
#ifdef _WIN32
128
  if (key.length() > 0 && key[0] == '=') return;
129
#endif
130
522
  uv_os_setenv(*key, *val);
131
522
  DateTimeConfigurationChangeNotification(isolate, key);
132
522
}
133
134
51685
int32_t RealEnvStore::Query(const char* key) const {
135
103370
  Mutex::ScopedLock lock(per_process::env_var_mutex);
136
137
  char val[2];
138
51685
  size_t init_sz = sizeof(val);
139
51685
  int ret = uv_os_getenv(key, val, &init_sz);
140
141
51685
  if (ret == UV_ENOENT) {
142
3
    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
51682
  return 0;
154
}
155
156
51685
int32_t RealEnvStore::Query(Isolate* isolate, Local<String> property) const {
157
103370
  node::Utf8Value key(isolate, property);
158
103370
  return Query(*key);
159
}
160
161
2
void RealEnvStore::Delete(Isolate* isolate, Local<String> property) {
162
4
  Mutex::ScopedLock lock(per_process::env_var_mutex);
163
164
4
  node::Utf8Value key(isolate, property);
165
2
  uv_os_unsetenv(*key);
166
2
  DateTimeConfigurationChangeNotification(isolate, key);
167
2
}
168
169
556
Local<Array> RealEnvStore::Enumerate(Isolate* isolate) const {
170
1112
  Mutex::ScopedLock lock(per_process::env_var_mutex);
171
  uv_env_item_t* items;
172
  int count;
173
174
1668
  auto cleanup = OnScopeLeave([&]() { uv_os_free_environ(items, count); });
175
556
  CHECK_EQ(uv_os_environ(&items, &count), 0);
176
177
1112
  MaybeStackBuffer<Local<Value>, 256> env_v(count);
178
556
  int env_v_index = 0;
179
39102
  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
38546
    MaybeLocal<String> str = String::NewFromUtf8(isolate, items[i].name);
185
38546
    if (str.IsEmpty()) {
186
      isolate->ThrowException(ERR_STRING_TOO_LONG(isolate));
187
      return Local<Array>();
188
    }
189
77092
    env_v[env_v_index++] = str.ToLocalChecked();
190
  }
191
192
556
  return Array::New(isolate, env_v.out(), env_v_index);
193
}
194
195
std::shared_ptr<KVStore> KVStore::Clone(Isolate* isolate) const {
196
  HandleScope handle_scope(isolate);
197
  Local<Context> context = isolate->GetCurrentContext();
198
199
  std::shared_ptr<KVStore> copy = KVStore::CreateMapKVStore();
200
  Local<Array> keys = Enumerate(isolate);
201
  uint32_t keys_length = keys->Length();
202
  for (uint32_t i = 0; i < keys_length; i++) {
203
    Local<Value> key = keys->Get(context, i).ToLocalChecked();
204
    CHECK(key->IsString());
205
    copy->Set(isolate,
206
              key.As<String>(),
207
              Get(isolate, key.As<String>()).ToLocalChecked());
208
  }
209
  return copy;
210
}
211
212
Maybe<std::string> MapKVStore::Get(const char* key) const {
213
  Mutex::ScopedLock lock(mutex_);
214
  auto it = map_.find(key);
215
  return it == map_.end() ? Nothing<std::string>() : Just(it->second);
216
}
217
218
MaybeLocal<String> MapKVStore::Get(Isolate* isolate, Local<String> key) const {
219
  Utf8Value str(isolate, key);
220
  Maybe<std::string> value = Get(*str);
221
  if (value.IsNothing()) return Local<String>();
222
  std::string val = value.FromJust();
223
  return String::NewFromUtf8(
224
      isolate, val.data(), NewStringType::kNormal, val.size());
225
}
226
227
void MapKVStore::Set(Isolate* isolate, Local<String> key, Local<String> value) {
228
  Mutex::ScopedLock lock(mutex_);
229
  Utf8Value key_str(isolate, key);
230
  Utf8Value value_str(isolate, value);
231
  if (*key_str != nullptr && key_str.length() > 0 && *value_str != nullptr) {
232
    map_[std::string(*key_str, key_str.length())] =
233
        std::string(*value_str, value_str.length());
234
  }
235
}
236
237
int32_t MapKVStore::Query(const char* key) const {
238
  Mutex::ScopedLock lock(mutex_);
239
  return map_.find(key) == map_.end() ? -1 : 0;
240
}
241
242
int32_t MapKVStore::Query(Isolate* isolate, Local<String> key) const {
243
  Utf8Value str(isolate, key);
244
  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
Local<Array> MapKVStore::Enumerate(Isolate* isolate) const {
254
  Mutex::ScopedLock lock(mutex_);
255
  std::vector<Local<Value>> values;
256
  values.reserve(map_.size());
257
  for (const auto& pair : map_) {
258
    values.emplace_back(
259
        String::NewFromUtf8(isolate, pair.first.data(),
260
                            NewStringType::kNormal, pair.first.size())
261
            .ToLocalChecked());
262
  }
263
  return Array::New(isolate, values.data(), values.size());
264
}
265
266
std::shared_ptr<KVStore> MapKVStore::Clone(Isolate* isolate) const {
267
  return std::make_shared<MapKVStore>(*this);
268
}
269
270
std::shared_ptr<KVStore> KVStore::CreateMapKVStore() {
271
  return std::make_shared<MapKVStore>();
272
}
273
274
Maybe<bool> KVStore::AssignFromObject(Local<Context> context,
275
                                      Local<Object> entries) {
276
  Isolate* isolate = context->GetIsolate();
277
  HandleScope handle_scope(isolate);
278
  Local<Array> keys;
279
  if (!entries->GetOwnPropertyNames(context).ToLocal(&keys))
280
    return Nothing<bool>();
281
  uint32_t keys_length = keys->Length();
282
  for (uint32_t i = 0; i < keys_length; i++) {
283
    Local<Value> key;
284
    if (!keys->Get(context, i).ToLocal(&key))
285
      return Nothing<bool>();
286
    if (!key->IsString()) continue;
287
288
    Local<Value> value;
289
    Local<String> value_string;
290
    if (!entries->Get(context, key).ToLocal(&value) ||
291
        !value->ToString(context).ToLocal(&value_string)) {
292
      return Nothing<bool>();
293
    }
294
295
    Set(isolate, key.As<String>(), value_string);
296
  }
297
  return Just(true);
298
}
299
300
68852
static void EnvGetter(Local<Name> property,
301
                      const PropertyCallbackInfo<Value>& info) {
302
68852
  Environment* env = Environment::GetCurrent(info);
303
68852
  CHECK(env->has_run_bootstrapping_code());
304
68852
  if (property->IsSymbol()) {
305
    return info.GetReturnValue().SetUndefined();
306
  }
307
137704
  CHECK(property->IsString());
308
  MaybeLocal<String> value_string =
309
137704
      env->env_vars()->Get(env->isolate(), property.As<String>());
310
68852
  if (!value_string.IsEmpty()) {
311
131250
    info.GetReturnValue().Set(value_string.ToLocalChecked());
312
  }
313
}
314
315
522
static void EnvSetter(Local<Name> property,
316
                      Local<Value> value,
317
                      const PropertyCallbackInfo<Value>& info) {
318
522
  Environment* env = Environment::GetCurrent(info);
319
522
  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


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

1566
      !value->IsNumber() && !value->IsBoolean() &&
325
      env->EmitProcessEnvWarning()) {
326
    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
      return;
335
  }
336
337
  Local<String> key;
338
  Local<String> value_string;
339

2610
  if (!property->ToString(env->context()).ToLocal(&key) ||
340
2088
      !value->ToString(env->context()).ToLocal(&value_string)) {
341
    return;
342
  }
343
344
522
  env->env_vars()->Set(env->isolate(), key, value_string);
345
346
  // Whether it worked or not, always return value.
347
1044
  info.GetReturnValue().Set(value);
348
}
349
350
51685
static void EnvQuery(Local<Name> property,
351
                     const PropertyCallbackInfo<Integer>& info) {
352
51685
  Environment* env = Environment::GetCurrent(info);
353
51685
  CHECK(env->has_run_bootstrapping_code());
354
103370
  if (property->IsString()) {
355
103370
    int32_t rc = env->env_vars()->Query(env->isolate(), property.As<String>());
356
155049
    if (rc != -1) info.GetReturnValue().Set(rc);
357
  }
358
51685
}
359
360
2
static void EnvDeleter(Local<Name> property,
361
                       const PropertyCallbackInfo<Boolean>& info) {
362
2
  Environment* env = Environment::GetCurrent(info);
363
2
  CHECK(env->has_run_bootstrapping_code());
364
4
  if (property->IsString()) {
365
4
    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
4
  info.GetReturnValue().Set(true);
371
2
}
372
373
556
static void EnvEnumerator(const PropertyCallbackInfo<Array>& info) {
374
556
  Environment* env = Environment::GetCurrent(info);
375
556
  CHECK(env->has_run_bootstrapping_code());
376
377
1668
  info.GetReturnValue().Set(
378
1112
      env->env_vars()->Enumerate(env->isolate()));
379
556
}
380
381
52
MaybeLocal<Object> CreateEnvVarProxy(Local<Context> context, Isolate* isolate) {
382
52
  EscapableHandleScope scope(isolate);
383
52
  Local<ObjectTemplate> env_proxy_template = ObjectTemplate::New(isolate);
384
156
  env_proxy_template->SetHandler(NamedPropertyHandlerConfiguration(
385
      EnvGetter, EnvSetter, EnvQuery, EnvDeleter, EnvEnumerator, Local<Value>(),
386
52
      PropertyHandlerFlags::kHasNoSideEffect));
387
104
  return scope.EscapeMaybe(env_proxy_template->NewInstance(context));
388
}
389
390
107
void RegisterEnvVarExternalReferences(ExternalReferenceRegistry* registry) {
391
107
  registry->Register(EnvGetter);
392
107
  registry->Register(EnvSetter);
393
107
  registry->Register(EnvQuery);
394
107
  registry->Register(EnvDeleter);
395
107
  registry->Register(EnvEnumerator);
396
107
}
397
}  // namespace node
398
399

473
NODE_MODULE_EXTERNAL_REFERENCE(env_var, node::RegisterEnvVarExternalReferences)