Skip to content

Commit

Permalink
Allow to specify environment variables in the .shim file (kiennq#4)
Browse files Browse the repository at this point in the history
  • Loading branch information
kodemeister committed May 1, 2024
1 parent b806aa8 commit 5ff5923
Showing 1 changed file with 20 additions and 4 deletions.
24 changes: 20 additions & 4 deletions shim.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ struct ShimInfo
{
std::wstring_p path;
std::wstring_p args;
std::vector<std::tuple<std::wstring, std::wstring>> vars;
};

std::wstring_view GetDirectory(std::wstring_view exe)
Expand Down Expand Up @@ -112,6 +113,7 @@ ShimInfo GetShimInfo()
wchar_t linebuf[1<<14];
std::wstring_p path;
std::wstring_p args;
std::vector<std::tuple<std::wstring, std::wstring>> vars;
while (true)
{
if (!fgetws(linebuf, ARRAYSIZE(linebuf), shimFile.get()))
Expand Down Expand Up @@ -152,9 +154,15 @@ ShimInfo GetShimInfo()
args.emplace(value);
continue;
}

if (!name.empty())
{
vars.emplace_back(name, value);
continue;
}
}

return {path, NormalizeArgs(args, GetDirectory(filename))};
return {path, NormalizeArgs(args, GetDirectory(filename)), vars};
}

std::tuple<std::unique_handle, std::unique_handle> MakeProcess(ShimInfo const& info)
Expand All @@ -163,13 +171,21 @@ std::tuple<std::unique_handle, std::unique_handle> MakeProcess(ShimInfo const& i
STARTUPINFOW si = {};
PROCESS_INFORMATION pi = {};

auto&& [path, args] = info;
auto&& [path, args, vars] = info;
std::vector<wchar_t> cmd(path->size() + args->size() + 2);
wmemcpy(cmd.data(), path->c_str(), path->size());
cmd[path->size()] = L' ';
wmemcpy(cmd.data() + path->size() + 1, args->c_str(), args->size());
cmd[path->size() + 1 + args->size()] = L'\0';

for (auto& [name, value] : vars)
{
if (_wputenv_s(name.c_str(), value.c_str()))
{
fprintf(stderr, "Shim: Could not set environment variable '%ls' to '%ls'.\n", name.c_str(), value.c_str());
}
}

std::unique_handle threadHandle;
std::unique_handle processHandle;

Expand Down Expand Up @@ -226,7 +242,7 @@ std::tuple<std::unique_handle, std::unique_handle> MakeProcess(ShimInfo const& i

int wmain(int argc, wchar_t* argv[])
{
auto [path, args] = GetShimInfo();
auto [path, args, vars] = GetShimInfo();

if (!path)
{
Expand Down Expand Up @@ -279,7 +295,7 @@ int wmain(int argc, wchar_t* argv[])
jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK;
SetInformationJobObject(jobHandle.get(), JobObjectExtendedLimitInformation, &jeli, sizeof(jeli));

auto [processHandle, threadHandle] = MakeProcess({path, args});
auto [processHandle, threadHandle] = MakeProcess({path, args, vars});
if (processHandle && !isWindowsApp)
{
AssignProcessToJobObject(jobHandle.get(), processHandle.get());
Expand Down

0 comments on commit 5ff5923

Please sign in to comment.