Repository navigation
Conversation
3b6c69d to
4f86d3b
Compare
ac98609 to
f7156d3
Compare
826b88f to
ddf3e3d
Compare
|
The runtime mem* test is needed because of a clang-cl-specific failure mode, not just a link/import check. On x64, <memset>:
jmp memsetThe link succeeded, so the existing probe only checking dependencies and This commit now builds the probe two ways:
The library itself no longer exports |
|
This became a bit complicated to review because of the reviewer call for renaming callsites instead of just And the PR experienced some churns because the need to make sure it works flawlessly on all three toolchains while being CI tested, MSVC/clang-cl/mingw while not exposing our own Sorry for the noise, please review this the way you see best. |
| # __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. |
There was a problem hiding this comment.
is this only for test or for normal operation too?
There was a problem hiding this comment.
These flags are for normal library operation, not just the test. The test target has its own flags.
I prototyped what is needed to remove the stack-probe flags (/Gs9999999 and -mno-stack-arg-probe). The cause is the descriptor lookup block:
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];Moving those two arrays to the heap removes the __chkstk/___chkstk_ms dependency. This is not committed; it is only the diff I tested:
diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt
@@ -36,14 +36,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)
+ if(MSVC)
+ target_compile_options(hidapi_winapi PRIVATE /GS-)
endif()
endif()
diff --git a/windows/hidapi_descriptor_reconstruct.c b/windows/hidapi_descriptor_reconstruct.c
@@ -527,10 +527,10 @@
{
- 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 */
@@ -597,6 +597,9 @@
}
+
+ HIDAPI_FREE(last_bit_position);
+ HIDAPI_FREE(last_report_item_lookup);
}With this patch, MinGW, MSVC, and clang-cl all build the library and both probes without /Gs9999999 or -mno-stack-arg-probe.
I also tried removing /GS- entirely. That still fails:
unresolved external symbol __security_cookie
unresolved external symbol __security_check_cookie
error LNK2001: unresolved external symbol __GSHandlerCheck
The security cookie is not caused by these two large arrays alone. Many functions have local Windows SDK structs that contain arrays — for example HIDP_CAPS.Reserved[17] and GUID.Data4[8] — so eliminating /GS- would require heap-allocating all those locals or annotating every affected function, which is substantially more invasive than the stack-probe cleanup.
So the practical result is: moving these two arrays removes the stack-probe flags, but /GS- remains necessary for the no-CRT MSVC build.
There was a problem hiding this comment.
This is now worked around in 570a5c8: the two descriptor lookup arrays are allocated on the heap, and /Gs9999999 / -mno-stack-arg-probe are removed from both the library and probe builds. /GS- remains because the security cookie is still needed.
For scale, on x64 the arrays were:
8 * 256 * sizeof(int)= 8 KiB8 * 256 * sizeof(pointer)= 16 KiB
so about 24 KiB, roughly six 4 KiB pages (16 KiB on 32-bit). That is the stack-probe threshold problem; it is not a huge stack frame relative to the default 1 MiB stack.
Being honest about the tradeoff: Stack allocation is normally cheaper (pointer adjustment plus probe) and is automatically released. The heap path adds allocator bookkeeping, a second allocation, a free, and a failure path. For this one-time descriptor reconstruction the cost is negligible, but the real benefit is avoiding is reducing the chance of failing on a constrained thread stack — not raw performance. But hid_winapi_descriptor_reconstruct_pp_data is already far from being alloc failure friendly, I have a draft for hardening the specific function here https://github.com/ebraminio/hidapi/pull/new/windows-alloc-failure but that's separate from this PR.
|
|
||
| if(HIDAPI_NO_CRT) | ||
| target_compile_definitions(hidapi_winapi PRIVATE HIDAPI_NO_CRT) | ||
| target_link_libraries(hidapi_winapi PUBLIC shlwapi) |
There was a problem hiding this comment.
where do we introduce this dependencty as public?
There was a problem hiding this comment.
Updated to PRIVATE shlwapi in ad715f4. shlwapi is an implementation dependency (no public header includes it); CMake static consumers still receive it as a link-only dependency through the target interface.
There was a problem hiding this comment.
Also the whole shlwapi is avoidable but I wanted the change as small as possible but shlwapi is the only thing that is able to provide a swprintf like function without a CRT (the other solution is to handwrite the only use, user32 also provides one deprecated formatter also) but this isn't the only use of shlwapi I should add but the other is also replaceable.
There was a problem hiding this comment.
Here is a tested prototype that removes shlwapi entirely, not just the link line. It is not committed.
The two shlwapi uses are:
StrStrWforHIDAPI_WCSSTRwnsprintfWfor the single WinAPI error message
The diff replaces StrStrW with an internal wcsstr-equivalent helper, and replaces the one wnsprintfW call with explicit wide-string assembly using the existing HIDAPI_MEMCPY. lstrcpynW remains because it comes from kernel32, not shlwapi.
diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt
index 3b8ba4f..bf26ed9 100644
--- a/windows/CMakeLists.txt
+++ b/windows/CMakeLists.txt
@@ -35,7 +35,6 @@ 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)
if(MSVC)
# The descriptor reconstructor has a large stack frame. Disable stack
# probes and the security cookie so the static library does not need
diff --git a/windows/hid.c b/windows/hid.c
index d089eae..114216c 100644
--- a/windows/hid.c
+++ b/windows/hid.c
@@ -253,6 +253,27 @@ static void free_hid_device(hid_device *dev)
HIDAPI_FREE(dev);
}
+static void hid_internal_format_winapi_error(wchar_t *msg, const wchar_t *op, DWORD op_len, DWORD error_code, const wchar_t *system_err, DWORD system_err_len)
+{
+ static const wchar_t hex[] = L"0123456789ABCDEF";
+ wchar_t *p = msg;
+
+ HIDAPI_MEMCPY(p, op, op_len * sizeof(wchar_t));
+ p += op_len;
+ *p++ = L':';
+ *p++ = L' ';
+ *p++ = L'(';
+ *p++ = L'0';
+ *p++ = L'x';
+ for (int shift = 28; shift >= 0; shift -= 4)
+ *p++ = hex[(error_code >> shift) & 0xF];
+ *p++ = L')';
+ *p++ = L' ';
+ HIDAPI_MEMCPY(p, system_err, system_err_len * sizeof(wchar_t));
+ p += system_err_len;
+ *p = L'\0';
+}
+
static void register_winapi_error_to_buffer(wchar_t **error_buffer, const WCHAR *op)
{
HIDAPI_FREE(*error_buffer);
@@ -291,15 +312,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);
- msg[msg_len] = L'\0';
-
- if (printf_written < 0)
- {
- /* Highly unlikely */
- msg[0] = L'\0';
- return;
- }
+ hid_internal_format_winapi_error(msg, op, op_len, error_code, system_err_buf, system_err_len);
/* Get rid of the CR and LF that FormatMessage() sticks at the
end of the message. Thanks Microsoft! */
diff --git a/windows/hidapi_winapi_crt.h b/windows/hidapi_winapi_crt.h
index 8eeb0a7..2f8f9c6 100644
--- a/windows/hidapi_winapi_crt.h
+++ b/windows/hidapi_winapi_crt.h
@@ -27,13 +27,11 @@
#include <string.h>
#include <wchar.h>
-/* 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
@@ -63,7 +61,6 @@ static inline void hid_internal_towupper(wchar_t *string)
#else /* HIDAPI_NO_CRT */
#include <windows.h>
-#include <shlwapi.h>
#include <stdint.h>
static inline void hid_internal_towupper(wchar_t *string)
@@ -184,11 +181,27 @@ static inline long hid_internal_wcstol_hex(const wchar_t *string, wchar_t **endp
#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))
+static inline wchar_t *hid_internal_wcsstr(const wchar_t *haystack, const wchar_t *needle)
+{
+ if (!*needle)
+ return (wchar_t *)haystack;
+ for (; *haystack; ++haystack) {
+ const wchar_t *h = haystack;
+ const wchar_t *n = needle;
+ while (*n && *h == *n) {
+ ++h;
+ ++n;
+ }
+ if (!*n)
+ return (wchar_t *)haystack;
+ }
+ return NULL;
+}
+
+#define HIDAPI_WCSSTR(haystack, needle) hid_internal_wcsstr((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))
diff --git a/windows/test/no_crt/CMakeLists.txt b/windows/test/no_crt/CMakeLists.txt
index 801bf6d..04e1328 100644
--- a/windows/test/no_crt/CMakeLists.txt
+++ b/windows/test/no_crt/CMakeLists.txt
@@ -27,7 +27,6 @@ target_link_libraries(no_crt_probe PRIVATE
hidapi_no_crt
kernel32
user32
- shlwapi
)
add_executable(no_crt_probe_mem_functions "${PROBE_SOURCE}")
@@ -40,7 +39,6 @@ target_compile_definitions(no_crt_probe_mem_functions PRIVATE
target_link_libraries(no_crt_probe_mem_functions PRIVATE
kernel32
user32
- shlwapi
)
if(MSVC OR CMAKE_C_SIMULATE_ID STREQUAL "MSVC")Verification with this prototype and no shlwapi anywhere in the link:
MinGW no-CRT library: pass
MinGW no-CRT probes: pass
MinGW CRT library: pass
MSVC no-CRT library/probes: pass
clang-cl no-CRT library/probes: pass
probe imports: KERNEL32.dll only
So the dependency really is removable; it just adds a small amount of formatting/string code instead of a system-library dependency.
There was a problem hiding this comment.
shlwapi is not a problem as a dependency, just make sure it is private
There was a problem hiding this comment.
It is private now, thanks 🙏 While trying to build the DLL it turned out kernel32 user32 also should be mentioned as a dependency in the same line.
Just to explain my motive and the reason this PR went this path, my initial goal was to upstream the patch I use for my CRT-free work but as an opt-in option, I was static linking the library so hidapi's DLL wasn't my concern but later learnt a CRT-free freestanding dll that is only 40kb instead of the current 150kb can also a good offering for the project. Of course I haven't touched the normal path of the project except that stack to heap allocation of that 8kb+24kb allocation that was triggering a MSVC/GCC's stack check probe even before my change. My view is we can have this and over the time converge the two implementations.
| if ($compiler -eq 'gcc') { | ||
| gcc -c -DHID_API_NO_EXPORT_DEFINE -Ihidapisrc\hidapi hidapisrc\windows\test\no_crt_probe.c -o no_crt_probe.o | ||
| if ($LASTEXITCODE -ne 0) { $ok = $false; continue } | ||
| gcc -nostdlib "-Wl,--entry=mainCRTStartup" "-Wl,--subsystem,console" ` | ||
| -o no_crt_probe.exe no_crt_probe.o "$($lib.FullName)" -lkernel32 -luser32 -lshlwapi -lgcc | ||
| if ($LASTEXITCODE -ne 0) { $ok = $false; continue } | ||
|
|
||
| gcc -c -DHIDAPI_NO_CRT -DHIDAPI_TEST_MEM_FUNCTIONS -DHID_API_NO_EXPORT_DEFINE -Ihidapisrc\hidapi hidapisrc\windows\test\no_crt_probe.c -o no_crt_probe_amalgamated.o | ||
| if ($LASTEXITCODE -ne 0) { $ok = $false; continue } | ||
| gcc -nostdlib "-Wl,--entry=mainCRTStartup" "-Wl,--subsystem,console" ` | ||
| -o no_crt_probe_amalgamated.exe no_crt_probe_amalgamated.o -lkernel32 -luser32 -lshlwapi -lgcc | ||
| if ($LASTEXITCODE -ne 0) { $ok = $false; continue } | ||
| } else { | ||
| & $compiler /nologo /c /GS- /Gs9999999 /DHID_API_NO_EXPORT_DEFINE /Ihidapisrc\hidapi hidapisrc\windows\test\no_crt_probe.c /Fo:no_crt_probe.obj | ||
| if ($LASTEXITCODE -ne 0) { $ok = $false; continue } | ||
| link /nologo /NODEFAULTLIB /ENTRY:mainCRTStartup /SUBSYSTEM:CONSOLE ` | ||
| /OUT:no_crt_probe.exe no_crt_probe.obj "$($lib.FullName)" kernel32.lib user32.lib shlwapi.lib | ||
| if ($LASTEXITCODE -ne 0) { $ok = $false; continue } | ||
|
|
||
| & $compiler /nologo /c /GS- /Gs9999999 /DHIDAPI_NO_CRT /DHIDAPI_TEST_MEM_FUNCTIONS /DHID_API_NO_EXPORT_DEFINE /Ihidapisrc\hidapi hidapisrc\windows\test\no_crt_probe.c /Fo:no_crt_probe_amalgamated.obj | ||
| if ($LASTEXITCODE -ne 0) { $ok = $false; continue } | ||
| link /nologo /NODEFAULTLIB /ENTRY:mainCRTStartup /SUBSYSTEM:CONSOLE ` | ||
| /OUT:no_crt_probe_amalgamated.exe no_crt_probe_amalgamated.obj kernel32.lib user32.lib shlwapi.lib | ||
| if ($LASTEXITCODE -ne 0) { $ok = $false; continue } | ||
| } |
There was a problem hiding this comment.
make a small CMake or Make/GMake/NMake script instead of direct compiler/linker invocation, this looks too verbose for a CI script
There was a problem hiding this comment.
Replaced the direct compiler/linker invocations with windows/test/no_crt/CMakeLists.txt. CI now configures/builds both probe targets through CMake for cl, clang-cl, and gcc.
|
|
|
I’ve addressed the review items in ad715f4 and resolved the threads:
The fundamental tradeoff is still real: |
7d92615 to
5720761
Compare
|
Unrelated to this patch please consider registering hidapi in https://github.com/anthropics/oss-scanner it catches interesting bugs and only the maintainers can do the registration (no need to reply if that's not interesting to you). And sorry for the repeated amends, will try to lower them from now on. |
cd82e22 to
7a8e7f2
Compare
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
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
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
|
Added shared-DLL support for Shared no-CRT builds now use a custom
CI now also builds the shared DLL for For size context, I reproduced the official Size comparison (x64, same backend): The normal MSVC |
|
One open design question I’d like your input on before settling the patch: Meson option The Meson wrapper delegates the actual build to a CMake subproject, so a parent Meson project cannot pass I’m unsure whether that belongs in hidapi. A Windows-only, opt-in build mode is fairly specialized, and adding a generic Meson option for it may be more surface area than it’s worth. The alternative is to leave CRT-free builds CMake-only and document that Meson subprojects cannot select it. Longer term, if CRT-free support becomes part of the normal Windows path rather than an opt-in mode, the option would become obsolete anyway. Would you prefer:
Naming Two names feel slightly off to me:
I’m happy to follow whichever naming and integration direction you prefer; I don’t want to be proactive about these until there’s a maintainer preference. |
Keep it CMake-only for now, no Meson-specific documentation is required.
|
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.
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.
HIDAPI's Windows backend uses the CRT for allocation, wide-string operations, and error formatting. That is fine for normal desktop builds, but it can matter when HIDAPI is linked into code that does not control the process runtime: ASI/Mod loader plugins, audio/video plugins, game overlays, and similar injected modules, or a native messaging host. Those hosts may build with
/NODEFAULTLIB, supply their own entry point, or pin a runtime, and a library that pulls in CRT imports can be awkward or impossible to fit. This is not a claim that the UCRT is usually missing or that/MTis not a valid alternative; the narrow case is a host that has already chosen a no-CRT or fixed-runtime model. Binary size can improve as a side effect, but it is not the main argument.This is a suggestion for an opt-in
HIDAPI_NO_CRTmode that uses Win32 allocation, string, and memory helpers instead. The normal CRT build remains the default and itsswprintf/wcstol/towupperpaths are untouched; the replacements are compiled only when the option is enabled. Report descriptor reconstruction is covered by the same helpers.A shared HIDAPI DLL still needs CRT startup unless its consumer supplies a custom entry point, so this only removes CRT function imports; the primary target is static embedding.now it supports DLL generation also.If this is accepted, a reasonable follow-up would be to make the internal helpers inline and use them in the default Windows path as well, so the two implementations can converge into one over the time. The
mem*shims are the part that needs care: they exist for compiler-generated calls, not for HIDAPI's own code, and removing them requires either compiler/linker changes or keeping a small shim. I would not expand this PR to change the default path yet; the safer sequence is to let the opt-in path get some use and CI coverage first. To not make things complicated, it doesn't include meson support but can be provided later.If this does not fit HIDAPI's direction or the maintenance cost is not worth it, closing or ignoring it is completely fine.