#!/usr/bin/env python3
# DF-2720 stage2: entry reads the wrapped file-backed mapping at 0x600000.
# exit code 65 (0x41) = read returned all-zero page; 66 (0x42) = non-zero data;
# signal death (sh prints 128+n / 'Memory fault') = SIGSEGV/SIGBUS on fault.
import struct
PAGE=4096
def phdr(t,flags,off,vaddr,paddr,filesz,memsz,align):
    return struct.pack('<IIQQQQQQ',t,flags,off,vaddr,paddr,filesz,memsz,align)
code = bytes.fromhex(
    '48a1000060000000000'  '0'      # placeholder fixed below
)
code = bytes.fromhex('48a100606000' + '00000000')  # wrong; assemble manually:
code  = bytes.fromhex('48a1') + struct.pack('<Q', 0x600000)   # movabs rax,[0x600000]
code += bytes.fromhex('4885c0')                               # test rax,rax
code += bytes.fromhex('7505')                                 # jne +5 -> exit(0x42)
code += bytes.fromhex('b83c000000') + bytes.fromhex('bf41000000') + bytes.fromhex('0f05')  # exit(65)
code += bytes.fromhex('b83c000000') + bytes.fromhex('bf42000000') + bytes.fromhex('0f05')  # exit(66)
e=bytearray(16); e[0:4]=b'\x7fELF'; e[4]=2; e[5]=1; e[6]=1
ph  = phdr(1,5,0,0x400000,0,2*PAGE,2*PAGE,PAGE)
ph += phdr(1,6,0xFFFFFFFFFFFFF000,0x600000,0,0x2000,0x4000,PAGE)
eh=struct.pack('<16sHHIQQQIHHHHHH',bytes(e),2,62,1,0x401000,64,0,0,64,56,2,0,0,0)
img=bytearray(2*PAGE)
img[0:len(eh)]=eh; img[64:64+len(ph)]=ph; img[PAGE:PAGE+len(code)]=code
open('wrapseg2','wb').write(bytes(img))
print('ok', len(code))
