2
votes

I'm trying to do a very simple exercise in assembly: sum N numbers located in contiguous memory cells. This is my actual code:

global _start 
section .data

        array: DD 300,10,20,30,40,50    ; Allocate the numbers
        arrayLen: EQU $-array           ; Get the quantity of numbers 

section .text
        _start:

        mov ecx, 0                       ; The counter
        mov ebx, 0                       ; The Accumulator

loop:   add ebx, DWORD [array+ecx]        ; get the i-th word  and add it to the accumulator
        add ecx, 4
        cmp ecx, arrayLen
        jne loop

        mov eax, 1
        int 0x80

The program is compiled and executed correctly but returns an incorrect value. The result should be 450, instead I obtain 194.

I noticed that 194 is the the same bitstream as 450, but the 9th bit is omitted. Debugging my program I argued that for some reason, that I can't understand, when I read

[array+ecx]

It reads only 8 bits although I specified the keyword DWORD.

Can someone help me? Thanks in advance

1
Where do you see the 8-bit read? ebx is increased by a 4-byte (dword) value, that's all right. Maybe you were looking at BL, not EBX?nullptr
When I execute the program on the terminal, it returns the value in ebx. To see this returned value, I type echo $?sirnino

1 Answers

4
votes

The program sums up the array correctly. The problem is with returning the result.

[Answer corrected, thanks to Jester.]

You pass the return value to sys_exit() (this is what mov eax, 1; int 0x80 does). sys_exit() leaves only the lower 8 bits of the return value (other bits are used for some flags).

That's where the 9th bit is lost.

Shell observes already truncated return value and prints it out.