Follow @Openwall on Twitter for new release announcements and other news
[<prev] [next>] [<thread-prev] [day] [month] [year] [list]
Message-ID: <20260626083101.39587-1-florian.schmaus@codasip.com>
Date: Fri, 26 Jun 2026 10:31:01 +0200
From: Florian Schmaus <florian.schmaus@...asip.com>
To: musl@...ts.openwall.com
Cc: Florian Schmaus <florian.schmaus@...asip.com>
Subject: [PATCH v3]  qsort: align 'tmp' buffer to improve codegen and preserve CHERI capabilities

The cycle() function in qsort.c uses a local stack buffer 'tmp' to
temporarily hold elements being permuted.

Previously, 'tmp' was declared as an 'unsigned char' array, which only
guarantees a 1-byte alignment. By changing the buffer type to a union
with a void pointer member, we force the compiler to align the stack
allocation to the architectural pointer alignment boundary.

Guaranteeing this alignment provides a twofold benefit. First, it may
improve code generation in the future, particularly if the use of
__builtin_memcpy is ever enabled for these buffer copies.

Second, because qsort is pure library code that is easily reused
outside of musl, this change facilitates its deployment on CHERI
architectures (e.g., CHERI RISC-V). On CHERI systems, pointers are
capabilities that include an out-of-band hardware tag bit. Storing
these capabilities in an unaligned buffer can cause the processor to
strip the validity tags, resulting in a capability fault when
dereferenced later. Forcing pointer-boundary alignment ensures these
tags remain intact.
---
Changes in v3:
- Adjust commit message to motivate change via codegen improvements
  (no functional changes)

 src/stdlib/qsort.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)

diff --git a/src/stdlib/qsort.c b/src/stdlib/qsort.c
index 28607450b885..ffd523f7cd8c 100644
--- a/src/stdlib/qsort.c
+++ b/src/stdlib/qsort.c
@@ -44,7 +44,12 @@ static inline int pntz(size_t p[2]) {
 
 static void cycle(size_t width, unsigned char* ar[], int n)
 {
-	unsigned char tmp[256];
+	/* Union forces pointer alignment to preserve CHERI capability tags */
+	union {
+		unsigned char c[256];
+		void *p;
+	} tmp_u;
+	unsigned char *tmp = tmp_u.c;
 	size_t l;
 	int i;
 
-- 
2.53.0

Powered by blists - more mailing lists

Confused about mailing lists and their use? Read about mailing lists on Wikipedia and check out these guidelines on proper formatting of your messages.