Tuesday, April 25, 2006

Deeper insight into gcc

The Problem
This is just a continuation of analysis of the "x86 Hello World" written and tested on my pc which is an AMD Athelon one. It worked well and its an i686 arch. Came back to my office and to my annoyment found it didnt work that well, ofcourse it SEGFAULTED. For an introduction, here is the link to the analysis of that code in my wiki:

LINK > x86 Hello World

And the version of GCC is 3.4.2 20041017.

The Discussion:
Me and a few others at the office were discussing (late night! OOPS) regarding this and told them that the linker tends to align the code in the 16-byte segment and this might be the problem. To my surprise i found its not actually true.

The Clarity
The alignment of the code and the block is decided by the compiler/linker depending on the architecture it has. Moreover my analysis on the "16-byte alignment" stuff didnt work that well in my PC at office though they both are the same with respect to architecture. So, it has become clear that dear GCC is playing some trick.

The Observation
Now comes the result, i didnt notice the version of GCC i have at home. But its going to be of no use. So, generated the assembly code out of the C-code and to my surprise found the code below in the assembly dump:


.section .note.GNU-stack,"",@progbits

It was a bit disturbing, coz i didnt get the above line at my home. So, i removed it and tried compiling the assembly code and BINGO, it worked. The code is processed and the "Hello World!" was at my sight. Replacing the above line back made the code to SEGFAULT.

The Result
Im still not sure as to why the above line has to make my code SEGFAULT. What i suspect is that the addition of that above innocent line makes some of the code to offset to a different location and that few things gets offsetted. Im yet to confirm the actual reason and would update the Wiki with this observation.

Yet, its still interesting to find how the compiler/linker could've been constructed by making all these stuff and experimenting, and so i believe there certainly exists "Pleasure in Finding Things out...".

No comments: