commit 7fecafe015505c0ebd47780050118ff789a9ae3f
parent dfdf53df99c8f59e5e3a4296c455041bee96a88d
Author: jvoisin <julien.voisin@dustri.org>
Date: Thu, 30 Apr 2026 17:57:51 +0200
Fix a POSIX violation for swab
Diffstat:
3 files changed, 21 insertions(+), 1 deletion(-)
diff --git 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
@@ -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
@@ -0,0 +1,19 @@
+#include "common.h"
+
+#include <unistd.h>
+
+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;
+}