Skip to content

Commit 318a9af

Browse files
committed
fix: fix segfault on linux
1 parent 7b6f7a8 commit 318a9af

File tree

1 file changed

+10
-2
lines changed

1 file changed

+10
-2
lines changed

Sources/LCLAuth/Utils/Security+LCLPingAuth.swift

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@ import Crypto
3131
- Returns: A `Result` type. When succeeded, the associated secure random data will be return; When failed, `LCLAuthError` will be returned
3232
*/
3333
public func generateSecureRandomBytes(count: Int) -> Result<Data, LCLAuthError> {
34+
precondition(count > 0, "count must be greater than 0")
35+
3436
var bytes: ByteArray = ByteArray(repeating: 0, count: count)
3537

3638
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
@@ -43,8 +45,12 @@ public func generateSecureRandomBytes(count: Int) -> Result<Data, LCLAuthError>
4345
// success
4446
return .success(Data(bytes))
4547
#elseif os(Linux)
46-
let res = withUnsafeMutableBytes(of: &bytes) { buffer in
47-
return getentropy(buffer.baseAddress, count)
48+
let res = bytes.withUnsafeMutableBytes { buffer -> Int32 in
49+
// The buffer might be empty if count was 0, so safely unwrap the baseAddress.
50+
guard let baseAddress = buffer.baseAddress else {
51+
return 0 // Nothing to do for an empty buffer.
52+
}
53+
return getentropy(baseAddress, buffer.count)
4854
}
4955

5056
if res == -1 {
@@ -53,6 +59,8 @@ public func generateSecureRandomBytes(count: Int) -> Result<Data, LCLAuthError>
5359
}
5460

5561
return .success(Data(bytes))
62+
#else
63+
#error("Unknown platform")
5664
#endif
5765
}
5866

0 commit comments

Comments
 (0)