Skip to content

Use _NSGetExecutablePath() instead of proc_pidpath() to get the main executable path. #374

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 25, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 13 additions & 5 deletions Sources/Testing/Support/Additions/CommandLineAdditions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,20 @@ extension CommandLine {
static var executablePath: String {
get throws {
#if os(macOS)
return try withUnsafeTemporaryAllocation(of: CChar.self, capacity: Int(PATH_MAX) * 2) { buffer in
guard 0 != proc_pidpath(getpid(), buffer.baseAddress!, UInt32(buffer.count)) else {
throw CError(rawValue: swt_errno())
var result: String?
var bufferCount = UInt32(1024)
while result == nil {
result = withUnsafeTemporaryAllocation(of: CChar.self, capacity: Int(bufferCount)) { buffer in
// _NSGetExecutablePath returns 0 on success and -1 if bufferCount is
// too small. If that occurs, we'll return nil here and loop with the
// new value of bufferCount.
if 0 == _NSGetExecutablePath(buffer.baseAddress, &bufferCount) {
return String(cString: buffer.baseAddress!)
}
return nil
}
return String(cString: buffer.baseAddress!)
}
return result!
#elseif os(Linux)
return try withUnsafeTemporaryAllocation(of: CChar.self, capacity: Int(PATH_MAX) * 2) { buffer in
let readCount = readlink("/proc/\(getpid())/exe", buffer.baseAddress!, buffer.count - 1)
Expand All @@ -49,7 +57,7 @@ extension CommandLine {
throw Win32Error(rawValue: GetLastError())
}
guard let path = String.decodeCString(buffer.baseAddress!, as: UTF16.self)?.result else {
throw CError(rawValue: ERROR_ILLEGAL_CHARACTER)
throw Win32Error(rawValue: ERROR_ILLEGAL_CHARACTER)
}
return path
}
Expand Down