teaching machines

CS 330 Lecture 15 – Assembly Analogs

February 26, 2016 by . Filed under cs330, lectures, spring 2016.

Agenda

Note

Today we continue our foray into assemble, examining how the notions we take for granted in high-level languages are implemented at the assembly level. But first, let’s start with a little warmup Program This:

Our code below assumes that globals a and b are already assigned values. With a neigbor, tweak it to get input from the user using scanf.

.section .data
a:
  .long 23
b:
  .long 4
out_message:
  .asciz "%d + %d = %d\n"

.section .text
.globl main

main:
  movl a, %eax
  addl b, %eax

  # push params
  pushl %eax
  pushl b
  pushl a
  pushl $out_message
  call printf
  addl $16, %esp

  pushl $0
  call exit

Code

add_input.s

.section .data
a:
  .long 23
b:
  .long 4
out_message:
  .asciz "%d + %d = %d\n"
in_message:
  .asciz "%d%d"

.section .text
.globl main

main:
  pushl $b
  pushl $a
  pushl $in_message
  call scanf
  addl $12, %esp

  movl a, %eax
  addl b, %eax

  # push params
  pushl %eax
  pushl b
  pushl a
  pushl $out_message
  call printf
  addl $16, %esp

  pushl $0
  call exit

typelessness.s

.section .data
a:
  .byte 65
b:
  .byte 66
c:
  .byte 67
d:
  .byte 10
e:
  .byte 0

.section .text
.globl main

main:
  pushl $a
  call printf
  addl $4, %esp

  pushl $0
  call exit

struct.s

.section .data
p:
  .long 20
  .long 30
out_message:
  .asciz "a: %d b: %d\n"

.section .text
.globl main

main:
  movl $p, %eax

  pushl 4(%eax)
  pushl (%eax)
  pushl $out_message
  call printf
  addl $12, %esp

  pushl $0
  call exit

loop.s

.section .data
i:
  .long 100
out_message:
  .asciz "%d\n"

.section .text
.globl main

main:
  movl i, %eax

loop:
  cmpl $0, %eax
  jz done

  # temp push
  pushl %eax

  pushl %eax
  pushl $out_message
  call printf
  addl $8, %esp

  popl %eax

  decl %eax
  jmp loop

done:
  pushl $0
  call exit

heads_tails.s

.section .data
heads_message:
  .asciz "heads\n"
tails_message:
  .asciz "tails\n"

.section .text
.globl main

main:
  pushl $0
  call time
  addl $4, %esp

  pushl %eax
  call srand
  addl $4, %esp

  call rand

  # %eax holds the random number
  andl $1, %eax
  cmpl $0, %eax

  jz heads

tails:
  pushl $tails_message
  call printf
  addl $4, %esp
  jmp done

heads:
  pushl $heads_message
  call printf
  addl $4, %esp

done:
  pushl $0
  call exit