We are currently migrating Bugzilla to GitHub issues.
Any changes made to the bug tracker now will be lost, so please do not post new bugs or make changes to them.
When we're done, all bug URLs will redirect to their equivalent location on the new bug tracker.

Bug 5276

Summary: [PATCH] Race condition may cause invalid joystick index in SDL_JOYDEVICEADDED event
Product: SDL Reporter: Cameron Gutman <cameron.gutman>
Component: joystickAssignee: Sam Lantinga <slouken>
Status: RESOLVED FIXED QA Contact: Sam Lantinga <slouken>
Severity: normal    
Priority: P2 CC: sezeroz
Version: HG 2.0Keywords: target-2.0.14
Hardware: x86   
OS: Windows 10   
Attachments: Patch

Description Cameron Gutman 2020-08-29 23:51:45 UTC
In the joystick and gamecontroller code, we attempt to fixup SDL_JOYDEVICEADDED/SDL_CONTROLLERDEVICEADDED events if a device is removed prior to the add event being processed by the SDL application.

    num_events = SDL_PeepEvents(events, num_events, SDL_GETEVENT, SDL_JOYDEVICEADDED, SDL_JOYDEVICEADDED);
    for (i = 0; i < num_events; ++i) {
        --events[i].jdevice.which;
    }
    SDL_PeepEvents(events, num_events, SDL_ADDEVENT, 0, 0);

However, there are a couple problems with this fixup logic:
- SDL_JOYDEVICEADDED for joysticks with indexes *lower* than the one removed should not be adjusted
- SDL_JOYDEVICEADDED for the joystick being removed must be removed completely

Due to the above issues, it's possible for SDL applications to receive an invalid device index in their SDL_JOYDEVICEADDED and SDL_CONTROLLERDEVICEADDED events if they aren't pumping events frequently and a joystick is added and removed before they process SDL_JOYDEVICEADDED.
Comment 1 Cameron Gutman 2020-08-29 23:52:25 UTC
Created attachment 4454 [details]
Patch
Comment 2 Sam Lantinga 2020-12-01 22:49:52 UTC
Fixed, thanks!
https://hg.libsdl.org/SDL/rev/8d5e22789f3f