Apache Mesos
environment.hpp
Go to the documentation of this file.
1 // Licensed under the Apache License, Version 2.0 (the "License");
2 // you may not use this file except in compliance with the License.
3 // You may obtain a copy of the License at
4 //
5 // http://www.apache.org/licenses/LICENSE-2.0
6 //
7 // Unless required by applicable law or agreed to in writing, software
8 // distributed under the License is distributed on an "AS IS" BASIS,
9 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 // See the License for the specific language governing permissions and
11 // limitations under the License.
12 
13 #ifndef __STOUT_OS_WINDOWS_ENVIRONMENT_HPP__
14 #define __STOUT_OS_WINDOWS_ENVIRONMENT_HPP__
15 
16 #include <map>
17 #include <memory>
18 #include <string>
19 #include <stout/stringify.hpp>
20 
21 
22 namespace os {
23 
24 inline std::map<std::string, std::string> environment()
25 {
26  // NOTE: The `GetEnvironmentStrings` call returns a pointer to a
27  // read-only block of memory with the following format (minus newlines):
28  // Var1=Value1\0
29  // Var2=Value2\0
30  // Var3=Value3\0
31  // ...
32  // VarN=ValueN\0\0
33  const std::unique_ptr<wchar_t[], decltype(&::FreeEnvironmentStringsW)> env(
34  ::GetEnvironmentStringsW(), &::FreeEnvironmentStringsW);
35  std::map<std::string, std::string> result;
36 
37  for (size_t i = 0; env[i] != L'\0' && env[i+1] != L'\0';
38  /* incremented below */) {
39  std::wstring entry(&env[i]);
40 
41  // Increment past the current environment string and null terminator.
42  i = i + entry.size() + 1;
43 
44  // In practice, sometimes the key starts with `=` even though it
45  // is not supposed to. If we don't skip it, we get an empty key.
46  size_t position = entry.find_first_of(L'=', 1);
47  if (position == std::string::npos) {
48  continue; // Skip malformed environment entries.
49  }
50 
51  result[stringify(entry.substr(0, position))] =
52  stringify(entry.substr(position + 1));
53  }
54 
55  return result;
56 }
57 
58 } // namespace os {
59 
60 #endif // __STOUT_OS_WINDOWS_ENVIRONMENT_HPP__
Definition: posix_signalhandler.hpp:23
std::map< std::string, std::string > environment()
Definition: environment.hpp:24
std::string stringify(int flags)