3

I am currently busy with assembly and ran into the following problem:

I'm trying to get a number that has been typed into the eax register. First i present a string which asks for input and then someone has to enter a number.

I've used the following code, but I don't understand every bit of it. Please note the comments in the code.

I know absolutely nothing happens now with the number, except that is has been moved into eax. What i do want to know is why i must use leal: why and what does it do? and why do i need to push eax back on the stack?

.text
string1: .asciz "Please enter a number\n"
input: .asciz "%d" 

.global main
main:
       # Editor's note: this code is broken / unsafe; missing push %ebp here
  movl %esp, %ebp
  
  push $string1          # prompt string
  call printf            #print the string
           # no add $4, %esp here: 4 bytes still allocated on the stack

  leal -4(%ebp), %eax   # ????
  pushl %eax            # the thing you pushed in eax is now pushed on the stack?
  pushl $input          #the number 
  
  call scanf      
  
  popl %eax
  popl %eax       # the number that has been entered is now in eax
  
  call end
  
end:
  push $0
  call exit
Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Gooey
  • 4,740
  • 10
  • 42
  • 76
  • Note that `push %esp` could replace that `lea` / `push %eax` because ESP is pointing at the 4 bytes reserved by the first `push $string1`. No need to use a frame pointer at all, so the broken `mov %esp, %ebp` could be removed. (Broken because you're not saving/restoring EBP, but in standard calling conventions it's call-preserved). – Peter Cordes Feb 19 '21 at 01:49
  • Also, this code isn't safe for modern systems that require 16-byte ESP alignment before calling functions. (e.g. i386 System V ABI on Linux, but not most other OSes.) – Peter Cordes Feb 19 '21 at 01:49

1 Answers1

2

You are calling functions, so you pass parameters to them on the stack. One integer is returned to you in eax, rest is via input-output pointer parameters, again, on the stack. Check out x86 calling conventions.

Edit 0:

The leal instruction stores effective address of some temporary variable (that's where scanf puts your integer value) into eax, then you pass it to scanf on the stack. Take a look here: What's the purpose of the LEA instruction?

Community
  • 1
  • 1
Nikolai Fetissov
  • 82,306
  • 11
  • 110
  • 171