diff --git a/Sources/NIO/ByteBuffer-core.swift b/Sources/NIO/ByteBuffer-core.swift index f8a926dde..3a12173d2 100644 --- a/Sources/NIO/ByteBuffer-core.swift +++ b/Sources/NIO/ByteBuffer-core.swift @@ -17,6 +17,9 @@ #else import Glibc #endif +let sysMalloc = malloc +let sysRealloc = realloc +let sysFree = free /// The preferred allocator for `ByteBuffer` values. The allocation strategy is opaque but is currently libc's /// `malloc`, `realloc` and `free`. @@ -26,8 +29,22 @@ public struct ByteBufferAllocator { /// therefore it's recommended to reuse `ByteBufferAllocators` where possible instead of creating fresh ones in /// many places. public init() { + self.init(hookedMalloc: { sysMalloc($0) }, + hookedRealloc: { sysRealloc($0, $1) }, + hookedFree: { sysFree($0) }, + hookedMemcpy: { $0.copyBytes(from: $1, count: $2) }) + } + + internal init(hookedMalloc: @escaping @convention(c) (Int) -> UnsafeMutableRawPointer!, + hookedRealloc: @escaping @convention(c) (UnsafeMutableRawPointer, Int) -> UnsafeMutableRawPointer!, + hookedFree: @escaping @convention(c) (UnsafeMutableRawPointer) -> Void, + hookedMemcpy: @escaping @convention(c) (UnsafeMutableRawPointer, UnsafeRawPointer, Int) -> Void) { assert(MemoryLayout.size <= 3 * MemoryLayout.size, "ByteBuffer has size \(MemoryLayout.size) which is larger than the built-in storage of the existential containers.") + self.malloc = hookedMalloc + self.realloc = hookedRealloc + self.free = hookedFree + self.memcpy = hookedMemcpy } /// Request a freshly allocated `ByteBuffer` of size `capacity` or larger. @@ -37,6 +54,12 @@ public struct ByteBufferAllocator { public func buffer(capacity: Int) -> ByteBuffer { return ByteBuffer(allocator: self, startingCapacity: capacity) } + + internal let malloc: @convention(c) (Int) -> UnsafeMutableRawPointer! + internal let realloc: @convention(c) (UnsafeMutableRawPointer, Int) -> UnsafeMutableRawPointer! + internal let free: @convention(c) (UnsafeMutableRawPointer) -> Void + internal let memcpy: @convention(c) (UnsafeMutableRawPointer, UnsafeRawPointer, Int) -> Void + } private typealias Index = UInt32 @@ -153,9 +176,9 @@ public struct ByteBuffer { self.deallocate() } - private static func allocateAndPrepareRawMemory(bytes: Capacity) -> UnsafeMutableRawPointer { + private static func allocateAndPrepareRawMemory(bytes: Capacity, allocator: Allocator) -> UnsafeMutableRawPointer { let bytes = Int(bytes) - let ptr = malloc(bytes)! + let ptr = allocator.malloc(bytes)! /* bind the memory so we can assume it elsewhere to be bound to UInt8 */ ptr.bindMemory(to: UInt8.self, capacity: bytes) return ptr @@ -163,16 +186,16 @@ public struct ByteBuffer { public func duplicate(slice: Slice, capacity: Capacity) -> _Storage { assert(slice.count <= capacity) - let newCapacity = capacity == 0 ? 0 : capacity.nextPowerOf2() - let new = _Storage(bytesNoCopy: _Storage.allocateAndPrepareRawMemory(bytes: newCapacity), + let newCapacity = capacity == 0 ? 0 : capacity.nextPowerOf2ClampedToMax() + let new = _Storage(bytesNoCopy: _Storage.allocateAndPrepareRawMemory(bytes: newCapacity, allocator: self.allocator), capacity: newCapacity, allocator: self.allocator) - new.bytes.copyBytes(from: self.bytes.advanced(by: Int(slice.lowerBound)), count: slice.count) + self.allocator.memcpy(new.bytes, self.bytes.advanced(by: Int(slice.lowerBound)), slice.count) return new } public func reallocStorage(capacity: Capacity) { - let ptr = realloc(self.bytes, Int(capacity))! + let ptr = self.allocator.realloc(self.bytes, Int(capacity))! /* bind the memory so we can assume it elsewhere to be bound to UInt8 */ ptr.bindMemory(to: UInt8.self, capacity: Int(capacity)) self.bytes = ptr @@ -181,13 +204,13 @@ public struct ByteBuffer { } private func deallocate() { - free(self.bytes) + self.allocator.free(self.bytes) } public static func reallocated(minimumCapacity: Capacity, allocator: Allocator) -> _Storage { - let newCapacity = minimumCapacity == 0 ? 0 : minimumCapacity.nextPowerOf2() + let newCapacity = minimumCapacity == 0 ? 0 : minimumCapacity.nextPowerOf2ClampedToMax() // TODO: Use realloc if possible - return _Storage(bytesNoCopy: _Storage.allocateAndPrepareRawMemory(bytes: newCapacity), + return _Storage(bytesNoCopy: _Storage.allocateAndPrepareRawMemory(bytes: newCapacity, allocator: allocator), capacity: newCapacity, allocator: allocator) } @@ -225,7 +248,12 @@ public struct ByteBuffer { // double the capacity until the requested capacity can be full-filled repeat { - newCapacity = newCapacity << 1 + precondition(newCapacity != Capacity.max, "cannot make ByteBuffers larger than \(newCapacity)") + if newCapacity < (Capacity.max >> 1) { + newCapacity = newCapacity << 1 + } else { + newCapacity = Capacity.max + } } while newCapacity < index || newCapacity - index < capacity self._storage.reallocStorage(capacity: newCapacity) diff --git a/Sources/NIO/ByteBuffer-int.swift b/Sources/NIO/ByteBuffer-int.swift index 0c07864d2..483296908 100644 --- a/Sources/NIO/ByteBuffer-int.swift +++ b/Sources/NIO/ByteBuffer-int.swift @@ -110,6 +110,27 @@ extension UInt64 { } extension UInt32 { + /// Returns the next power of two unless that would overflow in which case UInt32.max is returned. + public func nextPowerOf2ClampedToMax() -> UInt32 { + guard self > 0 else { + return 1 + } + + var n = self + + n -= 1 + n |= n >> 1 + n |= n >> 2 + n |= n >> 4 + n |= n >> 8 + n |= n >> 16 + if n != .max { + n += 1 + } + + return n + } + /// Returns the next power of two. public func nextPowerOf2() -> UInt32 { guard self > 0 else { diff --git a/Tests/NIOTests/ByteBufferTest+XCTest.swift b/Tests/NIOTests/ByteBufferTest+XCTest.swift index ab84d11c3..6f87a0e0c 100644 --- a/Tests/NIOTests/ByteBufferTest+XCTest.swift +++ b/Tests/NIOTests/ByteBufferTest+XCTest.swift @@ -101,6 +101,7 @@ extension ByteBufferTest { ("testGetIntegerBeyondCapacity", testGetIntegerBeyondCapacity), ("testSetStringBeyondCapacity", testSetStringBeyondCapacity), ("testGetStringBeyondCapacity", testGetStringBeyondCapacity), + ("testAllocationOfReallyBigByteBuffer", testAllocationOfReallyBigByteBuffer), ] } } diff --git a/Tests/NIOTests/ByteBufferTest.swift b/Tests/NIOTests/ByteBufferTest.swift index 5b73aadde..3b71a800c 100644 --- a/Tests/NIOTests/ByteBufferTest.swift +++ b/Tests/NIOTests/ByteBufferTest.swift @@ -993,4 +993,55 @@ class ByteBufferTest: XCTestCase { XCTAssertNil(i) } + func testAllocationOfReallyBigByteBuffer() throws { + let alloc = ByteBufferAllocator(hookedMalloc: { testAllocationOfReallyBigByteBuffer_mallocHook($0) }, + hookedRealloc: { testAllocationOfReallyBigByteBuffer_reallocHook($0, $1) }, + hookedFree: { testAllocationOfReallyBigByteBuffer_freeHook($0) }, + hookedMemcpy: { testAllocationOfReallyBigByteBuffer_memcpyHook($0, $1, $2) }) + + XCTAssertEqual(AllocationExpectationState.begin, testAllocationOfReallyBigByteBuffer_state) + var buf = alloc.buffer(capacity: Int(Int32.max)) + XCTAssertEqual(AllocationExpectationState.mallocDone, testAllocationOfReallyBigByteBuffer_state) + XCTAssertGreaterThanOrEqual(buf.capacity, Int(Int32.max)) + + buf.set(bytes: [1], at: 0) + /* now make it expand (will trigger realloc) */ + buf.set(bytes: [1], at: buf.capacity) + + XCTAssertEqual(AllocationExpectationState.reallocDone, testAllocationOfReallyBigByteBuffer_state) + XCTAssertEqual(buf.capacity, Int(UInt32.max)) + } +} + +private enum AllocationExpectationState: Int { + case begin + case mallocDone + case reallocDone + case freeDone +} + +private var testAllocationOfReallyBigByteBuffer_state = AllocationExpectationState.begin +private func testAllocationOfReallyBigByteBuffer_freeHook(_ ptr: UnsafeMutableRawPointer) -> Void { + precondition(AllocationExpectationState.reallocDone == testAllocationOfReallyBigByteBuffer_state) + testAllocationOfReallyBigByteBuffer_state = .freeDone + /* free the pointer initially produced by malloc and then rebased by realloc offsetting it back */ + free(ptr.advanced(by: Int(Int32.max))) +} + +private func testAllocationOfReallyBigByteBuffer_mallocHook(_ size: Int) -> UnsafeMutableRawPointer! { + precondition(AllocationExpectationState.begin == testAllocationOfReallyBigByteBuffer_state) + testAllocationOfReallyBigByteBuffer_state = .mallocDone + /* return a 16 byte pointer here, good enough to write an integer in there */ + return malloc(16) +} + +private func testAllocationOfReallyBigByteBuffer_reallocHook(_ ptr: UnsafeMutableRawPointer, _ count: Int) -> UnsafeMutableRawPointer! { + precondition(AllocationExpectationState.mallocDone == testAllocationOfReallyBigByteBuffer_state) + testAllocationOfReallyBigByteBuffer_state = .reallocDone + /* rebase this pointer by -Int32.max so that the byte copy extending the ByteBuffer below will land at actual index 0 into this buffer ;) */ + return ptr.advanced(by: -Int(Int32.max)) +} + +private func testAllocationOfReallyBigByteBuffer_memcpyHook(_ dst: UnsafeMutableRawPointer, _ src: UnsafeRawPointer, _ count: Int) -> Void { + /* not actually doing any copies */ }