Thursday 21 September 2017

SPO600 - Lab 2 - Compiled C Lab

In lab 2 we will be investigating C source code and the output of the C compiler.

The source code we will be working with is a basic Hello World C program:
#include <stdio.h>

int main() {
    printf("Hello World!\n");
}
We will be compiling this program using the "gcc" command along with the following compiler options:
-g - enable debugging information
-O0 - do not optimise
-fno-builtin - do not use builtin function optimizations

After compiling, the size of the file is 73088 bytes. Using the objdump command, we can examine the binary object that was produced and see that there are more than 30 different sections, in which ".text" is the section that holds our code. By closely inspecting the output of our objdump command, we can also see the that string that our program is intended to print is stored in the .rodata section:
Contents of section .rodata:
 400660 01000200 00000000 00000000 00000000  ................
 400670 00000000 00000000 00000000 00000000  ................
 400680 48656c6c 6f20576f 726c6421 0a00      Hello World!..

Now we will attempt to re-compile the code with different options and examine the changes in the output file:
Adding the "-static" option to the compiling command has increased the file size to 834,456 bytes. Examining the binary object using objdump will result in a longer waiting time (until the system finishes printing the entire output, due to the sections containing more information and requiring longer process time for the program.
Next, we will try compiling the program without the "-fno-builtin" option in the command. We can see that the file size has decreased slightly to 834,448 bytes. This cancels the use of built-in optimisation functions.
Next, we will re-compile the code again, this time removing the "-g" option from the compiling command. We can note that the file size has reduced to 832,032 bytes. The decrease in size is for the reason debugging information isn't enabled, thus shortening the size/process requirements.

Adding additional arguments (numbers 1-8 and two strings) to the code results in every argument being moved to a register and added to a stack:

Now, we will move the printf() function to a new function called output() and call that function from the main() function:
Compiling the code and examining the object binary, we can note that the objects of our function that previously resided in <main> section, have been moved to a new section called <output>, whereas the <main> section refers and calls the <output> section and executes it.

Lastly, we will now remove the "-O0" options from our compiling command and add "-O3" instead of it. Changing the 0 to 3, enables more levels of optimisation to your code, which invokes all optimisation features available.


No comments:

Post a Comment