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-09-25 22:36:03 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
9614
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
215
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
212
  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
5011
Mutex env_var_mutex;
59
5011
std::shared_ptr<KVStore> system_environment = std::make_shared<RealEnvStore>();
60
}  // namespace per_process
61
62
template <typename T>
63
15515
void DateTimeConfigurationChangeNotification(Isolate* isolate, const T& key) {
64


15515
  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
15515
}
74
75
1033498
MaybeLocal<String> RealEnvStore::Get(Isolate* isolate,
76
                                     Local<String> property) const {
77
1033498
  Mutex::ScopedLock lock(per_process::env_var_mutex);
78
79
2066996
  node::Utf8Value key(isolate, property);
80
1033498
  size_t init_sz = 256;
81
2066996
  MaybeStackBuffer<char, 256> val;
82
1033498
  int ret = uv_os_getenv(*key, *val, &init_sz);
83
84
1033498
  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
1033498
  if (ret >= 0) {  // Env key value fetch success.
92
    MaybeLocal<String> value_string =
93
970536
        String::NewFromUtf8(isolate, *val, NewStringType::kNormal, init_sz);
94
970536
    return value_string;
95
  }
96
97
1096460
  return MaybeLocal<String>();
98
}
99
100
14440
void RealEnvStore::Set(Isolate* isolate,
101
                       Local<String> property,
102
                       Local<String> value) {
103
14440
  Mutex::ScopedLock lock(per_process::env_var_mutex);
104
105
28880
  node::Utf8Value key(isolate, property);
106
28880
  node::Utf8Value val(isolate, value);
107
108
#ifdef _WIN32
109
  if (key[0] == L'=') return;
110
#endif
111
14440
  uv_os_setenv(*key, *val);
112
28880
  DateTimeConfigurationChangeNotification(isolate, key);
113
14440
}
114
115
1495007
int32_t RealEnvStore::Query(Isolate* isolate, Local<String> property) const {
116
1495007
  Mutex::ScopedLock lock(per_process::env_var_mutex);
117
118
2990014
  node::Utf8Value key(isolate, property);
119
120
  char val[2];
121
1495007
  size_t init_sz = sizeof(val);
122
1495007
  int ret = uv_os_getenv(*key, val, &init_sz);
123
124
1495007
  if (ret == UV_ENOENT) {
125
5455
    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
2984559
  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
14105
Local<Array> RealEnvStore::Enumerate(Isolate* isolate) const {
148
14105
  Mutex::ScopedLock lock(per_process::env_var_mutex);
149
  uv_env_item_t* items;
150
  int count;
151
152
42315
  OnScopeLeave cleanup([&]() { uv_os_free_environ(items, count); });
153
14105
  CHECK_EQ(uv_os_environ(&items, &count), 0);
154
155
28210
  MaybeStackBuffer<Local<Value>, 256> env_v(count);
156
14105
  int env_v_index = 0;
157
926288
  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
912183
        isolate, items[i].name, NewStringType::kNormal);
166
912183
    if (str.IsEmpty()) {
167
      isolate->ThrowException(ERR_STRING_TOO_LONG(isolate));
168
      return Local<Array>();
169
    }
170
1824366
    env_v[env_v_index++] = str.ToLocalChecked();
171
  }
172
173
28210
  return Array::New(isolate, env_v.out(), env_v_index);
174
}
175
176
211
std::shared_ptr<KVStore> KVStore::Clone(v8::Isolate* isolate) const {
177
211
  HandleScope handle_scope(isolate);
178
211
  Local<Context> context = isolate->GetCurrentContext();
179
180
211
  std::shared_ptr<KVStore> copy = KVStore::CreateMapKVStore();
181
211
  Local<Array> keys = Enumerate(isolate);
182
211
  uint32_t keys_length = keys->Length();
183
13754
  for (uint32_t i = 0; i < keys_length; i++) {
184
27086
    Local<Value> key = keys->Get(context, i).ToLocalChecked();
185
27086
    CHECK(key->IsString());
186
13543
    copy->Set(isolate,
187
              key.As<String>(),
188
40629
              Get(isolate, key.As<String>()).ToLocalChecked());
189
  }
190
211
  return copy;
191
}
192
193
26100
MaybeLocal<String> MapKVStore::Get(Isolate* isolate, Local<String> key) const {
194
26100
  Mutex::ScopedLock lock(mutex_);
195
52200
  Utf8Value str(isolate, key);
196
26100
  auto it = map_.find(std::string(*str, str.length()));
197
27207
  if (it == map_.end()) return Local<String>();
198
24993
  return String::NewFromUtf8(isolate, it->second.data(),
199
76086
                             NewStringType::kNormal, it->second.size());
200
}
201
202
13548
void MapKVStore::Set(Isolate* isolate, Local<String> key, Local<String> value) {
203
13548
  Mutex::ScopedLock lock(mutex_);
204
27096
  Utf8Value key_str(isolate, key);
205
27096
  Utf8Value value_str(isolate, value);
206

13548
  if (*key_str != nullptr && *value_str != nullptr) {
207
40644
    map_[std::string(*key_str, key_str.length())] =
208
27096
        std::string(*value_str, value_str.length());
209
13548
  }
210
13548
}
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
212
std::shared_ptr<KVStore> KVStore::CreateMapKVStore() {
243
212
  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
1031583
static void EnvGetter(Local<Name> property,
273
                      const PropertyCallbackInfo<Value>& info) {
274
1031583
  Environment* env = Environment::GetCurrent(info);
275
1031583
  if (property->IsSymbol()) {
276
1044543
    return info.GetReturnValue().SetUndefined();
277
  }
278
2050206
  CHECK(property->IsString());
279
  MaybeLocal<String> value_string =
280
2050206
      env->env_vars()->Get(env->isolate(), property.As<String>());
281
1025103
  if (!value_string.IsEmpty()) {
282
1943166
    info.GetReturnValue().Set(value_string.ToLocalChecked());
283
  }
284
}
285
286
14446
static void EnvSetter(Local<Name> property,
287
                      Local<Value> value,
288
                      const PropertyCallbackInfo<Value>& info) {
289
14446
  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


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

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


86674
  if (!property->ToString(env->context()).ToLocal(&key) ||
310
57781
      !value->ToString(env->context()).ToLocal(&value_string)) {
311
2
    return;
312
  }
313
314
14444
  env->env_vars()->Set(env->isolate(), key, value_string);
315
316
  // Whether it worked or not, always return value.
317
28888
  info.GetReturnValue().Set(value);
318
}
319
320
1542559
static void EnvQuery(Local<Name> property,
321
                     const PropertyCallbackInfo<Integer>& info) {
322
1542559
  Environment* env = Environment::GetCurrent(info);
323
3085118
  if (property->IsString()) {
324
3085116
    int32_t rc = env->env_vars()->Query(env->isolate(), property.As<String>());
325
4616040
    if (rc != -1) info.GetReturnValue().Set(rc);
326
  }
327
1542559
}
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
14612
static void EnvEnumerator(const PropertyCallbackInfo<Array>& info) {
342
14612
  Environment* env = Environment::GetCurrent(info);
343
344
  info.GetReturnValue().Set(
345
43836
      env->env_vars()->Enumerate(env->isolate()));
346
14612
}
347
348
5158
MaybeLocal<Object> CreateEnvVarProxy(Local<Context> context,
349
                                     Isolate* isolate,
350
                                     Local<Object> data) {
351
5158
  EscapableHandleScope scope(isolate);
352
5158
  Local<ObjectTemplate> env_proxy_template = ObjectTemplate::New(isolate);
353
  env_proxy_template->SetHandler(NamedPropertyHandlerConfiguration(
354
      EnvGetter, EnvSetter, EnvQuery, EnvDeleter, EnvEnumerator, data,
355
10316
      PropertyHandlerFlags::kHasNoSideEffect));
356
10316
  return scope.EscapeMaybe(env_proxy_template->NewInstance(context));
357
}
358

15033
}  // namespace node