shithub: drawcpu

ref: f6d48501c4c475c5c9cad077ae6b206e72e0c65d
dir: /posix-amd64/trampoline.c/

View raw version
#include <u.h>
#include <libc.h>
#include "../kern/fns.h"
#include "mem.h"

/* TODO: This is not arm64 code, this is amd64 code */
extern void asm_syscall_hook(void);
void ____asm_syscall_hook(void)
{
	/*
	 * asm_syscall_hook is the address where the
	 * trampoline code first jumps to.
	 *
	 * the procedure below calls the C function
	 * namded syscall_hook.
	 *
	 * at the entry point of this,
	 * the register values follow the calling convention
	 * of the system calls. the following transforms
	 * to the calling convention of the C functions.
	 *
	 * we do this just for writing the hook in C.
	 * so, this part would not be performance optimal.
	 */
	asm volatile (
	".globl asm_syscall_hook \n\t"
	"asm_syscall_hook: \n\t"
	"movq (%rsp), %rcx \n\t"
	"pushq %rbp \n\t"
	"movq %rsp, %rbp \n\t"
	"subq $16,%rsp \n\t"
	"movq %rcx,8(%rsp) \n\t"
	"movq %r9,(%rsp) \n\t"
	"movq %r8, %r9 \n\t"
	"movq %r10, %r8 \n\t"
	"movq %rdx, %rcx \n\t"
	"movq %rsi, %rdx \n\t"
	"movq %rdi, %rsi \n\t"
	"movq %rax, %rdi \n\t"
	"call syscall \n\t"
	"leaveq \n\t"
	"retq \n\t"
	);
}

int
trampoline(void *text)
{
    int i;
    for(i = 0; i < _NSYS; i++)
        ((uint8_t *)text)[i] = 0x90;

    /* Preserve redzone */
    ((uint8_t*)text)[_NSYS + 0x00] = 0x48;
    ((uint8_t *) text)[_NSYS + 0x01] = 0x81;
	((uint8_t *) text)[_NSYS + 0x02] = 0xec;
	((uint8_t *) text)[_NSYS + 0x03] = 0x80;
	((uint8_t *) text)[_NSYS + 0x04] = 0x00;
	((uint8_t *) text)[_NSYS + 0x05] = 0x00;
	((uint8_t *) text)[_NSYS + 0x06] = 0x00;

    /* 49 bb [64-bit addr (8-byte)] movabs [64-bit addr (8-byte)],%r11 */
	((uint8_t *) text)[_NSYS + 0x07] = 0x49;
	((uint8_t *) text)[_NSYS + 0x08] = 0xbb;
	((uint8_t *) text)[_NSYS + 0x09] = ((uint64_t) asm_syscall_hook >> (8 * 0)) & 0xff;
	((uint8_t *) text)[_NSYS + 0x0a] = ((uint64_t) asm_syscall_hook >> (8 * 1)) & 0xff;
	((uint8_t *) text)[_NSYS + 0x0b] = ((uint64_t) asm_syscall_hook >> (8 * 2)) & 0xff;
	((uint8_t *) text)[_NSYS + 0x0c] = ((uint64_t) asm_syscall_hook >> (8 * 3)) & 0xff;
	((uint8_t *) text)[_NSYS + 0x0d] = ((uint64_t) asm_syscall_hook >> (8 * 4)) & 0xff;
	((uint8_t *) text)[_NSYS + 0x0e] = ((uint64_t) asm_syscall_hook >> (8 * 5)) & 0xff;
	((uint8_t *) text)[_NSYS + 0x0f] = ((uint64_t) asm_syscall_hook >> (8 * 6)) & 0xff;
	((uint8_t *) text)[_NSYS + 0x10] = ((uint64_t) asm_syscall_hook >> (8 * 7)) & 0xff;

	// 41 ff e3                jmp    *%r11
	((uint8_t *) text)[_NSYS + 0x11] = 0x41;
	((uint8_t *) text)[_NSYS + 0x12] = 0xff;
	((uint8_t *) text)[_NSYS + 0x13] = 0xe3;
	return i + 0x13;
}