Prevent crashes if freed objects are passed to SDL API functions

Instead of using the magic tag in the object, we'll actually keep track of valid objects

Fixes https://github.com/libsdl-org/SDL/issues/9869
Fixes https://github.com/libsdl-org/SDL/issues/9235
This commit is contained in:
Sam Lantinga 2024-06-03 04:09:28 -07:00
parent 57a15933cd
commit b0e93e4e63
28 changed files with 191 additions and 126 deletions

View file

@ -1000,19 +1000,17 @@ static const struct hidapi_backend LIBUSB_Backend = {
struct SDL_hid_device
{
const void *magic;
void *device;
const struct hidapi_backend *backend;
SDL_hid_device_info info;
};
static char device_magic;
#if defined(HAVE_PLATFORM_BACKEND) || defined(HAVE_DRIVER_BACKEND) || defined(HAVE_LIBUSB)
static SDL_hid_device *CreateHIDDeviceWrapper(void *device, const struct hidapi_backend *backend)
{
SDL_hid_device *wrapper = (SDL_hid_device *)SDL_malloc(sizeof(*wrapper));
wrapper->magic = &device_magic;
SDL_SetObjectValid(wrapper, SDL_OBJECT_TYPE_HIDAPI_DEVICE, SDL_TRUE);
wrapper->device = device;
wrapper->backend = backend;
SDL_zero(wrapper->info);
@ -1021,20 +1019,20 @@ static SDL_hid_device *CreateHIDDeviceWrapper(void *device, const struct hidapi_
#endif /* HAVE_PLATFORM_BACKEND || HAVE_DRIVER_BACKEND || HAVE_LIBUSB */
static void DeleteHIDDeviceWrapper(SDL_hid_device *device)
static void DeleteHIDDeviceWrapper(SDL_hid_device *wrapper)
{
device->magic = NULL;
SDL_free(device->info.path);
SDL_free(device->info.serial_number);
SDL_free(device->info.manufacturer_string);
SDL_free(device->info.product_string);
SDL_free(device);
SDL_SetObjectValid(wrapper, SDL_OBJECT_TYPE_HIDAPI_DEVICE, SDL_FALSE);
SDL_free(wrapper->info.path);
SDL_free(wrapper->info.serial_number);
SDL_free(wrapper->info.manufacturer_string);
SDL_free(wrapper->info.product_string);
SDL_free(wrapper);
}
#define CHECK_DEVICE_MAGIC(device, retval) \
if (!device || device->magic != &device_magic) { \
SDL_SetError("Invalid device"); \
return retval; \
#define CHECK_DEVICE_MAGIC(device, retval) \
if (!SDL_ObjectValid(device, SDL_OBJECT_TYPE_HIDAPI_DEVICE)) { \
SDL_SetError("Invalid device"); \
return retval; \
}
#define COPY_IF_EXISTS(var) \