help-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Jump to code block.


From: Ted Williams
Subject: Jump to code block.
Date: Sun, 16 Jul 2006 08:50:18 -0700

The inline-assembly shown below jumps to a code block which executes and 
then returns to the
main code segment.  Unfortunately, a SIGSEGV is generated by the jmp 
instruction.
Any suggestions?

// jump.c - Employ inline assembly to perform a jump into code block.
// To compile:   gcc -gstabs -o jump jump.c
// To show assembler: gcc -S jump.c
// To generate obj:  gcc -c jump.c
// To disassemble:  objdump -d jump.o
// To debug:   gdb jump
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>

typedef unsigned long ulong;
int main()
{
 char *apIp;
 char *apBp = NULL, *apCp, *apEp;
 char **apLp;   // Ptr to place to place holding the return address
 int aSize = 100;  // code size in bytes
 int aRet;
 unsigned long aB = 2;

 // Allocate a block of memory to hold code. Align apIp to a page 
boundry
 apBp = malloc(aSize + 4096);
 aB = (unsigned long)apBp;
 aB += 4095;
 aB &= 0xFFFFF000;
 apIp = apCp = (char *)aB;
 apEp = apIp + aSize;

 // Fill code block with no-ops
 while (apCp < apEp)
    *apCp++ = 0x90;

 // End code block with a jump back to lDone
 apCp = apEp - 6;
 *apCp++ = 0xFF;  // jmp offset32
 *apCp++ = 0x25;
 apLp = (char **)apCp;
 *apLp = &&lDone;

 // Allow execute permission in data block.
 aRet = mprotect(apIp, aSize, PROT_EXEC | PROT_WRITE | PROT_READ);

 // Various jump instructions.
 ///asm ("jmp lDone");      // FF 25 ofs jmp lDone
 /// asm ("movl %0, %%eax\n\t"      // 8B 45 F8  mov -8(%epb), %eax
 /// "jmp *%%eax" : :"m" (apIp));   // FF E0     jmp *%eax
 /// asm (".intel_syntax\n\tjmp dword ptr [apX]"); // Does not work
 /// asm ("leal %0, %%eax\n\t"      // 8D 4f F8  lea -8(%ebp), %eax
 /// "jmp *(%%eax)" : : "m" (apIp));// FF 20     jmp *(%eax)
 asm ("jmp *%0" : : "m" (apIp));    // FF 65 F8  jmp *-8(%epb)
 // This statement is not reachable.
 free(apBp);
 exit (0);
 // Finish up here
lDone:
 printf("Return from code block\n");
 free(apBp);
 return 0; 






reply via email to

[Prev in Thread] Current Thread [Next in Thread]