Thursday, September 21, 2017

Pointer to certain address in memory

In embedded system where we are working with microcontroller, many times we find a scenario where we need to access a memory-mapped register in the MCU.  How do we do that in generic way (for example with GCC compiler)?

The answer is to write it like below:

volatile <type> *<varname> = (<type> *)<address>

For example:

#include <stdio.h>

volatile char *var = (char *)0x1000;

int main()
{
    if (*var != 0)
        puts("NOT NULL!");
}

rendered into x86 assembly (64-bit Intel CPU) as:
...
...
.LC0:
        .string "NOT NULL!"

main:
movq var(%rip), %rax      # rax = address of var
movzbl (%rax), %eax         # eax = *var
testb %al, %al
jne .L9
xorl %eax, %eax
ret
.L9:
pushq %rax
movl $.LC0, %edi
call puts
xorl %eax, %eax
popq %rdx
ret

...
.LCOLDE1:
.section .text.startup
.LHOTE1:
.globl var
.data
.align 8
.type var, @object
.size var, 8
var:
.quad 4096           # or 0x1000

No comments:

Post a Comment