CS 240 Lab 8: x86 Assembly

Peter Mawhorter

Outline

  • x86 Architecture
  • Questions (x86 assembly)
  • x86 Details
  • Disassembly
  • GO

x86 Architecture

x86 Architecture

x86 Architecture

There’s too much information here for us to understand all at once. But as in other parts of the class, we are honing our dealing-with-information-overload skills:

  • Pick out what’s important for your purposes
  • Cut a piece away using abstractions
  • Double-check foundational understanding

Write your questions on the boards.

  • x86 Assembly code

x86 Details

Register Names

  • %rax Accumulator (return value)
  • %rcx Count (arg 4)
  • %rdx Data (arg 3)
  • %rbx Base
  • %rsp Stack Pointer
  • %rbp Base Pointer
  • %rsi Source Index (arg 2)
  • %rdi Destination Index (arg 1)
  • %r8 - %r15 (args 5 + 6 in r8 and r9)

Registers for Arguments

Apparently this mnemonic is from Geoff Kuenning who I took classes from at HMC

Common Instructions

  • mov copies stuff
  • j* jumps (lots of varieties like je, jge, etc.)
  • cmp/test compares (to set up for conditional like je)
  • push and pop stores/reads stack
  • lea stores address in register (think of &)
    • “Load Effective Address,” a.k.a. “Lovely Efficient Arithmetic”
  • Keep this reference handy and use compiler explorer right-click docs (this link lets you enter assembly code directly)

Credit to Ben Wood for “Lovely Efficient Arithmetic”

Address Calculation

  • Syntax is offset ( base, index, stride ), e.g.: 8(%rdi, %rsi, 4)
    • base and index are registers
    • offset must be number
    • stride is a number (only 1, 2, 4, or 8)
  • The computed address is base + offset + (index × stride)
  • Iterating through a string:
    • base is the start of the string (original pointer)
    • index is the index variable
    • offset could be used, e.g., to skip 1st letter
    • stride would be 1, but could be 4 for ints instead of chars

Disassembly

  • Use objdump -d or disas command within gdb
  • Can also compile using -S flag for gcc to get a file
    • Using -O0 (the default) does no optimization; many things will be stored on the stack unnecessarily
    • Using -O3 does lots of optimization; gets stuff done without the stack where possible

Compiler Explorer

  • Compiler Explorer shows C and assembly side-by-side
  • Setup:
    • Select “C” language on the left side
    • Select “x86-64 gcc 4.8.5” from the right-side compiler menu
    • Add “–std=c99” to the compiler options on the right
      • Try “-Og” or “-O1” options for simpler assembly
    • Uncheck “Intel asm syntax” in the Output menu on the right
  • Right-click and use “View assembly documentation”

Exploring string_length_a

  • Compiler Explorer link
  • Can run objdump -d practice.bin
  • Could also run gdb practice.bin and then disas string_length_a

Lab Work

  • Let’s go on an adventure!
  • Pointers partners reminder