File: settings_loader.cpp

package info (click to toggle)
gfxreconstruct 0.9.18%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 24,636 kB
  • sloc: cpp: 328,961; ansic: 25,454; python: 18,156; xml: 255; sh: 128; makefile: 6
file content (327 lines) | stat: -rw-r--r-- 10,635 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
/*
** Copyright (c) 2018 Valve Corporation
** Copyright (c) 2018 LunarG, Inc.
**
** Permission is hereby granted, free of charge, to any person obtaining a
** copy of this software and associated documentation files (the "Software"),
** to deal in the Software without restriction, including without limitation
** the rights to use, copy, modify, merge, publish, distribute, sublicense,
** and/or sell copies of the Software, and to permit persons to whom the
** Software is furnished to do so, subject to the following conditions:
**
** The above copyright notice and this permission notice shall be included in
** all copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
** FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
** DEALINGS IN THE SOFTWARE.
*/

#include "util/settings_loader.h"

#include "util/file_path.h"
#include "util/logging.h"
#include "util/platform.h"

#include <array>
#include <cassert>
#include <cerrno>
#include <cstdio>
#include <fstream>
#include <vector>

GFXRECON_BEGIN_NAMESPACE(gfxrecon)
GFXRECON_BEGIN_NAMESPACE(util)
GFXRECON_BEGIN_NAMESPACE(settings)

// Using the same settings file search locations as the Vulkan validation layers.
#if defined(WIN32)
const char kSettingsKey[] = "Software\\Khronos\\Vulkan\\Settings";

struct HiveInfo
{
    HKEY        hive;
    const char* name;
    bool        elevated;
};
const std::array<HiveInfo, 2> kSettingsHives{ {
    { HKEY_LOCAL_MACHINE, "HKEY_LOCAL_MACHINE", true },
    { HKEY_CURRENT_USER, "HKEY_CURRENT_USER", false },
} };

#elif !defined(__ANDROID__)
const char kDataHome[]       = "XDG_DATA_HOME";
const char kUserHome[]       = "HOME";
const char kUserShareDir[]   = ".local/share/";
const char kSettingsDir[]    = "vulkan/settings.d/";
#endif

#if defined(__ANDROID__)
const char kSettingsEnvVar[] = "debug.gfxrecon.settings_path";
#else
const char kSettingsEnvVar[] = "VK_LAYER_SETTINGS_PATH";
#endif

const char kSettingsFilename[] = "vk_layer_settings.txt";
const char kCommentDelimiter   = '#';

const size_t kDefaultTokenSize = 512;

std::string RemoveQuotes(const std::string& source)
{
    size_t start_index = 0;
    size_t quote_count = 0;

    if (source.front() == '\"' || source.front() == '\'')
    {
        start_index = 1;
        ++quote_count;
    }

    if (source.back() == '\"' || source.back() == '\'')
    {
        ++quote_count;
    }

    if (quote_count > 0)
    {
        return source.substr(start_index, source.length() - quote_count);
    }

    return source;
}

#if defined(WIN32)
static bool IsElevated()
{
    HANDLE process_token = nullptr;
    bool   elevated      = false;
    if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &process_token))
    {
        DWORD           size;
        TOKEN_ELEVATION elevation;
        if (GetTokenInformation(process_token, TokenElevation, &elevation, sizeof(elevation), &size))
        {
            elevated = (elevation.TokenIsElevated != 0);
        }
        CloseHandle(process_token);
    }
    return elevated;
}
#endif

std::string FindLayerSettingsFile()
{
    std::string settings_file;

    // The first Windows/Linux search locations are for a file generated by vkconfig, which currently overrides other
    // files that the user could specify.
#if defined(WIN32)
    const bool elevated_process = IsElevated();
    auto       hive_info        = kSettingsHives.begin();
    while (settings_file.empty() && hive_info != kSettingsHives.end())
    {
        // A user process can read settings from an admin location, but an admin process should not read settings from a
        // user location
        if (!elevated_process || hive_info->elevated)
        {
            HKEY    key    = 0;
            LSTATUS result = RegOpenKeyExA(hive_info->hive, kSettingsKey, 0, KEY_READ, &key);

            if (result == ERROR_SUCCESS)
            {
                std::vector<char> data(MAX_PATH);
                DWORD             index      = 0;
                DWORD             type       = 0;
                DWORD             value      = 0;
                DWORD             data_size  = static_cast<DWORD>(data.size());
                DWORD             value_size = sizeof(value);

                for (;;)
                {
                    result = RegEnumValueA(key,
                                           index,
                                           data.data(),
                                           &data_size,
                                           nullptr,
                                           &type,
                                           reinterpret_cast<LPBYTE>(&value),
                                           &value_size);

                    if (result == ERROR_MORE_DATA)
                    {
                        data.resize(data_size);

                        result = RegEnumValueA(key,
                                               index,
                                               data.data(),
                                               &data_size,
                                               nullptr,
                                               &type,
                                               reinterpret_cast<LPBYTE>(&value),
                                               &value_size);
                    }

                    if (result == ERROR_SUCCESS)
                    {
                        // The file path is stored in the sub-key name, where sub-key type is DWORD and value is zero.
                        if ((type == REG_DWORD) && (value == 0) && filepath::IsFile(data.data()))
                        {
                            // Found a valid file path.
                            settings_file = data.data();
                            GFXRECON_LOG_INFO(
                                "Found layer settings registry key: %s\\%s", hive_info->name, kSettingsKey);
                            break;
                        }
                        else
                        {
                            // Check next entry.
                            ++index;
                        }
                    }
                    else
                    {
                        // Reached end of list, or an error occured.
                        break;
                    }
                }

                RegCloseKey(key);
            }
        }
        ++hive_info;
    }
#elif !defined(__ANDROID__)
    std::string search_path = platform::GetEnv(kDataHome);

    if (search_path.empty())
    {
        search_path = platform::GetEnv(kUserHome);
        if (!search_path.empty())
        {
            search_path = filepath::Join(search_path, kUserShareDir);
        }
    }

    if (!search_path.empty())
    {
        search_path = filepath::Join(search_path, kSettingsDir);
        search_path += kSettingsFilename; // Current search_path ends with the path separator.

        if (filepath::IsFile(search_path))
        {
            settings_file = search_path;
            GFXRECON_LOG_DEBUG("Using settings file %s from %s or %s environment variable.",
                               settings_file.c_str(),
                               kDataHome,
                               kUserHome);
        }
    }
#endif

    if (settings_file.empty())
    {
        // If the settings file was not found at a system specific location (or the current platform is Android), try
        // the layer settings environment variable.
        std::string env_path = platform::GetEnv(kSettingsEnvVar);

        if (!env_path.empty())
        {
            // If this is a directory, append the default settings file name.
            if (filepath::IsDirectory(env_path))
            {
                env_path = filepath::Join(env_path, kSettingsFilename);
            }

            if (filepath::IsFile(env_path))
            {
                settings_file = env_path;
            }
        }
    }

    if (settings_file.empty())
    {
        // Try the current working directory.
        if (filepath::IsFile(kSettingsFilename))
        {
            settings_file = kSettingsFilename;
        }
    }

    return settings_file;
}

int32_t LoadLayerSettingsFile(const std::string&                            filename,
                              const std::string&                            filter,
                              std::unordered_map<std::string, std::string>* settings)
{
    if (settings == nullptr)
    {
        return EINVAL;
    }

    int32_t       result = 0;
    std::ifstream file(filename);

    if (file.good())
    {
        char        key[kDefaultTokenSize]   = { '\0' };
        char        value[kDefaultTokenSize] = { '\0' };
        std::string line;

        std::getline(file, line);

        while (file.good())
        {
            // Strip comments that appear in the line.
            size_t comment_start = line.find_first_of(kCommentDelimiter);
            if (comment_start != std::string::npos)
            {
                line.erase(comment_start, std::string::npos);
            }

            // This is the same format string that the Vulkan validation layers use.
#if defined(WIN32)
            if (sscanf_s(line.c_str(),
                         " %511[^\r\n\t =] = %511[^\r\n \t]",
                         key,
                         static_cast<uint32_t>(kDefaultTokenSize),
                         value,
                         static_cast<uint32_t>(kDefaultTokenSize)) == 2)
#else
            if (sscanf(line.c_str(), " %511[^\r\n\t =] = %511[^\r\n \t]", key, value) == 2)
#endif
            {
                // Ignore entries with keys that do not start with the filter prefix.
                if (filter.empty() || (platform::StringCompare(key, filter.c_str(), filter.length()) == 0))
                {
                    (*settings)[key] = RemoveQuotes(value);
                }
            }

            std::getline(file, line);
        }

        if (!file.eof())
        {
            // An error occurred.
            result = errno;
        }
    }
    else
    {
        // Failed to open file.
        result = errno;
    }

    return result;
}

GFXRECON_END_NAMESPACE(settings)
GFXRECON_END_NAMESPACE(util)
GFXRECON_END_NAMESPACE(gfxrecon)