0

I'm learning the basics of AT&T assembler and I have a problem. When starting simple arithmetic operations I have the error: segmentation fault.

My work environment is Linux 32-bit. The problem is at startup, after compilation...

Where do I make a mistake?

.globl _start
        .section .text
        _start:

mov $4, %AX
mov $3, %BX
sub %AX, %BX
int $0x80
TomSQLdev
  • 11
  • 3
  • 1
    What do you think `int $0x80` is going to do? – David Wohlferd Jan 28 '18 at 21:56
  • avoid 8 and 16-bit operations as much as possible. Use eax ebx instead https://stackoverflow.com/a/41574531/995714 https://stackoverflow.com/q/163254/995714 – phuclv Jan 29 '18 at 03:33
  • @LưuVĩnhPhúc Actually it's not that bad if you consistently use 16 bit registers. Problems only occur if you frequently write to a 32 bit register and then update the corresponding 16 bit register. – fuz Jan 29 '18 at 11:11

1 Answers1

1

You are not doing simple arithmetic, at least you used system call explicitly.

If these lines are all your codes, then the problem causing the segfault is not in itself, it's the empty code after those lines.

See here the system call list for linux 32bit. When %eax is 4, the call is write. So written in C, you are calling

// write(unsigned int fd, const char * buf, size_t count);
write(0xffff, 0, 0);

since before int 0x80, your registers are %ebx=0xffff, %ecx=0, %edx=0. This call will return an error, but won't cause segfault, since 0xffff is not a valid file descriptor.

Then system call returns and your program resumes the execution. There is no planed code after this point, but CPU will still execute what is after this memory point, normally just many zeros, those garbage execution causes segfault.

If you want your assembly program terminate normally, you need to call another system call sys_exit explicitly. For better understanding your simple assembly program, use gdb to look at its effect step by step.

llllllllll
  • 15,080
  • 4
  • 23
  • 46
  • 1
    Note that it's a segfault, not a SIGILL. `00 00` decodes as `add [rax], al`, so the segfault is from the actions of the instructions decoded from the "garbage", not from code-fetch faulting or from it being garbage. – Peter Cordes Jan 29 '18 at 00:55