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-05 22:32:21 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
9447
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
212
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
209
  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
4944
Mutex env_var_mutex;
59
4944
std::shared_ptr<KVStore> system_environment = std::make_shared<RealEnvStore>();
60
}  // namespace per_process
61
62
template <typename T>
63
13990
void DateTimeConfigurationChangeNotification(Isolate* isolate, const T& key) {
64


13990
  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
13990
}
74
75
867220
MaybeLocal<String> RealEnvStore::Get(Isolate* isolate,
76
                                     Local<String> property) const {
77
867220
  Mutex::ScopedLock lock(per_process::env_var_mutex);
78
79
1734440
  node::Utf8Value key(isolate, property);
80
867220
  size_t init_sz = 256;
81
1734440
  MaybeStackBuffer<char, 256> val;
82
867220
  int ret = uv_os_getenv(*key, *val, &init_sz);
83
84
867220
  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
867220
  if (ret >= 0) {  // Env key value fetch success.
92
    MaybeLocal<String> value_string =
93
804558
        String::NewFromUtf8(isolate, *val, NewStringType::kNormal, init_sz);
94
804558
    return value_string;
95
  }
96
97
929882
  return MaybeLocal<String>();
98
}
99
100
12915
void RealEnvStore::Set(Isolate* isolate,
101
                       Local<String> property,
102
                       Local<String> value) {
103
12915
  Mutex::ScopedLock lock(per_process::env_var_mutex);
104
105
25830
  node::Utf8Value key(isolate, property);
106
25830
  node::Utf8Value val(isolate, value);
107
108
#ifdef _WIN32
109
  if (key[0] == L'=') return;
110
#endif
111
12915
  uv_os_setenv(*key, *val);
112
25830
  DateTimeConfigurationChangeNotification(isolate, key);
113
12915
}
114
115
1170063
int32_t RealEnvStore::Query(Isolate* isolate, Local<String> property) const {
116
1170063
  Mutex::ScopedLock lock(per_process::env_var_mutex);
117
118
2340126
  node::Utf8Value key(isolate, property);
119
120
  char val[2];
121
1170063
  size_t init_sz = sizeof(val);
122
1170063
  int ret = uv_os_getenv(*key, val, &init_sz);
123
124
1170063
  if (ret == UV_ENOENT) {
125
4435
    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
2335691
  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
10572
Local<Array> RealEnvStore::Enumerate(Isolate* isolate) const {
148
10572
  Mutex::ScopedLock lock(per_process::env_var_mutex);
149
  uv_env_item_t* items;
150
  int count;
151
152
31716
  OnScopeLeave cleanup([&]() { uv_os_free_environ(items, count); });
153
10572
  CHECK_EQ(uv_os_environ(&items, &count), 0);
154
155
21144
  MaybeStackBuffer<Local<Value>, 256> env_v(count);
156
10572
  int env_v_index = 0;
157
692526
  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
681954
        isolate, items[i].name, NewStringType::kNormal);
166
681954
    if (str.IsEmpty()) {
167
      isolate->ThrowException(ERR_STRING_TOO_LONG(isolate));
168
      return Local<Array>();
169
    }
170
1363908
    env_v[env_v_index++] = str.ToLocalChecked();
171
  }
172
173
21144
  return Array::New(isolate, env_v.out(), env_v_index);
174
}
175
176
208
std::shared_ptr<KVStore> KVStore::Clone(v8::Isolate* isolate) const {
177
208
  HandleScope handle_scope(isolate);
178
208
  Local<Context> context = isolate->GetCurrentContext();
179
180
208
  std::shared_ptr<KVStore> copy = KVStore::CreateMapKVStore();
181
208
  Local<Array> keys = Enumerate(isolate);
182
208
  uint32_t keys_length = keys->Length();
183
13558
  for (uint32_t i = 0; i < keys_length; i++) {
184
26700
    Local<Value> key = keys->Get(context, i).ToLocalChecked();
185
26700
    CHECK(key->IsString());
186
13350
    copy->Set(isolate,
187
              key.As<String>(),
188
40050
              Get(isolate, key.As<String>()).ToLocalChecked());
189
  }
190
208
  return copy;
191
}
192
193
9120
MaybeLocal<String> MapKVStore::Get(Isolate* isolate, Local<String> key) const {
194
9120
  Mutex::ScopedLock lock(mutex_);
195
18240
  Utf8Value str(isolate, key);
196
9121
  auto it = map_.find(std::string(*str, str.length()));
197
10218
  if (it == map_.end()) return Local<String>();
198
8022
  return String::NewFromUtf8(isolate, it->second.data(),
199
25165
                             NewStringType::kNormal, it->second.size());
200
}
201
202
13355
void MapKVStore::Set(Isolate* isolate, Local<String> key, Local<String> value) {
203
13355
  Mutex::ScopedLock lock(mutex_);
204
26710
  Utf8Value key_str(isolate, key);
205
26710
  Utf8Value value_str(isolate, value);
206

13355
  if (*key_str != nullptr && *value_str != nullptr) {
207
40065
    map_[std::string(*key_str, key_str.length())] =
208
26710
        std::string(*value_str, value_str.length());
209
13355
  }
210
13355
}
211
212
13370
int32_t MapKVStore::Query(Isolate* isolate, Local<String> key) const {
213
13370
  Mutex::ScopedLock lock(mutex_);
214
26740
  Utf8Value str(isolate, key);
215
13370
  auto it = map_.find(std::string(*str, str.length()));
216
26740
  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
204
Local<Array> MapKVStore::Enumerate(Isolate* isolate) const {
226
204
  Mutex::ScopedLock lock(mutex_);
227
408
  std::vector<Local<Value>> values;
228
204
  values.reserve(map_.size());
229
13402
  for (const auto& pair : map_) {
230
    values.emplace_back(
231
        String::NewFromUtf8(isolate, pair.first.data(),
232
13198
                            NewStringType::kNormal, pair.first.size())
233
26396
            .ToLocalChecked());
234
  }
235
408
  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
209
std::shared_ptr<KVStore> KVStore::CreateMapKVStore() {
243
209
  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
844915
static void EnvGetter(Local<Name> property,
273
                      const PropertyCallbackInfo<Value>& info) {
274
844915
  Environment* env = Environment::GetCurrent(info);
275
844915
  if (property->IsSymbol()) {
276
850164
    return info.GetReturnValue().SetUndefined();
277
  }
278
1684580
  CHECK(property->IsString());
279
  MaybeLocal<String> value_string =
280
1684580
      env->env_vars()->Get(env->isolate(), property.As<String>());
281
842289
  if (!value_string.IsEmpty()) {
282
1577920
    info.GetReturnValue().Set(value_string.ToLocalChecked());
283
  }
284
}
285
286
12921
static void EnvSetter(Local<Name> property,
287
                      Local<Value> value,
288
                      const PropertyCallbackInfo<Value>& info) {
289
12921
  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


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

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


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

14832
}  // namespace node