Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 28 additions & 30 deletions classparser/classfilebuilder/code.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ type stackFrameEntry struct {
type Code struct {
pool *ConstantPool
nodes []codeNode
insnCount int
nextLabel int
handlers []exceptionHandler
lines []lineNumber
Expand All @@ -119,6 +120,17 @@ type Code struct {

func newCode(pool *ConstantPool) *Code { return &Code{pool: pool} }

// InstructionCount returns the number of bytecode instructions appended so far.
func (c *Code) InstructionCount() int {
return c.insnCount
}

func (c *Code) appendInsn(insn *instruction) *Code {
c.nodes = append(c.nodes, codeNode{insn: insn})
c.insnCount++
return c
}

func (c *Code) fail(format string, args ...any) {
if c.err == nil {
c.err = fmt.Errorf(format, args...)
Expand Down Expand Up @@ -165,8 +177,7 @@ func (c *Code) Emit(op Opcode) *Code {
c.fail("opcode 0x%02x is not an operandless supported instruction", byte(op))
return c
}
c.nodes = append(c.nodes, codeNode{insn: &instruction{kind: kindSimple, op: op}})
return c
return c.appendInsn(&instruction{kind: kindSimple, op: op})
}

// Byte appends a supported instruction with one signed or unsigned byte
Expand All @@ -187,8 +198,7 @@ func (c *Code) Byte(op Opcode, operand int) *Code {
c.fail("opcode 0x%02x does not take a one-byte operand", byte(op))
return c
}
c.nodes = append(c.nodes, codeNode{insn: &instruction{kind: kindByte, op: op, arg: operand}})
return c
return c.appendInsn(&instruction{kind: kindByte, op: op, arg: operand})
}

// Short appends SIPUSH with a signed 16-bit operand.
Expand All @@ -201,8 +211,7 @@ func (c *Code) Short(op Opcode, operand int) *Code {
c.fail("SIPUSH operand %d is outside signed short range", operand)
return c
}
c.nodes = append(c.nodes, codeNode{insn: &instruction{kind: kindShort, op: op, arg: operand}})
return c
return c.appendInsn(&instruction{kind: kindShort, op: op, arg: operand})
}

// CP appends a supported instruction with a u2 constant-pool operand.
Expand All @@ -227,8 +236,7 @@ func (c *Code) CP(op Opcode, index uint16) *Code {
c.fail("opcode 0x%02x cannot use constant pool index %d (tag %d)", byte(op), index, entry.tag)
return c
}
c.nodes = append(c.nodes, codeNode{insn: &instruction{kind: kindCP, op: op, arg: int(index)}})
return c
return c.appendInsn(&instruction{kind: kindCP, op: op, arg: int(index)})
}

// InvokeInterface appends invokeinterface. The count byte is derived from the
Expand All @@ -252,8 +260,7 @@ func (c *Code) InvokeInterface(index uint16) *Code {
c.fail("invokeinterface argument word count %d exceeds 255", args+1)
return c
}
c.nodes = append(c.nodes, codeNode{insn: &instruction{kind: kindInvokeInterface, op: INVOKEINTERFACE, arg: int(index), arg2: args + 1}})
return c
return c.appendInsn(&instruction{kind: kindInvokeInterface, op: INVOKEINTERFACE, arg: int(index), arg2: args + 1})
}

// InvokeDynamic appends invokedynamic referencing a CONSTANT_InvokeDynamic CP entry.
Expand All @@ -271,8 +278,7 @@ func (c *Code) InvokeDynamic(index uint16) *Code {
c.fail("invokedynamic descriptor %q: %v", entry.text, err)
return c
}
c.nodes = append(c.nodes, codeNode{insn: &instruction{kind: kindInvokeDynamic, op: INVOKEDYNAMIC, arg: int(index)}})
return c
return c.appendInsn(&instruction{kind: kindInvokeDynamic, op: INVOKEDYNAMIC, arg: int(index)})
}

// Load appends a typed local load, selecting compact or WIDE encoding.
Expand All @@ -282,8 +288,7 @@ func (c *Code) Load(kind LocalKind, index uint16) *Code {
c.fail("invalid local kind %d", kind)
return c
}
c.nodes = append(c.nodes, codeNode{insn: &instruction{kind: kindLocal, op: op, arg: int(index), arg2: localWidth(kind)}})
return c
return c.appendInsn(&instruction{kind: kindLocal, op: op, arg: int(index), arg2: localWidth(kind)})
}

// Store appends a typed local store, selecting compact or WIDE encoding.
Expand All @@ -293,14 +298,12 @@ func (c *Code) Store(kind LocalKind, index uint16) *Code {
c.fail("invalid local kind %d", kind)
return c
}
c.nodes = append(c.nodes, codeNode{insn: &instruction{kind: kindLocal, op: op, arg: int(index), arg2: localWidth(kind)}})
return c
return c.appendInsn(&instruction{kind: kindLocal, op: op, arg: int(index), arg2: localWidth(kind)})
}

// IInc appends iinc, selecting WIDE when either operand requires it.
func (c *Code) IInc(index uint16, delta int16) *Code {
c.nodes = append(c.nodes, codeNode{insn: &instruction{kind: kindIInc, op: IINC, arg: int(index), arg2: int(delta)}})
return c
return c.appendInsn(&instruction{kind: kindIInc, op: IINC, arg: int(index), arg2: int(delta)})
}

// LDC appends ldc or ldc_w according to the final constant-pool index.
Expand All @@ -314,8 +317,7 @@ func (c *Code) LDC(index uint16) *Code {
c.fail("ldc does not support constant pool tag %d at index %d", entry.tag, index)
return c
}
c.nodes = append(c.nodes, codeNode{insn: &instruction{kind: kindLDC, op: LDC, arg: int(index)}})
return c
return c.appendInsn(&instruction{kind: kindLDC, op: LDC, arg: int(index)})
}

// LDC2 appends ldc2_w, which pushes a long or double constant.
Expand All @@ -329,8 +331,7 @@ func (c *Code) LDC2(index uint16) *Code {
c.fail("ldc2_w does not support constant pool tag %d at index %d", entry.tag, index)
return c
}
c.nodes = append(c.nodes, codeNode{insn: &instruction{kind: kindCP, op: LDC2_W, arg: int(index)}})
return c
return c.appendInsn(&instruction{kind: kindCP, op: LDC2_W, arg: int(index)})
}

// Branch appends goto or a supported conditional branch. Goto is widened to
Expand All @@ -343,8 +344,7 @@ func (c *Code) Branch(op Opcode, target *Label) *Code {
c.fail("opcode 0x%02x is not a supported branch", byte(op))
return c
}
c.nodes = append(c.nodes, codeNode{insn: &instruction{kind: kindBranch, op: op, target: target}})
return c
return c.appendInsn(&instruction{kind: kindBranch, op: op, target: target})
}

// TableSwitch appends a tableswitch whose consecutive case values start at
Expand All @@ -367,11 +367,10 @@ func (c *Code) TableSwitch(low int32, defaultTarget *Label, targets ...*Label) *
return c
}
}
c.nodes = append(c.nodes, codeNode{insn: &instruction{
return c.appendInsn(&instruction{
kind: kindTableSwitch, op: TABLESWITCH, arg: int(low), target: defaultTarget,
targets: append([]*Label(nil), targets...),
}})
return c
})
}

// LookupSwitch appends a lookupswitch. keys and targets are corresponding
Expand All @@ -393,11 +392,10 @@ func (c *Code) LookupSwitch(defaultTarget *Label, keys []int32, targets ...*Labe
return c
}
}
c.nodes = append(c.nodes, codeNode{insn: &instruction{
return c.appendInsn(&instruction{
kind: kindLookupSwitch, op: LOOKUPSWITCH, target: defaultTarget,
keys: append([]int32(nil), keys...), targets: append([]*Label(nil), targets...),
}})
return c
})
}

// Catch adds an exception-table entry. catchClass is an internal class name;
Expand Down
39 changes: 39 additions & 0 deletions classparser/decompiler/core/branch_array_inline_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,45 @@ func TestThrownOperandParticipatesInPrivateArrayOwnership(t *testing.T) {
}
}

func TestSourceAssignmentForwardParticipatesInLocalReferenceChecks(t *testing.T) {
target := values.NewJavaRef(utils.NewRootVariableId(), nil, types.NewJavaClass("java.lang.Object"))
unrelatedLHS := values.NewJavaRef(utils.NewRootVariableId(), nil, types.NewJavaClass("java.lang.String"))
unrelatedRHS := values.NewJavaLiteral("hello", types.NewJavaClass("java.lang.String"))

for _, tc := range []struct {
name string
stmt statements.Statement
want bool
}{
{
name: "unrelated assignment forward",
stmt: statements.NewSourceAssignmentForward(statements.NewAssignStatement(unrelatedLHS, unrelatedRHS, true)),
want: false,
},
{
name: "writes target ref",
stmt: statements.NewSourceAssignmentForward(statements.NewAssignStatement(target, unrelatedRHS, true)),
want: true,
},
{
name: "reads target ref on RHS",
stmt: statements.NewSourceAssignmentForward(statements.NewAssignStatement(unrelatedLHS, target, true)),
want: true,
},
{
name: "opaque custom statement stays true",
stmt: &statements.CustomStatement{StringFunc: func(*class_context.ClassContext) string { return "custom();" }},
want: true,
},
} {
t.Run(tc.name, func(t *testing.T) {
if got := statementReferencesLocal(tc.stmt, target); got != tc.want {
t.Fatalf("statementReferencesLocal=%v, want %v", got, tc.want)
}
})
}
}

func TestBranchArrayReturnWalkPreservesNestedCatchConsumer(t *testing.T) {
for _, scenario := range []string{"nested catch", "multiple uses", "opaque", "live expression"} {
t.Run(scenario, func(t *testing.T) {
Expand Down
3 changes: 3 additions & 0 deletions classparser/decompiler/core/guarded_call_inline.go
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,9 @@ func statementReferencesLocal(statement statements.Statement, ref *values.JavaRe
case *statements.SynchronizedStatement:
return read(s.Argument) || listReads(s.Body)
case *statements.CustomStatement:
if assign, ok := s.SourceAssignmentForward(); ok {
return statementReferencesLocal(assign, ref, skip...)
}
if s.ThrownValue != nil {
// ATHROW records its complete typed operand. Its rendering closure
// adds no hidden dependencies; inspect the thrown expression itself.
Expand Down
1 change: 1 addition & 0 deletions classparser/decompiler/rewriter/rewrite_var.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,7 @@ func RewriteVar(sts *[]statements.Statement, startVarId int, params []*values.Ja
// IsFirst decisions above are final and this pass's demotions are not subsequently undone.
hoistSwitchDeclarations(sts)
dropEmptySlotAssignments(sts)
dropDanglingCaughtExceptionDiscards(sts)
// General LCA declaration placement: hoist any generated local whose variable is referenced
// across more than one sibling scope to the block that dominates all of its uses. Runs last so it
// sees the final IsFirst/IsDeclare flags and any bare declarations the if/switch hoisters already
Expand Down
51 changes: 51 additions & 0 deletions classparser/decompiler/rewriter/source_assignment_forward_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -308,4 +308,55 @@ func TestHoistDeclarationsRewritesInBodyReadsAndUsesIdentity(t *testing.T) {
t.Fatalf("expected zero stale var29 tokens in unified arms, got:\n%s", rendered)
}
})

t.Run("drop_dangling_caught_exception_discards", func(t *testing.T) {
excType := types.NewJavaClass("java/lang/Exception")
newExcVal := func(name string) *values.CustomValue {
cv := values.NewCustomValue(func(*class_context.ClassContext) string {
return name
}, func() types.JavaType {
return excType
})
cv.Flag = "exception"
return cv
}

danglingTop := statements.NewExpressionStatement(newExcVal("Exception;"))
danglingIf := statements.NewExpressionStatement(newExcVal("Throwable;"))
danglingElse := statements.NewExpressionStatement(newExcVal("RuntimeException;"))

savedID := utils.NewRootVariableId().Next()
keepAssign := statements.NewAssignStatement(mkRef("ref-400", "saved", savedID, excType), newExcVal("caught"), true)
keepNormal := statements.NewExpressionStatement(values.NewJavaLiteral(1, intType))
keepThrow := statements.NewThrowStatement(newExcVal("rethrown"))

ifSt := statements.NewIfStatement(
values.NewJavaLiteral(true, boolType),
[]statements.Statement{danglingIf, keepAssign},
[]statements.Statement{danglingElse, keepNormal, keepThrow},
)
root := []statements.Statement{danglingTop, ifSt}

dropDanglingCaughtExceptionDiscards(&root)

if len(root) != 1 || root[0] != ifSt {
t.Fatalf("expected dangling top-level exception discard dropped, got len=%d", len(root))
}
if len(ifSt.IfBody) != 1 || ifSt.IfBody[0] != keepAssign {
t.Fatalf("expected dangling exception in IfBody dropped and AssignStatement kept, got %#v", ifSt.IfBody)
}
if len(ifSt.ElseBody) != 2 || ifSt.ElseBody[0] != keepNormal || ifSt.ElseBody[1] != keepThrow {
t.Fatalf("expected dangling exception in ElseBody dropped while normal expr & throw kept, got %#v", ifSt.ElseBody)
}

// Also confirm RewriteVar invokes dangling discard cleanup end-to-end.
rootViaRewrite := []statements.Statement{
statements.NewExpressionStatement(newExcVal("Exception;")),
statements.NewReturnStatement(values.NewJavaLiteral(0, intType)),
}
RewriteVar(&rootViaRewrite, 0, nil)
if len(rootViaRewrite) != 1 {
t.Fatalf("expected RewriteVar to drop dangling exception discard, got len=%d", len(rootViaRewrite))
}
})
}
50 changes: 50 additions & 0 deletions classparser/decompiler/rewriter/try_rewriter.go
Original file line number Diff line number Diff line change
Expand Up @@ -369,3 +369,53 @@ func TryRewriter(manager *RewriteManager, node *core.Node) error {
}
return finishForwardRegion(manager, node, regionStart)
}

func isDanglingCaughtExceptionDiscard(st statements.Statement) bool {
expr, ok := st.(*statements.ExpressionStatement)
if !ok || expr == nil {
return false
}
cv, ok := core.UnpackSoltValue(expr.Expression).(*values.CustomValue)
return ok && cv != nil && cv.Flag == "exception"
}

// dropDanglingCaughtExceptionDiscards removes orphaned statement-level caught
// exception placeholders (`Exception;` from JVM/DEX handler exception pops) left
// outside structured catch headers. AssignStatement, ThrowStatement, and other
// expressions are left untouched.
func dropDanglingCaughtExceptionDiscards(sts *[]statements.Statement) {
if sts == nil {
return
}
list := *sts
out := make([]statements.Statement, 0, len(list))
for _, st := range list {
if isDanglingCaughtExceptionDiscard(st) {
continue
}
switch s := st.(type) {
case *statements.IfStatement:
dropDanglingCaughtExceptionDiscards(&s.IfBody)
dropDanglingCaughtExceptionDiscards(&s.ElseBody)
case *statements.ForStatement:
dropDanglingCaughtExceptionDiscards(&s.SubStatements)
case *statements.WhileStatement:
dropDanglingCaughtExceptionDiscards(&s.Body)
case *statements.DoWhileStatement:
dropDanglingCaughtExceptionDiscards(&s.Body)
case *statements.SynchronizedStatement:
dropDanglingCaughtExceptionDiscards(&s.Body)
case *statements.TryCatchStatement:
dropDanglingCaughtExceptionDiscards(&s.TryBody)
for i := range s.CatchBodies {
dropDanglingCaughtExceptionDiscards(&s.CatchBodies[i])
}
case *statements.SwitchStatement:
for i := range s.Cases {
dropDanglingCaughtExceptionDiscards(&s.Cases[i].Body)
}
}
out = append(out, st)
}
*sts = out
}
5 changes: 3 additions & 2 deletions classparser/dumper.go
Original file line number Diff line number Diff line change
Expand Up @@ -12840,10 +12840,11 @@ func (c *ClassObjectDumper) dumpStubMethod(method *MemberInfo, name, descriptor,
case "<init>":
src = fmt.Sprintf("%s%s(%s)%s", prefix, c.GetConstructorMethodName(), paramsStr, throwBody)
default:
safeName := class_context.SafeIdentifier(name)
if isAbstract {
src = fmt.Sprintf("%s%s %s(%s);", prefix, returnTypeForRender.String(funcCtx), name, paramsStr)
src = fmt.Sprintf("%s%s %s(%s);", prefix, returnTypeForRender.String(funcCtx), safeName, paramsStr)
} else {
src = fmt.Sprintf("%s%s %s(%s)%s", prefix, returnTypeForRender.String(funcCtx), name, paramsStr, throwBody)
src = fmt.Sprintf("%s%s %s(%s)%s", prefix, returnTypeForRender.String(funcCtx), safeName, paramsStr, throwBody)
}
}
return &dumpedMethods{methodName: name, code: src, bodyCode: "stub", isStub: true}
Expand Down
Loading
Loading