forked from FEX-Emu/FEX
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConfig.cpp
More file actions
718 lines (592 loc) · 23.7 KB
/
Config.cpp
File metadata and controls
718 lines (592 loc) · 23.7 KB
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
// SPDX-License-Identifier: MIT
#include "Common/ArgumentLoader.h"
#include "Common/Config.h"
#include "Common/JSONPool.h"
#include <FEXCore/Config/Config.h>
#include <FEXCore/fextl/fmt.h>
#include <FEXCore/fextl/map.h>
#include <FEXCore/fextl/string.h>
#include <FEXCore/Utils/Allocator.h>
#include <FEXCore/Utils/FileLoading.h>
#include <FEXHeaderUtils/Filesystem.h>
#include <FEXHeaderUtils/SymlinkChecks.h>
#include <cstring>
#include <fmt/format.h>
#include <functional>
#ifndef _WIN32
#include <linux/limits.h>
#include <pwd.h>
#endif
#include <optional>
#include <utility>
#include <tiny-json.h>
#include <range/v3/view/split.hpp>
#include <range/v3/view/transform.hpp>
namespace FEX::Config {
namespace JSON {
static void LoadJSonConfig(const fextl::string& Config, std::function<void(const char* Name, const char* ConfigSring)> Func) {
fextl::vector<char> Data;
if (!FEXCore::FileLoading::LoadFile(Data, Config)) {
return;
}
FEX::JSON::JsonAllocator Pool {};
const json_t* json = FEX::JSON::CreateJSON(Data, Pool);
if (!json) {
ERROR_AND_DIE_FMT("Failed to parse JSON from file '{}' - invalid JSON format", Config);
}
const json_t* ConfigList = json_getProperty(json, "Config");
if (!ConfigList) {
// This is a non-error if the configuration file exists but no Config section
return;
}
for (const json_t* ConfigItem = json_getChild(ConfigList); ConfigItem != nullptr; ConfigItem = json_getSibling(ConfigItem)) {
const char* ConfigName = json_getName(ConfigItem);
const char* ConfigString = json_getValue(ConfigItem);
if (!ConfigName) {
LogMan::Msg::EFmt("JSON file '{}': Couldn't get config name for an item", Config);
return;
}
if (!ConfigString) {
LogMan::Msg::EFmt("JSON file '{}': Couldn't get value for config item '{}'", Config, ConfigName);
return;
}
Func(ConfigName, ConfigString);
}
}
} // namespace JSON
static constexpr std::pair<std::string_view, FEXCore::Config::ConfigOption> ConfigLookup[] {
#define OPT_BASE(type, group, enum, json, default) {#json, FEXCore::Config::ConfigOption::CONFIG_##enum},
#include <FEXCore/Config/ConfigValues.inl>
};
static char* SaveLayerToJSON(char* JsonBuffer, const FEXCore::Config::Layer* Layer) {
JsonBuffer = json_objOpen(JsonBuffer, "Config");
for (auto& it : Layer->GetOptionMap()) {
std::string_view Name {};
for (auto& name_it : ConfigLookup) {
if (name_it.second == it.first) {
Name = name_it.first;
break;
}
}
if (std::holds_alternative<fextl::string>(it.second)) {
JsonBuffer = json_str(JsonBuffer, Name.data(), std::get<fextl::string>(it.second).c_str());
} else if (std::holds_alternative<FEXCore::Config::StringArrayType>(it.second)) {
for (auto& var : std::get<FEXCore::Config::StringArrayType>(it.second)) {
JsonBuffer = json_str(JsonBuffer, Name.data(), var.c_str());
}
} else {
LogMan::Msg::AFmt("Trying to store config with pre-converted type");
}
}
return json_objClose(JsonBuffer);
}
void SaveLayerToJSON(const fextl::string& Filename, const FEXCore::Config::Layer* Layer, const fextl::unordered_map<fextl::string, bool>& HostLibs) {
char Buffer[4096];
char* Dest {};
Dest = json_objOpen(Buffer, nullptr);
Dest = SaveLayerToJSON(Dest, Layer);
Dest = json_objOpen(Dest, "ThunksDB");
for (auto& [Name, Enabled] : HostLibs) {
Dest = json_int(Dest, Name.c_str(), Enabled);
}
Dest = json_objClose(Dest);
Dest = json_objClose(Dest);
json_end(Dest);
LogMan::Throw::AFmt(Dest <= std::end(Buffer), "Exceeded JSON buffer size");
auto File = FEXCore::File::File(Filename.c_str(),
FEXCore::File::FileModes::WRITE | FEXCore::File::FileModes::CREATE | FEXCore::File::FileModes::TRUNCATE);
if (File.IsValid()) {
File.Write(Buffer, strlen(Buffer));
}
}
void SaveLayerToJSON(const fextl::string& Filename, const FEXCore::Config::Layer* Layer) {
fextl::unordered_map<fextl::string, bool> HostLibsDB;
// Load existing ThunksDB entry to persist it
{
fextl::vector<char> FileData;
if (!FEXCore::FileLoading::LoadFile(FileData, Filename)) {
goto WriteConfig;
}
// Find bounds of previously existing Config entry (if any)
FEX::JSON::JsonAllocator Pool {};
const json_t* json = FEX::JSON::CreateJSON(FileData, Pool);
if (!json) {
goto WriteConfig;
}
const json_t* ThunksDB = json_getProperty(json, "ThunksDB");
if (!ThunksDB) {
goto WriteConfig;
}
for (const json_t* Item = json_getChild(ThunksDB); Item != nullptr; Item = json_getSibling(Item)) {
HostLibsDB.emplace(json_getName(Item), (json_getInteger(Item) != 0));
}
}
WriteConfig:
SaveLayerToJSON(Filename, Layer, HostLibsDB);
}
// Application loaders
class OptionMapper : public FEXCore::Config::Layer {
public:
explicit OptionMapper(FEXCore::Config::LayerType Layer);
protected:
void MapNameToOption(const char* ConfigName, const char* ConfigString);
void SetCurrentConfigFile(const fextl::string& Filename) {
CurrentConfigFile = Filename;
}
fextl::string CurrentConfigFile;
};
class MainLoader final : public OptionMapper {
public:
explicit MainLoader(FEXCore::Config::LayerType Type);
explicit MainLoader(fextl::string ConfigFile);
explicit MainLoader(FEXCore::Config::LayerType Type, std::string_view ConfigFile);
void Load() override;
private:
fextl::string Config;
};
class AppLoader final : public OptionMapper {
public:
explicit AppLoader(const fextl::string& Filename, FEXCore::Config::LayerType Type);
void Load();
private:
fextl::string Config;
};
class EnvLoader final : public FEXCore::Config::Layer {
public:
explicit EnvLoader(char* const _envp[]);
void Load() override;
private:
char* const* envp;
};
OptionMapper::OptionMapper(FEXCore::Config::LayerType Layer)
: FEXCore::Config::Layer(Layer) {}
void OptionMapper::MapNameToOption(const char* ConfigName, const char* ConfigString) {
std::optional<FEXCore::Config::ConfigOption> KeyOptionValue;
for (auto& it : ConfigLookup) {
if (it.first != ConfigName) {
continue;
}
KeyOptionValue = it.second;
break;
}
if (!KeyOptionValue.has_value()) {
LogMan::Msg::IFmt("Unknown configuration option '{}' in JSON config file '{}'", ConfigName, CurrentConfigFile);
return;
}
const auto KeyOption = *KeyOptionValue;
const auto KeyName = std::string_view(ConfigName);
const auto Value_View = std::string_view(ConfigString);
#define JSONLOADER
#include <FEXCore/Config/ConfigOptions.inl>
}
MainLoader::MainLoader(FEXCore::Config::LayerType Type)
: OptionMapper(Type)
, Config {FEXCore::Config::GetConfigFileLocation(Type == FEXCore::Config::LayerType::LAYER_GLOBAL_MAIN)} {}
MainLoader::MainLoader(fextl::string ConfigFile)
: OptionMapper(FEXCore::Config::LayerType::LAYER_MAIN)
, Config {std::move(ConfigFile)} {}
MainLoader::MainLoader(FEXCore::Config::LayerType Type, std::string_view ConfigFile)
: OptionMapper(Type)
, Config {ConfigFile} {}
void MainLoader::Load() {
SetCurrentConfigFile(Config);
JSON::LoadJSonConfig(Config, [this](const char* Name, const char* ConfigString) { MapNameToOption(Name, ConfigString); });
}
AppLoader::AppLoader(const fextl::string& Filename, FEXCore::Config::LayerType Type)
: OptionMapper(Type) {
const bool Global = Type == FEXCore::Config::LayerType::LAYER_GLOBAL_STEAM_APP || Type == FEXCore::Config::LayerType::LAYER_GLOBAL_APP;
Config = FEXCore::Config::GetApplicationConfig(Filename, Global);
// Immediately load so we can reload the meta layer
Load();
}
void AppLoader::Load() {
SetCurrentConfigFile(Config);
JSON::LoadJSonConfig(Config, [this](const char* Name, const char* ConfigString) { MapNameToOption(Name, ConfigString); });
}
EnvLoader::EnvLoader(char* const _envp[])
: FEXCore::Config::Layer(FEXCore::Config::LayerType::LAYER_ENVIRONMENT)
, envp {_envp} {}
void EnvLoader::Load() {
using EnvMapType = fextl::unordered_map<std::string_view, fextl::string>;
EnvMapType EnvMap;
for (const char* const* pvar = envp; pvar && *pvar; pvar++) {
std::string_view Var(*pvar);
///< All FEX environment variables start with `FEX_`
if (!Var.starts_with("FEX_")) {
continue;
}
size_t pos = Var.rfind('=');
if (fextl::string::npos == pos) {
continue;
}
std::string_view Key = Var.substr(0, pos);
std::string_view Value_View {Var.substr(pos + 1)};
std::optional<fextl::string> Value;
#define ENVLOADER
#include <FEXCore/Config/ConfigOptions.inl>
if (Value) {
EnvMap.insert_or_assign(Key, std::move(*Value));
} else {
EnvMap.insert_or_assign(Key, Value_View);
}
}
auto GetVar = [](const EnvMapType& EnvMap, std::string_view id) -> std::optional<std::string_view> {
const auto EnvEntry = EnvMap.find(id);
if (EnvEntry != EnvMap.end()) {
return EnvEntry->second;
}
// If envp[] was empty, search using std::getenv()
const char* vs = std::getenv(id.data());
if (vs) {
return vs;
} else {
return std::nullopt;
}
};
std::optional<std::string_view> Value;
// Walk all the environment options and corresponding config option.
#define OPT_BASE(type, group, enum, json, default) \
Value = GetVar(EnvMap, "FEX_" #enum); \
if (Value.has_value()) Set(FEXCore::Config::ConfigOption::CONFIG_##enum, *Value);
#define OPT_STRARRAY(group, enum, json, default) \
Value = GetVar(EnvMap, "FEX_" #enum); \
if (Value.has_value()) AppendStrArrayValue(FEXCore::Config::ConfigOption::CONFIG_##enum, *Value);
#include <FEXCore/Config/ConfigValues.inl>
}
fextl::unique_ptr<FEXCore::Config::Layer> CreateGlobalMainLayer() {
return fextl::make_unique<MainLoader>(FEXCore::Config::LayerType::LAYER_GLOBAL_MAIN);
}
fextl::unique_ptr<FEXCore::Config::Layer> CreateMainLayer(const fextl::string* File) {
if (File) {
return fextl::make_unique<MainLoader>(*File);
} else {
return fextl::make_unique<MainLoader>(FEXCore::Config::LayerType::LAYER_MAIN);
}
}
fextl::unique_ptr<FEXCore::Config::Layer> CreateUserOverrideLayer(std::string_view AppConfig) {
return fextl::make_unique<MainLoader>(FEXCore::Config::LayerType::LAYER_USER_OVERRIDE, AppConfig);
}
fextl::unique_ptr<FEXCore::Config::Layer> CreateAppLayer(const fextl::string& Filename, FEXCore::Config::LayerType Type) {
return fextl::make_unique<AppLoader>(Filename, Type);
}
fextl::unique_ptr<FEXCore::Config::Layer> CreateEnvironmentLayer(char* const _envp[]) {
return fextl::make_unique<EnvLoader>(_envp);
}
fextl::string RecoverGuestProgramFilename(fextl::string Program, bool ExecFDInterp, int ProgramFDFromEnv) {
// If executed with a FEX FD then the Program argument might be empty.
// In this case we need to scan the FD node to recover the application binary that exists on disk.
// Only do this if the Program argument is empty, since we would prefer the application's expectation
// of application name.
if (ProgramFDFromEnv != -1 && Program.empty()) {
// Get the `dev` node of the execveat fd string.
Program = fextl::fmt::format("/dev/fd/{}", ProgramFDFromEnv);
}
// If we were provided a relative path then we need to canonicalize it to become absolute.
// If the program name isn't resolved to an absolute path then glibc breaks inside it's `_dl_get_origin` function.
// This is because we rewrite `/proc/self/exe` to the absolute program path calculated in here.
if (!Program.starts_with('/')) {
char ExistsTempPath[PATH_MAX];
char* RealPath = FHU::Filesystem::Absolute(Program.c_str(), ExistsTempPath);
if (RealPath) {
Program = RealPath;
}
}
// If FEX was invoked through an FD path (either binfmt_misc or execveat) then we need to check the
// Program to see if it is a symlink to find the real path.
//
// binfmt_misc: Arg[0] is actually the execve `pathname` argument or `/dev/fd/<FD>` path
// - `pathname` with execve (See Side Note)
// - FD path with execveat and FD doesn't have an existing file on the disk
//
// ProgramFDFromEnv: Arg[0] is Application provided data or `/dev/fd/<FD>` from above fix-up.
// - execveat was either passed no arguments (argv=NULL) or the first argument is an empty string (argv[0]="").
// - FD path with execveat and FD doesn't have an existing file on the disk
//
// Side Note:
// The `execve` syscall doesn't take an FD but binfmt_misc will give FEX an FD to execute still.
// Arg[0] will always contain the `pathname` argument provided to execve.
// It does not resolve symlinks, and it does not convert the path to absolute.
//
// Examples:
// - Regular execve. Application must exist on disk.
// execve binfmt_misc args layout: `FEX <Path provided to execve pathname> <user provided argv[0]> <user provided argv[n]>...`
// - Regular execveat with FD. FD is backed by application on disk.
// execveat binfmt_misc args layout: `FEX <Path provided to execve pathname> <user provided argv[0]> <user provided argv[n]>...`
// - Regular execveat with FD. FD points to file on disk that has been deleted.
// execveat binfmt_misc args layout: `FEX /dev/fd/<FD> <user provided argv[0]> <user provided argv[n]>...`
#ifndef _WIN32
if (ExecFDInterp || ProgramFDFromEnv != -1) {
// Only in the case that FEX is executing an FD will the program argument potentially be a symlink.
// This symlink will be in the style of `/dev/fd/<FD>`.
//
// If the argument /is/ a symlink then resolve its path to get the original application name.
if (FHU::Symlinks::IsSymlink(Program)) {
char Filename[PATH_MAX];
auto SymlinkPath = FHU::Symlinks::ResolveSymlink(Program, Filename);
if (SymlinkPath.starts_with('/')) {
// This file was executed through an FD.
// Remove the ` (deleted)` text if the file was deleted after the fact.
// Otherwise just get the symlink without the deleted text.
return fextl::string {SymlinkPath.substr(0, SymlinkPath.rfind(" (deleted)"))};
}
}
}
#endif
return Program;
}
ApplicationNames GetApplicationNames(const fextl::vector<fextl::string>& Args, bool ExecFDInterp, int ProgramFDFromEnv) {
if (Args.empty()) {
// Early exit if we weren't passed an argument
return {};
}
fextl::string Program {};
fextl::string ProgramName {};
Program = RecoverGuestProgramFilename(Args[0], ExecFDInterp, ProgramFDFromEnv);
bool Wine = false;
for (size_t CurrentProgramNameIndex = 0; CurrentProgramNameIndex < Args.size(); ++CurrentProgramNameIndex) {
auto CurrentProgramName = FHU::Filesystem::GetFilename(Args[CurrentProgramNameIndex]);
if (CurrentProgramName == "wine-preloader" || CurrentProgramName == "wine64-preloader") {
// Wine preloader is required to be in the format of `wine-preloader <wine executable>`
// The preloader doesn't execve the executable, instead maps it directly itself
// Skip the next argument since we know it is wine (potentially with custom wine executable name)
++CurrentProgramNameIndex;
Wine = true;
} else if (CurrentProgramName == "wine" || CurrentProgramName == "wine64") {
// Next argument, this isn't the program we want
//
// If we are running wine or wine64 then we should check the next argument for the application name instead.
// wine will change the active program name with `setprogname` or `prctl(PR_SET_NAME`.
// Since FEX needs this data far earlier than libraries we need a different check.
Wine = true;
} else {
if (Wine == true) {
// If this was path separated with '\' then we need to check that.
auto WinSeparator = CurrentProgramName.find_last_of('\\');
if (WinSeparator != CurrentProgramName.npos) {
// Used windows separators
CurrentProgramName = CurrentProgramName.substr(WinSeparator + 1);
}
}
ProgramName = std::move(CurrentProgramName);
// Past any wine program names
break;
}
}
return ApplicationNames {std::move(Program), std::move(ProgramName)};
}
void LoadConfig(fextl::string ProgramName, char** const envp, const PortableInformation& PortableInfo) {
const bool IsPortable = PortableInfo.IsPortable;
FEXCore::Config::Initialize();
FEX::Config::InitializeConfigs(PortableInfo);
if (!IsPortable) {
FEXCore::Config::AddLayer(CreateGlobalMainLayer());
}
FEXCore::Config::AddLayer(CreateMainLayer());
if (!ProgramName.empty()) {
if (!IsPortable) {
FEXCore::Config::AddLayer(CreateAppLayer(ProgramName, FEXCore::Config::LayerType::LAYER_GLOBAL_APP));
}
FEXCore::Config::AddLayer(CreateAppLayer(ProgramName, FEXCore::Config::LayerType::LAYER_LOCAL_APP));
auto SteamID = getenv("SteamAppId");
if (SteamID) {
// If a SteamID exists then let's search for Steam application configs as well.
// We want to key off both the SteamAppId number /and/ the executable since we may not want to thunk all binaries.
fextl::string SteamAppName = fextl::fmt::format("Steam_{}_{}", SteamID, ProgramName);
if (!IsPortable) {
FEXCore::Config::AddLayer(CreateAppLayer(SteamAppName, FEXCore::Config::LayerType::LAYER_GLOBAL_STEAM_APP));
}
FEXCore::Config::AddLayer(CreateAppLayer(SteamAppName, FEXCore::Config::LayerType::LAYER_LOCAL_STEAM_APP));
}
}
const char* AppConfig = getenv("FEX_APP_CONFIG");
if (AppConfig) {
fextl::string AppConfigStr = AppConfig;
if (IsPortable && FHU::Filesystem::IsRelative(AppConfig)) {
AppConfigStr = PortableInfo.InterpreterPath + AppConfigStr;
}
if (FHU::Filesystem::Exists(AppConfigStr)) {
FEXCore::Config::AddLayer(CreateUserOverrideLayer(AppConfigStr));
}
}
FEXCore::Config::AddLayer(CreateEnvironmentLayer(envp));
FEXCore::Config::Load();
}
#ifndef _WIN32
fextl::string FindUserHomeThroughUID() {
// `getpwuid` allocates memory, parse `/etc/passwd` manually.
// Format is trivial: `<name>:<password hash>:<uid>:<gid>:<comment>:<home>:<shell>`
fextl::vector<char> Data;
if (!FEXCore::FileLoading::LoadFile(Data, "/etc/passwd")) {
return {};
}
auto to_string_view = [](auto rng) {
return std::string_view(&*rng.begin(), ranges::distance(rng));
};
const auto uid = geteuid();
for (const auto entry : ranges::views::split(Data, '\n') | ranges::views::transform(to_string_view)) {
const auto elements = ranges::views::split(entry, ':') | ranges::views::transform(to_string_view);
// Reject bad entries.
if (std::distance(elements.begin(), elements.end()) != 7) {
continue;
}
auto iter = elements.begin();
++iter; // name
++iter; // password hash
++iter; // comment
// uid
const auto uid_s = *iter;
++iter;
++iter; // gid
// home
const auto home_s = *iter;
++iter;
++iter; // shell
uint64_t element_uid;
auto Results = std::from_chars(uid_s.begin(), uid_s.end(), element_uid, 10);
// Error parsing.
if (Results.ptr == uid_s.begin()) {
continue;
}
if (element_uid == uid) {
return fextl::string(home_s);
}
}
return {};
}
fextl::string GetHomeDirectory() {
const char* HomeDir = getenv("HOME");
// Try to get home directory from uid
if (!HomeDir || !FHU::Filesystem::Exists(HomeDir)) {
auto UIDHome = FindUserHomeThroughUID();
if (!UIDHome.empty() && FHU::Filesystem::Exists(UIDHome)) {
return UIDHome;
}
}
// try the PWD
if (!HomeDir || !FHU::Filesystem::Exists(HomeDir)) {
HomeDir = getenv("PWD");
}
// Still doesn't exit? You get local
if (!HomeDir || !FHU::Filesystem::Exists(HomeDir)) {
HomeDir = ".";
}
return HomeDir;
}
#else
fextl::string GetHomeDirectory() {
const char* HomeDir = getenv("WINEHOMEDIR");
if (HomeDir) {
// Skip over the \??\ prefix in the NT path since we want a DOS path
HomeDir += 4;
};
if (!HomeDir) {
HomeDir = getenv("LOCALAPPDATA");
}
if (!HomeDir) {
HomeDir = ".";
}
return HomeDir;
}
#endif
fextl::string GetDataDirectory(bool Global, const PortableInformation& PortableInfo) {
#ifdef FEX_STEAM_SUPPORT
const char* SteamDataPath = getenv("STEAM_COMPAT_DATA_PATH");
if (SteamDataPath) {
return fextl::fmt::format("{}/fex-emu/", SteamDataPath);
}
#endif
const char* DataOverride = getenv("FEX_APP_DATA_LOCATION");
if (PortableInfo.IsPortable && (Global || !DataOverride)) {
return fextl::fmt::format("{}/fex-emu/", PortableInfo.InterpreterPath);
}
if (Global) {
return GLOBAL_DATA_DIRECTORY;
}
auto HomeDir = GetHomeDirectory();
const char* DataXDG = getenv("XDG_DATA_HOME");
const fextl::string LegacyDir = fextl::string {HomeDir} + "/.fex-emu/";
// If $HOME/.fex-emu exists, use that
if (FHU::Filesystem::Exists(LegacyDir)) {
return LegacyDir;
}
fextl::string DataDir {};
if (DataOverride) {
// Data override will override the complete directory
DataDir = DataOverride;
} else {
// use ~/.local/share if XDG_DATA_HOME is unset
DataDir = DataXDG ? DataXDG : fmt::format("{}/.local/share", HomeDir);
DataDir += "/fex-emu/";
}
return DataDir;
}
fextl::string GetConfigDirectory(bool Global, const PortableInformation& PortableInfo) {
const char* ConfigOverride = getenv("FEX_APP_CONFIG_LOCATION");
if (PortableInfo.IsPortable && Global) {
return fextl::fmt::format("{}/fex-emu/", PortableInfo.InterpreterPath);
} else if (ConfigOverride && !Global) {
fextl::string AppConfigStr = ConfigOverride;
if (FHU::Filesystem::IsRelative(AppConfigStr)) {
AppConfigStr = PortableInfo.InterpreterPath + AppConfigStr;
}
return AppConfigStr;
}
#ifdef FEX_STEAM_SUPPORT
const char* SteamDataPath = getenv("STEAM_COMPAT_DATA_PATH");
if (SteamDataPath) {
return fextl::fmt::format("{}/fex-emu/", SteamDataPath);
}
#endif
fextl::string ConfigDir;
if (Global) {
return GLOBAL_DATA_DIRECTORY;
}
auto HomeDir = GetHomeDirectory();
const char* ConfigXDG = getenv("XDG_CONFIG_HOME");
const fextl::string LegacyDir = fextl::string {HomeDir} + "/.fex-emu/";
// If $HOME/.fex-emu exists, use that
if (FHU::Filesystem::Exists(LegacyDir)) {
return LegacyDir;
}
if (ConfigOverride) {
// Config override will override the complete directory
ConfigDir = ConfigOverride;
} else {
// use ~/.config if XDG_CONFIG_HOME is unset
ConfigDir = ConfigXDG ? ConfigXDG : fmt::format("{}/.config", HomeDir);
ConfigDir += "/fex-emu/";
}
return ConfigDir;
}
fextl::string GetCacheDirectory() {
const char* CacheOverride = getenv("FEX_APP_CACHE_LOCATION");
if (CacheOverride) {
return CacheOverride;
}
#ifndef _WIN32
#ifdef FEX_STEAM_SUPPORT
const char* SteamDataPath = getenv("STEAM_COMPAT_SHADER_PATH");
if (SteamDataPath) {
return fextl::fmt::format("{}/fex-emu/", SteamDataPath);
}
#endif
auto HomeDir = GetHomeDirectory();
const char* CacheXDG = getenv("XDG_CACHE_HOME");
return (CacheXDG ? fextl::string {CacheXDG} : (fextl::string {HomeDir} + "/.cache")) + "/fex-emu/";
#else
const char* PrefixAppData = getenv("LOCALAPPDATA");
return PrefixAppData ? (fextl::string {PrefixAppData} + "\\fex-emu\\") : fextl::string {".\\"};
#endif
}
fextl::string GetConfigFileLocation(bool Global, const PortableInformation& PortableInfo) {
return GetConfigDirectory(Global, PortableInfo) + "Config.json";
}
void InitializeConfigs(const PortableInformation& PortableInfo) {
FEXCore::Config::SetDataDirectory(GetDataDirectory(false, PortableInfo), false);
FEXCore::Config::SetDataDirectory(GetDataDirectory(true, PortableInfo), true);
FEXCore::Config::SetConfigDirectory(GetConfigDirectory(false, PortableInfo), false);
FEXCore::Config::SetConfigDirectory(GetConfigDirectory(true, PortableInfo), true);
FEXCore::Config::SetConfigFileLocation(GetConfigFileLocation(false, PortableInfo), false);
FEXCore::Config::SetConfigFileLocation(GetConfigFileLocation(true, PortableInfo), true);
}
} // namespace FEX::Config