CS 208 s21 — Learning Block #10

Table of Contents

1 Review

What effect do these instructions

:
    leaq (%rdx,%rcx,4), %rax
    movq (%rdx,%rcx,4), %rbx
    leaq (%rdx), %rdi
    movq (%rdx), %rsi

have on register values give the initial state below?1

topic-10-review-initial.png

2 Which condition codes indicate \(a > b\)?

  • not less than and not equal
  • ~(SF ^ OF) and ~ZF
  • ~(SF ^ OF) & ~ZF

3 Conditional Exercise

Translate this C code to assembly2

long wacky(long x, long y) {
    long result;
    if (x + y > 7) {
        result = x;
    } else {
        result = y + 2;
    }
    return result;
}

3.1 Jump Instruction Encodings

If we compile wacky and disassemble it, we can see how jump instructions are encoded into machine code3:

0000000000400497 <wacky>:
  400497:       48 8d 04 37             lea    (%rdi,%rsi,1),%rax
  40049b:       48 83 f8 07             cmp    $0x7,%rax
  40049f:       7f 05                   jg     4004a6 <wacky+0xf>
  4004a1:       48 8d 46 02             lea    0x2(%rsi),%rax
  4004a5:       c3                      retq
  4004a6:       48 89 f8                mov    %rdi,%rax
  4004a9:       c3                      retq
  • jump target encoded compactly with instruction pointer relative representation
    • specify offset to the address of the immediately following instruction
    • 7f is the encoding for the jg instruction
    • 05 is the jump target, meaning it will add 0x5 to %rip (the instruction pointer) if it jumps
    • when we execute the jg instruction, %rip is set to the address of the next instruction, 0x4004a1. Adding 0x5 to this will result in executing the mov instruction at 0x4004a6 instead.
    • objdump, the disassembler I used to produce the above example, computes this for us and displays 0x4004a6 as the jump target even though in the machine code the target is encoded as 0x5

4 Practice

CSPP practice problems 3.16 (p. 212) and 3.18 (p. 213)

Footnotes:

1

topic-10-review-answers.png

2
wacky:
        leaq    (%rdi,%rsi), %rax
        cmpq    $7, %rax
        jg      .L3
        leaq    2(%rsi), %rax
        ret
.L3:
        movq    %rdi, %rax
        ret
3

Perform this disassembly via an option on godbolt.org

godbolt-compile-to-binary.png

or, by putting the code for wacky and an empty main in wacky.c and running these commands:

gcc -Og -no-pie -o wacky wacky.c
objdump -d wacky

objdump will print out a bunch of boilerplate assembly that's part of any program, so you'll need to locate the definition of wacky within it.