Search code examples
linuxassemblyx86gnu-assembler

Can't open file in Linux via 0x80


I'm trying to implement in GAS a simple test program which opens a file, writes to it some text and exits. However, the system call for 'open' keeps returning '-14' ("EFAULT - bad address" if I understand correctly). The program code is the following:

.intel_syntax noprefix
.section .data

textoutput:
    .asciz  "Hello world!"
pstr_end:
    .set lentext, pstr_end - textoutput
filetoopen:
    .asciz  "/tmp/tsttxt"

.section .text
.globl main

.func main
main:

mov eax, 5          #  open
mov ebx, filetoopen   # filname
mov ecx, 2            # flags: read and write
mov edx, 0700    # mode
int 0x80

mov ebx, eax      # <<< !!! eax here contains -14
mov eax, 4
mov ecx, textoutput
mov edx, lentext
int 0x80

mov eax, 1
mov ebx, 0
int 0x80

The problem seems to be with the filetoopen string (the manpage to open says that EFAULT means pathname points outside your accessible address space.) Is the filetoopen declared properly in the program's code? What can be the cause of this error?

Thanks.


Solution

  • In intel syntax you need to use mov ebx, offset filetoopen. If you look at the actual instruction as assembled you can see it's a memory load:

    80483e1:       8b 1d 2d 96 04 08       mov    ebx,DWORD PTR ds:0x804962d
    

    That is of course wrong, you need the address here. This applies to the other two occurrences of this pattern as well.