Quantcast
Viewing all articles
Browse latest Browse all 22067

Preventing Compiler from optimizing code without the use of volatile

I'm trying to create a kernel from scratch (just trying something new)

Everything is ready now and I'm testing the output and noticed something very weird

I build my files with:

gcc ./kernel/kernel.c -ffreestanding -O0 -m32 -c -o./bin/kernel.o -fno-pie

and link them together with:

ld -nostdlib -nodefaultlibs -Tlink.ld ./bin/kernel_ep.elf.bin ./bin/kernel.o -o ./bin/kernel.bin

So from my understanding, I already tell the compiler NOT to optimize my code.

Now the C part

#define BYTE unsigned char
#define VIDMEM ((BYTE*)0xb8000)

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

void print(char *msg)
{
    volatile BYTE *screen = VIDMEM;
    for(const char *msgPtr = msg; *msgPtr; ++msgPtr)
    {
        *(screen++) = *msgPtr;
        screen++;
    }
}

void init() {
    //volatile char test[] = "Test";
    //print(test);
    print("Test");    
}

If i run this, nothing will happen, I checked the whole thing in ghidra - the char array of "Test" is in the memory, but I have no reference to init() -> So print never gets called.

If I now use the commented text (and comment print("Test")) everything works fine, text gets printed the way I want.

But the real question is: Is there some kind of "Trick" to tell the compiler NOT to optimize this code except using volatile? because I don't think declearing everything which could maybe be printed as volatile is the way I should do this.

As far as I understand, the main problem is that the print function basically does nothing, because the compiler doesn't seem to know that 0xb8000 is a kinda... special adress.


Viewing all articles
Browse latest Browse all 22067

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>