carmbuffer-overflowcortex-mcontiki

Why a variable would not be allocated as local in stack


I'm trying to force a buffer overflow to change the value of a variable. The idea is to overflow var_a to change var_b in the following code, which runs Contiki-NG operating system in an ARM Cortex-M4:

#include "contiki.h"
#include "board.h"
#include <dev/leds.h>

#include <stdio.h>
#include <string.h>

PROCESS(main_process, "main_process");

AUTOSTART_PROCESSES(&main_process);

PROCESS_THREAD(main_process, ev, data) {
    uint8_t data_buffer[16] = {
        0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
        0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f
    };

    uint32_t var_b;
    uint8_t var_a[4];

    PROCESS_BEGIN();

    var_b = 0;
    printf("var_b = %08lx\n", var_b);

    memcpy(var_a, data_buffer, 8);
    printf("var_b = %08lx\n", var_b);

    if (var_b) {
        leds_arch_set(LEDS_RED);
    }

    PROCESS_END();
}

The problem is that overflow is not affecting var_b, but data_buffer. I used a debugger to check the addresses of the local variables in the process, and got the following:

enter image description here

Looking at this explains why the overflow is affecting to data_buffer, since it is located right after var_a. But what I didn't expect was that the address of var_b is <outofscope>, which suggests that this variable might be allocated in other memory region different from the current stack frame.

What's the reason for this happening when allocating var_b? Is there any way I can make it local?


Solution

  • A couple suggestions:

    1. You could try disable compiler optimization with -O0 cflags.
    2. Add volatile