// File: /workspace/github_cpp_makefile_star2_O2/overfl0[P]iojack/iojack.cpp
// Function: main
int main(int argc, char *argv[])
{
    pthread_t pollStdinThread;
    setSignalHandlers();
    initSyscallHooks();

    int firstPid = getArgs(argc, argv);

    printf("Attaching to pid: %d\n", firstPid);
    if(ptrace(PTRACE_ATTACH, firstPid, NULL, NULL) == -1)
    {
        if(errno == EPERM)
        {
            pexit("Could not attach to process due to lack of permissions\n"
                  "If you're on ubuntu, you may try the following as root:\n"
                  "echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope\n");
        }
        else
            perrorexit("PTRACE_ATTACH");
    }

    int status;
    // Should be checked
    firstPid = wait(&status);
    if(WIFEXITED(status))
    {
        printf("Process %d exited\n", firstPid);
        return 0;
    }

    if(ptrace(PTRACE_SETOPTIONS, firstPid, NULL,
        PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORK | PTRACE_O_TRACECLONE | PTRACE_O_TRACEEXEC
        /*| PTRACE_O_TRACESYSGOOD ? */) == -1)
        perrorexit("PTRACE_SETOPTIONS");

    int retval = pthread_create(&pollStdinThread, NULL, stdinPoll, (void*)&inputBuffer);
    if(retval)
        perrorexit("Reading input thread");

    processes[firstPid] = new processInfo(firstPid);
    processes[firstPid]->guessFds();

    // We are interested only in syscalls
    processes[firstPid]->stopAtSyscall();

    unsigned char applicationSequences[] = {0x1b, 0x5b, 0x3f, 0x31, 0x68};
    if(!globalSettings.sendANSI)
        printf("%s", applicationSequences);

    //=========================================================================
    while(!processes.empty())
    {
        // Wait for a syscall to be called
        int pidReceived = wait(&status);
        if(pidReceived == -1)
        {
            perror("wait");
            continue;
        }

        // pidReceived != -1, so get full info about this process
        processes_t::iterator it = processes.find(pidReceived);
        if(it == processes.end())
        {
            // On purpose. This may be a bug that should not get unnoticed!
            //pexit("Unexpected pid %d received by wait call\n", pidReceived);

            // Too bad that this may happen on clone() and fork() calls :(
            // Ugly workaround
            // FIXME TODO FIXME TODO This is WAY too ugly to be kept unchanged
            processes[pidReceived] = new processInfo(pidReceived);
            it = processes.find(pidReceived);
            it->second->sigstopNewChild = 1;
        }
        processInfo * pi = it->second;

        if(WIFEXITED(status) || WIFSIGNALED(status))
        {
            dprintf("Process %d exited\n", pidReceived);
            processes.erase(pidReceived);

            continue;
        }

        if(WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP)
        {
            dprintf("[%d] ******WIFSTOPPED!******\n", pi->pid);
            if(pi->sigstopToDetach)
            {
                // That's our chance! :)
                printf("Pid %d stopped while we wanted to quit. Trying to detach now...\n", pi->pid);
                pi->detachProcess();
                processes.erase(pidReceived);
                continue;
            }

            if(pi->sigstopToRestartSyscall)
            {
                dprintf("Restarting tracing of pid %d\n", pi->pid);
                pi->sigstopToRestartSyscall = 0;

                pi->stopAtSyscall();
                continue;
            }

            if(pi->sigstopNewChild)
            {
                pi->sigstopNewChild = 0;
                dprintf("[%d] The new child has stopped.\n", pi->pid);

                if(ptrace(PTRACE_SETOPTIONS, pi->pid, NULL,
                   PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORK | PTRACE_O_TRACECLONE | PTRACE_O_TRACEEXEC
                   /*| PTRACE_O_TRACESYSGOOD ? */) == -1)
                    perrorexit("PTRACE_SETOPTIONS");

                pi->stopAtSyscall();
                continue;
            }
        }

        // If it's not our signal, forward it to the program and continue the loop
        if(WIFSTOPPED(status) && WSTOPSIG(status) != SIGTRAP)
        {
            dprintf("Pid %d stopped with signal: %d\n", pi->pid, WSTOPSIG(status));

            pi->stopAtSyscall(WSTOPSIG(status));
            continue;
        }

        // Check if we have got a new child
        // FIXME: Find a macro that returns the event
        int event = status >> 16;
        if(event == PTRACE_EVENT_FORK || event == PTRACE_EVENT_VFORK || event == PTRACE_EVENT_CLONE)
        {
            unsigned long newPid;
            if(ptrace(PTRACE_GETEVENTMSG, pi->pid, 0, &newPid) == -1)
                perrorexit("PTRACE_GETEVENTMSG");
            printf("[%d] A new process forked/vforked/cloned: %lu\n", pi->pid, newPid);

            processInfo *newPi = new processInfo(newPid);
            newPi->sigstopNewChild = 1;
            // Copy file descriptors from the parent
            //FIXME: Race condition with pi->pid calling close() before we get here
            newPi->stdin = pi->stdin;
            newPi->stdout = pi->stdout;
            newPi->stderr = pi->stderr;
            processes[newPid] = newPi;

            pi->stopAtSyscall();

            continue;
        }
        if(event == PTRACE_EVENT_EXEC)
        {
            // TODO: We probably need to close some fds here (FD_CLOEXEC)
            dprintf("###################################################################\n");
            dprintf("Wykryto exec!\n");
            dprintf("###################################################################\n");
            pi->stopAtSyscall();

            continue;
        }

        //=Handle syscalls and registers=======================================
        struct user_regs_struct regs;
        if(ptrace((__ptrace_request)PTRACE_GETREGS, pi->pid, 0, &regs) == -1)
            perrorexit("PTRACE_GETREGS");

        int saveRegs = 0;
        processSyscall(pi, &regs, &saveRegs);
        if(saveRegs)
        {
            if(ptrace((__ptrace_request)PTRACE_SETREGS, pi->pid, 0, &regs) == -1)
                perrorexit("PTRACE_SETREGS");
        }
        //=====================================================================

        if(wantToExit && pi->inSyscall == 0 && pi->fakingSyscall != -1)
        {
            pi->detachProcess();
            processes.erase(pi->pid);
            continue;
        }

        // We are interested only in syscalls
        pi->stopAtSyscall();
    }

    wantToExit = 1;
    pthread_join(pollStdinThread, NULL);

    return 0;
}

// Assembly:
pushq %rbp
pushq %r15
pushq %r14
pushq %r13
pushq %r12
pushq %rbx
subq $0xf8, %rsp
movq %rsi, %rbx
movl %edi, %ebp
callq 0x2700
callq 0x531b
movl %ebp, %edi
movq %rbx, %rsi
callq 0x255b
movl %eax, %ebx
leaq 0x368d(%rip), %rdi      # 0x60ca
movl %eax, %esi
xorl %eax, %eax
callq 0x2040
pushq $0x10
popq %rdi
movl %ebx, %esi
xorl %edx, %edx
xorl %ecx, %ecx
xorl %eax, %eax
callq 0x2140
cmpq $-0x1, %rax
je 0x2e53
leaq 0x8(%rsp), %rbx
movq %rbx, %rdi
callq 0x2200
movl %eax, 0x14(%rsp)
testb $0x7f, (%rbx)
je 0x2e26
pushq $0x1e
popq %rcx
movl $0x4200, %edi           # imm = 0x4200
movl %eax, %esi
xorl %edx, %edx
xorl %eax, %eax
callq 0x2140
cmpq $-0x1, %rax
je 0x2e6b
leaq -0x355(%rip), %rdx      # 0x2749
leaq 0x87db(%rip), %rcx      # 0xb280
leaq 0x18(%rsp), %rdi
xorl %esi, %esi
callq 0x2330
testl %eax, %eax
jne 0x2e74
movl $0x180, %edi            # imm = 0x180
callq 0x2170
movq %rax, %rbx
leaq 0x14(%rsp), %r14
movl (%r14), %esi
movq %rax, %rdi
callq 0x2eaa
leaq 0x86eb(%rip), %r15      # 0xb1c8
movq %r15, %rdi
movq %r14, %rsi
callq 0x2f4e
movq %rbx, (%rax)
movq %r15, %rdi
movq %r14, %rsi
callq 0x2f4e
movq (%rax), %rdi
callq 0x45ee
movq %r15, %rdi
movq %r14, %rsi
callq 0x2f4e
movq (%rax), %rdi
xorl %esi, %esi
callq 0x45b4
movb $0x68, 0x10(%rsp)
movl $0x313f5b1b, 0xc(%rsp)  # imm = 0x313F5B1B
cmpb $0x0, 0x8699(%rip)      # 0xb1c0
jne 0x2b3c
leaq 0x4efc(%rip), %rdi      # 0x7a2c
leaq 0xc(%rsp), %rsi
xorl %eax, %eax
callq 0x2040
leaq 0x8(%rsp), %rbx
leaq 0x8680(%rip), %r15      # 0xb1c8
movq %rsp, %r13
leaq 0x867e(%rip), %rbp      # 0xb1d0
leaq 0x20(%rsp), %r12
cmpq $0x0, 0x8691(%rip)      # 0xb1f0
je 0x2e0e
movq %rbx, %rdi
callq 0x2200
movl %eax, (%rsp)
cmpl $-0x1, %eax
je 0x2d01
movq %r15, %rdi
movq %r13, %rsi
callq 0x35e2
cmpq %rbp, %rax
je 0x2b8f
movq 0x28(%rax), %r14
jmp 0x2bcc
movl $0x180, %edi            # imm = 0x180
callq 0x2170
movq %rax, %r14
movl (%rsp), %esi
movq %rax, %rdi
callq 0x2eaa
movq %r15, %rdi
movq %r13, %rsi
callq 0x2f4e
movq %r14, (%rax)
movq %r15, %rdi
movq %r13, %rsi
callq 0x35e2
movq 0x28(%rax), %r14
movl $0x1, 0x14(%r14)
movl 0x8(%rsp), %eax
movl %eax, %ecx
andl $0x7f, %ecx
je 0x2c12
shll $0x18, %ecx
addl $0x1000000, %ecx        # imm = 0x1000000
cmpl $0x2000000, %ecx        # imm = 0x2000000
jge 0x2c12
cmpw $0x137f, %ax            # imm = 0x137F
jne 0x2c22
cmpl $0x0, 0xc(%r14)
je 0x2d94
movl (%r14), %esi
leaq 0x3525(%rip), %rdi      # 0x6128
xorl %eax, %eax
callq 0x2040
movq %r14, %rdi
callq 0x44e4
movq %r15, %rdi
movq %r13, %rsi
callq 0x3616
jmp 0x2b57
cmpb $0x7f, %al
jne 0x2c32
movzbl %ah, %esi
cmpl $0x5, %esi
jne 0x2da2
sarl $0x10, %eax
leal -0x1(%rax), %ecx
cmpl $0x2, %ecx
ja 0x2d12
movq %rbp, %rbx
movl (%r14), %esi
movl $0x4201, %edi           # imm = 0x4201
xorl %edx, %edx
movq %r12, %rcx
xorl %eax, %eax
callq 0x2140
cmpq $-0x1, %rax
je 0x2e4a
movl (%r14), %esi
movq 0x20(%rsp), %rdx
leaq 0x350b(%rip), %rdi      # 0x617c
xorl %eax, %eax
callq 0x2040
movl $0x180, %edi            # imm = 0x180
callq 0x2170
movq %rax, %r13
movl 0x20(%rsp), %esi
movq %rax, %rdi
callq 0x2eaa
movl $0x1, 0x14(%r13)
movl $0xf0, %eax
leaq (%r14,%rax), %rsi
leaq (%rax,%r13), %rdi
callq 0x304e
movl $0x120, %eax            # imm = 0x120
leaq (%r14,%rax), %rsi
leaq (%rax,%r13), %rdi
callq 0x304e
movl $0x150, %eax            # imm = 0x150
leaq (%r14,%rax), %rsi
leaq (%rax,%r13), %rdi
callq 0x304e
movl 0x20(%rsp), %eax
movl %eax, 0x4(%rsp)
movq %r15, %rdi
leaq 0x4(%rsp), %rsi
callq 0x2f9c
movq %r13, (%rax)
movq %r14, %rdi
xorl %esi, %esi
callq 0x45b4
movq %rbx, %rbp
leaq 0x8(%rsp), %rbx
movq %rsp, %r13
jmp 0x2b57
leaq 0x47e8(%rip), %rdi      # 0x74f0
callq 0x2130
jmp 0x2b57
cmpl $0x4, %eax
je 0x2ddd
movl (%r14), %esi
pushq $0xc
popq %rdi
xorl %edx, %edx
movq %r12, %r13
movq %r12, %rcx
xorl %eax, %eax
callq 0x2140
cmpq $-0x1, %rax
je 0x2e7d
andl $0x0, 0x4(%rsp)
movq %r14, %rdi
movq %r13, %rsi
leaq 0x4(%rsp), %rdx
callq 0x28e0
cmpl $0x0, 0x4(%rsp)
je 0x2d72
movl (%r14), %esi
pushq $0xd
popq %rdi
xorl %edx, %edx
movq %r13, %rcx
xorl %eax, %eax
callq 0x2140
cmpq $-0x1, %rax
je 0x2e8f
cmpl $0x0, 0x844b(%rip)      # 0xb1c4
je 0x2d82
cmpl $0x0, 0x4(%r14)
je 0x2dec
movq %r14, %rdi
xorl %esi, %esi
callq 0x45b4
movq %rsp, %r13
jmp 0x2b57
cmpl $0x0, 0x10(%r14)
je 0x2daf
andl $0x0, 0x10(%r14)
jmp 0x2ddd
movq %r14, %rdi
callq 0x45b4
jmp 0x2b57
cmpl $0x0, 0x14(%r14)
je 0x2c26
andl $0x0, 0x14(%r14)
movl (%r14), %esi
movl $0x4200, %edi           # imm = 0x4200
xorl %edx, %edx
pushq $0x1e
popq %rcx
xorl %eax, %eax
callq 0x2140
cmpq $-0x1, %rax
je 0x2e6b
movq %r14, %rdi
xorl %esi, %esi
callq 0x45b4
jmp 0x2b57
cmpl $-0x1, 0x8(%r14)
je 0x2d82
movq %r14, %rdi
callq 0x44e4
movq %r15, %rdi
movq %r14, %rsi
callq 0x3616
movq %rsp, %r13
jmp 0x2b57
movl $0x1, 0x83ac(%rip)      # 0xb1c4
movq 0x18(%rsp), %rdi
xorl %esi, %esi
callq 0x2160
jmp 0x2e36
leaq 0x32c1(%rip), %rdi      # 0x60ee
movl %eax, %esi
xorl %eax, %eax
callq 0x2040
xorl %eax, %eax
addq $0xf8, %rsp
popq %rbx
popq %r12
popq %r13
popq %r14
popq %r15
popq %rbp
retq
leaq 0x3318(%rip), %rdi      # 0x6169
jmp 0x2e96
callq 0x2030
cmpl $0x1, (%rax)
jne 0x2e86
leaq 0x3436(%rip), %rdi      # 0x629a
callq 0x22c0
jmp 0x2e9b
leaq 0x328f(%rip), %rdi      # 0x6101
jmp 0x2e96
leaq 0x3298(%rip), %rdi      # 0x6113
jmp 0x2e96
leaq 0x3327(%rip), %rdi      # 0x61ab
jmp 0x2e96
leaq 0x3253(%rip), %rdi      # 0x60e0
jmp 0x2e96
leaq 0x3324(%rip), %rdi      # 0x61ba
callq 0x2130
pushq $0x1
popq %rdi
callq 0x21f0
nop