Possible false-positive Out of bound memory access (access exceeds upper limit of memory block)

Hello,

I’m probably experiencing false-positive with following configuration and code snippet. Could you please elaborate and let me know if I’m right.

I’m using following configuration:

Problematic code snippet can be found below or here

uint16_t SYSTEM_get_stack_left(void)
{
    const uint8_t *p = &_end;
    uint16_t       c = 0;

    while( p <= &__stack && *p == STACK_CANARY )
    {
        p++;
        c++;
    }

    return c;
}

I think, that this is false-positive, because while loop starts iterating from &__end address, which is end address of (.bss + .data ) sections e.g. 0x0100u till &__stack address, which is end of RAM address e.g. 0x045Fu. In my opinion it is totally legit to deference pointer set to &__stack. Please tell me if I’m right or maybe when I’m missing something

Hello Dawid, and welcome to the community!

The code you mention has undefined behavior according to C11 standard (see section 6.5.8) because you are comparing pointers to _end and __stack objects that do not belong to the same array or aggregate.
Therefore all bets are off, and the C standard cannot guarantee anything at this point.

I see you are relying on the assembly code to ensure the correct position of __stack and _end in the inline assembly in SYSTEM_stack_paint. Unfortunately, our analyzer cannot take this into account (for technical reasons it treats the inline assembly code as a black box).

Hence, from the C language point of view, and ignoring the contents of the inline assembly part, the p pointer starts from an object _end, and once it increments, it is not guaranteed to point to anything meaningful and dereferencing it might result in accessing invalid memory (according to the C semantics).

SonarCloud analysis works with your code on this level which results in the issue you mentioned.

Now on the practical level, your code might be safe and, given the platform you use and the implementation of the compiler and the assembler, this might well be a false positive.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.