opnsense-src/lib/libc/stdlib/memalignment.c
Robert Clausecker 24ea81047d lib/libc: implement C23 memalignment()
This new function computes the alignment of a pointer.
It is part of ISO/IEC 9899:2024, the new C standard.
If the pointer is a null pointer, null is returned.
I have tried to write an implementation that can cope
with traditional address-based architectures, even if
size_t and uintptr_t are of different length.  Adjustments
may be needed for CHERI though.

A man page is provided, too.  No unit test for now.

Reviewed by:	kib, imp, ziaee (manpages), pauamma@gundo.com
Approved by:	markj (mentor)
MFC after:	1 month
Relnotes:	yes
Differential Revision:	https://reviews.freebsd.org/D53673

(cherry picked from commit 6c57e368eb1777f6097158eeca2fcc175d068dba)
2025-12-12 11:32:58 +01:00

28 lines
452 B
C

/*
* Copyright (c) 2025 Robert Clausecker <fuz@FreeBSD.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <stdint.h>
#include <stdlib.h>
size_t
memalignment(const void *p)
{
uintptr_t align;
if (p == NULL)
return (0);
align = (uintptr_t)p;
align &= -align;
#if UINTPTR_MAX > SIZE_MAX
/* if alignment overflows size_t, return maximum possible */
if (align > SIZE_MAX)
align = SIZE_MAX - SIZE_MAX/2;
#endif
return (align);
}