1

I am currently learning the ASM, I have a question about the following code (which compiles)

This code come from this tutorial.

The question is: Why do I have the same behaviour when the fd is egual to 0, 1 or 2 (corresponding to stdin, stdout and stderr), at the indicated line, and when the fd is egual to 3 or more, it does nothing (it skips the scanf).

section .data                           ;Data segment
   userMsg db 'Please enter a number: ' ;Ask the user to enter a number
   lenUserMsg equ $-userMsg             ;The length of the message
   dispMsg db 'You have entered: '
   lenDispMsg equ $-dispMsg                 

section .bss           ;Uninitialized data
   num resb 5

section .text          ;Code Segment
   global _start

_start:                ;User prompt
   mov eax, 4
   mov ebx, 1
   mov ecx, userMsg
   mov edx, lenUserMsg
   int 80h

   ;Read and store the user input
   mov eax, 3
   mov ebx, 2 ; /!\ QUESTION IS ABOUT THIS LINE /!\
   mov ecx, num  
   mov edx, 5          ;5 bytes (numeric, 1 for sign) of that information
   int 80h

   ;Output the message 'The entered number is: '
   mov eax, 4
   mov ebx, 1
   mov ecx, dispMsg
   mov edx, lenDispMsg
   int 80h  

   ;Output the number entered
   mov eax, 4
   mov ebx, 1
   mov ecx, num
   mov edx, 5
   int 80h  

   ; Exit code
   mov eax, 1
   mov ebx, 0
   int 80h

We can compile and execute this code with the following command:

$> nasm -f elf64 test.S
$> ld test.o
$> ./a.out

Thank you,

void
  • 407
  • 6
  • 18
  • Forgot about my dupehammer.. Not sure if it's a perfect duplicate, but I think http://stackoverflow.com/questions/7383803/writing-to-stdin-and-reading-from-stdout-unix-linux-c-programming pretty much covers the same thing as this question. – Michael Mar 17 '17 at 12:57
  • My question is about read function in Assembly (ASM), I don't have any question about the bevahior of read in C language, thank you – void Mar 17 '17 at 12:58
  • 1
    When run at the command line, `0`, `1` and `2` all refer to the terminal, and anything higher will fail because you haven't opened any more files. – Crowman Mar 17 '17 at 13:12
  • I have several issues on my VM to make your code work: if I strace it, I only see `stat` calls. Also, that tutorial focuses on 32 bits architecture. I have tried using `syscall` and 64bits register, and I get a working example, where strace is happy. – Aif Mar 17 '17 at 13:15
  • 1
    @void: C or assembly is irrelevant in this case. – Michael Mar 17 '17 at 13:16

0 Answers0