From 7fecafe015505c0ebd47780050118ff789a9ae3f Mon Sep 17 00:00:00 2001 From: jvoisin Date: Thu, 30 Apr 2026 17:57:51 +0200 Subject: Fix a POSIX violation for swab --- include/unistd.h | 2 +- tests/Makefile | 1 + tests/test_swab_negative.c | 19 +++++++++++++++++++ 3 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 tests/test_swab_negative.c diff --git a/include/unistd.h b/include/unistd.h index a2b3105..a73279b 100644 --- a/include/unistd.h +++ b/include/unistd.h @@ -177,7 +177,7 @@ _FORTIFY_FN(swab) void swab(const void * _FORTIFY_POS0 __os, size_t __bs = __bos(__os, 0); size_t __bd = __bos(__od, 0); - if ((size_t)__n > __bs || (size_t)__n > __bd) + if (__n > 0 && ((size_t)__n > __bs || (size_t)__n > __bd)) __builtin_trap(); return __orig_swab(__os, __od, __n); } diff --git a/tests/Makefile b/tests/Makefile index fbfd178..9fc8287 100644 --- a/tests/Makefile +++ b/tests/Makefile @@ -87,6 +87,7 @@ RUNTIME_TARGETS= \ test_strncpy_static_write \ test_swab_dynamic_read \ test_swab_dynamic_write \ + test_swab_negative \ test_swab_static_read \ test_ttyname_r_dynamic \ test_ttyname_r_static \ diff --git a/tests/test_swab_negative.c b/tests/test_swab_negative.c new file mode 100644 index 0000000..f9c182b --- /dev/null +++ b/tests/test_swab_negative.c @@ -0,0 +1,19 @@ +#include "common.h" + +#include + +int main(int argc, char** argv) { + char src[8] = "ABCDEFG"; + char dst[8] = {0}; + + /* Positive case: normal swab works */ + swab(src, dst, 6); + puts(dst); + + /* Negative n: POSIX says swab does nothing, must NOT trap */ + swab(src, dst, -1); + swab(src, dst, -100); + + puts(dst); + return ret; +} -- cgit v1.3