distatus / battery

cross-platform, normalized battery information library
MIT License
249 stars 36 forks source link

Possible panic on x86 systems #20

Closed AlexT2594 closed 2 years ago

AlexT2594 commented 3 years ago

https://github.com/distatus/battery/blob/master/battery_windows.go#L197 could cause a panic on x86 systems. This happens because, if cbRequired < 3, then cbRequired/2-1 will be a negative value, which for a uint will cause wrapping to happen. An x64 system will be able to allocate enough memory, but not an x86 system.

Thus I suggest changing didd := make([]uint16, cbRequired/2-1) to didd := make([]uint16, cbRequired/2).

Another reason for this change is because

    errno = setupDiCall(
        setupDiGetDeviceInterfaceDetailW,
        6,
        hdev,
        uintptr(unsafe.Pointer(&did)),
        uintptr(unsafe.Pointer(&didd[0])),
        uintptr(cbRequired),
        uintptr(unsafe.Pointer(&cbRequired)),
        0,
    )

is called, where we inform the call that cbRequired bytes can be written, but the memory allocated is less than that. The null terminator is still written and used subsequently, but the above behavior is not correct.