Page 1 of 1

code optimization

Posted: Fri Mar 18, 2011 6:51 am
by otenki
I have been starting to write my first os in c but I have a question concerning optimisation by the compiler.
I have written an interupt handler and for testing that it works I have put a simple printk() inside which writes to the screen whenever I receive an interupt.
So my ouput would be something like:
"Interupt fired: 0x03"

When I compile my code with -O however I get a page full of: "Interupt fired:0x0d after the normal 0x3 interupt has been fired.
So I looked at the error part of the Global Protection Fault and checked the address in my kernel disasembly.
And this was somewhere in the .bss section where my GDT pointer is.

So my question is how can optimization affect this and how do I go about debugging this and fixing it?
I'm a bit stuck in this so any help would bring much rejoicing :-)

Thanks,
Otenki

Re: code optimization

Posted: Fri Mar 18, 2011 7:05 am
by Combuster
Reduce the problem first. Can you do "nothing" on an int 3, and see if you still get the GPF afterwards? How much do you need to add back before the problem reappears? At least you'll know what code to investigate deeper (i.e. look at disassemblies and singlestep through it).

Re: code optimization

Posted: Fri Mar 18, 2011 7:21 am
by Solar
Generally speaking, if changing the optimization settings of your compiler breaks your program, it's your code that is broken, not your compiler.

One-in-a-million exceptions to the rule notwithstanding.

Combuster already hinted at the "reduce the problem" approach. I call it Machete Debugging.

Re: code optimization

Posted: Fri Mar 18, 2011 11:46 am
by Tosi
I compile everything with -O2 from the beginning, it helps me catch bugs earlier and faster code is always better.
If I need to debug heavily I will remove the optimization as the optimizer moves things around and can make heavy-duty debugging difficult.
-O3 can be a good way to find bugs, but can also be a good way to create bugs ex nihil. This especially holds true in OS development if you aren't careful with multithreaded code and don't declare necessary variables volatile.

Another, better way is to catch some bugs at compile time. Turning on all compiler warnings and making it treat them as errors is a good way to spot some bugs that you could have spent an hour debugging.