Skip to content

Commit 0e61321

Browse files
committed
Document STACKMAN_SP_FURTHEST/NEAREST overflow risk
Add comprehensive documentation warning that STACKMAN_SP_FURTHEST and STACKMAN_SP_NEAREST are sentinel values that should only be used for comparison operations (SP_LS, SP_LE) and never for arithmetic operations (SP_ADD, SP_DIFF) due to risk of pointer overflow when operating on addresses at extreme ends of the address space.
1 parent 0499946 commit 0e61321

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

stackman/stackman.h

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,24 @@
8484
#define STACKMAN_SP_ALIGN_DOWN(a) (((intptr_t)(a) & ~(STACKMAN_STACK_ALIGN-1)))
8585
#define STACKMAN_SP_ALIGN_UP(a) (((intptr_t)((a)+STACKMAN_STACK_ALIGN-1) & ~(STACKMAN_STACK_ALIGN-1)))
8686

87+
/* Stack pointer manipulation macros that work for both descending and ascending stacks.
88+
*
89+
* STACKMAN_SP_FURTHEST and STACKMAN_SP_NEAREST are sentinel values representing the
90+
* theoretical limits of the stack address space. These should be used for initialization
91+
* and comparison only.
92+
*
93+
* WARNING: Do NOT use STACKMAN_SP_FURTHEST or STACKMAN_SP_NEAREST with STACKMAN_SP_ADD
94+
* or STACKMAN_SP_DIFF operations, as these sentinel values are at the extreme ends of
95+
* the address space and arithmetic operations with them can cause pointer overflow and
96+
* undefined behavior.
97+
*
98+
* Safe operations with FURTHEST/NEAREST: STACKMAN_SP_LS, STACKMAN_SP_LE (comparison)
99+
* Unsafe operations: STACKMAN_SP_ADD, STACKMAN_SP_DIFF (arithmetic)
100+
*
101+
* For actual stack boundaries, use real pointer values (e.g., address of a stack variable).
102+
* The sentinel values can be used instead if the stack bounds are unknown, but then the value
103+
* should always be checked first for the sentinel value before performing any arithmetic operations.
104+
*/
87105
#if STACKMAN_STACK_DIR == 0
88106
#define STACKMAN_SP_FURTHEST ((void*) (intptr_t) -STACKMAN_STACK_ALIGN)
89107
#define STACKMAN_SP_NEAREST ((void*) 0)

0 commit comments

Comments
 (0)