From 854394ee137915c9c067cb7afdbcb06d917716ab Mon Sep 17 00:00:00 2001 From: Ebrahim Date: Wed, 25 Nov 2026 23:11:21 +0330 Subject: [PATCH 01/20] windows: add opt-in CRT-free backend Add HIDAPI_NO_CRT to replace CRT allocation, string, memory and formatting helpers with Win32 equivalents while leaving CRT builds unchanged. Route the implementation through HIDAPI_* aliases and use the volatile byte-loop fallback for clang instead of its CRT-lowered intrinsics. Avoid compiler-generated memset calls in the descriptor reconstruction and device-detection initialization so the library exports no standard memory symbols. Add MSVC, clang-cl and MinGW no-CRT CI that builds the library, links regular and amalgamated probes without the CRT, checks imports, and runs the memory helpers at runtime. Assisted-by: deepseek-harness:deepseek-flash --- .github/workflows/builds.yml | 83 ++++++++++ CMakeLists.txt | 1 + windows/CMakeLists.txt | 15 ++ windows/hid.c | 181 ++++++++++----------- windows/hidapi_descriptor_reconstruct.c | 72 +++++---- windows/hidapi_winapi_crt.h | 204 ++++++++++++++++++++++++ windows/test/no_crt/CMakeLists.txt | 74 +++++++++ windows/test/no_crt/init_probe.c | 10 ++ windows/test/no_crt/mem_probe.c | 31 ++++ 9 files changed, 538 insertions(+), 133 deletions(-) create mode 100644 windows/hidapi_winapi_crt.h create mode 100644 windows/test/no_crt/CMakeLists.txt create mode 100644 windows/test/no_crt/init_probe.c create mode 100644 windows/test/no_crt/mem_probe.c diff --git a/.github/workflows/builds.yml b/.github/workflows/builds.yml index a7a3d2cec..2749d2ad6 100644 --- a/.github/workflows/builds.yml +++ b/.github/workflows/builds.yml @@ -344,6 +344,89 @@ jobs: ninja + windows-cmake-no-crt: + + name: windows no-CRT + runs-on: windows-latest + + steps: + - uses: actions/checkout@v7 + with: + path: hidapisrc + - name: Set up MSVC developer environment + uses: TheMrMilchmann/setup-msvc-dev@v4 + with: + arch: x64 + - name: Install Ninja + shell: cmd + run: choco install ninja -y --no-progress + - name: Build and check all no-CRT compilers + shell: pwsh + run: | + $ok = $true + foreach ($compiler in @('cl', 'clang-cl', 'gcc')) { + Write-Host "`n===== $compiler =====" + $build = "build\no-crt-$compiler" + + cmake -G Ninja ` + -B $build ` + -S hidapisrc ` + "-DCMAKE_C_COMPILER=$compiler" ` + -DCMAKE_BUILD_TYPE=Release ` + -DBUILD_SHARED_LIBS=OFF ` + -DHIDAPI_NO_CRT=ON ` + -DHIDAPI_WITH_TESTS=OFF ` + -DHIDAPI_BUILD_HIDTEST=OFF + if ($LASTEXITCODE -ne 0) { $ok = $false; continue } + + cmake --build $build + if ($LASTEXITCODE -ne 0) { $ok = $false; continue } + + $lib = Get-ChildItem "$build\src\windows" -File | + Where-Object { $_.Name -eq 'hidapi.lib' -or $_.Name -eq 'libhidapi.a' } | + Select-Object -First 1 + if (-not $lib) { + Write-Host "::error title=$compiler::no-CRT static library not found" + $ok = $false + continue + } + + $probeBuild = "$build\probes" + cmake -G Ninja ` + -B $probeBuild ` + -S hidapisrc\windows\test\no_crt ` + "-DCMAKE_C_COMPILER=$compiler" ` + -DCMAKE_BUILD_TYPE=Release ` + "-DHIDAPI_SOURCE_DIR=$((Get-Location).Path)\hidapisrc" ` + "-DHIDAPI_LIBRARY=$($lib.FullName)" + if ($LASTEXITCODE -ne 0) { $ok = $false; continue } + + cmake --build $probeBuild + if ($LASTEXITCODE -ne 0) { $ok = $false; continue } + + foreach ($probeName in @('no_crt_init_probe', 'no_crt_mem_probe')) { + $probePath = Join-Path $probeBuild "$probeName.exe" + $proc = Start-Process -FilePath $probePath -PassThru + if (-not $proc.WaitForExit(5000)) { + $proc.Kill() + Write-Host "::error title=$compiler/$probeName::no-CRT probe timed out" + $ok = $false + continue + } + if ($proc.ExitCode -ne 0) { + Write-Host "::error title=$compiler/$probeName::no-CRT probe exited with $($proc.ExitCode)" + $ok = $false + } + + $deps = dumpbin /nologo /dependents $probePath | Out-String + if ($deps -match '(?i)(vcruntime|ucrtbase|msvcrt|api-ms-win-crt|libgcc|libwinpthread)') { + Write-Host "::error title=$compiler/$probeName::CRT dependency found in the no-CRT probe" + $ok = $false + } + } + } + if (-not $ok) { exit 1 } + windows-cmake-mingw: runs-on: windows-latest diff --git a/CMakeLists.txt b/CMakeLists.txt index 207e27971..8cd256ae8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -82,6 +82,7 @@ endif() if(WIN32) option(HIDAPI_BUILD_PP_DATA_DUMP "Build small Windows console application pp_data_dump.exe" ${IS_DEBUG_BUILD}) + option(HIDAPI_NO_CRT "Build the Windows backend without the C runtime" OFF) endif() add_subdirectory(src) diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt index eca7aa394..3b8ba4fcc 100644 --- a/windows/CMakeLists.txt +++ b/windows/CMakeLists.txt @@ -8,6 +8,7 @@ set(SOURCES hidapi_hidclass.h hidapi_hidpi.h hidapi_hidsdi.h + hidapi_winapi_crt.h ) if(BUILD_SHARED_LIBS) @@ -32,6 +33,20 @@ target_compile_definitions(hidapi_winapi PRIVATE HIDAPI_CMAKE_V0_BUILD ) +if(HIDAPI_NO_CRT) + target_compile_definitions(hidapi_winapi PRIVATE HIDAPI_NO_CRT) + target_link_libraries(hidapi_winapi PRIVATE shlwapi) + if(MSVC) + # The descriptor reconstructor has a large stack frame. Disable stack + # probes and the security cookie so the static library does not need + # __chkstk or __security_cookie from the CRT. + target_compile_options(hidapi_winapi PRIVATE /GS- /Gs9999999) + elseif(MINGW) + # GCC's automatic stack probe would need ___chkstk_ms from the CRT. + target_compile_options(hidapi_winapi PRIVATE -mno-stack-arg-probe) + endif() +endif() + if(NOT BUILD_SHARED_LIBS) target_compile_definitions(hidapi_winapi # prevent marking functions as __declspec(dllexport) for static library build diff --git a/windows/hid.c b/windows/hid.c index 8456c9b32..d089eae1f 100644 --- a/windows/hid.c +++ b/windows/hid.c @@ -47,7 +47,6 @@ typedef LONG NTSTATUS; #ifdef __CYGWIN__ #include #include -#define _wcsdup wcsdup #endif /*#define HIDAPI_USE_DDK*/ @@ -56,19 +55,7 @@ typedef LONG NTSTATUS; #include "hidapi_hidclass.h" #include "hidapi_hidsdi.h" -#include -#include -#include - -/* MSVC secure CRT (VS2005+) provides swprintf_s/wcsncpy_s. - Older MSVC and GCC/MinGW/Cygwin use the classic variants. */ -#if defined(_MSC_VER) && (_MSC_VER >= 1400) -#define HIDAPI_SWPRINTF swprintf_s -#define HIDAPI_WCSNCPY(dest, dest_count, src) wcsncpy_s((dest), (dest_count), (src), _TRUNCATE) -#else -#define HIDAPI_SWPRINTF swprintf -#define HIDAPI_WCSNCPY(dest, dest_count, src) wcsncpy((dest), (src), (dest_count)) -#endif +#include "hidapi_winapi_crt.h" #ifdef MIN #undef MIN @@ -153,7 +140,7 @@ static int lookup_functions() #define RESOLVE(lib_handle, x) do { \ FARPROC proc_addr = GetProcAddress(lib_handle, #x); \ if (!proc_addr) goto err; \ - memcpy(&x, &proc_addr, sizeof(x)); \ + HIDAPI_MEMCPY(&x, &proc_addr, sizeof(x)); \ } while (0) RESOLVE(hid_lib_handle, HidD_GetHidGuid); @@ -213,7 +200,7 @@ static void free_hid_device(hid_device *dev); static hid_device *new_hid_device() { - hid_device *dev = (hid_device*) calloc(1, sizeof(hid_device)); + hid_device *dev = (hid_device*) HIDAPI_CALLOC(1, sizeof(hid_device)); if (dev == NULL) { return NULL; @@ -230,9 +217,9 @@ static hid_device *new_hid_device() dev->last_read_error_str = NULL; dev->read_pending = FALSE; dev->read_buf = NULL; - memset(&dev->ol, 0, sizeof(dev->ol)); + HIDAPI_MEMSET(&dev->ol, 0, sizeof(dev->ol)); dev->ol.hEvent = CreateEvent(NULL, FALSE, FALSE /*initial state f=nonsignaled*/, NULL); - memset(&dev->write_ol, 0, sizeof(dev->write_ol)); + HIDAPI_MEMSET(&dev->write_ol, 0, sizeof(dev->write_ol)); dev->write_ol.hEvent = CreateEvent(NULL, FALSE, FALSE /*initial state f=nonsignaled*/, NULL); dev->interrupt_event = CreateEvent(NULL, TRUE /*manual reset*/, FALSE /*initial state nonsignaled*/, NULL); if (dev->interrupt_event == NULL) { @@ -255,20 +242,20 @@ static void free_hid_device(hid_device *dev) CloseHandle(dev->write_ol.hEvent); CloseHandle(dev->interrupt_event); CloseHandle(dev->device_handle); - free(dev->last_error_str); - free(dev->last_read_error_str); + HIDAPI_FREE(dev->last_error_str); + HIDAPI_FREE(dev->last_read_error_str); dev->last_error_str = NULL; dev->last_read_error_str = NULL; - free(dev->write_buf); - free(dev->feature_buf); - free(dev->read_buf); + HIDAPI_FREE(dev->write_buf); + HIDAPI_FREE(dev->feature_buf); + HIDAPI_FREE(dev->read_buf); hid_free_enumeration(dev->device_info); - free(dev); + HIDAPI_FREE(dev); } static void register_winapi_error_to_buffer(wchar_t **error_buffer, const WCHAR *op) { - free(*error_buffer); + HIDAPI_FREE(*error_buffer); *error_buffer = NULL; /* Only clear out error messages if NULL is passed into op */ @@ -287,7 +274,7 @@ static void register_winapi_error_to_buffer(wchar_t **error_buffer, const WCHAR system_err_buf, ARRAYSIZE(system_err_buf), NULL); - DWORD op_len = (DWORD)wcslen(op); + DWORD op_len = (DWORD)HIDAPI_WCSLEN(op); DWORD op_prefix_len = op_len @@ -298,7 +285,7 @@ static void register_winapi_error_to_buffer(wchar_t **error_buffer, const WCHAR + system_err_len ; - *error_buffer = (WCHAR *)calloc(msg_len + 1, sizeof (WCHAR)); + *error_buffer = (WCHAR *)HIDAPI_CALLOC(msg_len + 1, sizeof (WCHAR)); WCHAR *msg = *error_buffer; if (!msg) @@ -334,11 +321,11 @@ static void register_winapi_error_to_buffer(wchar_t **error_buffer, const WCHAR static void register_string_error_to_buffer(wchar_t **error_buffer, const WCHAR *string_error) { - free(*error_buffer); + HIDAPI_FREE(*error_buffer); *error_buffer = NULL; if (string_error) { - *error_buffer = _wcsdup(string_error); + *error_buffer = HIDAPI_WCSDUP(string_error); } } @@ -431,10 +418,10 @@ static void* hid_internal_get_devnode_property(DEVINST dev_node, const DEVPROPKE if (cr != CR_BUFFER_SMALL || property_type != expected_property_type) return NULL; - property_value = (PBYTE)calloc(len, sizeof(BYTE)); + property_value = (PBYTE)HIDAPI_CALLOC(len, sizeof(BYTE)); cr = CM_Get_DevNode_PropertyW(dev_node, property_key, &property_type, property_value, &len, 0); if (cr != CR_SUCCESS) { - free(property_value); + HIDAPI_FREE(property_value); return NULL; } @@ -452,32 +439,28 @@ static void* hid_internal_get_device_interface_property(const wchar_t* interface if (cr != CR_BUFFER_SMALL || property_type != expected_property_type) return NULL; - property_value = (PBYTE)calloc(len, sizeof(BYTE)); + property_value = (PBYTE)HIDAPI_CALLOC(len, sizeof(BYTE)); cr = CM_Get_Device_Interface_PropertyW(interface_path, property_key, &property_type, property_value, &len, 0); if (cr != CR_SUCCESS) { - free(property_value); + HIDAPI_FREE(property_value); return NULL; } return property_value; } -static void hid_internal_towupper(wchar_t* string) -{ - for (wchar_t* p = string; *p; ++p) *p = towupper(*p); -} static int hid_internal_extract_int_token_value(wchar_t* string, const wchar_t* token) { int token_value; wchar_t* startptr, * endptr; - startptr = wcsstr(string, token); + startptr = HIDAPI_WCSSTR(string, token); if (!startptr) return -1; - startptr += wcslen(token); - token_value = wcstol(startptr, &endptr, 16); + startptr += HIDAPI_WCSLEN(token); + token_value = HIDAPI_WCSTOL_HEX(startptr, &endptr); if (endptr == startptr) return -1; @@ -514,7 +497,7 @@ static void hid_internal_get_usb_info(struct hid_device_info* dev, DEVINST dev_n https://docs.microsoft.com/windows-hardware/drivers/install/standard-usb-identifiers https://docs.microsoft.com/windows-hardware/drivers/usbcon/enumeration-of-interfaces-not-grouped-in-collections */ - for (wchar_t* hardware_id = hardware_ids; *hardware_id; hardware_id += wcslen(hardware_id) + 1) { + for (wchar_t* hardware_id = hardware_ids; *hardware_id; hardware_id += HIDAPI_WCSLEN(hardware_id) + 1) { /* Normalize to upper case */ hid_internal_towupper(hardware_id); @@ -536,16 +519,16 @@ static void hid_internal_get_usb_info(struct hid_device_info* dev, DEVINST dev_n } /* Try to get USB device manufacturer string if not provided by HidD_GetManufacturerString. */ - if (wcslen(dev->manufacturer_string) == 0) { + if (HIDAPI_WCSLEN(dev->manufacturer_string) == 0) { wchar_t* manufacturer_string = (wchar_t *)hid_internal_get_devnode_property(dev_node, &DEVPKEY_Device_Manufacturer, DEVPROP_TYPE_STRING); if (manufacturer_string) { - free(dev->manufacturer_string); + HIDAPI_FREE(dev->manufacturer_string); dev->manufacturer_string = manufacturer_string; } } /* Try to get USB device serial number if not provided by HidD_GetSerialNumberString. */ - if (wcslen(dev->serial_number) == 0) { + if (HIDAPI_WCSLEN(dev->serial_number) == 0) { DEVINST usb_dev_node = dev_node; if (dev->interface_number != -1) { /* Get devnode parent to reach out composite parent USB device. @@ -556,7 +539,7 @@ static void hid_internal_get_usb_info(struct hid_device_info* dev, DEVINST dev_n } /* Get the device id of the USB device. */ - free(device_id); + HIDAPI_FREE(device_id); device_id = (wchar_t *)hid_internal_get_devnode_property(usb_dev_node, &DEVPKEY_Device_InstanceId, DEVPROP_TYPE_STRING); if (!device_id) goto end; @@ -565,15 +548,15 @@ static void hid_internal_get_usb_info(struct hid_device_info* dev, DEVINST dev_n For USB devices it may contain device's serial number. https://docs.microsoft.com/windows-hardware/drivers/install/instance-ids */ - for (wchar_t *ptr = device_id + wcslen(device_id); ptr > device_id; --ptr) { + for (wchar_t *ptr = device_id + HIDAPI_WCSLEN(device_id); ptr > device_id; --ptr) { /* Instance ID is unique only within the scope of the bus. For USB devices it means that serial number is not available. Skip. */ if (*ptr == L'&') break; if (*ptr == L'\\') { - free(dev->serial_number); - dev->serial_number = _wcsdup(ptr + 1); + HIDAPI_FREE(dev->serial_number); + dev->serial_number = HIDAPI_WCSDUP(ptr + 1); break; } } @@ -584,8 +567,8 @@ static void hid_internal_get_usb_info(struct hid_device_info* dev, DEVINST dev_n dev->interface_number = 0; end: - free(device_id); - free(hardware_ids); + HIDAPI_FREE(device_id); + HIDAPI_FREE(hardware_ids); } /* HidD_GetProductString/HidD_GetManufacturerString/HidD_GetSerialNumberString is not working for BLE HID devices @@ -594,25 +577,25 @@ static void hid_internal_get_usb_info(struct hid_device_info* dev, DEVINST dev_n */ static void hid_internal_get_ble_info(struct hid_device_info* dev, DEVINST dev_node) { - if (wcslen(dev->manufacturer_string) == 0) { + if (HIDAPI_WCSLEN(dev->manufacturer_string) == 0) { /* Manufacturer Name String (UUID: 0x2A29) */ wchar_t* manufacturer_string = (wchar_t *)hid_internal_get_devnode_property(dev_node, (const DEVPROPKEY*)&PKEY_DeviceInterface_Bluetooth_Manufacturer, DEVPROP_TYPE_STRING); if (manufacturer_string) { - free(dev->manufacturer_string); + HIDAPI_FREE(dev->manufacturer_string); dev->manufacturer_string = manufacturer_string; } } - if (wcslen(dev->serial_number) == 0) { + if (HIDAPI_WCSLEN(dev->serial_number) == 0) { /* Serial Number String (UUID: 0x2A25) */ wchar_t* serial_number = (wchar_t *)hid_internal_get_devnode_property(dev_node, (const DEVPROPKEY*)&PKEY_DeviceInterface_Bluetooth_DeviceAddress, DEVPROP_TYPE_STRING); if (serial_number) { - free(dev->serial_number); + HIDAPI_FREE(dev->serial_number); dev->serial_number = serial_number; } } - if (wcslen(dev->product_string) == 0) { + if (HIDAPI_WCSLEN(dev->product_string) == 0) { /* Model Number String (UUID: 0x2A24) */ wchar_t* product_string = (wchar_t *)hid_internal_get_devnode_property(dev_node, (const DEVPROPKEY*)&PKEY_DeviceInterface_Bluetooth_ModelNumber, DEVPROP_TYPE_STRING); if (!product_string) { @@ -625,7 +608,7 @@ static void hid_internal_get_ble_info(struct hid_device_info* dev, DEVINST dev_n } if (product_string) { - free(dev->product_string); + HIDAPI_FREE(dev->product_string); dev->product_string = product_string; } } @@ -646,7 +629,9 @@ static hid_internal_detect_bus_type_result hid_internal_detect_bus_type(const wc wchar_t *device_id = NULL, *compatible_ids = NULL; CONFIGRET cr; DEVINST dev_node; - hid_internal_detect_bus_type_result result = { 0 }; + hid_internal_detect_bus_type_result result; + + HIDAPI_MEMSET(&result, 0, sizeof(result)); /* Get the device id from interface path */ device_id = (wchar_t *)hid_internal_get_device_interface_property(interface_path, &DEVPKEY_Device_InstanceId, DEVPROP_TYPE_STRING); @@ -669,27 +654,27 @@ static hid_internal_detect_bus_type_result hid_internal_detect_bus_type(const wc goto end; /* Now we can parse parent's compatible IDs to find out the device bus type */ - for (wchar_t* compatible_id = compatible_ids; *compatible_id; compatible_id += wcslen(compatible_id) + 1) { + for (wchar_t* compatible_id = compatible_ids; *compatible_id; compatible_id += HIDAPI_WCSLEN(compatible_id) + 1) { /* Normalize to upper case */ hid_internal_towupper(compatible_id); /* USB devices https://docs.microsoft.com/windows-hardware/drivers/hid/plug-and-play-support https://docs.microsoft.com/windows-hardware/drivers/install/standard-usb-identifiers */ - if (wcsstr(compatible_id, L"USB") != NULL) { + if (HIDAPI_WCSSTR(compatible_id, L"USB") != NULL) { result.bus_type = HID_API_BUS_USB; break; } /* Bluetooth devices https://docs.microsoft.com/windows-hardware/drivers/bluetooth/installing-a-bluetooth-device */ - if (wcsstr(compatible_id, L"BTHENUM") != NULL) { + if (HIDAPI_WCSSTR(compatible_id, L"BTHENUM") != NULL) { result.bus_type = HID_API_BUS_BLUETOOTH; break; } /* Bluetooth LE devices */ - if (wcsstr(compatible_id, L"BTHLEDEVICE") != NULL) { + if (HIDAPI_WCSSTR(compatible_id, L"BTHLEDEVICE") != NULL) { result.bus_type = HID_API_BUS_BLUETOOTH; result.bus_flags |= HID_API_BUS_FLAG_BLE; break; @@ -697,14 +682,14 @@ static hid_internal_detect_bus_type_result hid_internal_detect_bus_type(const wc /* I2C devices https://docs.microsoft.com/windows-hardware/drivers/hid/plug-and-play-support-and-power-management */ - if (wcsstr(compatible_id, L"PNP0C50") != NULL) { + if (HIDAPI_WCSSTR(compatible_id, L"PNP0C50") != NULL) { result.bus_type = HID_API_BUS_I2C; break; } /* SPI devices https://docs.microsoft.com/windows-hardware/drivers/hid/plug-and-play-for-spi */ - if (wcsstr(compatible_id, L"PNP0C51") != NULL) { + if (HIDAPI_WCSSTR(compatible_id, L"PNP0C51") != NULL) { result.bus_type = HID_API_BUS_SPI; break; } @@ -713,8 +698,8 @@ static hid_internal_detect_bus_type_result hid_internal_detect_bus_type(const wc result.dev_node = dev_node; end: - free(device_id); - free(compatible_ids); + HIDAPI_FREE(device_id); + HIDAPI_FREE(compatible_ids); return result; } @@ -723,7 +708,7 @@ static char *hid_internal_UTF16toUTF8(const wchar_t *src) char *dst = NULL; int len = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, src, -1, NULL, 0, NULL, NULL); if (len) { - dst = (char*)calloc(len, sizeof(char)); + dst = (char*)HIDAPI_CALLOC(len, sizeof(char)); if (dst == NULL) { return NULL; } @@ -738,7 +723,7 @@ static wchar_t *hid_internal_UTF8toUTF16(const char *src) wchar_t *dst = NULL; int len = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, src, -1, NULL, 0); if (len) { - dst = (wchar_t*)calloc(len, sizeof(wchar_t)); + dst = (wchar_t*)HIDAPI_CALLOC(len, sizeof(wchar_t)); if (dst == NULL) { return NULL; } @@ -760,7 +745,7 @@ static struct hid_device_info *hid_internal_get_device_info(const wchar_t *path, hid_internal_detect_bus_type_result detect_bus_type_result; /* Create the record. */ - dev = (struct hid_device_info*)calloc(1, sizeof(struct hid_device_info)); + dev = (struct hid_device_info*)HIDAPI_CALLOC(1, sizeof(struct hid_device_info)); if (dev == NULL) { return NULL; @@ -802,17 +787,17 @@ static struct hid_device_info *hid_internal_get_device_info(const wchar_t *path, /* Serial Number */ string[0] = L'\0'; HidD_GetSerialNumberString(handle, string, size); - dev->serial_number = _wcsdup(string); + dev->serial_number = HIDAPI_WCSDUP(string); /* Manufacturer String */ string[0] = L'\0'; HidD_GetManufacturerString(handle, string, size); - dev->manufacturer_string = _wcsdup(string); + dev->manufacturer_string = HIDAPI_WCSDUP(string); /* Product String */ string[0] = L'\0'; HidD_GetProductString(handle, string, size); - dev->product_string = _wcsdup(string); + dev->product_string = HIDAPI_WCSDUP(string); /* now, the portion that depends on string descriptors */ switch (dev->bus_type) { @@ -865,10 +850,10 @@ struct hid_device_info HID_API_EXPORT * HID_API_CALL hid_enumerate(unsigned shor } if (device_interface_list != NULL) { - free(device_interface_list); + HIDAPI_FREE(device_interface_list); } - device_interface_list = (wchar_t*)calloc(len, sizeof(wchar_t)); + device_interface_list = (wchar_t*)HIDAPI_CALLOC(len, sizeof(wchar_t)); if (device_interface_list == NULL) { register_global_error(L"Failed to allocate memory for HID device interface list"); return NULL; @@ -884,7 +869,7 @@ struct hid_device_info HID_API_EXPORT * HID_API_CALL hid_enumerate(unsigned shor } /* Iterate over each device interface in the HID class, looking for the right one. */ - for (wchar_t* device_interface = device_interface_list; *device_interface; device_interface += wcslen(device_interface) + 1) { + for (wchar_t* device_interface = device_interface_list; *device_interface; device_interface += HIDAPI_WCSLEN(device_interface) + 1) { HANDLE device_handle = INVALID_HANDLE_VALUE; HIDD_ATTRIBUTES attrib; @@ -937,7 +922,7 @@ struct hid_device_info HID_API_EXPORT * HID_API_CALL hid_enumerate(unsigned shor } end_of_function: - free(device_interface_list); + HIDAPI_FREE(device_interface_list); return root; } @@ -948,11 +933,11 @@ void HID_API_EXPORT HID_API_CALL hid_free_enumeration(struct hid_device_info *d struct hid_device_info *d = devs; while (d) { struct hid_device_info *next = d->next; - free(d->path); - free(d->serial_number); - free(d->manufacturer_string); - free(d->product_string); - free(d); + HIDAPI_FREE(d->path); + HIDAPI_FREE(d->serial_number); + HIDAPI_FREE(d->manufacturer_string); + HIDAPI_FREE(d->product_string); + HIDAPI_FREE(d); d = next; } } @@ -976,7 +961,7 @@ HID_API_EXPORT hid_device * HID_API_CALL hid_open(unsigned short vendor_id, unsi if (cur_dev->vendor_id == vendor_id && cur_dev->product_id == product_id) { if (serial_number) { - if (cur_dev->serial_number && wcscmp(serial_number, cur_dev->serial_number) == 0) { + if (cur_dev->serial_number && HIDAPI_WCSCMP(serial_number, cur_dev->serial_number) == 0) { path_to_open = cur_dev->path; break; } @@ -1069,11 +1054,11 @@ HID_API_EXPORT hid_device * HID_API_CALL hid_open_path(const char *path) dev->output_report_length = caps.OutputReportByteLength; dev->input_report_length = caps.InputReportByteLength; dev->feature_report_length = caps.FeatureReportByteLength; - dev->read_buf = (char*) malloc(dev->input_report_length); + dev->read_buf = (char*) HIDAPI_MALLOC(dev->input_report_length); dev->device_info = hid_internal_get_device_info(interface_path, dev->device_handle); end_of_function: - free(interface_path); + HIDAPI_FREE(interface_path); if (device_handle != INVALID_HANDLE_VALUE) { CloseHandle(device_handle); @@ -1118,7 +1103,7 @@ int HID_API_EXPORT HID_API_CALL hid_write(hid_device *dev, const unsigned char * buf = (unsigned char *) data; } else { if (dev->write_buf == NULL) { - dev->write_buf = (unsigned char *) malloc(dev->output_report_length); + dev->write_buf = (unsigned char *) HIDAPI_MALLOC(dev->output_report_length); if (dev->write_buf == NULL) { register_string_error(dev, L"hid_write/malloc"); @@ -1127,8 +1112,8 @@ int HID_API_EXPORT HID_API_CALL hid_write(hid_device *dev, const unsigned char * } buf = dev->write_buf; - memcpy(buf, data, length); - memset(buf + length, 0, dev->output_report_length - length); + HIDAPI_MEMCPY(buf, data, length); + HIDAPI_MEMSET(buf + length, 0, dev->output_report_length - length); length = dev->output_report_length; } @@ -1201,7 +1186,7 @@ int HID_API_EXPORT HID_API_CALL hid_read_timeout(hid_device *dev, unsigned char if (!dev->read_pending) { /* Start an Overlapped I/O read. */ dev->read_pending = TRUE; - memset(dev->read_buf, 0, dev->input_report_length); + HIDAPI_MEMSET(dev->read_buf, 0, dev->input_report_length); ResetEvent(ev); res = ReadFile(dev->device_handle, dev->read_buf, (DWORD) dev->input_report_length, &bytes_read, &dev->ol); @@ -1254,12 +1239,12 @@ int HID_API_EXPORT HID_API_CALL hid_read_timeout(hid_device *dev, unsigned char HID spec, we'll skip over this byte. */ bytes_read--; copy_len = length > bytes_read ? bytes_read : length; - memcpy(data, dev->read_buf+1, copy_len); + HIDAPI_MEMCPY(data, dev->read_buf+1, copy_len); } else { /* Copy the whole buffer, report number and all. */ copy_len = length > bytes_read ? bytes_read : length; - memcpy(data, dev->read_buf, copy_len); + HIDAPI_MEMCPY(data, dev->read_buf, copy_len); } } if (!res) { @@ -1349,7 +1334,7 @@ int HID_API_EXPORT HID_API_CALL hid_send_feature_report(hid_device *dev, const u length_to_send = length; } else { if (dev->feature_buf == NULL) { - dev->feature_buf = (unsigned char *) malloc(dev->feature_report_length); + dev->feature_buf = (unsigned char *) HIDAPI_MALLOC(dev->feature_report_length); if (dev->feature_buf == NULL) { register_string_error(dev, L"hid_send_feature_report/malloc"); @@ -1358,8 +1343,8 @@ int HID_API_EXPORT HID_API_CALL hid_send_feature_report(hid_device *dev, const u } buf = dev->feature_buf; - memcpy(buf, data, length); - memset(buf + length, 0, dev->feature_report_length - length); + HIDAPI_MEMCPY(buf, data, length); + HIDAPI_MEMSET(buf + length, 0, dev->feature_report_length - length); length_to_send = dev->feature_report_length; } @@ -1379,7 +1364,7 @@ static int hid_get_report(hid_device *dev, DWORD report_type, unsigned char *dat DWORD bytes_returned = 0; OVERLAPPED ol; - memset(&ol, 0, sizeof(ol)); + HIDAPI_MEMSET(&ol, 0, sizeof(ol)); if (!data || !length) { register_string_error(dev, L"Zero buffer/length"); @@ -1450,7 +1435,7 @@ int HID_API_EXPORT HID_API_CALL hid_send_output_report(hid_device* dev, const un length_to_send = length; } else { if (dev->write_buf == NULL) { - dev->write_buf = (unsigned char *) malloc(dev->output_report_length); + dev->write_buf = (unsigned char *) HIDAPI_MALLOC(dev->output_report_length); if (dev->write_buf == NULL) { register_string_error(dev, L"hid_send_output_report/malloc"); @@ -1459,8 +1444,8 @@ int HID_API_EXPORT HID_API_CALL hid_send_output_report(hid_device* dev, const un } buf = dev->write_buf; - memcpy(buf, data, length); - memset(buf + length, 0, dev->output_report_length - length); + HIDAPI_MEMCPY(buf, data, length); + HIDAPI_MEMSET(buf + length, 0, dev->output_report_length - length); length_to_send = dev->output_report_length; } @@ -1633,8 +1618,8 @@ int HID_API_EXPORT_CALL hid_winapi_get_container_id(hid_device *dev, GUID *conta register_string_error(dev, L"Failed to read ContainerId property from device node"); end: - free(interface_path); - free(device_id); + HIDAPI_FREE(interface_path); + HIDAPI_FREE(device_id); return cr == CR_SUCCESS ? 0 : -1; } diff --git a/windows/hidapi_descriptor_reconstruct.c b/windows/hidapi_descriptor_reconstruct.c index f771f62a8..dc83d1726 100644 --- a/windows/hidapi_descriptor_reconstruct.c +++ b/windows/hidapi_descriptor_reconstruct.c @@ -18,6 +18,8 @@ ********************************************************/ #include "hidapi_descriptor_reconstruct.h" +#include "hidapi_winapi_crt.h" + /** * @brief References to report descriptor buffer. * @@ -140,7 +142,7 @@ static struct rd_main_item_node * rd_append_main_item_node(int first_bit, int la list = &(*list)->next; } - new_list_node = (struct rd_main_item_node *)malloc(sizeof(*new_list_node)); // Create new list entry + new_list_node = (struct rd_main_item_node *)HIDAPI_MALLOC(sizeof(*new_list_node)); // Create new list entry new_list_node->FirstBit = first_bit; new_list_node->LastBit = last_bit; new_list_node->TypeOfNode = type_of_node; @@ -183,7 +185,7 @@ int hid_winapi_descriptor_reconstruct_pp_data(void *preparsed_data, unsigned cha hidp_preparsed_data *pp_data = (hidp_preparsed_data *) preparsed_data; // Check if MagicKey is correct, to ensure that pp_data points to an valid preparse data structure - if (memcmp(pp_data->MagicKey, "HidP KDR", 8) != 0) { + if (HIDAPI_MEMCMP(pp_data->MagicKey, "HidP KDR", 8) != 0) { return -1; } @@ -203,13 +205,13 @@ int hid_winapi_descriptor_reconstruct_pp_data(void *preparsed_data, unsigned cha // Allocate memory and initialize lookup table rd_bit_range ****coll_bit_range; - coll_bit_range = (rd_bit_range ****)malloc(pp_data->NumberLinkCollectionNodes * sizeof(*coll_bit_range)); + coll_bit_range = (rd_bit_range ****)HIDAPI_MALLOC(pp_data->NumberLinkCollectionNodes * sizeof(*coll_bit_range)); for (USHORT collection_node_idx = 0; collection_node_idx < pp_data->NumberLinkCollectionNodes; collection_node_idx++) { - coll_bit_range[collection_node_idx] = (rd_bit_range ***)malloc(256 * sizeof(*coll_bit_range[0])); // 256 possible report IDs (incl. 0x00) + coll_bit_range[collection_node_idx] = (rd_bit_range ***)HIDAPI_MALLOC(256 * sizeof(*coll_bit_range[0])); // 256 possible report IDs (incl. 0x00) for (int reportid_idx = 0; reportid_idx < 256; reportid_idx++) { - coll_bit_range[collection_node_idx][reportid_idx] = (rd_bit_range **)malloc(NUM_OF_HIDP_REPORT_TYPES * sizeof(*coll_bit_range[0][0])); + coll_bit_range[collection_node_idx][reportid_idx] = (rd_bit_range **)HIDAPI_MALLOC(NUM_OF_HIDP_REPORT_TYPES * sizeof(*coll_bit_range[0][0])); for (int rt_idx = 0; rt_idx < NUM_OF_HIDP_REPORT_TYPES; rt_idx++) { - coll_bit_range[collection_node_idx][reportid_idx][rt_idx] = (rd_bit_range *)malloc(sizeof(rd_bit_range)); + coll_bit_range[collection_node_idx][reportid_idx][rt_idx] = (rd_bit_range *)HIDAPI_MALLOC(sizeof(rd_bit_range)); coll_bit_range[collection_node_idx][reportid_idx][rt_idx]->FirstBit = -1; coll_bit_range[collection_node_idx][reportid_idx][rt_idx]->LastBit = -1; } @@ -241,12 +243,12 @@ int hid_winapi_descriptor_reconstruct_pp_data(void *preparsed_data, unsigned cha // coll_number_of_direct_childs[COLLECTION_INDEX] // ************************************************************************* int max_coll_level = 0; - int *coll_levels = (int *)malloc(pp_data->NumberLinkCollectionNodes * sizeof(coll_levels[0])); - int *coll_number_of_direct_childs = (int *)malloc(pp_data->NumberLinkCollectionNodes * sizeof(coll_number_of_direct_childs[0])); - memset(coll_levels, -1, - pp_data->NumberLinkCollectionNodes * sizeof(coll_levels[0])); - memset(coll_number_of_direct_childs, 0, - pp_data->NumberLinkCollectionNodes * sizeof(coll_number_of_direct_childs[0])); + int *coll_levels = (int *)HIDAPI_MALLOC(pp_data->NumberLinkCollectionNodes * sizeof(coll_levels[0])); + int *coll_number_of_direct_childs = (int *)HIDAPI_MALLOC(pp_data->NumberLinkCollectionNodes * sizeof(coll_number_of_direct_childs[0])); + HIDAPI_MEMSET(coll_levels, -1, + pp_data->NumberLinkCollectionNodes * sizeof(coll_levels[0])); + HIDAPI_MEMSET(coll_number_of_direct_childs, 0, + pp_data->NumberLinkCollectionNodes * sizeof(coll_number_of_direct_childs[0])); { int actual_coll_level = 0; @@ -307,9 +309,9 @@ int hid_winapi_descriptor_reconstruct_pp_data(void *preparsed_data, unsigned cha // Determine child collection order of the whole hierarchy, based on previously determined bit ranges // and store it this index coll_child_order[COLLECTION_INDEX][DIRECT_CHILD_INDEX] // ************************************************************************************************** - USHORT **coll_child_order = (USHORT **)malloc(pp_data->NumberLinkCollectionNodes * sizeof(*coll_child_order)); + USHORT **coll_child_order = (USHORT **)HIDAPI_MALLOC(pp_data->NumberLinkCollectionNodes * sizeof(*coll_child_order)); { - BOOLEAN *coll_parsed_flag = (BOOLEAN *)malloc(pp_data->NumberLinkCollectionNodes * sizeof(coll_parsed_flag[0])); + BOOLEAN *coll_parsed_flag = (BOOLEAN *)HIDAPI_MALLOC(pp_data->NumberLinkCollectionNodes * sizeof(coll_parsed_flag[0])); for (USHORT collection_node_idx = 0; collection_node_idx < pp_data->NumberLinkCollectionNodes; collection_node_idx++) { coll_parsed_flag[collection_node_idx] = FALSE; } @@ -319,7 +321,7 @@ int hid_winapi_descriptor_reconstruct_pp_data(void *preparsed_data, unsigned cha if ((coll_number_of_direct_childs[collection_node_idx] != 0) && (coll_parsed_flag[link_collection_nodes[collection_node_idx].FirstChild] == FALSE)) { coll_parsed_flag[link_collection_nodes[collection_node_idx].FirstChild] = TRUE; - coll_child_order[collection_node_idx] = (USHORT *)malloc((coll_number_of_direct_childs[collection_node_idx]) * sizeof(*coll_child_order[0])); + coll_child_order[collection_node_idx] = (USHORT *)HIDAPI_MALLOC((coll_number_of_direct_childs[collection_node_idx]) * sizeof(*coll_child_order[0])); { // Create list of child collection indices @@ -369,7 +371,7 @@ int hid_winapi_descriptor_reconstruct_pp_data(void *preparsed_data, unsigned cha } } } - free(coll_parsed_flag); + HIDAPI_FREE(coll_parsed_flag); } @@ -378,12 +380,12 @@ int hid_winapi_descriptor_reconstruct_pp_data(void *preparsed_data, unsigned cha // *************************************************************************************** struct rd_main_item_node *main_item_list = NULL; // List root // Lookup table to find the Collection items in the list by index - struct rd_main_item_node **coll_begin_lookup = (struct rd_main_item_node **)malloc(pp_data->NumberLinkCollectionNodes * sizeof(*coll_begin_lookup)); - struct rd_main_item_node **coll_end_lookup = (struct rd_main_item_node **)malloc(pp_data->NumberLinkCollectionNodes * sizeof(*coll_end_lookup)); + struct rd_main_item_node **coll_begin_lookup = (struct rd_main_item_node **)HIDAPI_MALLOC(pp_data->NumberLinkCollectionNodes * sizeof(*coll_begin_lookup)); + struct rd_main_item_node **coll_end_lookup = (struct rd_main_item_node **)HIDAPI_MALLOC(pp_data->NumberLinkCollectionNodes * sizeof(*coll_end_lookup)); { - int *coll_last_written_child = (int *)malloc(pp_data->NumberLinkCollectionNodes * sizeof(coll_last_written_child[0])); - memset(coll_last_written_child, -1, - pp_data->NumberLinkCollectionNodes * sizeof(coll_last_written_child[0])); + int *coll_last_written_child = (int *)HIDAPI_MALLOC(pp_data->NumberLinkCollectionNodes * sizeof(coll_last_written_child[0])); + HIDAPI_MEMSET(coll_last_written_child, -1, + pp_data->NumberLinkCollectionNodes * sizeof(coll_last_written_child[0])); int actual_coll_level = 0; USHORT collection_node_idx = 0; @@ -456,7 +458,7 @@ int hid_winapi_descriptor_reconstruct_pp_data(void *preparsed_data, unsigned cha collection_node_idx = link_collection_nodes[collection_node_idx].Parent; } } - free(coll_last_written_child); + HIDAPI_FREE(coll_last_written_child); } @@ -527,8 +529,8 @@ int hid_winapi_descriptor_reconstruct_pp_data(void *preparsed_data, unsigned cha { int last_bit_position[NUM_OF_HIDP_REPORT_TYPES][256]; struct rd_main_item_node *last_report_item_lookup[NUM_OF_HIDP_REPORT_TYPES][256]; - memset(last_bit_position, -1, sizeof(last_bit_position)); - memset(last_report_item_lookup, 0, sizeof(last_report_item_lookup)); /* fill with NULL pointers */ + HIDAPI_MEMSET(last_bit_position, -1, sizeof(last_bit_position)); + HIDAPI_MEMSET(last_report_item_lookup, 0, sizeof(last_report_item_lookup)); /* fill with NULL pointers */ BOOLEAN devicehasReportIDs = FALSE; struct rd_main_item_node *list = main_item_list; // List root; @@ -996,7 +998,7 @@ int hid_winapi_descriptor_reconstruct_pp_data(void *preparsed_data, unsigned cha // Go to next item in main_item_list and free the memory of the actual item struct rd_main_item_node *main_item_list_prev = main_item_list; main_item_list = main_item_list->next; - free(main_item_list_prev); + HIDAPI_FREE(main_item_list_prev); } // Free multidimensionable array: coll_bit_range[COLLECTION_INDEX][REPORT_ID][INPUT/OUTPUT/FEATURE] @@ -1004,21 +1006,21 @@ int hid_winapi_descriptor_reconstruct_pp_data(void *preparsed_data, unsigned cha for (USHORT collection_node_idx = 0; collection_node_idx < pp_data->NumberLinkCollectionNodes; collection_node_idx++) { for (int reportid_idx = 0; reportid_idx < 256; reportid_idx++) { for (int rt_idx = 0; rt_idx < NUM_OF_HIDP_REPORT_TYPES; rt_idx++) { - free(coll_bit_range[collection_node_idx][reportid_idx][rt_idx]); + HIDAPI_FREE(coll_bit_range[collection_node_idx][reportid_idx][rt_idx]); } - free(coll_bit_range[collection_node_idx][reportid_idx]); + HIDAPI_FREE(coll_bit_range[collection_node_idx][reportid_idx]); } - free(coll_bit_range[collection_node_idx]); - if (coll_number_of_direct_childs[collection_node_idx] != 0) free(coll_child_order[collection_node_idx]); + HIDAPI_FREE(coll_bit_range[collection_node_idx]); + if (coll_number_of_direct_childs[collection_node_idx] != 0) HIDAPI_FREE(coll_child_order[collection_node_idx]); } - free(coll_bit_range); - free(coll_child_order); + HIDAPI_FREE(coll_bit_range); + HIDAPI_FREE(coll_child_order); // Free one dimensional arrays - free(coll_begin_lookup); - free(coll_end_lookup); - free(coll_levels); - free(coll_number_of_direct_childs); + HIDAPI_FREE(coll_begin_lookup); + HIDAPI_FREE(coll_end_lookup); + HIDAPI_FREE(coll_levels); + HIDAPI_FREE(coll_number_of_direct_childs); return (int) rpt_desc.byte_idx; } diff --git a/windows/hidapi_winapi_crt.h b/windows/hidapi_winapi_crt.h new file mode 100644 index 000000000..96844744e --- /dev/null +++ b/windows/hidapi_winapi_crt.h @@ -0,0 +1,204 @@ +/******************************************************* + HIDAPI - Multi-Platform library for + communication with HID devices. + + libusb/hidapi Team + + Copyright 2026, All Rights Reserved. + + At the discretion of the user of this library, + this software may be licensed under the terms of the + GNU General Public License v3, a BSD-Style license, or the + original HIDAPI license as outlined in the LICENSE.txt, + LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt + files located at the root of the source distribution. + These files may also be found in the public source + code repository located at: + https://github.com/libusb/hidapi . +********************************************************/ + +#ifndef HIDAPI_WINAPI_CRT_H__ +#define HIDAPI_WINAPI_CRT_H__ + +#ifndef HIDAPI_NO_CRT + +#include +#include +#include +#include + +/* MSVC secure CRT (VS2005+) provides swprintf_s/wcsncpy_s. + Older MSVC and GCC/MinGW/Cygwin use the classic variants. */ +#if defined(_MSC_VER) && (_MSC_VER >= 1400) +#define HIDAPI_SWPRINTF swprintf_s +#define HIDAPI_WCSNCPY(dest, dest_count, src) wcsncpy_s((dest), (dest_count), (src), _TRUNCATE) +#else +#define HIDAPI_SWPRINTF swprintf +#define HIDAPI_WCSNCPY(dest, dest_count, src) wcsncpy((dest), (src), (dest_count)) +#endif + +static inline void hid_internal_towupper(wchar_t *string) +{ + for (wchar_t *p = string; *p; ++p) + *p = (wchar_t)towupper(*p); +} + +#define HIDAPI_MALLOC(n) malloc(n) +#define HIDAPI_CALLOC(n, size) calloc((n), (size)) +#define HIDAPI_FREE(p) free(p) +#define HIDAPI_MEMCPY(dest, src, bytes) memcpy((dest), (src), (bytes)) +#define HIDAPI_MEMSET(dest, value, bytes) memset((dest), (value), (bytes)) +#define HIDAPI_MEMCMP(lhs, rhs, bytes) memcmp((lhs), (rhs), (bytes)) +#define HIDAPI_WCSLEN(s) wcslen(s) +#define HIDAPI_WCSCMP(lhs, rhs) wcscmp((lhs), (rhs)) +#define HIDAPI_WCSSTR(haystack, needle) wcsstr((haystack), (needle)) +#define HIDAPI_WCSTOL_HEX(s, end) wcstol((s), (end), 16) +#ifdef __CYGWIN__ +#define HIDAPI_WCSDUP(s) wcsdup(s) +#else +#define HIDAPI_WCSDUP(s) _wcsdup(s) +#endif +#define HIDAPI_STRDUP(s) _strdup(s) + +#else /* HIDAPI_NO_CRT */ + +#include +#include +#include + +static inline void hid_internal_towupper(wchar_t *string) +{ + CharUpperW(string); +} + +static inline void *hid_internal_malloc(size_t bytes) +{ + return HeapAlloc(GetProcessHeap(), 0, bytes ? bytes : 1); +} + +static inline void *hid_internal_calloc(size_t count, size_t size) +{ + size_t bytes; + + if (count != 0 && size > SIZE_MAX / count) + return NULL; + + bytes = count * size; + return HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, bytes ? bytes : 1); +} + +static inline void hid_internal_free(void *ptr) +{ + if (ptr) + HeapFree(GetProcessHeap(), 0, ptr); +} + +#if (defined(_M_IX86) || defined(_M_X64)) && defined(_MSC_VER) +#include +#define HIDAPI_WINAPI_HAVE_MSVC_MEM_INTRIN +#endif + +static inline void *hid_internal_memcpy(void *dest, const void *src, size_t bytes) +{ +#ifdef HIDAPI_WINAPI_HAVE_MSVC_MEM_INTRIN + __movsb((unsigned char *)dest, (const unsigned char *)src, bytes); +#else + volatile unsigned char *d = (volatile unsigned char *)dest; + const unsigned char *s = (const unsigned char *)src; + while (bytes--) + *d++ = *s++; +#endif + return dest; +} + +static inline void *hid_internal_memset(void *dest, int value, size_t bytes) +{ +/* clang-cl lowers __stosb to external memset, which no-CRT builds cannot use. */ +#if defined(HIDAPI_WINAPI_HAVE_MSVC_MEM_INTRIN) && !defined(__clang__) + __stosb((unsigned char *)dest, (unsigned char)value, bytes); +#else + volatile unsigned char *d = (volatile unsigned char *)dest; + while (bytes--) + *d++ = (unsigned char)value; +#endif + return dest; +} + +#undef HIDAPI_WINAPI_HAVE_MSVC_MEM_INTRIN + +static inline int hid_internal_memcmp(const void *lhs, const void *rhs, size_t bytes) +{ + const volatile unsigned char *a = (const volatile unsigned char *)lhs; + const volatile unsigned char *b = (const volatile unsigned char *)rhs; + while (bytes--) { + if (*a != *b) + return *a < *b ? -1 : 1; + ++a; + ++b; + } + return 0; +} + +static inline void *hid_internal_dup(const void *src, size_t bytes) +{ + void *dest = hid_internal_malloc(bytes); + if (dest) + hid_internal_memcpy(dest, src, bytes); + return dest; +} + +static inline char *hid_internal_strdup(const char *src) +{ + return (char *)hid_internal_dup(src, (size_t)lstrlenA(src) + 1); +} + +static inline wchar_t *hid_internal_wcsdup(const wchar_t *src) +{ + return (wchar_t *)hid_internal_dup(src, ((size_t)lstrlenW(src) + 1) * sizeof(wchar_t)); +} + +static inline int hid_internal_wcscmp(const wchar_t *lhs, const wchar_t *rhs) +{ + int result = CompareStringOrdinal(lhs, -1, rhs, -1, FALSE); + if (result == CSTR_EQUAL) + return 0; + return result == CSTR_LESS_THAN ? -1 : 1; +} + +static inline long hid_internal_wcstol_hex(const wchar_t *string, wchar_t **endptr) +{ + long value = 0; + const wchar_t *p = string; + + for (;; ++p) { + wchar_t c = *p; + int digit; + if (c >= L'0' && c <= L'9') digit = c - L'0'; + else if (c >= L'A' && c <= L'F') digit = c - L'A' + 10; + else if (c >= L'a' && c <= L'f') digit = c - L'a' + 10; + else break; + value = (value << 4) | digit; + } + *endptr = (wchar_t *)p; + return value; +} + +#define HIDAPI_MALLOC(n) hid_internal_malloc(n) +#define HIDAPI_CALLOC(n, size) hid_internal_calloc((n), (size)) +#define HIDAPI_FREE(p) hid_internal_free(p) +#define HIDAPI_MEMCPY(dest, src, bytes) hid_internal_memcpy((dest), (src), (bytes)) +#define HIDAPI_MEMSET(dest, value, bytes) hid_internal_memset((dest), (value), (bytes)) +#define HIDAPI_MEMCMP(lhs, rhs, bytes) hid_internal_memcmp((lhs), (rhs), (bytes)) +#define HIDAPI_WCSLEN(s) ((size_t)lstrlenW(s)) +#define HIDAPI_WCSCMP(lhs, rhs) hid_internal_wcscmp((lhs), (rhs)) +#define HIDAPI_WCSSTR(haystack, needle) StrStrW((haystack), (needle)) +#define HIDAPI_WCSTOL_HEX(s, end) hid_internal_wcstol_hex((s), (end)) +#define HIDAPI_WCSDUP(s) hid_internal_wcsdup(s) +#define HIDAPI_STRDUP(s) hid_internal_strdup(s) +#define HIDAPI_SWPRINTF(dest, count, ...) wnsprintfW((dest), (int)(count), __VA_ARGS__) +#define HIDAPI_WCSNCPY(dest, dest_count, src) lstrcpynW((dest), (src), (int)(dest_count)) + + +#endif /* HIDAPI_NO_CRT */ + +#endif /* HIDAPI_WINAPI_CRT_H__ */ diff --git a/windows/test/no_crt/CMakeLists.txt b/windows/test/no_crt/CMakeLists.txt new file mode 100644 index 000000000..975ab9575 --- /dev/null +++ b/windows/test/no_crt/CMakeLists.txt @@ -0,0 +1,74 @@ +cmake_minimum_required(VERSION 3.20) +project(hidapi_no_crt_init_probe C) + +if(NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE) +endif() + +if(NOT HIDAPI_SOURCE_DIR) + message(FATAL_ERROR "HIDAPI_SOURCE_DIR is required") +endif() +if(NOT HIDAPI_LIBRARY) + message(FATAL_ERROR "HIDAPI_LIBRARY is required") +endif() + +set(PROBE_INIT_SOURCE "${CMAKE_CURRENT_LIST_DIR}/init_probe.c") +set(PROBE_MEM_SOURCE "${CMAKE_CURRENT_LIST_DIR}/mem_probe.c") +set(PROBE_INCLUDES "${HIDAPI_SOURCE_DIR}/hidapi") + +add_library(hidapi_no_crt STATIC IMPORTED) +set_target_properties(hidapi_no_crt PROPERTIES + IMPORTED_LOCATION "${HIDAPI_LIBRARY}" +) + +add_executable(no_crt_init_probe "${PROBE_INIT_SOURCE}") +target_include_directories(no_crt_init_probe PRIVATE "${PROBE_INCLUDES}") +target_compile_definitions(no_crt_init_probe PRIVATE HID_API_NO_EXPORT_DEFINE) +target_link_libraries(no_crt_init_probe PRIVATE + hidapi_no_crt + kernel32 + user32 + shlwapi +) + +add_executable(no_crt_mem_probe "${PROBE_MEM_SOURCE}") +target_include_directories(no_crt_mem_probe PRIVATE "${PROBE_INCLUDES}") +target_compile_definitions(no_crt_mem_probe PRIVATE + HIDAPI_NO_CRT + HID_API_NO_EXPORT_DEFINE +) +target_link_libraries(no_crt_mem_probe PRIVATE + kernel32 + user32 + shlwapi +) + +if(MSVC OR CMAKE_C_SIMULATE_ID STREQUAL "MSVC") + target_compile_options(no_crt_init_probe PRIVATE /GS- /Gs9999999) + target_compile_options(no_crt_mem_probe PRIVATE /GS- /Gs9999999) + target_link_options(no_crt_init_probe PRIVATE + /NODEFAULTLIB + /ENTRY:mainCRTStartup + /SUBSYSTEM:CONSOLE + ) + target_link_options(no_crt_mem_probe PRIVATE + /NODEFAULTLIB + /ENTRY:mainCRTStartup + /SUBSYSTEM:CONSOLE + ) +elseif(MINGW) + target_compile_options(no_crt_init_probe PRIVATE -mno-stack-arg-probe) + target_compile_options(no_crt_mem_probe PRIVATE -mno-stack-arg-probe) + target_link_options(no_crt_init_probe PRIVATE + -nostdlib + -Wl,--entry=mainCRTStartup + -Wl,--subsystem,console + ) + target_link_options(no_crt_mem_probe PRIVATE + -nostdlib + -Wl,--entry=mainCRTStartup + -Wl,--subsystem,console + ) +else() + message(FATAL_ERROR "Unsupported no-CRT toolchain") +endif() diff --git a/windows/test/no_crt/init_probe.c b/windows/test/no_crt/init_probe.c new file mode 100644 index 000000000..f2c7d8c97 --- /dev/null +++ b/windows/test/no_crt/init_probe.c @@ -0,0 +1,10 @@ +/* Minimal executable entry point for the no-CRT link/runtime check. */ +#include +#include + +void __cdecl mainCRTStartup(void) +{ + if (hid_init() == 0) + hid_exit(); + ExitProcess(0); +} diff --git a/windows/test/no_crt/mem_probe.c b/windows/test/no_crt/mem_probe.c new file mode 100644 index 000000000..b063a7589 --- /dev/null +++ b/windows/test/no_crt/mem_probe.c @@ -0,0 +1,31 @@ +/* Exercise the HIDAPI memory helpers in an amalgamated no-CRT build. */ +#include +#include + +#include "../../hid.c" + +void __cdecl mainCRTStartup(void) +{ + volatile unsigned char src[64]; + volatile unsigned char dst[64]; + unsigned int salt = GetTickCount(); + + for (unsigned int i = 0; i < sizeof(src); i++) + src[i] = (unsigned char)(salt + i * 31u); + + hid_internal_memset((void *)dst, 0xA5, sizeof(dst)); + if (dst[0] != 0xA5 || dst[sizeof(dst) - 1] != 0xA5) + ExitProcess(2); + + hid_internal_memcpy((void *)dst, (const void *)src, sizeof(dst)); + if (hid_internal_memcmp((const void *)dst, (const void *)src, sizeof(dst)) != 0) + ExitProcess(3); + + src[0] ^= 0xFF; + if (hid_internal_memcmp((const void *)dst, (const void *)src, sizeof(dst)) == 0) + ExitProcess(4); + + if (hid_init() == 0) + hid_exit(); + ExitProcess(0); +} From 570a5c8233cbf2695e5faf9dc4bc4797187928b7 Mon Sep 17 00:00:00 2001 From: Ebrahim Date: Thu, 26 Nov 2026 14:35:07 +0330 Subject: [PATCH 02/20] windows: move descriptor lookup tables to the heap Move the two 8x256 descriptor lookup arrays off the stack so the no-CRT build no longer needs stack-probe suppression. Keep /GS- because the security cookie is still required for local SDK structs. Assisted-by: deepseek-harness:deepseek-flash --- windows/CMakeLists.txt | 9 ++------- windows/hidapi_descriptor_reconstruct.c | 11 +++++++---- windows/test/no_crt/CMakeLists.txt | 6 ++---- 3 files changed, 11 insertions(+), 15 deletions(-) diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt index 3b8ba4fcc..68b0c44cf 100644 --- a/windows/CMakeLists.txt +++ b/windows/CMakeLists.txt @@ -37,13 +37,8 @@ if(HIDAPI_NO_CRT) target_compile_definitions(hidapi_winapi PRIVATE HIDAPI_NO_CRT) target_link_libraries(hidapi_winapi PRIVATE shlwapi) if(MSVC) - # The descriptor reconstructor has a large stack frame. Disable stack - # probes and the security cookie so the static library does not need - # __chkstk or __security_cookie from the CRT. - target_compile_options(hidapi_winapi PRIVATE /GS- /Gs9999999) - elseif(MINGW) - # GCC's automatic stack probe would need ___chkstk_ms from the CRT. - target_compile_options(hidapi_winapi PRIVATE -mno-stack-arg-probe) + # The static library does not need __security_cookie from the CRT. + target_compile_options(hidapi_winapi PRIVATE /GS-) endif() endif() diff --git a/windows/hidapi_descriptor_reconstruct.c b/windows/hidapi_descriptor_reconstruct.c index dc83d1726..039fd076a 100644 --- a/windows/hidapi_descriptor_reconstruct.c +++ b/windows/hidapi_descriptor_reconstruct.c @@ -527,10 +527,10 @@ int hid_winapi_descriptor_reconstruct_pp_data(void *preparsed_data, unsigned cha // report descriptors seem to have it, as assumed here. // *********************************************************** { - int last_bit_position[NUM_OF_HIDP_REPORT_TYPES][256]; - struct rd_main_item_node *last_report_item_lookup[NUM_OF_HIDP_REPORT_TYPES][256]; - HIDAPI_MEMSET(last_bit_position, -1, sizeof(last_bit_position)); - HIDAPI_MEMSET(last_report_item_lookup, 0, sizeof(last_report_item_lookup)); /* fill with NULL pointers */ + int (*last_bit_position)[256] = (int (*)[256])HIDAPI_MALLOC(NUM_OF_HIDP_REPORT_TYPES * sizeof(*last_bit_position)); + struct rd_main_item_node *(*last_report_item_lookup)[256] = (struct rd_main_item_node *(*)[256])HIDAPI_MALLOC(NUM_OF_HIDP_REPORT_TYPES * sizeof(*last_report_item_lookup)); + HIDAPI_MEMSET(last_bit_position, -1, NUM_OF_HIDP_REPORT_TYPES * sizeof(*last_bit_position)); + HIDAPI_MEMSET(last_report_item_lookup, 0, NUM_OF_HIDP_REPORT_TYPES * sizeof(*last_report_item_lookup)); /* fill with NULL pointers */ BOOLEAN devicehasReportIDs = FALSE; struct rd_main_item_node *list = main_item_list; // List root; @@ -597,6 +597,9 @@ int hid_winapi_descriptor_reconstruct_pp_data(void *preparsed_data, unsigned cha } } } + + HIDAPI_FREE(last_bit_position); + HIDAPI_FREE(last_report_item_lookup); } diff --git a/windows/test/no_crt/CMakeLists.txt b/windows/test/no_crt/CMakeLists.txt index 975ab9575..e11a46911 100644 --- a/windows/test/no_crt/CMakeLists.txt +++ b/windows/test/no_crt/CMakeLists.txt @@ -44,8 +44,8 @@ target_link_libraries(no_crt_mem_probe PRIVATE ) if(MSVC OR CMAKE_C_SIMULATE_ID STREQUAL "MSVC") - target_compile_options(no_crt_init_probe PRIVATE /GS- /Gs9999999) - target_compile_options(no_crt_mem_probe PRIVATE /GS- /Gs9999999) + target_compile_options(no_crt_init_probe PRIVATE /GS-) + target_compile_options(no_crt_mem_probe PRIVATE /GS-) target_link_options(no_crt_init_probe PRIVATE /NODEFAULTLIB /ENTRY:mainCRTStartup @@ -57,8 +57,6 @@ if(MSVC OR CMAKE_C_SIMULATE_ID STREQUAL "MSVC") /SUBSYSTEM:CONSOLE ) elseif(MINGW) - target_compile_options(no_crt_init_probe PRIVATE -mno-stack-arg-probe) - target_compile_options(no_crt_mem_probe PRIVATE -mno-stack-arg-probe) target_link_options(no_crt_init_probe PRIVATE -nostdlib -Wl,--entry=mainCRTStartup From fd0832d152c9998b45b4a61b95049d00f590d8cc Mon Sep 17 00:00:00 2001 From: Ebrahim Date: Thu, 26 Nov 2026 15:43:07 +0330 Subject: [PATCH 03/20] windows: support CRT-free shared builds Add a custom DllMain and no-default-lib link options for shared HIDAPI_NO_CRT builds, and check the DLL imports/exports in CI. Reproduced the official hidapi-0.16.0 x64 release from tag 750c87a using windows/hidapi.vcxproj (MSBuild Release|x64, /MT static CRT, LTCG): 169,472 bytes, importing only KERNEL32.dll. x64 DLL sizes before/after: Official release (/MT static CRT, LTCG): 169,472 bytes this no-CRT build: MSVC LTCG: 42,496 bytes (-75%) MSVC: 39,424 bytes (-77%) clang-cl: 43,520 bytes (-74%) MinGW: 56,057 bytes (-67%) The regular MSVC /MD build is 42,496 bytes but imports VCRUNTIME140 and the UCRT API sets; the no-CRT builds import only system DLLs. Exact sizes depend on compiler/linker versions and release packaging. Assisted-by: deepseek-harness:deepseek-flash --- .github/workflows/builds.yml | 34 +++++++++++++++++++++++++++ windows/CMakeLists.txt | 18 ++++++++++++-- windows/hidapi_winapi_nocrt_dllmain.c | 10 ++++++++ 3 files changed, 60 insertions(+), 2 deletions(-) create mode 100644 windows/hidapi_winapi_nocrt_dllmain.c diff --git a/.github/workflows/builds.yml b/.github/workflows/builds.yml index 2749d2ad6..a674d8b9a 100644 --- a/.github/workflows/builds.yml +++ b/.github/workflows/builds.yml @@ -424,6 +424,40 @@ jobs: $ok = $false } } + + $sharedBuild = "$build-shared" + cmake -G Ninja ` + -B $sharedBuild ` + -S hidapisrc ` + "-DCMAKE_C_COMPILER=$compiler" ` + -DCMAKE_BUILD_TYPE=Release ` + -DBUILD_SHARED_LIBS=ON ` + -DHIDAPI_NO_CRT=ON ` + -DHIDAPI_WITH_TESTS=OFF ` + -DHIDAPI_BUILD_HIDTEST=OFF + if ($LASTEXITCODE -ne 0) { $ok = $false; continue } + + cmake --build $sharedBuild + if ($LASTEXITCODE -ne 0) { $ok = $false; continue } + + $dll = Get-ChildItem "$sharedBuild\src\windows" -File -Filter '*.dll' | + Select-Object -First 1 + if (-not $dll) { + Write-Host "::error title=$compiler::no-CRT shared DLL not found" + $ok = $false + continue + } + + $deps = dumpbin /nologo /dependents $dll.FullName | Out-String + if ($deps -match '(?i)(vcruntime|ucrtbase|msvcrt|api-ms-win-crt|libgcc|libwinpthread)') { + Write-Host "::error title=$compiler::CRT dependency found in the no-CRT shared DLL" + $ok = $false + } + $exports = dumpbin /nologo /exports $dll.FullName | Out-String + if ($exports -notmatch '(?m)\bhid_init\b') { + Write-Host "::error title=$compiler::hid_init missing from the no-CRT shared DLL" + $ok = $false + } } if (-not $ok) { exit 1 } diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt index 68b0c44cf..69e423c47 100644 --- a/windows/CMakeLists.txt +++ b/windows/CMakeLists.txt @@ -13,6 +13,9 @@ set(SOURCES if(BUILD_SHARED_LIBS) list(APPEND SOURCES hidapi.rc) + if(HIDAPI_NO_CRT) + list(APPEND SOURCES hidapi_winapi_nocrt_dllmain.c) + endif() endif() add_library(hidapi_winapi @@ -35,11 +38,22 @@ target_compile_definitions(hidapi_winapi if(HIDAPI_NO_CRT) target_compile_definitions(hidapi_winapi PRIVATE HIDAPI_NO_CRT) - target_link_libraries(hidapi_winapi PRIVATE shlwapi) + target_link_libraries(hidapi_winapi PRIVATE shlwapi kernel32 user32) if(MSVC) - # The static library does not need __security_cookie from the CRT. + # The library does not need __security_cookie from the CRT. target_compile_options(hidapi_winapi PRIVATE /GS-) endif() + if(BUILD_SHARED_LIBS) + if(MSVC) + target_link_options(hidapi_winapi PRIVATE /NODEFAULTLIB /ENTRY:DllMain) + elseif(MINGW) + target_link_options(hidapi_winapi PRIVATE + -nostdlib + -nodefaultlibs + -Wl,--entry=DllMain + ) + endif() + endif() endif() if(NOT BUILD_SHARED_LIBS) diff --git a/windows/hidapi_winapi_nocrt_dllmain.c b/windows/hidapi_winapi_nocrt_dllmain.c new file mode 100644 index 000000000..b1e7ecfa0 --- /dev/null +++ b/windows/hidapi_winapi_nocrt_dllmain.c @@ -0,0 +1,10 @@ +/* Minimal DLL entry point for the CRT-free shared build. */ +#include + +BOOL WINAPI DllMain(HINSTANCE instance, DWORD reason, LPVOID reserved) +{ + (void)instance; + (void)reason; + (void)reserved; + return TRUE; +} From 7dd840c7f64e7b1b3025be365c79fd9588800bf4 Mon Sep 17 00:00:00 2001 From: Ebrahim Date: Fri, 27 Nov 2026 21:13:04 +0330 Subject: [PATCH 04/20] windows: clarify CRT compatibility and DllMain names Rename the CRT/WinAPI compatibility header to hidapi_winapi_crt_compat.h and the optional CRT-free DLL entry source to hidapi_winapi_dllmain.c. Keep the CRT-free Meson integration out of this patch; it remains CMake-only for now. --- windows/CMakeLists.txt | 4 +-- windows/hid.c | 2 +- windows/hidapi_descriptor_reconstruct.c | 2 +- ...inapi_crt.h => hidapi_winapi_crt_compat.h} | 6 ++-- windows/hidapi_winapi_dllmain.c | 29 +++++++++++++++++++ windows/hidapi_winapi_nocrt_dllmain.c | 10 ------- 6 files changed, 36 insertions(+), 17 deletions(-) rename windows/{hidapi_winapi_crt.h => hidapi_winapi_crt_compat.h} (98%) create mode 100644 windows/hidapi_winapi_dllmain.c delete mode 100644 windows/hidapi_winapi_nocrt_dllmain.c diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt index 69e423c47..aa90cc5c1 100644 --- a/windows/CMakeLists.txt +++ b/windows/CMakeLists.txt @@ -8,13 +8,13 @@ set(SOURCES hidapi_hidclass.h hidapi_hidpi.h hidapi_hidsdi.h - hidapi_winapi_crt.h + hidapi_winapi_crt_compat.h ) if(BUILD_SHARED_LIBS) list(APPEND SOURCES hidapi.rc) if(HIDAPI_NO_CRT) - list(APPEND SOURCES hidapi_winapi_nocrt_dllmain.c) + list(APPEND SOURCES hidapi_winapi_dllmain.c) endif() endif() diff --git a/windows/hid.c b/windows/hid.c index d089eae1f..e02344e22 100644 --- a/windows/hid.c +++ b/windows/hid.c @@ -55,7 +55,7 @@ typedef LONG NTSTATUS; #include "hidapi_hidclass.h" #include "hidapi_hidsdi.h" -#include "hidapi_winapi_crt.h" +#include "hidapi_winapi_crt_compat.h" #ifdef MIN #undef MIN diff --git a/windows/hidapi_descriptor_reconstruct.c b/windows/hidapi_descriptor_reconstruct.c index 039fd076a..ea2cca06b 100644 --- a/windows/hidapi_descriptor_reconstruct.c +++ b/windows/hidapi_descriptor_reconstruct.c @@ -18,7 +18,7 @@ ********************************************************/ #include "hidapi_descriptor_reconstruct.h" -#include "hidapi_winapi_crt.h" +#include "hidapi_winapi_crt_compat.h" /** * @brief References to report descriptor buffer. diff --git a/windows/hidapi_winapi_crt.h b/windows/hidapi_winapi_crt_compat.h similarity index 98% rename from windows/hidapi_winapi_crt.h rename to windows/hidapi_winapi_crt_compat.h index 96844744e..2940db844 100644 --- a/windows/hidapi_winapi_crt.h +++ b/windows/hidapi_winapi_crt_compat.h @@ -17,8 +17,8 @@ https://github.com/libusb/hidapi . ********************************************************/ -#ifndef HIDAPI_WINAPI_CRT_H__ -#define HIDAPI_WINAPI_CRT_H__ +#ifndef HIDAPI_WINAPI_CRT_COMPAT_H__ +#define HIDAPI_WINAPI_CRT_COMPAT_H__ #ifndef HIDAPI_NO_CRT @@ -201,4 +201,4 @@ static inline long hid_internal_wcstol_hex(const wchar_t *string, wchar_t **endp #endif /* HIDAPI_NO_CRT */ -#endif /* HIDAPI_WINAPI_CRT_H__ */ +#endif /* HIDAPI_WINAPI_CRT_COMPAT_H__ */ diff --git a/windows/hidapi_winapi_dllmain.c b/windows/hidapi_winapi_dllmain.c new file mode 100644 index 000000000..342ebe165 --- /dev/null +++ b/windows/hidapi_winapi_dllmain.c @@ -0,0 +1,29 @@ +/******************************************************* + HIDAPI - Multi-Platform library for + communication with HID devices. + + libusb/hidapi Team + + Copyright 2026, All Rights Reserved. + + At the discretion of the user of this library, + this software may be licensed under the terms of the + GNU General Public License v3, a BSD-Style license, or the + original HIDAPI license as outlined in the LICENSE.txt, + LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt + files located at the root of the source distribution. + These files may also be found in the public source + code repository located at: + https://github.com/libusb/hidapi . +********************************************************/ + +/* Minimal DLL entry point for the CRT-free shared build. */ +#include + +BOOL WINAPI DllMain(HINSTANCE instance, DWORD reason, LPVOID reserved) +{ + (void)instance; + (void)reason; + (void)reserved; + return TRUE; +} diff --git a/windows/hidapi_winapi_nocrt_dllmain.c b/windows/hidapi_winapi_nocrt_dllmain.c deleted file mode 100644 index b1e7ecfa0..000000000 --- a/windows/hidapi_winapi_nocrt_dllmain.c +++ /dev/null @@ -1,10 +0,0 @@ -/* Minimal DLL entry point for the CRT-free shared build. */ -#include - -BOOL WINAPI DllMain(HINSTANCE instance, DWORD reason, LPVOID reserved) -{ - (void)instance; - (void)reason; - (void)reserved; - return TRUE; -} From 3c92a865773252b974e22501b89d90f05bb7724e Mon Sep 17 00:00:00 2001 From: Ebrahim Date: Fri, 27 Nov 2026 21:34:14 +0330 Subject: [PATCH 05/20] windows: order no-CRT libraries by import usage KERNEL32.dll 26 symbols files, heaps, events, overlapped I/O, code pages, lstrlenW, lstrcpynW, FormatMessageW, etc. SHLWAPI.dll 2 symbols wnsprintfW, StrStrW USER32.dll 1 symbol CharUpperW This does not change behavior; it makes the link declaration reflect which system DLL provides the bulk of the backend's Win32 surface. --- windows/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt index aa90cc5c1..a4cb593df 100644 --- a/windows/CMakeLists.txt +++ b/windows/CMakeLists.txt @@ -38,7 +38,7 @@ target_compile_definitions(hidapi_winapi if(HIDAPI_NO_CRT) target_compile_definitions(hidapi_winapi PRIVATE HIDAPI_NO_CRT) - target_link_libraries(hidapi_winapi PRIVATE shlwapi kernel32 user32) + target_link_libraries(hidapi_winapi PRIVATE kernel32 shlwapi user32) if(MSVC) # The library does not need __security_cookie from the CRT. target_compile_options(hidapi_winapi PRIVATE /GS-) From 34308a0b00643c4c40eb70d4837a5f56ed33db17 Mon Sep 17 00:00:00 2001 From: Ebrahim Date: Sat, 28 Nov 2026 14:34:48 +0330 Subject: [PATCH 06/20] windows: support CRT-free Cygwin builds Apply the shared no-CRT link flags to Cygwin. Without those flags Cygwin's GCC still pulls in the Cygwin runtime. The main advantage is that the CRT-free Cygwin DLL no longer depends on cygwin1.dll: the CMake build is about 57 KB instead of 96 KB and imports only kernel32, shlwapi, and user32. Verified normal and no-CRT builds with Cygwin CMake, MSVC, and MinGW. --- windows/CMakeLists.txt | 2 +- windows/hid.c | 1 - windows/hidapi_winapi_crt_compat.h | 5 ++++- windows/hidapi_winapi_dllmain.c | 8 ++++++++ 4 files changed, 13 insertions(+), 3 deletions(-) diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt index a4cb593df..0f30b9620 100644 --- a/windows/CMakeLists.txt +++ b/windows/CMakeLists.txt @@ -46,7 +46,7 @@ if(HIDAPI_NO_CRT) if(BUILD_SHARED_LIBS) if(MSVC) target_link_options(hidapi_winapi PRIVATE /NODEFAULTLIB /ENTRY:DllMain) - elseif(MINGW) + elseif(MINGW OR CYGWIN) target_link_options(hidapi_winapi PRIVATE -nostdlib -nodefaultlibs diff --git a/windows/hid.c b/windows/hid.c index e02344e22..bbf276f66 100644 --- a/windows/hid.c +++ b/windows/hid.c @@ -46,7 +46,6 @@ typedef LONG NTSTATUS; #ifdef __CYGWIN__ #include -#include #endif /*#define HIDAPI_USE_DDK*/ diff --git a/windows/hidapi_winapi_crt_compat.h b/windows/hidapi_winapi_crt_compat.h index 2940db844..fb4999537 100644 --- a/windows/hidapi_winapi_crt_compat.h +++ b/windows/hidapi_winapi_crt_compat.h @@ -26,6 +26,9 @@ #include #include #include +#ifdef __CYGWIN__ +#include +#endif /* MSVC secure CRT (VS2005+) provides swprintf_s/wcsncpy_s. Older MSVC and GCC/MinGW/Cygwin use the classic variants. */ @@ -62,8 +65,8 @@ static inline void hid_internal_towupper(wchar_t *string) #else /* HIDAPI_NO_CRT */ -#include #include +#include #include static inline void hid_internal_towupper(wchar_t *string) diff --git a/windows/hidapi_winapi_dllmain.c b/windows/hidapi_winapi_dllmain.c index 342ebe165..44a83b4e8 100644 --- a/windows/hidapi_winapi_dllmain.c +++ b/windows/hidapi_winapi_dllmain.c @@ -20,6 +20,10 @@ /* Minimal DLL entry point for the CRT-free shared build. */ #include +#ifdef __cplusplus +extern "C" { +#endif + BOOL WINAPI DllMain(HINSTANCE instance, DWORD reason, LPVOID reserved) { (void)instance; @@ -27,3 +31,7 @@ BOOL WINAPI DllMain(HINSTANCE instance, DWORD reason, LPVOID reserved) (void)reserved; return TRUE; } + +#ifdef __cplusplus +} +#endif From 040267cddb3fef2e5fe73a66552b79788ed0079b Mon Sep 17 00:00:00 2001 From: Ebrahim Date: Sat, 28 Nov 2026 17:59:46 +0330 Subject: [PATCH 07/20] windows: tidy platform includes and no-CRT helpers Use one guarded ntdef include for MinGW and Cygwin, parenthesize all compatibility macro arguments consistently, and add the standard license header to both no-CRT probe sources. --- windows/hid.c | 9 ++++----- windows/hidapi_winapi_crt_compat.h | 22 +++++++++++----------- windows/test/no_crt/init_probe.c | 19 +++++++++++++++++++ windows/test/no_crt/mem_probe.c | 19 +++++++++++++++++++ 4 files changed, 53 insertions(+), 16 deletions(-) diff --git a/windows/hid.c b/windows/hid.c index bbf276f66..3899ba413 100644 --- a/windows/hid.c +++ b/windows/hid.c @@ -38,14 +38,13 @@ extern "C" { typedef LONG NTSTATUS; #endif -#ifdef __MINGW32__ +#if defined(__MINGW32__) || defined(__CYGWIN__) #include -#include -#define WC_ERR_INVALID_CHARS 0x00000080 #endif -#ifdef __CYGWIN__ -#include +#ifdef __MINGW32__ +#include +#define WC_ERR_INVALID_CHARS 0x00000080 #endif /*#define HIDAPI_USE_DDK*/ diff --git a/windows/hidapi_winapi_crt_compat.h b/windows/hidapi_winapi_crt_compat.h index fb4999537..93f78ccb7 100644 --- a/windows/hidapi_winapi_crt_compat.h +++ b/windows/hidapi_winapi_crt_compat.h @@ -46,22 +46,22 @@ static inline void hid_internal_towupper(wchar_t *string) *p = (wchar_t)towupper(*p); } -#define HIDAPI_MALLOC(n) malloc(n) +#define HIDAPI_MALLOC(n) malloc((n)) #define HIDAPI_CALLOC(n, size) calloc((n), (size)) -#define HIDAPI_FREE(p) free(p) +#define HIDAPI_FREE(p) free((p)) #define HIDAPI_MEMCPY(dest, src, bytes) memcpy((dest), (src), (bytes)) #define HIDAPI_MEMSET(dest, value, bytes) memset((dest), (value), (bytes)) #define HIDAPI_MEMCMP(lhs, rhs, bytes) memcmp((lhs), (rhs), (bytes)) -#define HIDAPI_WCSLEN(s) wcslen(s) +#define HIDAPI_WCSLEN(s) wcslen((s)) #define HIDAPI_WCSCMP(lhs, rhs) wcscmp((lhs), (rhs)) #define HIDAPI_WCSSTR(haystack, needle) wcsstr((haystack), (needle)) #define HIDAPI_WCSTOL_HEX(s, end) wcstol((s), (end), 16) #ifdef __CYGWIN__ -#define HIDAPI_WCSDUP(s) wcsdup(s) +#define HIDAPI_WCSDUP(s) wcsdup((s)) #else -#define HIDAPI_WCSDUP(s) _wcsdup(s) +#define HIDAPI_WCSDUP(s) _wcsdup((s)) #endif -#define HIDAPI_STRDUP(s) _strdup(s) +#define HIDAPI_STRDUP(s) _strdup((s)) #else /* HIDAPI_NO_CRT */ @@ -186,18 +186,18 @@ static inline long hid_internal_wcstol_hex(const wchar_t *string, wchar_t **endp return value; } -#define HIDAPI_MALLOC(n) hid_internal_malloc(n) +#define HIDAPI_MALLOC(n) hid_internal_malloc((n)) #define HIDAPI_CALLOC(n, size) hid_internal_calloc((n), (size)) -#define HIDAPI_FREE(p) hid_internal_free(p) +#define HIDAPI_FREE(p) hid_internal_free((p)) #define HIDAPI_MEMCPY(dest, src, bytes) hid_internal_memcpy((dest), (src), (bytes)) #define HIDAPI_MEMSET(dest, value, bytes) hid_internal_memset((dest), (value), (bytes)) #define HIDAPI_MEMCMP(lhs, rhs, bytes) hid_internal_memcmp((lhs), (rhs), (bytes)) -#define HIDAPI_WCSLEN(s) ((size_t)lstrlenW(s)) +#define HIDAPI_WCSLEN(s) ((size_t)lstrlenW((s))) #define HIDAPI_WCSCMP(lhs, rhs) hid_internal_wcscmp((lhs), (rhs)) #define HIDAPI_WCSSTR(haystack, needle) StrStrW((haystack), (needle)) #define HIDAPI_WCSTOL_HEX(s, end) hid_internal_wcstol_hex((s), (end)) -#define HIDAPI_WCSDUP(s) hid_internal_wcsdup(s) -#define HIDAPI_STRDUP(s) hid_internal_strdup(s) +#define HIDAPI_WCSDUP(s) hid_internal_wcsdup((s)) +#define HIDAPI_STRDUP(s) hid_internal_strdup((s)) #define HIDAPI_SWPRINTF(dest, count, ...) wnsprintfW((dest), (int)(count), __VA_ARGS__) #define HIDAPI_WCSNCPY(dest, dest_count, src) lstrcpynW((dest), (src), (int)(dest_count)) diff --git a/windows/test/no_crt/init_probe.c b/windows/test/no_crt/init_probe.c index f2c7d8c97..1b82d7840 100644 --- a/windows/test/no_crt/init_probe.c +++ b/windows/test/no_crt/init_probe.c @@ -1,3 +1,22 @@ +/******************************************************* + HIDAPI - Multi-Platform library for + communication with HID devices. + + libusb/hidapi Team + + Copyright 2026, All Rights Reserved. + + At the discretion of the user of this library, + this software may be licensed under the terms of the + GNU General Public License v3, a BSD-Style license, or the + original HIDAPI license as outlined in the LICENSE.txt, + LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt + files located at the root of the source distribution. + These files may also be found in the public source + code repository located at: + https://github.com/libusb/hidapi . +********************************************************/ + /* Minimal executable entry point for the no-CRT link/runtime check. */ #include #include diff --git a/windows/test/no_crt/mem_probe.c b/windows/test/no_crt/mem_probe.c index b063a7589..d09a0f344 100644 --- a/windows/test/no_crt/mem_probe.c +++ b/windows/test/no_crt/mem_probe.c @@ -1,3 +1,22 @@ +/******************************************************* + HIDAPI - Multi-Platform library for + communication with HID devices. + + libusb/hidapi Team + + Copyright 2026, All Rights Reserved. + + At the discretion of the user of this library, + this software may be licensed under the terms of the + GNU General Public License v3, a BSD-Style license, or the + original HIDAPI license as outlined in the LICENSE.txt, + LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt + files located at the root of the source distribution. + These files may also be found in the public source + code repository located at: + https://github.com/libusb/hidapi . +********************************************************/ + /* Exercise the HIDAPI memory helpers in an amalgamated no-CRT build. */ #include #include From c7fea593e48794daa054eec5f1d78a6febd5efd5 Mon Sep 17 00:00:00 2001 From: Ebrahim Date: Sat, 28 Nov 2026 18:10:58 +0330 Subject: [PATCH 08/20] windows: run no-CRT probe against shared DLL Add optional shared-DLL/import-library inputs to the no-CRT probe project, copy the DLL beside the probe, and run an init smoke test in the no-CRT CI job. This covers loader, custom DllMain, and import-library behavior that import-table checks alone miss. --- .github/workflows/builds.yml | 41 ++++++++++++++++++ windows/test/no_crt/CMakeLists.txt | 69 +++++++++++++++++++----------- 2 files changed, 86 insertions(+), 24 deletions(-) diff --git a/.github/workflows/builds.yml b/.github/workflows/builds.yml index a674d8b9a..55ec08524 100644 --- a/.github/workflows/builds.yml +++ b/.github/workflows/builds.yml @@ -458,6 +458,47 @@ jobs: Write-Host "::error title=$compiler::hid_init missing from the no-CRT shared DLL" $ok = $false } + + $implib = Get-ChildItem "$sharedBuild\src\windows" -File | + Where-Object { $_.Name -eq 'hidapi.lib' -or $_.Name -eq 'libhidapi.dll.a' } | + Select-Object -First 1 + if (-not $implib) { + Write-Host "::error title=$compiler::no-CRT shared import library not found" + $ok = $false + continue + } + + $sharedProbeBuild = "$build\shared-probe" + cmake -G Ninja ` + -B $sharedProbeBuild ` + -S hidapisrc\windows\test\no_crt ` + "-DCMAKE_C_COMPILER=$compiler" ` + -DCMAKE_BUILD_TYPE=Release ` + "-DHIDAPI_SOURCE_DIR=$((Get-Location).Path)\hidapisrc" ` + "-DHIDAPI_LIBRARY=$($lib.FullName)" ` + "-DHIDAPI_SHARED_LIBRARY=$($dll.FullName)" ` + "-DHIDAPI_SHARED_IMPLIB=$($implib.FullName)" + if ($LASTEXITCODE -ne 0) { $ok = $false; continue } + + cmake --build $sharedProbeBuild --target no_crt_shared_init_probe + if ($LASTEXITCODE -ne 0) { $ok = $false; continue } + + $sharedProbePath = Join-Path $sharedProbeBuild "no_crt_shared_init_probe.exe" + $proc = Start-Process -FilePath $sharedProbePath -PassThru + if (-not $proc.WaitForExit(5000)) { + $proc.Kill() + Write-Host "::error title=$compiler/no_crt_shared_init_probe::shared no-CRT probe timed out" + $ok = $false + } elseif ($proc.ExitCode -ne 0) { + Write-Host "::error title=$compiler/no_crt_shared_init_probe::shared no-CRT probe exited with $($proc.ExitCode)" + $ok = $false + } + + $deps = dumpbin /nologo /dependents $sharedProbePath | Out-String + if ($deps -match '(?i)(vcruntime|ucrtbase|msvcrt|api-ms-win-crt|libgcc|libwinpthread)') { + Write-Host "::error title=$compiler/no_crt_shared_init_probe::CRT dependency found in the shared no-CRT probe" + $ok = $false + } } if (-not $ok) { exit 1 } diff --git a/windows/test/no_crt/CMakeLists.txt b/windows/test/no_crt/CMakeLists.txt index e11a46911..10fa11ebf 100644 --- a/windows/test/no_crt/CMakeLists.txt +++ b/windows/test/no_crt/CMakeLists.txt @@ -12,6 +12,9 @@ if(NOT HIDAPI_LIBRARY) message(FATAL_ERROR "HIDAPI_LIBRARY is required") endif() +set(HIDAPI_SHARED_LIBRARY "" CACHE FILEPATH "Optional no-CRT shared DLL") +set(HIDAPI_SHARED_IMPLIB "" CACHE FILEPATH "Import library for HIDAPI_SHARED_LIBRARY") + set(PROBE_INIT_SOURCE "${CMAKE_CURRENT_LIST_DIR}/init_probe.c") set(PROBE_MEM_SOURCE "${CMAKE_CURRENT_LIST_DIR}/mem_probe.c") set(PROBE_INCLUDES "${HIDAPI_SOURCE_DIR}/hidapi") @@ -42,31 +45,49 @@ target_link_libraries(no_crt_mem_probe PRIVATE user32 shlwapi ) - -if(MSVC OR CMAKE_C_SIMULATE_ID STREQUAL "MSVC") - target_compile_options(no_crt_init_probe PRIVATE /GS-) - target_compile_options(no_crt_mem_probe PRIVATE /GS-) - target_link_options(no_crt_init_probe PRIVATE - /NODEFAULTLIB - /ENTRY:mainCRTStartup - /SUBSYSTEM:CONSOLE +if(HIDAPI_SHARED_LIBRARY AND HIDAPI_SHARED_IMPLIB) + add_library(hidapi_no_crt_shared SHARED IMPORTED) + set_target_properties(hidapi_no_crt_shared PROPERTIES + IMPORTED_LOCATION "${HIDAPI_SHARED_LIBRARY}" + IMPORTED_IMPLIB "${HIDAPI_SHARED_IMPLIB}" ) - target_link_options(no_crt_mem_probe PRIVATE - /NODEFAULTLIB - /ENTRY:mainCRTStartup - /SUBSYSTEM:CONSOLE - ) -elseif(MINGW) - target_link_options(no_crt_init_probe PRIVATE - -nostdlib - -Wl,--entry=mainCRTStartup - -Wl,--subsystem,console + + add_executable(no_crt_shared_init_probe "${PROBE_INIT_SOURCE}") + target_include_directories(no_crt_shared_init_probe PRIVATE "${PROBE_INCLUDES}") + target_compile_definitions(no_crt_shared_init_probe PRIVATE HID_API_NO_EXPORT_DEFINE) + target_link_libraries(no_crt_shared_init_probe PRIVATE + hidapi_no_crt_shared + kernel32 + user32 + shlwapi ) - target_link_options(no_crt_mem_probe PRIVATE - -nostdlib - -Wl,--entry=mainCRTStartup - -Wl,--subsystem,console + add_custom_command(TARGET no_crt_shared_init_probe POST_BUILD + COMMAND "${CMAKE_COMMAND}" -E copy_if_different + "${HIDAPI_SHARED_LIBRARY}" + "$" ) -else() - message(FATAL_ERROR "Unsupported no-CRT toolchain") endif() + +set(NO_CRT_PROBE_TARGETS no_crt_init_probe no_crt_mem_probe) +if(TARGET no_crt_shared_init_probe) + list(APPEND NO_CRT_PROBE_TARGETS no_crt_shared_init_probe) +endif() + +foreach(probe IN LISTS NO_CRT_PROBE_TARGETS) + if(MSVC) + target_compile_options(${probe} PRIVATE /GS-) + target_link_options(${probe} PRIVATE + /NODEFAULTLIB + /ENTRY:mainCRTStartup + /SUBSYSTEM:CONSOLE + ) + elseif(MINGW OR CYGWIN) + target_link_options(${probe} PRIVATE + -nostdlib + -Wl,--entry=mainCRTStartup + -Wl,--subsystem,console + ) + else() + message(FATAL_ERROR "Unsupported no-CRT toolchain") + endif() +endforeach() From f5eaac0cf5374367d93a386485985486a4f5577a Mon Sep 17 00:00:00 2001 From: Ebrahim Date: Sat, 28 Nov 2026 23:01:04 +0330 Subject: [PATCH 09/20] ci: centralize no-CRT dependency check Use one Test-NoCrtDependencies helper for the static probes, shared DLL, and shared probe instead of repeating the dumpbin regex. --- .github/workflows/builds.yml | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/.github/workflows/builds.yml b/.github/workflows/builds.yml index 55ec08524..6abda8fc8 100644 --- a/.github/workflows/builds.yml +++ b/.github/workflows/builds.yml @@ -363,6 +363,12 @@ jobs: - name: Build and check all no-CRT compilers shell: pwsh run: | + function Test-NoCrtDependencies { + param([string]$Path) + $deps = dumpbin /nologo /dependents $Path | Out-String + return $deps -notmatch '(?i)(vcruntime|ucrtbase|msvcrt|api-ms-win-crt|libgcc|libwinpthread|cygwin1)' + } + $ok = $true foreach ($compiler in @('cl', 'clang-cl', 'gcc')) { Write-Host "`n===== $compiler =====" @@ -418,8 +424,7 @@ jobs: $ok = $false } - $deps = dumpbin /nologo /dependents $probePath | Out-String - if ($deps -match '(?i)(vcruntime|ucrtbase|msvcrt|api-ms-win-crt|libgcc|libwinpthread)') { + if (-not (Test-NoCrtDependencies $probePath)) { Write-Host "::error title=$compiler/$probeName::CRT dependency found in the no-CRT probe" $ok = $false } @@ -448,8 +453,7 @@ jobs: continue } - $deps = dumpbin /nologo /dependents $dll.FullName | Out-String - if ($deps -match '(?i)(vcruntime|ucrtbase|msvcrt|api-ms-win-crt|libgcc|libwinpthread)') { + if (-not (Test-NoCrtDependencies $dll.FullName)) { Write-Host "::error title=$compiler::CRT dependency found in the no-CRT shared DLL" $ok = $false } @@ -494,8 +498,7 @@ jobs: $ok = $false } - $deps = dumpbin /nologo /dependents $sharedProbePath | Out-String - if ($deps -match '(?i)(vcruntime|ucrtbase|msvcrt|api-ms-win-crt|libgcc|libwinpthread)') { + if (-not (Test-NoCrtDependencies $sharedProbePath)) { Write-Host "::error title=$compiler/no_crt_shared_init_probe::CRT dependency found in the shared no-CRT probe" $ok = $false } From ec08b75620a8fd54fbd7ebfb5a33f6563233e57b Mon Sep 17 00:00:00 2001 From: Ebrahim Date: Mon, 30 Nov 2026 20:14:37 +0330 Subject: [PATCH 10/20] windows: use intrin.h on MinGW/Cygwin too The x86 memory-intrinsic path only recognized MSVC/clang-cl, so GCC fell back to byte loops even though its intrin.h provides __stosb and __movsb as inline asm. Include it for MinGW as well and rename the feature macro to HIDAPI_WINAPI_HAVE_X86_MEM_INTRIN. --- windows/hidapi_winapi_crt_compat.h | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/windows/hidapi_winapi_crt_compat.h b/windows/hidapi_winapi_crt_compat.h index 93f78ccb7..c1409a254 100644 --- a/windows/hidapi_winapi_crt_compat.h +++ b/windows/hidapi_winapi_crt_compat.h @@ -96,14 +96,16 @@ static inline void hid_internal_free(void *ptr) HeapFree(GetProcessHeap(), 0, ptr); } -#if (defined(_M_IX86) || defined(_M_X64)) && defined(_MSC_VER) +#if (defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64))) || \ + ((defined(__MINGW32__) || defined(__CYGWIN__)) && \ + (defined(__i386__) || defined(__x86_64__))) #include -#define HIDAPI_WINAPI_HAVE_MSVC_MEM_INTRIN +#define HIDAPI_WINAPI_HAVE_X86_MEM_INTRIN #endif static inline void *hid_internal_memcpy(void *dest, const void *src, size_t bytes) { -#ifdef HIDAPI_WINAPI_HAVE_MSVC_MEM_INTRIN +#ifdef HIDAPI_WINAPI_HAVE_X86_MEM_INTRIN __movsb((unsigned char *)dest, (const unsigned char *)src, bytes); #else volatile unsigned char *d = (volatile unsigned char *)dest; @@ -117,7 +119,7 @@ static inline void *hid_internal_memcpy(void *dest, const void *src, size_t byte static inline void *hid_internal_memset(void *dest, int value, size_t bytes) { /* clang-cl lowers __stosb to external memset, which no-CRT builds cannot use. */ -#if defined(HIDAPI_WINAPI_HAVE_MSVC_MEM_INTRIN) && !defined(__clang__) +#if defined(HIDAPI_WINAPI_HAVE_X86_MEM_INTRIN) && !defined(__clang__) __stosb((unsigned char *)dest, (unsigned char)value, bytes); #else volatile unsigned char *d = (volatile unsigned char *)dest; @@ -127,7 +129,7 @@ static inline void *hid_internal_memset(void *dest, int value, size_t bytes) return dest; } -#undef HIDAPI_WINAPI_HAVE_MSVC_MEM_INTRIN +#undef HIDAPI_WINAPI_HAVE_X86_MEM_INTRIN static inline int hid_internal_memcmp(const void *lhs, const void *rhs, size_t bytes) { From 6ece5cfe7005f0d4a1b8d1253750457ff1648e4d Mon Sep 17 00:00:00 2001 From: Ihor Dutchak Date: Tue, 1 Dec 2026 11:44:56 +0200 Subject: [PATCH 11/20] Fix Windows CRT-free builds and consumer checks Require CMake 3.13 for Windows. Link the MSVC Debug DLL without runtime checks, select the x86 MinGW entry points, and publish private libraries for static pkg-config consumers. Report lifecycle failures from the initialization probe. Assisted-by: Codex:gpt-6.2-astra --- .github/workflows/builds.yml | 11 +++++++++++ BUILD.cmake.md | 2 ++ configure.ac | 1 + pc/hidapi-backend-specific.pc.in | 1 + pc/hidapi.pc.in | 1 + src/CMakeLists.txt | 8 ++++++++ windows/CMakeLists.txt | 15 +++++++++++++-- windows/no-crt-msvc.cmake | 8 ++++++++ windows/test/no_crt/CMakeLists.txt | 17 ++++++++++++++++- windows/test/no_crt/init_probe.c | 6 +++--- windows/test/no_crt/mem_probe.c | 2 -- 11 files changed, 64 insertions(+), 8 deletions(-) create mode 100644 windows/no-crt-msvc.cmake diff --git a/.github/workflows/builds.yml b/.github/workflows/builds.yml index 6abda8fc8..598d305d2 100644 --- a/.github/workflows/builds.yml +++ b/.github/workflows/builds.yml @@ -360,6 +360,17 @@ jobs: - name: Install Ninja shell: cmd run: choco install ninja -y --no-progress + - name: Build MSVC Debug no-CRT DLL + shell: cmd + run: | + cmake -G Ninja ^ + -S hidapisrc ^ + -B build/no-crt-msvc-debug ^ + -DCMAKE_C_COMPILER=cl ^ + -DCMAKE_BUILD_TYPE=Debug ^ + -DHIDAPI_NO_CRT=ON ^ + -DBUILD_SHARED_LIBS=ON || exit /b 1 + cmake --build build/no-crt-msvc-debug --target hidapi_winapi - name: Build and check all no-CRT compilers shell: pwsh run: | diff --git a/BUILD.cmake.md b/BUILD.cmake.md index efcbfeb71..5100266f2 100644 --- a/BUILD.cmake.md +++ b/BUILD.cmake.md @@ -13,6 +13,8 @@ most of this document may not be of interest for you; just check variables names ## Installing CMake +Windows builds require CMake 3.13 or later. + CMake can be installed either using your system's package manager, or by downloading an installer/prebuilt version from the [official website](https://cmake.org/download/). diff --git a/configure.ac b/configure.ac index 554d685e6..d4e636894 100644 --- a/configure.ac +++ b/configure.ac @@ -298,6 +298,7 @@ fi m4_undefine([HIDAPI_CONFIGURE_BACKEND_PC]) AC_SUBST([HIDAPI_LIB_NAME]) +AC_SUBST([HIDAPI_PC_LIBS_PRIVATE], []) AC_SUBST([HIDAPI_GENERIC_REQUIRES_PRIVATE]) AC_CONFIG_FILES([pc/hidapi.pc]) diff --git a/pc/hidapi-backend-specific.pc.in b/pc/hidapi-backend-specific.pc.in index ff7a6b392..4770fd477 100644 --- a/pc/hidapi-backend-specific.pc.in +++ b/pc/hidapi-backend-specific.pc.in @@ -9,4 +9,5 @@ URL: https://github.com/libusb/hidapi Version: @VERSION@ Libs: -L${libdir} -l@HIDAPI_BACKEND_LIBRARY_NAME@ @HIDAPI_BACKEND_REQUIRES_PRIVATE@ +@HIDAPI_PC_LIBS_PRIVATE@ Cflags: -I${includedir}/hidapi diff --git a/pc/hidapi.pc.in b/pc/hidapi.pc.in index dcbae5987..7d6663f1e 100644 --- a/pc/hidapi.pc.in +++ b/pc/hidapi.pc.in @@ -9,4 +9,5 @@ URL: https://github.com/libusb/hidapi Version: @VERSION@ Libs: -L${libdir} -l@HIDAPI_LIB_NAME@ @HIDAPI_GENERIC_REQUIRES_PRIVATE@ +@HIDAPI_PC_LIBS_PRIVATE@ Cflags: -I${includedir}/hidapi diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index eeea1fc3b..8a718cb31 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -93,6 +93,11 @@ function(hidapi_configure_pc PC_IN_FILE) set(HIDAPI_BACKEND_REQUIRES_PRIVATE "") endif() set(HIDAPI_GENERIC_REQUIRES_PRIVATE "${HIDAPI_BACKEND_REQUIRES_PRIVATE}") + set(HIDAPI_PC_LIBS_PRIVATE "") + if(HIDAPI_WINAPI_SYSTEM_LIBS) + string(REPLACE ";" " -l" pc_system_libs "${HIDAPI_WINAPI_SYSTEM_LIBS}") + set(HIDAPI_PC_LIBS_PRIVATE "Libs.private: -l${pc_system_libs}") + endif() set(PC_FILE "${CMAKE_CURRENT_BINARY_DIR}/pc/${PC_IN_FILENAME}.pc") configure_file("${PC_IN_FILE}" "${PC_FILE}" @ONLY) if(HIDAPI_INSTALL_TARGETS) @@ -140,6 +145,9 @@ set(HIDAPI_NEED_EXPORT_LIBUDEV FALSE) set(HIDAPI_NEED_EXPORT_ICONV FALSE) if(WIN32) + if(HIDAPI_NO_CRT) + set(HIDAPI_WINAPI_SYSTEM_LIBS kernel32 shlwapi user32) + endif() target_include_directories(hidapi_include INTERFACE "$" ) diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt index 0f30b9620..899a48c96 100644 --- a/windows/CMakeLists.txt +++ b/windows/CMakeLists.txt @@ -1,3 +1,5 @@ +cmake_minimum_required(VERSION 3.13...4.3) + list(APPEND HIDAPI_PUBLIC_HEADERS "hidapi_winapi.h") set(SOURCES @@ -38,8 +40,10 @@ target_compile_definitions(hidapi_winapi if(HIDAPI_NO_CRT) target_compile_definitions(hidapi_winapi PRIVATE HIDAPI_NO_CRT) - target_link_libraries(hidapi_winapi PRIVATE kernel32 shlwapi user32) + target_link_libraries(hidapi_winapi PRIVATE ${HIDAPI_WINAPI_SYSTEM_LIBS}) if(MSVC) + include("${CMAKE_CURRENT_LIST_DIR}/no-crt-msvc.cmake") + hidapi_disable_msvc_runtime_checks(hidapi_winapi) # The library does not need __security_cookie from the CRT. target_compile_options(hidapi_winapi PRIVATE /GS-) endif() @@ -47,10 +51,17 @@ if(HIDAPI_NO_CRT) if(MSVC) target_link_options(hidapi_winapi PRIVATE /NODEFAULTLIB /ENTRY:DllMain) elseif(MINGW OR CYGWIN) + include(CheckSymbolExists) + check_symbol_exists(__i386__ "" HIDAPI_TARGET_I386) + if(HIDAPI_TARGET_I386) + set(dll_entry "_DllMain@12") + else() + set(dll_entry DllMain) + endif() target_link_options(hidapi_winapi PRIVATE -nostdlib -nodefaultlibs - -Wl,--entry=DllMain + -Wl,--entry=${dll_entry} ) endif() endif() diff --git a/windows/no-crt-msvc.cmake b/windows/no-crt-msvc.cmake new file mode 100644 index 000000000..c803abbc2 --- /dev/null +++ b/windows/no-crt-msvc.cmake @@ -0,0 +1,8 @@ +# Runtime checks require CRT startup and support functions. +macro(hidapi_disable_msvc_runtime_checks target) + set_property(TARGET ${target} PROPERTY MSVC_RUNTIME_CHECKS "") + # Before CMP0184 NEW, CMake adds /RTC1 directly to the Debug flags. + foreach(lang C CXX) + string(REGEX REPLACE "(^| )[-/]RTC1( |$)" " " CMAKE_${lang}_FLAGS_DEBUG "${CMAKE_${lang}_FLAGS_DEBUG}") + endforeach() +endmacro() diff --git a/windows/test/no_crt/CMakeLists.txt b/windows/test/no_crt/CMakeLists.txt index 10fa11ebf..16a1c3f20 100644 --- a/windows/test/no_crt/CMakeLists.txt +++ b/windows/test/no_crt/CMakeLists.txt @@ -15,6 +15,10 @@ endif() set(HIDAPI_SHARED_LIBRARY "" CACHE FILEPATH "Optional no-CRT shared DLL") set(HIDAPI_SHARED_IMPLIB "" CACHE FILEPATH "Import library for HIDAPI_SHARED_LIBRARY") +if(MSVC) + include("${CMAKE_CURRENT_LIST_DIR}/../../no-crt-msvc.cmake") +endif() + set(PROBE_INIT_SOURCE "${CMAKE_CURRENT_LIST_DIR}/init_probe.c") set(PROBE_MEM_SOURCE "${CMAKE_CURRENT_LIST_DIR}/mem_probe.c") set(PROBE_INCLUDES "${HIDAPI_SOURCE_DIR}/hidapi") @@ -73,8 +77,19 @@ if(TARGET no_crt_shared_init_probe) list(APPEND NO_CRT_PROBE_TARGETS no_crt_shared_init_probe) endif() +if(MINGW OR CYGWIN) + include(CheckSymbolExists) + check_symbol_exists(__i386__ "" HIDAPI_TARGET_I386) + if(HIDAPI_TARGET_I386) + set(probe_entry _mainCRTStartup) + else() + set(probe_entry mainCRTStartup) + endif() +endif() + foreach(probe IN LISTS NO_CRT_PROBE_TARGETS) if(MSVC) + hidapi_disable_msvc_runtime_checks(${probe}) target_compile_options(${probe} PRIVATE /GS-) target_link_options(${probe} PRIVATE /NODEFAULTLIB @@ -84,7 +99,7 @@ foreach(probe IN LISTS NO_CRT_PROBE_TARGETS) elseif(MINGW OR CYGWIN) target_link_options(${probe} PRIVATE -nostdlib - -Wl,--entry=mainCRTStartup + -Wl,--entry=${probe_entry} -Wl,--subsystem,console ) else() diff --git a/windows/test/no_crt/init_probe.c b/windows/test/no_crt/init_probe.c index 1b82d7840..bdc382e57 100644 --- a/windows/test/no_crt/init_probe.c +++ b/windows/test/no_crt/init_probe.c @@ -23,7 +23,7 @@ void __cdecl mainCRTStartup(void) { - if (hid_init() == 0) - hid_exit(); - ExitProcess(0); + if (hid_init() != 0) + ExitProcess(1); + ExitProcess(hid_exit() == 0 ? 0 : 2); } diff --git a/windows/test/no_crt/mem_probe.c b/windows/test/no_crt/mem_probe.c index d09a0f344..6b108df96 100644 --- a/windows/test/no_crt/mem_probe.c +++ b/windows/test/no_crt/mem_probe.c @@ -44,7 +44,5 @@ void __cdecl mainCRTStartup(void) if (hid_internal_memcmp((const void *)dst, (const void *)src, sizeof(dst)) == 0) ExitProcess(4); - if (hid_init() == 0) - hid_exit(); ExitProcess(0); } From b618cace8cf5530b45794ed31f91ff15e2d74001 Mon Sep 17 00:00:00 2001 From: Ebrahim Date: Tue, 1 Dec 2026 14:40:03 +0330 Subject: [PATCH 12/20] windows: minor comment tweak --- windows/hidapi_winapi_crt_compat.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/windows/hidapi_winapi_crt_compat.h b/windows/hidapi_winapi_crt_compat.h index c1409a254..ee0beeae4 100644 --- a/windows/hidapi_winapi_crt_compat.h +++ b/windows/hidapi_winapi_crt_compat.h @@ -118,7 +118,8 @@ static inline void *hid_internal_memcpy(void *dest, const void *src, size_t byte static inline void *hid_internal_memset(void *dest, int value, size_t bytes) { -/* clang-cl lowers __stosb to external memset, which no-CRT builds cannot use. */ +/* clang-cl lowers __stosb to external memset, which no-CRT builds cannot use. + * See also: https://github.com/llvm/llvm-project/issues/33522 */ #if defined(HIDAPI_WINAPI_HAVE_X86_MEM_INTRIN) && !defined(__clang__) __stosb((unsigned char *)dest, (unsigned char)value, bytes); #else From 312289d7bc87e2a3d26d61d94fd55929b6fb8bf4 Mon Sep 17 00:00:00 2001 From: Ebrahim Date: Tue, 1 Dec 2026 14:44:26 +0330 Subject: [PATCH 13/20] windows: guard against alloc fails in const main items additions It needs to wrap the ending part of the function with a block otherwise it will become an invalid C++ code as -Wjump-misses-init, the alternative solution is to move the variables at the of the function that however decrease readability as widens lifespan of the variables to places they didn't actually touched. --- windows/hidapi_descriptor_reconstruct.c | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/windows/hidapi_descriptor_reconstruct.c b/windows/hidapi_descriptor_reconstruct.c index ea2cca06b..0987963fa 100644 --- a/windows/hidapi_descriptor_reconstruct.c +++ b/windows/hidapi_descriptor_reconstruct.c @@ -517,6 +517,7 @@ int hid_winapi_descriptor_reconstruct_pp_data(void *preparsed_data, unsigned cha } } + int result = -1; // *********************************************************** // Add const main items for padding to main_item_list @@ -528,9 +529,16 @@ int hid_winapi_descriptor_reconstruct_pp_data(void *preparsed_data, unsigned cha // *********************************************************** { int (*last_bit_position)[256] = (int (*)[256])HIDAPI_MALLOC(NUM_OF_HIDP_REPORT_TYPES * sizeof(*last_bit_position)); - struct rd_main_item_node *(*last_report_item_lookup)[256] = (struct rd_main_item_node *(*)[256])HIDAPI_MALLOC(NUM_OF_HIDP_REPORT_TYPES * sizeof(*last_report_item_lookup)); + if (last_bit_position == NULL) { + goto cleanup; + } + struct rd_main_item_node *(*last_report_item_lookup)[256] = (struct rd_main_item_node *(*)[256])HIDAPI_CALLOC(NUM_OF_HIDP_REPORT_TYPES, sizeof(*last_report_item_lookup)); + if (last_report_item_lookup == NULL) { + HIDAPI_FREE(last_bit_position); + goto cleanup; + } HIDAPI_MEMSET(last_bit_position, -1, NUM_OF_HIDP_REPORT_TYPES * sizeof(*last_bit_position)); - HIDAPI_MEMSET(last_report_item_lookup, 0, NUM_OF_HIDP_REPORT_TYPES * sizeof(*last_report_item_lookup)); /* fill with NULL pointers */ + /* last_report_item_lookup is already filled with NULL pointers via HIDAPI_CALLOC call */ BOOLEAN devicehasReportIDs = FALSE; struct rd_main_item_node *list = main_item_list; // List root; @@ -606,6 +614,7 @@ int hid_winapi_descriptor_reconstruct_pp_data(void *preparsed_data, unsigned cha // *********************************** // Encode the report descriptor output // *********************************** + { UCHAR last_report_id = 0; USAGE last_usage_page = 0; LONG last_physical_min = 0;// If both, Physical Minimum and Physical Maximum are 0, the logical limits should be taken as physical limits according USB HID spec 1.11 chapter 6.2.2.7 @@ -1003,6 +1012,10 @@ int hid_winapi_descriptor_reconstruct_pp_data(void *preparsed_data, unsigned cha main_item_list = main_item_list->next; HIDAPI_FREE(main_item_list_prev); } + } + + result = (int) rpt_desc.byte_idx; +cleanup: // Free multidimensionable array: coll_bit_range[COLLECTION_INDEX][REPORT_ID][INPUT/OUTPUT/FEATURE] // Free multidimensionable array: coll_child_order[COLLECTION_INDEX][DIRECT_CHILD_INDEX] @@ -1025,5 +1038,5 @@ int hid_winapi_descriptor_reconstruct_pp_data(void *preparsed_data, unsigned cha HIDAPI_FREE(coll_levels); HIDAPI_FREE(coll_number_of_direct_childs); - return (int) rpt_desc.byte_idx; + return result; } From 237d2b1ea52fa9b594a5f661f612dd80b948a6a7 Mon Sep 17 00:00:00 2001 From: Ebrahim Date: Tue, 1 Dec 2026 16:41:14 +0330 Subject: [PATCH 14/20] windows: Make sure main_item_list doesn't leak If an allocation failure happens the above list freeing part is bypassed so this makes sure leak won't happen even if "Encode the report descriptor output" part is bypassed by the goto. --- windows/hidapi_descriptor_reconstruct.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/windows/hidapi_descriptor_reconstruct.c b/windows/hidapi_descriptor_reconstruct.c index 0987963fa..0e8d87469 100644 --- a/windows/hidapi_descriptor_reconstruct.c +++ b/windows/hidapi_descriptor_reconstruct.c @@ -1016,6 +1016,12 @@ int hid_winapi_descriptor_reconstruct_pp_data(void *preparsed_data, unsigned cha result = (int) rpt_desc.byte_idx; cleanup: + // If an allocation failure occurred, free the memory of the main_item_list + while (main_item_list != NULL) { + struct rd_main_item_node *next = main_item_list->next; + HIDAPI_FREE(main_item_list); + main_item_list = next; + } // Free multidimensionable array: coll_bit_range[COLLECTION_INDEX][REPORT_ID][INPUT/OUTPUT/FEATURE] // Free multidimensionable array: coll_child_order[COLLECTION_INDEX][DIRECT_CHILD_INDEX] From 2180c06d316b093966d98a54156d3a21c2d59683 Mon Sep 17 00:00:00 2001 From: Ebrahim Date: Tue, 1 Dec 2026 22:28:27 +0330 Subject: [PATCH 15/20] windows: avoid signed overflow in hex conversion The no-CRT fallback shifted a signed long and could overflow. Saturate at LONG_MAX while still advancing endptr, matching wcstol behavior. --- windows/hidapi_winapi_crt_compat.h | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/windows/hidapi_winapi_crt_compat.h b/windows/hidapi_winapi_crt_compat.h index ee0beeae4..27cd10a37 100644 --- a/windows/hidapi_winapi_crt_compat.h +++ b/windows/hidapi_winapi_crt_compat.h @@ -65,6 +65,7 @@ static inline void hid_internal_towupper(wchar_t *string) #else /* HIDAPI_NO_CRT */ +#include #include #include #include @@ -183,7 +184,10 @@ static inline long hid_internal_wcstol_hex(const wchar_t *string, wchar_t **endp else if (c >= L'A' && c <= L'F') digit = c - L'A' + 10; else if (c >= L'a' && c <= L'f') digit = c - L'a' + 10; else break; - value = (value << 4) | digit; + if (value > (LONG_MAX - digit) / 16) + value = LONG_MAX; + else + value = value * 16 + digit; } *endptr = (wchar_t *)p; return value; From 8018cb777dac5d9d333d426b19301384c54c4d86 Mon Sep 17 00:00:00 2001 From: Ebrahim Date: Tue, 1 Dec 2026 22:28:49 +0330 Subject: [PATCH 16/20] windows: bound WCSNCPY by capacity without narrowing Use a size_t-capacity helper so 64-bit callers don't truncate maxlen to int, and always terminate the destination. --- windows/hidapi_winapi_crt_compat.h | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/windows/hidapi_winapi_crt_compat.h b/windows/hidapi_winapi_crt_compat.h index 27cd10a37..895c9464f 100644 --- a/windows/hidapi_winapi_crt_compat.h +++ b/windows/hidapi_winapi_crt_compat.h @@ -193,6 +193,17 @@ static inline long hid_internal_wcstol_hex(const wchar_t *string, wchar_t **endp return value; } +static inline void hid_internal_wcsncpy(wchar_t *dest, size_t capacity, const wchar_t *src) +{ + if (capacity == 0) + return; + while (capacity > 1 && *src) { + *dest++ = *src++; + --capacity; + } + *dest = L'\0'; +} + #define HIDAPI_MALLOC(n) hid_internal_malloc((n)) #define HIDAPI_CALLOC(n, size) hid_internal_calloc((n), (size)) #define HIDAPI_FREE(p) hid_internal_free((p)) @@ -206,7 +217,7 @@ static inline long hid_internal_wcstol_hex(const wchar_t *string, wchar_t **endp #define HIDAPI_WCSDUP(s) hid_internal_wcsdup((s)) #define HIDAPI_STRDUP(s) hid_internal_strdup((s)) #define HIDAPI_SWPRINTF(dest, count, ...) wnsprintfW((dest), (int)(count), __VA_ARGS__) -#define HIDAPI_WCSNCPY(dest, dest_count, src) lstrcpynW((dest), (src), (int)(dest_count)) +#define HIDAPI_WCSNCPY(dest, dest_count, src) hid_internal_wcsncpy((dest), (dest_count), (src)) #endif /* HIDAPI_NO_CRT */ From b1c15e3a97231426061ce8b5382a87d0cef1808b Mon Sep 17 00:00:00 2001 From: Ebrahim Date: Tue, 1 Dec 2026 22:29:34 +0330 Subject: [PATCH 17/20] windows: format WinAPI errors without wnsprintfW Use HIDAPI_SWPRINTF in the CRT path and FormatMessageW with an argument array in the no-CRT path, behind a shared helper. --- windows/hid.c | 2 +- windows/hidapi_winapi_crt_compat.h | 24 +++++++++++++++++++++++- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/windows/hid.c b/windows/hid.c index 3899ba413..0d7a81c27 100644 --- a/windows/hid.c +++ b/windows/hid.c @@ -289,7 +289,7 @@ static void register_winapi_error_to_buffer(wchar_t **error_buffer, const WCHAR if (!msg) return; - int printf_written = HIDAPI_SWPRINTF(msg, msg_len + 1, L"%.*ls: (0x%08X) %.*ls", (int)op_len, op, error_code, (int)system_err_len, system_err_buf); + int printf_written = hid_internal_format_winapi_error(msg, msg_len + 1, (int)op_len, op, error_code, (int)system_err_len, system_err_buf); msg[msg_len] = L'\0'; if (printf_written < 0) diff --git a/windows/hidapi_winapi_crt_compat.h b/windows/hidapi_winapi_crt_compat.h index 895c9464f..5d27347ca 100644 --- a/windows/hidapi_winapi_crt_compat.h +++ b/windows/hidapi_winapi_crt_compat.h @@ -40,6 +40,15 @@ #define HIDAPI_WCSNCPY(dest, dest_count, src) wcsncpy((dest), (src), (dest_count)) #endif +static inline int hid_internal_format_winapi_error(WCHAR *dest, DWORD capacity, + int op_len, const WCHAR *op, DWORD error_code, int system_err_len, + const WCHAR *detail) +{ + return HIDAPI_SWPRINTF(dest, (size_t)capacity, L"%.*ls: (0x%08X) %.*ls", + op_len, op, error_code, system_err_len, detail); +} +#undef HIDAPI_SWPRINTF + static inline void hid_internal_towupper(wchar_t *string) { for (wchar_t *p = string; *p; ++p) @@ -66,10 +75,24 @@ static inline void hid_internal_towupper(wchar_t *string) #else /* HIDAPI_NO_CRT */ #include +#include #include #include #include +static inline int hid_internal_format_winapi_error(WCHAR *dest, DWORD capacity, + int op_len, const WCHAR *op, DWORD error_code, int system_err_len, + const WCHAR *detail) +{ + DWORD_PTR args[] = { (DWORD_PTR)op, (DWORD_PTR)error_code, (DWORD_PTR)detail }; + DWORD written; + (void)op_len; + (void)system_err_len; + written = FormatMessageW(FORMAT_MESSAGE_FROM_STRING | FORMAT_MESSAGE_ARGUMENT_ARRAY, + L"%1: (0x%2!08X!) %3", 0, 0, dest, capacity, (va_list *)args); + return written ? (int)written : -1; +} + static inline void hid_internal_towupper(wchar_t *string) { CharUpperW(string); @@ -216,7 +239,6 @@ static inline void hid_internal_wcsncpy(wchar_t *dest, size_t capacity, const wc #define HIDAPI_WCSTOL_HEX(s, end) hid_internal_wcstol_hex((s), (end)) #define HIDAPI_WCSDUP(s) hid_internal_wcsdup((s)) #define HIDAPI_STRDUP(s) hid_internal_strdup((s)) -#define HIDAPI_SWPRINTF(dest, count, ...) wnsprintfW((dest), (int)(count), __VA_ARGS__) #define HIDAPI_WCSNCPY(dest, dest_count, src) hid_internal_wcsncpy((dest), (dest_count), (src)) From 0116876cfa582025fa6b466ae7d51cf18fbc4a54 Mon Sep 17 00:00:00 2001 From: Ebrahim Date: Wed, 2 Dec 2026 01:19:27 +0330 Subject: [PATCH 18/20] windows: match CRT error formatting in no-CRT builds Build the no-CRT WinAPI error string directly instead of using FormatMessageW's FROM_STRING formatting. FROM_STRING requires a second format language and argument array, and %3 dereferences the detail even when the system lookup returned nothing. The direct formatter preserves the original `%.*ls: (0x%08X) %.*ls` output without changing the shared caller or its trimming behavior. --- windows/hidapi_winapi_crt_compat.h | 57 +++++++++++++++++++++++++----- 1 file changed, 49 insertions(+), 8 deletions(-) diff --git a/windows/hidapi_winapi_crt_compat.h b/windows/hidapi_winapi_crt_compat.h index 5d27347ca..d9cd341d1 100644 --- a/windows/hidapi_winapi_crt_compat.h +++ b/windows/hidapi_winapi_crt_compat.h @@ -75,7 +75,6 @@ static inline void hid_internal_towupper(wchar_t *string) #else /* HIDAPI_NO_CRT */ #include -#include #include #include #include @@ -84,13 +83,55 @@ static inline int hid_internal_format_winapi_error(WCHAR *dest, DWORD capacity, int op_len, const WCHAR *op, DWORD error_code, int system_err_len, const WCHAR *detail) { - DWORD_PTR args[] = { (DWORD_PTR)op, (DWORD_PTR)error_code, (DWORD_PTR)detail }; - DWORD written; - (void)op_len; - (void)system_err_len; - written = FormatMessageW(FORMAT_MESSAGE_FROM_STRING | FORMAT_MESSAGE_ARGUMENT_ARRAY, - L"%1: (0x%2!08X!) %3", 0, 0, dest, capacity, (va_list *)args); - return written ? (int)written : -1; + /* + * Match the CRT formatting used by the normal build: + * L"%.*ls: (0x%08X) %.*ls" + */ + static const WCHAR hex[] = L"0123456789ABCDEF"; + DWORD pos = 0; + int i; + size_t total; + + if (!dest || capacity == 0) + return -1; + if (op_len < 0) + op_len = 0; + if (system_err_len < 0) + system_err_len = 0; + if (!op) + op = L""; + if (!detail) + detail = L""; + if (system_err_len == 0) + detail = L""; + + static const WCHAR prefix[] = L": (0x"; + static const WCHAR suffix[] = L") "; + total = (size_t)op_len + + (sizeof(prefix) / sizeof(prefix[0]) - 1) + + 8 + + (sizeof(suffix) / sizeof(suffix[0]) - 1) + + (size_t)system_err_len; + if (total >= capacity) + return -1; + + /* first %.*ls: operation name */ + for (i = 0; i < op_len; ++i) + dest[pos++] = op[i]; + /* literal ": (0x" */ + for (i = 0; prefix[i] != L'\0'; ++i) + dest[pos++] = prefix[i]; + /* %08X: error code */ + for (i = 7; i >= 0; --i) + dest[pos++] = hex[(error_code >> (i * 4)) & 0xF]; + /* literal ") " */ + for (i = 0; suffix[i] != L'\0'; ++i) + dest[pos++] = suffix[i]; + /* second %.*ls: system error detail */ + for (i = 0; i < system_err_len; ++i) + dest[pos++] = detail[i]; + dest[pos] = L'\0'; + return (int)pos; } static inline void hid_internal_towupper(wchar_t *string) From c898022ecff8918e18b400a537ffd4c0e613e8aa Mon Sep 17 00:00:00 2001 From: Ihor Dutchak Date: Wed, 2 Dec 2026 01:04:27 +0200 Subject: [PATCH 19/20] windows: format WinAPI errors with FormatMessageW directly Drop hid_internal_format_winapi_error and HIDAPI_SWPRINTF. The CRT and the no-CRT builds now format the error string with one FormatMessageW call in register_winapi_error_to_buffer. The output is unchanged. Assisted-by: claude-code:claude-fable-5-2 --- windows/hid.c | 11 ++++- windows/hidapi_winapi_crt_compat.h | 71 +----------------------------- 2 files changed, 11 insertions(+), 71 deletions(-) diff --git a/windows/hid.c b/windows/hid.c index 0d7a81c27..31c6f87d2 100644 --- a/windows/hid.c +++ b/windows/hid.c @@ -289,10 +289,17 @@ static void register_winapi_error_to_buffer(wchar_t **error_buffer, const WCHAR if (!msg) return; - int printf_written = hid_internal_format_winapi_error(msg, msg_len + 1, (int)op_len, op, error_code, (int)system_err_len, system_err_buf); + /* system_err_buf is not initialized when the system message lookup fails */ + DWORD_PTR args[] = { (DWORD_PTR)op, error_code, (DWORD_PTR)(system_err_len ? system_err_buf : L"") }; + DWORD written = FormatMessageW( + FORMAT_MESSAGE_FROM_STRING | FORMAT_MESSAGE_ARGUMENT_ARRAY, + L"%1: (0x%2!08X!) %3", + 0, 0, + msg, msg_len + 1, + (va_list *)args); msg[msg_len] = L'\0'; - if (printf_written < 0) + if (!written) { /* Highly unlikely */ msg[0] = L'\0'; diff --git a/windows/hidapi_winapi_crt_compat.h b/windows/hidapi_winapi_crt_compat.h index d9cd341d1..c6e3802a2 100644 --- a/windows/hidapi_winapi_crt_compat.h +++ b/windows/hidapi_winapi_crt_compat.h @@ -22,7 +22,6 @@ #ifndef HIDAPI_NO_CRT -#include #include #include #include @@ -30,25 +29,14 @@ #include #endif -/* MSVC secure CRT (VS2005+) provides swprintf_s/wcsncpy_s. - Older MSVC and GCC/MinGW/Cygwin use the classic variants. */ +/* MSVC secure CRT (VS2005+) provides wcsncpy_s. + Older MSVC and GCC/MinGW/Cygwin use the classic variant. */ #if defined(_MSC_VER) && (_MSC_VER >= 1400) -#define HIDAPI_SWPRINTF swprintf_s #define HIDAPI_WCSNCPY(dest, dest_count, src) wcsncpy_s((dest), (dest_count), (src), _TRUNCATE) #else -#define HIDAPI_SWPRINTF swprintf #define HIDAPI_WCSNCPY(dest, dest_count, src) wcsncpy((dest), (src), (dest_count)) #endif -static inline int hid_internal_format_winapi_error(WCHAR *dest, DWORD capacity, - int op_len, const WCHAR *op, DWORD error_code, int system_err_len, - const WCHAR *detail) -{ - return HIDAPI_SWPRINTF(dest, (size_t)capacity, L"%.*ls: (0x%08X) %.*ls", - op_len, op, error_code, system_err_len, detail); -} -#undef HIDAPI_SWPRINTF - static inline void hid_internal_towupper(wchar_t *string) { for (wchar_t *p = string; *p; ++p) @@ -79,61 +67,6 @@ static inline void hid_internal_towupper(wchar_t *string) #include #include -static inline int hid_internal_format_winapi_error(WCHAR *dest, DWORD capacity, - int op_len, const WCHAR *op, DWORD error_code, int system_err_len, - const WCHAR *detail) -{ - /* - * Match the CRT formatting used by the normal build: - * L"%.*ls: (0x%08X) %.*ls" - */ - static const WCHAR hex[] = L"0123456789ABCDEF"; - DWORD pos = 0; - int i; - size_t total; - - if (!dest || capacity == 0) - return -1; - if (op_len < 0) - op_len = 0; - if (system_err_len < 0) - system_err_len = 0; - if (!op) - op = L""; - if (!detail) - detail = L""; - if (system_err_len == 0) - detail = L""; - - static const WCHAR prefix[] = L": (0x"; - static const WCHAR suffix[] = L") "; - total = (size_t)op_len - + (sizeof(prefix) / sizeof(prefix[0]) - 1) - + 8 - + (sizeof(suffix) / sizeof(suffix[0]) - 1) - + (size_t)system_err_len; - if (total >= capacity) - return -1; - - /* first %.*ls: operation name */ - for (i = 0; i < op_len; ++i) - dest[pos++] = op[i]; - /* literal ": (0x" */ - for (i = 0; prefix[i] != L'\0'; ++i) - dest[pos++] = prefix[i]; - /* %08X: error code */ - for (i = 7; i >= 0; --i) - dest[pos++] = hex[(error_code >> (i * 4)) & 0xF]; - /* literal ") " */ - for (i = 0; suffix[i] != L'\0'; ++i) - dest[pos++] = suffix[i]; - /* second %.*ls: system error detail */ - for (i = 0; i < system_err_len; ++i) - dest[pos++] = detail[i]; - dest[pos] = L'\0'; - return (int)pos; -} - static inline void hid_internal_towupper(wchar_t *string) { CharUpperW(string); From 382e6e365d5c09ed741e5c9f617048a7504b1860 Mon Sep 17 00:00:00 2001 From: Ihor Dutchak Date: Wed, 2 Dec 2026 01:16:59 +0200 Subject: [PATCH 20/20] windows: include stdio.h in pp_data_dump pp_data_dump.c uses stdio functions and got only through hid.c, which no longer includes it. Assisted-by: claude-code:claude-fable-5-2 --- windows/pp_data_dump/pp_data_dump.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/windows/pp_data_dump/pp_data_dump.c b/windows/pp_data_dump/pp_data_dump.c index 9a1752726..3cbc3ca79 100644 --- a/windows/pp_data_dump/pp_data_dump.c +++ b/windows/pp_data_dump/pp_data_dump.c @@ -3,6 +3,8 @@ #define __USE_MINGW_ANSI_STDIO 1 #endif +#include + #include #include <../windows/hidapi_descriptor_reconstruct.h>