diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index c129ddea..cb38e98e 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -58,6 +58,11 @@ jobs: run: | make build/libllhttp.a + - name: Run dispatch test + shell: bash + run: | + make test-c + - name: Build WebAssembly run: npm run build-wasm if: runner.os == 'Linux' diff --git a/CMakeLists.txt b/CMakeLists.txt index 54ae1b1a..a180b0a7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -35,6 +35,18 @@ set(LLHTTP_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/src/api.c ) +# On x86-64, compile a second instantiation of the parser with SSE4.2 enabled so +# llhttp_execute() can select it at runtime (see src/api.c). The default build +# passes no -march, so the SSE4.2 span scanners in the generated code are +# otherwise never compiled in. Skipped on MSVC (no __builtin_cpu_supports). +if(NOT MSVC AND CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|amd64|AMD64)$") + list(APPEND LLHTTP_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/src/llhttp_sse42.c) + set_source_files_properties( + ${CMAKE_CURRENT_SOURCE_DIR}/src/llhttp_sse42.c + PROPERTIES COMPILE_OPTIONS "-msse4.2" + ) +endif() + set(LLHTTP_HEADERS ${CMAKE_CURRENT_SOURCE_DIR}/include/llhttp.h ) @@ -48,6 +60,13 @@ configure_file( function(config_library target) target_sources(${target} PRIVATE ${LLHTTP_SOURCES} ${LLHTTP_HEADERS}) + # Enable the runtime SSE4.2 dispatch in api.c only where the second object + # (llhttp_sse42.c) is also compiled, so a build without it keeps the baseline + # path and does not reference llhttp__internal_execute_sse42. + if(NOT MSVC AND CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|amd64|AMD64)$") + target_compile_definitions(${target} PRIVATE LLHTTP_SSE42_DISPATCH) + endif() + target_include_directories(${target} PUBLIC $ $ diff --git a/Makefile b/Makefile index 16fe819f..75581316 100644 --- a/Makefile +++ b/Makefile @@ -11,6 +11,25 @@ endif INCLUDES += -Ibuild/ +# On x86-64 (non-Windows), also build a second instantiation of the generated +# parser with -msse4.2 so llhttp_execute() can select the SSE4.2 span scanners +# at runtime (see src/native/api.c). The default build passes no -march, so the +# SSE4.2 code generated under `#ifdef __SSE4_2__` is otherwise never compiled +# in. LLHTTP_SSE42_DISPATCH enables the dispatch in api.c and is defined only +# here, where the second object is also built. Detect the *target* from the +# compiler, not the host (uname -m), so a cross-compile (e.g. CLANG with +# --target=aarch64-...) does not add an x86-only object. Windows/MSVC is +# skipped (no __builtin_cpu_supports), matching the CMake and gyp builds. +TARGET_MACHINE ?= $(shell $(CLANG) $(CFLAGS) -dumpmachine 2>/dev/null) +TARGET_CPU := $(firstword $(subst -, ,$(TARGET_MACHINE))) +IS_WINDOWS := $(or $(findstring windows,$(TARGET_MACHINE)),$(findstring mingw,$(TARGET_MACHINE))) +ifeq (,$(IS_WINDOWS)) +ifneq (,$(filter $(TARGET_CPU),x86_64 amd64)) + SSE42_OBJ = build/c/llhttp_sse42.o + CFLAGS += -DLLHTTP_SSE42_DISPATCH +endif +endif + INSTALL ?= install PREFIX ?= /usr/local LIBDIR = $(PREFIX)/lib @@ -23,17 +42,20 @@ clean: rm -rf build/ rm -rf test/tmp -build/libllhttp.so: build/c/llhttp.o build/native/api.o \ +build/libllhttp.so: build/c/llhttp.o $(SSE42_OBJ) build/native/api.o \ build/native/http.o $(CLANG) -shared $^ -o $@ -build/libllhttp.a: build/c/llhttp.o build/native/api.o \ +build/libllhttp.a: build/c/llhttp.o $(SSE42_OBJ) build/native/api.o \ build/native/http.o - $(AR) rcs $@ build/c/llhttp.o build/native/api.o build/native/http.o + $(AR) rcs $@ build/c/llhttp.o $(SSE42_OBJ) build/native/api.o build/native/http.o build/c/llhttp.o: build/c/llhttp.c $(CLANG) $(CFLAGS) $(INCLUDES) -c $< -o $@ +build/c/llhttp_sse42.o: build/c/llhttp_sse42.c build/c/llhttp.c + $(CLANG) $(CFLAGS) -msse4.2 $(INCLUDES) -c $< -o $@ + build/native/%.o: src/native/%.c build/llhttp.h src/native/api.h \ build/native $(CLANG) $(CFLAGS) $(INCLUDES) -c $< -o $@ @@ -52,6 +74,8 @@ release: clean all generate mkdir -p release/include cp -rf build/llhttp.h release/include/ cp -rf build/c/llhttp.c release/src/ + cp -rf build/c/llhttp_sse42.c release/src/ + cp -rf build/c/llhttp_sse42_rename.h release/src/ cp -rf src/native/*.c release/src/ cp -rf src/llhttp.gyp release/ cp -rf src/common.gypi release/ @@ -87,6 +111,14 @@ postversion: release generate: node --import tsx bin/generate.ts +# Links a small C program against the built library (which contains api.c and, +# on x86-64, both parser instantiations) and drives the runtime dispatch added +# in src/native/api.c. The markdown test suite never compiles api.c. +test-c: build/libllhttp.a + $(CLANG) $(CFLAGS) $(INCLUDES) test/dispatch/dispatch_test.c \ + build/libllhttp.a -o build/dispatch_test + ./build/dispatch_test + install: build/libllhttp.a build/libllhttp.so $(INSTALL) -d $(DESTDIR)$(INCLUDEDIR) $(INSTALL) -d $(DESTDIR)$(LIBDIR) @@ -94,4 +126,4 @@ install: build/libllhttp.a build/libllhttp.so $(INSTALL) -C build/libllhttp.a $(DESTDIR)$(LIBDIR)/libllhttp.a $(INSTALL) build/libllhttp.so $(DESTDIR)$(LIBDIR)/libllhttp.so -.PHONY: all generate clean release postversion github-release +.PHONY: all generate clean release postversion github-release test-c diff --git a/bin/generate.ts b/bin/generate.ts index 727269dd..dbb4c993 100755 --- a/bin/generate.ts +++ b/bin/generate.ts @@ -11,6 +11,8 @@ const semverRE = /^(?0|[1-9]\d*)\.(?0|[1-9]\d*)\.(?0|[1-9]\ const C_FILE = resolve(__dirname, '../build/c/llhttp.c'); const HEADER_FILE = resolve(__dirname, '../build/llhttp.h'); +const SSE42_RENAME_FILE = resolve(__dirname, '../build/c/llhttp_sse42_rename.h'); +const SSE42_C_FILE = resolve(__dirname, '../build/c/llhttp_sse42.c'); const pkg = JSON.parse( readFileSync(resolve(__dirname, '..', 'package.json')).toString(), @@ -49,3 +51,32 @@ ${nativeHeaders} mkdirSync(dirname(C_FILE), { recursive: true }); writeFileSync(HEADER_FILE, headers); writeFileSync(C_FILE, generated.c); + +// A second instantiation of the generated parser, compiled with -msse4.2, lets +// llhttp_execute() use the SSE4.2 span scanners at runtime on default x86-64 +// builds (which pass no -march, so the `#ifdef __SSE4_2__` code is otherwise +// dead). The parser defines symbols prefixed `llhttp__internal`; the callbacks +// it imports are prefixed `llhttp__on`/`llhttp__before`/`llhttp__after` and stay +// shared. Rename only the defined `llhttp__internal*` symbols so the second copy +// links beside the first. Derived from the generated source, so it stays correct +// across grammar changes. +const internalSymbols = Array.from( + new Set(generated.c.match(/\bllhttp__internal[0-9A-Za-z_]*/g) ?? []), +).sort(); +const renameHeader = `/* Generated by bin/generate.ts. Renames the defined symbols of llhttp.c so a + * second, -msse4.2 instantiation (llhttp_sse42.c) can link beside the first. */ +#ifndef INCLUDE_LLHTTP_SSE42_RENAME_H_ +#define INCLUDE_LLHTTP_SSE42_RENAME_H_ +${internalSymbols.map((s) => `#define ${s} ${s}_sse42`).join('\n')} +#endif /* INCLUDE_LLHTTP_SSE42_RENAME_H_ */ +`; +const sse42Wrapper = `/* Generated by bin/generate.ts. See src/native/api.c: a second instantiation of + * the generated parser with the SSE4.2 span scanners enabled, selected once at + * runtime by llhttp_execute(). Built with -msse4.2 by the build system. */ +#if defined(__x86_64__) || defined(_M_X64) +#include "llhttp_sse42_rename.h" +#include "llhttp.c" +#endif +`; +writeFileSync(SSE42_RENAME_FILE, renameHeader); +writeFileSync(SSE42_C_FILE, sse42Wrapper); diff --git a/src/llhttp.gyp b/src/llhttp.gyp index c7b8800a..28bb6425 100644 --- a/src/llhttp.gyp +++ b/src/llhttp.gyp @@ -17,6 +17,37 @@ 'sources': [ '<@(llhttp_sources)', ], + 'conditions': [ + # On x86-64, api.c (llhttp_execute) calls llhttp__internal_execute_sse42, + # a second instantiation of the parser compiled with -msse4.2 and chosen + # at runtime via __builtin_cpu_supports (see src/native/api.c). It is a + # separate target so -msse4.2 applies only to that one translation unit. + # Skipped on MSVC, which has no __builtin_cpu_supports (the dispatch in + # api.c is then compiled out and the symbol is not referenced). + ['OS!="win" and (target_arch=="x64" or target_arch=="x86_64")', { + 'dependencies': [ 'llhttp_sse42' ], + # Enables the dispatch in api.c; defined only here, where the second + # object is also built, so other consumers keep the baseline path. + 'defines': [ 'LLHTTP_SSE42_DISPATCH' ], + }], + ], }, - ] + ], + 'conditions': [ + ['OS!="win" and (target_arch=="x64" or target_arch=="x86_64")', { + 'targets': [ + { + 'target_name': 'llhttp_sse42', + 'type': 'static_library', + 'include_dirs': [ '.', 'include' ], + 'sources': [ 'src/llhttp_sse42.c' ], + 'cflags': [ '-msse4.2' ], + 'cflags_cc': [ '-msse4.2' ], + 'xcode_settings': { + 'OTHER_CFLAGS': [ '-msse4.2' ], + }, + }, + ], + }], + ], } diff --git a/src/native/api.c b/src/native/api.c index ae5e862d..d6add329 100644 --- a/src/native/api.c +++ b/src/native/api.c @@ -122,9 +122,40 @@ void llhttp_reset(llhttp_t* parser) { } +/* Opt-in runtime SSE4.2 dispatch. The build system defines + * LLHTTP_SSE42_DISPATCH only when it also compiles the second parser + * instantiation (llhttp_sse42.c, built with -msse4.2); see the Makefile, + * CMakeLists.txt and src/llhttp.gyp. A consumer that compiles llhttp.c, api.c + * and http.c directly with its own build system (aiohttp, distro packagers, + * other bindings) does not define it and keeps the baseline path, so it needs + * no second object and does not get an unresolved + * llhttp__internal_execute_sse42. _MSC_VER is excluded because MSVC/clang-cl + * lack __builtin_cpu_supports and those builds skip the second object anyway. */ +#if defined(LLHTTP_SSE42_DISPATCH) && \ + (defined(__x86_64__) || defined(_M_X64)) && !defined(__SSE4_2__) && \ + !defined(_MSC_VER) && (defined(__GNUC__) || defined(__clang__)) +/* The second instantiation turns on the SSE4.2 span scanners that the + * generated code guards with `#ifdef __SSE4_2__`; the default x86-64 build (no + * -march) never contains them. Both instantiations come from the same + * generated source, so the parser state layout is identical and a parser may + * be driven by either. */ +llhttp_errno_t llhttp__internal_execute_sse42(llhttp_t* state, const char* p, + const char* endp); + +llhttp_errno_t llhttp_execute(llhttp_t* parser, const char* data, size_t len) { + /* __builtin_cpu_supports only loads and tests __cpu_model, which libgcc / + * compiler-rt initialize in a constructor, so there is no benefit to caching + * the result and no data race from doing without the cache. */ + if (__builtin_cpu_supports("sse4.2")) { + return llhttp__internal_execute_sse42(parser, data, data + len); + } + return llhttp__internal_execute(parser, data, data + len); +} +#else llhttp_errno_t llhttp_execute(llhttp_t* parser, const char* data, size_t len) { return llhttp__internal_execute(parser, data, data + len); } +#endif void llhttp_settings_init(llhttp_settings_t* settings) { diff --git a/test/dispatch/dispatch_test.c b/test/dispatch/dispatch_test.c new file mode 100644 index 00000000..1888fa60 --- /dev/null +++ b/test/dispatch/dispatch_test.c @@ -0,0 +1,212 @@ +/* + * Dispatch test for the runtime SSE4.2 selection in src/native/api.c. + * + * The markdown test suite links the generated parser compiled with -msse4.2 + * directly; it never compiles api.c, so the runtime dispatch added in + * llhttp_execute() is not exercised there. This test links against the built + * library (build/libllhttp.a), which contains api.c and -- on x86-64 -- both + * the baseline parser and the -msse4.2 instantiation selected at runtime. + * + * It parses a request whose header values are long enough to drive the SSE4.2 + * span scanners (they need >= 16 bytes in a span), once in a single call and + * once one byte at a time, and asserts the two runs agree and are correct. + * Feeding one byte at a time keeps spans short, so the scalar fallback inside + * the same dispatched parser is exercised too; the single-shot run takes the + * vector path. Any divergence between them, or any parse error, fails. + */ + +#include +#include + +#include "llhttp.h" + +/* When the library is built with the SSE4.2 dispatch (LLHTTP_SSE42_DISPATCH, + * set by the Makefile/CMake/gyp on x86-64), expose the internal entry point of + * the -msse4.2 instantiation so the test can drive it directly and confirm it + * is linked and correct -- otherwise the test would pass on the baseline path + * alone and never actually prove the SSE4.2 path works. */ +#if defined(LLHTTP_SSE42_DISPATCH) && \ + (defined(__x86_64__) || defined(_M_X64)) && !defined(__SSE4_2__) && \ + !defined(_MSC_VER) && (defined(__GNUC__) || defined(__clang__)) +#define LLHTTP_HAVE_SSE42_ENTRY 1 +llhttp_errno_t llhttp__internal_execute_sse42(llhttp_t* state, const char* p, + const char* endp); +#endif + +static const char kRequest[] = + "GET /de/catalog?q=widget&page=2 HTTP/1.1\r\n" + "Host: shop.example.de\r\n" + "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) " + "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36\r\n" + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9," + "image/avif,image/webp,*/*;q=0.8\r\n" + "Accept-Language: de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7\r\n" + "Cookie: session=0123456789abcdef0123456789abcdef; " + "consent=granted-analytics-marketing-preferences; " + "cart=a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6\r\n" + "\r\n"; + +/* + * All counters are chunk-independent: byte lengths are accumulated across + * however many data callbacks occur, and headers are counted via the + * *_complete callbacks, which fire once per header regardless of how the input + * was split. (The raw on_header_* data callbacks fire once per span piece, so + * their invocation count legitimately differs between single-shot and + * byte-wise feeding -- that is not a divergence.) + */ +typedef struct { + int messages; + int headers; + size_t url_len; + size_t header_field_len; + size_t header_value_len; + int errored; +} counters_t; + +static int on_url(llhttp_t* p, const char* at, size_t len) { + (void) at; + ((counters_t*) p->data)->url_len += len; + return 0; +} + +static int on_header_field(llhttp_t* p, const char* at, size_t len) { + (void) at; + ((counters_t*) p->data)->header_field_len += len; + return 0; +} + +static int on_header_value(llhttp_t* p, const char* at, size_t len) { + (void) at; + ((counters_t*) p->data)->header_value_len += len; + return 0; +} + +static int on_header_value_complete(llhttp_t* p) { + ((counters_t*) p->data)->headers++; + return 0; +} + +static int on_message_complete(llhttp_t* p) { + ((counters_t*) p->data)->messages++; + return 0; +} + +static void init_settings(llhttp_settings_t* s) { + llhttp_settings_init(s); + s->on_url = on_url; + s->on_header_field = on_header_field; + s->on_header_value = on_header_value; + s->on_header_value_complete = on_header_value_complete; + s->on_message_complete = on_message_complete; +} + +/* Returns 0 on HPE_OK, else the error code. */ +static int run(counters_t* c, int chunked) { + llhttp_settings_t settings; + llhttp_t parser; + size_t len = sizeof(kRequest) - 1; + + init_settings(&settings); + llhttp_init(&parser, HTTP_REQUEST, &settings); + memset(c, 0, sizeof(*c)); + parser.data = c; + + if (chunked) { + for (size_t i = 0; i < len; i++) { + llhttp_errno_t err = llhttp_execute(&parser, kRequest + i, 1); + if (err != HPE_OK) { + c->errored = 1; + return (int) err; + } + } + return (int) HPE_OK; + } + + return (int) llhttp_execute(&parser, kRequest, len); +} + +#ifdef LLHTTP_HAVE_SSE42_ENTRY +/* Drive the SSE4.2 instantiation directly (llhttp_execute dispatches to this + * same entry on SSE4.2-capable CPUs). Single shot, so the SSE span scanners + * run. */ +static int run_sse42(counters_t* c) { + llhttp_settings_t settings; + llhttp_t parser; + size_t len = sizeof(kRequest) - 1; + + init_settings(&settings); + llhttp_init(&parser, HTTP_REQUEST, &settings); + memset(c, 0, sizeof(*c)); + parser.data = c; + return (int) llhttp__internal_execute_sse42(&parser, kRequest, kRequest + len); +} +#endif + +static int eq(const counters_t* a, const counters_t* b) { + return a->messages == b->messages && + a->headers == b->headers && + a->url_len == b->url_len && + a->header_field_len == b->header_field_len && + a->header_value_len == b->header_value_len; +} + +int main(void) { + counters_t one_shot, byte_wise; + int err_one = run(&one_shot, 0); + int err_byte = run(&byte_wise, 1); + + if (err_one != (int) HPE_OK) { + fprintf(stderr, "single-shot parse failed: %d\n", err_one); + return 1; + } + if (err_byte != (int) HPE_OK) { + fprintf(stderr, "byte-wise parse failed: %d\n", err_byte); + return 1; + } + if (one_shot.messages != 1) { + fprintf(stderr, "expected 1 message, got %d\n", one_shot.messages); + return 1; + } + if (one_shot.headers != 5) { + fprintf(stderr, "expected 5 headers, got %d\n", one_shot.headers); + return 1; + } + if (!eq(&one_shot, &byte_wise)) { + fprintf(stderr, + "single-shot and byte-wise parses diverged: " + "msgs %d/%d headers %d/%d url %zu/%zu field %zu/%zu value %zu/%zu\n", + one_shot.messages, byte_wise.messages, + one_shot.headers, byte_wise.headers, + one_shot.url_len, byte_wise.url_len, + one_shot.header_field_len, byte_wise.header_field_len, + one_shot.header_value_len, byte_wise.header_value_len); + return 1; + } + +#ifdef LLHTTP_HAVE_SSE42_ENTRY + if (__builtin_cpu_supports("sse4.2")) { + /* The library has the dispatch and this CPU supports SSE4.2, so the + * single-shot run above took the SSE4.2 path. Confirm that instantiation + * is linked and parses identically to the baseline. */ + counters_t sse; + int err_sse = run_sse42(&sse); + if (err_sse != (int) HPE_OK) { + fprintf(stderr, "SSE4.2 instantiation parse failed: %d\n", err_sse); + return 1; + } + if (!eq(&one_shot, &sse)) { + fprintf(stderr, "SSE4.2 instantiation diverged from the baseline parse\n"); + return 1; + } + printf("dispatch test OK: SSE4.2 path exercised and matches baseline; "); + } else { + printf("dispatch test OK (CPU lacks SSE4.2, baseline path): "); + } +#else + printf("dispatch test OK (no SSE4.2 dispatch in this build): "); +#endif + + printf("1 message, %d headers, url=%zu, values=%zu bytes\n", + one_shot.headers, one_shot.url_len, one_shot.header_value_len); + return 0; +}