Skip to content

Commit 64fff9d

Browse files
authored
Bin compat: use Platform.getFullExecutablePath instead of CommandLine.arguments.first for ProcessInfo.processName. (#1411)
* Bin compat: use Platform.getFullExecutablePath instead of CommandLine.arguments.first for ProcessInfo.processName. The original NSProcessInfo implementation calls _CFProcessPath for processName, which Platform.getFullExecutablePath internally calls. We should maintain the same behavior for binary compatibility. * Update Platform.getFullExecutablePath implementation for Windows to match _CFProcessPath
1 parent eefacbc commit 64fff9d

File tree

2 files changed

+7
-13
lines changed

2 files changed

+7
-13
lines changed

Sources/FoundationEssentials/Platform.swift

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -355,17 +355,14 @@ extension Platform {
355355
return try? FileManager.default.destinationOfSymbolicLink(
356356
atPath: "/proc/self/exe").standardizingPath
357357
#elseif os(Windows)
358-
let hFile = GetModuleHandleW(nil)
359-
let dwLength: DWORD = GetFinalPathNameByHandleW(hFile, nil, 0, FILE_NAME_NORMALIZED)
360-
guard dwLength > 0 else { return nil }
361-
return withUnsafeTemporaryAllocation(of: WCHAR.self, capacity: Int(dwLength)) { lpBuffer in
362-
guard GetFinalPathNameByHandleW(hFile, lpBuffer.baseAddress, dwLength, FILE_NAME_NORMALIZED) == dwLength - 1 else {
358+
return withUnsafeTemporaryAllocation(of: WCHAR.self, capacity: Int(MAX_PATH)) { lpBuffer in
359+
let actualLength = GetModuleFileNameW(nil, lpBuffer.baseAddress!, DWORD(lpBuffer.count))
360+
// Windows Documentation:
361+
// If the function fails, the return value is 0 (zero).
362+
// To get extended error information, call GetLastError.
363+
guard actualLength > 0 else {
363364
return nil
364365
}
365-
366-
// The `GetFinalPathNameByHandleW` function will normalise the path
367-
// for us as part of the query. This allows us to avoid having to
368-
// standardize the path ourselves.
369366
return String(decodingCString: lpBuffer.baseAddress!, as: UTF16.self)
370367
}
371368
#else

Sources/FoundationEssentials/ProcessInfo/ProcessInfo.swift

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -597,10 +597,7 @@ extension _ProcessInfo {
597597
}
598598

599599
private static func _getProcessName() -> String {
600-
guard let processPath = CommandLine.arguments.first else {
601-
return ""
602-
}
603-
return processPath.lastPathComponent
600+
return Platform.getFullExecutablePath()?.lastPathComponent ?? ""
604601
}
605602

606603
#if os(macOS)

0 commit comments

Comments
 (0)