// Copyright 2026 aicongli-829
// Licensed under the Apache-2.0

///! PE AMD64 image identity and exception directory. Offsets follow Windows
///! SDK 10.0.26100.0 um/winnt.h: IMAGE_NT_HEADERS64 lines 19562-19566,
///! exception/debug directory indices lines 19636-19639,
///! IMAGE_SECTION_HEADER lines 19702-19716, RUNTIME_FUNCTION lines
///! 21382-21389, IMAGE_DEBUG_DIRECTORY lines 21500-21513.
///! UNWIND_INFO and UWOP semantics follow Microsoft Learn, "x64 exception handling".
///! All reads are bounded by the original file, never by SizeOfImage alone.

///|
#derive(Eq, Debug)
pub(all) struct BinaryX64Image {
  data : Bytes
  debug_id : String
  sections : Array[(UInt32, UInt32, UInt32)]
  exception_rva : UInt32
  exception_size : UInt32
}

///|
pub extend BinaryX64Image with Eq::{equal, not_equal}

///|
pub extend BinaryX64Image with Debug::{to_repr}

///|
fn pe_u8(data : Bytes, offset : Int32) -> Int32? {
  if offset < 0 || offset >= data.length() {
    None
  } else {
    match data.get(offset) {
      Some(v) => Some(v.to_int())
      None => None
    }
  }
}

///|
fn pe_u16(data : Bytes, offset : Int32) -> UInt32? {
  if offset < 0 || offset > data.length() - 2 {
    None
  } else {
    Some(data.unsafe_read_uint16_le(offset).to_int().reinterpret_as_uint())
  }
}

///|
fn pe_u32(data : Bytes, offset : Int32) -> UInt32? {
  if offset < 0 || offset > data.length() - 4 {
    None
  } else {
    Some(data.unsafe_read_uint32_le(offset))
  }
}

///|
fn pe_at(data : Bytes, offset : Int32, bytes : Array[Int32]) -> Bool {
  let mut i = 0
  while i < bytes.length() {
    if pe_u8(data, offset + i) != Some(bytes[i]) {
      return false
    }
    i = i + 1
  }
  true
}

///|
fn pe_file_offset(
  data : Bytes,
  sections : Array[(UInt32, UInt32, UInt32)],
  rva : UInt32,
  size : UInt32,
) -> Int32? {
  for (base, raw_size, raw_ptr) in sections {
    if rva >= base && size <= raw_size && rva - base <= raw_size - size {
      let offset = raw_ptr.to_uint64() + (rva - base).to_uint64()
      if offset <= data.length().to_uint64() &&
        size.to_uint64() <= data.length().to_uint64() - offset {
        return Some(offset.to_int())
      }
    }
  }
  None
}

///|
pub fn binary_x64_image(data : Bytes) -> BinaryX64Image? {
  if !pe_at(data, 0, [0x4d, 0x5a]) {
    return None
  }
  let pe = match pe_u32(data, 0x3c) {
    Some(v) => v.reinterpret_as_int()
    None => return None
  }
  if !pe_at(data, pe, [0x50, 0x45, 0, 0]) ||
    pe_u16(data, pe + 4) != Some(0x8664U) {
    return None
  }
  let count = match pe_u16(data, pe + 6) {
    Some(v) => v.reinterpret_as_int()
    None => return None
  }
  let opt_size = match pe_u16(data, pe + 20) {
    Some(v) => v.reinterpret_as_int()
    None => return None
  }
  let opt = pe + 24
  if opt_size < 168 ||
    pe_u16(data, opt) != Some(0x20bU) ||
    count > 96 ||
    opt < 0 ||
    opt > data.length() - opt_size {
    return None
  }
  let exception_rva = match pe_u32(data, opt + 112 + 3 * 8) {
    Some(v) => v
    None => return None
  }
  let exception_size = match pe_u32(data, opt + 112 + 3 * 8 + 4) {
    Some(v) => v
    None => return None
  }
  let debug_rva = match pe_u32(data, opt + 112 + 6 * 8) {
    Some(v) => v
    None => return None
  }
  let debug_size = match pe_u32(data, opt + 112 + 6 * 8 + 4) {
    Some(v) => v
    None => return None
  }
  if exception_size % 12U != 0U || debug_size == 0U || debug_size % 28U != 0U {
    return None
  }
  let sections : Array[(UInt32, UInt32, UInt32)] = []
  for i in 0.. v
      None => return None
    }
    let raw_size = match pe_u32(data, at + 16) {
      Some(v) => v
      None => return None
    }
    let raw_ptr = match pe_u32(data, at + 20) {
      Some(v) => v
      None => return None
    }
    sections.push((base, raw_size, raw_ptr))
  }
  let debug_at = match pe_file_offset(data, sections, debug_rva, debug_size) {
    Some(v) => v
    None => return None
  }
  let mut debug_id = ""
  for i in 0..<(debug_size.reinterpret_as_int() / 28) {
    let entry = debug_at + i * 28
    if pe_u32(data, entry + 12) == Some(2U) {
      let length = match pe_u32(data, entry + 16) {
        Some(v) => v
        None => return None
      }
      let raw = match pe_u32(data, entry + 24) {
        Some(v) => v.reinterpret_as_int()
        None => return None
      }
      if length >= 24U &&
        raw >= 0 &&
        raw.to_uint64() <= data.length().to_uint64() &&
        length.to_uint64() <= data.length().to_uint64() - raw.to_uint64() &&
        pe_at(data, raw, [0x52, 0x53, 0x44, 0x53]) {
        let order = [3, 2, 1, 0, 5, 4, 7, 6, 8, 9, 10, 11, 12, 13, 14, 15]
        let out = StringBuilder()
        for j in 0..<16 {
          match data.get(raw + 4 + order[j]) {
            Some(v) => out.write_string(hex_byte(v))
            None => return None
          }
        }
        let age = match pe_u32(data, raw + 20) {
          Some(v) => v
          None => return None
        }
        debug_id = out.to_string() + upper_hex(age.to_string(radix=16))
        break
      }
    }
  }
  if debug_id.length() == 0 ||
    (
      exception_size > 0U &&
      pe_file_offset(data, sections, exception_rva, exception_size) is None
    ) {
    None
  } else {
    Some({ data, debug_id, sections, exception_rva, exception_size, })
  }
}

///|
pub fn BinaryX64Image::runtime_function(
  self : BinaryX64Image,
  rva : UInt32,
) -> (UInt32, UInt32, UInt32)? {
  let start = match
    pe_file_offset(
      self.data,
      self.sections,
      self.exception_rva,
      self.exception_size,
    ) {
    Some(v) => v
    None => return None
  }
  for i in 0..<(self.exception_size.reinterpret_as_int() / 12) {
    let at = start + i * 12
    let begin = match pe_u32(self.data, at) {
      Some(v) => v
      None => return None
    }
    let end = match pe_u32(self.data, at + 4) {
      Some(v) => v
      None => return None
    }
    let unwind = match pe_u32(self.data, at + 8) {
      Some(v) => v
      None => return None
    }
    if begin <= rva && rva < end {
      return Some((begin, end, unwind))
    }
  }
  None
}

///|
fn binary_image_for_address(
  store : SymbolStore,
  modules : Array[Module],
  address : UInt64,
) -> BinaryX64Image? {
  let owner = match find_module(modules, address) {
    Some((_, m)) => m
    None => return None
  }
  let id = module_debug_id(owner)
  if id.length() == 0 {
    return None
  }
  let mut found : BinaryX64Image? = None
  for image in store.images {
    if image.debug_id == id {
      if found is Some(_) {
        return None
      }
      found = Some(image)
    }
  }
  found
}

///|
fn binary_read_stack(
  dump : Dump,
  map : MemoryMap,
  address : UInt64,
) -> UInt64? raise ParseError {
  if address > 0xfffffffffffffff7UL {
    None
  } else {
    dump.read_uint64_at(map, address)
  }
}

///|
fn binary_set_gpr(
  registers : UnwindRegisters,
  index : Int32,
  value : UInt64,
) -> Unit {
  set_register(registers, unwind_gpr_base + index, value)
  if index == 5 {
    set_register(registers, unwind_fp_slot, value)
  } else if index == 4 {
    set_register(registers, unwind_sp_slot, value)
  }
}

///|
fn binary_epilog(
  dump : Dump,
  map : MemoryMap,
  image : BinaryX64Image,
  rva : UInt32,
  end : UInt32,
  state : UnwindState,
) -> UnwindApply? raise ParseError {
  let size = if end - rva < 64U { end - rva } else { 64U }
  let start = match pe_file_offset(image.data, image.sections, rva, size) {
    Some(v) => v
    None => return Some(UnwindApply::Failed("epilog bytes are unavailable"))
  }
  let regs = clone_registers(state.registers)
  let mut rsp = state.sp
  let mut i = 0
  let mut started = false
  while i < size.reinterpret_as_int() && i <= 48 {
    let at = start + i
    let a = match pe_u8(image.data, at) {
      Some(v) => v
      None => return Some(UnwindApply::Failed("truncated epilog"))
    }
    let b = pe_u8(image.data, at + 1)
    let c = pe_u8(image.data, at + 2)
    if a == 0x48 &&
      b == Some(0x83) &&
      c == Some(0xc4) &&
      i + 4 <= size.reinterpret_as_int() {
      let amount = match pe_u8(image.data, at + 3) {
        Some(v) => v
        None => return Some(UnwindApply::Failed("truncated epilog"))
      }
      rsp = add_saturating(rsp, amount.to_uint64())
      i = i + 4
    } else if a == 0x48 &&
      b == Some(0x81) &&
      c == Some(0xc4) &&
      i + 7 <= size.reinterpret_as_int() {
      let amount = match pe_u32(image.data, at + 3) {
        Some(v) => v
        None => return Some(UnwindApply::Failed("truncated epilog"))
      }
      rsp = add_saturating(rsp, amount.to_uint64())
      i = i + 7
    } else if (a == 0x48 || a == 0x49) &&
      b == Some(0x8d) &&
      (c == Some(0x65) || c == Some(0xa5)) {
      let frame_reg = if a == 0x49 { 13 } else { 5 }
      let base = match register_value(regs, unwind_gpr_base + frame_reg) {
        Some(v) => v
        None =>
          return Some(UnwindApply::Failed("epilog frame register unavailable"))
      }
      let disp = if c == Some(0x65) {
        if i + 4 > size.reinterpret_as_int() {
          return Some(UnwindApply::Failed("truncated epilog"))
        }
        let raw = match pe_u8(image.data, at + 3) {
          Some(v) => v
          None => return Some(UnwindApply::Failed("truncated epilog"))
        }
        i = i + 4
        if raw >= 128 {
          raw - 256
        } else {
          raw
        }
      } else {
        if i + 7 > size.reinterpret_as_int() {
          return Some(UnwindApply::Failed("truncated epilog"))
        }
        let raw = match pe_u32(image.data, at + 3) {
          Some(v) => v.reinterpret_as_int()
          None => return Some(UnwindApply::Failed("truncated epilog"))
        }
        i = i + 7
        raw
      }
      let delta = disp.to_int64()
      let magnitude = if delta < 0L {
        (0L - delta).reinterpret_as_uint64()
      } else {
        delta.reinterpret_as_uint64()
      }
      if delta < 0L && base < magnitude {
        return Some(UnwindApply::Failed("epilog RSP underflow"))
      }
      rsp = if delta < 0L {
        base - magnitude
      } else {
        add_saturating(base, disp.to_uint64())
      }
    } else {
      let rex = if a >= 0x40 && a <= 0x4f { a } else { 0 }
      let op = if rex > 0 {
        match b {
          Some(v) => v
          None => 0
        }
      } else {
        a
      }
      let jump_ff = match b {
        Some(v) => a == 0xff && (v / 8 % 8 == 4 || v / 8 % 8 == 5)
        None => false
      }
      if op >= 0x58 && op <= 0x5f {
        let reg = op - 0x58 + (if rex % 2 == 1 { 8 } else { 0 })
        if reg == 4 {
          return Some(UnwindApply::Failed("POP RSP in epilog"))
        }
        match binary_read_stack(dump, map, rsp) {
          Some(v) => binary_set_gpr(regs, reg, v)
          None =>
            return Some(UnwindApply::Failed("epilog saved register missing"))
        }
        rsp = add_saturating(rsp, 8UL)
        i = i + (if rex > 0 { 2 } else { 1 })
      } else if op == 0xc3 && rex == 0 {
        let rip = match binary_read_stack(dump, map, rsp) {
          Some(v) => v
          None => return Some(UnwindApply::Failed("epilog return slot missing"))
        }
        let caller_sp = add_saturating(rsp, 8UL)
        if caller_sp <= state.sp {
          return Some(UnwindApply::Failed("epilog did not increase RSP"))
        }
        binary_set_gpr(regs, 4, caller_sp)
        set_register(regs, unwind_ra_slot, rip)
        return Some(
          UnwindApply::Step({
            state: {
              registers: regs,
              ip: rip,
              ip_known: true,
              lookup_ip: if rip > 0UL {
                rip - 1UL
              } else {
                0UL
              },
              sp: caller_sp,
              callee_parameter_size: 0UL,
              cfa_rule: None,
              ra_rule: None,
              register_rules: [],
            },
            stack_address: Some(rsp),
          }),
        )
      } else if started ||
        a == 0xc2 ||
        a == 0xe9 ||
        a == 0xeb ||
        jump_ff ||
        ((a == 0x48 || a == 0x49) && b == Some(0x8d)) {
        return Some(UnwindApply::Failed("unsupported x64 epilog instruction"))
      } else {
        return None
      }
    }
    started = true
  }
  if started {
    Some(UnwindApply::Failed("incomplete x64 epilog"))
  } else {
    None
  }
}

///|
fn binary_step(
  dump : Dump,
  map : MemoryMap,
  image : BinaryX64Image,
  rva : UInt32,
  state : UnwindState,
) -> UnwindApply raise ParseError {
  let regs = clone_registers(state.registers)
  let mut rsp = state.sp
  let entry = image.runtime_function(rva)
  if entry is Some(_) {
    let (initial_begin, end, initial_unwind) = match entry {
      Some(v) => v
      None => return UnwindApply::Failed("missing runtime function")
    }
    match binary_epilog(dump, map, image, rva, end, state) {
      Some(result) => return result
      None => ()
    }
    let mut begin = initial_begin
    let mut unwind_rva = initial_unwind
    let mut first = true
    let seen : Array[UInt32] = []
    let mut running = true
    while running {
      if seen.length() >= 8 || seen.contains(unwind_rva) {
        return UnwindApply::Failed("cyclic or deep chained UNWIND_INFO")
      }
      seen.push(unwind_rva)
      let at = match
        pe_file_offset(image.data, image.sections, unwind_rva, 4U) {
        Some(v) => v
        None =>
          return UnwindApply::Failed("UNWIND_INFO is not backed by PE bytes")
      }
      let header = match pe_u8(image.data, at) {
        Some(v) => v
        None => return UnwindApply::Failed("truncated UNWIND_INFO")
      }
      let prolog = match pe_u8(image.data, at + 1) {
        Some(v) => v
        None => return UnwindApply::Failed("truncated UNWIND_INFO")
      }
      let count = match pe_u8(image.data, at + 2) {
        Some(v) => v
        None => return UnwindApply::Failed("truncated UNWIND_INFO")
      }
      let frame = match pe_u8(image.data, at + 3) {
        Some(v) => v
        None => return UnwindApply::Failed("truncated UNWIND_INFO")
      }
      let flags = header / 8
      if header % 8 != 1 || flags > 7 || (flags >= 4 && flags % 4 != 0) {
        return UnwindApply::Failed("unsupported UNWIND_INFO version or flags")
      }
      let span = 4UL +
        ((count + 1) / 2 * 4).to_uint64() +
        (if flags >= 4 { 12UL } else { 0UL })
      if unwind_rva.to_uint64() + span > 0x100000000UL {
        return UnwindApply::Failed("UNWIND_INFO RVA overflow")
      }
      let code_at = match
        pe_file_offset(
          image.data,
          image.sections,
          unwind_rva + 4U,
          (count * 2).reinterpret_as_uint(),
        ) {
        Some(v) => v
        None => return UnwindApply::Failed("truncated UNWIND_CODE array")
      }
      let frame_reg = frame % 16
      let frame_offset = frame / 16
      let frame_base = if frame_reg > 0 {
        match register_value(regs, unwind_gpr_base + frame_reg) {
          Some(v) =>
            if v >= (frame_offset * 16).to_uint64() {
              Some(v - (frame_offset * 16).to_uint64())
            } else {
              None
            }
          None => None
        }
      } else {
        None
      }
      if frame_reg > 0 && frame_base is None {
        return UnwindApply::Failed("frame register is unavailable")
      }
      let mut i = 0
      let mut prior = 256
      while i < count {
        let offset = match pe_u8(image.data, code_at + i * 2) {
          Some(v) => v
          None => return UnwindApply::Failed("truncated UNWIND_CODE")
        }
        let packed = match pe_u8(image.data, code_at + i * 2 + 1) {
          Some(v) => v
          None => return UnwindApply::Failed("truncated UNWIND_CODE")
        }
        if offset > prolog || offset > prior {
          return UnwindApply::Failed("UNWIND_CODE offset is invalid")
        }
        prior = offset
        let op = packed % 16
        let info = packed / 16
        let extra = if op == 1 && info == 1 {
          2
        } else if op == 1 || op == 4 || op == 8 {
          1
        } else if op == 5 || op == 9 {
          2
        } else {
          0
        }
        if i + extra >= count {
          return UnwindApply::Failed("truncated UNWIND_CODE operand")
        }
        let operand = if extra == 1 {
          match pe_u16(image.data, code_at + (i + 1) * 2) {
            Some(v) => v.to_uint64()
            None => return UnwindApply::Failed("truncated UNWIND_CODE operand")
          }
        } else if extra == 2 {
          match pe_u32(image.data, code_at + (i + 1) * 2) {
            Some(v) => v.to_uint64()
            None => return UnwindApply::Failed("truncated UNWIND_CODE operand")
          }
        } else {
          0UL
        }
        i = i + 1 + extra
        if first &&
          (rva - begin).reinterpret_as_int() < prolog &&
          offset > (rva - begin).reinterpret_as_int() {
          continue
        }
        if op == 0 {
          match binary_read_stack(dump, map, rsp) {
            Some(v) => binary_set_gpr(regs, info, v)
            None =>
              return UnwindApply::Failed("saved register was not captured")
          }
          rsp = add_saturating(rsp, 8UL)
        } else if op == 1 && (info == 0 || info == 1) {
          rsp = add_saturating(
            rsp,
            if info == 0 {
              operand * 8UL
            } else {
              operand
            },
          )
        } else if op == 2 {
          rsp = add_saturating(rsp, (info * 8 + 8).to_uint64())
        } else if op == 3 && info == 0 {
          rsp = match frame_base {
            Some(v) => v
            None =>
              return UnwindApply::Failed("SET_FPREG has no frame register")
          }
        } else if op == 4 || op == 5 {
          let base = match frame_base {
            Some(v) => v
            None => rsp
          }
          let address = add_saturating(
            base,
            if op == 4 {
              operand * 8UL
            } else {
              operand
            },
          )
          match binary_read_stack(dump, map, address) {
            Some(v) => binary_set_gpr(regs, info, v)
            None =>
              return UnwindApply::Failed("saved register was not captured")
          }
        } else if op == 8 || op == 9 {
          // XMM restoration does not change a GPR, RIP, or RSP.
          ()
        } else if op == 10 && (info == 0 || info == 1) {
          let slot = add_saturating(rsp, if info == 1 { 8UL } else { 0UL })
          let rip = match binary_read_stack(dump, map, slot) {
            Some(v) => v
            None => return UnwindApply::Failed("machine-frame RIP missing")
          }
          let old_rsp = match
            binary_read_stack(dump, map, add_saturating(slot, 24UL)) {
            Some(v) => v
            None => return UnwindApply::Failed("machine-frame RSP missing")
          }
          if old_rsp <= state.sp {
            return UnwindApply::Failed("machine frame did not increase RSP")
          }
          binary_set_gpr(regs, 4, old_rsp)
          set_register(regs, unwind_ra_slot, rip)
          return UnwindApply::Step({
            state: {
              registers: regs,
              ip: rip,
              ip_known: true,
              lookup_ip: if rip > 0UL {
                rip - 1UL
              } else {
                0UL
              },
              sp: old_rsp,
              callee_parameter_size: 0UL,
              cfa_rule: None,
              ra_rule: None,
              register_rules: [],
            },
            stack_address: Some(slot),
          })
        } else {
          return UnwindApply::Failed("unsupported UNWIND_CODE opcode")
        }
        if rsp <= state.sp && rsp > 0xffffffffffffff00UL {
          return UnwindApply::Failed("RSP overflow")
        }
      }
      if flags >= 4 {
        let tail_rva = unwind_rva +
          4U +
          ((count + 1) / 2 * 4).reinterpret_as_uint()
        let tail = match
          pe_file_offset(image.data, image.sections, tail_rva, 12U) {
          Some(v) => v
          None => return UnwindApply::Failed("truncated chained UNWIND_INFO")
        }
        begin = match pe_u32(image.data, tail) {
          Some(v) => v
          None => return UnwindApply::Failed("truncated chained UNWIND_INFO")
        }
        unwind_rva = match pe_u32(image.data, tail + 8) {
          Some(v) => v
          None => return UnwindApply::Failed("truncated chained UNWIND_INFO")
        }
        first = false
      } else {
        running = false
      }
    }
  }
  let rip = match binary_read_stack(dump, map, rsp) {
    Some(v) => v
    None => return UnwindApply::Failed("return address slot was not captured")
  }
  let caller_sp = add_saturating(rsp, 8UL)
  if caller_sp <= state.sp {
    return UnwindApply::Failed("binary x64 unwind did not increase RSP")
  }
  binary_set_gpr(regs, 4, caller_sp)
  set_register(regs, unwind_ra_slot, rip)
  let next : UnwindState = {
    registers: regs,
    ip: rip,
    ip_known: true,
    lookup_ip: if rip > 0UL {
      rip - 1UL
    } else {
      0UL
    },
    sp: caller_sp,
    callee_parameter_size: 0UL,
    cfa_rule: None,
    ra_rule: None,
    register_rules: [],
  }
  UnwindApply::Step({ state: next, stack_address: Some(rsp), })
}