Skip to content

Commit 8106355

Browse files
committed
Review comments.
Signed-off-by: fruffy <fruffy@nyu.edu>
1 parent ef32d61 commit 8106355

File tree

1 file changed

+18
-10
lines changed

1 file changed

+18
-10
lines changed

lib/exename.cpp

+18-10
Original file line numberDiff line numberDiff line change
@@ -55,25 +55,32 @@ std::filesystem::path getExecutablePath(const std::filesystem::path &suggestedPa
5555
}
5656
}
5757
#elif defined(__APPLE__)
58-
static std::array<char, PATH_MAX> buffer{};
58+
std::array<char, PATH_MAX> buffer{};
5959
uint32_t size = static_cast<uint32_t>(buffer.size());
6060
if (_NSGetExecutablePath(buffer.data(), &size) == 0) {
6161
// TODO: What to do about the allocation here?
62-
return (buffer.data());
63-
}
62+
return buffer.data();
63+
} else
6464
#elif defined(_WIN32)
65-
static std::array<char, PATH_MAX> buffer{};
65+
std::array<char, PATH_MAX> buffer{};
6666
// TODO: Do we need to support this?
6767
DWORD size = GetModuleFileNameA(nullptr, buffer.data(), static_cast<DWORD>(buffer.size()));
6868
if (size > 0 && size < buffer.size()) {
69-
return (buffer.data());
70-
}
69+
return buffer.data();
70+
} else
7171
#endif
72-
// If the above fails, try to convert argv0 to a path.
73-
if (std::filesystem::exists(suggestedPath)) {
74-
return suggestedPath;
72+
if (auto *path = getenv("_")) {
73+
return path;
74+
}
75+
// If the above fails, try to convert suggestedPath to a path.
76+
try {
77+
// std::filesystem::canonical will throw on error if the path is invalid.
78+
// It will also try to resolve symlinks.
79+
return std::filesystem::canonical(suggestedPath);
80+
} catch (const std::filesystem::filesystem_error &) {
81+
// In the case of an error, return an empty path.
82+
return {};
7583
}
76-
return {};
7784
}
7885

7986
const char *exename(const char *argv0) {
@@ -84,6 +91,7 @@ const char *exename(const char *argv0) {
8491
if (path.empty()) {
8592
return nullptr;
8693
}
94+
// TODO: There is a potential leak here.
8795
return strdup(path.c_str());
8896
}
8997

0 commit comments

Comments
 (0)