ARM Technical Support Knowledge Articles

How can I protect against stack overflow at run-time?

Applies to: DS-5

Answer

There are many different ways to measure stack usage to help developers calculate how much stack is required for a given application.  These techniques are discussed in the armcc User Guide.

One of the techniques is to use a debugger to set a watchpoint on the last available location on the stack and see if the watchpoint is ever hit.  However, watchpoints will not be available when the final application is released.  In ARM Compiler 5 there is an option called --protect_stack that provides a way to protect against stack overflow at run-time.  More information about this option can be found in the armcc User Guide.

The example below built with --protect_stack will cause the compiler to add some stack checking code to the beginning of the copy() function.  If the stack checking code detects that the __stack_chk_guard guard variable has been overwritten it will make a call to the __stack_chk_fail() function.

#include <string.h>

void * __stack_chk_guard = (void *)(0xDEADBEEF);     // initialize guard variable

void __stack_chk_fail(void)                          // called by stack checking code if guard variable is corrupted
{
  /* report error */                                 
}

void copy(const char *p)
{
  char buf[4];
  strcpy(buf, p);
}

Rather than the stack_chk_fail() function reporting an error itself, it could alternatively report the error to the operating system by making a supervisor call, provided that the operating system uses a separate stack.  For example:

void __svc(43) stack_overflow(const char *string);   // SVC declaration (43 is an example of a code an OS may use to determine a stack overflow) 

void __stack_chk_fail(void)                          // Called by stack checking code if guard variable is corrupted
{
  stack_overflow("DEAD CANARY!");                    // Generate supervisor call and pass string to OS
}

The operating system could then decide how to handle the stack being full, for example, it could allocate some more stack space or reset the system.

See also:

Article last edited on: 2015-04-28 10:51:08

Rate this article

[Bad]
|
|
[Good]
Disagree? Move your mouse over the bar and click

Did you find this article helpful? Yes No

How can we improve this article?

Link to this article
Copyright © 2011 ARM Limited. All rights reserved. External (Open), Non-Confidential