Kalzium
Kalzium

Reputation: 3

confusing with JMP instruction

I write an inline assembly program to unlink "grades.txt" in /home/httpd, here is the code:

void main()
{
   __asm__(
   "jmp L\n"\
   "sub1:\n"\
   "movl 0x4(%esp), %ebx\n"\
   "movb $0xa, %al\n"\
   "int $0x80\n"\
   "L:\n"\
   "call sub1\n"\
   ".string \"//home//httpd//grades.txt\" "
   );
}

I think the code shall do what I want, to unlink the grades.txt in "/home/httpd", yet when I execute it, there is a segment fault.

And I use gdb to tackle this fault, I found that it can't execute the line "jmp L", the program will stop when in line 5 ["__asm__("] until I enter "ctrl + c" to interrupt it.

If I add the assembly of "exit(0)" to let the program exit cleanly , and continue execute it, the program will just exit without doing anything.

so this is quite confusing, why the program doesn't execute the jmp instruction? Is there any errors?

I shall very much appreciate your help!

Upvotes: 0

Views: 498

Answers (1)

szx
szx

Reputation: 6926

Few things:

  • You should use %eax instead of %al because the 3 most significant bytes can be not 000000
  • The movl 0x4(%esp), %ebx line should be movl (%esp), %ebx because %ebp is not pushed onto the stack hence return address is at %esp+0
  • After doinig int 80h the code will fall through and call sub1 over and over again, so you need an extra jump:

    int80h
    add $4, %esp # pop the return address
    jmp exit     # jump over the call
    call sub1
    ....
    exit:
    
  • No need to use \ - the strings will be concatenated for you

  • void is not a valid return type for main() in C

Summing up the above tips:

int main()
{
   __asm__(
   "jmp L\n"
   "sub1:\n"
   "movl (%esp), %ebx\n"
   "movl $0xa, %eax\n"
   "int $0x80\n"
   "add $4, %esp\n"
   "jmp exit\n"
   "L:\n"
   "call sub1\n"
   ".string \"//home//httpd//grades.txt\"\n"
   "exit:\n"
   );
}

Upvotes: 1

Related Questions