// Copyright (c) 2026 Petr BalvĂ­n (https://petrbalvin.org) // SPDX-License-Identifier: BSD-3-Clause //go:build freebsd && riscv64 package debug import ( "fmt" "strings" "sourcedock.dev/petrbalvin/gasm-sdk/arch" "sourcedock.dev/petrbalvin/gasm-sdk/disasm" ) // Disassemble decodes the instruction at the given address in the debuggee's // memory and returns its text representation and length in bytes. The read // shrinks from 4 to 2 bytes when the full word crosses into unmapped memory: // a compressed instruction at the mapping's end still fits the shorter // window, and an instruction can never extend past the mapping that holds it. func (s *Session) Disassemble(addr uint64) (string, int, error) { var lastErr error for _, n := range []int{4, 2} { mem, err := s.ReadMemory(addr, n) if err != nil { lastErr = err continue } ins, derr := disasm.Decode(arch.RISCV, mem, addr) if derr != nil { return "", 0, derr } return ins.Text, ins.Len, nil } return "", 0, lastErr } // DisassembleN decodes up to n instructions starting at addr and returns // them as a formatted string with addresses and byte offsets. func (s *Session) DisassembleN(addr uint64, n int) string { var result strings.Builder pc := addr for range n { text, length, err := s.Disassemble(pc) if err != nil { result.WriteString(fmt.Sprintf(" %#08x: \n", pc, err)) break } result.WriteString(fmt.Sprintf(" %#08x: %s\n", pc, text)) if length == 0 { length = 1 } pc += uint64(length) } return result.String() } // isCallInsn reports whether disassembled text (riscv64asm.GoSyntax) is a // call. GoSyntax renders jal and jalr calls as CALL; the native mnemonics // are accepted too. The first token must match exactly: a prefix test on // "bl" would catch branches on other architectures, and jalr as ret prints // RET, which must not be stepped over. func isCallInsn(text string) bool { m, _, _ := strings.Cut(text, " ") switch strings.ToLower(m) { case "call", "jal", "jalr": return true } return false }