1

I am learning assembly language from Programming from Ground Up book. I am running the following code but I am getting wrong output. I am running one of the example from the book which is on page 60. The goal is to output the sum of 2^3 + 5^2 but my output is 139.

I am running my code on Ubuntu 18 which is running on a virtual machine inside windows 10. I have i7 Processor.

as power.s -o power.o 
ld power.o -o power
./power
echo $?

After running ./power I am getting segmentation fault.

Here is my code:-

    .code32
    .section .data
    .section .text

    .globl _start
_start:
    pushl $3
    pushl $2
    call power

    addl $8, %esp
    pushl %eax

    pushl $2
    pushl $5
    call power
    addl $8, %esp

    popl %ebx
    addl %eax, %ebx

    movl $1, %eax
    int $0x80



################################
#power
################################
    .type power, @function
power:
    pushl %ebp
    movl %esp, %ebp
    subl $4, %esp

    movl 8(%ebp), %ebx
    movl 12(%ebp), %ecx

    movl %ebx, -4(%ebp)

power_loop_start:
    cmpl $1, %ecx
    je end_power

    movl -4(%ebp), %eax
    imull %ebx, %eax
    movl %eax, -4(%ebp)

    decl %ecx
    jmp power_loop_start

end_power:
    movl -4(%ebp), %eax
    movl %ebp, %esp
    popl %ebp
    ret

I have compared my code with the book at least 5 times so there isn't any typo mistakes.

Michael Petch
  • 46,082
  • 8
  • 107
  • 198
killerprince182
  • 455
  • 2
  • 12
  • 1
    You are likely using 64-bit Linux and trying to run a 32-bit program as 64-bit code. The segmentation fault would likely be stack related problem with ESP. You either have to convert all this code to 64-bit code or assemble and compile it to a 32-bit program with `as --32 power.s -o power.o` and `ld -melf_i386 power.o -o power` – Michael Petch Jun 02 '20 at 15:17
  • Thank you! That worked! – killerprince182 Jun 02 '20 at 15:27
  • Don't use `.code32` unless you're writing a kernel that needs to far-jump between 32 and 64-bit code. That let you assemble 32-bit machine code into a 64-bit `.o` so it crashes at runtime instead of having the assembler tell you that `pushl` isn't a valid x86-64 instruction. – Peter Cordes Jun 03 '20 at 01:18

0 Answers0