diff --git a/tools/linuxfs/preload/inputudev.c b/tools/linuxfs/preload/inputudev.c index d33a0adaac..823614bfd3 100644 --- a/tools/linuxfs/preload/inputudev.c +++ b/tools/linuxfs/preload/inputudev.c @@ -4,15 +4,20 @@ #define _GNU_SOURCE #include +#include #include #include #include +#include +#include +#include #include #include #include #include #include #include +#include #define RING_MAX 4 #define UINPUT_BASE 16 @@ -29,17 +34,43 @@ "NAME=\"Xbox 360 Controller (%d)\"\n" \ "PHYS=\"usb-fakeinput/input%d\"\n" +#define PARENT_NAME "droiddeck-input" +#define PARENT_SYSPATH_FORMAT "/sys/devices/droiddeck%d/" PARENT_NAME "%d" +#define EVENT_SYSPATH_FORMAT PARENT_SYSPATH_FORMAT "/event%d" + struct pad { - char syspath[64]; + char syspath[80]; char devnode[32]; - char sysname[16]; + char sysname[24]; char uevent[256]; dev_t devnum; + int node; + int parent; + int live; }; static struct pad pads[PAD_MAX]; +static struct pad parents[PAD_MAX]; static int pad_count; static pthread_mutex_t virtual_lock = PTHREAD_MUTEX_INITIALIZER; +static pthread_mutex_t enumerate_lock = PTHREAD_MUTEX_INITIALIZER; + +/* The event device's parent has to answer as a separate device so that its syspath differs from + * the child's: consumers compare parent syspaths to tell gamepads apart. */ +static void make_parent(int node, const struct pad *pad, struct pad *parent) { + snprintf(parent->syspath, sizeof(parent->syspath), PARENT_SYSPATH_FORMAT, node, node); + snprintf(parent->sysname, sizeof(parent->sysname), PARENT_NAME "%d", node); + parent->devnode[0] = '\0'; + memcpy(parent->uevent, pad->uevent, sizeof(parent->uevent)); + parent->devnum = makedev(0, 0); + parent->node = node; + parent->parent = 1; + parent->live = pad->live; +} + +static void sync_parent(int node) { + make_parent(node, &pads[node], &parents[node]); +} static void discover_pads(void) { const char *spec = getenv("FAKE_EVDEV_MEMFD_PATHS"); @@ -55,12 +86,15 @@ static void discover_pads(void) { if (pad->devnode[0] == '\0') { snprintf(pad->sysname, sizeof(pad->sysname), "event%ld", slot); - snprintf(pad->syspath, sizeof(pad->syspath), "/sys/devices/virtual/input/droiddeck%ld", - slot); + snprintf(pad->syspath, sizeof(pad->syspath), EVENT_SYSPATH_FORMAT, (int)slot, (int)slot, + (int)slot); snprintf(pad->devnode, sizeof(pad->devnode), "/dev/input/event%ld", slot); snprintf(pad->uevent, sizeof(pad->uevent), PAD_UEVENT_FORMAT, (int)slot, (int)slot); pad->devnum = makedev(13, EVENT_MINOR_BASE + (unsigned int)slot); + pad->node = (int)slot; + pad->live = 1; if (slot >= pad_count) pad_count = (int)slot + 1; + sync_parent((int)slot); } } entry = strchr(entry, ';'); @@ -103,70 +137,304 @@ static int any_virtual_pad(void) { return 0; } -static void refresh_pad(int node) { - struct pad *pad; +static void refresh_locked(int node) { + struct pad *pad = &pads[node]; - if (node < 0 || node >= PAD_MAX) return; - pad = &pads[node]; - pthread_mutex_lock(&virtual_lock); if (node >= UINPUT_BASE) { char uevent[sizeof(pad->uevent)]; if (read_virtual_uevent(node, uevent, sizeof(uevent))) { snprintf(pad->sysname, sizeof(pad->sysname), "event%d", node); - snprintf(pad->syspath, sizeof(pad->syspath), "/sys/devices/virtual/input/droiddeck%d", node); + snprintf(pad->syspath, sizeof(pad->syspath), EVENT_SYSPATH_FORMAT, node, node, node); memcpy(pad->uevent, uevent, sizeof(uevent)); pad->devnum = makedev(13, EVENT_MINOR_BASE + (unsigned int)node); snprintf(pad->devnode, sizeof(pad->devnode), "/dev/input/event%d", node); + pad->node = node; + pad->live = 1; if (node >= pad_count) pad_count = node + 1; } else { pad->devnode[0] = '\0'; + pad->live = 0; + } + } else if (pad->sysname[0] != '\0') { + char path[PATH_MAX]; + const char *dir = getenv("FAKE_EVDEV_DIR"); + + if (dir == NULL || snprintf(path, sizeof(path), "%s/event%d", dir, node) >= (int)sizeof(path) || + access(path, F_OK) != 0) { + pad->devnode[0] = '\0'; + pad->live = 0; + } else { + snprintf(pad->devnode, sizeof(pad->devnode), "/dev/input/event%d", node); + pad->live = 1; + if (uinput_enabled()) + snprintf(pad->uevent, sizeof(pad->uevent), + any_virtual_pad() ? PAD_PHYSICAL_UEVENT_FORMAT : PAD_UEVENT_FORMAT, node, node); } - } else if (pad->devnode[0] != '\0' && uinput_enabled()) { - snprintf(pad->uevent, sizeof(pad->uevent), - any_virtual_pad() ? PAD_PHYSICAL_UEVENT_FORMAT : PAD_UEVENT_FORMAT, node, node); } - pthread_mutex_unlock(&virtual_lock); + sync_parent(node); } -static struct pad *pad_for_syspath(const char *syspath) { +static int snapshot_pad(int node, int parent, struct pad *out) { + int found; + + if (node < 0 || node >= PAD_MAX) return 0; + ensure_pads(); + pthread_mutex_lock(&virtual_lock); + refresh_locked(node); + found = parent ? parents[node].live : pads[node].devnode[0] != '\0'; + if (found) *out = parent ? parents[node] : pads[node]; + pthread_mutex_unlock(&virtual_lock); + return found; +} + +static int parse_number(const char **cursor) { + int value = 0; + + if (**cursor < '0' || **cursor > '9') return -1; + while (**cursor >= '0' && **cursor <= '9') { + if (value < PAD_MAX) value = value * 10 + (*(*cursor) - '0'); + (*cursor)++; + } + return value; +} + +static int match_numbered(const char **cursor, const char *literal, int node) { + char expected[32]; + int length = snprintf(expected, sizeof(expected), "%s%d", literal, node); + + if (strncmp(*cursor, expected, (size_t)length) != 0) return 0; + *cursor += length; + return 1; +} + +/* Returns the pad node behind one of our syspaths, -1 for anything else. */ +static int node_from_syspath(const char *syspath, int *child) { + static const char virtual_prefix[] = "/sys/devices/virtual/input/droiddeck"; + static const char child_prefix[] = "/sys/devices/droiddeck"; + const char *cursor; + int node; + + if (syspath == NULL) return -1; + if (strncmp(syspath, virtual_prefix, sizeof(virtual_prefix) - 1) == 0) { + cursor = syspath + sizeof(virtual_prefix) - 1; + *child = 0; + } else if (strncmp(syspath, child_prefix, sizeof(child_prefix) - 1) == 0) { + cursor = syspath + sizeof(child_prefix) - 1; + *child = 1; + } else { + return -1; + } + node = parse_number(&cursor); + if (node < 0 || node >= PAD_MAX) return -1; + if (!*child) { + if (*cursor == '\0') return node; + return match_numbered(&cursor, "/event", node) && *cursor == '\0' ? node : -1; + } + if (!match_numbered(&cursor, "/" PARENT_NAME, node)) return -1; + if (*cursor == '\0') return node; + if (!match_numbered(&cursor, "/event", node) || *cursor != '\0') return -1; + *child = 0; + return node; +} + +static int syspath_pad(const char *syspath, struct pad *out) { + int child = 0; + int node = node_from_syspath(syspath, &child); + + return node >= 0 && snapshot_pad(node, child, out); +} + +static int sysname_pad(const char *sysname, struct pad *out) { + static const char parent_name[] = PARENT_NAME; + const char *cursor; + int parent; + int node; + + if (strncmp(sysname, "event", 5) == 0) { + cursor = sysname + 5; + parent = 0; + } else if (strncmp(sysname, parent_name, sizeof(parent_name) - 1) == 0) { + cursor = sysname + sizeof(parent_name) - 1; + parent = 1; + } else { + return 0; + } + node = parse_number(&cursor); + return node >= 0 && *cursor == '\0' && snapshot_pad(node, parent, out); +} + +/* Each construction hands out its own handle bound to the context that built it, so one consumer + * releasing its libudev context can never leave another consumer's device with a dangling one. */ +#define HANDLE_MAX 256 + +static const char *const property_keys[] = {"DEVNAME", "DEVPATH", "ID_INPUT", "ID_INPUT_JOYSTICK"}; + +#define PROPERTY_COUNT (sizeof(property_keys) / sizeof(property_keys[0])) + +struct handle { + struct pad info; + void *udev; + struct handle *parent; + int refs; + char properties[PROPERTY_COUNT]; +}; + +static struct handle handles[HANDLE_MAX]; +static pthread_mutex_t handle_lock = PTHREAD_MUTEX_INITIALIZER; + +static struct handle *live_handle(void *device) { + uintptr_t offset = (uintptr_t)device - (uintptr_t)handles; + struct handle *handle; + + if (offset >= sizeof(handles) || offset % sizeof(handles[0]) != 0) return NULL; + handle = &handles[offset / sizeof(handles[0])]; + return handle->refs > 0 ? handle : NULL; +} + +static struct handle *claim_slot(const struct pad *info, void *udev) { int i; - if (syspath == NULL) return NULL; - ensure_pads(); - for (i = 0; i < pad_count; i++) { - if (pads[i].devnode[0] != '\0' && strcmp(pads[i].syspath, syspath) == 0) return &pads[i]; + for (i = 0; i < HANDLE_MAX; i++) { + if (handles[i].refs == 0) { + handles[i].refs = 1; + handles[i].info = *info; + handles[i].udev = udev; + handles[i].parent = NULL; + return &handles[i]; + } } return NULL; } -static struct pad *pad_for_device(void *device) { - int i; +static void *claim_handle(const struct pad *info, void *udev) { + struct handle *handle; + + pthread_mutex_lock(&handle_lock); + handle = claim_slot(info, udev); + pthread_mutex_unlock(&handle_lock); + return handle; +} + +static int retain_handle(void *device) { + struct handle *handle; + + pthread_mutex_lock(&handle_lock); + handle = live_handle(device); + if (handle != NULL) handle->refs++; + pthread_mutex_unlock(&handle_lock); + return handle != NULL; +} + +static int release_handle(void *device) { + struct handle *handle; + int found; + + pthread_mutex_lock(&handle_lock); + handle = live_handle(device); + found = handle != NULL; + while (handle != NULL && --handle->refs == 0) { + struct handle *parent = handle->parent; + + handle->parent = NULL; + handle = parent; + } + pthread_mutex_unlock(&handle_lock); + return found; +} + +static struct handle *device_handle(void *device) { + struct handle *handle; if (device == NULL) return NULL; - ensure_pads(); - for (i = 0; i < pad_count; i++) { - if (&pads[i] == device) return pads[i].devnode[0] != '\0' ? &pads[i] : NULL; + pthread_mutex_lock(&handle_lock); + handle = live_handle(device); + pthread_mutex_unlock(&handle_lock); + return handle; +} + +static struct pad *device_pad(void *device) { + struct handle *handle = device_handle(device); + + return handle != NULL ? &handle->info : NULL; +} + +/* The parent belongs to the child that handed it out and goes away with it, as in libudev. */ +static void *parent_device(void *device, struct pad *pad) { + struct handle *handle; + struct handle *parent = NULL; + struct pad info; + + if (pad->parent) return NULL; + make_parent(pad->node, pad, &info); + pthread_mutex_lock(&handle_lock); + handle = live_handle(device); + if (handle != NULL) { + if (handle->parent == NULL) handle->parent = claim_slot(&info, handle->udev); + parent = handle->parent; } + pthread_mutex_unlock(&handle_lock); + return parent; +} + +static const char *pad_property(const struct pad *pad, const char *key) { + if (key == NULL) return NULL; + if (strcmp(key, "ID_INPUT") == 0 || strcmp(key, "ID_INPUT_JOYSTICK") == 0) return "1"; + if (strcmp(key, "DEVNAME") == 0) return !pad->parent && pad->devnode[0] != '\0' ? pad->devnode : NULL; + if (strcmp(key, "DEVPATH") == 0) return pad->syspath + 4; return NULL; } -static struct pad *pad_for_syslink(const char *path) { +static struct handle *property_handle(void *entry, size_t *index) { + uintptr_t offset = (uintptr_t)entry - (uintptr_t)handles; + size_t within; + + if (offset >= sizeof(handles)) return NULL; + within = offset % sizeof(handles[0]); + if (within < offsetof(struct handle, properties) || + within >= offsetof(struct handle, properties) + PROPERTY_COUNT) + return NULL; + *index = within - offsetof(struct handle, properties); + return &handles[offset / sizeof(handles[0])]; +} + +static void *next_property(struct handle *handle, size_t from) { + size_t i; + + for (i = from; i < PROPERTY_COUNT; i++) + if (pad_property(&handle->info, property_keys[i]) != NULL) return &handle->properties[i]; + return NULL; +} + +static int syslink_pad(const char *path, struct pad *out) { static const char prefix[] = "/sys/class/input/"; - const char *name; - int i; - if (path == NULL || strncmp(path, prefix, sizeof(prefix) - 1) != 0) return NULL; - name = path + sizeof(prefix) - 1; - ensure_pads(); - if (strncmp(name, "event", 5) == 0 && name[5] >= '0' && name[5] <= '9') refresh_pad(atoi(name + 5)); - for (i = 0; i < pad_count; i++) { - if (pads[i].devnode[0] != '\0' && strcmp(pads[i].sysname, name) == 0) return &pads[i]; - } - return NULL; + if (path == NULL || strncmp(path, prefix, sizeof(prefix) - 1) != 0) return 0; + return sysname_pad(path + sizeof(prefix) - 1, out); } -static void *next_symbol(const char *name) { return dlsym(RTLD_NEXT, name); } +static void *real_dlsym(void); + +/* libudev is often opened with RTLD_LOCAL, which keeps it out of the global scope that RTLD_NEXT + * searches, so the handle the program opened is the only way back to the real implementation. */ +static _Atomic(void *) udev_handle; + +__attribute__((visibility("hidden"))) void bl_inputudev_note_dlopen(const char *path, void *handle) { + if (handle != NULL && path != NULL && strstr(path, "libudev") != NULL) + atomic_store_explicit(&udev_handle, handle, memory_order_release); +} + +static void *next_symbol(const char *name) { + void *(*forward)(void *, const char *) = real_dlsym(); + void *symbol; + + if (forward == NULL) return NULL; + if (strncmp(name, "udev_", 5) == 0) { + symbol = atomic_load_explicit(&udev_handle, memory_order_acquire); + if (symbol != NULL && (symbol = forward(symbol, name)) != NULL) return symbol; + } + return forward(RTLD_NEXT, name); +} char *dd_cached_realpath(const char *path, char *resolved, char *(*real)(const char *, char *)) __attribute__((visibility("hidden"))); @@ -194,12 +462,11 @@ __attribute__((visibility("hidden"))) int dd_winebus_rumble_ioctl(int (*real)(in char *realpath(const char *path, char *resolved) { static char *(*real_realpath)(const char *, char *); - void *caller = __builtin_return_address(0); - struct pad *pad = caller_is_winebus(caller) ? pad_for_syslink(path) : NULL; + struct pad pad; - if (pad != NULL) { - if (resolved == NULL) return strdup(pad->syspath); - memcpy(resolved, pad->syspath, strlen(pad->syspath) + 1); + if (syslink_pad(path, &pad)) { + if (resolved == NULL) return strdup(pad.syspath); + memcpy(resolved, pad.syspath, strlen(pad.syspath) + 1); return resolved; } if (real_realpath == NULL) real_realpath = next_symbol("realpath"); @@ -209,10 +476,9 @@ char *realpath(const char *path, char *resolved) { void *udev_device_new_from_syspath(void *udev, const char *syspath) { static void *(*real_new)(void *, const char *); - void *caller = __builtin_return_address(0); - struct pad *pad = caller_is_winebus(caller) ? pad_for_syspath(syspath) : NULL; + struct pad pad; - if (pad != NULL) return pad; + if (syspath_pad(syspath, &pad)) return claim_handle(&pad, udev); if (real_new == NULL) real_new = next_symbol("udev_device_new_from_syspath"); if (real_new == NULL) return NULL; return real_new(udev, syspath); @@ -221,7 +487,7 @@ void *udev_device_new_from_syspath(void *udev, const char *syspath) { void *udev_device_ref(void *device) { static void *(*real_ref)(void *); - if (pad_for_device(device) != NULL) return device; + if (retain_handle(device)) return device; if (real_ref == NULL) real_ref = next_symbol("udev_device_ref"); if (real_ref == NULL) return NULL; return real_ref(device); @@ -230,7 +496,7 @@ void *udev_device_ref(void *device) { void *udev_device_unref(void *device) { static void *(*real_unref)(void *); - if (pad_for_device(device) != NULL) return NULL; + if (release_handle(device)) return NULL; if (real_unref == NULL) real_unref = next_symbol("udev_device_unref"); if (real_unref == NULL) return NULL; return real_unref(device); @@ -238,9 +504,9 @@ void *udev_device_unref(void *device) { const char *udev_device_get_devnode(void *device) { static const char *(*real_get)(void *); - struct pad *pad = pad_for_device(device); + struct pad *pad = device_pad(device); - if (pad != NULL) return pad->devnode; + if (pad != NULL) return pad->parent || pad->devnode[0] == '\0' ? NULL : pad->devnode; if (real_get == NULL) real_get = next_symbol("udev_device_get_devnode"); if (real_get == NULL) return NULL; return real_get(device); @@ -248,7 +514,7 @@ const char *udev_device_get_devnode(void *device) { const char *udev_device_get_syspath(void *device) { static const char *(*real_get)(void *); - struct pad *pad = pad_for_device(device); + struct pad *pad = device_pad(device); if (pad != NULL) return pad->syspath; if (real_get == NULL) real_get = next_symbol("udev_device_get_syspath"); @@ -256,9 +522,19 @@ const char *udev_device_get_syspath(void *device) { return real_get(device); } +const char *udev_device_get_devpath(void *device) { + static const char *(*real_get)(void *); + struct pad *pad = device_pad(device); + + if (pad != NULL) return pad->syspath + 4; + if (real_get == NULL) real_get = next_symbol("udev_device_get_devpath"); + if (real_get == NULL) return NULL; + return real_get(device); +} + const char *udev_device_get_sysname(void *device) { static const char *(*real_get)(void *); - struct pad *pad = pad_for_device(device); + struct pad *pad = device_pad(device); if (pad != NULL) return pad->sysname; if (real_get == NULL) real_get = next_symbol("udev_device_get_sysname"); @@ -266,9 +542,19 @@ const char *udev_device_get_sysname(void *device) { return real_get(device); } +const char *udev_device_get_sysnum(void *device) { + static const char *(*real_get)(void *); + struct pad *pad = device_pad(device); + + if (pad != NULL) return pad->sysname + strcspn(pad->sysname, "0123456789"); + if (real_get == NULL) real_get = next_symbol("udev_device_get_sysnum"); + if (real_get == NULL) return NULL; + return real_get(device); +} + const char *udev_device_get_subsystem(void *device) { static const char *(*real_get)(void *); - struct pad *pad = pad_for_device(device); + struct pad *pad = device_pad(device); if (pad != NULL) return "input"; if (real_get == NULL) real_get = next_symbol("udev_device_get_subsystem"); @@ -278,7 +564,7 @@ const char *udev_device_get_subsystem(void *device) { const char *udev_device_get_devtype(void *device) { static const char *(*real_get)(void *); - struct pad *pad = pad_for_device(device); + struct pad *pad = device_pad(device); if (pad != NULL) return NULL; if (real_get == NULL) real_get = next_symbol("udev_device_get_devtype"); @@ -288,7 +574,7 @@ const char *udev_device_get_devtype(void *device) { const char *udev_device_get_action(void *device) { static const char *(*real_get)(void *); - struct pad *pad = pad_for_device(device); + struct pad *pad = device_pad(device); if (pad != NULL) return NULL; if (real_get == NULL) real_get = next_symbol("udev_device_get_action"); @@ -298,7 +584,7 @@ const char *udev_device_get_action(void *device) { dev_t udev_device_get_devnum(void *device) { static dev_t (*real_get)(void *); - struct pad *pad = pad_for_device(device); + struct pad *pad = device_pad(device); if (pad != NULL) return pad->devnum; if (real_get == NULL) real_get = next_symbol("udev_device_get_devnum"); @@ -306,13 +592,31 @@ dev_t udev_device_get_devnum(void *device) { return real_get(device); } +void *udev_device_get_udev(void *device) { + static void *(*real_get)(void *); + struct handle *handle = device_handle(device); + + if (handle != NULL) return handle->udev; + if (real_get == NULL) real_get = next_symbol("udev_device_get_udev"); + return real_get != NULL ? real_get(device) : NULL; +} + +int udev_device_get_is_initialized(void *device) { + static int (*real_get)(void *); + + if (device_pad(device) != NULL) return 1; + if (real_get == NULL) real_get = next_symbol("udev_device_get_is_initialized"); + return real_get != NULL ? real_get(device) : 0; +} + void *udev_device_get_parent_with_subsystem_devtype(void *device, const char *subsystem, const char *devtype) { static void *(*real_get)(void *, const char *, const char *); - struct pad *pad = pad_for_device(device); + struct pad *pad = device_pad(device); if (pad != NULL) { - if (subsystem != NULL && strcmp(subsystem, "input") == 0 && devtype == NULL) return pad; + if (subsystem != NULL && strcmp(subsystem, "input") == 0 && devtype == NULL) + return parent_device(device, pad); return NULL; } if (real_get == NULL) real_get = next_symbol("udev_device_get_parent_with_subsystem_devtype"); @@ -322,7 +626,7 @@ void *udev_device_get_parent_with_subsystem_devtype(void *device, const char *su const char *udev_device_get_sysattr_value(void *device, const char *attr) { static const char *(*real_get)(void *, const char *); - struct pad *pad = pad_for_device(device); + struct pad *pad = device_pad(device); if (pad != NULL) return attr != NULL && strcmp(attr, "uevent") == 0 ? pad->uevent : NULL; if (real_get == NULL) real_get = next_symbol("udev_device_get_sysattr_value"); @@ -332,10 +636,567 @@ const char *udev_device_get_sysattr_value(void *device, const char *attr) { const char *udev_device_get_property_value(void *device, const char *key) { static const char *(*real_get)(void *, const char *); - struct pad *pad = pad_for_device(device); + struct pad *pad = device_pad(device); - if (pad != NULL) return key != NULL && strcmp(key, "ID_INPUT_JOYSTICK") == 0 ? "1" : NULL; + if (pad != NULL) return pad_property(pad, key); if (real_get == NULL) real_get = next_symbol("udev_device_get_property_value"); if (real_get == NULL) return NULL; return real_get(device, key); } + +void *udev_device_get_parent(void *device) { + static void *(*real_get)(void *); + struct pad *pad = device_pad(device); + + if (pad != NULL) return parent_device(device, pad); + if (real_get == NULL) real_get = next_symbol("udev_device_get_parent"); + return real_get != NULL ? real_get(device) : NULL; +} + +int udev_device_has_tag(void *device, const char *tag) { + static int (*real_has)(void *, const char *); + + if (device_pad(device) != NULL) return 0; + if (real_has == NULL) real_has = next_symbol("udev_device_has_tag"); + return real_has != NULL ? real_has(device, tag) : 0; +} + +void *udev_device_get_properties_list_entry(void *device) { + static void *(*real_get)(void *); + struct handle *handle = device_handle(device); + + if (handle != NULL) return next_property(handle, 0); + if (real_get == NULL) real_get = next_symbol("udev_device_get_properties_list_entry"); + return real_get != NULL ? real_get(device) : NULL; +} + +void *udev_device_get_tags_list_entry(void *device) { + static void *(*real_get)(void *); + + if (device_pad(device) != NULL) return NULL; + if (real_get == NULL) real_get = next_symbol("udev_device_get_tags_list_entry"); + return real_get != NULL ? real_get(device) : NULL; +} + +void *udev_device_get_sysattr_list_entry(void *device) { + static void *(*real_get)(void *); + + if (device_pad(device) != NULL) return NULL; + if (real_get == NULL) real_get = next_symbol("udev_device_get_sysattr_list_entry"); + return real_get != NULL ? real_get(device) : NULL; +} + +void *udev_device_new_from_devnum(void *udev, char type, dev_t devnum) { + static void *(*real_new)(void *, char, dev_t); + struct pad pad; + int node; + + for (node = 0; node < PAD_MAX; node++) + if (snapshot_pad(node, 0, &pad) && pad.devnum == devnum) return claim_handle(&pad, udev); + if (real_new == NULL) real_new = next_symbol("udev_device_new_from_devnum"); + return real_new != NULL ? real_new(udev, type, devnum) : NULL; +} + +void *udev_device_new_from_subsystem_sysname(void *udev, const char *subsystem, const char *sysname) { + static void *(*real_new)(void *, const char *, const char *); + struct pad pad; + + if (subsystem != NULL && sysname != NULL && strcmp(subsystem, "input") == 0 && sysname_pad(sysname, &pad)) + return claim_handle(&pad, udev); + if (real_new == NULL) real_new = next_symbol("udev_device_new_from_subsystem_sysname"); + return real_new != NULL ? real_new(udev, subsystem, sysname) : NULL; +} + +#define ENTRY_MAX (PAD_MAX * 2) + +struct enumerate { + struct enumerate *next; + void *real; + void *real_head; + int matched; + int filtered; + int parent_node; + int real_parent; + int real_listed; + int scanned; + int refs; + char names[ENTRY_MAX][sizeof(pads[0].syspath)]; +}; + +static struct enumerate *enumerates; + +static struct enumerate *entry_state(void *entry, int *slot) { + struct enumerate *state; + + pthread_mutex_lock(&enumerate_lock); + for (state = enumerates; state != NULL; state = state->next) { + uintptr_t offset = (uintptr_t)entry - (uintptr_t)state->names; + + if (offset < sizeof(state->names) && offset % sizeof(state->names[0]) == 0) { + *slot = (int)(offset / sizeof(state->names[0])); + break; + } + } + pthread_mutex_unlock(&enumerate_lock); + return state; +} + +static struct enumerate *enumerate_state(void *enumerate) { + struct enumerate *state; + + pthread_mutex_lock(&enumerate_lock); + for (state = enumerates; state != NULL && state->real != enumerate; state = state->next) { + } + pthread_mutex_unlock(&enumerate_lock); + return state; +} + +void *udev_enumerate_new(void *udev) { + static void *(*real_new)(void *); + void *enumerate; + struct enumerate *state; + + if (real_new == NULL) real_new = next_symbol("udev_enumerate_new"); + if (real_new == NULL) return NULL; + enumerate = real_new(udev); + if (enumerate == NULL) return NULL; + state = calloc(1, sizeof(*state)); + if (state == NULL) return enumerate; + state->real = enumerate; + state->parent_node = -1; + state->refs = 1; + pthread_mutex_lock(&enumerate_lock); + state->next = enumerates; + enumerates = state; + pthread_mutex_unlock(&enumerate_lock); + return enumerate; +} + +void *udev_enumerate_ref(void *enumerate) { + static void *(*real_ref)(void *); + struct enumerate *state = enumerate_state(enumerate); + + if (state != NULL) { + pthread_mutex_lock(&enumerate_lock); + state->refs++; + pthread_mutex_unlock(&enumerate_lock); + } + if (real_ref == NULL) real_ref = next_symbol("udev_enumerate_ref"); + return real_ref != NULL ? real_ref(enumerate) : enumerate; +} + +void *udev_enumerate_unref(void *enumerate) { + static void *(*real_unref)(void *); + struct enumerate *state = enumerate_state(enumerate); + + if (state != NULL) { + pthread_mutex_lock(&enumerate_lock); + if (--state->refs <= 0) { + struct enumerate **link; + + for (link = &enumerates; *link != NULL && *link != state; link = &(*link)->next) { + } + if (*link != NULL) *link = state->next; + } else { + state = NULL; + } + pthread_mutex_unlock(&enumerate_lock); + free(state); + } + if (real_unref == NULL) real_unref = next_symbol("udev_enumerate_unref"); + return real_unref != NULL ? real_unref(enumerate) : NULL; +} + +int udev_enumerate_add_match_subsystem(void *enumerate, const char *subsystem) { + static int (*real_add)(void *, const char *); + struct enumerate *state = enumerate_state(enumerate); + int rc; + + if (real_add == NULL) real_add = next_symbol("udev_enumerate_add_match_subsystem"); + rc = real_add != NULL ? real_add(enumerate, subsystem) : 0; + if (rc == 0 && state != NULL && subsystem != NULL) { + pthread_mutex_lock(&enumerate_lock); + state->filtered = 1; + state->matched = state->matched || strcmp(subsystem, "input") == 0; + pthread_mutex_unlock(&enumerate_lock); + } + return rc; +} + +int udev_enumerate_add_match_parent(void *enumerate, void *parent) { + static int (*real_add)(void *, void *); + struct enumerate *state = enumerate_state(enumerate); + struct pad *pad = device_pad(parent); + int rc; + + if (pad != NULL) { + if (state == NULL) return -EINVAL; + pthread_mutex_lock(&enumerate_lock); + state->parent_node = pad->node; + state->real_parent = 0; + pthread_mutex_unlock(&enumerate_lock); + return 0; + } + if (real_add == NULL) real_add = next_symbol("udev_enumerate_add_match_parent"); + rc = real_add != NULL ? real_add(enumerate, parent) : -ENOSYS; + if (rc == 0 && state != NULL) { + pthread_mutex_lock(&enumerate_lock); + state->parent_node = -1; + state->real_parent = 1; + pthread_mutex_unlock(&enumerate_lock); + } + return rc; +} + +static void *real_get_list_entry(void *enumerate) { + static void *(*real_get)(void *); + + if (real_get == NULL) real_get = next_symbol("udev_enumerate_get_list_entry"); + return real_get != NULL ? real_get(enumerate) : NULL; +} + +int udev_enumerate_scan_devices(void *enumerate) { + static int (*real_scan)(void *); + struct enumerate *state = enumerate_state(enumerate); + char names[ENTRY_MAX][sizeof(pads[0].syspath)]; + int include; + int parent_node; + int added = 0; + int node; + int rc; + + if (real_scan == NULL) real_scan = next_symbol("udev_enumerate_scan_devices"); + rc = real_scan != NULL ? real_scan(enumerate) : -1; + if (state == NULL) return rc; + pthread_mutex_lock(&enumerate_lock); + parent_node = state->parent_node; + include = !state->real_parent && (state->filtered ? state->matched : parent_node >= 0); + pthread_mutex_unlock(&enumerate_lock); + for (node = 0; node < PAD_MAX; node++) { + struct pad pad; + + names[2 * node][0] = '\0'; + names[2 * node + 1][0] = '\0'; + if (!include || (parent_node >= 0 && parent_node != node)) continue; + if (parent_node >= 0 && snapshot_pad(node, 1, &pad)) { + memcpy(names[2 * node], pad.syspath, sizeof(names[0])); + added++; + } + if (snapshot_pad(node, 0, &pad)) { + memcpy(names[2 * node + 1], pad.syspath, sizeof(names[0])); + added++; + } + } + pthread_mutex_lock(&enumerate_lock); + memcpy(state->names, names, sizeof(names)); + state->scanned = 1; + state->real_listed = rc == 0 && parent_node < 0; + state->real_head = NULL; + pthread_mutex_unlock(&enumerate_lock); + /* Both browsers abandon the enumeration when the scan reports an error, and the real scan always + fails here because Android hides /sys/class from readdir. */ + if (added > 0 && rc < 0) rc = 0; + return rc; +} + +static void *next_pad_entry(struct enumerate *state, int from) { + void *entry; + int slot; + + pthread_mutex_lock(&enumerate_lock); + for (slot = from; slot < ENTRY_MAX && state->names[slot][0] == '\0'; slot++) { + } + entry = slot < ENTRY_MAX ? (void *)state->names[slot] : state->real_head; + pthread_mutex_unlock(&enumerate_lock); + return entry; +} + +void *udev_enumerate_get_list_entry(void *enumerate) { + struct enumerate *state = enumerate_state(enumerate); + void *head = NULL; + int own; + int real_listed; + + if (state == NULL) return real_get_list_entry(enumerate); + pthread_mutex_lock(&enumerate_lock); + own = state->scanned && (state->matched || state->parent_node >= 0); + real_listed = state->real_listed; + pthread_mutex_unlock(&enumerate_lock); + if (!own) return real_get_list_entry(enumerate); + if (real_listed) head = real_get_list_entry(enumerate); + pthread_mutex_lock(&enumerate_lock); + state->real_head = head; + pthread_mutex_unlock(&enumerate_lock); + return next_pad_entry(state, 0); +} + +void *udev_list_entry_get_next(void *entry) { + static void *(*real_get)(void *); + struct enumerate *state; + struct handle *handle; + size_t index; + int slot; + + if ((state = entry_state(entry, &slot)) != NULL) return next_pad_entry(state, slot + 1); + if ((handle = property_handle(entry, &index)) != NULL) return next_property(handle, index + 1); + if (real_get == NULL) real_get = next_symbol("udev_list_entry_get_next"); + return real_get != NULL ? real_get(entry) : NULL; +} + +void *udev_list_entry_get_by_name(void *entry, const char *name) { + static void *(*real_get)(void *, const char *); + struct enumerate *state; + struct handle *handle; + size_t index; + int slot; + + if ((state = entry_state(entry, &slot)) != NULL) { + if (name == NULL) return NULL; + pthread_mutex_lock(&enumerate_lock); + for (slot = 0; slot < ENTRY_MAX && (state->names[slot][0] == '\0' || strcmp(state->names[slot], name) != 0); + slot++) { + } + entry = slot < ENTRY_MAX ? (void *)state->names[slot] : state->real_head; + pthread_mutex_unlock(&enumerate_lock); + if (entry == NULL || slot < ENTRY_MAX) return entry; + } else if ((handle = property_handle(entry, &index)) != NULL) { + for (index = 0; index < PROPERTY_COUNT; index++) + if (name != NULL && strcmp(property_keys[index], name) == 0 && pad_property(&handle->info, name) != NULL) + return &handle->properties[index]; + return NULL; + } + if (real_get == NULL) real_get = next_symbol("udev_list_entry_get_by_name"); + return real_get != NULL ? real_get(entry, name) : NULL; +} + +const char *udev_list_entry_get_name(void *entry) { + static const char *(*real_get)(void *); + size_t index; + int slot; + + if (entry_state(entry, &slot) != NULL) return entry; + if (property_handle(entry, &index) != NULL) return property_keys[index]; + if (real_get == NULL) real_get = next_symbol("udev_list_entry_get_name"); + return real_get != NULL ? real_get(entry) : NULL; +} + +const char *udev_list_entry_get_value(void *entry) { + static const char *(*real_get)(void *); + struct handle *handle; + size_t index; + int slot; + + if (entry_state(entry, &slot) != NULL) return ""; + if ((handle = property_handle(entry, &index)) != NULL) return pad_property(&handle->info, property_keys[index]); + if (real_get == NULL) real_get = next_symbol("udev_list_entry_get_value"); + return real_get != NULL ? real_get(entry) : NULL; +} + +struct udev_symbol { + const char *name; + void *address; +}; + +static const struct udev_symbol udev_symbols[] = { + {"udev_device_new_from_syspath", (void *)udev_device_new_from_syspath}, + {"udev_device_new_from_devnum", (void *)udev_device_new_from_devnum}, + {"udev_device_new_from_subsystem_sysname", (void *)udev_device_new_from_subsystem_sysname}, + {"udev_device_ref", (void *)udev_device_ref}, + {"udev_device_unref", (void *)udev_device_unref}, + {"udev_device_get_devnode", (void *)udev_device_get_devnode}, + {"udev_device_get_syspath", (void *)udev_device_get_syspath}, + {"udev_device_get_devpath", (void *)udev_device_get_devpath}, + {"udev_device_get_sysname", (void *)udev_device_get_sysname}, + {"udev_device_get_sysnum", (void *)udev_device_get_sysnum}, + {"udev_device_get_subsystem", (void *)udev_device_get_subsystem}, + {"udev_device_get_devtype", (void *)udev_device_get_devtype}, + {"udev_device_get_action", (void *)udev_device_get_action}, + {"udev_device_get_devnum", (void *)udev_device_get_devnum}, + {"udev_device_get_sysattr_value", (void *)udev_device_get_sysattr_value}, + {"udev_device_get_property_value", (void *)udev_device_get_property_value}, + {"udev_device_get_parent_with_subsystem_devtype", + (void *)udev_device_get_parent_with_subsystem_devtype}, + {"udev_device_get_parent", (void *)udev_device_get_parent}, + {"udev_device_get_udev", (void *)udev_device_get_udev}, + {"udev_device_get_is_initialized", (void *)udev_device_get_is_initialized}, + {"udev_device_has_tag", (void *)udev_device_has_tag}, + {"udev_device_get_properties_list_entry", (void *)udev_device_get_properties_list_entry}, + {"udev_device_get_tags_list_entry", (void *)udev_device_get_tags_list_entry}, + {"udev_device_get_sysattr_list_entry", (void *)udev_device_get_sysattr_list_entry}, + {"udev_enumerate_new", (void *)udev_enumerate_new}, + {"udev_enumerate_ref", (void *)udev_enumerate_ref}, + {"udev_enumerate_unref", (void *)udev_enumerate_unref}, + {"udev_enumerate_add_match_subsystem", (void *)udev_enumerate_add_match_subsystem}, + {"udev_enumerate_add_match_parent", (void *)udev_enumerate_add_match_parent}, + {"udev_enumerate_scan_devices", (void *)udev_enumerate_scan_devices}, + {"udev_enumerate_get_list_entry", (void *)udev_enumerate_get_list_entry}, + {"udev_list_entry_get_next", (void *)udev_list_entry_get_next}, + {"udev_list_entry_get_by_name", (void *)udev_list_entry_get_by_name}, + {"udev_list_entry_get_name", (void *)udev_list_entry_get_name}, + {"udev_list_entry_get_value", (void *)udev_list_entry_get_value}, +}; + +static void *own_udev_symbol(const char *name) { + size_t i; + + for (i = 0; i < sizeof(udev_symbols) / sizeof(udev_symbols[0]); i++) + if (strcmp(udev_symbols[i].name, name) == 0) return udev_symbols[i].address; + return NULL; +} + +static void *dlvsym_any(const char *name) { + static const char *versions[] = {"GLIBC_2.17", "GLIBC_2.2.5", "GLIBC_2.0", "GLIBC_2.34"}; + size_t i; + void *resolved = NULL; + + for (i = 0; i < sizeof(versions) / sizeof(versions[0]) && resolved == NULL; i++) + resolved = dlvsym(RTLD_NEXT, name, versions[i]); + return resolved; +} + +/* A versioned lookup only ever finds libc, so the next dlsym in line is asked for by plain name to + * keep another preload's dlsym in the chain. */ +static void *real_dlsym(void) { + static void *resolved; + + if (resolved == NULL) { + void *(*libc)(void *, const char *) = dlvsym_any("dlsym"); + void *next = libc != NULL ? libc(RTLD_NEXT, "dlsym") : NULL; + + resolved = next != NULL ? next : (void *)libc; + } + return resolved; +} + +static int steam_runtime_path(const char *path) { + static const char *const runtimes[] = {"steamrtarm64", "steamrt64"}; + const char *name = strrchr(path, '/'); + size_t i; + + if (name == NULL || strcmp(name + 1, "steam") != 0) return 0; + for (i = 0; i < sizeof(runtimes) / sizeof(runtimes[0]); i++) { + size_t length = strlen(runtimes[i]); + + if ((size_t)(name - path) > length && name[-(ptrdiff_t)length - 1] == '/' && + memcmp(name - length, runtimes[i], length) == 0) + return 1; + } + return 0; +} + +/* The Steam client reads the pads straight from /dev/input and hands whatever the udev enumeration + * gives it back to the real libudev, which cannot read these synthetic devices. */ +static int steam_client_process(void) { + static _Atomic int cached = -1; + char path[PATH_MAX]; + ssize_t length; + int result = atomic_load_explicit(&cached, memory_order_acquire); + + if (result >= 0) return result; + result = 0; + length = readlink("/proc/self/exe", path, sizeof(path) - 1); + if (length > 0) { + path[length] = '\0'; + result = steam_runtime_path(path); + } + atomic_store_explicit(&cached, result, memory_order_release); + return result; +} + +static void *missing_dlsym(void *handle, const char *name) { + (void)handle; + (void)name; + return NULL; +} + +static void *own_dlsym(void *handle, const char *name) { + (void)handle; + return own_udev_symbol(name); +} + +/* Returns what dlsym jumps to. Anything outside the udev_ names has to reach the real dlsym without + * a single interposable call on the way, because other preloads resolve their own symbols from + * inside one-time initialisers that those calls would re-enter. */ +__attribute__((visibility("hidden"), used)) void *inputudev_dlsym_target(void *handle, const char *name) { + void *forward = real_dlsym(); + + (void)handle; + if (name != NULL && strncmp(name, "udev_", 5) == 0 && own_udev_symbol(name) != NULL && + !steam_client_process()) + return (void *)own_dlsym; + return forward != NULL ? forward : (void *)missing_dlsym; +} + +/* Browsers resolve libudev through dlopen and dlsym, which skips symbol interposition, so the + * devices have to be handed out from here as well. The real dlsym is entered with a jump so that it + * still sees the original caller, which is what RTLD_NEXT and RTLD_DEFAULT lookups are relative to. */ +#if defined(__aarch64__) +__asm__(".text\n" + ".globl dlsym\n" + ".type dlsym, %function\n" + "dlsym:\n" + ".cfi_startproc\n" + "hint #34\n" + "stp x29, x30, [sp, #-32]!\n" + ".cfi_adjust_cfa_offset 32\n" + ".cfi_offset x29, -32\n" + ".cfi_offset x30, -24\n" + "mov x29, sp\n" + "stp x0, x1, [sp, #16]\n" + "bl inputudev_dlsym_target\n" + "mov x16, x0\n" + "ldp x0, x1, [sp, #16]\n" + "ldp x29, x30, [sp], #32\n" + ".cfi_adjust_cfa_offset -32\n" + ".cfi_restore x29\n" + ".cfi_restore x30\n" + "br x16\n" + ".cfi_endproc\n" + ".size dlsym, .-dlsym\n"); +#elif defined(__x86_64__) +__asm__(".text\n" + ".globl dlsym\n" + ".type dlsym, @function\n" + "dlsym:\n" + ".cfi_startproc\n" + "pushq %rdi\n" + ".cfi_adjust_cfa_offset 8\n" + "pushq %rsi\n" + ".cfi_adjust_cfa_offset 8\n" + "subq $8, %rsp\n" + ".cfi_adjust_cfa_offset 8\n" + "call inputudev_dlsym_target\n" + "addq $8, %rsp\n" + ".cfi_adjust_cfa_offset -8\n" + "popq %rsi\n" + ".cfi_adjust_cfa_offset -8\n" + "popq %rdi\n" + ".cfi_adjust_cfa_offset -8\n" + "jmp *%rax\n" + ".cfi_endproc\n" + ".size dlsym, .-dlsym\n"); +#elif defined(__i386__) +__asm__(".text\n" + ".globl dlsym\n" + ".type dlsym, @function\n" + "dlsym:\n" + ".cfi_startproc\n" + "subl $12, %esp\n" + ".cfi_adjust_cfa_offset 12\n" + "movl 20(%esp), %eax\n" + "movl %eax, 4(%esp)\n" + "movl 16(%esp), %eax\n" + "movl %eax, (%esp)\n" + "call inputudev_dlsym_target\n" + "addl $12, %esp\n" + ".cfi_adjust_cfa_offset -12\n" + "jmp *%eax\n" + ".cfi_endproc\n" + ".size dlsym, .-dlsym\n"); +#else +void *dlsym(void *handle, const char *name) { + void *(*target)(void *, const char *) = inputudev_dlsym_target(handle, name); + + return target(handle, name); +} +#endif diff --git a/tools/linuxfs/preload/robust.c b/tools/linuxfs/preload/robust.c index 6d3393b506..9d5707e352 100644 --- a/tools/linuxfs/preload/robust.c +++ b/tools/linuxfs/preload/robust.c @@ -100,7 +100,11 @@ static long path_statx(int dirfd, const char *path, int flags, unsigned int mask return next_statx(dirfd, path, flags, mask, out); } +void bl_inputudev_note_dlopen(const char *path, void *handle) __attribute__((weak, visibility("hidden"))); + void *dlopen(const char *filename, int flags) { + void *handle; + if (!real_dlopen) { real_dlopen = (void *(*)(const char *, int))dlsym(RTLD_NEXT, "dlopen"); } @@ -109,7 +113,9 @@ void *dlopen(const char *filename, int flags) { if (basename && strcmp(basename, "vrclient.so") == 0) { flags &= ~RTLD_DEEPBIND; } - return real_dlopen(filename, flags); + handle = real_dlopen != NULL ? real_dlopen(filename, flags) : NULL; + if (handle != NULL && bl_inputudev_note_dlopen != NULL) bl_inputudev_note_dlopen(filename, handle); + return handle; } int dd_fsync_syscall(long number, const long *args, long *ret) __attribute__((visibility("hidden"))); diff --git a/tools/tests/test_inputudev_preload.py b/tools/tests/test_inputudev_preload.py new file mode 100644 index 0000000000..c1d970fd1d --- /dev/null +++ b/tools/tests/test_inputudev_preload.py @@ -0,0 +1,529 @@ +from pathlib import Path +import os +import shutil +import subprocess +import sys +import tempfile +import unittest + +PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload" + +ONCE = r""" +#define _GNU_SOURCE +#include +#include +#include +#include + +static pthread_once_t once = PTHREAD_ONCE_INIT; +static long (*next_syscall)(long, ...); + +static void init(void) { next_syscall = (long (*)(long, ...))dlsym(RTLD_NEXT, "syscall"); } + +ssize_t readlink(const char *path, char *buf, size_t size) { + pthread_once(&once, init); + return next_syscall(SYS_readlinkat, -100, path, buf, size); +} + +__attribute__((constructor)) static void start(void) { + char link[4096]; + readlink("/proc/self/exe", link, sizeof(link)); +} +""" + +FIRST = r""" +#define _GNU_SOURCE +#include +#include + +int marker(void) { return 1; } + +int next_marker(void) { + int (*next)(void) = (int (*)(void))dlsym(RTLD_NEXT, "marker"); + return next != NULL ? next() : 0; +} +""" + +SECOND = "int marker(void) { return 2; }\n" + +CHAIN = r""" +#define _GNU_SOURCE +#include +#include + +static int calls; + +int chained(void) { return calls > 1; } + +void *dlsym(void *handle, const char *name) { + static void *(*real)(void *, const char *); + if (real == NULL) real = (void *(*)(void *, const char *))dlvsym(RTLD_NEXT, "dlsym", "GLIBC_2.2.5"); + if (real == NULL) real = (void *(*)(void *, const char *))dlvsym(RTLD_NEXT, "dlsym", "GLIBC_2.17"); + if (real == NULL) real = (void *(*)(void *, const char *))dlvsym(RTLD_NEXT, "dlsym", "GLIBC_2.34"); + calls++; + return real(handle, name); +} +""" + +MARK = r""" +#include +#include + +char *realpath(const char *path, char *resolved) { + (void)path; + if (resolved == NULL) return strdup("marked"); + strcpy(resolved, "marked"); + return resolved; +} +""" + +UDEV = r""" +#include +#include +#include + +struct list { const char *name; struct list *next; }; +struct enumerate { struct list head; struct list added; char name[16]; int fail; }; + +void *udev_enumerate_new(void *udev) { + static int count; + struct enumerate *enumerate = calloc(1, sizeof(*enumerate)); + (void)udev; + snprintf(enumerate->name, sizeof(enumerate->name), "real%d", count++); + enumerate->head.name = enumerate->name; + enumerate->added.name = "added"; + return enumerate; +} +void *udev_enumerate_unref(void *enumerate) { free(enumerate); return NULL; } +int udev_enumerate_add_match_subsystem(void *enumerate, const char *subsystem) { + if (strcmp(subsystem, "fail") == 0) ((struct enumerate *)enumerate)->fail = 1; + return 0; +} +int udev_enumerate_add_match_parent(void *enumerate, void *parent) { + if (parent == NULL) return -1; + ((struct enumerate *)enumerate)->head.name = "parented"; + return 0; +} +int udev_enumerate_add_syspath(void *enumerate, const char *syspath) { + (void)syspath; + ((struct enumerate *)enumerate)->head.next = &((struct enumerate *)enumerate)->added; + return 0; +} +int udev_enumerate_scan_devices(void *enumerate) { return ((struct enumerate *)enumerate)->fail ? -1 : 0; } +void *udev_enumerate_get_list_entry(void *enumerate) { return &((struct enumerate *)enumerate)->head; } +void *udev_list_entry_get_next(void *entry) { return ((struct list *)entry)->next; } +void *udev_list_entry_get_by_name(void *entry, const char *name) { + return strcmp(((struct list *)entry)->name, name) == 0 ? entry : NULL; +} +const char *udev_list_entry_get_name(void *entry) { return ((struct list *)entry)->name; } +void *udev_device_new_from_syspath(void *udev, const char *syspath) { (void)udev; (void)syspath; return NULL; } +void *udev_device_new_from_subsystem_sysname(void *udev, const char *subsystem, const char *sysname) { + (void)udev; (void)subsystem; (void)sysname; + return NULL; +} +void *udev_device_unref(void *device) { (void)device; return NULL; } +void *udev_device_ref(void *device) { (void)device; return NULL; } +void *udev_device_get_parent(void *device) { (void)device; return NULL; } +void *udev_device_get_udev(void *device) { (void)device; return NULL; } +const char *udev_device_get_syspath(void *device) { (void)device; return "real"; } +const char *udev_device_get_sysnum(void *device) { (void)device; return "real"; } +""" + +PROGRAM = r""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include + +#define PAD "/sys/devices/virtual/input/droiddeck0" +#define PARENT0 "/sys/devices/droiddeck0/droiddeck-input0" +#define EVENT0 PARENT0 "/event0" +#define EVENT1 "/sys/devices/droiddeck1/droiddeck-input1/event1" +#define HANDLES 256 + +int next_marker(void); + +static void *lib; +static void *(*new_device)(void *, const char *); +static void *(*new_sysname)(void *, const char *, const char *); +static void *(*ref)(void *); +static void *(*unref)(void *); +static void *(*get_parent)(void *); +static void *(*get_udev)(void *); +static const char *(*syspath)(void *); +static const char *(*sysname)(void *); +static const char *(*sysnum)(void *); +static const char *(*devnode)(void *); +static const char *(*property)(void *, const char *); +static void *(*properties)(void *); +static void *(*enumerate_new)(void *); +static int (*match)(void *, const char *); +static int (*match_parent)(void *, void *); +static int (*add_syspath)(void *, const char *); +static int (*scan)(void *); +static void *(*list)(void *); +static void *(*next)(void *); +static void *(*by_name)(void *, const char *); +static const char *(*name)(void *); +static const char *(*value)(void *); + +static void *sym(const char *symbol) { return dlsym(lib, symbol); } + +static const char *entry_name(void *entry) { return entry != NULL ? name(entry) : "none"; } + +static void print_list(const char *label, void *entry) { + printf("%s", label); + for (; entry != NULL; entry = next(entry)) printf(" %s", name(entry)); + printf("\n"); +} + +static void print_properties(const char *label, void *device) { + void *entry; + + printf("%s", label); + for (entry = properties(device); entry != NULL; entry = next(entry)) printf(" %s=%s", name(entry), value(entry)); + printf("\n"); +} + +static void *matched(void *udev, const char *subsystem) { + void *enumerate = enumerate_new(udev); + + match(enumerate, subsystem); + return enumerate; +} + +static void pad_file(const char *node, int present) { + char path[4096]; + FILE *file; + + snprintf(path, sizeof(path), "%s/%s", getenv("FAKE_EVDEV_DIR"), node); + if (!present) { + unlink(path); + } else if ((file = fopen(path, "w")) != NULL) { + fclose(file); + } +} + +static void run_udev(void) { + int udev_a, udev_b, i, failures = 0; + void *device, *parent, *other, *entry, *held[HANDLES] = {0}; + char resolved[4096]; + const char *path; + + printf("missing %d\n", sym("udev_no_such_symbol") == NULL); + printf("plain %d\n", dlsym(RTLD_DEFAULT, "printf") != NULL); + device = new_device(&udev_a, PAD); + printf("syspath %s sysnum %s devnode %s\n", syspath(device), sysnum(device), devnode(device)); + parent = get_parent(device); + printf("nested %d\n", strncmp(syspath(device), syspath(parent), strlen(syspath(parent))) == 0 && + syspath(device)[strlen(syspath(parent))] == '/'); + other = new_device(&udev_a, EVENT0); + printf("canonical %s\n", other != NULL ? syspath(other) : "none"); + if (other != NULL) unref(other); + printf("parent %s sysname %s stable %d\n", syspath(parent), sysname(parent), parent == get_parent(device)); + print_properties("device properties", device); + print_properties("parent properties", parent); + entry = properties(device); + printf("joystick %s unknown %d\n", value(by_name(entry, "ID_INPUT_JOYSTICK")), by_name(entry, "NO_SUCH_KEY") == NULL); + ref(device); + unref(device); + printf("held %s\n", syspath(device)); + ref(parent); + unref(device); + printf("retained %s\n", syspath(parent)); + unref(parent); + for (i = 0; i < 1000; i++) { + device = new_device(&udev_a, PAD); + if (device == NULL || get_parent(device) == NULL || get_parent(device) != get_parent(device) || + strcmp(syspath(device), EVENT0) != 0) + failures++; + if (device != NULL) unref(device); + } + printf("reuse failures %d\n", failures); + for (i = 0; i < HANDLES && (held[i] = new_device(&udev_a, PAD)) != NULL; i++) { + } + printf("full %d extra %d parent %d\n", i, new_device(&udev_a, PAD) == NULL, get_parent(held[0]) == NULL); + unref(held[1]); + parent = get_parent(held[0]); + printf("freed parent %s stable %d\n", parent != NULL ? syspath(parent) : "none", parent == get_parent(held[0])); + for (i = 0; i < HANDLES; i++) + if (i != 1 && held[i] != NULL) unref(held[i]); + path = realpath("/sys/class/input/droiddeck-input0", resolved); + printf("parent link %s\n", path != NULL ? path : "none"); + path = realpath("/sys/class/input/input0", resolved); + printf("kernel link shadowed %d\n", path != NULL && strncmp(path, "/sys/devices/droiddeck", 22) == 0); + printf("kernel sysname shadowed %d\n", new_sysname(&udev_a, "input", "input0") != NULL); + other = new_sysname(&udev_a, "input", "droiddeck-input0"); + printf("parent sysname %s\n", other != NULL ? syspath(other) : "none"); + if (other != NULL) unref(other); + device = new_device(&udev_a, PAD); + other = new_device(&udev_b, PAD); + printf("contexts %d %d\n", get_udev(device) == (void *)&udev_a, get_udev(other) == (void *)&udev_b); +} + +static void run_stable(void) { + int udev; + char copy[64]; + void *device = new_device(&udev, PAD); + const char *before = devnode(device); + + snprintf(copy, sizeof(copy), "%s", before); + pad_file("event0", 0); + printf("gone %d\n", new_device(&udev, PAD) == NULL); + printf("devnode %s same %d property %s\n", devnode(device), devnode(device) == before && strcmp(before, copy) == 0, + property(device, "DEVNAME")); +} + +static void run_enumerate(void) { + int udev, i; + void *first, *entry, *found, *missing, *failed, *parented, *real_parent, *device, *parent, *other; + + first = matched(&udev, "input"); + scan(first); + entry = list(first); + print_list("scan", entry); + pad_file("event1", 1); + print_list("same scan", list(first)); + entry = list(first); + found = by_name(entry, EVENT0); + missing = by_name(entry, EVENT1); + printf("by name %s missing %d\n", entry_name(found), missing == NULL); + for (i = 0; i < 20; i++) { + void *other = matched(&udev, "input"); + scan(other); + list(other); + } + printf("kept tail %s\n", entry_name(next(entry))); + scan(first); + print_list("rescan", list(first)); + printf("rescan by name %s\n", entry_name(by_name(list(first), EVENT1))); + add_syspath(first, "/sys/devices/added"); + print_list("added", list(first)); + failed = matched(&udev, "input"); + match(failed, "fail"); + printf("failed scan %d\n", scan(failed)); + print_list("failed", list(failed)); + device = new_device(&udev, PAD); + parent = get_parent(device); + parented = enumerate_new(&udev); + printf("synthetic parent %d\n", match_parent(parented, parent)); + scan(parented); + print_list("parented", list(parented)); + real_parent = enumerate_new(&udev); + printf("real parent %d\n", match_parent(real_parent, &udev)); + scan(real_parent); + print_list("real parent list", list(real_parent)); + other = matched(&udev, "input"); + match_parent(other, &udev); + scan(other); + print_list("real parent suppressed", list(other)); + other = matched(&udev, "input"); + match_parent(other, parent); + match_parent(other, &udev); + scan(other); + print_list("real replaces synthetic", list(other)); + other = matched(&udev, "input"); + match_parent(other, &udev); + match_parent(other, parent); + scan(other); + print_list("synthetic replaces real", list(other)); + other = matched(&udev, "input"); + match_parent(other, parent); + printf("bad parent %d\n", match_parent(other, NULL)); + scan(other); + print_list("bad parent kept", list(other)); + other = enumerate_new(&udev); + match(other, "fail"); + match_parent(other, parent); + printf("nothing added scan %d\n", scan(other)); +} + +static void run_probe(void) { + int udev; + + printf("pad %d\n", new_device(&udev, PAD) != NULL); +} + +int main(int argc, char **argv) { + char link[4096]; + + if (strcmp(argv[1], "once") == 0) { + printf("readlink %d\n", readlink("/proc/self/exe", link, sizeof(link)) > 0); + return 0; + } + if (strcmp(argv[1], "next") == 0) { + int (*chained)(void) = (int (*)(void))dlsym(RTLD_DEFAULT, "chained"); + printf("next %d\n", next_marker()); + if (chained != NULL) printf("chained %d\n", chained()); + return 0; + } + lib = dlopen(argv[2], RTLD_NOW | RTLD_LOCAL); + if (strcmp(argv[1], "realpath") == 0) { + printf("realpath %s\n", realpath("/no/such/inputudev/path", link)); + return 0; + } + new_device = sym("udev_device_new_from_syspath"); + new_sysname = sym("udev_device_new_from_subsystem_sysname"); + ref = sym("udev_device_ref"); + unref = sym("udev_device_unref"); + get_parent = sym("udev_device_get_parent"); + get_udev = sym("udev_device_get_udev"); + syspath = sym("udev_device_get_syspath"); + sysname = sym("udev_device_get_sysname"); + sysnum = sym("udev_device_get_sysnum"); + devnode = sym("udev_device_get_devnode"); + property = sym("udev_device_get_property_value"); + properties = sym("udev_device_get_properties_list_entry"); + enumerate_new = sym("udev_enumerate_new"); + match = sym("udev_enumerate_add_match_subsystem"); + match_parent = sym("udev_enumerate_add_match_parent"); + add_syspath = sym("udev_enumerate_add_syspath"); + scan = sym("udev_enumerate_scan_devices"); + list = sym("udev_enumerate_get_list_entry"); + next = sym("udev_list_entry_get_next"); + by_name = sym("udev_list_entry_get_by_name"); + name = sym("udev_list_entry_get_name"); + value = sym("udev_list_entry_get_value"); + if (strcmp(argv[1], "probe") == 0) run_probe(); + else if (strcmp(argv[1], "stable") == 0) run_stable(); + else if (strcmp(argv[1], "enumerate") == 0) run_enumerate(); + else run_udev(); + fflush(stdout); + return 0; +} +""" + + +def compile_c(*args): + result = subprocess.run(["cc", *args], capture_output=True, text=True) + if result.returncode != 0: + raise AssertionError(f"cc {' '.join(args)} failed:\n{result.stderr}") + return result.stdout + + +@unittest.skipUnless(sys.platform == "linux" and shutil.which("cc"), "needs Linux and cc") +class InputUdevPreloadTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.dir = Path(tempfile.mkdtemp()) + cls.addClassCleanup(shutil.rmtree, cls.dir, ignore_errors=True) + build = cls.dir / "build" + build.mkdir() + if "__GLIBC__" not in compile_c("-dM", "-E", "-x", "c", "-include", "limits.h", "/dev/null"): + raise unittest.SkipTest("needs a glibc toolchain") + sources = (("once.c", ONCE), ("first.c", FIRST), ("second.c", SECOND), ("chain.c", CHAIN), ("mark.c", MARK), + ("udev.c", UDEV), ("program.c", PROGRAM)) + for name, text in sources: + (build / name).write_text(text) + cls.lib = cls.dir / "libddsession.so" + compile_c("-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(cls.lib), + *map(str, sorted(PRELOAD.glob("*.c"))), "-ldl") + for name in ("once", "first", "second", "chain", "mark"): + compile_c("-shared", "-fPIC", "-O0", "-pthread", "-o", str(cls.dir / f"lib{name}.so"), + str(build / f"{name}.c"), "-ldl") + cls.udev = cls.dir / "libudev.so.1" + compile_c("-shared", "-fPIC", "-O2", "-o", str(cls.udev), str(build / "udev.c")) + cls.program = cls.dir / "program" + compile_c("-O0", "-o", str(cls.program), str(build / "program.c"), str(cls.dir / "libfirst.so"), "-ldl") + cls.pads = cls.pad_dir("pads", "event0") + + @classmethod + def pad_dir(cls, name, *nodes): + pads = cls.dir / name + pads.mkdir() + for node in nodes: + (pads / node).write_text("") + return pads + + def run_program(self, mode, *preloads, pads=None, slots="0=/pad", program=None): + env = dict(os.environ, LD_PRELOAD=":".join(str(self.dir / name) for name in ("libddsession.so", *preloads)), + FAKE_EVDEV_MEMFD_PATHS=slots, FAKE_EVDEV_DIR=str(pads or self.pads)) + env.pop("FAKE_EVDEV_UINPUT", None) + result = subprocess.run([str(program or self.program), mode, str(self.udev)], env=env, capture_output=True, text=True, + timeout=20) + self.assertEqual(result.returncode, 0, result.stderr) + return result.stdout.splitlines() + + def test_a_lookup_from_another_preloads_initialiser_does_not_reenter_it(self): + self.assertEqual(self.run_program("once", "libonce.so"), ["readlink 1"]) + + def test_the_real_lookup_still_sees_the_original_caller(self): + self.assertEqual(self.run_program("next", "libfirst.so", "libsecond.so"), ["next 2"]) + + def test_another_preloads_dlsym_stays_in_the_chain(self): + self.assertEqual(self.run_program("next", "libfirst.so", "libchain.so", "libsecond.so"), ["next 2", "chained 1"]) + + def test_non_udev_lookups_skip_the_opened_libudev(self): + self.assertEqual(self.run_program("realpath", "libmark.so"), ["realpath marked"]) + + def test_a_program_resolving_udev_through_dlsym_gets_the_pads(self): + parent = "/sys/devices/droiddeck0/droiddeck-input0" + pad = f"{parent}/event0" + self.assertEqual(self.run_program("udev"), [ + "missing 1", + "plain 1", + f"syspath {pad} sysnum 0 devnode /dev/input/event0", + "nested 1", + f"canonical {pad}", + f"parent {parent} sysname droiddeck-input0 stable 1", + f"device properties DEVNAME=/dev/input/event0 DEVPATH={pad[4:]} ID_INPUT=1 ID_INPUT_JOYSTICK=1", + f"parent properties DEVPATH={parent[4:]} ID_INPUT=1 ID_INPUT_JOYSTICK=1", + "joystick 1 unknown 1", + f"held {pad}", + f"retained {parent}", + "reuse failures 0", + "full 256 extra 1 parent 1", + f"freed parent {parent} stable 1", + f"parent link {parent}", + "kernel link shadowed 0", + "kernel sysname shadowed 0", + f"parent sysname {parent}", + "contexts 1 1", + ]) + + def test_a_handle_keeps_its_strings_after_the_pad_goes_away(self): + self.assertEqual(self.run_program("stable", pads=self.pad_dir("stable", "event0")), [ + "gone 1", + "devnode /dev/input/event0 same 1 property /dev/input/event0", + ]) + + def test_enumerations_keep_their_scan_and_their_state(self): + parent = "/sys/devices/droiddeck0/droiddeck-input0" + pad = f"{parent}/event0" + pad1 = "/sys/devices/droiddeck1/droiddeck-input1/event1" + self.assertEqual(self.run_program("enumerate", pads=self.pad_dir("enumerate", "event0"), slots="0=/pad;1=/pad"), [ + f"scan {pad} real0", + f"same scan {pad} real0", + f"by name {pad} missing 1", + "kept tail real0", + f"rescan {pad} {pad1} real0", + f"rescan by name {pad1}", + f"added {pad} {pad1} real0 added", + "failed scan 0", + f"failed {pad} {pad1}", + "synthetic parent 0", + f"parented {parent} {pad}", + "real parent 0", + "real parent list parented", + "real parent suppressed parented", + "real replaces synthetic parented", + f"synthetic replaces real {parent} {pad}", + "bad parent -1", + f"bad parent kept {parent} {pad}", + "nothing added scan -1", + ]) + + def test_only_the_steam_client_runtime_path_gets_the_real_libudev(self): + for path, pad in (("steamrt64/steam", 0), ("steamrtarm64/steam", 0), ("steamrt64/steam-probe", 1), + ("xsteamrt64/steam", 1), ("steamrt64/xsteam", 1), ("steamrt/steam", 1)): + with self.subTest(path=path): + client = self.dir / "clients" / path + client.parent.mkdir(parents=True, exist_ok=True) + shutil.copy(self.program, client) + self.assertEqual(self.run_program("probe", program=client), [f"pad {pad}"]) + + +if __name__ == "__main__": + unittest.main()