Skip to content

Omnibus to get a clean OpenBSD build. #3003

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 9 commits into from
Jul 14, 2021
62 changes: 62 additions & 0 deletions CoreFoundation/Base.subproj/CFPlatform.c
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,12 @@ static inline void _CFSetProgramNameFromPath(const char *path) {
__CFprogname = (__CFprogname ? __CFprogname + 1 : __CFProcessPath);
}

#if TARGET_OS_BSD && defined(__OpenBSD__)
#include <sys/types.h>
#include <sys/sysctl.h>
#include <sys/exec.h>
#endif

const char *_CFProcessPath(void) {
if (__CFProcessPath) return __CFProcessPath;

Expand Down Expand Up @@ -175,6 +181,53 @@ const char *_CFProcessPath(void) {
}
return __CFProcessPath;
#else // TARGET_OS_BSD
char *argv0 = NULL;

// Get argv[0].
#if defined(__OpenBSD__)
int mib[2] = {CTL_VM, VM_PSSTRINGS};
struct _ps_strings _ps;
size_t len = sizeof(_ps);

if (sysctl(mib, 2, &_ps, &len, NULL, 0) != -1) {
struct ps_strings *ps = _ps.val;
char *res = realpath(ps->ps_argvstr[0], NULL);
argv0 = res? res: strdup(ps->ps_argvstr[0]);
}
#endif

if (!__CFProcessIsRestricted() && argv0 && argv0[0] == '/') {
_CFSetProgramNameFromPath(argv0);
free(argv0);
return __CFProcessPath;
}

// Search PATH.
if (argv0) {
char *paths = getenv("PATH");
char *p = NULL;
while ((p = strsep(&paths, ":")) != NULL) {
char pp[PATH_MAX];
int l = snprintf(pp, PATH_MAX, "%s/%s", p, argv0);
if (l >= PATH_MAX) {
continue;
}
char *res = realpath(pp, NULL);
if (!res) {
continue;
}
if (!__CFProcessIsRestricted() && access(res, X_OK) == 0) {
_CFSetProgramNameFromPath(res);
free(argv0);
free(res);
return __CFProcessPath;
}
free(res);
}
free(argv0);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you just tidy up the formatting in this if block so its all consistent at 4 space indent, thanks.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oops -- sorry about that. Fixed.


Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would this have issues if the executable was specified using a relative path ,eg ../some_executable ? It would fail the first check but not necessarily be in the PATH

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, that would not work if the realpath call failed and we fell back to argv[0]. We can call realpath a second time to ensure we get an absolute path. Added missing free calls as well.

// See if the shell will help.
if (!__CFProcessIsRestricted()) {
char *path = getenv("_");
if (path != NULL) {
Expand Down Expand Up @@ -1574,6 +1627,9 @@ CF_CROSS_PLATFORM_EXPORT int _CFThreadSetName(_CFThreadRef thread, const char *_
return 0;
#elif TARGET_OS_LINUX
return pthread_setname_np(thread, name);
#elif TARGET_OS_BSD
pthread_set_name_np(thread, name);
return 0;
#endif
}

Expand All @@ -1593,6 +1649,9 @@ CF_CROSS_PLATFORM_EXPORT int _CFThreadGetName(char *buf, int length) {
return 0;
#elif TARGET_OS_LINUX
return pthread_getname_np(pthread_self(), buf, length);
#elif TARGET_OS_BSD
pthread_get_name_np(pthread_self(), buf, length);
return 0;
#elif TARGET_OS_WIN32
*buf = '\0';

Expand Down Expand Up @@ -1630,6 +1689,9 @@ CF_EXPORT char **_CFEnviron(void) {
#elif TARGET_OS_WIN32
return _environ;
#else
#if TARGET_OS_BSD
extern char **environ;
#endif
return environ;
#endif
}
Expand Down
4 changes: 3 additions & 1 deletion CoreFoundation/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,9 @@ add_compile_options($<$<COMPILE_LANGUAGE:C>:-fblocks>)
if("${CMAKE_C_SIMULATE_ID}" STREQUAL "MSVC")
add_compile_options($<$<COMPILE_LANGUAGE:C>:/EHsc>)
else()
add_compile_options($<$<COMPILE_LANGUAGE:C>:-fexceptions>)
if(NOT CMAKE_SYSTEM_NAME STREQUAL OpenBSD)
add_compile_options($<$<COMPILE_LANGUAGE:C>:-fexceptions>)
endif()
endif()

if(NOT "${CMAKE_C_SIMULATE_ID}" STREQUAL "MSVC")
Expand Down
4 changes: 4 additions & 0 deletions CoreFoundation/PlugIn.subproj/CFBundle_Binary.c
Original file line number Diff line number Diff line change
Expand Up @@ -470,7 +470,11 @@ CF_PRIVATE Boolean _CFBundleDlfcnCheckLoaded(CFBundleRef bundle) {
char buff[CFMaxPathSize];

if (executableURL && CFURLGetFileSystemRepresentation(executableURL, true, (uint8_t *)buff, CFMaxPathSize)) {
#if !defined(__OpenBSD__)
int mode = RTLD_LAZY | RTLD_LOCAL | RTLD_NOLOAD | RTLD_FIRST;
#else
int mode = RTLD_LAZY | RTLD_LOCAL | RTLD_FIRST;
#endif
void *handle = dlopen(buff, mode);
if (handle) {
if (!bundle->_handleCookie) {
Expand Down
4 changes: 4 additions & 0 deletions CoreFoundation/PlugIn.subproj/CFBundle_Main.c
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,11 @@ static CFBundleRef _CFBundleGetMainBundleAlreadyLocked(void) {
// get cookie for already-loaded main bundle
#if defined(BINARY_SUPPORT_DLFCN)
if (!_mainBundle->_handleCookie) {
#if !defined(__OpenBSD__)
_mainBundle->_handleCookie = dlopen(NULL, RTLD_NOLOAD | RTLD_FIRST);
#else
_mainBundle->_handleCookie = dlopen(NULL, RTLD_FIRST);
#endif
#if LOG_BUNDLE_LOAD
printf("main bundle %p getting handle %p\n", _mainBundle, _mainBundle->_handleCookie);
#endif /* LOG_BUNDLE_LOAD */
Expand Down
6 changes: 1 addition & 5 deletions CoreFoundation/Stream.subproj/CFStream.c
Original file line number Diff line number Diff line change
Expand Up @@ -1675,11 +1675,7 @@ static void _perform(void* info)

static void* _legacyStreamRunLoop_workThread(void* arg)
{
#if TARGET_OS_LINUX
pthread_setname_np(pthread_self(), "com.apple.CFStream.LegacyThread");
#else
pthread_setname_np("com.apple.CFStream.LegacyThread");
#endif
_CFThreadSetName(pthread_self(), "com.apple.CFStream.LegacyThread");
sLegacyRL = CFRunLoopGetCurrent();

#if defined(LOG_STREAM)
Expand Down
26 changes: 26 additions & 0 deletions Sources/Foundation/FileManager+POSIX.swift
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,32 @@ extension FileManager {
}
urls = mountPoints(statBuf, Int(fsCount))
}
#elseif os(OpenBSD)
func mountPoints(_ statBufs: UnsafePointer<statfs>, _ fsCount: Int) -> [URL] {
var urls: [URL] = []

for fsIndex in 0..<fsCount {
var fs = statBufs.advanced(by: fsIndex).pointee

let mountPoint = withUnsafePointer(to: &fs.f_mntonname.0) { (ptr: UnsafePointer<Int8>) -> String in
return string(withFileSystemRepresentation: ptr, length: strlen(ptr))
}
urls.append(URL(fileURLWithPath: mountPoint, isDirectory: true))
}
return urls
}

var fsCount = getfsstat(nil, 0, MNT_WAIT)
guard fsCount > 0 else {
return nil
}
let statBuf = UnsafeMutablePointer<statfs>.allocate(capacity: Int(fsCount))
defer { statBuf.deallocate() }
fsCount = getfsstat(statBuf, Int(fsCount) * MemoryLayout<statfs>.stride, MNT_WAIT)
guard fsCount > 0 else {
return nil
}
urls = mountPoints(statBuf, Int(fsCount))
#else
#error("Requires a platform-specific implementation")
#endif
Expand Down
14 changes: 12 additions & 2 deletions Sources/Foundation/Host.swift
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,12 @@ open class Host: NSObject {
let family = ifa_addr.pointee.sa_family
if family == sa_family_t(AF_INET) || family == sa_family_t(AF_INET6) {
let sa_len: socklen_t = socklen_t((family == sa_family_t(AF_INET6)) ? MemoryLayout<sockaddr_in6>.size : MemoryLayout<sockaddr_in>.size)
if getnameinfo(ifa_addr, sa_len, address, socklen_t(NI_MAXHOST), nil, 0, NI_NUMERICHOST) == 0 {
#if os(OpenBSD)
let hostlen = size_t(NI_MAXHOST)
#else
let hostlen = socklen_t(NI_MAXHOST)
#endif
if getnameinfo(ifa_addr, sa_len, address, hostlen, nil, 0, NI_NUMERICHOST) == 0 {
_addresses.append(String(cString: address))
}
}
Expand Down Expand Up @@ -303,7 +308,12 @@ open class Host: NSObject {
}
let sa_len: socklen_t = socklen_t((family == AF_INET6) ? MemoryLayout<sockaddr_in6>.size : MemoryLayout<sockaddr_in>.size)
let lookupInfo = { (content: inout [String], flags: Int32) in
if getnameinfo(info.ai_addr, sa_len, host, socklen_t(NI_MAXHOST), nil, 0, flags) == 0 {
#if os(OpenBSD)
let hostlen = size_t(NI_MAXHOST)
#else
let hostlen = socklen_t(NI_MAXHOST)
#endif
if getnameinfo(info.ai_addr, sa_len, host, hostlen, nil, 0, flags) == 0 {
content.append(String(cString: host))
}
}
Expand Down
4 changes: 4 additions & 0 deletions Sources/Foundation/NSError.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1344,6 +1344,7 @@ extension POSIXError {
/// Bad message.
public static var EBADMSG: POSIXError.Code { return .EBADMSG }

#if !os(OpenBSD)
/// Reserved.
public static var EMULTIHOP: POSIXError.Code { return .EMULTIHOP }

Expand All @@ -1358,13 +1359,16 @@ extension POSIXError {

/// Not a STREAM.
public static var ENOSTR: POSIXError.Code { return .ENOSTR }
#endif

/// Protocol error.
public static var EPROTO: POSIXError.Code { return .EPROTO }

#if !os(OpenBSD)
/// STREAM ioctl timeout.
public static var ETIME: POSIXError.Code { return .ETIME }
#endif
#endif

#if canImport(Darwin)
/// No such policy registered.
Expand Down
7 changes: 6 additions & 1 deletion Sources/Foundation/NSLock.swift
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,12 @@ open class NSRecursiveLock: NSObject, NSLocking {
#endif
withUnsafeMutablePointer(to: &attrib) { attrs in
pthread_mutexattr_init(attrs)
pthread_mutexattr_settype(attrs, Int32(PTHREAD_MUTEX_RECURSIVE))
#if os(OpenBSD)
let type = Int32(PTHREAD_MUTEX_RECURSIVE.rawValue)
#else
let type = Int32(PTHREAD_MUTEX_RECURSIVE)
#endif
pthread_mutexattr_settype(attrs, type)
pthread_mutex_init(mutex, attrs)
}
#if os(macOS) || os(iOS)
Expand Down
7 changes: 5 additions & 2 deletions Sources/Foundation/Port.swift
Original file line number Diff line number Diff line change
Expand Up @@ -83,19 +83,22 @@ public protocol PortDelegate: AnyObject {
func handle(_ message: PortMessage)
}

#if canImport(Glibc) && !os(Android)
#if canImport(Glibc) && !os(Android) && !os(OpenBSD)
import Glibc
fileprivate let SOCK_STREAM = Int32(Glibc.SOCK_STREAM.rawValue)
fileprivate let SOCK_DGRAM = Int32(Glibc.SOCK_DGRAM.rawValue)
fileprivate let IPPROTO_TCP = Int32(Glibc.IPPROTO_TCP)
#endif

#if canImport(Glibc) && os(Android)
#if canImport(Glibc) && os(Android) || os(OpenBSD)
import Glibc
fileprivate let SOCK_STREAM = Int32(Glibc.SOCK_STREAM)
fileprivate let SOCK_DGRAM = Int32(Glibc.SOCK_DGRAM)
fileprivate let IPPROTO_TCP = Int32(Glibc.IPPROTO_TCP)
fileprivate let INADDR_ANY: in_addr_t = 0
#if os(OpenBSD)
fileprivate let INADDR_LOOPBACK = 0x7f000001
#endif
#endif


Expand Down
8 changes: 4 additions & 4 deletions Sources/Foundation/Thread.swift
Original file line number Diff line number Diff line change
Expand Up @@ -135,13 +135,13 @@ open class Thread : NSObject {
var ti = end_at - start_at
let end_ut = start_ut + ti
while (0.0 < ti) {
var __ts__ = timespec(tv_sec: Int.max, tv_nsec: 0)
var __ts__ = timespec(tv_sec: time_t.max, tv_nsec: 0)
if ti < Double(Int.max) {
var integ = 0.0
let frac: Double = withUnsafeMutablePointer(to: &integ) { integp in
return modf(ti, integp)
}
__ts__.tv_sec = Int(integ)
__ts__.tv_sec = time_t(integ)
__ts__.tv_nsec = Int(frac * 1000000000.0)
}
let _ = withUnsafePointer(to: &__ts__) { ts in
Expand Down Expand Up @@ -170,13 +170,13 @@ open class Thread : NSObject {
let start_ut = CFGetSystemUptime()
let end_ut = start_ut + ti
while 0.0 < ti {
var __ts__ = timespec(tv_sec: Int.max, tv_nsec: 0)
var __ts__ = timespec(tv_sec: time_t.max, tv_nsec: 0)
if ti < Double(Int.max) {
var integ = 0.0
let frac: Double = withUnsafeMutablePointer(to: &integ) { integp in
return modf(ti, integp)
}
__ts__.tv_sec = Int(integ)
__ts__.tv_sec = time_t(integ)
__ts__.tv_nsec = Int(frac * 1000000000.0)
}
let _ = withUnsafePointer(to: &__ts__) { ts in
Expand Down
4 changes: 4 additions & 0 deletions Tests/Foundation/HTTPServer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ import Dispatch
typealias SOCKET = Int32
#endif

#if os(OpenBSD)
let INADDR_LOOPBACK = 0x7f000001
#endif

private let serverDebug = (ProcessInfo.processInfo.environment["SCLF_HTTP_SERVER_DEBUG"] == "YES")

private func debugLog(_ msg: String) {
Expand Down
15 changes: 13 additions & 2 deletions Tests/Foundation/Tests/TestThread.swift
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ class TestThread : XCTestCase {
#if os(Linux) || os(Android) // Linux sets the initial thread name to the process name.
XCTAssertEqual(Thread.current.name, "TestFoundation")
testInternalThreadName("TestFoundation")
#elseif os(OpenBSD) // OpenBSD sets the initial thread name to this.
XCTAssertEqual(Thread.current.name, "Original thread")
testInternalThreadName("Original thread")
#else
// No name is set initially
XCTAssertEqual(Thread.current.name, "")
Expand Down Expand Up @@ -160,8 +163,16 @@ class TestThread : XCTestCase {
("test_currentThread", test_currentThread),
("test_threadStart", test_threadStart),
("test_mainThread", test_mainThread),
("test_callStackSymbols", testExpectedToFailOnAndroid(test_callStackSymbols, "Android doesn't support backtraces at the moment.")),
("test_callStackReturnAddresses", testExpectedToFailOnAndroid(test_callStackReturnAddresses, "Android doesn't support backtraces at the moment.")),
("test_callStackSymbols", testExpectedToFailOnOpenBSD(
testExpectedToFailOnAndroid(
test_callStackSymbols,
"Android doesn't support backtraces at the moment."),
"And not currently on OpenBSD.")),
("test_callStackReturnAddresses", testExpectedToFailOnOpenBSD(
testExpectedToFailOnAndroid(
test_callStackReturnAddresses,
"Android doesn't support backtraces at the moment."),
"And not currently on OpenBSD.")),
("test_sleepForTimeInterval", test_sleepForTimeInterval),
("test_sleepUntilDate", test_sleepUntilDate),
("test_threadName", test_threadName),
Expand Down
12 changes: 12 additions & 0 deletions Tests/Foundation/Utilities.swift
Original file line number Diff line number Diff line change
Expand Up @@ -557,6 +557,14 @@ func shouldAttemptAndroidXFailTests(_ reason: String) -> Bool {
#endif
}

func shouldAttemptOpenBSDXFailTests(_ reason: String) -> Bool {
#if os(OpenBSD)
return shouldAttemptXFailTests(reason)
#else
return true
#endif
}

#if !DARWIN_COMPATIBILITY_TESTS
func testCaseExpectedToFail<T: XCTestCase>(_ allTests: [(String, (T) -> () throws -> Void)], _ reason: String) -> XCTestCaseEntry {
return testCase(allTests.map { ($0.0, testExpectedToFail($0.1, "This test suite is disabled: \(reason)")) })
Expand All @@ -581,6 +589,10 @@ func testExpectedToFailOnAndroid<T>(_ test: @escaping (T) -> () throws -> Void,
testExpectedToFailWithCheck(check: shouldAttemptAndroidXFailTests(_:), test, reason)
}

func testExpectedToFailOnOpenBSD<T>(_ test: @escaping (T) -> () throws -> Void, _ reason: String) -> (T) -> () throws -> Void {
testExpectedToFailWithCheck(check: shouldAttemptOpenBSDXFailTests(_:), test, reason)
}

func testExpectedToFailWithCheck<T>(check: (String) -> Bool, _ test: @escaping (T) -> () throws -> Void, _ reason: String) -> (T) -> () throws -> Void {
if check(reason) {
return test
Expand Down
2 changes: 2 additions & 0 deletions cmake/modules/SwiftSupport.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ function(get_swift_host_arch result_var_name)
set("${result_var_name}" "armv7" PARENT_SCOPE)
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "armv7-a")
set("${result_var_name}" "armv7" PARENT_SCOPE)
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "amd64")
set("${result_var_name}" "amd64" PARENT_SCOPE)
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "AMD64")
set("${result_var_name}" "x86_64" PARENT_SCOPE)
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "IA64")
Expand Down