From 854394ee137915c9c067cb7afdbcb06d917716ab Mon Sep 17 00:00:00 2001 From: Ebrahim Date: Wed, 25 Nov 2026 23:11:21 +0330 Subject: [PATCH 1/6] 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 2/6] 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 3/6] 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 4/6] 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 5/6] 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 6/6] 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