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:
        .string "NOT NULL!"

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

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

No comments:

Post a Comment