Crash in darwin/SDL_sysjoystick.c when unplugging controller


I think I found a bug in the OSX joystick code. It reliably crashes when unplugging a controller while my game is running - in this particular case I’m using a wired Xbox 360 controller with the driver on an Early 2013 15" Retina Macbook Pro. This is with SDL2 from the mercurial repository.

The bug is a use-after free and looks like it has to do with the order of event processing. The device gets remove and freed, but there is still one event left in the queue and it crashes while processing that event. Screenshot with stack trace at crash point in SDL_SYS_JoystickUpdate:

I was able to work around the bug by leaking memory:

diff -r e29fec41a2c6 src/joystick/darwin/SDL_sysjoystick.c
— a/src/joystick/darwin/SDL_sysjoystick.c Tue Feb 03 21:22:25 2015 +0100
+++ b/src/joystick/darwin/SDL_sysjoystick.c Sun Feb 08 07:51:18 2015 -0800
@@ -93,7 +93,8 @@

  •    SDL_free(removeDevice);
  •    removeDevice->removed = 1;
  •    //SDL_free(removeDevice);
    return pDeviceNext;