1 /**************************************************************************
2  *
3  * Copyright 2014-2020 Valve Software
4  * Copyright 2015-2020 Google Inc.
5  * Copyright 2019-2020 LunarG, Inc.
6  * All Rights Reserved.
7  *
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *     http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  * Author: Jon Ashburn <jon@lunarg.com>
21  * Author: Courtney Goeltzenleuchter <courtney@LunarG.com>
22  * Author: Tobin Ehlis <tobin@lunarg.com>
23  * Author: Mark Lobodzinski <mark@lunarg.com>
24  **************************************************************************/
25 #include "vk_layer_config.h"
26 
27 #include <string.h>
28 #include <fstream>
29 #include <array>
30 #include <iostream>
31 #include <map>
32 #include <sstream>
33 #include <string>
34 #include <sys/stat.h>
35 
36 #include <vulkan/vk_layer.h>
37 // sdk_platform header redefines NOMINMAX
38 #undef NOMINMAX
39 #include <vulkan/vk_sdk_platform.h>
40 #include "vk_string_utils.h"
41 
42 #if defined(_WIN32)
43 #include <windows.h>
44 #include <direct.h>
45 #define GetCurrentDir _getcwd
46 #else
47 #include <unistd.h>
48 #define GetCurrentDir getcwd
49 #endif
50 
51 using std::string;
52 
53 class ConfigFile {
54   public:
55     ConfigFile();
~ConfigFile()56     ~ConfigFile(){};
57 
58     const char *GetOption(const string &option);
59     void SetOption(const string &option, const string &value);
60     string vk_layer_disables_env_var;
61     SettingsFileInfo settings_info{};
62 
63   private:
64     bool file_is_parsed_;
65     std::map<string, string> value_map_;
66 
67     string FindSettings();
68     void ParseFile(const char *filename);
69 };
70 
71 static ConfigFile layer_config;
72 
GetEnvironment(const char * variable)73 string GetEnvironment(const char *variable) {
74 #if !defined(__ANDROID__) && !defined(_WIN32)
75     const char *output = getenv(variable);
76     return output == NULL ? "" : output;
77 #elif defined(_WIN32)
78     int size = GetEnvironmentVariable(variable, NULL, 0);
79     if (size == 0) {
80         return "";
81     }
82     char *buffer = new char[size];
83     GetEnvironmentVariable(variable, buffer, size);
84     string output = buffer;
85     delete[] buffer;
86     return output;
87 #elif defined(__ANDROID__)
88     string command = "getprop " + string(variable);
89     FILE *pPipe = popen(command.c_str(), "r");
90     if (pPipe != nullptr) {
91         char value[256];
92         fgets(value, 256, pPipe);
93         pclose(pPipe);
94 
95         // Make sure its not an empty line
96         if (strcspn(value, "\r\n") == 0) {
97             return "";
98         } else {
99             return string(value);
100         }
101     } else {
102         return "";
103     }
104 #else
105     return "";
106 #endif
107 }
108 
getLayerOption(const char * option)109 VK_LAYER_EXPORT const char *getLayerOption(const char *option) { return layer_config.GetOption(option); }
GetLayerEnvVar(const char * option)110 VK_LAYER_EXPORT const char *GetLayerEnvVar(const char *option) {
111     layer_config.vk_layer_disables_env_var = GetEnvironment(option);
112     return layer_config.vk_layer_disables_env_var.c_str();
113 }
114 
GetLayerSettingsFileInfo()115 VK_LAYER_EXPORT const SettingsFileInfo *GetLayerSettingsFileInfo() { return &layer_config.settings_info; }
116 
117 // If option is NULL or stdout, return stdout, otherwise try to open option
118 // as a filename. If successful, return file handle, otherwise stdout
getLayerLogOutput(const char * option,const char * layer_name)119 VK_LAYER_EXPORT FILE *getLayerLogOutput(const char *option, const char *layer_name) {
120     FILE *log_output = NULL;
121     if (!option || !strcmp("stdout", option)) {
122         log_output = stdout;
123     } else {
124         log_output = fopen(option, "w");
125         if (log_output == NULL) {
126             if (option) {
127                 std::cout << std::endl
128                           << layer_name << " ERROR: Bad output filename specified: " << option << ". Writing to STDOUT instead"
129                           << std::endl
130                           << std::endl;
131             }
132             log_output = stdout;
133         }
134     }
135     return log_output;
136 }
137 
138 // Map option strings to flag enum values
GetLayerOptionFlags(string option,std::unordered_map<string,VkFlags> const & enum_data,uint32_t option_default)139 VK_LAYER_EXPORT VkFlags GetLayerOptionFlags(string option, std::unordered_map<string, VkFlags> const &enum_data,
140                                             uint32_t option_default) {
141     VkDebugReportFlagsEXT flags = option_default;
142     string option_list = layer_config.GetOption(option.c_str());
143 
144     while (option_list.length() != 0) {
145         // Find length of option string
146         std::size_t option_length = option_list.find(",");
147         if (option_length == option_list.npos) {
148             option_length = option_list.size();
149         }
150 
151         // Get first option item in list
152         const string option_item = option_list.substr(0, option_length);
153 
154         auto enum_value = enum_data.find(option_item);
155         if (enum_value != enum_data.end()) {
156             flags |= enum_value->second;
157         }
158 
159         // Remove first option from option_list
160         option_list.erase(0, option_length);
161         // Remove possible comma separator
162         std::size_t char_position = option_list.find(",");
163         if (char_position == 0) {
164             option_list.erase(char_position, 1);
165         }
166         // Remove possible space
167         char_position = option_list.find(" ");
168         if (char_position == 0) {
169             option_list.erase(char_position, 1);
170         }
171     }
172     return flags;
173 }
174 
setLayerOption(const char * option,const char * value)175 VK_LAYER_EXPORT void setLayerOption(const char *option, const char *value) { layer_config.SetOption(option, value); }
176 
177 // Constructor for ConfigFile. Initialize layers to log error messages to stdout by default. If a vk_layer_settings file is present,
178 // its settings will override the defaults.
ConfigFile()179 ConfigFile::ConfigFile() : file_is_parsed_(false) {
180 }
181 
GetOption(const string & option)182 const char *ConfigFile::GetOption(const string &option) {
183     std::map<string, string>::const_iterator it;
184     if (!file_is_parsed_) {
185         string settings_file = FindSettings();
186         ParseFile(settings_file.c_str());
187     }
188 
189     if ((it = value_map_.find(option)) == value_map_.end()) {
190         return "";
191     } else {
192         return it->second.c_str();
193     }
194 }
195 
SetOption(const string & option,const string & val)196 void ConfigFile::SetOption(const string &option, const string &val) {
197     if (!file_is_parsed_) {
198         string settings_file = FindSettings();
199         ParseFile(settings_file.c_str());
200     }
201 
202     value_map_[option] = val;
203 }
204 
205 #if defined(WIN32)
206 // Check for admin rights
IsHighIntegrity()207 static inline bool IsHighIntegrity() {
208     HANDLE process_token;
209     if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_QUERY_SOURCE, &process_token)) {
210         // Maximum possible size of SID_AND_ATTRIBUTES is maximum size of a SID + size of attributes DWORD.
211         uint8_t mandatory_label_buffer[SECURITY_MAX_SID_SIZE + sizeof(DWORD)];
212         DWORD buffer_size;
213         if (GetTokenInformation(process_token, TokenIntegrityLevel, mandatory_label_buffer, sizeof(mandatory_label_buffer),
214                                 &buffer_size) != 0) {
215             const TOKEN_MANDATORY_LABEL *mandatory_label = (const TOKEN_MANDATORY_LABEL *)mandatory_label_buffer;
216             const DWORD sub_authority_count = *GetSidSubAuthorityCount(mandatory_label->Label.Sid);
217             const DWORD integrity_level = *GetSidSubAuthority(mandatory_label->Label.Sid, sub_authority_count - 1);
218 
219             CloseHandle(process_token);
220             return integrity_level > SECURITY_MANDATORY_MEDIUM_RID;
221         }
222 
223         CloseHandle(process_token);
224     }
225 
226     return false;
227 }
228 #endif
229 
FindSettings()230 string ConfigFile::FindSettings() {
231     struct stat info;
232 
233 #if defined(WIN32)
234     // Look for VkConfig-specific settings location specified in the windows registry
235     HKEY key;
236 
237     const std::array<HKEY, 2> hives = {DEFAULT_VK_REGISTRY_HIVE, SECONDARY_VK_REGISTRY_HIVE};
238     const size_t hives_to_check_count = IsHighIntegrity() ? 1 : hives.size();  // Admin checks only the default hive
239 
240     for (size_t hive_index = 0; hive_index < hives_to_check_count; ++hive_index) {
241         LSTATUS err = RegOpenKeyEx(hives[hive_index], "Software\\Khronos\\Vulkan\\Settings", 0, KEY_READ, &key);
242         if (err == ERROR_SUCCESS) {
243             char name[2048];
244             DWORD i = 0, name_size, type, value, value_size;
245             while (ERROR_SUCCESS == RegEnumValue(key, i++, name, &(name_size = sizeof(name)), nullptr, &type,
246                                                  reinterpret_cast<LPBYTE>(&value), &(value_size = sizeof(value)))) {
247                 // Check if the registry entry is a dword with a value of zero
248                 if (type != REG_DWORD || value != 0) {
249                     continue;
250                 }
251 
252                 // Check if this actually points to a file
253                 if ((stat(name, &info) != 0) || !(info.st_mode & S_IFREG)) {
254                     continue;
255                 }
256 
257                 // Use this file
258                 RegCloseKey(key);
259                 settings_info.source = kVkConfig;
260                 settings_info.location = name;
261                 return name;
262             }
263 
264             RegCloseKey(key);
265         }
266     }
267 
268 #else
269     // Look for VkConfig-specific settings location specified in a specific spot in the linux settings store
270     string search_path = GetEnvironment("XDG_DATA_HOME");
271     if (search_path == "") {
272         search_path = GetEnvironment("HOME");
273         if (search_path != "") {
274             search_path += "/.local/share";
275         }
276     }
277     // Use the vk_layer_settings.txt file from here, if it is present
278     if (search_path != "") {
279         string home_file = search_path + "/vulkan/settings.d/vk_layer_settings.txt";
280         if (stat(home_file.c_str(), &info) == 0) {
281             if (info.st_mode & S_IFREG) {
282                 settings_info.source = kVkConfig;
283                 settings_info.location = home_file;
284                 return home_file;
285             }
286         }
287     }
288 
289 #endif
290     // Look for an enviornment variable override for the settings file location
291     string env_path = GetEnvironment("VK_LAYER_SETTINGS_PATH");
292 
293     // If the path exists use it, else use vk_layer_settings
294     if (stat(env_path.c_str(), &info) == 0) {
295         // If this is a directory, append settings file name
296         if (info.st_mode & S_IFDIR) {
297             env_path.append("/vk_layer_settings.txt");
298         }
299         settings_info.source = kEnvVar;
300         settings_info.location = env_path;
301         return env_path;
302     }
303 
304     // Default -- use the current working directory for the settings file location
305     settings_info.source = kLocal;
306     char buff[512];
307     auto buf_ptr = GetCurrentDir(buff, 512);
308     if (buf_ptr) {
309         settings_info.location = buf_ptr;
310         settings_info.location.append("\\vk_layer_settings.txt");
311     }
312     return "vk_layer_settings.txt";
313 }
314 
ParseFile(const char * filename)315 void ConfigFile::ParseFile(const char *filename) {
316     file_is_parsed_ = true;
317 
318     // Extract option = value pairs from a file
319     std::ifstream file(filename);
320     if (file.good()) {
321         settings_info.file_found = true;
322         for (string line; std::getline(file, line);) {
323             // discard comments, which start with '#'
324             const auto comments_pos = line.find_first_of('#');
325             if (comments_pos != string::npos) line.erase(comments_pos);
326 
327             const auto value_pos = line.find_first_of('=');
328             if (value_pos != string::npos) {
329                 const string option = string_trim(line.substr(0, value_pos));
330                 const string value = string_trim(line.substr(value_pos + 1));
331                 value_map_[option] = value;
332             }
333         }
334     }
335 }
336 
PrintMessageFlags(VkFlags vk_flags,char * msg_flags)337 VK_LAYER_EXPORT void PrintMessageFlags(VkFlags vk_flags, char *msg_flags) {
338     bool separator = false;
339 
340     msg_flags[0] = 0;
341     if (vk_flags & VK_DEBUG_REPORT_DEBUG_BIT_EXT) {
342         strcat(msg_flags, "DEBUG");
343         separator = true;
344     }
345     if (vk_flags & VK_DEBUG_REPORT_INFORMATION_BIT_EXT) {
346         if (separator) strcat(msg_flags, ",");
347         strcat(msg_flags, "INFO");
348         separator = true;
349     }
350     if (vk_flags & VK_DEBUG_REPORT_WARNING_BIT_EXT) {
351         if (separator) strcat(msg_flags, ",");
352         strcat(msg_flags, "WARN");
353         separator = true;
354     }
355     if (vk_flags & VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT) {
356         if (separator) strcat(msg_flags, ",");
357         strcat(msg_flags, "PERF");
358         separator = true;
359     }
360     if (vk_flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) {
361         if (separator) strcat(msg_flags, ",");
362         strcat(msg_flags, "ERROR");
363     }
364 }
365 
PrintMessageSeverity(VkFlags vk_flags,char * msg_flags)366 VK_LAYER_EXPORT void PrintMessageSeverity(VkFlags vk_flags, char *msg_flags) {
367     bool separator = false;
368 
369     msg_flags[0] = 0;
370     if (vk_flags & VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT) {
371         strcat(msg_flags, "VERBOSE");
372         separator = true;
373     }
374     if (vk_flags & VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT) {
375         if (separator) strcat(msg_flags, ",");
376         strcat(msg_flags, "INFO");
377         separator = true;
378     }
379     if (vk_flags & VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) {
380         if (separator) strcat(msg_flags, ",");
381         strcat(msg_flags, "WARN");
382         separator = true;
383     }
384     if (vk_flags & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) {
385         if (separator) strcat(msg_flags, ",");
386         strcat(msg_flags, "ERROR");
387     }
388 }
389 
PrintMessageType(VkFlags vk_flags,char * msg_flags)390 VK_LAYER_EXPORT void PrintMessageType(VkFlags vk_flags, char *msg_flags) {
391     bool separator = false;
392 
393     msg_flags[0] = 0;
394     if (vk_flags & VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT) {
395         strcat(msg_flags, "GEN");
396         separator = true;
397     }
398     if (vk_flags & VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT) {
399         if (separator) strcat(msg_flags, ",");
400         strcat(msg_flags, "SPEC");
401         separator = true;
402     }
403     if (vk_flags & VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT) {
404         if (separator) strcat(msg_flags, ",");
405         strcat(msg_flags, "PERF");
406     }
407 }
408 
409