Annotation of wikisrc/examples/elf_executables_for_powerpc.mdwn, revision 1.3

1.2       schmonz     1: **Contents**
                      3: [[!toc levels=3]]
                      5: #   Introduction 
                      7: This wiki page examines the transformation of a very simple C program into a running ELF executable containing PowerPC machine code. A NetBSD system (NetBSD 4.0.1/macppc in these examples) and its toolchain (gcc and GNU binutils) perform several steps in this transformation. 
                      9:   1. gcc translates our C code to assembly code. 
                     10:   2. gcc calls GNU as to translate the assembly code to machine code in an ELF relocatable object. 
                     11:   3. gcc calls GNU ld to link our relocatable object with the C runtime and the C library to form an ELF executable object. 
                     12:   4. NetBSD kernel loads ld.elf_so, which loads our ELF executable and the C library (an ELF shared object) to run our program. 
                     14: _So far, this wiki page examines only the first two steps._
                     16: #   A very simple C program 
1.3     ! kim        18: This program is only one C file, which contains only one main function, which calls [[!template id=man name="printf" section="3"]] to print a single message, then returns 0 as the exit status. 
1.2       schmonz    19:     
                     22:     #include <stdio.h>
                     24:     int
                     25:     main(int argc, char *argv[])
                     26:     {
                     27:        printf("%s", "Greetings, Earth!\n");
                     28:        return 0;
                     29:     }
1.3     ! kim        32: The C compiler _gcc_ likes to use its knowledge of builtin functions to manipulate code. The version of gcc in NetBSD 4.0.1/macppc will simplify the printf statement to puts("Greeting, Earth!"); so the main function effectively calls [[!template id=man name="puts" section="3"]] once and then returns 0. 
1.2       schmonz    33: 
1.3     ! kim        35: We can apply [[!template id=man name="gcc" section="1"]] in the usual way to compile this program. (With NetBSD, _cc_ or _gcc_ invokes the same command, so we use either name.) Then we can run our program: 
1.2       schmonz    36:     
                     38: $ cc -o greetings greetings.c
                     39:     $ ./greetings
                     40:     Greetings, Earth!
                     41:     $
                     44: We can apply gcc with the _-v_ option to see some extra information. (Unlike most other commands, gcc does not allow combined options. Instead of _gcc -vo_, we must type _gcc -v -o_.) The gcc driver program actually runs three other commands. Here is the output from one run using my NetBSD 4.0.1 system. I have put the three commands in **bold**. 
                     46:     $ cc -v -o greetings greetings.c
                     47:     Using built-in specs.
                     48:     Target: powerpc--netbsd
                     49:     Configured with: /usr/src/tools/gcc/../../gnu/dist/gcc4/configure --enable-long-
                     50:     long --disable-multilib --enable-threads --disable-symvers --build=i386-unknown-
                     51:     netbsdelf4.99.3 --host=powerpc--netbsd --target=powerpc--netbsd
                     52:     Thread model: posix
                     53:     gcc version 4.1.2 20061021 prerelease (NetBSD nb3 20061125)
                     54:      **/usr/libexec/cc1 -quiet -v greetings.c -quiet -dumpbase greetings.c -auxbase gr**
                     55:     **eetings -version -o /var/tmp//ccVB1DcZ.s**
                     56:     #include "..." search starts here:
                     57:     #include <...> search starts here:
                     58:      /usr/include
                     59:     End of search list.
                     60:     GNU C version 4.1.2 20061021 prerelease (NetBSD nb3 20061125) (powerpc--netbsd)
                     61:        compiled by GNU C version 4.1.2 20061021 (prerelease) (NetBSD nb3 200611
                     62:     25).
                     63:     GGC heuristics: --param ggc-min-expand=38 --param ggc-min-heapsize=77491
                     64:     Compiler executable checksum: 325f59dbd937debe20281bd6a60a4aef
                     65:      **as -mppc -many -V -Qy -o /var/tmp//ccMiXutV.o /var/tmp//ccVB1DcZ.s**
                     66:     GNU assembler version 2.16.1 (powerpc--netbsd) using BFD version 2.16.1
                     67:      **ld --eh-frame-hdr -dc -dp -e _start -dynamic-linker /usr/libexec/ld.elf_so -o g**
                     68:     **reetings /usr/lib/crt0.o /usr/lib/crti.o /usr/lib/crtbegin.o /var/tmp//ccMiXutV.**
                     69:     **o -lgcc -lgcc_eh -lc -lgcc -lgcc_eh /usr/lib/crtend.o /usr/lib/crtn.o**
                     72: The first command, _/usr/libexec/cc1_, is internal to gcc and is not for our direct use. The other two commands, _as_ and _ld_, are external to gcc. We would use _as_ and _ld_ without gcc, if we would want so. 
                     74: The first command, _/usr/libexec/cc1_, is the C compiler proper; it compiles C code and outputs assembly code, in a file with the _.s_ suffix. In the above example, it created the assembly version of our main function. The second command, _as_, assembles the _.s_ file to machine code, in a relocatable object file with the _.o_ suffix. It created the machine code version of our main function. The third command, _ld_, links object files into an executable file. It combined our main function with the C runtime and the C library to create our program of _greetings_. 
                     76: The _.s_ assembly file and the _.o_ object file were temporary files, so the gcc driver program deleted them. We only keep the final executable of _greetings_. 
                     78: #   The program in PowerPC assembly language 
1.3     ! kim        80: The manual page for [[!template id=man name="gcc" section="1"]] explains that we can use the _-S_ option to stop gcc with the assembly code. For PowerPC targets, gcc outputs register numbers by default; the _-mregnames_ option tells gcc to output register names instead. If you are learning assembly language, then _cc -mregnames -S_ is a good way to produce examples of assembly code. 
1.2       schmonz    81: 
                     83: The command _cc -mregnames -S greetings.c_ produces the output file _greetings.s_ which contains the assembly version of our main function. (If you want _greeting.s_ to contain PowerPC assembly code, then you need to use compiler that targets PowerPC.) The assembly syntax allows for comments, assembler directives, instructions and labels. 
                     85:   * Comments begin with a '#' sign, though gcc never puts any comments in its generated code. PowerPC uses '#', unlike many other architectures that use ';' instead. 
                     86:   * Assembler directives have names that begin with a dot (like _.section_ or _.string_) and may take arguments. 
                     87:   * Instructions have mnemonics without a dot (like _li_ or _stw_) and may take operands. 
                     88:   * Labels end with a colon (like _.LC0:_ or _main:_) and save the current address into a symbol. 
                     90: The PowerPC processor executes instructions. Most PowerPC instructions operate on the registers inside the processor. There are other instructions that load registers from memory or store registers to memory. Each of the general purpose registers (named r0 through r31) and the link register (named lr) hold a 32-bit integer. 
                     92: Assembly code may contain the register numbers (0 through 31) or the register names. Register numbers become confusing, when a 3 in the code might refer to the general purpose register r3, the floating point register f3, or the immediate value 3. The _cc -mregnames_ flag uses the assembly syntax for register names, which is to put a '%' sign before each name, as in _%r3_ or _%f3_. This is necessary to distinguish register _%r3_ from a symbol named _r3_. 
                     94: ##   Commented copy of greetings.s 
                     96: Here is a copy of _greeting.s_ (from the gcc of NetBSD 4.0.1/macppc) with added comments. Each instruction has a comment in pseudo-C to show the effect, if you know C language. Pretend that the registers are (char *) for indexing, but int or (int *) for assignment. 
                     99:     # This is a commented version of greeting.s, the 32-bit PowerPC
                    100:     # assembly code output from cc -mregnames -S greetings.c
                    102:        # .file takes the name of the original source file,
                    103:        # because this was a generated file. I guess that this
                    104:        # allows error messages or debuggers to blame the
                    105:        # original source file.
                    106:        .file   "greetings.c"
                    108:     # Enter the .rodata section for read-only data. String constants
                    109:     # belong in this section.
                    110:        .section        .rodata
                    112:        # For PowerPC, .align takes an exponent of 2.
                    113:        # So .align 2 gives an alignment of 4 bytes, so that
                    114:        # the current address is a multiple of 4.
                    115:        .align 2
                    117:        # .string inserts a C string, and the assembler provides
                    118:        # the terminating \0 byte. The label sets the symbol
                    119:        # .LC0 to the address of the string.
                    120:     .LC0:
                    121:        .string "Greetings, Earth!"
                    123:     # Enter the .text section for program text, which is the
                    124:     # executable part.
                    125:        .section        ".text"
                    127:        # We need an alignment of 4 bytes for the following
                    128:        # PowerPC processor instructions.
                    129:        .align 2
                    131:        # We need to export main as a global symbol so that the
                    132:        # linker will see it. ELF wants to know that main is a
                    133:        # @function symbol, not an @object symbol.
                    134:        .globl main
                    135:        .type   main, @function
                    136:     main:
                    137:        # The code for the main function begins here.
                    138:        # Passed in general purpose registers:
                    139:        #       r1 = stack pointer, r3 = argc, r4 = argv
                    140:        # Passed in link register:
                    141:        #       lr = return address
                    142:        # The int return value goes in r3.
                    144:        # Allocate 32 bytes for our the stack frame. Use the
                    145:        # atomic instruction "store word with update" (stwu) so
                    146:        # that r1[0] always points to the previous stack frame.
                    147:        stwu %r1,-32(%r1)       # r1[-32] = r1; r1 -= 32
                    149:        # Save registers r31 and lr to the stack. We need to
                    150:        # save r31 because it is a nonvolatile register, and to
                    151:        # save lr before any function calls. Now r31 belongs in
                    152:        # the register save area at the top of our stack frame,
                    153:        # but lr belongs in the previous stack frame, in the
                    154:        # lr save word at (r1[0])[0] == r1[36].
                    155:        mflr %r0                # r0 = lr
                    156:        stw %r31,28(%r1)        # r1[28] = r31
                    157:        stw %r0,36(%r1)         # r1[36] = r0
                    159:        # Save argc, argv to the stack.
                    160:        mr %r31,%r1             # r31 = r1
                    161:        stw %r3,8(%r31)         # r31[8] = r3 /* argc */
                    162:        stw %r4,12(%r31)        # r31[12] = r4 /* argv */
                    164:        # Call puts(.LC0). First we need to load r3 = .LC0, but
                    165:        # each instruction can load only 16 bits.
                    166:        #       .LC0@ha = (.LC0 >> 16) & 0xff
                    167:        #       .LC0@l = .LC0 & 0xff
                    168:        # This method uses "load immediate shifted" (lis) to
                    169:        # load r9 = (.LC0@ha << 16), then "load address" (la) to
                    170:        # load r3 = &(r9[.LC0@l]), same as r3 = (r9 + .LC0@l).
                    171:        lis %r9,.LC0@ha
                    172:        la %r3,.LC0@l(%r9)      # r3 = .LC0
                    174:        # The "bl" instruction calls a function; it also sets
                    175:        # the link register (lr) to the address of the next
                    176:        # instruction after "bl" so that puts can return here.
                    177:        bl puts                 # puts(r3)
                    179:        # Load r3 = 0 so that main returns 0.
                    180:        li %r0,0                # r0 = 0
                    181:        mr %r3,%r0              # r3 = r0
                    183:        # Point r11 to the previous stack frame.
                    184:        lwz %r11,0(%r1)         # r11 = r1[0]
                    186:        # Restore lr from r11[4]. Restore r31 from r11[-4],
                    187:        # same as r1[28].
                    188:        lwz %r0,4(%r11)         # r0 = r11[4]
                    189:        mtlr %r0                # lr = r0
                    190:        lwz %r31,-4(%r11)       # r31 = r11[-4]
                    192:        # Free the stack frame, then return.
                    193:        mr %r1,%r11             # r1 = r11
                    194:        blr                     # return r3
                    195:        # End of main function.
                    197:        # ELF wants to know the size of the function. The dot
                    198:        # symbol is the current address, now the end of the
                    199:        # function, and the "main" symbol is the start, so we
                    200:        # set the size to dot minus main.
                    201:        .size   main, .-main
                    203:        # This is the tag of the gcc from NetBSD 4.0.1; the
                    204:        # assembler will put this string in the object file.
                    205:        .ident  "GCC: (GNU) 4.1.2 20061021 prerelease (NetBSD nb3 20061125)"
1.3     ! kim       208: The above code is not a complete, standalone assembly program! It only contains a main function, for linking with the C runtime and the C library. It obeys the ELF and PowerPC conventions for the use of registers. (These conventions require the code to save r31 but not r9.) The _bl puts_ instruction is our evidence that the program calls [[!template id=man name="puts" section="3"]] instead of [[!template id=man name="printf" section="3"]]. 
1.2       schmonz   209: 
                    211: The compiler did not optimize the above code. Some optimizations might be obvious! Consider the code that saves argc and argv to the stack. We would can use r1 instead of copying r1 to r11. Going further, we would can delete the code and never save argc and argv, because this main function never uses argc and argv! 
                    213: ##   Optimizing the main function 
                    215: Expect a compiler like gcc to write better assembly code than a human programmer who knows assembly language. The best way to optimize the assembly code is to enable some gcc optimization flags. 
                    217: Released software often uses the -O2 flag, so here is a commented copy of greetings.s (from the gcc of NetBSD 4.0.1/macppc) with -O2 in use. 
                    220:     # This is a commented version of the optimized assembly output
                    221:     # from cc -O2 -mregnames -S greetings.c
                    223:        .file   "greetings.c"
                    225:     # Our string constant is now in a section that would allow an
                    226:     # ELF linker to remove duplicate strings. See the "info as"
                    227:     # documentation for the .section directive.
                    228:        .section        .rodata.str1.4,"aMS",@progbits,1
                    229:        .align 2
                    230:     .LC0:
                    231:        .string "Greetings, Earth!"
                    233:     # Enter the .text section and declare main, as before.
                    234:        .section        ".text"
                    235:        .align 2
                    236:        .globl main
                    237:        .type   main, @function
                    238:     main:
                    239:        # We use registers as before:
                    240:        #       r1 = stack pointer, r3 = argc, r4 = argv,
                    241:        #       lr = return address, r3 = int return value
                    243:        # Set r0 = lr so that we can save lr later.
                    244:        mflr %r0                # r0 = lr
                    246:        # Allocate only 16 bytes for our stack frame, and
                    247:        # point r1[0] to the previous stack frame.
                    248:        stwu %r1,-16(%r1)       # r1[-16] = r1; r1 -= 16
                    250:        # Save lr in the lr save word at (r1[0])[0] == r1[20],
                    251:        # before calling puts(.LC0).
                    252:        lis %r3,.LC0@ha
                    253:        la %r3,.LC0@l(%r3)      # r3 = .LC0
                    254:        stw %r0,20(%r1)         # r1[20] = r0
                    255:        bl puts                 # puts(r3)
                    257:        # Restore lr, free stack frame, and return 0.
                    258:        lwz %r0,20(%r1)         # r0 = r1[20]
                    259:        li %r3,0                # r3 = 0
                    260:        addi %r1,%r1,16         # r1 = r1 + 16
                    261:        mtlr %r0                # lr = r0
                    262:        blr                     # return r3
                    264:        # This main function is smaller than before but ELF
                    265:        # wants to know the size.
                    266:        .size   main, .-main
                    267:        .ident  "GCC: (GNU) 4.1.2 20061021 prerelease (NetBSD nb3 20061125)"
                    270: The optimized version of the main function does not use the r9, r11 or r31 registers; and it does not save r31, argc or argv to the stack. The stack frame occupies only 16 bytes, not 32 bytes. 
                    272: The main function barely uses the stack frame, only writing the frame pointer to 0(r1) and never reading anything. The main function must reserve 4 bytes of space at 4(r1) for an lr save word, in case the puts function saves its link register. The frame pointer and lr save word together occupy 8 bytes of stack space. The main function allocates 16 bytes, instead of only 8 bytes, because of a convention that the stack pointer is a multiple of 16. 
                    274: #   The relocatable object file 
                    276: Now that we have the assembly code, there are two more steps before we have the final executable. 
                    278:   1. The first step is to run the assembler (as), which translates the assembly code to machine code, and stores the machine code in an ELF relocatable object. 
                    279:   2. The second step is to run the linker (ld), which combines some ELF relocatables into one ELF executable. 
1.3     ! kim       281: There are various tools that can examine ELF files. The command [[!template id=man name="nm" section="1"]] lists the global symbols in an object file. The commands [[!template id=man name="objdump" section="1"]] and [[!template id=man name="readelf" section="1"]] show other information. These commands can examine both relocatables and executables. Though the executable is more interesting, the relocatable is simpler. 
1.2       schmonz   282: 
                    283: To continue our example, we can run the assembler with _greetings.s_ to produce _greetings.o_. We use the optimized code in _greetings.s_ from _cc -O2 -mregnames -S greetings.c_, because it was shorter. We feed our file _greeting.s_ to /usr/bin/as with a simple command. 
                    285:     $ as -o greetings.o greetings.s
1.3     ! kim       288: The output _greetings.o_ is a relocatable object file, and [[!template id=man name="file" section="1"]] confirms this. 
1.2       schmonz   289:     
                    290: $ file greetings.o
                    291:     greetings.o: ELF 32-bit MSB relocatable, PowerPC or cisco 4500, version 1 (SYSV)
                    292:     , not stripped
                    295: ##   List of sections 
                    297: The source _greetings.s_ had assembler directives for two sections (_.rodata.str1.4_ and _.text_), so the ELF relocatable _greetings.o_ should contain those two sections. The command _objdump_ can list the sections. 
                    299:     $ objdump
                    300:     Usage: objdump <option(s)> <file(s)>
                    301:      Display information from object <file(s)>.
                    302:      At least one of the following switches must be given:
                    303:      ...
                    304:      -h, --[section-]headers  Display the contents of the section headers
                    305:      ...
                    306:     $ objdump -h greetings.o
                    308:     greetings.o:     file format elf32-powerpc
                    310:     Sections:
                    311:     Idx Name          Size      VMA       LMA       File off  Algn
                    312:       0 .text         0000002c  00000000  00000000  00000034  2**2
                    313:                       CONTENTS, ALLOC, LOAD, RELOC, READONLY, CODE
                    314:       1 .data         00000000  00000000  00000000  00000060  2**0
                    315:                       CONTENTS, ALLOC, LOAD, DATA
                    316:       2 .bss          00000000  00000000  00000000  00000060  2**0
                    317:                       ALLOC
                    318:       3 .rodata.str1.4 00000014  00000000  00000000  00000060  2**2
                    319:                       CONTENTS, ALLOC, LOAD, READONLY, DATA
                    320:       4 .comment      0000003c  00000000  00000000  00000074  2**0
                    321:                       CONTENTS, READONLY
                    324: This command verifies the presence of the _.text_ and _.rodata.str1.4_ sections. The _.text_ section begins at file offset 0x34 and has size 0x2c, in bytes. The _.rodata.str1.4_ section begins at file offset 0x60 and has size 0x14. 
1.3     ! kim       326: Because the source _greetings.s_ does not have assembler directives for the _.data_ or _.bss_ or _.comment_ section, there must be another explanation for those three sections. The _.data_ and _.bss_ section has size 0x0. Perhaps for traditional reasons, the assembler puts these sections into every object file. Because the source _greeting.s_ never mentioned the _.data_ or _.bss_ section, nor allocated space in them, so the assembler output them as empty sections. (The [[!template id=man name="a.out" section="5"]] format always had text, data and bss segments. The [[!template id=man name="elf" section="5"]] format distinguishes segments and sections, and also allows for arbitrary sections like _.rodata.str1.4_ and _.comment_.) 
1.2       schmonz   327: 
                    329: That leaves the mystery of the _.comment_ section. The _objdump_ command accepts _-j_ to select a section and _-s_ to show the contents, so _objdump -j .comment -s greetings.o_ dumps the 0x3c bytes in that section. 
                    331:     $ objdump -j .comment -s greetings.o
                    333:     greetings.o:     file format elf32-powerpc
                    335:     Contents of section .comment:
                    336:      0000 00474343 3a202847 4e552920 342e312e  .GCC: (GNU) 4.1.
                    337:      0010 32203230 30363130 32312070 72657265  2 20061021 prere
                    338:      0020 6c656173 6520284e 65744253 44206e62  lease (NetBSD nb
                    339:      0030 33203230 30363131 32352900           3 20061125).    
                    342: This is just the string fromm the _.ident_ assembler directive, between a pair of \0 bytes. So whenever gcc generates an _.ident_ directive, the assembler leaves this _.comment_ section to identify the compiler that produced this relocatable. (The "info as" documentation for the _.ident_ directive, shipped with NetBSD 4.0.1, continues to claim that the assembler "does not actually emit anything for it", but in fact the assembler emits this _.comment_ section.) 
                    344: The _objdump_ tool also has a disassembler through its _-d_ option. Disassembly is the reverse process of assembly; it translates machine code to assembly code. We would can disassemble _greetings.o_ but the output would have a few defects, because of symbols that lack their final values. 
                    346: ##   Of symbols and addresses 
                    348: Our assembly code in _greetings.s_ had three symbols. The first symbol had the name _.LC0_ and pointed to our string. 
                    351:     .LC0:
                    352:        .string "Greetings, Earth!"
                    355: The second symbol had the name _main_. It was a global symbol that pointed to a function. 
                    358:        .globl main
                    359:        .type   main, @function
                    360:     main:
                    361:        mflr %r0
                    362:        ...
                    365: The third symbol had the name _puts_. Our code used _puts_ in a function call, though it never defined the symbol. 
                    368:        bl puts
                    371: A symbol has a name and an integer value. In assembly code, a symbol acts as a constant inline integer. The very most common use of a symbol is to hold an address, pointing to either a function or a datum. When a symbol appears as an operand to an instruction, the assembler would inline the value of that symbol into the machine code. The problem is that the assembler often does not know the final value of the symbol. So the assembler _as_ saves some information about symbols into the ELF file. The linker _ld_ can use this information to relocate symbols to their final values, resolve undefined symbols and inline the final values into the machine code. The fact that _ld_ relocates symbols is also the reason that _.o_ files are relocatable objects. 
                    373: The _nm_ command shows the names of symbols in an object file. The output of nm shows that _greetings.o_ contains only two symbols. The _.LC0_ symbol is missing. 
                    375:     $ nm greetings.o
                    376:     00000000 T main
                    377:              U puts
                    380: The _nm_ tool comes from Unix tradition, and remains a great way to check the list of symbols. For each symbol, _nm_ displays the hexadecimal value, a single letter for the type, then the name. The letter 'T' marks symbols that point into a text section, either the _.text_ section or some other arbitrary section of executable code. The letter 'U' marks undefined symbols, which do not have a value. 
                    382: The _nm_ tool claims that symbol _main_ has address 0x00000000, which to be a useless value. The actual meaning is that _main_ points to offset 0x0 within section _.text_. A more detailed view of the symbol table would provide evidence of this. 
                    384: ##   Fate of symbols 
                    386: The machine code in _greetings.o_ is incomplete. If the address of the string "Greetings, Earth!" is not zero, then something must fix the instructions at 0x8 and 0xc. To avoid an infinite loop, something must fix the instruction at 0x14 to find the function _puts_. The linker will have the task to edit and finish the machine code. 
                    388: _(Because this part of the wiki page now comes before the part about machine code, this disassembly should probably not be here.)_
                    390:     00000000 <main>:
                    391:        0:      (31|00000|01000|02a6)   mflr    r0
                    392:        4:      (37|00001|00001|fff0)   stwu    r1,-16(r1)
                    393:        8:      (15|00011|00000|0000)   lis     r3,0
                    394:        c:      (14|00011|00011|0000)   addi    r3,r3,0
                    395:       10:      (36|00000|00001|0014)   stw     r0,20(r1)
                    396:       14:      (18|00000|00000|0001)   bl      14 <main+0x14>
                    397:       18:      (32|00000|00001|0014)   lwz     r0,20(r1)
                    398:       1c:      (14|00011|00000|0000)   li      r3,0
                    399:       20:      (14|00001|00001|0010)   addi    r1,r1,16
                    400:       24:      (31|00000|01000|03a6)   mtlr    r0
                    401:       28:      (19|10100|00000|0020)   blr
                    404: The above disassembly does not tell that the code at 0x8, 0xc and 0x14 is incomplete (though the infinite loop at 0x14 is a hint). There must be another way to find where the above code uses a symbol that lacks a final value. The ELF relocatable _greetings.o_ bears information about both relocating symbols and resolving undefined symbols; some uses of _objdump_ or _readelf_ can reveal this information. 
                    406: ELF, like any object format, allows for a symbol table. The list of symbols from _nm greetings.o_ is only an incomplete view of this table. 
                    408:     $ nm greetings.o
                    409:     00000000 T main
                    410:              U puts
                    413: The command _objdump -t_ shows the symbol table in more detail. 
                    415:     $ objdump -t greetings.o
                    417:     greetings.o:     file format elf32-powerpc
                    419:     SYMBOL TABLE:
                    420:     00000000 l    df *ABS*     00000000 greetings.c
                    421:     00000000 l    d  .text     00000000 .text
                    422:     00000000 l    d  .data     00000000 .data
                    423:     00000000 l    d  .bss      00000000 .bss
                    424:     00000000 l    d  .rodata.str1.4    00000000 .rodata.str1.4
                    425:     00000000 l    d  .comment  00000000 .comment
                    426:     00000000 g     F .text     0000002c main
                    427:     00000000         *UND*     00000000 puts
                    430: The first column is the value of the symbol in hexadecimal. By some coincidence, every symbol in _greetings.o_ has the value zero. The second column gives letter 'l' for a local symbol or letter 'g' for a global symbol. The third column gives the type of symbol, with 'd' for a debugging symbol, lowercase 'f' for a filename or uppercase 'F' for a function symbol. The fourth column gives the section of the symbol, or '*ABS*' for an absolute symbol, or '*UND*' for an undefined symbol. The fifth column gives the size of the symbol in hexadecimal. The sixth column gives the name of the symbol. 
                    432: The filename symbol _greetings.c_ exists because the assembly code _greetings.s_ had a directive _.file greetings.c_. The symbol _main_ has a nonzero size because of the _.size_ directive. 
                    434: Each section of this ELF relocatable has a symbol that points to address 0x0 in the section. Then every section of this relocatable must contain address 0x0. A view of the section headers in _greetings.o_ confirms that every section begins at address 0x0. 
                    436:     $ objdump -h greetings.o
                    438:     greetings.o:     file format elf32-powerpc
                    440:     Sections:
                    441:     Idx Name          Size      VMA       LMA       File off  Algn
                    442:       0 .text         0000002c  00000000  00000000  00000034  2**2
                    443:                       CONTENTS, ALLOC, LOAD, RELOC, READONLY, CODE
                    444:       1 .data         00000000  00000000  00000000  00000060  2**0
                    445:                       CONTENTS, ALLOC, LOAD, DATA
                    446:       2 .bss          00000000  00000000  00000000  00000060  2**0
                    447:                       ALLOC
                    448:       3 .rodata.str1.4 00000014  00000000  00000000  00000060  2**2
                    449:                       CONTENTS, ALLOC, LOAD, READONLY, DATA
                    450:       4 .comment      0000003c  00000000  00000000  00000074  2**0
                    451:                       CONTENTS, READONLY
                    454: The output of _objdump -h_ shows the address of each section in the VMA and LMA columns. (ELF files always use the same address for both VMA and LMA.) All five sections in _greetings.o_ begin at address 0x0. Thus, all four sections marked ALLOC would overlap in memory. The linker will must relocate these four sections so that they do not overlap. 
                    456: The value of each symbol is the address. The section of each symbol serves to disambiguate addresses where sections overlap. Thus symbol _main_ points to address 0x0 in the section _.text_, not any other section. Because every section begins at address 0x0, each address is relative to the beginning of the section. Therefore, symbol _main_ points to offset 0x0 into the section _.text_. 
                    458: TODO: explain "relocation records" 
                    461:     $ objdump -r greetings.o
                    463:     greetings.o:     file format elf32-powerpc
                    465:     RELOCATION RECORDS FOR [.text]:
                    466:     OFFSET   TYPE              VALUE 
                    467:     0000000a R_PPC_ADDR16_HA   .rodata.str1.4
                    468:     0000000e R_PPC_ADDR16_LO   .rodata.str1.4
                    469:     00000014 R_PPC_REL24       puts
                    472: #   Disassembly and machine code 
                    474: ##   Disassembly 
                    476: GNU binutils provide both assembly and the reverse process, disassembly. While _as_ does assembly, _objdump -d_ does disassembly. Both programs use the same library of opcodes. 
                    478: By default, _objdump -d_ disassembles all executable sections. (The _-j_ option can select a section to disassemble. Our example relocatable _greetings.o_ has only executable section, so _-j .text_ becomes optional.) The disassembler works better with linked executable files. It can also disassemble relocatables like _greetings._. The output will confuse the reader because of undefined symbols, and symbols not relocated to their final values. 
                    480:     $ objdump -d greetings.o
                    482:     greetings.o:     file format elf32-powerpc
                    484:     Disassembly of section .text:
                    486:     00000000 <main>:
                    487:        0:      7c 08 02 a6     mflr    r0
                    488:        4:      94 21 ff f0     stwu    r1,-16(r1)
                    489:        8:      3c 60 00 00     lis     r3,0
                    490:        c:      38 63 00 00     addi    r3,r3,0
                    491:       10:      90 01 00 14     stw     r0,20(r1)
                    492:       14:      48 00 00 01     bl      14 <main+0x14>
                    493:       18:      80 01 00 14     lwz     r0,20(r1)
                    494:       1c:      38 60 00 00     li      r3,0
                    495:       20:      38 21 00 10     addi    r1,r1,16
                    496:       24:      7c 08 03 a6     mtlr    r0
                    497:       28:      4e 80 00 20     blr
                    500: The disassembled code has a slightly different syntax. Every instruction has a label, and each label is the hexadecimal address. The hex after each label is the machine code for that instruction. The syntax is more ambiguous, so register names do not begin with a '%' sign, "r3" can be a register instead of a symbol, and "14" can be a label instead of an immediate value. 
                    502: The size of every PowerPC instruction is four bytes. PowerPC architecture requires this fixed width of four bytes or 32 bits for every instruction. It also requires an alignment of four bytes for every instruction, meaning that the address of every instruction is a multiple of four. The above code meets both requirements. 
                    504: The disassembled code would must resemble the assembly code in _greetings.s_. A comparison shows that every instruction is the same, except for three instructions. 
                    506:   * Address 0x8 has _lis r3,0_ instead of _lis %r3,.LC0@ha_. 
                    507:   * Address 0xc has _addi r3,r3,0_ instead of _la %r3,.LC0@l(%r3)_. 
                    508:   * Address 0x14 has _bl 14 <main+0x14>_ instead of _bl puts_. 
                    510: The fate of the symbols _.LC0_ and _puts_ would explain these differences. The linker will inline the correct values of _.LC0_ and _puts_, so that these three instructions have sense. Because we have the source file _greeting.s_, we know about the _.LC0_ and _puts_ symbols. 
                    512: If the reader of _objdump -d greetings.o_ would not know about these symbols, then the three instructions at 0x8, 0xc and 0x14 would seem strange, useless and wrong. 
                    514:   * The "load immediate shifted" (lis) instruction shifts the immediate value leftward by 16 bits, then loads the register with the shifted value. So _lis r3,0_ shifts zero leftward by 16 bits, but the shifted value remains zero. The unnecessary shift seems strange, but it is not a problem. 
                    515:   * The "add immediate" (addi) instruction does addition, so _addi r3,r3,0_ increments r3 by zero, which effectively does nothing! The instruction seems unnecessary and useless. 
                    516:   * The instruction at address 0x14 is _bl 14 <main+0x14>_, which branches to label 14, effectively forming an infinite loop because it branches to itself! Something is wrong. 
                    518: If the reader understands that the infinite loop is actually a branch to function _puts_, then the function call still seems wrong, because _puts_ uses the argument in r3, and the code loads r3 with zero. Therefore the function call might be _puts(NULL)_ or _puts(&main)_. Zero is the null pointer, and also the address of the main function, but function _puts_ wants the address of some string. Before the linker relocates some things away from zero, now zero has two or three redundant meanings. The reader cannot follow the code. 
                    520: In the build of a large C program, there are many _.c_ and _.o_ files but no _.s_ files. (NetBSD and pkgsrc both provide many examples of this.) If someone did _objdump -d_ to read a _.o_ file, then the reader be unable to follow and understand the disassembly, because of undefined symbols, and symbols not relocated to their final values, and overlapping addresses with redundant meanings. 
                    522: A better understanding of how symbols fit into machine code would help. 
                    524: ##   Machine code in parts 
                    526: The output of _objdump -d_ has the machine code in hexadecimal. This allows the reader to identify individual bytes. This is good with architectures that organize opcodes and operands into bytes. 
                    528: PowerPC packs the opcodes and operands more tightly into bits. Each instruction has 32 bits. The first 6 bits (at the big end) have the opcode. In a typical instruction, the next 5 bits pick the first register, the next 5 bits pick the second register, and the remaining 16 bits hold an immediate value. A filter program that takes the hexadecimal machine code from _objdump -d_ and splits each instruction into these four parts would be helpful. 
                    530: One can write the filter program using a scripting language that provides both regular expressions and bit-shifting operations. Perl (available in [lang/perl5]( is such a language. Here follows _machine.pl_, such a script. 
                    533:     #!/usr/bin/env perl
                    535:     # usage: objdump -d ... | perl
                    536:     #
                    537:     # The output of objdump -d shows the machine code in hexadecimal. This
                    538:     # script converts the machine code to a format that shows the parts of a
                    539:     # typical PowerPC instruction such as "addi".
                    540:     #
                    541:     # The format is (opcode|register-1|register-2|immediate-value),
                    542:     # with digits in (decimal|binary|binary|hexadecimal).
                    544:     use strict;
                    545:     use warnings;
                    547:     my $byte = "[0-9a-f][0-9a-f]";
                    548:     my $word = "$byte $byte $byte $byte";
                    550:     while (defined(my $line = <ARGV>)) {
                    551:        chomp $line;
                    552:        if ($line =~ m/^([^:]*:\s*)($word)(.*)$/) {
                    553:                my ($before, $code, $after) = ($1, $2, $3);
                    554:                $code =~ s/ //g;
                    555:                $code = hex($code);
                    557:                my $opcode = $code >> (32-6);           # first 6 bits
                    558:                my $reg1 = ($code >> (32-11)) & 0x1f;   # next 5 bits
                    559:                my $reg2 = ($code >> (32-16)) & 0x1f;   # next 5 bits
                    560:                my $imm = $code & 0xffff;               # last 16 bits
                    562:                $line = sprintf("%s(%2d|%05b|%05b|%04x)%s",
                    563:                                $before, $opcode, $reg1, $reg2, $imm,
                    564:                                $after);
                    565:        }
                    566:        print "$line\n";
                    567:     }
                    570: Here follows the disassembly of _greetings.o_, with the machine code in parts. 
                    572:     $ objdump -d greetings.o | perl
                    574:     greetings.o:     file format elf32-powerpc
                    576:     Disassembly of section .text:
                    578:     00000000 <main>:
                    579:        0:      (31|00000|01000|02a6)   mflr    r0
                    580:        4:      (37|00001|00001|fff0)   stwu    r1,-16(r1)
                    581:        8:      (15|00011|00000|0000)   lis     r3,0
                    582:        c:      (14|00011|00011|0000)   addi    r3,r3,0
                    583:       10:      (36|00000|00001|0014)   stw     r0,20(r1)
                    584:       14:      (18|00000|00000|0001)   bl      14 <main+0x14>
                    585:       18:      (32|00000|00001|0014)   lwz     r0,20(r1)
                    586:       1c:      (14|00011|00000|0000)   li      r3,0
                    587:       20:      (14|00001|00001|0010)   addi    r1,r1,16
                    588:       24:      (31|00000|01000|03a6)   mtlr    r0
                    589:       28:      (19|10100|00000|0020)   blr
                    592: The disassembly now shows the machine code with the opcode in decimal, then the next 5 bits in binary, then another 5 bits in binary, then the remaining 16 bits in hexadecimal. 
                    594: The "load word and zero" (lwz) instruction given _lwz X,N(Y)_ would load register X with a value from memory. It indexes memory using register Y as a pointer and value N as an offset in bytes. Thus the memory location is N bytes after where register Y points. The mnemonic _lwz_ uses opcode 32. The next 5 bits hold the register number for X. Another 5 bits hold the register number for Y. The remaining 16 bits hold the offset value N. Given _lwz r0,20(r1)_ then r0 is 00000 in binary, r1 is 00001 in binary, 20 is 0x14 in hexadecimal, so the filter script would write _(32|00000|00001|0014)_. 
                    596: It becomes apparent that "store word" (stw) uses opcode 36, while "store word with update" (stwu) uses opcode 37. Given _stw r0,20(r1)_ then the filter script would write _(36|00000|00001|0014)_. Given _stwu r1,-16(r1)_ then -16 is 0xfff0 in hexadecimal 2s complement, so the filter script would write _(37|00001|00001|fff0)_. 
                    598: The "add immediate" (addi) instruction given _addi X,Y,Z_ would load register X with the sum of register Y and immediate value Z. The mnemonic _addi_ uses opcode 14. The next 5 bits hold the register number for X. Another 5 bits hold the register number for Y. The remaining 16 bits hold the immediate value Z. Given _addi r3,r3,0_ then r3 is 00011 in binary, so the filter script would write _(14|00011|00011|0000)_. Given _addi r1,r1,16_, then r1 is 00001 in binary, 16 is 0x10 in hexadecimal, so the filter script would write _(14|00001|00001|0010)_. 
                    600: The addi instruction has one more quirk. The second operand Y is either the immediate value 0, or a register number 1 through 31. (Some other instructions have this same quirk and cannot read register 0.) Thus _addi 4,0,5_ would actually do _r4 = 0 + 5_ instead of _r4 = r0 + 5_, as if register 0 would contain value 0 instead of the value in register 0. This quirk allows the "load immediate" (li) mnemonic, which also uses opcode 14, to load an immediate value by adding it to zero. So _li r3,0_ is the same as _addi 3,0,0_ which becomes _(14|00011|00000|0000)_. 
                    602: The "load address" (la) instruction given _la X,N(Y)_ would load register X with the address of N bytes after where register Y points. This is the same as to add register Y to immediate value N, so _la X,N(Y)_ and _addi X,Y,N_ are the same, and both use opcode 14. 
                    604: When machine code contains opcode 14, then the disassembler tries to be smart about choosing an instruction mnemonic. Here follows a quick example. 
                    606:     $ cat quick-example.s
                    607:        .section        .text
                    608:        addi    4,0,5           # bad
                    609:        la      3,3(0)          # very bad
                    610:        la      3,0(3)
                    611:        la      5,2500(3)
                    612:     $ as -o quick-example.o quick-example.s
                    613:     $ objdump -d quick-example.o | perl
                    615:     quick-example.o:     file format elf32-powerpc
                    617:     Disassembly of section .text:
                    619:     00000000 <.text>:
                    620:        0:      (14|00100|00000|0005)   li      r4,5
                    621:        4:      (14|00011|00000|0003)   li      r3,3
                    622:        8:      (14|00011|00011|0000)   addi    r3,r3,0
                    623:        c:      (14|00101|00011|09c4)   addi    r5,r3,2500
                    626: If the second register operand to opcode 14 is 00000, then the machine code looks like an instruction "li", so the disassembler uses the mnemonic "li". Otherwise the disassembler prefers mnemonic "addi" to "la". 
                    628: ##   Opcodes more strange 
                    630: The filter script shows the four parts of a typical instruction, but not all instructions have those four parts. The instructions that do branching or access special registers are not typical instructions. 
                    632: Here again is the disassembly of the main function in _greetings.o_: 
                    634:     00000000 <main>:
                    635:        0:      (31|00000|01000|02a6)   mflr    r0
                    636:        4:      (37|00001|00001|fff0)   stwu    r1,-16(r1)
                    637:        8:      (15|00011|00000|0000)   lis     r3,0
                    638:        c:      (14|00011|00011|0000)   addi    r3,r3,0
                    639:       10:      (36|00000|00001|0014)   stw     r0,20(r1)
                    640:       14:      (18|00000|00000|0001)   bl      14 <main+0x14>
                    641:       18:      (32|00000|00001|0014)   lwz     r0,20(r1)
                    642:       1c:      (14|00011|00000|0000)   li      r3,0
                    643:       20:      (14|00001|00001|0010)   addi    r1,r1,16
                    644:       24:      (31|00000|01000|03a6)   mtlr    r0
                    645:       28:      (19|10100|00000|0020)   blr
                    648: Assembly code uses "branch and link" (bl) to call functions and "branch to link register" (blr) to return from functions. 
                    650:   * The instruction _bl_ branches to the address of a function, and stores the return address in the link register. 
                    651:   * The instruction _blr_ branches to the address in the link register. 
                    652:   * The instructions "move from link register" (mflr) and "move to link register" (mtlr) access the link register, so that a function may save its return address while it uses _bl_ to call other functions. 
                    654: Every processor has a program counter (ctr) to hold the address of the current instruction. The branch instructions change the program counter. PowerPC uses a link register (lr) instead of a general purpose register (any of r0 through r31) or a memory location to hold the return address, seemingly to separate the branch processing unit (bpu) from the units that access general purpose registers or memory. 
                    656: The instruction _bl_ takes one operand, an immediate value for the address. There is no way to fit an opcode of 6 bits and an address of 32 bits into an instruction of only 32 bits. So _bl_ has only 26 bits for an operand. Thus _bl_ actually takes a 26-bit relative address and increments the program counter. This provides a range of about 32 MB in either direction. The assembler converts the operand to a relative address when it assembles the instruction _bl_. 
                    658: The instruction _bl puts_ would cause the assembler to convert the value of symbol _puts_ to a relative address; but _puts_ was an undefined symbol, so the assembler output a meaningless relative address of zero. An instruction _bl_ with relative address zero would branch to itself for an infinite loop. (The address for PowerPC is relative to the branch instruction. The address for some other architectures would be relative to the next instruction after the branch.) 
                    660: The address of every PowerPC instruction is a multiple of 4, thus the relative branch can also ignore the low 2 bits of the 26-bit relative address. Thus PowerPC uses those 2 bits to select the type of branch. Instruction _bl_ uses opcode 18 and sets the lower 2 bits to 0x1. Mnemonic _bl_ shares opcode 18 with three other mnemonics that set the lower 2 bits in other way. Given _bl puts_ the assembler began with opcode 18, ended with 0x1, and filled the intermediate 24 bits with zeros, so the filter script would write _(18|00000|00000|0001)_. A better filter script would write opcode 18 in decimal, the 26-bit relative address in hexadecimal, and the low 2 bits in binary. 
                    662: Opcode 19 is for many types of branches; the lower 26 bits somehow specify the type of branch. Mnemonic _blr_ shares opcode 19 with many other mnemonics. Opcode 31 is for operations with special purpose registers; the lower 26 bits somehow pick a special register and an action. Mnemonics _mflr_ and _mtlr_ share opcode 31 with many other mnemonics, including the more general "move from special purpose register" (mfspr) and "move to special purpose register" (mtspr). The instructions _blr', _mflr_ and _mtlr_ do not involve any symbols, so the lower 26 bits already have their final values._
                    664: The source file [/usr/src/gnu/dist/binutils/opcodes/ppc-opc.c]( contains a table of _powerpc_opcodes_ that lists the various mnemonics that use opcodes 18, 19 and 31. 

CVSweb for NetBSD wikisrc <> software: FreeBSD-CVSweb