Open a file from command line argument

2019-03-04 03:29发布

问题:

I'm trying to create an assembly program that creates a file that's specified on the command line (argv[1]). It works perfectly fine if the string is stored in already, but if I run it as is with the file_name not moved to rbx, it works perfectly fine.

section .text
   global _start

_start:

  ; Equivalent to mov rsp, [rsp+8]
  pop   rbx; argc
  pop   rbx; argv[0]
  pop   rbx; argv[1]

  mov   rax, 8
 ;mov   rbx, file_name  ; Commented out 
  mov   rcx, 0744
  syscall

  ; Exit
  mov   rax, 1
  mov   rbx, 0
  syscall

section .data
  file_name db'file.txt'

I've also tried this from here and I now realize that this is jumping to exit even though argc is 2, but nonetheless I tried it to no avail:

  pop   rcx
  cmp   rcx, 2
  jne   exit
  add   rsp, 8
  pop   rbx

  mov   rax, 8
  mov   rcx, 0744
  syscall

How can I fix this?

Edit 1:

Switched to 64bit syscalls. Here's my hello world practice:

section .text
   global _start

_start:
  mov   rax, 1
  mov   rdi, 1
  mov   rsi, string
  mov   rdx, strlen
  syscall

  ; Exit
  mov   rax, 60
  mov   rbx, 0
  syscall

  section .data
    string      db 'Hello, World!', 10
    strlen      equ $ - string

Now with file create:

section .text
   global _start

_start:
  mov   rax, 85
  mov   rdi, file_name
  mov   rsi, 0744
  syscall

  ; Exit
  mov   rax, 60
  mov   rbx, 0
  syscall

section .data
  file_name     db 'File.txt'

And finally with file arguments:

section .text
   global _start

_start:
  pop   rbx
  pop   rbx
  pop   rbx
  mov   rdi, rbx

  mov   rax, 85
  mov   rsi, 0744
  syscall

  ; Exit
  mov   rax, 60
  mov   rbx, 0
  syscall