Lecture 2: Assembly

Introduction

Aside: A little bit about numbers and number bases

What’s the job of a CPU?

x86_64

Where does assembly fit in today?

-- hello.c --> | Preprocessor | -- hello.i --> | Compiler | -- hello.s --> | Assembler | -- hello.o --> | Linker | -- hello -->

Aside

Programming in Assembly

Data

Where does it go?

Moving data

Arithmetic

Jumping and Labels

Conditional Branching

Calling Functions

SysV ABI x86_64 Calling Conventions

Arguments

Argument Register
1 %rdi
2 %rsi
3 %rdx
4 %rcx
5 %r8
6 %r9
Special Case: printf, fprintf, scanf, etc.

Return Value

Register Saving

Callee-save registers

%rbx, %rbp, and %r12%r15

Caller-save registers

all argument registers (see above), the return value register (%rax), %r10, %r11

These are best used as temporaries - they might “go bad” as soon as you call a function.

Structure of an Assembly File


.global main    # any symbols (e.g., functions) that should be visible 
                # outside this module, need to be declared global

.text           # begin the executable code segment

main:           # start of the main function
  enter $0, $0  # set up the call stack (more next time)

  # code
  # ...
  # code
  # ...
  # code

  leave         # clean up the stack space
  ret           # return from the function

# more functions ...

.data           # beginning of the data segment
                # - this is where global variables are defined

format_string:
  .asciz "Hello, my age is: %d\n"

some_long_integer:
  .quad 42