0

I have trouble understanding why the command is used twice in sys_execve: It is directly in ebx, and a pointer to it is in ecx.


%include 'commonlib.asm'

section .data               
command db '/bin/echo', 0   
arg1 db 'Hello world!', 0
callargs dd command         ;used here
         dd arg1
         dd 0               
environment dd 0            

section .text
global _start

_start:
    mov edx, environment    
    mov ecx, callargs       
    mov ebx, command        ;used here
    mov eax, 11             
    int 80h                 

    call exit

exit simply does sys_exit.

I checked what it would do without each of them, but in both cases the program didn't work properly (it didn't print Hello world.).

Is there a reason to this? Why is it supposed to be used twice?

Random
  • 505
  • 2
  • 17
  • 2
    By convention, programs expect their name as the first argument. See [man execve](https://man7.org/linux/man-pages/man2/execve.2.html): _"By convention, the first of these strings (i.e., argv[0]) should contain the filename associated with the file being executed."_ – Jester Jul 30 '22 at 12:21
  • @Jester So that's also why trying to get command line arguments in assembly shows that the first argument is the name? And in the shell, is that done automatically? – Random Jul 30 '22 at 12:23
  • Yes, that is correct. – Jester Jul 30 '22 at 12:23
  • 2
    In addition to @Jester's comment - the kernel considers "the thing to execute" and "the args for that thing" to be unrelated, so the caller of execve is responsible for following the convention. – access violation Jul 30 '22 at 12:24
  • 1
    WINE even "mis-uses" the fact that both are unrelated: It starts itself (e.g. `/usr/bin/wine` or similar) with `argv[0]` set to the file name of the Windows executable. If you use `ps` to see all running processes, you won't see `/usr/bin/wine` but something like `f:\programs\notepad++.exe`. – Martin Rosenau Jul 30 '22 at 13:06
  • 1
    Not to mention the multi-call binary utilities, or even some shells behaving differently when called as `sh` and not by their full name :) – Jester Jul 30 '22 at 14:09
  • 1
    Appears to be a duplicate of [Why do we pass the command name twice to execve, as a path and in the argument list?](https://stackoverflow.com/q/59040362) . (I just retitled it from "Confusion about execve parameters" after finding it as one of many hits for `site:stackoverflow.com execve program name first arg`, so hopefully future readers will have an easier time than you did.) – Peter Cordes Jul 30 '22 at 17:07
  • 1
    BTW, some programs still work if you pass an empty argument list, a pointer to a NULL pointer. (Or in Linux, ECX=0 is treated as a valid empty list, rather than returning -EFAULT for a bad pointer to a NULL-terminated array.) This is common in shellcode, since `xor ecx,ecx` is smaller than `xor ecx,ecx` / `push ecx` / `mov ecx, esp` – Peter Cordes Jul 30 '22 at 17:10

0 Answers0