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: 155 166 93.4 %
Date: 2019-10-06 22:30:00 Branches: 73 102 71.6 %

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


15426
  if (key.length() == 2 && key[0] == 'T' && key[1] == 'Z') {
65
#ifdef __POSIX__
66
4
    tzset();
67
#else
68
    _tzset();
69
#endif
70
4
    auto constexpr time_zone_detection = Isolate::TimeZoneDetection::kRedetect;
71
4
    isolate->DateTimeConfigurationChangeNotification(time_zone_detection);
72
  }
73
15426
}
74
75
1025838
MaybeLocal<String> RealEnvStore::Get(Isolate* isolate,
76
                                     Local<String> property) const {
77
1025838
  Mutex::ScopedLock lock(per_process::env_var_mutex);
78
79
2051676
  node::Utf8Value key(isolate, property);
80
1025838
  size_t init_sz = 256;
81
2051676
  MaybeStackBuffer<char, 256> val;
82
1025838
  int ret = uv_os_getenv(*key, *val, &init_sz);
83
84
1025838
  if (ret == UV_ENOBUFS) {
85
    // Buffer is not large enough, reallocate to the updated init_sz
86
    // and fetch env value again.
87
    val.AllocateSufficientStorage(init_sz);
88
    ret = uv_os_getenv(*key, *val, &init_sz);
89
  }
90
91
1025838
  if (ret >= 0) {  // Env key value fetch success.
92
    MaybeLocal<String> value_string =
93
962476
        String::NewFromUtf8(isolate, *val, NewStringType::kNormal, init_sz);
94
962476
    return value_string;
95
  }
96
97
1089200
  return MaybeLocal<String>();
98
}
99
100
14351
void RealEnvStore::Set(Isolate* isolate,
101
                       Local<String> property,
102
                       Local<String> value) {
103
14351
  Mutex::ScopedLock lock(per_process::env_var_mutex);
104
105
28702
  node::Utf8Value key(isolate, property);
106
28702
  node::Utf8Value val(isolate, value);
107
108
#ifdef _WIN32
109
  if (key[0] == L'=') return;
110
#endif
111
14351
  uv_os_setenv(*key, *val);
112
28702
  DateTimeConfigurationChangeNotification(isolate, key);
113
14351
}
114
115
1477348
int32_t RealEnvStore::Query(Isolate* isolate, Local<String> property) const {
116
1477348
  Mutex::ScopedLock lock(per_process::env_var_mutex);
117
118
2954696
  node::Utf8Value key(isolate, property);
119
120
  char val[2];
121
1477348
  size_t init_sz = sizeof(val);
122
1477348
  int ret = uv_os_getenv(*key, val, &init_sz);
123
124
1477348
  if (ret == UV_ENOENT) {
125
5464
    return -1;
126
  }
127
128
#ifdef _WIN32
129
  if (key[0] == L'=') {
130
    return static_cast<int32_t>(v8::ReadOnly) |
131
           static_cast<int32_t>(v8::DontDelete) |
132
           static_cast<int32_t>(v8::DontEnum);
133
  }
134
#endif
135
136
2949232
  return 0;
137
}
138
139
1075
void RealEnvStore::Delete(Isolate* isolate, Local<String> property) {
140
1075
  Mutex::ScopedLock lock(per_process::env_var_mutex);
141
142
2150
  node::Utf8Value key(isolate, property);
143
1075
  uv_os_unsetenv(*key);
144
2150
  DateTimeConfigurationChangeNotification(isolate, key);
145
1075
}
146
147
13973
Local<Array> RealEnvStore::Enumerate(Isolate* isolate) const {
148
13973
  Mutex::ScopedLock lock(per_process::env_var_mutex);
149
  uv_env_item_t* items;
150
  int count;
151
152
41919
  OnScopeLeave cleanup([&]() { uv_os_free_environ(items, count); });
153
13973
  CHECK_EQ(uv_os_environ(&items, &count), 0);
154
155
27946
  MaybeStackBuffer<Local<Value>, 256> env_v(count);
156
13973
  int env_v_index = 0;
157
917705
  for (int i = 0; i < count; i++) {
158
#ifdef _WIN32
159
    // If the key starts with '=' it is a hidden environment variable.
160
    // The '\0' check is a workaround for the bug behind
161
    // https://github.com/libuv/libuv/pull/2473 and can be removed later.
162
    if (items[i].name[0] == '=' || items[i].name[0] == '\0') continue;
163
#endif
164
    MaybeLocal<String> str = String::NewFromUtf8(
165
903732
        isolate, items[i].name, NewStringType::kNormal);
166
903732
    if (str.IsEmpty()) {
167
      isolate->ThrowException(ERR_STRING_TOO_LONG(isolate));
168
      return Local<Array>();
169
    }
170
1807464
    env_v[env_v_index++] = str.ToLocalChecked();
171
  }
172
173
27946
  return Array::New(isolate, env_v.out(), env_v_index);
174
}
175
176
213
std::shared_ptr<KVStore> KVStore::Clone(v8::Isolate* isolate) const {
177
213
  HandleScope handle_scope(isolate);
178
213
  Local<Context> context = isolate->GetCurrentContext();
179
180
213
  std::shared_ptr<KVStore> copy = KVStore::CreateMapKVStore();
181
213
  Local<Array> keys = Enumerate(isolate);
182
213
  uint32_t keys_length = keys->Length();
183
13885
  for (uint32_t i = 0; i < keys_length; i++) {
184
27344
    Local<Value> key = keys->Get(context, i).ToLocalChecked();
185
27344
    CHECK(key->IsString());
186
13672
    copy->Set(isolate,
187
              key.As<String>(),
188
41016
              Get(isolate, key.As<String>()).ToLocalChecked());
189
  }
190
213
  return copy;
191
}
192
193
26125
MaybeLocal<String> MapKVStore::Get(Isolate* isolate, Local<String> key) const {
194
26125
  Mutex::ScopedLock lock(mutex_);
195
52251
  Utf8Value str(isolate, key);
196
26126
  auto it = map_.find(std::string(*str, str.length()));
197
27245
  if (it == map_.end()) return Local<String>();
198
25007
  return String::NewFromUtf8(isolate, it->second.data(),
199
76139
                             NewStringType::kNormal, it->second.size());
200
}
201
202
13677
void MapKVStore::Set(Isolate* isolate, Local<String> key, Local<String> value) {
203
13677
  Mutex::ScopedLock lock(mutex_);
204
27354
  Utf8Value key_str(isolate, key);
205
27354
  Utf8Value value_str(isolate, value);
206

13677
  if (*key_str != nullptr && *value_str != nullptr) {
207
41031
    map_[std::string(*key_str, key_str.length())] =
208
27354
        std::string(*value_str, value_str.length());
209
13677
  }
210
13677
}
211
212
47551
int32_t MapKVStore::Query(Isolate* isolate, Local<String> key) const {
213
47551
  Mutex::ScopedLock lock(mutex_);
214
95102
  Utf8Value str(isolate, key);
215
47551
  auto it = map_.find(std::string(*str, str.length()));
216
95102
  return it == map_.end() ? -1 : 0;
217
}
218
219
void MapKVStore::Delete(Isolate* isolate, Local<String> key) {
220
  Mutex::ScopedLock lock(mutex_);
221
  Utf8Value str(isolate, key);
222
  map_.erase(std::string(*str, str.length()));
223
}
224
225
718
Local<Array> MapKVStore::Enumerate(Isolate* isolate) const {
226
718
  Mutex::ScopedLock lock(mutex_);
227
1436
  std::vector<Local<Value>> values;
228
718
  values.reserve(map_.size());
229
47840
  for (const auto& pair : map_) {
230
    values.emplace_back(
231
        String::NewFromUtf8(isolate, pair.first.data(),
232
47122
                            NewStringType::kNormal, pair.first.size())
233
94244
            .ToLocalChecked());
234
  }
235
1436
  return Array::New(isolate, values.data(), values.size());
236
}
237
238
4
std::shared_ptr<KVStore> MapKVStore::Clone(Isolate* isolate) const {
239
4
  return std::make_shared<MapKVStore>(*this);
240
}
241
242
214
std::shared_ptr<KVStore> KVStore::CreateMapKVStore() {
243
214
  return std::make_shared<MapKVStore>();
244
}
245
246
1
Maybe<bool> KVStore::AssignFromObject(Local<Context> context,
247
                                      Local<Object> entries) {
248
1
  Isolate* isolate = context->GetIsolate();
249
1
  HandleScope handle_scope(isolate);
250
  Local<Array> keys;
251
2
  if (!entries->GetOwnPropertyNames(context).ToLocal(&keys))
252
    return Nothing<bool>();
253
1
  uint32_t keys_length = keys->Length();
254
2
  for (uint32_t i = 0; i < keys_length; i++) {
255
    Local<Value> key;
256
2
    if (!keys->Get(context, i).ToLocal(&key))
257
      return Nothing<bool>();
258
2
    if (!key->IsString()) continue;
259
260
    Local<Value> value;
261
    Local<String> value_string;
262


7
    if (!entries->Get(context, key.As<String>()).ToLocal(&value) ||
263
3
        !value->ToString(context).ToLocal(&value_string)) {
264
      return Nothing<bool>();
265
    }
266
267
2
    Set(isolate, key.As<String>(), value_string);
268
  }
269
1
  return Just(true);
270
}
271
272
1023606
static void EnvGetter(Local<Name> property,
273
                      const PropertyCallbackInfo<Value>& info) {
274
1023606
  Environment* env = Environment::GetCurrent(info);
275
1023609
  if (property->IsSymbol()) {
276
1036569
    return info.GetReturnValue().SetUndefined();
277
  }
278
2034258
  CHECK(property->IsString());
279
  MaybeLocal<String> value_string =
280
2034256
      env->env_vars()->Get(env->isolate(), property.As<String>());
281
1017129
  if (!value_string.IsEmpty()) {
282
1926608
    info.GetReturnValue().Set(value_string.ToLocalChecked());
283
  }
284
}
285
286
14357
static void EnvSetter(Local<Name> property,
287
                      Local<Value> value,
288
                      const PropertyCallbackInfo<Value>& info) {
289
14357
  Environment* env = Environment::GetCurrent(info);
290
  // calling env->EmitProcessEnvWarning() sets a variable indicating that
291
  // warnings have been emitted. It should be called last after other
292
  // conditions leading to a warning have been met.
293


43102
  if (env->options()->pending_deprecation && !value->IsString() &&
294

43074
      !value->IsNumber() && !value->IsBoolean() &&
295
1
      env->EmitProcessEnvWarning()) {
296
2
    if (ProcessEmitDeprecationWarning(
297
            env,
298
            "Assigning any value other than a string, number, or boolean to a "
299
            "process.env property is deprecated. Please make sure to convert "
300
            "the "
301
            "value to a string before setting process.env with it.",
302
            "DEP0104")
303
2
            .IsNothing())
304
2
      return;
305
  }
306
307
  Local<String> key;
308
  Local<String> value_string;
309


86140
  if (!property->ToString(env->context()).ToLocal(&key) ||
310
57425
      !value->ToString(env->context()).ToLocal(&value_string)) {
311
2
    return;
312
  }
313
314
14355
  env->env_vars()->Set(env->isolate(), key, value_string);
315
316
  // Whether it worked or not, always return value.
317
28710
  info.GetReturnValue().Set(value);
318
}
319
320
1524900
static void EnvQuery(Local<Name> property,
321
                     const PropertyCallbackInfo<Integer>& info) {
322
1524900
  Environment* env = Environment::GetCurrent(info);
323
3049800
  if (property->IsString()) {
324
3049798
    int32_t rc = env->env_vars()->Query(env->isolate(), property.As<String>());
325
4563045
    if (rc != -1) info.GetReturnValue().Set(rc);
326
  }
327
1524900
}
328
329
1076
static void EnvDeleter(Local<Name> property,
330
                       const PropertyCallbackInfo<Boolean>& info) {
331
1076
  Environment* env = Environment::GetCurrent(info);
332
2152
  if (property->IsString()) {
333
2150
    env->env_vars()->Delete(env->isolate(), property.As<String>());
334
  }
335
336
  // process.env never has non-configurable properties, so always
337
  // return true like the tc39 delete operator.
338
2152
  info.GetReturnValue().Set(true);
339
1076
}
340
341
14478
static void EnvEnumerator(const PropertyCallbackInfo<Array>& info) {
342
14478
  Environment* env = Environment::GetCurrent(info);
343
344
  info.GetReturnValue().Set(
345
43434
      env->env_vars()->Enumerate(env->isolate()));
346
14478
}
347
348
5209
MaybeLocal<Object> CreateEnvVarProxy(Local<Context> context,
349
                                     Isolate* isolate,
350
                                     Local<Object> data) {
351
5209
  EscapableHandleScope scope(isolate);
352
5209
  Local<ObjectTemplate> env_proxy_template = ObjectTemplate::New(isolate);
353
  env_proxy_template->SetHandler(NamedPropertyHandlerConfiguration(
354
      EnvGetter, EnvSetter, EnvQuery, EnvDeleter, EnvEnumerator, data,
355
10418
      PropertyHandlerFlags::kHasNoSideEffect));
356
10418
  return scope.EscapeMaybe(env_proxy_template->NewInstance(context));
357
}
358

15177
}  // namespace node