probably a very beginner’s question, but I’m really interested in how to make it work.
I have following assembly code (heavily inspired from here, the rename() example):
[SECTION .text]
global _start
_start:
mov esi, msg ; saves pointer to string to ESI
xor eax, eax
mov byte [esi+6], al ; terminates first string with NULL char
mov byte [esi+13], al ; terminates second string with NULL char
mov byte al, 38 ; syscall number (38 = rename)
lea ebx, [esi] ; put the adress of /tmp/a in EBX
lea ecx, [esi+7] ; put the adress of /tmp/b in ECX
int 0x80 ; syscall execution
mov al, 0x01 ; prepare to exit!
xor ebx, ebx
int 0x80 ; exit!
[SECTION .data]
msg: db '/tmp/a#/tmp/b#'
Let me explain it: This program calls syscall rename to rename file /tmp/a to /tmp/b The string in section .data contains name of the source file and name of the target file.
Because I want to avoid NULLs, I decided to put # instead of NULLs and change it on runtime. However, the program terminates with SEGFAULT. It really seems that there is a problem with rewriting the # character(s) in .data segment. My question is – how should I deal with it and make it work? I know it’s a beginner question, maybe I’m missing something very important.
Thanks for any advice.
EDIT – commands used for assembling and linking
This is for NASM:
nasm -f elf -o ThisWorks.o ThisWorks.asm
And this for linker (notice that I’m building it as 32bit, although I have 64bit Phenom II).
ld -melf_i386 -o ThisWorks.aout ThisWorks.o
Than I execute it:
./ThisWorks.aout
And the result is:
Segmentation fault
Disassembly
This is disassembly by objdump -D ThisWorks.aout
ThisWorks.aout: file format elf32-i386
Disassembly of section .text:
08048080 <_start>:
8048080: be 9c 90 04 08 mov $0x804909c,%esi
8048085: 31 c0 xor %eax,%eax
8048087: 88 46 06 mov %al,0x6(%esi)
804808a: 88 46 0d mov %al,0xd(%esi)
804808d: b0 26 mov $0x26,%al
804808f: 8d 1e lea (%esi),%ebx
8048091: 8d 4e 07 lea 0x7(%esi),%ecx
8048094: cd 80 int $0x80
8048096: b0 01 mov $0x1,%al
8048098: 31 db xor %ebx,%ebx
804809a: cd 80 int $0x80
Disassembly of section .data:
0804909c <msg>:
804909c: 2f das
804909d: 74 6d je 804910c <_end+0x60>
804909f: 70 2f jo 80490d0 <_end+0x24>
80490a1: 61 popa
80490a2: 23 2f and (%edi),%ebp
80490a4: 74 6d je 8049113 <_end+0x67>
80490a6: 70 2f jo 80490d7 <_end+0x2b>
80490a8: 62 23 bound %esp,(%ebx)
SOLUTION
The debugging has shown, that program works normally, but falls into segfault when there is no file to rename. Otherwise my code works as expected. Sorry for that.
Running your probram under strace show:
Conclusions:
.datasection — the rename syscall is executed as you would expect.Your setup for
exitis incorrect.To fix it, change
mov al, 0x01tomov eax, 0x01.