0

I'd like to specify that I'm just getting started on assembly, so I really have 0 experience. Also, mine is just a curiosity, not asking because the program doesn't work or anything. My program is just some simple loop, but the thing I don't understand is, when I run it, it returns a value. That value is fine on its own, it's correct, but the issue is that I haven't used any system call to print anything.

The code is as follows:

global _start

section .text

_start:
    mov ebx,1 
    mov ecx,4 

label:
    add ebx,ebx 
    dec ecx 
    cmp ecx,0 
    jg label 
    mov eax,1 
    int 0x80 

As you can see, I'm just adding on ebx and decrementing ecx and at the end call sys_exit and interruption. All this is fine, but the thing is, like I said, that when I run the executable, it prints the value from ebx. Is this how it should be? And if it is, why? From what I've learned so far, I'd need to perform a system call to print a value, but here is not like this.

CatalinC
  • 77
  • 10
  • https://syscalls.kernelgrok.com/ - ebx = error code for `sys_exit`. It should not print it, it should just set it as exit status. – Ped7g May 25 '18 at 20:19
  • 1
    `int 0x80` with EAX=1 is `sys_exit(ebx)`. This is a system call! ([What are the calling conventions for UNIX & Linux system calls on i386 and x86-64](https://stackoverflow.com/q/2535989)). So the exit status of your process is the low byte of EBX, but your program itself doesn't *print* that. The shell might print the return status, e.g. if you run `./a.out ; echo $?`. Or if you're using some other environment that prints exit statuses by default (like https://tio.run) – Peter Cordes May 25 '18 at 20:20
  • To print numbers from asm with system calls directly, use code like this: [How do I print an integer in Assembly Level Programming without printf from the c library?](https://stackoverflow.com/a/46301894) (or a 32-bit port of that code). – Peter Cordes May 25 '18 at 20:22
  • 2
    Indeed, I do use ./a.out ; echo $?. I think it makes sense. So technically the exit code is stored in ebx and by using echo $? it actually prints the exit code. Sorry if it was a silly question, but I was a bit confused. – CatalinC May 25 '18 at 20:35
  • 1
    The exit status is *passed to the kernel* in EBX, by `int 0x80`. EBX is the first arg, and `int 0x80` is like a `call` into the kernel. From there, the shell retrieves it with a [`wait` system call](http://man7.org/linux/man-pages/man2/waitpid.2.html), after your process has totally finished exiting and doesn't have its own registers or memory anymore. – Peter Cordes May 25 '18 at 20:43
  • I see, it makes sense. Well, thank you for your explanation. – CatalinC May 25 '18 at 21:02

0 Answers0