GCC compile and link raw output

2019-08-21 06:29发布

问题:

I am trying to get the raw instruction code output for a simple C program with function calls.

I have already searched on here and Google for the answer but can only find answers that are correct for single functions (no function calls).

A trivial example:

int main(){
    return addition(5, 7);
}

int addition(int a, int b){
    return a + b;
}

When I use gcc -c test.c -o test.o and then objdump -d test.o on this, the JAL (jump and link) instruction shows a jump to address 0x00000000 which is obviously incorrect, however when I compile the program fully, I get an enormous amount of junk in the objdump command

I am compiling with the mips compiler (and associated mips-objdump, etc).

The programs I am compiling are self contained (no external libraries, or system include files). What I want is a dump of the instructions where the JAL and equivalent instructions point to the correct addresses for the functions they call.

回答1:

While your code is not linked, the addresses may or may not be resolved (absolute addresses certainly won't be). In the latter case, you should see relocation entries if you use objdump -dr. If you link your program, those issues should be gone, and if the program is really standalone (ie. not even C libraries) then all you see should be your code. You might want to use -nostdlib switch to gcc. I don't have mips gcc available, but here is the x86 version for illustration:

080480d8 <addition>:
 80480d8:       8b 44 24 08             mov    0x8(%esp),%eax
 80480dc:       03 44 24 04             add    0x4(%esp),%eax
 80480e0:       c3                      ret

080480e1 <main>:
 80480e1:       83 ec 08                sub    $0x8,%esp
 80480e4:       c7 44 24 04 07 00 00    movl   $0x7,0x4(%esp)
 80480eb:       00
 80480ec:       c7 04 24 05 00 00 00    movl   $0x5,(%esp)
 80480f3:       e8 e0 ff ff ff          call   80480d8 <addition>
 80480f8:       83 c4 08                add    $0x8,%esp
 80480fb:       c3                      ret

That is all the code in the binary, and as you can see at 80480f3 the call is resolved. I expect it works similarly for mips.