Skip to content

windows: opt-in CRT-free build - #860

Open
ebraminio wants to merge 5 commits into
libusb:masterfrom
ebraminio:crt-free
Open

ebraminio wants to merge 5 commits into
libusb:masterfrom
ebraminio:crt-free

Conversation

@ebraminio

@ebraminio ebraminio commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

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 /MT is 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_CRT mode that uses Win32 allocation, string, and memory helpers instead. The normal CRT build remains the default and its swprintf/wcstol/towupper paths 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.

@ebraminio
ebraminio force-pushed the crt-free branch 11 times, most recently from 3b6c69d to 4f86d3b Compare November 20, 2026 01:38
@mcuee mcuee added the Windows Related to Windows backend label Nov 22, 2026
@ebraminio
ebraminio force-pushed the crt-free branch 10 times, most recently from ac98609 to f7156d3 Compare November 22, 2026 12:45
@ebraminio
ebraminio force-pushed the crt-free branch 4 times, most recently from 826b88f to ddf3e3d Compare November 25, 2026 12:11
Comment thread windows/hidapi_descriptor_reconstruct.c Resolved
Comment thread .github/workflows/builds.yml Resolved
@ebraminio

Copy link
Copy Markdown
Contributor Author

The runtime mem* test is needed because of a clang-cl-specific failure mode, not just a link/import check.

On x64, SecureZeroMemory/__stosb is lowered by clang-cl to an external memset call. The previous implementation satisfied that symbol with a separate shim whose memset also used __stosb, producing:

<memset>:
    jmp memset

The link succeeded, so the existing probe only checking dependencies and hid_init/hid_exit passed, but the first actual memset recursed until timeout.

This commit now builds the probe two ways:

  • The regular probe links the static library and does not test mem*.
  • The HIDAPI_TEST_MEM_FUNCTIONS probe includes the actual hid.c/descriptor sources and calls hid_internal_memset, hid_internal_memcpy, and hid_internal_memcmp directly, so a lowering back to the missing/recursive standard symbols is caught at runtime.

The library itself no longer exports memset, memcpy, or memcmp.

@ebraminio
ebraminio marked this pull request as ready for review November 25, 2026 15:16
@ebraminio

ebraminio commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor Author

This became a bit complicated to review because of the reviewer call for renaming callsites instead of just undef (which is reasonable request but made the the diff a bit more lengthy, I wanted to make sure the most small possible change is in first then try to gradually to change callsites for CRT agnostic implementation)

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 mem* function for the rest of the project someone wants this.

Sorry for the noise, please review this the way you see best.

Comment thread windows/CMakeLists.txt Outdated
# __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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this only for test or for normal operation too?

@ebraminio ebraminio Nov 25, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@ebraminio ebraminio Nov 26, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 KiB
  • 8 * 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.

Comment thread windows/CMakeLists.txt Outdated

if(HIDAPI_NO_CRT)
target_compile_definitions(hidapi_winapi PRIVATE HIDAPI_NO_CRT)
target_link_libraries(hidapi_winapi PUBLIC shlwapi)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

where do we introduce this dependencty as public?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@ebraminio ebraminio Nov 25, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here is a tested prototype that removes shlwapi entirely, not just the link line. It is not committed.

The two shlwapi uses are:

  • StrStrW for HIDAPI_WCSSTR
  • wnsprintfW for 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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shlwapi is not a problem as a dependency, just make sure it is private

@ebraminio ebraminio Nov 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread .github/workflows/builds.yml Resolved
Comment thread .github/workflows/builds.yml Outdated
Comment on lines +389 to +413
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 }
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

make a small CMake or Make/GMake/NMake script instead of direct compiler/linker invocation, this looks too verbose for a CI script

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread windows/hidapi_winapi_crt.h Resolved
@Youw

Youw commented Nov 25, 2026

Copy link
Copy Markdown
Member

windows/hidapi_winapi_crt.h is the only thing I haven't properly reviewed yet, I'll get back to it shortly. Everhting else - already has my review commenst

@ebraminio

Copy link
Copy Markdown
Contributor Author

I’ve addressed the review items in ad715f4 and resolved the threads:

  • HIDAPI_WCSTOL → explicit HIDAPI_WCSTOL_HEX
  • shlwapi is now a PRIVATE implementation dependency
  • CI probe builds moved into windows/test/no_crt/CMakeLists.txt
  • CMake configuration arguments split one per line
  • Removed the remaining compiler-generated memset from the aggregate zero-initialization

The fundamental tradeoff is still real: HIDAPI_NO_CRT has to prevent every compiler-generated CRT libcall, not just the ones we call explicitly. The CI now links and runs both probes across MSVC, clang-cl, and GCC, so a regression should be caught, but it does add maintenance sensitivity to compiler code generation. If maintainers conclude that burden is not worth an opt-in mode, I understand closing this rather than forcing it in.

@ebraminio
ebraminio force-pushed the crt-free branch 4 times, most recently from 7d92615 to 5720761 Compare November 26, 2026 07:24
@ebraminio

ebraminio commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor Author

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.

@ebraminio
ebraminio force-pushed the crt-free branch 4 times, most recently from cd82e22 to 7a8e7f2 Compare November 26, 2026 09:19
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
@ebraminio

Copy link
Copy Markdown
Contributor Author

Added shared-DLL support for HIDAPI_NO_CRT in fd0832d.

Shared no-CRT builds now use a custom DllMain and no default libraries:

  • MSVC/clang-cl: /NODEFAULTLIB /ENTRY:DllMain
  • MinGW: -nostdlib -nodefaultlibs -Wl,--entry=DllMain

CI now also builds the shared DLL for cl, clang-cl, and gcc, checks that it has no CRT imports, and checks the hid_init export.

For size context, I reproduced the official hidapi-0.16.0 x64 release from tag 750c87a using windows/hidapi.vcxproj (MSBuild Release|x64, /MT static CRT, LTCG). It is exactly 169,472 bytes and imports only KERNEL32.dll.

Size comparison (x64, same backend):

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 normal MSVC /MD build is also 42,496 bytes, but imports VCRUNTIME140.dll and the UCRT API sets. The no-CRT builds import only KERNEL32.dll, USER32.dll, and SHLWAPI.dll.

@ebraminio

ebraminio commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor Author

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 HIDAPI_NO_CRT through something like c_args; I confirmed that path does not reach the CMake target. Exposing the CRT-free build through Meson would therefore require a dedicated Meson option that translates to a CMake define.

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:

  • no Meson option, keeping this CMake-only for now;
  • a Meson no_crt option; or
  • deferring the Meson integration until the long-term direction is clearer?

Naming

Two names feel slightly off to me:

  • windows/hidapi_winapi_crt.h: the header now provides either normal CRT-based macros or the WinAPI-backed compatibility shim. The crt part describes only one branch, and winapi is redundant under windows/. I was thinking something like hidapi_runtime.h, hidapi_compat.h, hidapi_crt.h or hidapi_crt_compat.h, but I don’t feel strongly.
  • windows/hidapi_winapi_nocrt_dllmain.c: accurate for the current opt-in CRT-free shared build (aside winapi feels being redundant), but long and tied to the mode. If CRT-free eventually becomes the normal path, hidapi_winapi_entry.c or hidapi_winapi_dllmain.c might age better.

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.

@Youw

Youw commented Nov 27, 2026

Copy link
Copy Markdown
Member

Meson option

Keep it CMake-only for now, no Meson-specific documentation is required.

Naming

  • hidapi_winapi_dllmain.c seem fine even now, when it is used optionally
  • windows/hidapi_winapi_crt_compat.h - it is what it is, this name is explicit leaves zero room for misinterpretation; if it feels too verbose - I don't think we should agree to anything less than windows/hidapi_crt_compat.h

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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Windows Related to Windows backend

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants