Skip to content

ATOMIC_VALUE might return inconsistent values on avr8 (or other 8bit mcu) #6491

@melshuber

Description

@melshuber

threre might an issue in ATOMIC_VALUE(...) on avr8

#include <atomic.h>

atomic_int_t atomic = ATOMIC_INIT(0);

int atomic_val(void) {
    return ATOMIC_VALUE(atomic);
}

int main(void)
{
    while (1);
}

copiles to

$ BOARD=arduino-mega2560 make
$ avr-objdump -S bin/arduino-mega2560/atomic/main.o

Disassembly of section .text.atomic_val:

00000000 <atomic_val>:
#include <atomic.h>

atomic_int_t atomic = ATOMIC_INIT(0);

int atomic_val(void) {
    return ATOMIC_VALUE(atomic);
   0:	80 91 00 00 	lds	r24, 0x0000
   4:	90 91 00 00 	lds	r25, 0x0000
}
   8:	08 95       	ret

Disassembly of section .text.startup.main:

00000000 <main>:

int main(void)
{
   0:	00 c0       	rjmp	.+0      	; 0x2 <__zero_reg__+0x1>

you see two lds instructions in atomic_val()

Problem case: Suppose a higher priority thread interrupts just after the first lds and changes the value itself to 0xFFFF. In this case an inconsistent value would be returned (endianness depended either 0xFF or 0xFF00)

The correct behavior should be return either the old or the new value

Metadata

Metadata

Assignees

Labels

Platform: AVRPlatform: This PR/issue effects AVR-based platformsType: bugThe issue reports a bug / The PR fixes a bug (including spelling errors)

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions