GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_env_var.cc Lines: 178 187 95.2 %
Date: 2021-09-16 04:12:46 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_i18n.h"
6
#include "node_process-inl.h"
7
8
#include <time.h>  // tzset(), _tzset()
9
10
namespace node {
11
using v8::Array;
12
using v8::Boolean;
13
using v8::Context;
14
using v8::DontDelete;
15
using v8::DontEnum;
16
using v8::EscapableHandleScope;
17
using v8::HandleScope;
18
using v8::Integer;
19
using v8::Isolate;
20
using v8::Just;
21
using v8::Local;
22
using v8::Maybe;
23
using v8::MaybeLocal;
24
using v8::Name;
25
using v8::NamedPropertyHandlerConfiguration;
26
using v8::NewStringType;
27
using v8::Nothing;
28
using v8::Object;
29
using v8::ObjectTemplate;
30
using v8::PropertyCallbackInfo;
31
using v8::PropertyHandlerFlags;
32
using v8::ReadOnly;
33
using v8::String;
34
using v8::Value;
35
36
class RealEnvStore final : public KVStore {
37
 public:
38
  MaybeLocal<String> Get(Isolate* isolate, Local<String> key) const override;
39
  Maybe<std::string> Get(const char* key) const override;
40
  void Set(Isolate* isolate, Local<String> key, Local<String> value) override;
41
  int32_t Query(Isolate* isolate, Local<String> key) const override;
42
  int32_t Query(const char* key) const override;
43
  void Delete(Isolate* isolate, Local<String> key) override;
44
  Local<Array> Enumerate(Isolate* isolate) const override;
45
};
46
47
class MapKVStore final : public KVStore {
48
 public:
49
  MaybeLocal<String> Get(Isolate* isolate, Local<String> key) const override;
50
  Maybe<std::string> Get(const char* key) const override;
51
  void Set(Isolate* isolate, Local<String> key, Local<String> value) override;
52
  int32_t Query(Isolate* isolate, Local<String> key) const override;
53
  int32_t Query(const char* key) const override;
54
  void Delete(Isolate* isolate, Local<String> key) override;
55
  Local<Array> Enumerate(Isolate* isolate) const override;
56
57
  std::shared_ptr<KVStore> Clone(Isolate* isolate) const override;
58
59
798
  MapKVStore() = default;
60
10
  MapKVStore(const MapKVStore& other) : KVStore(), map_(other.map_) {}
61
62
 private:
63
  mutable Mutex mutex_;
64
  std::unordered_map<std::string, std::string> map_;
65
};
66
67
namespace per_process {
68
Mutex env_var_mutex;
69
std::shared_ptr<KVStore> system_environment = std::make_shared<RealEnvStore>();
70
}  // namespace per_process
71
72
template <typename T>
73
8047
void DateTimeConfigurationChangeNotification(
74
    Isolate* isolate,
75
    const T& key,
76
    const char* val = nullptr) {
77


8047
  if (key.length() == 2 && key[0] == 'T' && key[1] == 'Z') {
78
#ifdef __POSIX__
79
8
    tzset();
80
8
    isolate->DateTimeConfigurationChangeNotification(
81
        Isolate::TimeZoneDetection::kRedetect);
82
#else
83
    _tzset();
84
85
# if defined(NODE_HAVE_I18N_SUPPORT)
86
    isolate->DateTimeConfigurationChangeNotification(
87
        Isolate::TimeZoneDetection::kSkip);
88
89
    // On windows, the TZ environment is not supported out of the box.
90
    // By default, v8 will only be able to detect the system configured
91
    // timezone. This supports using the TZ environment variable to set
92
    // the default timezone instead.
93
    if (val != nullptr) i18n::SetDefaultTimeZone(val);
94
# else
95
    isolate->DateTimeConfigurationChangeNotification(
96
        Isolate::TimeZoneDetection::kRedetect);
97
# endif
98
#endif
99
  }
100
8047
}
101
102
595170
Maybe<std::string> RealEnvStore::Get(const char* key) const {
103
1190340
  Mutex::ScopedLock lock(per_process::env_var_mutex);
104
105
595170
  size_t init_sz = 256;
106
1190340
  MaybeStackBuffer<char, 256> val;
107
595170
  int ret = uv_os_getenv(key, *val, &init_sz);
108
109
595170
  if (ret == UV_ENOBUFS) {
110
    // Buffer is not large enough, reallocate to the updated init_sz
111
    // and fetch env value again.
112
6416
    val.AllocateSufficientStorage(init_sz);
113
6416
    ret = uv_os_getenv(key, *val, &init_sz);
114
  }
115
116
595170
  if (ret >= 0) {  // Env key value fetch success.
117
532200
    return Just(std::string(*val, init_sz));
118
  }
119
120
62970
  return Nothing<std::string>();
121
}
122
123
595170
MaybeLocal<String> RealEnvStore::Get(Isolate* isolate,
124
                                     Local<String> property) const {
125
1190340
  node::Utf8Value key(isolate, property);
126
1190340
  Maybe<std::string> value = Get(*key);
127
128
595170
  if (value.IsJust()) {
129
532200
    std::string val = value.FromJust();
130
    return String::NewFromUtf8(
131
532200
        isolate, val.data(), NewStringType::kNormal, val.size());
132
  }
133
134
62970
  return MaybeLocal<String>();
135
}
136
137
7013
void RealEnvStore::Set(Isolate* isolate,
138
                       Local<String> property,
139
                       Local<String> value) {
140
14026
  Mutex::ScopedLock lock(per_process::env_var_mutex);
141
142
14026
  node::Utf8Value key(isolate, property);
143
14026
  node::Utf8Value val(isolate, value);
144
145
#ifdef _WIN32
146
  if (key.length() > 0 && key[0] == '=') return;
147
#endif
148
7013
  uv_os_setenv(*key, *val);
149
7013
  DateTimeConfigurationChangeNotification(isolate, key, *val);
150
7013
}
151
152
676187
int32_t RealEnvStore::Query(const char* key) const {
153
1352374
  Mutex::ScopedLock lock(per_process::env_var_mutex);
154
155
  char val[2];
156
676187
  size_t init_sz = sizeof(val);
157
676187
  int ret = uv_os_getenv(key, val, &init_sz);
158
159
676187
  if (ret == UV_ENOENT) {
160
5867
    return -1;
161
  }
162
163
#ifdef _WIN32
164
  if (key[0] == '=') {
165
    return static_cast<int32_t>(ReadOnly) |
166
           static_cast<int32_t>(DontDelete) |
167
           static_cast<int32_t>(DontEnum);
168
  }
169
#endif
170
171
670320
  return 0;
172
}
173
174
676187
int32_t RealEnvStore::Query(Isolate* isolate, Local<String> property) const {
175
1352374
  node::Utf8Value key(isolate, property);
176
676187
  return Query(*key);
177
}
178
179
1034
void RealEnvStore::Delete(Isolate* isolate, Local<String> property) {
180
2068
  Mutex::ScopedLock lock(per_process::env_var_mutex);
181
182
2068
  node::Utf8Value key(isolate, property);
183
1034
  uv_os_unsetenv(*key);
184
1034
  DateTimeConfigurationChangeNotification(isolate, key);
185
1034
}
186
187
8142
Local<Array> RealEnvStore::Enumerate(Isolate* isolate) const {
188
16284
  Mutex::ScopedLock lock(per_process::env_var_mutex);
189
  uv_env_item_t* items;
190
  int count;
191
192
24426
  auto cleanup = OnScopeLeave([&]() { uv_os_free_environ(items, count); });
193
8142
  CHECK_EQ(uv_os_environ(&items, &count), 0);
194
195
16284
  MaybeStackBuffer<Local<Value>, 256> env_v(count);
196
8142
  int env_v_index = 0;
197
603152
  for (int i = 0; i < count; i++) {
198
#ifdef _WIN32
199
    // If the key starts with '=' it is a hidden environment variable.
200
    if (items[i].name[0] == '=') continue;
201
#endif
202
595010
    MaybeLocal<String> str = String::NewFromUtf8(isolate, items[i].name);
203
595010
    if (str.IsEmpty()) {
204
      isolate->ThrowException(ERR_STRING_TOO_LONG(isolate));
205
      return Local<Array>();
206
    }
207
595010
    env_v[env_v_index++] = str.ToLocalChecked();
208
  }
209
210
8142
  return Array::New(isolate, env_v.out(), env_v_index);
211
}
212
213
772
std::shared_ptr<KVStore> KVStore::Clone(Isolate* isolate) const {
214
1544
  HandleScope handle_scope(isolate);
215
772
  Local<Context> context = isolate->GetCurrentContext();
216
217
772
  std::shared_ptr<KVStore> copy = KVStore::CreateMapKVStore();
218
772
  Local<Array> keys = Enumerate(isolate);
219
772
  uint32_t keys_length = keys->Length();
220
56403
  for (uint32_t i = 0; i < keys_length; i++) {
221
111262
    Local<Value> key = keys->Get(context, i).ToLocalChecked();
222
111262
    CHECK(key->IsString());
223
111262
    copy->Set(isolate,
224
              key.As<String>(),
225
166893
              Get(isolate, key.As<String>()).ToLocalChecked());
226
  }
227
772
  return copy;
228
}
229
230
34172
Maybe<std::string> MapKVStore::Get(const char* key) const {
231
34172
  Mutex::ScopedLock lock(mutex_);
232
34172
  auto it = map_.find(key);
233
34172
  return it == map_.end() ? Nothing<std::string>() : Just(it->second);
234
}
235
236
33128
MaybeLocal<String> MapKVStore::Get(Isolate* isolate, Local<String> key) const {
237
66256
  Utf8Value str(isolate, key);
238
66256
  Maybe<std::string> value = Get(*str);
239
35986
  if (value.IsNothing()) return Local<String>();
240
30270
  std::string val = value.FromJust();
241
  return String::NewFromUtf8(
242
30270
      isolate, val.data(), NewStringType::kNormal, val.size());
243
}
244
245
57371
void MapKVStore::Set(Isolate* isolate, Local<String> key, Local<String> value) {
246
114742
  Mutex::ScopedLock lock(mutex_);
247
114742
  Utf8Value key_str(isolate, key);
248
114742
  Utf8Value value_str(isolate, value);
249


57371
  if (*key_str != nullptr && key_str.length() > 0 && *value_str != nullptr) {
250
114742
    map_[std::string(*key_str, key_str.length())] =
251
172113
        std::string(*value_str, value_str.length());
252
  }
253
57371
}
254
255
53871
int32_t MapKVStore::Query(const char* key) const {
256
53871
  Mutex::ScopedLock lock(mutex_);
257
53871
  return map_.find(key) == map_.end() ? -1 : 0;
258
}
259
260
53871
int32_t MapKVStore::Query(Isolate* isolate, Local<String> key) const {
261
107742
  Utf8Value str(isolate, key);
262
53871
  return Query(*str);
263
}
264
265
void MapKVStore::Delete(Isolate* isolate, Local<String> key) {
266
  Mutex::ScopedLock lock(mutex_);
267
  Utf8Value str(isolate, key);
268
  map_.erase(std::string(*str, str.length()));
269
}
270
271
722
Local<Array> MapKVStore::Enumerate(Isolate* isolate) const {
272
1444
  Mutex::ScopedLock lock(mutex_);
273
1444
  std::vector<Local<Value>> values;
274
722
  values.reserve(map_.size());
275
53868
  for (const auto& pair : map_) {
276
53146
    values.emplace_back(
277
53146
        String::NewFromUtf8(isolate, pair.first.data(),
278
53146
                            NewStringType::kNormal, pair.first.size())
279
53146
            .ToLocalChecked());
280
  }
281
722
  return Array::New(isolate, values.data(), values.size());
282
}
283
284
10
std::shared_ptr<KVStore> MapKVStore::Clone(Isolate* isolate) const {
285
10
  return std::make_shared<MapKVStore>(*this);
286
}
287
288
798
std::shared_ptr<KVStore> KVStore::CreateMapKVStore() {
289
798
  return std::make_shared<MapKVStore>();
290
}
291
292
26
Maybe<bool> KVStore::AssignFromObject(Local<Context> context,
293
                                      Local<Object> entries) {
294
26
  Isolate* isolate = context->GetIsolate();
295
52
  HandleScope handle_scope(isolate);
296
  Local<Array> keys;
297
52
  if (!entries->GetOwnPropertyNames(context).ToLocal(&keys))
298
    return Nothing<bool>();
299
26
  uint32_t keys_length = keys->Length();
300
1758
  for (uint32_t i = 0; i < keys_length; i++) {
301
    Local<Value> key;
302
3464
    if (!keys->Get(context, i).ToLocal(&key))
303
      return Nothing<bool>();
304
3464
    if (!key->IsString()) continue;
305
306
    Local<Value> value;
307
    Local<String> value_string;
308
5196
    if (!entries->Get(context, key).ToLocal(&value) ||
309

5196
        !value->ToString(context).ToLocal(&value_string)) {
310
      return Nothing<bool>();
311
    }
312
313
3464
    Set(isolate, key.As<String>(), value_string);
314
  }
315
26
  return Just(true);
316
}
317
318
558268
static void EnvGetter(Local<Name> property,
319
                      const PropertyCallbackInfo<Value>& info) {
320
558268
  Environment* env = Environment::GetCurrent(info);
321
558268
  CHECK(env->has_run_bootstrapping_code());
322
558268
  if (property->IsSymbol()) {
323
16044
    return info.GetReturnValue().SetUndefined();
324
  }
325
1100492
  CHECK(property->IsString());
326
  MaybeLocal<String> value_string =
327
1100492
      env->env_vars()->Get(env->isolate(), property.As<String>());
328
550246
  if (!value_string.IsEmpty()) {
329
991106
    info.GetReturnValue().Set(value_string.ToLocalChecked());
330
  }
331
}
332
333
7023
static void EnvSetter(Local<Name> property,
334
                      Local<Value> value,
335
                      const PropertyCallbackInfo<Value>& info) {
336
7023
  Environment* env = Environment::GetCurrent(info);
337
7023
  CHECK(env->has_run_bootstrapping_code());
338
  // calling env->EmitProcessEnvWarning() sets a variable indicating that
339
  // warnings have been emitted. It should be called last after other
340
  // conditions leading to a warning have been met.
341

7071
  if (env->options()->pending_deprecation && !value->IsString() &&
342


7049
      !value->IsNumber() && !value->IsBoolean() &&
343
1
      env->EmitProcessEnvWarning()) {
344
1
    if (ProcessEmitDeprecationWarning(
345
            env,
346
            "Assigning any value other than a string, number, or boolean to a "
347
            "process.env property is deprecated. Please make sure to convert "
348
            "the "
349
            "value to a string before setting process.env with it.",
350
1
            "DEP0104")
351
1
            .IsNothing())
352
2
      return;
353
  }
354
355
  Local<String> key;
356
  Local<String> value_string;
357
21068
  if (!property->ToString(env->context()).ToLocal(&key) ||
358

21067
      !value->ToString(env->context()).ToLocal(&value_string)) {
359
2
    return;
360
  }
361
362
7021
  env->env_vars()->Set(env->isolate(), key, value_string);
363
364
  // Whether it worked or not, always return value.
365
14042
  info.GetReturnValue().Set(value);
366
}
367
368
730059
static void EnvQuery(Local<Name> property,
369
                     const PropertyCallbackInfo<Integer>& info) {
370
730059
  Environment* env = Environment::GetCurrent(info);
371
730059
  CHECK(env->has_run_bootstrapping_code());
372
1460118
  if (property->IsString()) {
373
1460116
    int32_t rc = env->env_vars()->Query(env->isolate(), property.As<String>());
374
2177716
    if (rc != -1) info.GetReturnValue().Set(rc);
375
  }
376
730059
}
377
378
1035
static void EnvDeleter(Local<Name> property,
379
                       const PropertyCallbackInfo<Boolean>& info) {
380
1035
  Environment* env = Environment::GetCurrent(info);
381
1035
  CHECK(env->has_run_bootstrapping_code());
382
2070
  if (property->IsString()) {
383
2068
    env->env_vars()->Delete(env->isolate(), property.As<String>());
384
  }
385
386
  // process.env never has non-configurable properties, so always
387
  // return true like the tc39 delete operator.
388
1035
  info.GetReturnValue().Set(true);
389
1035
}
390
391
8092
static void EnvEnumerator(const PropertyCallbackInfo<Array>& info) {
392
8092
  Environment* env = Environment::GetCurrent(info);
393
8092
  CHECK(env->has_run_bootstrapping_code());
394
395
8092
  info.GetReturnValue().Set(
396
16184
      env->env_vars()->Enumerate(env->isolate()));
397
8092
}
398
399
619
MaybeLocal<Object> CreateEnvVarProxy(Local<Context> context, Isolate* isolate) {
400
619
  EscapableHandleScope scope(isolate);
401
619
  Local<ObjectTemplate> env_proxy_template = ObjectTemplate::New(isolate);
402
1238
  env_proxy_template->SetHandler(NamedPropertyHandlerConfiguration(
403
      EnvGetter, EnvSetter, EnvQuery, EnvDeleter, EnvEnumerator, Local<Value>(),
404
      PropertyHandlerFlags::kHasNoSideEffect));
405
1238
  return scope.EscapeMaybe(env_proxy_template->NewInstance(context));
406
}
407
408
4850
void RegisterEnvVarExternalReferences(ExternalReferenceRegistry* registry) {
409
4850
  registry->Register(EnvGetter);
410
4850
  registry->Register(EnvSetter);
411
4850
  registry->Register(EnvQuery);
412
4850
  registry->Register(EnvDeleter);
413
4850
  registry->Register(EnvEnumerator);
414
4850
}
415
}  // namespace node
416
417
4850
NODE_MODULE_EXTERNAL_REFERENCE(env_var, node::RegisterEnvVarExternalReferences)