adafruit / Adafruit_CircuitPython_HID

USB Human Interface Device drivers.
MIT License
373 stars 105 forks source link

Use proper signed/unsigned designations in `struct` format strings #30

Closed dhalbert closed 5 years ago

dhalbert commented 5 years ago

from @ATMakersBill (part of https://github.com/adafruit/circuitpython/issues/1451)

As we were trying to track down a problem w/the gamepad HID interface (or more likely the Microsoft XAC's implementation) @dhalbert and I saw that the format strings for pack_into() were not taking into consideration whether the variable was signed. For example in gamepad.py you'll find:

    struct.pack_into('<HBBBB', self._report, 0,
                     self._buttons_state,
                     self._joy_x, self._joy_y,
                     self._joy_z, self._joy_r_z)

The "<HBBBB" string says that it's expecting an unsigned 16-bit value followed by four unsigned bytes. However, we are sending signed bytes (-127 through 127) as defined in our descriptor.

In this case, circruitpython doesn't care because it would encode them the same way. However, CPython would error out after checking this and in general this is dangerous, because with types > 8 bit, we very much do care about endianness.

@dhalbert asked that I open an issue about this. The fix on gamepad.py is pretty simple, just change the string to "<Hbbbb", however, we should probably do a sanity check on this.