apple / swift-nio

Event-driven network application framework for high performance protocol servers & clients, non-blocking.
https://swiftpackageindex.com/apple/swift-nio/documentation
Apache License 2.0
7.85k stars 633 forks source link

Forceful unwrapping of bytes in NIOCore #2738

Closed RohiniK28 closed 3 weeks ago

RohiniK28 commented 3 weeks ago

Actual behavior

The App can be crashed because of using forceful unwrapping of optional value.

Steps to reproduce

While creating a buffer, forceful unwrapping is done that is causing a crash.

static func _allocateAndPrepareRawMemory(bytes: _Capacity, allocator: Allocator) -> UnsafeMutableRawPointer {

        let ptr = allocator.malloc(size_t(bytes))! // forceful unwrapping

        /* bind the memory so we can assume it elsewhere to be bound to UInt8 */
        ptr.bindMemory(to: UInt8.self, capacity: Int(bytes))
        return ptr
    }

Is there any possible reason behind forcefully unwrapping it. From what i know, forceful unwrapping is not a good approach to handle as it might cause app crash. Kindly let me know the inputs.

Lukasa commented 3 weeks ago

We force-unwrap on malloc failure because there is no recovery. Swift does not support running in environments where malloc might fail, and we inherit that restriction. There is no point continuing in this case.