简体   繁体   中英

ARM assembly. Storing and loading data from stack with negative offset

Can we store and load data from the stack with negative address offset like in the following code snippet? Is it safe to write and read data from the memory address that is actually outside ( [sp, #-16] or [sp, #-20] ) of the stack boundaries? Thanks!

stmdb sp, { r4 - r6 }

mov r4, #255
str r4, [sp, #-16]

mov r3, #127
str r3, [sp, #-20]

ldr r4, [sp, #-20]

sub sp, #12
ldmia sp, { r4 - r6 }

This is a question of ABI, rather than architecture or language, so ultimately it depends on the operating environment and ABI in force.

Whilst you can access addresses below SP, in the sense that a load or store with a base register of r13 and a negative offset is a perfectly valid instruction, it's only the ABI which dictates whether your data will be safe there or not, and whether such an access is guaranteed not to segfault in the first place. Most systems in current use will probably be using some variant of the ARM EABI, whose procedure call standard says, as part of "Universal stack constraints":

A process may only access (for reading or writing) the closed interval of the entire stack delimited by [SP, stack-base – 1] (where SP is the value of register r13).

ie Whilst nothing will actually prevent you violating that constraint, try it and all bets are off.

Since you mention Android, which is definitely EABI (specifically the GNU variant), the most obvious concern there is the way the Linux kernel delivers signals. If your process happens to take a signal immediately after str r3, [sp, #-20] , a signal handler may run using the process stack, so when (if) normal execution resumes, whilst SP itself will be back to the same value it was before, who knows what ldr r4, [sp, #-20] will actually load.

Note that some environments might give certain additional guarantees about what goes on below the stack pointer, and if you're in a bare-metal scenario or otherwise in complete control then you can do whatever you like, but generally, unless you know otherwise then assume the answer to be "no".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM