Debian Codegraph @

tests/framework/util/env_var_wrapper.cpp

raw
1 /*
2 * Copyright (c) 2025 The Khronos Group Inc.
3 * Copyright (c) 2025 Valve Corporation
4 * Copyright (c) 2025 LunarG, Inc.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and/or associated documentation files (the "Materials"), to
8 * deal in the Materials without restriction, including without limitation the
9 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10 * sell copies of the Materials, and to permit persons to whom the Materials are
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice(s) and this permission notice shall be included in
14 * all copies or substantial portions of the Materials.
15 *
16 * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19 *
20 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
21 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
22 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE
23 * USE OR OTHER DEALINGS IN THE MATERIALS.
24 *
25 */
26
27 #include "env_var_wrapper.h"
28
29 #include <stdlib.h>
30
31 #include <iostream>
32
33 #include "wide_char_handling.h"
34
35 // NOTE: get_env_var() are only intended for test framework code, all test code MUST use
36 // EnvVarWrapper
37
38 #if defined(_WIN32)
39 #include <Windows.h>
40 #include <wchar.h>
41 #include <strsafe.h>
42
43 // Windows specific error handling logic
44 const long ERROR_SETENV_FAILED = 10543; // chosen at random, attempts to not conflict
45 const long ERROR_REMOVEDIRECTORY_FAILED = 10544; // chosen at random, attempts to not conflict
46 const char* win_api_error_str(LSTATUS status) {
47 if (status == ERROR_INVALID_FUNCTION) return "ERROR_INVALID_FUNCTION";
48 if (status == ERROR_FILE_NOT_FOUND) return "ERROR_FILE_NOT_FOUND";
49 if (status == ERROR_PATH_NOT_FOUND) return "ERROR_PATH_NOT_FOUND";
50 if (status == ERROR_TOO_MANY_OPEN_FILES) return "ERROR_TOO_MANY_OPEN_FILES";
51 if (status == ERROR_ACCESS_DENIED) return "ERROR_ACCESS_DENIED";
52 if (status == ERROR_INVALID_HANDLE) return "ERROR_INVALID_HANDLE";
53 if (status == ERROR_ENVVAR_NOT_FOUND) return "ERROR_ENVVAR_NOT_FOUND";
54 if (status == ERROR_SETENV_FAILED) return "ERROR_SETENV_FAILED";
55 return "UNKNOWN ERROR";
56 }
57 std::string error_code_to_string(DWORD error_code) {
58 LPSTR lpMsgBuf{};
59 size_t MsgBufSize = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
60 nullptr, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), lpMsgBuf, 0, nullptr);
61 std::string code_str(lpMsgBuf, MsgBufSize);
62 LocalFree(lpMsgBuf);
63 return code_str;
64 }
65
66 void print_error_message(LSTATUS status, const char* function_name, std::string optional_message = "") {
67 DWORD dw = GetLastError();
68
69 std::cerr << function_name << " failed with " << win_api_error_str(status) << ": " << error_code_to_string(dw);
70 if (optional_message != "") {
71 std::cerr << " | " << optional_message;
72 }
73 std::cerr << "\n";
74 }
75
76 // get_env_var() - returns a std::string of `name`. if report_failure is true, then it will log to stderr that it didn't find the
77 // env-var
78 std::string get_env_var(std::string const& name, bool report_failure) {
79 std::wstring name_utf16 = widen(name);
80 DWORD value_size = GetEnvironmentVariableW(name_utf16.c_str(), nullptr, 0);
81 if (0 == value_size) {
82 if (report_failure) print_error_message(ERROR_ENVVAR_NOT_FOUND, "GetEnvironmentVariableW");
83 return {};
84 }
85 std::wstring value(value_size, L'\0');
86 if (GetEnvironmentVariableW(name_utf16.c_str(), &value[0], value_size) != value_size - 1) {
87 return {};
88 }
89 return narrow(value);
90 }
91 #elif TESTING_COMMON_UNIX_PLATFORMS
92
93 // get_env_var() - returns a std::string of `name`. if report_failure is true, then it will log to stderr that it didn't find the
94 // env-var
95 std::string get_env_var(std::string const& name, bool report_failure) {
96 char* ret = getenv(name.c_str());
97 if (ret == nullptr) {
98 if (report_failure) std::cerr << "Failed to get environment variable:" << name << "\n";
99 return std::string();
100 }
101 return ret;
102 }
103 #endif
104
105 std::vector<std::string> split_env_var_as_list(std::string const& env_var_contents) {
106 std::vector<std::string> items;
107 size_t start = 0;
108 size_t len = 0;
109 for (size_t i = 0; i < env_var_contents.size(); i++) {
110 if (env_var_contents[i] == OS_ENV_VAR_LIST_SEPARATOR) {
111 if (len != 0) {
112 // only push back non empty strings
113 items.push_back(env_var_contents.substr(start, len));
114 }
115 start = i + 1;
116 len = 0;
117 } else {
118 len++;
119 }
120 }
121 items.push_back(env_var_contents.substr(start, len));
122 return items;
123 }
124
125 /*
126 * Wrapper around Environment Variables with common operations
127 * Since Environment Variables leak between tests, there needs to be RAII code to remove them during test cleanup
128
129 */
130
131 EnvVarWrapper::EnvVarWrapper(std::string const& name) noexcept : name(name) {
132 initial_value = get_env_var(name, false);
133 remove_env_var();
134 }
135 EnvVarWrapper::EnvVarWrapper(std::string const& name, std::string const& value) noexcept : name(name), cur_value(value) {
136 initial_value = get_env_var(name, false);
137 set_env_var();
138 }
139 EnvVarWrapper::~EnvVarWrapper() noexcept {
140 remove_env_var();
141 if (!initial_value.empty()) {
142 set_new_value(initial_value);
143 }
144 }
145
146 void EnvVarWrapper::set_new_value(std::string const& value) {
147 cur_value = value;
148 set_env_var();
149 }
150 void EnvVarWrapper::add_to_list(std::string const& list_item) {
151 if (!cur_value.empty()) {
152 cur_value += OS_ENV_VAR_LIST_SEPARATOR;
153 }
154 cur_value += list_item;
155 set_env_var();
156 }
157 #if defined(_WIN32)
158 void EnvVarWrapper::add_to_list(std::wstring const& list_item) {
159 if (!cur_value.empty()) {
160 cur_value += OS_ENV_VAR_LIST_SEPARATOR;
161 }
162 cur_value += narrow(list_item);
163 set_env_var();
164 }
165 #endif
166 void EnvVarWrapper::remove_value() const { remove_env_var(); }
167 const char* EnvVarWrapper::get() const { return name.c_str(); }
168 const char* EnvVarWrapper::value() const { return cur_value.c_str(); }
169
170 #if defined(_WIN32)
171
172 void EnvVarWrapper::set_env_var() const {
173 BOOL ret = SetEnvironmentVariableW(widen(name).c_str(), widen(cur_value).c_str());
174 if (ret == 0) {
175 print_error_message(ERROR_SETENV_FAILED, "SetEnvironmentVariableW");
176 }
177 }
178 void EnvVarWrapper::remove_env_var() const { SetEnvironmentVariableW(widen(name).c_str(), nullptr); }
179
180 #elif TESTING_COMMON_UNIX_PLATFORMS
181
182 void EnvVarWrapper::set_env_var() const { setenv(name.c_str(), cur_value.c_str(), 1); }
183 void EnvVarWrapper::remove_env_var() const { unsetenv(name.c_str()); }
184 #endif