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 1533

Summary: SDL_Keycode value range allows segfaults with negative values
Product: SDL Reporter: Marcus von Appen <mva>
Component: eventsAssignee: Andreas Schiffler <aschiffler>
Status: RESOLVED FIXED QA Contact: Sam Lantinga <slouken>
Severity: normal    
Priority: P2 CC: aschiffler
Version: HG 2.0   
Hardware: All   
OS: All   
Attachments: SDL_GetKeyName() patch

Description Marcus von Appen 2012-07-03 01:48:20 UTC
Created attachment 893 [details]
SDL_GetKeyName() patch

SDL_Keycode is defined as Sint32, although the mapping tables for keycodes and scancodes indicate that there is no need to have negative keycode values.

The missing range definition can cause an index overflow in SDL_GetKeyName()/SDL_GetScancodeName(), when an improper (key & ~SDLK_SCANCODE_MASK) value is passed around.

Test program:

#include <SDL.h>
int main (int argc, char *argv[])
{
    SDL_Keycode val = -88; /* perfectly valid (technical) assignment */
    printf ("'%d'\n", ((SDL_Scancode)(val & ~SDLK_SCANCODE_MASK)));
    printf ("'%s'\n", SDL_GetKeyName (val));
    return 0;
}

Fixes:

1) redefine typedef Sint32 SDL_Keycode; to typedef Uint32 SDL_Keycode;
This will warn developers at compile time about improper value usage.
2) use the attached patch to do a proper range check for SDL_Scancode results in SDL_GetKeyName().
Comment 1 Andreas Schiffler 2013-03-08 22:48:42 UTC
Assigning to myself to fix and add test coverage.
Comment 2 Andreas Schiffler 2013-03-09 02:08:47 UTC
Added range checking and test cases.
http://hg.libsdl.org/SDL/rev/b72f56ab9867

Since ABI is locked, we don't want to change the typedef at this point.