From 57ffec6c1a2b8d90ece96ff98134ee1ee0222b37 Mon Sep 17 00:00:00 2001 From: v1ll4n Date: Sun, 22 Nov 2026 13:56:37 +0800 Subject: [PATCH 1/2] feat(dex): harden Android/DEX translation, R8 recovery, canonical enums, and parallel archive export - DEX recovery & annotation hardening (internal/dexparser, dex2jar/input): tolerate mismatched DEX SHA-1 headers with valid Adler-32 checksums and orphan AnnotationDefault elements under FailureRecover while preserving FailureStrict failure contracts. - IR & register-kind soundness (dex2jar/ir, dex2jar/lower): fix null-array ops (0x44..0x51), JVMS interface assignability, untyped-null reference joins across non-array uses, multi-kind companion slots/prologue stores, legacy single-kind pinnedZeroKind, zero-source move/stackmap local-kind alignment, and safe try-catch exception table coalescing. - CFG constructor validation & R8 synthesis (dex2jar/r8_init.go, dex2jar/lower/validate.go): synthesize R8-inlined/stripped forwarding chains (including platform exception/core hierarchies and Void-parameter collision disambiguation via PatchedMethods/PatchedNullArgs) plus CFG-based this-initialization, branching/throw-only , discarded filled-new-array, and recovered parameter annotation right-alignment. - Canonical DEX/Kotlin enums & enum decompilation (dex2jar/lower/enum_canonical.go, classparser/decompiler/core): infer declaration ordinal order from , emit javac/Kotlin-canonical values()/valueOf()/()///enum-constant bytecode, and delegate sealed SourceAssignmentForward checks in guarded_call_inline.go. - Archive export recovery & throughput (internal/filesys, classparser/jarwar, classparser/dumper.go): sanitize best-effort case-fold archive collisions into __caseN/ subdirectories preserving .java filenames, parallelize DumpToLocalFileSystem deterministically with bounded workers, and sanitize stub method names with SafeIdentifier. - Sealed CI & soundness tests: add Wave 1-3.5 regression tests and sync tools/requiredci/main.go. --- classparser/classfilebuilder/code.go | 58 +- .../core/branch_array_inline_test.go | 39 + .../decompiler/core/guarded_call_inline.go | 3 + .../decompiler/rewriter/rewrite_var.go | 1 + .../source_assignment_forward_test.go | 51 + .../decompiler/rewriter/try_rewriter.go | 50 + classparser/dumper.go | 5 +- classparser/jarwar/casefold_recover_test.go | 81 ++ classparser/jarwar/exports.go | 2 + classparser/jarwar/jarwar.go | 291 +++- classparser/jarwar/structured.go | 33 +- classparser/stub_method_name_test.go | 34 + classparser/t23_archive.go | 34 +- dex2jar/dex2jar.go | 26 +- dex2jar/input/input.go | 11 +- dex2jar/ir/build.go | 25 +- dex2jar/ir/categories.go | 13 +- dex2jar/ir/cfg.go | 20 +- dex2jar/ir/constants.go | 9 +- dex2jar/ir/constraints.go | 19 +- dex2jar/ir/decode.go | 6 + dex2jar/ir/ir.go | 3 + dex2jar/lower/enum_canonical.go | 1294 +++++++++++++++++ dex2jar/lower/lower.go | 210 ++- dex2jar/lower/method.go | 709 +++++++-- dex2jar/lower/references.go | 13 +- dex2jar/lower/stackmap.go | 244 +++- dex2jar/lower/validate.go | 579 ++++++-- dex2jar/lower/wave1_soundness_test.go | 342 +++++ dex2jar/lower/wave2_soundness_test.go | 716 +++++++++ dex2jar/lower/wave3_soundness_test.go | 941 ++++++++++++ dex2jar/lower/webs.go | 292 +++- dex2jar/model/model.go | 18 + dex2jar/r8_init.go | 868 +++++++++++ dex2jar/r8_init_test.go | 538 +++++++ dex2jar/roundtrip_gate_test.go | 4 +- internal/dexparser/annotations.go | 12 + internal/dexparser/parser.go | 33 +- internal/dexparser/parser_recover_test.go | 87 ++ internal/filesys/t23_archive.go | 43 +- internal/filesys/zip_fs.go | 32 +- tools/requiredci/main.go | 12 +- 42 files changed, 7347 insertions(+), 454 deletions(-) create mode 100644 classparser/jarwar/casefold_recover_test.go create mode 100644 classparser/stub_method_name_test.go create mode 100644 dex2jar/lower/enum_canonical.go create mode 100644 dex2jar/lower/wave1_soundness_test.go create mode 100644 dex2jar/lower/wave2_soundness_test.go create mode 100644 dex2jar/lower/wave3_soundness_test.go create mode 100644 dex2jar/r8_init.go create mode 100644 dex2jar/r8_init_test.go create mode 100644 internal/dexparser/parser_recover_test.go diff --git a/classparser/classfilebuilder/code.go b/classparser/classfilebuilder/code.go index cd137231..4c687fd6 100644 --- a/classparser/classfilebuilder/code.go +++ b/classparser/classfilebuilder/code.go @@ -104,6 +104,7 @@ type stackFrameEntry struct { type Code struct { pool *ConstantPool nodes []codeNode + insnCount int nextLabel int handlers []exceptionHandler lines []lineNumber @@ -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...) @@ -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 @@ -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. @@ -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. @@ -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 @@ -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. @@ -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. @@ -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. @@ -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. @@ -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. @@ -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 @@ -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 @@ -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 @@ -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; diff --git a/classparser/decompiler/core/branch_array_inline_test.go b/classparser/decompiler/core/branch_array_inline_test.go index 9d7a9347..15c79c4c 100644 --- a/classparser/decompiler/core/branch_array_inline_test.go +++ b/classparser/decompiler/core/branch_array_inline_test.go @@ -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) { diff --git a/classparser/decompiler/core/guarded_call_inline.go b/classparser/decompiler/core/guarded_call_inline.go index 985b8d6c..84d0306f 100644 --- a/classparser/decompiler/core/guarded_call_inline.go +++ b/classparser/decompiler/core/guarded_call_inline.go @@ -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. diff --git a/classparser/decompiler/rewriter/rewrite_var.go b/classparser/decompiler/rewriter/rewrite_var.go index 666e5e18..56801562 100644 --- a/classparser/decompiler/rewriter/rewrite_var.go +++ b/classparser/decompiler/rewriter/rewrite_var.go @@ -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 diff --git a/classparser/decompiler/rewriter/source_assignment_forward_test.go b/classparser/decompiler/rewriter/source_assignment_forward_test.go index d6ea1a34..641ef6c0 100644 --- a/classparser/decompiler/rewriter/source_assignment_forward_test.go +++ b/classparser/decompiler/rewriter/source_assignment_forward_test.go @@ -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)) + } + }) } diff --git a/classparser/decompiler/rewriter/try_rewriter.go b/classparser/decompiler/rewriter/try_rewriter.go index c503d184..9495a8c9 100644 --- a/classparser/decompiler/rewriter/try_rewriter.go +++ b/classparser/decompiler/rewriter/try_rewriter.go @@ -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 +} diff --git a/classparser/dumper.go b/classparser/dumper.go index 846818b2..84ad28c1 100644 --- a/classparser/dumper.go +++ b/classparser/dumper.go @@ -12840,10 +12840,11 @@ func (c *ClassObjectDumper) dumpStubMethod(method *MemberInfo, name, descriptor, case "": 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} diff --git a/classparser/jarwar/casefold_recover_test.go b/classparser/jarwar/casefold_recover_test.go new file mode 100644 index 00000000..57940f29 --- /dev/null +++ b/classparser/jarwar/casefold_recover_test.go @@ -0,0 +1,81 @@ +package jarwar + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/yaklang/javajive/classparser/classfilebuilder" +) + +func buildMinimalClassBytes(internalName string) []byte { + b := classfilebuilder.NewClass(internalName, "java/lang/Object", classfilebuilder.ACC_PUBLIC|classfilebuilder.ACC_SUPER) + initM := b.AddMethod(classfilebuilder.ACC_PUBLIC, "", "()V") + code := initM.Code() + ref, _ := b.Pool().Methodref("java/lang/Object", "", "()V") + code.Load(classfilebuilder.RefLocal, 0).CP(classfilebuilder.INVOKESPECIAL, ref).Emit(classfilebuilder.RETURN) + raw, err := b.Bytes() + if err != nil { + panic(err) + } + return raw +} + +func TestCaseFoldAndIllegalFilenameRecovery(t *testing.T) { + archive := t23ZipOrdered(t, []struct { + name string + body []byte + }{ + {"D0/A.class", buildMinimalClassBytes("D0/A")}, + {"D0/a.class", buildMinimalClassBytes("D0/a")}, + {"?/??.class", buildMinimalClassBytes("?/??")}, + }) + src := t23WriteArchive(t, archive, ".jar") + + strictDst := t.TempDir() + if err := AutoDecompile(src, strictDst); err == nil { + t.Fatal("strict AutoDecompile unexpectedly accepted case-fold collision") + } + + recoverDst := t.TempDir() + if _, err := AutoDecompileWithOptions(src, recoverDst, ArchiveOptions{ + RetainUnprovedSource: true, + }); err != nil { + t.Fatalf("best-effort AutoDecompileWithOptions failed: %v", err) + } + + files := t23Files(t, recoverDst) + if len(files) != 3 { + t.Fatalf("expected 3 non-overwriting exported files, got %#v", files) + } + var sawSanitized, sawDisambiguated bool + for _, rel := range files { + if strings.Contains(rel, "_u003f") { + sawSanitized = true + } + if strings.Contains(rel, "__case2/") && strings.EqualFold(filepath.Base(rel), "a.java") { + sawDisambiguated = true + } + body, err := os.ReadFile(filepath.Join(recoverDst, filepath.FromSlash(rel))) + if err != nil || !strings.Contains(string(body), "class") { + t.Fatalf("exported file %s unreadable or missing class source: err=%v body=%q", rel, err, body) + } + } + if !sawSanitized || !sawDisambiguated { + t.Fatalf("expected both sanitized illegal filename and __case2/ file, got %#v", files) + } + + // Structured export under RetainUnprovedSource must also disambiguate instead of failing. + structDst := t.TempDir() + rep, err := AutoDecompileWithOptions(src, structDst, ArchiveOptions{ + Structured: true, + RetainUnprovedSource: true, + }) + if err != nil { + t.Fatalf("structured RetainUnprovedSource failed: %v", err) + } + if len(rep.Entries) != 3 { + t.Fatalf("expected 3 structured entries, got %d (%+v)", len(rep.Entries), rep.Entries) + } +} diff --git a/classparser/jarwar/exports.go b/classparser/jarwar/exports.go index 66c43edb..5304e261 100644 --- a/classparser/jarwar/exports.go +++ b/classparser/jarwar/exports.go @@ -112,6 +112,7 @@ func autoDecompileFlat(from, to string, options ArchiveOptions) error { Work: options.Work, TargetRelease: options.TargetRelease, }) + archiveOptions.AllowCaseFoldCollisions = options.RetainUnprovedSource if err := archiveOptions.Work.CheckContext(options.Context); err != nil { return err } @@ -127,6 +128,7 @@ func autoDecompileFlat(from, to string, options ArchiveOptions) error { _ = zipFS.Close() return utils.Errorf("create archive failed: %v", err) } + jar.bestEffort = options.RetainUnprovedSource defer jar.Close() return jar.DumpToLocalFileSystem(to) case strings.HasSuffix(fromLower, ".class"): diff --git a/classparser/jarwar/jarwar.go b/classparser/jarwar/jarwar.go index 0c451239..e1f95d47 100644 --- a/classparser/jarwar/jarwar.go +++ b/classparser/jarwar/jarwar.go @@ -3,9 +3,12 @@ package jarwar import ( "fmt" "os" + "path" "path/filepath" + "runtime" "strings" "sync" + "sync/atomic" "github.com/yaklang/javajive/classparser" "github.com/yaklang/javajive/internal/filesys" @@ -20,6 +23,9 @@ type JarWar struct { ManifestMF JarManifest fs *javaclassparser.JarFS + bestEffort bool + writtenFold map[string]int + // 存储反编译失败的文件列表 failedDecompiledFiles map[string]struct{} failedFilesLock sync.RWMutex @@ -91,6 +97,13 @@ func (j *JarWar) GetStructDump() string { return filesys.DumpTreeView(j.fs) } +type dumpTask struct { + visiblePath string + entryPath string + outPath string + isClass bool +} + func (j *JarWar) DumpToLocalFileSystem(dir string) error { if utils.GetFirstExistedPath(dir) == "" { log.Info("output directory not existed, create it, os.MkdirAll") @@ -100,13 +113,89 @@ func (j *JarWar) DumpToLocalFileSystem(dir string) error { } } - if err := j.dumpDirectory(dir, "."); err != nil { + var tasks []dumpTask + if err := j.collectDumpTasks(dir, ".", &tasks); err != nil { return fmt.Errorf("archive file system dump failed: %w", err) } + if len(tasks) == 0 { + return nil + } + + workers := runtime.GOMAXPROCS(0) + if workers > 8 { + workers = 8 + } + if workers < 1 { + workers = 1 + } + if len(tasks) <= 1 || workers == 1 { + for _, task := range tasks { + if err := j.executeDumpTask(dir, task); err != nil { + return fmt.Errorf("archive file system dump failed: %w", err) + } + } + return nil + } + if workers > len(tasks) { + workers = len(tasks) + } + + var nextIdx atomic.Int64 + var failed atomic.Bool + var errMu sync.Mutex + var firstErr error + var wg sync.WaitGroup + wg.Add(workers) + for w := 0; w < workers; w++ { + go func() { + defer wg.Done() + for { + if failed.Load() { + return + } + idx := int(nextIdx.Add(1) - 1) + if idx >= len(tasks) { + return + } + if err := j.executeDumpTask(dir, tasks[idx]); err != nil { + errMu.Lock() + if firstErr == nil { + firstErr = err + } + errMu.Unlock() + failed.Store(true) + return + } + } + }() + } + wg.Wait() + if firstErr != nil { + return fmt.Errorf("archive file system dump failed: %w", firstErr) + } return nil } -func (j *JarWar) dumpDirectory(root, directory string) error { +func (j *JarWar) recordFailedFile(visiblePath string) { + j.failedFilesLock.Lock() + if j.failedDecompiledFiles == nil { + j.failedDecompiledFiles = make(map[string]struct{}) + } + j.failedDecompiledFiles[visiblePath] = struct{}{} + j.failedFilesLock.Unlock() +} + +func (j *JarWar) bestEffortOutputPath(rel string) string { + sanitized := sanitizeBestEffortPath(rel) + j.failedFilesLock.Lock() + defer j.failedFilesLock.Unlock() + if j.writtenFold == nil { + j.writtenFold = make(map[string]int) + } + return disambiguateCaseFoldPath(sanitized, j.writtenFold) +} + +func (j *JarWar) collectDumpTasks(root, directory string, tasks *[]dumpTask) error { entries, err := j.fs.ReadDir(directory) if err != nil { return fmt.Errorf("read archive directory %q: %w", directory, err) @@ -115,64 +204,115 @@ func (j *JarWar) dumpDirectory(root, directory string) error { entryPath := filepath.ToSlash(filepath.Join(directory, entry.Name())) info, statErr := j.fs.Stat(entryPath) if statErr != nil { + if j.bestEffort { + log.Warnf("stat archive entry %q failed: %v", entryPath, statErr) + j.recordFailedFile(entryPath) + continue + } return fmt.Errorf("stat archive entry %q: %w", entryPath, statErr) } if info.IsDir() { - target, joinErr := SafeJoin(root, entryPath) + outDir := entryPath + if j.bestEffort { + outDir = sanitizeBestEffortPath(entryPath) + } + target, joinErr := SafeJoin(root, outDir) if joinErr != nil { + if j.bestEffort { + log.Warnf("resolve archive directory %q failed: %v", entryPath, joinErr) + j.recordFailedFile(entryPath) + continue + } return fmt.Errorf("resolve archive directory %q: %w", entryPath, joinErr) } if mkdirErr := os.MkdirAll(target, 0o755); mkdirErr != nil { + if j.bestEffort { + log.Warnf("create archive directory %q failed: %v", entryPath, mkdirErr) + j.recordFailedFile(entryPath) + continue + } return fmt.Errorf("create archive directory %q: %w", entryPath, mkdirErr) } - if walkErr := j.dumpDirectory(root, entryPath); walkErr != nil { + if walkErr := j.collectDumpTasks(root, entryPath, tasks); walkErr != nil { return walkErr } continue } - if err := j.dumpFile(root, entryPath); err != nil { - return err + + actualPath := entryPath + if filepath.Ext(actualPath) == ".java" { + if _, err := j.fs.ReadRawFile(actualPath); err != nil { + actualPath = strings.TrimSuffix(actualPath, ".java") + ".class" + } + } + isClass := filepath.Ext(actualPath) == ".class" + outPath := entryPath + if isClass { + outPath = strings.TrimSuffix(actualPath, ".class") + ".java" + } + if j.bestEffort { + outPath = j.bestEffortOutputPath(outPath) } + *tasks = append(*tasks, dumpTask{ + visiblePath: entryPath, + entryPath: actualPath, + outPath: outPath, + isClass: isClass, + }) } return nil } -func (j *JarWar) dumpFile(root, visiblePath string) error { - entryPath := visiblePath - if filepath.Ext(entryPath) == ".java" { - if _, err := j.fs.ReadRawFile(entryPath); err != nil { - entryPath = strings.TrimSuffix(entryPath, ".java") + ".class" - } - } - - if filepath.Ext(entryPath) == ".class" { - originalRaw, err := j.fs.ReadRawFile(entryPath) +func (j *JarWar) executeDumpTask(root string, task dumpTask) error { + if task.isClass { + originalRaw, err := j.fs.ReadRawFile(task.entryPath) if err != nil { - return fmt.Errorf("read archive entry %q: %w", entryPath, err) + if j.bestEffort { + log.Warnf("read archive entry %q failed: %v", task.entryPath, err) + j.recordFailedFile(task.visiblePath) + return nil + } + return fmt.Errorf("read archive entry %q: %w", task.entryPath, err) } - decompiled, err := j.fs.ReadFile(entryPath) + decompiled, err := j.fs.ReadFile(task.entryPath) if err != nil { - j.failedFilesLock.Lock() - j.failedDecompiledFiles[visiblePath] = struct{}{} - j.failedFilesLock.Unlock() - return fmt.Errorf("decompile archive entry %q: %w", entryPath, err) + j.recordFailedFile(task.visiblePath) + if j.bestEffort { + log.Warnf("decompile archive entry %q failed: %v", task.entryPath, err) + return nil + } + return fmt.Errorf("decompile archive entry %q: %w", task.entryPath, err) } - javaName := strings.TrimSuffix(entryPath, ".class") + ".java" - if err := writeFlatFile(root, javaName, decompiled); err != nil { - return fmt.Errorf("write archive entry %q: %w", entryPath, err) + if err := writeFlatFile(root, task.outPath, decompiled); err != nil { + if j.bestEffort { + log.Warnf("write archive entry %q failed: %v", task.entryPath, err) + j.recordFailedFile(task.visiblePath) + return nil + } + return fmt.Errorf("write archive entry %q: %w", task.entryPath, err) } lines := strings.Count(string(decompiled), "\n") + 1 log.Infof("Decompiled [%v] - Original size: %d bytes, Decompiled size: %d bytes, Lines of code: %d", - visiblePath, len(originalRaw), len(decompiled), lines) + task.visiblePath, len(originalRaw), len(decompiled), lines) return nil } - raw, err := j.fs.ReadRawFile(entryPath) + raw, err := j.fs.ReadRawFile(task.entryPath) if err != nil { - return fmt.Errorf("read archive entry %q: %w", entryPath, err) + if j.bestEffort { + log.Warnf("read archive entry %q failed: %v", task.entryPath, err) + j.recordFailedFile(task.visiblePath) + return nil + } + return fmt.Errorf("read archive entry %q: %w", task.entryPath, err) } - if err := writeFlatFile(root, visiblePath, raw); err != nil { - return fmt.Errorf("write archive entry %q: %w", entryPath, err) + if err := writeFlatFile(root, task.outPath, raw); err != nil { + if j.bestEffort { + log.Warnf("write archive entry %q failed: %v", task.entryPath, err) + j.recordFailedFile(task.visiblePath) + return nil + } + return fmt.Errorf("write archive entry %q: %w", task.entryPath, err) } return nil } @@ -191,3 +331,94 @@ func writeFlatFile(root, name string, data []byte) error { } return os.WriteFile(target, data, 0o644) } + +func sanitizeBestEffortPath(rel string) string { + slash := strings.ReplaceAll(filepath.ToSlash(rel), "\\", "/") + slash = strings.TrimPrefix(slash, "./") + parts := strings.Split(slash, "/") + out := make([]string, 0, len(parts)) + for _, seg := range parts { + if seg == "" || seg == "." || seg == ".." { + out = append(out, seg) + continue + } + out = append(out, sanitizeBestEffortSegment(seg)) + } + return strings.Join(out, "/") +} + +func sanitizeBestEffortSegment(seg string) string { + var b strings.Builder + b.Grow(len(seg)) + for _, r := range seg { + if r < 0x20 || strings.ContainsRune(`<>:"|?*`, r) { + fmt.Fprintf(&b, "_u%04x", r) + continue + } + b.WriteRune(r) + } + s := b.String() + if len(s) > 0 && (s[len(s)-1] == '.' || s[len(s)-1] == ' ') { + end := len(s) + for end > 0 && (s[end-1] == '.' || s[end-1] == ' ') { + end-- + } + var tb strings.Builder + tb.WriteString(s[:end]) + for i := end; i < len(s); i++ { + fmt.Fprintf(&tb, "_u%04x", s[i]) + } + s = tb.String() + } + if s == "" || s == "." || s == ".." { + return "_" + } + stem := s + if dot := strings.IndexByte(s, '.'); dot >= 0 { + stem = s[:dot] + } + if isWindowsReservedDeviceName(stem) { + if dot := strings.IndexByte(s, '.'); dot >= 0 { + s = stem + "_" + s[dot:] + } else { + s += "_" + } + } + return s +} + +func isWindowsReservedDeviceName(stem string) bool { + if stem == "" { + return false + } + upper := strings.ToUpper(stem) + switch upper { + case "CON", "PRN", "AUX", "NUL": + return true + } + if len(upper) == 4 && (strings.HasPrefix(upper, "COM") || strings.HasPrefix(upper, "LPT")) { + d := upper[3] + return d >= '1' && d <= '9' + } + return false +} + +func disambiguateCaseFoldPath(rel string, used map[string]int) string { + if used == nil { + return rel + } + lower := strings.ToLower(rel) + if used[lower] == 0 { + used[lower] = 1 + return rel + } + dir, base := path.Split(rel) + for n := 2; ; n++ { + candidate := fmt.Sprintf("%s__case%d/%s", dir, n, base) + candLower := strings.ToLower(candidate) + if used[candLower] == 0 { + used[candLower] = 1 + return candidate + } + } +} diff --git a/classparser/jarwar/structured.go b/classparser/jarwar/structured.go index 90ae71bc..5c75d836 100644 --- a/classparser/jarwar/structured.go +++ b/classparser/jarwar/structured.go @@ -33,6 +33,7 @@ func decompileArchiveStructured(from, to string, options ArchiveOptions) (Archiv Work: options.Work, TargetRelease: options.TargetRelease, }) + archiveOptions.AllowCaseFoldCollisions = options.RetainUnprovedSource zipFS, err := filesys.NewZipFSFromLocalWithOptions(from, filesys.WithArchiveOptions(archiveOptions)) if err != nil { return ArchiveReport{}, fmt.Errorf("open archive %q: %w", from, err) @@ -47,7 +48,11 @@ func decompileArchiveStructured(from, to string, options ArchiveOptions) (Archiv } var report ArchiveReport - exportErr := exportStructuredArchive(to, zipFS, decompiler, "", 0, options.MaxAnalysisUpdates, options.RetainUnprovedSource, &report) + var usedFold map[string]int + if options.RetainUnprovedSource { + usedFold = make(map[string]int) + } + exportErr := exportStructuredArchive(to, zipFS, decompiler, "", 0, options.MaxAnalysisUpdates, options.RetainUnprovedSource, usedFold, &report) closeErr := decompilerOwner.Close() if exportErr != nil { return ArchiveReport{}, exportErr @@ -96,11 +101,11 @@ func prepareStructuredRoot(root string) error { return nil } -func exportStructuredArchive(root string, zipFS *filesys.ZipFS, decompiler *javaclassparser.JarFS, archivePath string, depth, maxAnalysisUpdates int, retainUnproved bool, report *ArchiveReport) error { - return walkStructuredDirectory(root, zipFS, decompiler, ".", archivePath, depth, maxAnalysisUpdates, retainUnproved, report) +func exportStructuredArchive(root string, zipFS *filesys.ZipFS, decompiler *javaclassparser.JarFS, archivePath string, depth, maxAnalysisUpdates int, retainUnproved bool, usedFold map[string]int, report *ArchiveReport) error { + return walkStructuredDirectory(root, zipFS, decompiler, ".", archivePath, depth, maxAnalysisUpdates, retainUnproved, usedFold, report) } -func walkStructuredDirectory(root string, zipFS *filesys.ZipFS, decompiler *javaclassparser.JarFS, directory, archivePath string, depth, maxAnalysisUpdates int, retainUnproved bool, report *ArchiveReport) error { +func walkStructuredDirectory(root string, zipFS *filesys.ZipFS, decompiler *javaclassparser.JarFS, directory, archivePath string, depth, maxAnalysisUpdates int, retainUnproved bool, usedFold map[string]int, report *ArchiveReport) error { entries, err := decompiler.ReadDir(directory) if err != nil { return fmt.Errorf("read archive directory %q: %w", provenancePath(archivePath, cleanArchivePath(directory)), err) @@ -111,32 +116,34 @@ func walkStructuredDirectory(root string, zipFS *filesys.ZipFS, decompiler *java entryPath := path.Join(directory, javaclassparser.EntryOriginalName(entry)) entryPath = cleanArchivePath(entryPath) if isArchiveName(entryPath) { - if err := exportNestedArchive(root, zipFS, entryPath, archivePath, depth+1, maxAnalysisUpdates, retainUnproved, report); err != nil { + if err := exportNestedArchive(root, zipFS, entryPath, archivePath, depth+1, maxAnalysisUpdates, retainUnproved, usedFold, report); err != nil { return err } continue } if entry.IsDir() { - if err := walkStructuredDirectory(root, zipFS, decompiler, entryPath, archivePath, depth, maxAnalysisUpdates, retainUnproved, report); err != nil { + if err := walkStructuredDirectory(root, zipFS, decompiler, entryPath, archivePath, depth, maxAnalysisUpdates, retainUnproved, usedFold, report); err != nil { return err } continue } - if err := exportStructuredFile(root, decompiler, entryPath, archivePath, report); err != nil { + if err := exportStructuredFile(root, decompiler, entryPath, archivePath, retainUnproved, usedFold, report); err != nil { return err } } return nil } -func exportNestedArchive(root string, parentZip *filesys.ZipFS, entryPath, parentArchive string, depth, maxAnalysisUpdates int, retainUnproved bool, report *ArchiveReport) error { +func exportNestedArchive(root string, parentZip *filesys.ZipFS, entryPath, parentArchive string, depth, maxAnalysisUpdates int, retainUnproved bool, usedFold map[string]int, report *ArchiveReport) error { raw, err := parentZip.ReadFile(entryPath) if err != nil { return fmt.Errorf("read nested archive %q: %w", provenancePath(parentArchive, entryPath), err) } provenance := provenancePath(parentArchive, entryPath) outputPath := path.Join(structuredArchivesRoot, provenance) - if err := reserveStructuredOutput(report, outputPath); err != nil { + if retainUnproved { + outputPath = disambiguateCaseFoldPath(sanitizeBestEffortPath(outputPath), usedFold) + } else if err := reserveStructuredOutput(report, outputPath); err != nil { return err } if err := writeStructuredFile(root, outputPath, raw); err != nil { @@ -158,13 +165,13 @@ func exportNestedArchive(root string, parentZip *filesys.ZipFS, entryPath, paren nestedDecompiler := javaclassparser.NewJarFS(nestedZip) nestedDecompiler.SetAnalysisBudget(maxAnalysisUpdates) nestedDecompiler.SetRetainUnprovedSource(retainUnproved) - if err := exportStructuredArchive(root, nestedZip, nestedDecompiler, provenance, depth, maxAnalysisUpdates, retainUnproved, report); err != nil { + if err := exportStructuredArchive(root, nestedZip, nestedDecompiler, provenance, depth, maxAnalysisUpdates, retainUnproved, usedFold, report); err != nil { return err } return nil } -func exportStructuredFile(root string, decompiler *javaclassparser.JarFS, entryPath, archivePath string, report *ArchiveReport) error { +func exportStructuredFile(root string, decompiler *javaclassparser.JarFS, entryPath, archivePath string, retainUnproved bool, usedFold map[string]int, report *ArchiveReport) error { outcome, err := decompiler.ReadClassOutcome(entryPath) if err != nil { return fmt.Errorf("read archive entry %q: %w", provenancePath(archivePath, entryPath), err) @@ -188,7 +195,9 @@ func exportStructuredFile(root string, decompiler *javaclassparser.JarFS, entryP outputEntry = provenancePath(archivePath, outputEntry) } outputPath := path.Join(outputRoot, outputEntry) - if err := reserveStructuredOutput(report, outputPath); err != nil { + if retainUnproved { + outputPath = disambiguateCaseFoldPath(sanitizeBestEffortPath(outputPath), usedFold) + } else if err := reserveStructuredOutput(report, outputPath); err != nil { return err } if err := writeStructuredFile(root, outputPath, data); err != nil { diff --git a/classparser/stub_method_name_test.go b/classparser/stub_method_name_test.go new file mode 100644 index 00000000..ba071e36 --- /dev/null +++ b/classparser/stub_method_name_test.go @@ -0,0 +1,34 @@ +package javaclassparser + +import ( + "bytes" + "os" + "strings" + "testing" +) + +func TestStubMethodNameSanitizedAsSafeIdentifier(t *testing.T) { + seed, err := os.ReadFile("testdata/regression/StubGenericSigSeed.class") + if err != nil { + t.Fatalf("read StubGenericSigSeed.class: %v", err) + } + target := []byte("\x01\x00\x07consume") + if !bytes.Contains(seed, target) { + t.Fatalf("seed class missing expected Utf8 entry %q", target) + } + mutated := bytes.ReplaceAll(seed, target, []byte("\x01\x00\x07foo-bar")) + + res, err := DecompileWithOptions(mutated, DecompileOptions{RetainUnprovedSource: true}) + if err != nil { + t.Fatalf("DecompileWithOptions failed: %v", err) + } + if len(res.StubMethods) == 0 { + t.Fatalf("expected dumpStubMethod to record stubbed method, got StubMethods=%v\n%s", res.StubMethods, res.Source) + } + if strings.Contains(res.Source, "foo-bar(") { + t.Fatalf("unsanitized stub identifier `foo-bar(` leaked into Java source:\n%s", res.Source) + } + if !strings.Contains(res.Source, "foo_bar(") { + t.Fatalf("expected sanitized Java identifier `foo_bar(`, got:\n%s", res.Source) + } +} diff --git a/classparser/t23_archive.go b/classparser/t23_archive.go index 3649fab0..062ce451 100644 --- a/classparser/t23_archive.go +++ b/classparser/t23_archive.go @@ -32,13 +32,14 @@ func ArchiveOptionsFrom(opts DecompileOptions) filesys.ArchiveOptions { // archiveFSState is the request-scoped archive policy copied onto ExpandedZipFS/JarFS. type archiveFSState struct { - budget *filesys.ArchiveBudget - limits filesys.ArchiveLimits - ctx context.Context - depth int - targetRelease int - safe bool - active bool + budget *filesys.ArchiveBudget + limits filesys.ArchiveLimits + ctx context.Context + depth int + targetRelease int + safe bool + allowCaseFoldCollisions bool + active bool } func archiveStateFromZipFS(z *filesys.ZipFS) *archiveFSState { @@ -46,13 +47,14 @@ func archiveStateFromZipFS(z *filesys.ZipFS) *archiveFSState { return nil } return &archiveFSState{ - budget: z.ArchiveBudget(), - limits: z.ArchiveLimits(), - ctx: z.ArchiveContext(), - depth: z.ArchiveDepth(), - targetRelease: z.TargetRelease(), - safe: z.SafeArchive() || z.ArchiveActive(), - active: true, + budget: z.ArchiveBudget(), + limits: z.ArchiveLimits(), + ctx: z.ArchiveContext(), + depth: z.ArchiveDepth(), + targetRelease: z.TargetRelease(), + safe: z.SafeArchive() || z.ArchiveActive(), + allowCaseFoldCollisions: z.AllowCaseFoldCollisions(), + active: true, } } @@ -89,6 +91,9 @@ func (s *archiveFSState) zipOptions(depth int) []filesys.ZipFSOption { if s.ctx != nil { opts = append(opts, filesys.WithArchiveContext(s.ctx)) } + if s.allowCaseFoldCollisions { + opts = append(opts, filesys.WithAllowCaseFoldCollisions(true)) + } return opts } @@ -111,6 +116,7 @@ func mergeArchiveState(base *archiveFSState, opts filesys.ArchiveOptions) *archi } s.targetRelease = opts.TargetRelease s.safe = true + s.allowCaseFoldCollisions = s.allowCaseFoldCollisions || opts.AllowCaseFoldCollisions s.active = true if s.budget == nil && opts.Limits != (filesys.ArchiveLimits{}) { s.budget = filesys.NewArchiveBudget(opts.Context, s.limits) diff --git a/dex2jar/dex2jar.go b/dex2jar/dex2jar.go index 7a3d92f4..33445b40 100644 --- a/dex2jar/dex2jar.go +++ b/dex2jar/dex2jar.go @@ -251,7 +251,7 @@ func DexToJarWithOptions(data []byte, options ConvertOptions) (jar []byte, detai if policy != FailureStrict && policy != FailureStubUnsupportedMethods && policy != FailureRecover { return nil, detailed, fmt.Errorf("dex2jar: unknown failure policy %q", policy) } - app, _, err := parseApplication(data, options.Input) + app, _, err := parseApplicationWithPolicy(data, options.Input, policy) if err != nil { appendConversionDiagnostic(&detailed, diagnosticFromError(err, "failed", "")) return nil, detailed, err @@ -359,8 +359,13 @@ func inputOptions(options Options) input.Options { } } -func parseApplication(data []byte, options Options) (*model.Application, ContainerKind, error) { - app, kind, err := input.ParseApplicationWithOptions(data, "", inputOptions(options)) +func parseApplicationWithPolicy(data []byte, options Options, policy FailurePolicy) (*model.Application, ContainerKind, error) { + inOpts := inputOptions(options) + if policy == FailureRecover { + inOpts.TolerateSignatureMismatch = true + inOpts.TolerateOrphanAnnotationDefault = true + } + app, kind, err := input.ParseApplicationWithOptions(data, "", inOpts) if err != nil { return nil, ContainerKind(kind), err } @@ -388,6 +393,10 @@ func applicationToJarWithPolicy(app *model.Application, policy FailurePolicy) ([ lowerPolicy = lower.StubUnsupportedMethods case FailureRecover: lowerPolicy = lower.Recover + for _, diag := range synthesizeR8InlinedConstructors(app, hierarchy) { + appendConversionDiagnostic(&detailed, diag) + detailed.Summary.Warnings++ + } } for _, file := range app.Files { if file == nil { @@ -398,6 +407,17 @@ func applicationToJarWithPolicy(app *model.Application, policy FailurePolicy) ([ appendConversionDiagnostic(&detailed, diagnosticFromError(err, "failed", "")) return nil, detailed, err } + for _, w := range file.ParseWarnings { + detailed.Summary.Warnings++ + if w.Action == "drop_attribute" { + detailed.DroppedAttributes++ + } + appendConversionDiagnostic(&detailed, ConversionDiagnostic{ + Entry: w.Entry, Class: w.Class, Category: "recovery", Action: w.Action, + Feature: w.Feature, Code: w.Code, Kind: "structural", + Scope: "dex", Stage: "parse_dex", Severity: "warning", Message: w.Message, + }) + } for classIndex := range file.Classes { class := &file.Classes[classIndex] detailed.AttemptedClasses++ diff --git a/dex2jar/input/input.go b/dex2jar/input/input.go index 5a555d75..14fa37ee 100644 --- a/dex2jar/input/input.go +++ b/dex2jar/input/input.go @@ -36,6 +36,12 @@ type Options struct { // MaxNestedAPKs bounds the number of nested APK entries in a split bundle. // Non-positive values use DefaultMaxNestedAPKs. MaxNestedAPKs int + // TolerateSignatureMismatch accepts a DEX whose Adler-32 checksum matches + // even if its SHA-1 signature was left stale by anti-tamper or repackers. + TolerateSignatureMismatch bool + // TolerateOrphanAnnotationDefault drops AnnotationDefault entries whose + // annotation method was stripped by ProGuard/R8 shrinking. + TolerateOrphanAnnotationDefault bool } func ParseDEX(data []byte, entry string) (*model.File, error) { @@ -47,7 +53,10 @@ func ParseDEXWithOptions(data []byte, entry string, options Options) (*model.Fil if int64(len(data)) > limit { return nil, report.New(entry, "", "", 0, "input", fmt.Errorf("DEX size %d exceeds limit %d", len(data), limit)) } - return dexparser.Parse(data, entry) + return dexparser.ParseWithOptions(data, entry, dexparser.ParseOptions{ + TolerateSignatureMismatch: options.TolerateSignatureMismatch, + TolerateOrphanAnnotationDefault: options.TolerateOrphanAnnotationDefault, + }) } func ParseAPK(data []byte) (*model.Application, error) { diff --git a/dex2jar/ir/build.go b/dex2jar/ir/build.go index b021912d..865148e3 100644 --- a/dex2jar/ir/build.go +++ b/dex2jar/ir/build.go @@ -274,11 +274,28 @@ func validateInstructions(method *Method, file *model.File) error { } func validateInvokeShape(method *Method, instruction *Instruction, proto model.Proto, wordCount, firstParamPos int) error { - if len(instruction.Regs) != wordCount { - return diagnostic(method.Context, instruction, "", fmt.Errorf("invoke has %d register words; descriptor requires %d", len(instruction.Regs), wordCount)) + if instruction.ExtraNullArgs < 0 { + return diagnostic(method.Context, instruction, "", fmt.Errorf("negative extra null arguments %d", instruction.ExtraNullArgs)) } - if wordCount > int(method.Code.OutsSize) { - return diagnostic(method.Context, instruction, "", fmt.Errorf("invoke requires %d outgoing register words; outs_size is %d", wordCount, method.Code.OutsSize)) + if instruction.ExtraNullArgs > 0 { + if !isInvoke(instruction.Opcode) { + return diagnostic(method.Context, instruction, "", fmt.Errorf("extra null arguments are only valid on invoke instructions")) + } + if len(proto.Parameters) < instruction.ExtraNullArgs { + return diagnostic(method.Context, instruction, "", fmt.Errorf("invoke extra null arguments %d exceed %d parameters", instruction.ExtraNullArgs, len(proto.Parameters))) + } + for _, p := range proto.Parameters[len(proto.Parameters)-instruction.ExtraNullArgs:] { + if p != "Ljava/lang/Void;" { + return diagnostic(method.Context, instruction, "", fmt.Errorf("invoke extra null arguments require trailing Ljava/lang/Void; parameters, got %q", p)) + } + } + } + expectedRegWords := wordCount - instruction.ExtraNullArgs + if len(instruction.Regs) != expectedRegWords { + return diagnostic(method.Context, instruction, "", fmt.Errorf("invoke has %d register words; descriptor requires %d", len(instruction.Regs), expectedRegWords)) + } + if expectedRegWords > int(method.Code.OutsSize) { + return diagnostic(method.Context, instruction, "", fmt.Errorf("invoke requires %d outgoing register words; outs_size is %d", expectedRegWords, method.Code.OutsSize)) } if _, err := DescriptorCategory(proto.ReturnType); err != nil { return diagnostic(method.Context, instruction, "", err) diff --git a/dex2jar/ir/categories.go b/dex2jar/ir/categories.go index e2d388e9..a2236db7 100644 --- a/dex2jar/ir/categories.go +++ b/dex2jar/ir/categories.go @@ -30,6 +30,11 @@ func (m *Method) EffectsAt(index int) (uses, defs []uint16) { return instructionEffects(instruction) } +// InstructionEffects returns the read and written registers of one decoded instruction. +func InstructionEffects(instruction Instruction) (uses, defs []uint16) { + return instructionEffects(instruction) +} + // instructionEffects is the per-opcode use/define table shared by liveness, // definite-assignment and category analysis. A category-2 definition also // defines the following register, which is how the pair stays assigned. @@ -214,10 +219,10 @@ func walkBlock(method *Method, file *model.File, allocations []Allocation, block } return nil, diagnostic(method.Context, instruction, "", fmt.Errorf("v%d: %w", register, err)) } - if state[register].Kind == Null { - // Keep zero/null constants open during forward propagation so - // refineConstants can distinguish single-type uses from a - // polymorphic zero shared across int/float/reference reads. + if state[register].Kind == Null || (state[register].Kind == Reference && state[register].Descriptor == "") { + // Keep zero/null constants and untyped-descriptor reference values open + // across use constraints so refineConstants stays accurate and a non-array + // null use does not stamp a concrete descriptor before an array/ref join. continue } if state[register].Kind.isUntyped() && merged.Kind != state[register].Kind { diff --git a/dex2jar/ir/cfg.go b/dex2jar/ir/cfg.go index 5edf96a5..ebb9ddcd 100644 --- a/dex2jar/ir/cfg.go +++ b/dex2jar/ir/cfg.go @@ -7,9 +7,10 @@ import ( "github.com/yaklang/javajive/dex2jar/model" ) -// mayThrow reports whether an instruction can transfer control to an exception -// handler. Moves, constants, comparisons, branches and returns cannot. -func mayThrow(opcode byte) bool { +// MayThrow reports whether a DEX opcode can transfer control to an exception +// handler. Moves, numeric/null constants, comparisons, branches, switches, +// returns, unary casts/negations, and non-div/rem integer/float binary ops cannot. +func MayThrow(opcode byte) bool { switch { case opcode == 0x00: return false @@ -17,11 +18,24 @@ func mayThrow(opcode byte) bool { return false case opcode >= 0x28 && opcode <= 0x3d: return false + case opcode >= 0x7b && opcode <= 0x8f: + return false + case opcode >= 0x90 && opcode <= 0xe2: + switch opcode { + case 0x93, 0x94, 0x9e, 0x9f, 0xb3, 0xb4, 0xbe, 0xbf, 0xd3, 0xd4, 0xdb, 0xdc: + return true + default: + return false + } default: return true } } +func mayThrow(opcode byte) bool { + return MayThrow(opcode) +} + func isGoto(opcode byte) bool { return opcode >= 0x28 && opcode <= 0x2a } func isIf(opcode byte) bool { return opcode >= 0x32 && opcode <= 0x3d } func isSwitch(opcode byte) bool { diff --git a/dex2jar/ir/constants.go b/dex2jar/ir/constants.go index 4631997d..9529867d 100644 --- a/dex2jar/ir/constants.go +++ b/dex2jar/ir/constants.go @@ -262,9 +262,14 @@ func resolveConstant(category, demand Category) (Category, error) { switch category.Kind { case Null: switch demand.Kind { - case Int, Float, Reference: - // The zero constant is 32 bits and fits all three readings. + case Int, Float: + // The zero constant is 32 bits and fits int, float and reference readings. return demand, nil + case Reference: + // Keep reference null constants untyped by class/interface descriptor so + // later control-flow joins (e.g., merging null with an array) do not + // inherit an unrelated non-array reference descriptor. + return Category{Kind: Reference}, nil case Bits32: // A move chain left the interpretation open; the raw zero bits are // an int constant. diff --git a/dex2jar/ir/constraints.go b/dex2jar/ir/constraints.go index a9ed87b0..6ea80478 100644 --- a/dex2jar/ir/constraints.go +++ b/dex2jar/ir/constraints.go @@ -187,9 +187,18 @@ func instructionConstraints(method *Method, file *model.File, index int, current } case instruction.Opcode >= 0x44 && instruction.Opcode <= 0x51: // The element type is not encoded in the instruction: DEX tracks it in - // the array register's type, which the category analysis carries. + // the array register's type, which the category analysis carries. A known + // null reference is also legal under the JVM verifier (it throws NPE at + // runtime) and produces Null/default-width values. array := current[instruction.Regs[1]] - if len(array.Descriptor) < 2 || array.Descriptor[0] != '[' { + isNullArray := array.Kind == Null || (array.Kind == Reference && array.Descriptor == "") + component := "" + arrCategory := Category{Kind: Reference, Descriptor: array.Descriptor} + if len(array.Descriptor) >= 2 && array.Descriptor[0] == '[' { + component = array.Descriptor[1:] + } else if isNullArray { + arrCategory = refCategory + } else { if !final { // During the category fixpoint a predecessor entry may not be // resolved yet. Leave the register untouched: merging an empty @@ -199,9 +208,11 @@ func instructionConstraints(method *Method, file *model.File, index int, current } return nil, nil, fmt.Errorf("array register v%d has no array type", instruction.Regs[1]) } - component := array.Descriptor[1:] value := arrayElementCategory(instruction.Opcode, component) - use(instruction.Regs[1], Category{Kind: Reference, Descriptor: array.Descriptor}) + if isNullArray && instruction.Opcode == 0x46 { + value = Category{Kind: Null} + } + use(instruction.Regs[1], arrCategory) use(instruction.Regs[2], intCategory) if instruction.Opcode <= 0x4a { define(instruction.Regs[0], value) diff --git a/dex2jar/ir/decode.go b/dex2jar/ir/decode.go index 261cc065..8624c50e 100644 --- a/dex2jar/ir/decode.go +++ b/dex2jar/ir/decode.go @@ -176,6 +176,12 @@ func Decode(code *model.Code, ctx Context) ([]Instruction, error) { default: return nil, diagnostic(ctx, &instruction, "", fmt.Errorf("decoder has no implementation for format %s", info.format)) } + if patched, ok := code.PatchedMethods[offset]; ok { + instruction.Index = patched + } + if extra, ok := code.PatchedNullArgs[offset]; ok && extra > 0 { + instruction.ExtraNullArgs = extra + } instructions = append(instructions, instruction) offset += uint32(info.width) } diff --git a/dex2jar/ir/ir.go b/dex2jar/ir/ir.go index a0a59830..d350efef 100644 --- a/dex2jar/ir/ir.go +++ b/dex2jar/ir/ir.go @@ -148,6 +148,9 @@ type Instruction struct { // DataWidth the element width the payload declares. Data []byte DataWidth uint16 + // ExtraNullArgs records trailing null reference arguments appended during + // JVM lowering for R8-synthesized disambiguating forwarding constructors. + ExtraNullArgs int } func (i Instruction) End() uint32 { return i.Offset + uint32(i.Width) } diff --git a/dex2jar/lower/enum_canonical.go b/dex2jar/lower/enum_canonical.go new file mode 100644 index 00000000..1ff240cb --- /dev/null +++ b/dex2jar/lower/enum_canonical.go @@ -0,0 +1,1294 @@ +package lower + +import ( + "sort" + "strings" + + "github.com/yaklang/javajive/classparser/classfilebuilder" + "github.com/yaklang/javajive/dex2jar/ir" + "github.com/yaklang/javajive/dex2jar/model" +) + +const ( + jvmSyntheticBackingFlags = uint16(classfilebuilder.ACC_PRIVATE | classfilebuilder.ACC_STATIC | classfilebuilder.ACC_FINAL | classfilebuilder.ACC_SYNTHETIC) + jvmSyntheticHelperFlags = uint16(classfilebuilder.ACC_PRIVATE | classfilebuilder.ACC_STATIC | classfilebuilder.ACC_SYNTHETIC) + jvmEnumConstantFlags = uint16(0x4019) // public static final enum + jvmEnumFactoryFlags = uint16(classfilebuilder.ACC_PUBLIC | classfilebuilder.ACC_STATIC) + jvmEnumFactoryFinalFlags = uint16(classfilebuilder.ACC_PUBLIC | classfilebuilder.ACC_STATIC | classfilebuilder.ACC_FINAL) +) + +type canonicalClinitPlan struct { + startIdx int + endIdx int + skipSet map[int]bool + backingField string + helperName string + constants []string + entriesField string +} + +type pureConstKind uint8 + +const ( + pureNone pureConstKind = iota + pure32Bits + pure64Bits + pureString + pureClass +) + +type pureConstVal struct { + kind pureConstKind + bits int64 + text string +} + +type canonicalConstArg struct { + paramDesc string + kind pureConstKind + bits int64 + text string +} + +type canonicalEnumConstSpan struct { + startIdx int + allocDesc string + ctorProto model.Proto + args []canonicalConstArg + fieldName string +} + +func enumBackingField(class *model.Class) (string, bool) { + if class == nil { + return "", false + } + wantType := "[" + class.Descriptor + backingName := "" + count := 0 + for i := range class.StaticFields { + sf := &class.StaticFields[i] + if sf.Field.Class != class.Descriptor || sf.Field.Type != wantType { + continue + } + acc, err := fieldAccess(sf.AccessFlags) + if err != nil || acc != jvmSyntheticBackingFlags { + continue + } + if len(fieldAnnotationsOf(class, sf.FieldIndex)) != 0 { + continue + } + backingName = sf.Field.Name + count++ + } + if count != 1 || backingName == "" { + return "", false + } + return backingName, true +} + +func orderedEnumConstantNames(file *model.File, class *model.Class, hierarchy map[string]*model.Class) ([]string, bool) { + if file == nil || class == nil { + return nil, false + } + var names []string + for i := range class.StaticFields { + sf := &class.StaticFields[i] + if sf.AccessFlags&dexEnum == 0 { + continue + } + acc, err := fieldAccess(sf.AccessFlags) + if err != nil || acc != jvmEnumConstantFlags || sf.Field.Type != class.Descriptor || sf.Field.Class != class.Descriptor { + return nil, false + } + names = append(names, sf.Field.Name) + } + if len(names) > 1 { + if ordinals := inferEnumFieldOrdinals(file, class, hierarchy); len(ordinals) == len(names) { + seen := make([]bool, len(names)) + valid := true + for _, name := range names { + ord, ok := ordinals[name] + if !ok || ord < 0 || ord >= len(names) || seen[ord] { + valid = false + break + } + seen[ord] = true + } + if valid { + sort.Slice(names, func(i, j int) bool { + return ordinals[names[i]] < ordinals[names[j]] + }) + } + } + } + return names, true +} + +func isCanonicalEnumClass(class *model.Class) bool { + return class != nil && class.AccessFlags&dexEnum != 0 && class.Superclass == "Ljava/lang/Enum;" +} + +func (l *methodLowerer) tryEmitCanonicalEnumMethod() (bool, error) { + if !isCanonicalEnumClass(l.class) || len(l.method.Code.Tries) != 0 || len(l.method.Blocks) != 1 { + return false, nil + } + access, err := methodAccess(l.encoded.AccessFlags, l.encoded.Method.Name) + if err != nil { + return false, nil + } + proto := l.method.Proto + name := l.encoded.Method.Name + arrDesc := "[" + l.class.Descriptor + + if name == "values" && len(proto.Parameters) == 0 && proto.ReturnType == arrDesc && + (access == jvmEnumFactoryFlags || access == jvmEnumFactoryFinalFlags) { + return l.tryEmitCanonicalEnumValues() + } + if name == "valueOf" && len(proto.Parameters) == 1 && proto.Parameters[0] == "Ljava/lang/String;" && + proto.ReturnType == l.class.Descriptor && (access == jvmEnumFactoryFlags || access == jvmEnumFactoryFinalFlags) { + return l.tryEmitCanonicalEnumValueOf() + } + if len(proto.Parameters) == 0 && proto.ReturnType == arrDesc && + (access == jvmSyntheticHelperFlags || access == jvmSyntheticBackingFlags) { + return l.tryEmitCanonicalEnumValuesHelper() + } + return false, nil +} + +func (l *methodLowerer) tryEmitCanonicalEnumValues() (bool, error) { + backingName, ok := enumBackingField(l.class) + if !ok { + return false, nil + } + arrDesc := "[" + l.class.Descriptor + block := l.method.Blocks[0] + regBacking := make(map[uint16]bool) + regCloned := make(map[uint16]bool) + regCast := make(map[uint16]bool) + clearReg := func(r uint16) { + delete(regBacking, r) + delete(regCloned, r) + delete(regCast, r) + } + sawInvoke, sawCast, sawReturn := false, false, false + for p := 0; p < len(block.Instructions); p++ { + idx := block.Instructions[p] + ins := &l.method.Instructions[idx] + op := ins.Opcode + switch { + case op == 0x00: + continue + case (op >= 0x01 && op <= 0x03) || (op >= 0x07 && op <= 0x09): + dst, src := ins.Regs[0], ins.Regs[1] + b, cl, ca := regBacking[src], regCloned[src], regCast[src] + clearReg(dst) + if b { + regBacking[dst] = true + } + if cl { + regCloned[dst] = true + } + if ca { + regCast[dst] = true + } + case op == 0x62: + if sawInvoke || sawReturn || int(ins.Index) >= len(l.file.Fields) { + return false, nil + } + f := l.file.Fields[ins.Index] + if f.Class != l.class.Descriptor || f.Name != backingName || f.Type != arrDesc { + return false, nil + } + clearReg(ins.Regs[0]) + regBacking[ins.Regs[0]] = true + case op == 0x6e || op == 0x74: + if sawInvoke || sawReturn || len(ins.Regs) != 1 || !regBacking[ins.Regs[0]] || int(ins.Index) >= len(l.file.Methods) { + return false, nil + } + callee := l.file.Methods[ins.Index] + if callee.Name != "clone" || (callee.Class != arrDesc && callee.Class != "Ljava/lang/Object;" && callee.Class != "[Ljava/lang/Object;") || int(callee.ProtoIndex) >= len(l.file.Protos) { + return false, nil + } + calleeProto := l.file.Protos[callee.ProtoIndex] + if len(calleeProto.Parameters) != 0 || calleeProto.ReturnType != "Ljava/lang/Object;" { + return false, nil + } + if p+1 >= len(block.Instructions) { + return false, nil + } + next := &l.method.Instructions[block.Instructions[p+1]] + if next.Opcode != 0x0c { + return false, nil + } + sawInvoke = true + clearReg(next.Regs[0]) + regCloned[next.Regs[0]] = true + p++ + case op == 0x1f: + if !sawInvoke || sawCast || sawReturn || !regCloned[ins.Regs[0]] || int(ins.Index) >= len(l.file.Types) { + return false, nil + } + if l.file.Types[ins.Index].Descriptor != arrDesc { + return false, nil + } + clearReg(ins.Regs[0]) + regCast[ins.Regs[0]] = true + sawCast = true + case op == 0x11: + if p != len(block.Instructions)-1 || !sawInvoke || !sawCast || !regCast[ins.Regs[0]] { + return false, nil + } + sawReturn = true + default: + return false, nil + } + } + if !sawReturn { + return false, nil + } + ownerInternal, err := objectInternalName(l.class.Descriptor) + if err != nil { + return false, methodDiagnostic(l.method.Context, nil, "enum values()", err) + } + fieldRef, err := l.builder.Pool().Fieldref(ownerInternal, backingName, arrDesc) + if err != nil { + return false, methodDiagnostic(l.method.Context, nil, "enum values()", err) + } + cloneRef, err := l.builder.Pool().Methodref(arrDesc, "clone", "()Ljava/lang/Object;") + if err != nil { + return false, methodDiagnostic(l.method.Context, nil, "enum values()", err) + } + castClass, err := l.builder.Pool().Class(arrDesc) + if err != nil { + return false, methodDiagnostic(l.method.Context, nil, "enum values()", err) + } + l.code.CP(classfilebuilder.GETSTATIC, fieldRef) + l.code.CP(classfilebuilder.INVOKEVIRTUAL, cloneRef) + l.code.CP(classfilebuilder.CHECKCAST, castClass) + l.code.Emit(classfilebuilder.ARETURN) + l.code.SetMaxLocals(0) + return true, nil +} + +func (l *methodLowerer) tryEmitCanonicalEnumValueOf() (bool, error) { + if l.method.Code.InsSize != 1 || l.method.Code.RegistersSize < 1 { + return false, nil + } + param0 := l.method.Code.RegistersSize - l.method.Code.InsSize + block := l.method.Blocks[0] + regParam := map[uint16]bool{param0: true} + regClass := make(map[uint16]bool) + regEnum := make(map[uint16]bool) + regCast := make(map[uint16]bool) + clearReg := func(r uint16) { + delete(regParam, r) + delete(regClass, r) + delete(regEnum, r) + delete(regCast, r) + } + sawInvoke, sawCast, sawReturn := false, false, false + for p := 0; p < len(block.Instructions); p++ { + idx := block.Instructions[p] + ins := &l.method.Instructions[idx] + op := ins.Opcode + switch { + case op == 0x00: + continue + case (op >= 0x01 && op <= 0x03) || (op >= 0x07 && op <= 0x09): + dst, src := ins.Regs[0], ins.Regs[1] + pa, cl, en, ca := regParam[src], regClass[src], regEnum[src], regCast[src] + clearReg(dst) + if pa { + regParam[dst] = true + } + if cl { + regClass[dst] = true + } + if en { + regEnum[dst] = true + } + if ca { + regCast[dst] = true + } + case op == 0x1c: + if sawInvoke || sawReturn || int(ins.Index) >= len(l.file.Types) || l.file.Types[ins.Index].Descriptor != l.class.Descriptor { + return false, nil + } + clearReg(ins.Regs[0]) + regClass[ins.Regs[0]] = true + case op == 0x71 || op == 0x77: + if sawInvoke || sawReturn || len(ins.Regs) != 2 || !regClass[ins.Regs[0]] || !regParam[ins.Regs[1]] || int(ins.Index) >= len(l.file.Methods) { + return false, nil + } + callee := l.file.Methods[ins.Index] + if callee.Class != "Ljava/lang/Enum;" || callee.Name != "valueOf" || int(callee.ProtoIndex) >= len(l.file.Protos) { + return false, nil + } + cp := l.file.Protos[callee.ProtoIndex] + if len(cp.Parameters) != 2 || cp.Parameters[0] != "Ljava/lang/Class;" || cp.Parameters[1] != "Ljava/lang/String;" || cp.ReturnType != "Ljava/lang/Enum;" { + return false, nil + } + if p+1 >= len(block.Instructions) { + return false, nil + } + next := &l.method.Instructions[block.Instructions[p+1]] + if next.Opcode != 0x0c { + return false, nil + } + sawInvoke = true + clearReg(next.Regs[0]) + regEnum[next.Regs[0]] = true + p++ + case op == 0x1f: + if !sawInvoke || sawCast || sawReturn || !regEnum[ins.Regs[0]] || int(ins.Index) >= len(l.file.Types) { + return false, nil + } + if l.file.Types[ins.Index].Descriptor != l.class.Descriptor { + return false, nil + } + clearReg(ins.Regs[0]) + regCast[ins.Regs[0]] = true + sawCast = true + case op == 0x11: + if p != len(block.Instructions)-1 || !sawInvoke || !sawCast || !regCast[ins.Regs[0]] { + return false, nil + } + sawReturn = true + default: + return false, nil + } + } + if !sawReturn { + return false, nil + } + ownerInternal, err := objectInternalName(l.class.Descriptor) + if err != nil { + return false, methodDiagnostic(l.method.Context, nil, "enum valueOf()", err) + } + ownerClass, err := l.builder.Pool().Class(ownerInternal) + if err != nil { + return false, methodDiagnostic(l.method.Context, nil, "enum valueOf()", err) + } + enumValueOf, err := l.builder.Pool().Methodref("java/lang/Enum", "valueOf", "(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Enum;") + if err != nil { + return false, methodDiagnostic(l.method.Context, nil, "enum valueOf()", err) + } + l.code.LDC(ownerClass) + l.code.Load(classfilebuilder.RefLocal, 0) + l.code.CP(classfilebuilder.INVOKESTATIC, enumValueOf) + l.code.CP(classfilebuilder.CHECKCAST, ownerClass) + l.code.Emit(classfilebuilder.ARETURN) + l.code.SetMaxLocals(1) + return true, nil +} + +func matchEnumArrayPacket( + file *model.File, + ownerDesc string, + insns []ir.Instruction, + seq []int, + constants []string, + preInt map[uint16]int32, + preConst map[uint16]string, +) (arrRegs map[uint16]bool, ok bool) { + arrDesc := "[" + ownerDesc + constSet := make(map[string]bool, len(constants)) + for _, name := range constants { + constSet[name] = true + } + intVals := make(map[uint16]int32, len(preInt)) + for k, v := range preInt { + intVals[k] = v + } + constInReg := make(map[uint16]string, len(preConst)) + for k, v := range preConst { + constInReg[k] = v + } + arrRegs = make(map[uint16]bool) + clearReg := func(r uint16) { + delete(intVals, r) + delete(constInReg, r) + delete(arrRegs, r) + } + sawArray := false + filled := make([]bool, len(constants)) + for _, idx := range seq { + ins := &insns[idx] + op := ins.Opcode + switch { + case op == 0x00: + continue + case op >= 0x12 && op <= 0x15: + clearReg(ins.Regs[0]) + intVals[ins.Regs[0]] = int32(ins.Literal) + case (op >= 0x01 && op <= 0x03) || (op >= 0x07 && op <= 0x09): + dst, src := ins.Regs[0], ins.Regs[1] + iv, hasIV := intVals[src] + cn, hasCN := constInReg[src] + isArr := arrRegs[src] + clearReg(dst) + if hasIV { + intVals[dst] = iv + } + if hasCN { + constInReg[dst] = cn + } + if isArr { + arrRegs[dst] = true + } + case op == 0x23: + if sawArray || int(ins.Index) >= len(file.Types) || file.Types[ins.Index].Descriptor != arrDesc { + return nil, false + } + n, hasLen := intVals[ins.Regs[1]] + if !hasLen || int(n) != len(constants) { + return nil, false + } + sawArray = true + clearReg(ins.Regs[0]) + arrRegs[ins.Regs[0]] = true + case op == 0x62: + if int(ins.Index) >= len(file.Fields) { + return nil, false + } + f := file.Fields[ins.Index] + if f.Class != ownerDesc || f.Type != ownerDesc || !constSet[f.Name] { + return nil, false + } + clearReg(ins.Regs[0]) + constInReg[ins.Regs[0]] = f.Name + case op == 0x4d: + if !sawArray || !arrRegs[ins.Regs[1]] { + return nil, false + } + elemIdx, hasIdx := intVals[ins.Regs[2]] + if !hasIdx || elemIdx < 0 || int(elemIdx) >= len(constants) { + return nil, false + } + cName, hasConst := constInReg[ins.Regs[0]] + if !hasConst || cName != constants[elemIdx] || filled[elemIdx] { + return nil, false + } + filled[elemIdx] = true + default: + return nil, false + } + } + if !sawArray { + return nil, false + } + for _, done := range filled { + if !done { + return nil, false + } + } + return arrRegs, true +} + +func (l *methodLowerer) emitCanonicalEnumArrayBody(constants []string) error { + ownerInternal, err := objectInternalName(l.class.Descriptor) + if err != nil { + return err + } + ownerClass, err := l.builder.Pool().Class(ownerInternal) + if err != nil { + return err + } + if err := l.pushInt(int32(len(constants))); err != nil { + return err + } + l.code.CP(classfilebuilder.ANEWARRAY, ownerClass) + for i, constName := range constants { + constRef, err := l.builder.Pool().Fieldref(ownerInternal, constName, l.class.Descriptor) + if err != nil { + return err + } + l.code.Emit(classfilebuilder.DUP) + if err := l.pushInt(int32(i)); err != nil { + return err + } + l.code.CP(classfilebuilder.GETSTATIC, constRef) + l.code.Emit(classfilebuilder.AASTORE) + } + return nil +} + +func (l *methodLowerer) tryEmitCanonicalEnumValuesHelper() (bool, error) { + constants, ok := orderedEnumConstantNames(l.file, l.class, l.hierarchy) + if !ok { + return false, nil + } + block := l.method.Blocks[0] + if len(block.Instructions) < 2 { + return false, nil + } + lastIdx := block.Instructions[len(block.Instructions)-1] + lastInsn := &l.method.Instructions[lastIdx] + if lastInsn.Opcode != 0x11 { + return false, nil + } + arrRegs, matched := matchEnumArrayPacket(l.file, l.class.Descriptor, l.method.Instructions, block.Instructions[:len(block.Instructions)-1], constants, nil, nil) + if !matched || !arrRegs[lastInsn.Regs[0]] { + return false, nil + } + if err := l.emitCanonicalEnumArrayBody(constants); err != nil { + return false, methodDiagnostic(l.method.Context, nil, "enum $values()", err) + } + l.code.Emit(classfilebuilder.ARETURN) + l.code.SetMaxLocals(0) + return true, nil +} + +func (l *methodLowerer) detectCanonicalEnumClinitBacking() *canonicalClinitPlan { + if !isCanonicalEnumClass(l.class) || l.encoded.Method.Name != "" { + return nil + } + backingName, ok := enumBackingField(l.class) + if !ok { + return nil + } + constants, ok := orderedEnumConstantNames(l.file, l.class, l.hierarchy) + if !ok { + return nil + } + arrDesc := "[" + l.class.Descriptor + writeBlockIdx, writePos, writeCount := -1, -1, 0 + for bIdx, blk := range l.method.Blocks { + if !blk.Reachable { + continue + } + for pos, idx := range blk.Instructions { + ins := &l.method.Instructions[idx] + if ins.Opcode == 0x69 && int(ins.Index) < len(l.file.Fields) { + f := l.file.Fields[ins.Index] + if f.Class == l.class.Descriptor && f.Name == backingName && f.Type == arrDesc { + writeBlockIdx = bIdx + writePos = pos + writeCount++ + } + } + } + } + if writeCount != 1 || writeBlockIdx < 0 || writePos < 0 { + return nil + } + block := l.method.Blocks[writeBlockIdx] + startPos := 0 + if len(constants) > 0 { + lastConst := constants[len(constants)-1] + lastConstPos := -1 + for p := 0; p < writePos; p++ { + ins := &l.method.Instructions[block.Instructions[p]] + if ins.Opcode == 0x69 && int(ins.Index) < len(l.file.Fields) { + f := l.file.Fields[ins.Index] + if f.Class == l.class.Descriptor && f.Name == lastConst && f.Type == l.class.Descriptor { + lastConstPos = p + } + } + } + if lastConstPos < 0 { + return nil + } + startPos = lastConstPos + 1 + } else if len(block.Predecessors) > 0 { + return nil + } + if startPos >= writePos { + return nil + } + + constSet := make(map[string]bool, len(constants)) + for _, name := range constants { + constSet[name] = true + } + preInt := make(map[uint16]int32) + preConst := make(map[uint16]string) + for p := 0; p < startPos; p++ { + idx := block.Instructions[p] + ins := &l.method.Instructions[idx] + op := ins.Opcode + switch { + case op >= 0x12 && op <= 0x15: + delete(preConst, ins.Regs[0]) + preInt[ins.Regs[0]] = int32(ins.Literal) + case (op >= 0x01 && op <= 0x03) || (op >= 0x07 && op <= 0x09): + dst, src := ins.Regs[0], ins.Regs[1] + iv, hasIV := preInt[src] + cn, hasCN := preConst[src] + delete(preInt, dst) + delete(preConst, dst) + if hasIV { + preInt[dst] = iv + } + if hasCN { + preConst[dst] = cn + } + case op == 0x62 && int(ins.Index) < len(l.file.Fields): + f := l.file.Fields[ins.Index] + delete(preInt, ins.Regs[0]) + delete(preConst, ins.Regs[0]) + if f.Class == l.class.Descriptor && f.Type == l.class.Descriptor && constSet[f.Name] { + preConst[ins.Regs[0]] = f.Name + } + case op == 0x69 && int(ins.Index) < len(l.file.Fields): + f := l.file.Fields[ins.Index] + if f.Class == l.class.Descriptor && f.Type == l.class.Descriptor && constSet[f.Name] { + preConst[ins.Regs[0]] = f.Name + } + default: + _, defs := l.method.EffectsAt(idx) + for _, r := range defs { + delete(preInt, r) + delete(preConst, r) + } + } + } + + helperName := "" + backingSrcReg := l.method.Instructions[block.Instructions[writePos]].Regs[0] + var matchedInline bool + helperRegs := make(map[uint16]bool) + matchedHelper := false + // Option 1: synthetic helper call returning [LOwner; + sawCall := false + for p := startPos; p < writePos; p++ { + ins := &l.method.Instructions[block.Instructions[p]] + op := ins.Opcode + switch { + case op == 0x00: + continue + case (op == 0x71 || op == 0x77) && !sawCall && len(ins.Regs) == 0 && p+1 < writePos && int(ins.Index) < len(l.file.Methods): + callee := l.file.Methods[ins.Index] + next := &l.method.Instructions[block.Instructions[p+1]] + if next.Opcode == 0x0c && callee.Class == l.class.Descriptor && int(callee.ProtoIndex) < len(l.file.Protos) { + cp := l.file.Protos[callee.ProtoIndex] + if len(cp.Parameters) == 0 && cp.ReturnType == arrDesc && l.isSyntheticEnumArrayHelper(callee.Name, arrDesc) { + sawCall = true + helperName = callee.Name + helperRegs[next.Regs[0]] = true + p++ + continue + } + } + matchedHelper = false + goto checkInline + case sawCall && ((op >= 0x01 && op <= 0x03) || (op >= 0x07 && op <= 0x09)): + dst, src := ins.Regs[0], ins.Regs[1] + isH := helperRegs[src] + delete(helperRegs, dst) + if isH { + helperRegs[dst] = true + } + default: + matchedHelper = false + goto checkInline + } + } + if sawCall && helperRegs[backingSrcReg] { + matchedHelper = true + } + +checkInline: + if !matchedHelper { + helperName = "" + arrRegs, ok := matchEnumArrayPacket(l.file, l.class.Descriptor, l.method.Instructions, block.Instructions[startPos:writePos], constants, preInt, preConst) + if !ok || !arrRegs[backingSrcReg] { + return nil + } + matchedInline = true + } + if !matchedHelper && !matchedInline { + return nil + } + + endPos := writePos + entriesField := "" + if fieldName, ePos := l.matchKotlinEntriesTail(block.Instructions, writePos, backingName, arrDesc, backingSrcReg); ePos > writePos { + endPos = ePos + entriesField = fieldName + } + + // Verify Span doesn't overlap any exception try region. + startIdx := block.Instructions[startPos] + endIdx := block.Instructions[endPos] + spanStartOff := l.method.Instructions[startIdx].Offset + spanEndOff := l.method.Instructions[endIdx].End() + for _, t := range l.method.Code.Tries { + tStart := t.StartAddress + tEnd := t.StartAddress + uint32(t.InstructionCount) + if tStart < spanEndOff && tEnd > spanStartOff { + return nil + } + } + + // Verify no register defined inside [startPos..endPos] is live-read afterwards before redef. + if !l.clinitFusedSpanRegsDeadAfter(writeBlockIdx, startPos, endPos) { + return nil + } + + skipSet := make(map[int]bool, endPos-startPos) + if l.fusedNoLocals == nil { + l.fusedNoLocals = make(map[int]bool, endPos-startPos+1) + } + for p := startPos; p <= endPos; p++ { + idx := block.Instructions[p] + l.fusedNoLocals[idx] = true + if p > startPos { + skipSet[idx] = true + } + } + return &canonicalClinitPlan{ + startIdx: startIdx, + endIdx: endIdx, + skipSet: skipSet, + backingField: backingName, + helperName: helperName, + constants: constants, + entriesField: entriesField, + } +} + +func (l *methodLowerer) isSyntheticEnumArrayHelper(name, arrDesc string) bool { + for i := range l.class.DirectMethods { + m := &l.class.DirectMethods[i] + if m.Method.Name != name || int(m.Method.ProtoIndex) >= len(l.file.Protos) { + continue + } + cp := l.file.Protos[m.Method.ProtoIndex] + if len(cp.Parameters) != 0 || cp.ReturnType != arrDesc { + continue + } + acc, err := methodAccess(m.AccessFlags, m.Method.Name) + if err == nil && (acc == jvmSyntheticHelperFlags || acc == jvmSyntheticBackingFlags) { + return true + } + } + return false +} + +func (l *methodLowerer) matchKotlinEntriesTail(blockInsns []int, writePos int, backingName, arrDesc string, backingSrcReg uint16) (string, int) { + arrRegs := map[uint16]bool{backingSrcReg: true} + var callResultReg uint16 + sawCall := false + for p := writePos + 1; p < len(blockInsns); p++ { + idx := blockInsns[p] + ins := &l.method.Instructions[idx] + op := ins.Opcode + switch { + case op == 0x00: + continue + case !sawCall && op == 0x62 && int(ins.Index) < len(l.file.Fields): + f := l.file.Fields[ins.Index] + if f.Class != l.class.Descriptor || f.Name != backingName || f.Type != arrDesc { + return "", -1 + } + arrRegs[ins.Regs[0]] = true + case !sawCall && op == 0x1f && int(ins.Index) < len(l.file.Types): + if !arrRegs[ins.Regs[0]] || l.file.Types[ins.Index].Descriptor != "[Ljava/lang/Enum;" { + return "", -1 + } + case !sawCall && ((op >= 0x01 && op <= 0x03) || (op >= 0x07 && op <= 0x09)): + dst, src := ins.Regs[0], ins.Regs[1] + isA := arrRegs[src] + delete(arrRegs, dst) + if isA { + arrRegs[dst] = true + } + case !sawCall && (op == 0x71 || op == 0x77) && len(ins.Regs) == 1 && arrRegs[ins.Regs[0]] && p+1 < len(blockInsns) && int(ins.Index) < len(l.file.Methods): + callee := l.file.Methods[ins.Index] + next := &l.method.Instructions[blockInsns[p+1]] + if next.Opcode == 0x0c && callee.Class == "Lkotlin/enums/EnumEntriesKt;" && callee.Name == "enumEntries" && int(callee.ProtoIndex) < len(l.file.Protos) { + cp := l.file.Protos[callee.ProtoIndex] + if len(cp.Parameters) == 1 && cp.Parameters[0] == "[Ljava/lang/Enum;" && cp.ReturnType == "Lkotlin/enums/EnumEntries;" { + sawCall = true + callResultReg = next.Regs[0] + p++ + continue + } + } + return "", -1 + case sawCall && ((op >= 0x01 && op <= 0x03) || (op >= 0x07 && op <= 0x09)): + if ins.Regs[1] == callResultReg { + callResultReg = ins.Regs[0] + } else if ins.Regs[0] == callResultReg { + return "", -1 + } + case sawCall && op == 0x69 && ins.Regs[0] == callResultReg && int(ins.Index) < len(l.file.Fields): + f := l.file.Fields[ins.Index] + if f.Class == l.class.Descriptor && f.Type == "Lkotlin/enums/EnumEntries;" { + return f.Name, p + } + return "", -1 + default: + return "", -1 + } + } + return "", -1 +} + +func (l *methodLowerer) clinitFusedSpanRegsDeadAfter(blockIdx, startPos, endPos int) bool { + written := make(map[uint16]bool) + blk := l.method.Blocks[blockIdx] + for p := startPos; p <= endPos; p++ { + _, defs := l.method.EffectsAt(blk.Instructions[p]) + for _, r := range defs { + written[r] = true + } + } + if len(written) == 0 { + return true + } + + dirty := make(map[uint16]bool, len(written)) + for r := range written { + dirty[r] = true + } + walkRange := func(insns []int, d map[uint16]bool) bool { + for _, idx := range insns { + if l.fusedNoLocals[idx] { + continue + } + uses, defs := l.method.EffectsAt(idx) + for _, r := range uses { + if d[r] { + return false + } + } + for _, r := range defs { + delete(d, r) + } + } + return true + } + if !walkRange(blk.Instructions[endPos+1:], dirty) { + return false + } + if len(dirty) == 0 { + return true + } + + inDirty := make([]map[uint16]bool, len(l.method.Blocks)) + var queue []int + enqueue := func(succ int, d map[uint16]bool) { + if len(d) == 0 { + return + } + if inDirty[succ] == nil { + inDirty[succ] = make(map[uint16]bool, len(d)) + } + grew := false + for r := range d { + if !inDirty[succ][r] { + inDirty[succ][r] = true + grew = true + } + } + if grew { + queue = append(queue, succ) + } + } + for _, succ := range blk.Successors { + enqueue(succ, dirty) + } + for len(queue) > 0 { + cur := queue[0] + queue = queue[1:] + out := make(map[uint16]bool, len(inDirty[cur])) + for r := range inDirty[cur] { + out[r] = true + } + if !walkRange(l.method.Blocks[cur].Instructions, out) { + return false + } + for _, succ := range l.method.Blocks[cur].Successors { + enqueue(succ, out) + } + } + return true +} + +func (l *methodLowerer) emitCanonicalEnumClinitPacket() error { + plan := l.canonicalClinit + ownerInternal, err := objectInternalName(l.class.Descriptor) + if err != nil { + return methodDiagnostic(l.method.Context, nil, "enum ", err) + } + arrDesc := "[" + l.class.Descriptor + backingRef, err := l.builder.Pool().Fieldref(ownerInternal, plan.backingField, arrDesc) + if err != nil { + return methodDiagnostic(l.method.Context, nil, "enum ", err) + } + if plan.helperName != "" { + helperRef, err := l.builder.Pool().Methodref(ownerInternal, plan.helperName, "()"+arrDesc) + if err != nil { + return methodDiagnostic(l.method.Context, nil, "enum ", err) + } + l.code.CP(classfilebuilder.INVOKESTATIC, helperRef) + } else { + if err := l.emitCanonicalEnumArrayBody(plan.constants); err != nil { + return methodDiagnostic(l.method.Context, nil, "enum ", err) + } + } + l.code.CP(classfilebuilder.PUTSTATIC, backingRef) + if plan.entriesField != "" { + enumArrClass, err := l.builder.Pool().Class("[Ljava/lang/Enum;") + if err != nil { + return methodDiagnostic(l.method.Context, nil, "enum ", err) + } + enumEntriesFn, err := l.builder.Pool().Methodref("kotlin/enums/EnumEntriesKt", "enumEntries", "([Ljava/lang/Enum;)Lkotlin/enums/EnumEntries;") + if err != nil { + return methodDiagnostic(l.method.Context, nil, "enum ", err) + } + entriesRef, err := l.builder.Pool().Fieldref(ownerInternal, plan.entriesField, "Lkotlin/enums/EnumEntries;") + if err != nil { + return methodDiagnostic(l.method.Context, nil, "enum ", err) + } + l.code.CP(classfilebuilder.GETSTATIC, backingRef) + l.code.CP(classfilebuilder.CHECKCAST, enumArrClass) + l.code.CP(classfilebuilder.INVOKESTATIC, enumEntriesFn) + l.code.CP(classfilebuilder.PUTSTATIC, entriesRef) + } + return nil +} + +func (l *methodLowerer) isEnumSelfOrSubclass(desc string) bool { + if desc == l.class.Descriptor { + return true + } + if l.hierarchy != nil { + if sub, ok := l.hierarchy[desc]; ok && sub != nil && sub.Superclass == l.class.Descriptor { + return true + } + } + for i := range l.file.Classes { + if l.file.Classes[i].Descriptor == desc && l.file.Classes[i].Superclass == l.class.Descriptor { + return true + } + } + prefix := strings.TrimSuffix(l.class.Descriptor, ";") + "$" + return strings.HasPrefix(desc, prefix) +} + +func resolvePureConstArg(paramDesc string, val pureConstVal) (canonicalConstArg, bool) { + switch paramDesc { + case "I", "Z", "B", "C", "S", "F": + if val.kind != pure32Bits { + return canonicalConstArg{}, false + } + return canonicalConstArg{paramDesc: paramDesc, kind: pure32Bits, bits: val.bits}, true + case "J", "D": + if val.kind != pure64Bits { + return canonicalConstArg{}, false + } + return canonicalConstArg{paramDesc: paramDesc, kind: pure64Bits, bits: val.bits}, true + case "Ljava/lang/String;": + if val.kind == pureString { + return canonicalConstArg{paramDesc: paramDesc, kind: pureString, text: val.text}, true + } + if val.kind == pure32Bits && val.bits == 0 { + return canonicalConstArg{paramDesc: paramDesc, kind: pure32Bits, bits: 0}, true + } + return canonicalConstArg{}, false + case "Ljava/lang/Class;": + if val.kind == pureClass { + return canonicalConstArg{paramDesc: paramDesc, kind: pureClass, text: val.text}, true + } + if val.kind == pure32Bits && val.bits == 0 { + return canonicalConstArg{paramDesc: paramDesc, kind: pure32Bits, bits: 0}, true + } + return canonicalConstArg{}, false + default: + if (strings.HasPrefix(paramDesc, "L") || strings.HasPrefix(paramDesc, "[")) && val.kind == pure32Bits && val.bits == 0 { + return canonicalConstArg{paramDesc: paramDesc, kind: pure32Bits, bits: 0}, true + } + return canonicalConstArg{}, false + } +} + +func (l *methodLowerer) detectCanonicalEnumClinitConstSpans() { + if !isCanonicalEnumClass(l.class) || l.encoded.Method.Name != "" { + return + } + enumFields := make(map[string]bool) + for i := range l.class.StaticFields { + sf := &l.class.StaticFields[i] + if sf.AccessFlags&dexEnum != 0 && sf.Field.Class == l.class.Descriptor && sf.Field.Type == l.class.Descriptor { + enumFields[sf.Field.Name] = true + } + } + if len(enumFields) == 0 { + return + } + + for bIdx, blk := range l.method.Blocks { + if !blk.Reachable { + continue + } + for pos := 0; pos < len(blk.Instructions); pos++ { + startIdx := blk.Instructions[pos] + if l.fusedNoLocals[startIdx] || (pos == 0 && len(blk.Predecessors) > 0) { + continue + } + startInsn := &l.method.Instructions[startIdx] + if startInsn.Opcode != 0x22 || int(startInsn.Index) >= len(l.file.Types) { + continue + } + allocDesc := l.file.Types[startInsn.Index].Descriptor + if !l.isEnumSelfOrSubclass(allocDesc) { + continue + } + allocReg := startInsn.Regs[0] + vals := make(map[uint16]pureConstVal) + + for k := pos + 1; k < len(blk.Instructions); k++ { + idx := blk.Instructions[k] + if l.fusedNoLocals[idx] { + break + } + ins := &l.method.Instructions[idx] + op := ins.Opcode + switch { + case op == 0x00: + continue + case op >= 0x12 && op <= 0x15: + if ins.Regs[0] == allocReg { + goto nextStart + } + vals[ins.Regs[0]] = pureConstVal{kind: pure32Bits, bits: ins.Literal} + case op >= 0x16 && op <= 0x19: + if ins.Regs[0] == allocReg || ins.Regs[0]+1 == allocReg { + goto nextStart + } + vals[ins.Regs[0]] = pureConstVal{kind: pure64Bits, bits: ins.Literal} + delete(vals, ins.Regs[0]+1) + case op == 0x1a || op == 0x1b: + if ins.Regs[0] == allocReg || int(ins.Index) >= len(l.file.Strings) { + goto nextStart + } + vals[ins.Regs[0]] = pureConstVal{kind: pureString, text: l.file.Strings[ins.Index]} + case op == 0x1c: + if ins.Regs[0] == allocReg || int(ins.Index) >= len(l.file.Types) { + goto nextStart + } + vals[ins.Regs[0]] = pureConstVal{kind: pureClass, text: l.file.Types[ins.Index].Descriptor} + case (op >= 0x01 && op <= 0x03) || (op >= 0x07 && op <= 0x09): + dst, src := ins.Regs[0], ins.Regs[1] + if dst == allocReg || src == allocReg { + goto nextStart + } + if v, ok := vals[src]; ok { + vals[dst] = v + } else { + delete(vals, dst) + } + case op >= 0x04 && op <= 0x06: + dst, src := ins.Regs[0], ins.Regs[1] + if dst == allocReg || dst+1 == allocReg || src == allocReg || src+1 == allocReg { + goto nextStart + } + if v, ok := vals[src]; ok && v.kind == pure64Bits { + vals[dst] = v + delete(vals, dst+1) + } else { + delete(vals, dst) + delete(vals, dst+1) + } + case (op == 0x70 || op == 0x76) && ins.ExtraNullArgs == 0 && len(ins.Regs) >= 3 && ins.Regs[0] == allocReg && int(ins.Index) < len(l.file.Methods): + callee := l.file.Methods[ins.Index] + if callee.Class != allocDesc || callee.Name != "" || int(callee.ProtoIndex) >= len(l.file.Protos) { + goto nextStart + } + calleeProto := l.file.Protos[callee.ProtoIndex] + if len(calleeProto.Parameters) < 2 || calleeProto.Parameters[0] != "Ljava/lang/String;" || calleeProto.Parameters[1] != "I" || calleeProto.ReturnType != "V" { + goto nextStart + } + regPos := 1 + args := make([]canonicalConstArg, 0, len(calleeProto.Parameters)) + validArgs := true + for _, pDesc := range calleeProto.Parameters { + words := descriptorWords(pDesc) + if regPos+words > len(ins.Regs) { + validArgs = false + break + } + v, ok := vals[ins.Regs[regPos]] + if !ok { + validArgs = false + break + } + arg, ok := resolvePureConstArg(pDesc, v) + if !ok { + validArgs = false + break + } + args = append(args, arg) + regPos += words + } + if !validArgs || regPos != len(ins.Regs) { + goto nextStart + } + + postAlias := map[uint16]bool{allocReg: true} + endPos := -1 + fieldName := "" + for sPos := k + 1; sPos < len(blk.Instructions); sPos++ { + sIdx := blk.Instructions[sPos] + if l.fusedNoLocals[sIdx] { + break + } + sIns := &l.method.Instructions[sIdx] + sOp := sIns.Opcode + if sOp == 0x00 { + continue + } + if (sOp >= 0x01 && sOp <= 0x03) || (sOp >= 0x07 && sOp <= 0x09) { + dst, src := sIns.Regs[0], sIns.Regs[1] + isA := postAlias[src] + delete(postAlias, dst) + if isA { + postAlias[dst] = true + } + continue + } + if sOp == 0x69 && len(sIns.Regs) > 0 && postAlias[sIns.Regs[0]] && int(sIns.Index) < len(l.file.Fields) { + f := l.file.Fields[sIns.Index] + if f.Class == l.class.Descriptor && f.Type == l.class.Descriptor && enumFields[f.Name] { + endPos = sPos + fieldName = f.Name + } + } + break + } + if endPos < 0 { + goto nextStart + } + endIdx := blk.Instructions[endPos] + spanStartOff := l.method.Instructions[startIdx].Offset + spanEndOff := l.method.Instructions[endIdx].End() + for _, t := range l.method.Code.Tries { + tStart := t.StartAddress + tEnd := t.StartAddress + uint32(t.InstructionCount) + if tStart < spanEndOff && tEnd > spanStartOff { + goto nextStart + } + } + if !l.clinitFusedSpanRegsDeadAfter(bIdx, pos, endPos) { + goto nextStart + } + if l.fusedNoLocals == nil { + l.fusedNoLocals = make(map[int]bool, endPos-pos+1) + } + if l.canonicalClinitConsts == nil { + l.canonicalClinitConsts = make(map[int]*canonicalEnumConstSpan) + } + if l.canonicalClinitConstSkip == nil { + l.canonicalClinitConstSkip = make(map[int]bool) + } + for p := pos; p <= endPos; p++ { + pIdx := blk.Instructions[p] + l.fusedNoLocals[pIdx] = true + if p > pos { + l.canonicalClinitConstSkip[pIdx] = true + } + } + l.canonicalClinitConsts[startIdx] = &canonicalEnumConstSpan{ + startIdx: startIdx, + allocDesc: allocDesc, + ctorProto: calleeProto, + args: args, + fieldName: fieldName, + } + pos = endPos + goto nextStart + default: + goto nextStart + } + } + nextStart: + } + } +} + +func (l *methodLowerer) emitCanonicalEnumConstSpan(span *canonicalEnumConstSpan) error { + allocInternal, err := objectInternalName(span.allocDesc) + if err != nil { + return methodDiagnostic(l.method.Context, nil, "enum const", err) + } + ownerInternal, err := objectInternalName(l.class.Descriptor) + if err != nil { + return methodDiagnostic(l.method.Context, nil, "enum const", err) + } + allocClass, err := l.builder.Pool().Class(allocInternal) + if err != nil { + return methodDiagnostic(l.method.Context, nil, "enum const", err) + } + ctorDesc, err := methodDescriptor(span.ctorProto) + if err != nil { + return methodDiagnostic(l.method.Context, nil, "enum const", err) + } + ctorRef, err := l.builder.Pool().Methodref(allocInternal, "", ctorDesc) + if err != nil { + return methodDiagnostic(l.method.Context, nil, "enum const", err) + } + fieldRef, err := l.builder.Pool().Fieldref(ownerInternal, span.fieldName, l.class.Descriptor) + if err != nil { + return methodDiagnostic(l.method.Context, nil, "enum const", err) + } + + l.code.CP(classfilebuilder.NEW, allocClass).Emit(classfilebuilder.DUP) + for _, arg := range span.args { + switch { + case arg.kind == pureString: + c, err := l.builder.Pool().String(arg.text) + if err != nil { + return methodDiagnostic(l.method.Context, nil, "enum const", err) + } + l.code.LDC(c) + case arg.kind == pureClass: + if owner, ok := primitiveClassOwner(arg.text); ok { + c, err := l.builder.Pool().Fieldref(owner, "TYPE", "Ljava/lang/Class;") + if err != nil { + return methodDiagnostic(l.method.Context, nil, "enum const", err) + } + l.code.CP(classfilebuilder.GETSTATIC, c) + } else { + name, err := ir.InternalName(arg.text) + if err != nil { + return methodDiagnostic(l.method.Context, nil, "enum const", err) + } + c, err := l.builder.Pool().Class(name) + if err != nil { + return methodDiagnostic(l.method.Context, nil, "enum const", err) + } + l.code.LDC(c) + } + case arg.paramDesc == "F": + c, err := l.builder.Pool().Float(uint32(arg.bits)) + if err != nil { + return methodDiagnostic(l.method.Context, nil, "enum const", err) + } + l.code.LDC(c) + case arg.paramDesc == "J": + c, err := l.builder.Pool().Long(arg.bits) + if err != nil { + return methodDiagnostic(l.method.Context, nil, "enum const", err) + } + l.code.LDC2(c) + case arg.paramDesc == "D": + c, err := l.builder.Pool().Double(uint64(arg.bits)) + if err != nil { + return methodDiagnostic(l.method.Context, nil, "enum const", err) + } + l.code.LDC2(c) + case strings.HasPrefix(arg.paramDesc, "L") || strings.HasPrefix(arg.paramDesc, "["): + l.code.Emit(classfilebuilder.ACONST_NULL) + default: + if err := l.pushInt(int32(arg.bits)); err != nil { + return methodDiagnostic(l.method.Context, nil, "enum const", err) + } + } + } + l.code.CP(classfilebuilder.INVOKESPECIAL, ctorRef) + l.code.CP(classfilebuilder.PUTSTATIC, fieldRef) + return nil +} diff --git a/dex2jar/lower/lower.go b/dex2jar/lower/lower.go index f591dfd1..8f76f530 100644 --- a/dex2jar/lower/lower.go +++ b/dex2jar/lower/lower.go @@ -4,6 +4,7 @@ package lower import ( "errors" "fmt" + "sort" "strings" "github.com/yaklang/javajive/classparser/classfilebuilder" @@ -114,7 +115,7 @@ func ClassWithPolicy(file *model.File, class *model.Class, options ClassOptions, } return emitClassShell(file, class, options, errors.New(reason), false) } - result, err := classWithPolicyOnce(file, class, options, StubUnsupportedMethods) + result, err := classWithPolicyOnce(file, class, options, Recover) if err == nil { return result, nil } @@ -286,7 +287,7 @@ func lowerClassBody(file *model.File, class *model.Class, builder *classfilebuil } builder.AddInterface(name) } - if err := addFields(file, class, builder); err != nil { + if err := addFields(file, class, options.Hierarchy, builder); err != nil { return ClassResult{}, err } seenMethods := make(map[string]bool) @@ -331,13 +332,64 @@ func appendMethods(first, second []model.EncodedMethod) []model.EncodedMethod { return methods } -func addFields(file *model.File, class *model.Class, builder *classfilebuilder.Class) error { +func addFields(file *model.File, class *model.Class, hierarchy map[string]*model.Class, builder *classfilebuilder.Class) error { seen := make(map[string]bool) - fields := make([]model.EncodedField, 0, len(class.StaticFields)+len(class.InstanceFields)) - fields = append(fields, class.StaticFields...) - fields = append(fields, class.InstanceFields...) - for index := range fields { - field := fields[index] + type fieldEntry struct { + field model.EncodedField + isStatic bool + hasStaticVal bool + staticVal model.EncodedValue + } + entries := make([]fieldEntry, 0, len(class.StaticFields)+len(class.InstanceFields)) + for i, sf := range class.StaticFields { + item := fieldEntry{field: sf, isStatic: true} + if i < len(class.StaticValues) { + item.hasStaticVal = true + item.staticVal = class.StaticValues[i] + } + entries = append(entries, item) + } + for _, inf := range class.InstanceFields { + entries = append(entries, fieldEntry{field: inf}) + } + if class.AccessFlags&dexEnum != 0 && class.Superclass == "Ljava/lang/Enum;" && len(class.StaticFields) > 1 { + if ordinals := inferEnumFieldOrdinals(file, class, hierarchy); len(ordinals) > 0 { + var enumPositions []int + for i := 0; i < len(class.StaticFields); i++ { + sf := class.StaticFields[i] + if sf.AccessFlags&dexEnum != 0 && sf.Field.Type == class.Descriptor { + enumPositions = append(enumPositions, i) + } + } + if len(enumPositions) == len(ordinals) && len(enumPositions) > 1 { + seenOrd := make([]bool, len(enumPositions)) + valid := true + for _, pos := range enumPositions { + ord, ok := ordinals[entries[pos].field.Field.Name] + if !ok || ord < 0 || ord >= len(enumPositions) || seenOrd[ord] { + valid = false + break + } + seenOrd[ord] = true + } + if valid { + ordered := make([]fieldEntry, len(enumPositions)) + for i, pos := range enumPositions { + ordered[i] = entries[pos] + } + sort.Slice(ordered, func(i, j int) bool { + return ordinals[ordered[i].field.Field.Name] < ordinals[ordered[j].field.Field.Name] + }) + for i, pos := range enumPositions { + entries[pos] = ordered[i] + } + } + } + } + } + for index := range entries { + entry := entries[index] + field := entry.field if field.Field.Class != class.Descriptor { return classDiagnostic(file, class, "field", fmt.Errorf("field %q owner %q does not match class", field.Field.Name, field.Field.Class)) } @@ -359,16 +411,15 @@ func addFields(file *model.File, class *model.Class, builder *classfilebuilder.C if err != nil { return classDiagnostic(file, class, "field", fmt.Errorf("field %q: %w", field.Field.Name, err)) } - isStatic := index < len(class.StaticFields) - if isStatic != (field.AccessFlags&dexStatic != 0) { + if entry.isStatic != (field.AccessFlags&dexStatic != 0) { return classDiagnostic(file, class, "field", fmt.Errorf("field %q static membership and access flag disagree", field.Field.Name)) } if err := validateInterfaceFieldShape(class, field.AccessFlags); err != nil { return classDiagnostic(file, class, "field", fmt.Errorf("field %q: %w", field.Field.Name, err)) } member := builder.AddField(access, field.Field.Name, field.Field.Type) - if isStatic && index < len(class.StaticValues) { - if err := applyStaticValue(file, class, &fields[index], member, builder, class.StaticValues[index]); err != nil { + if entry.isStatic && entry.hasStaticVal { + if err := applyStaticValue(file, class, &entries[index].field, member, builder, entry.staticVal); err != nil { return err } } @@ -388,6 +439,115 @@ func addFields(file *model.File, class *model.Class, builder *classfilebuilder.C return nil } +// inferEnumFieldOrdinals decodes an enum class initializer and maps each ACC_ENUM +// static field name to the ordinal passed to Enum(String, int) before sput-object. +func inferEnumFieldOrdinals(file *model.File, class *model.Class, hierarchy map[string]*model.Class) map[string]int { + if file == nil || class == nil { + return nil + } + enumFields := make(map[string]bool) + for _, sf := range class.StaticFields { + if sf.AccessFlags&dexEnum != 0 && sf.Field.Type == class.Descriptor { + enumFields[sf.Field.Name] = true + } + } + if len(enumFields) < 2 { + return nil + } + var clinit *model.EncodedMethod + for i := range class.DirectMethods { + m := &class.DirectMethods[i] + if m.Method.Name == "" && m.Code != nil { + clinit = m + break + } + } + if clinit == nil { + return nil + } + insns, err := ir.Decode(clinit.Code, methodContext(file, class, clinit)) + if err != nil || len(insns) == 0 { + return nil + } + + prefix := strings.TrimSuffix(class.Descriptor, ";") + "$" + isEnumSubclass := func(desc string) bool { + if desc == class.Descriptor || strings.HasPrefix(desc, prefix) { + return true + } + if hierarchy != nil { + if sub, ok := hierarchy[desc]; ok && sub != nil && sub.Superclass == class.Descriptor { + return true + } + } + for i := range file.Classes { + if file.Classes[i].Descriptor == desc && file.Classes[i].Superclass == class.Descriptor { + return true + } + } + return false + } + + intVals := make(map[uint16]int32) + enumOrd := make(map[uint16]int) + ordinals := make(map[string]int, len(enumFields)) + + for i := range insns { + ins := insns[i] + op := ins.Opcode + switch { + case op >= 0x12 && op <= 0x15 && len(ins.Regs) > 0: + intVals[ins.Regs[0]] = int32(ins.Literal) + delete(enumOrd, ins.Regs[0]) + case op >= 0x01 && op <= 0x03 && len(ins.Regs) >= 2: + if v, ok := intVals[ins.Regs[1]]; ok { + intVals[ins.Regs[0]] = v + } else { + delete(intVals, ins.Regs[0]) + } + delete(enumOrd, ins.Regs[0]) + case op >= 0x07 && op <= 0x09 && len(ins.Regs) >= 2: + if ord, ok := enumOrd[ins.Regs[1]]; ok { + enumOrd[ins.Regs[0]] = ord + } else { + delete(enumOrd, ins.Regs[0]) + } + delete(intVals, ins.Regs[0]) + case (op == 0x70 || op == 0x76) && int(ins.Index) < len(file.Methods): + callee := file.Methods[ins.Index] + if callee.Name == "" && int(callee.ProtoIndex) < len(file.Protos) && len(ins.Regs) >= 3 && isEnumSubclass(callee.Class) { + proto := file.Protos[callee.ProtoIndex] + if len(proto.Parameters) >= 2 && proto.Parameters[0] == "Ljava/lang/String;" && proto.Parameters[1] == "I" { + if ord, ok := intVals[ins.Regs[2]]; ok { + enumOrd[ins.Regs[0]] = int(ord) + delete(intVals, ins.Regs[0]) + continue + } + } + } + _, defs := ir.InstructionEffects(ins) + for _, r := range defs { + delete(intVals, r) + delete(enumOrd, r) + } + case op == 0x69 && len(ins.Regs) > 0 && int(ins.Index) < len(file.Fields): + f := file.Fields[ins.Index] + if f.Class == class.Descriptor && f.Type == class.Descriptor && enumFields[f.Name] { + if ord, ok := enumOrd[ins.Regs[0]]; ok { + ordinals[f.Name] = ord + } + } + default: + _, defs := ir.InstructionEffects(ins) + for _, r := range defs { + delete(intVals, r) + delete(enumOrd, r) + } + } + } + return ordinals +} + func fieldAnnotationsOf(class *model.Class, index uint32) []model.Annotation { if position, ok := class.FieldAnnotationIndex[index]; ok && position >= 0 && position < len(class.FieldAnnotations) { return class.FieldAnnotations[position].Annotations @@ -566,7 +726,7 @@ func addMethod(file *model.File, class *model.Class, method *model.EncodedMethod if !declarationOnly { built, err = ir.Build(ir.Input{File: file, Class: class, Method: method, SkipFileValidation: options.FileValidated}) if err != nil { - if policy != StubUnsupportedMethods || !report.IsUnsupported(err) { + if (policy != StubUnsupportedMethods && policy != Recover) || !report.IsUnsupported(err) { return nil, err } var capability *report.CapabilityError @@ -602,11 +762,27 @@ func addMethod(file *model.File, class *model.Class, method *model.EncodedMethod } } if parameters := parameterAnnotationsOf(class, method.MethodIndex); len(parameters) > 0 { - converted, visible, err := translateParameterAnnotations(file, parameters, len(proto.Parameters)) - if err != nil { - return nil, methodDiagnostic(ctx, nil, "parameter annotation", err) + if len(parameters) != len(proto.Parameters) { + if policy == Recover { + if method.Method.Name == "" && len(parameters) < len(proto.Parameters) { + aligned := make([][]model.Annotation, len(proto.Parameters)) + copy(aligned[len(proto.Parameters)-len(parameters):], parameters) + converted, visible, err := translateParameterAnnotations(file, aligned, len(proto.Parameters)) + if err == nil { + builder.SetMethodParameterAnnotations(member, converted, visible) + } + } + } else { + _, _, err := translateParameterAnnotations(file, parameters, len(proto.Parameters)) + return nil, methodDiagnostic(ctx, nil, "parameter annotation", err) + } + } else { + converted, visible, err := translateParameterAnnotations(file, parameters, len(proto.Parameters)) + if err != nil { + return nil, methodDiagnostic(ctx, nil, "parameter annotation", err) + } + builder.SetMethodParameterAnnotations(member, converted, visible) } - builder.SetMethodParameterAnnotations(member, converted, visible) } if declarationOnly { return nil, nil diff --git a/dex2jar/lower/method.go b/dex2jar/lower/method.go index ddd4e0b1..983955d7 100644 --- a/dex2jar/lower/method.go +++ b/dex2jar/lower/method.go @@ -55,6 +55,11 @@ type methodLowerer struct { useWebDef map[regUseKey]int entryDefByReg []int webReachIn []defState + webPolySlots map[webPolyKey]uint16 + webPolyMask map[int]uint8 + webZeroKind map[int]ir.CategoryKind + webSingleZeroKind map[int]ir.CategoryKind + pinnedZeroKind map[uint16]ir.CategoryKind refIn []referenceState // allocationNewLabels maps an Allocation.ID to the JVM bytecode label right // before NEW so StackMapTable frames can emit ITEM_Uninitialized offsets. @@ -74,10 +79,21 @@ type methodLowerer struct { // caught exception to the stub that discards it. handlerTrampolines map[uint32]*classfilebuilder.Label - // delegationIndex marks this-constructor delegation; field stores that DEX - // permits before it are emitted immediately after it. - delegationIndex int - deferredStores []deferredStore + // delegationIndex marks a single-site this-constructor delegation; field + // stores that DEX permits before delegation are tracked per delegation site. + delegationIndex int + delegationSites map[int]bool + deferredByDelegation map[int][]int + deferredStores []deferredStore + deferredInsn map[int]bool + labelOp map[*classfilebuilder.Label]int + insnStartLabel []*classfilebuilder.Label + insnThrowEndLabel []*classfilebuilder.Label + insnEndLabel []*classfilebuilder.Label + canonicalClinit *canonicalClinitPlan + canonicalClinitConsts map[int]*canonicalEnumConstSpan + canonicalClinitConstSkip map[int]bool + fusedNoLocals map[int]bool } func (l *methodLowerer) lower() error { @@ -87,6 +103,11 @@ func (l *methodLowerer) lower() error { if err := l.assignHomes(); err != nil { return methodDiagnostic(l.method.Context, nil, "locals", err) } + l.index = -1 + l.labelOp = make(map[*classfilebuilder.Label]int, len(l.method.Instructions)*3+len(l.method.Blocks)+16) + l.insnStartLabel = make([]*classfilebuilder.Label, len(l.method.Instructions)) + l.insnThrowEndLabel = make([]*classfilebuilder.Label, len(l.method.Instructions)) + l.insnEndLabel = make([]*classfilebuilder.Label, len(l.method.Instructions)) l.labels = make(map[uint32]*classfilebuilder.Label, len(l.method.Blocks)) for _, block := range l.method.Blocks { l.labels[block.Start] = l.code.NewLabel() @@ -97,6 +118,8 @@ func (l *methodLowerer) lower() error { l.registerDescriptor[register] = category.Descriptor } l.delegationIndex = -1 + l.delegationSites = nil + l.deferredByDelegation = nil l.allocationAliasOps = make(map[int]bool) for _, allocation := range l.method.Allocations { l.allocationByNew[allocation.NewInstruction] = allocation @@ -124,6 +147,11 @@ func (l *methodLowerer) lower() error { if err := l.validateReferenceUses(); err != nil { return err } + if handled, err := l.tryEmitCanonicalEnumMethod(); err != nil { + return err + } else if handled { + return nil + } if err := l.emitPrologue(); err != nil { return err } @@ -132,43 +160,88 @@ func (l *methodLowerer) lower() error { return err } deferred := make(map[int]*deferredStore, len(l.deferredStores)) + l.deferredInsn = make(map[int]bool, len(l.deferredStores)) for index := range l.deferredStores { deferred[l.deferredStores[index].index] = &l.deferredStores[index] + l.deferredInsn[l.deferredStores[index].index] = true } + l.canonicalClinit = l.detectCanonicalEnumClinitBacking() + l.detectCanonicalEnumClinitConstSpans() for _, block := range l.method.Blocks { - l.code.Mark(l.labels[block.Start]) + l.markLabel(l.labels[block.Start]) for _, index := range block.Instructions { instruction := &l.method.Instructions[index] // A deferred store still owns its address: debug data may reference // it, and an unmarked label would fail class assembly. - if label := l.addressLabels[instruction.Offset]; label != nil && label != l.labels[block.Start] { - l.code.Mark(label) + startLabel := l.addressLabels[instruction.Offset] + if startLabel != nil && startLabel != l.labels[block.Start] { + l.markLabel(startLabel) + } else if startLabel == nil { + startLabel = l.code.NewLabel() + l.markLabel(startLabel) } - if store, ok := deferred[index]; ok { + l.insnStartLabel[index] = startLabel + if span := l.canonicalClinitConsts[index]; span != nil { + if err := l.emitCanonicalEnumConstSpan(span); err != nil { + return err + } + } else if l.canonicalClinitConstSkip[index] { + // Fused into canonical enum constant allocation span. + } else if l.canonicalClinit != nil && index == l.canonicalClinit.startIdx { + if err := l.emitCanonicalEnumClinitPacket(); err != nil { + return err + } + } else if l.canonicalClinit != nil && l.canonicalClinit.skipSet[index] { + // Fused into canonical enum backing packet at startIdx. + } else if store, ok := deferred[index]; ok { l.captureDeferredValue(store) - continue - } - if err := l.emitInstruction(index); err != nil { - return err - } - if index == l.delegationIndex { - for position := range l.deferredStores { - if err := l.emitDeferredStore(&l.deferredStores[position]); err != nil { - return err + } else { + if err := l.emitInstruction(index); err != nil { + return err + } + if l.isDelegationSite(index) { + positions := l.deferredByDelegation[index] + if len(positions) == 0 && index == l.delegationIndex && len(l.delegationSites) <= 1 { + for position := range l.deferredStores { + if err := l.emitDeferredStore(&l.deferredStores[position]); err != nil { + return err + } + } + } else { + for _, position := range positions { + if err := l.emitDeferredStore(&l.deferredStores[position]); err != nil { + return err + } + } } } } + endLabel := l.code.NewLabel() + l.markLabel(endLabel) + l.insnEndLabel[index] = endLabel } } + l.index = -1 if l.endLabel != nil { - l.code.Mark(l.endLabel) + l.markLabel(l.endLabel) } l.emitHandlerTrampolines() - if err := l.emitExceptionTable(); err != nil { + var smState *stackMapState + if len(l.method.Code.Tries) > 0 || l.builder.Version() >= classfilebuilder.VersionJava7 { + state, err := l.computeStackMapFrames() + if err != nil { + if l.builder.Version() >= classfilebuilder.VersionJava7 { + return err + } + } else { + smState = state + } + } + if err := l.emitExceptionTable(smState); err != nil { return err } if l.builder.Version() >= classfilebuilder.VersionJava7 { - if err := l.emitStackMapTable(); err != nil { + if err := l.emitStackMapTable(smState); err != nil { return err } } @@ -179,6 +252,33 @@ func (l *methodLowerer) lower() error { return nil } +func (l *methodLowerer) markLabel(label *classfilebuilder.Label) *classfilebuilder.Code { + if l.labelOp != nil && label != nil { + l.labelOp[label] = l.code.InstructionCount() + } + return l.code.Mark(label) +} + +func (l *methodLowerer) markThrowEnd() { + if l.index < 0 || l.index >= len(l.insnThrowEndLabel) { + return + } + if l.insnThrowEndLabel[l.index] != nil || !ir.MayThrow(l.method.Instructions[l.index].Opcode) { + return + } + startLabel := l.insnStartLabel[l.index] + if startLabel == nil { + return + } + startOp, ok := l.labelOp[startLabel] + if !ok || l.code.InstructionCount() <= startOp { + return + } + end := l.code.NewLabel() + l.markLabel(end) + l.insnThrowEndLabel[l.index] = end +} + // prepareAddressLabels binds a JVM label to every DEX address that debug data // refers to, so line numbers and local ranges survive branch widening. // assignHomesLegacy gives every DEX register a JVM local. A register that ever holds @@ -187,6 +287,11 @@ func (l *methodLowerer) lower() error { func (l *methodLowerer) assignHomesLegacy() error { l.webSplitting = false l.polySlots = nil + l.webPolySlots = nil + l.webPolyMask = nil + l.webZeroKind = nil + l.webSingleZeroKind = nil + l.pinnedZeroKind = nil l.paramPrologueSlot = nil registerCount := int(l.method.Code.RegistersSize) widths := make([]int, registerCount) @@ -278,14 +383,97 @@ func (l *methodLowerer) assignHomesLegacy() error { l.homeSlots[register] = uint16(next) next += width } - for register, mask := range l.method.PolyZeroRegisters { - if mask == 0 || register >= registerCount || skipHome[register] { + regNarrowMask := make([]uint8, registerCount) + regHasWide := make([]bool, registerCount) + incomingReg := registerCount - int(l.method.Code.InsSize) + if l.encoded.AccessFlags&dexStatic == 0 { + if incomingReg >= 0 && incomingReg < registerCount { + regNarrowMask[incomingReg] |= ir.PolyZeroRef + } + incomingReg++ + } + for _, descriptor := range l.method.Proto.Parameters { + if incomingReg >= 0 && incomingReg < registerCount { + if fk, fkErr := fieldKind(descriptor); fkErr == nil { + if bit, wide := categoryMaskBit(fk, 0, descriptor); bit != 0 || wide { + regNarrowMask[incomingReg] |= bit + if wide { + regHasWide[incomingReg] = true + } + } + } + } + incomingReg += descriptorWords(descriptor) + } + for _, block := range l.method.Blocks { + if !block.Reachable { + continue + } + for _, idx := range block.Instructions { + _, effDefs := l.method.EffectsAt(idx) + var defReg int = -1 + if len(effDefs) > 0 { + defReg = int(effDefs[0]) + } else if def, ok := l.method.DefinitionAt(idx); ok && def.Register >= 0 { + defReg = int(def.Register) + } + if defReg >= 0 && defReg < registerCount { + cat := l.definitionCategoryAt(idx, uint16(defReg)) + if bit, wide := categoryMaskBit(cat.Kind, cat.Allocation, cat.Descriptor); bit != 0 || wide { + regNarrowMask[defReg] |= bit + if wide { + regHasWide[defReg] = true + } + } + } + uses, _ := l.method.EffectsAt(idx) + for _, u := range uses { + if int(u) >= registerCount { + continue + } + cat := l.method.CategoryAt(idx, u) + if cat.Kind == ir.WideUpper { + continue + } + if bit, wide := categoryMaskBit(cat.Kind, cat.Allocation, cat.Descriptor); bit != 0 || wide { + regNarrowMask[u] |= bit + if wide { + regHasWide[u] = true + } + } + } + } + } + for register := 0; register < registerCount; register++ { + if skipHome[register] { + continue + } + var mask uint8 + if register < len(l.method.PolyZeroRegisters) { + mask = l.method.PolyZeroRegisters[register] + } + if hasMultipleNarrowBits(regNarrowMask[register]) || (regNarrowMask[register] != 0 && regHasWide[register]) { + mask |= regNarrowMask[register] + } + if !hasMultipleNarrowBits(regNarrowMask[register]) && !regHasWide[register] && (register >= len(l.method.PolyZeroRegisters) || l.method.PolyZeroRegisters[register] == 0) { + if regNarrowMask[register] == ir.PolyZeroInt || regNarrowMask[register] == ir.PolyZeroFloat { + if l.pinnedZeroKind == nil { + l.pinnedZeroKind = make(map[uint16]ir.CategoryKind) + } + k := ir.Int + if regNarrowMask[register] == ir.PolyZeroFloat { + k = ir.Float + } + l.pinnedZeroKind[uint16(register)] = k + } + } + if mask == 0 { continue } if l.polySlots == nil { l.polySlots = make(map[polySlotKey]uint16) } - first := true + first := widths[register] == 1 && !regHasWide[register] for _, entry := range []struct { bit uint8 kind classfilebuilder.LocalKind @@ -311,6 +499,27 @@ func (l *methodLowerer) assignHomesLegacy() error { l.polySlots[polySlotKey{reg: uint16(register), kind: entry.kind}] = slot } } + for _, block := range l.method.Blocks { + if !block.Reachable { + continue + } + for _, idx := range block.Instructions { + insn := &l.method.Instructions[idx] + if insn.Opcode < 0x12 || insn.Opcode > 0x15 || insn.Literal != 0 || len(insn.Regs) == 0 { + continue + } + r := insn.Regs[0] + if k, ok := l.pinnedZeroKind[r]; ok { + defCat := l.definitionCategoryAt(idx, r) + if defCat.Kind == ir.Null && defCat.Allocation == 0 { + if l.webZeroKind == nil { + l.webZeroKind = make(map[int]ir.CategoryKind) + } + l.webZeroKind[idx] = k + } + } + } + } if int(l.homeBase)+next > math.MaxUint16 { return fmt.Errorf("incoming arguments and DEX register homes require %d locals", int(l.homeBase)+next) } @@ -357,16 +566,22 @@ func (l *methodLowerer) prepareAddressLabels() { } } -// emitExceptionTable records every DEX try item as JVM exception-table -// entries. Handler order is preserved: typed handlers first, then catch-all. -func (l *methodLowerer) emitExceptionTable() error { +// emitExceptionTable records narrowed JVM exception-table entries covering only +// throwing instructions while coalescing safe intermediate non-throwing ranges +// whose stackmap frames stay compatible with every active catch handler. +func (l *methodLowerer) emitExceptionTable(state *stackMapState) error { for _, try := range l.method.Code.Tries { - start := l.addressLabels[try.StartAddress] - end := l.addressLabels[try.StartAddress+uint32(try.InstructionCount)] - if start == nil || end == nil { - return methodDiagnostic(l.method.Context, nil, "try", fmt.Errorf("try item [%d,%d) has no bound labels", try.StartAddress, try.StartAddress+uint32(try.InstructionCount))) + tryStart := try.StartAddress + tryEnd := try.StartAddress + uint32(try.InstructionCount) + if l.addressLabels[tryStart] == nil || l.addressLabels[tryEnd] == nil { + return methodDiagnostic(l.method.Context, nil, "try", fmt.Errorf("try item [%d,%d) has no bound labels", tryStart, tryEnd)) } - emit := func(address uint32, catchType string) error { + type resolvedHandler struct { + handler *classfilebuilder.Label + class string + } + resolved := make([]resolvedHandler, 0, len(try.Handler.Handlers)+1) + resolve := func(address uint32, catchType string) error { handler := l.labels[address] if handler == nil { return methodDiagnostic(l.method.Context, nil, "try", fmt.Errorf("handler address %d is not a basic block", address)) @@ -385,19 +600,152 @@ func (l *methodLowerer) emitExceptionTable() error { } class = name } - l.code.Catch(start, end, handler, class) + resolved = append(resolved, resolvedHandler{handler: handler, class: class}) return nil } for _, handler := range try.Handler.Handlers { - if err := emit(handler.Address, handler.Type); err != nil { + if err := resolve(handler.Address, handler.Type); err != nil { return err } } if try.Handler.CatchAllAddress != nil { - if err := emit(*try.Handler.CatchAllAddress, ""); err != nil { + if err := resolve(*try.Handler.CatchAllAddress, ""); err != nil { return err } } + + var handlerFrames []slotFrame + canCoalesce := state != nil + if canCoalesce { + collectFrame := func(addr uint32) { + if hb, ok := state.blockByStart[addr]; ok && state.visited[hb] { + handlerFrames = append(handlerFrames, state.in[hb]) + } else { + canCoalesce = false + } + } + for _, handler := range try.Handler.Handlers { + collectFrame(handler.Address) + } + if try.Handler.CatchAllAddress != nil { + collectFrame(*try.Handler.CatchAllAddress) + } + if len(handlerFrames) == 0 { + canCoalesce = false + } + } + compatibleFrame := func(frame slotFrame) bool { + if !canCoalesce || frame == nil { + return false + } + for _, hf := range handlerFrames { + if !l.slotFrameCompatibleWithHandler(frame, hf) { + return false + } + } + return true + } + + type labelRun struct { + start, end *classfilebuilder.Label + } + var runs []labelRun + var curStart, curEnd *classfilebuilder.Label + hasOpen := false + flush := func() { + if hasOpen { + runs = append(runs, labelRun{start: curStart, end: curEnd}) + hasOpen = false + } + } + for blockIdx, block := range l.method.Blocks { + var curFrame slotFrame + blockValid := canCoalesce && state.visited[blockIdx] + if blockValid { + curFrame = cloneSlotFrame(state.in[blockIdx]) + if hasOpen && !compatibleFrame(curFrame) { + flush() + } + } else { + flush() + } + for _, index := range block.Instructions { + insn := &l.method.Instructions[index] + inTry := insn.Offset >= tryStart && insn.Offset < tryEnd + if !inTry { + flush() + if blockValid { + l.transferSlotFrame(blockIdx, index, curFrame, state.deferred, state.catchClassByAddr) + } + continue + } + alloc, isNew := l.allocationByNew[index] + protected := ir.MayThrow(insn.Opcode) && + !l.allocationAliasOps[index] && + !(isNew && alloc.Fused) && + !l.deferredInsn[index] + if !protected { + if hasOpen { + if !blockValid || !compatibleFrame(curFrame) { + flush() + } else { + l.transferSlotFrame(blockIdx, index, curFrame, state.deferred, state.catchClassByAddr) + if !compatibleFrame(curFrame) { + flush() + } + continue + } + } + if blockValid { + l.transferSlotFrame(blockIdx, index, curFrame, state.deferred, state.catchClassByAddr) + } + continue + } + s := l.insnStartLabel[index] + e := l.insnThrowEndLabel[index] + if e == nil { + e = l.insnEndLabel[index] + } + if s == nil || e == nil { + flush() + if blockValid { + l.transferSlotFrame(blockIdx, index, curFrame, state.deferred, state.catchClassByAddr) + } + continue + } + sOp, okS := l.labelOp[s] + eOp, okE := l.labelOp[e] + if !okS || !okE || sOp >= eOp { + flush() + if blockValid { + l.transferSlotFrame(blockIdx, index, curFrame, state.deferred, state.catchClassByAddr) + } + continue + } + if hasOpen && (l.labelOp[curEnd] == sOp || compatibleFrame(curFrame)) { + curEnd = e + } else { + flush() + curStart, curEnd = s, e + hasOpen = true + } + if blockValid { + l.transferSlotFrame(blockIdx, index, curFrame, state.deferred, state.catchClassByAddr) + if hasOpen && !compatibleFrame(curFrame) { + flush() + } + } else { + flush() + } + } + } + flush() + + for _, r := range runs { + for _, rh := range resolved { + l.code.Catch(r.start, r.end, rh.handler, rh.class) + } + } } return nil } @@ -436,7 +784,7 @@ func (l *methodLowerer) emitHandlerTrampolines() { continue } label := l.code.NewLabel() - l.code.Mark(label).Emit(classfilebuilder.POP) + l.markLabel(label).Emit(classfilebuilder.POP) l.code.Branch(classfilebuilder.GOTO, l.labels[address]) l.handlerTrampolines[address] = label } @@ -444,23 +792,30 @@ func (l *methodLowerer) emitHandlerTrampolines() { } // emitDebug records line numbers, local variable names and parameter names from -// the original DEX debug_info. Positions that cannot be anchored to a real -// instruction boundary are dropped rather than misattributed. +// the original DEX debug_info. Positions that cannot be anchored strictly inside +// emitted JVM code are dropped rather than misattributed or failing assembly. func (l *methodLowerer) emitDebug() error { debug := l.method.Code.Debug if debug == nil { return nil } + codeUnits := uint32(len(l.method.Code.Instructions)) + totalOps := l.code.InstructionCount() for _, position := range debug.Positions { + if position.Line == 0 || position.Address >= codeUnits { + continue + } label := l.addressLabels[position.Address] - if label == nil || position.Line == 0 { - // R8 emits line 0 for synthetic code; a JVM LineNumberTable cannot - // represent it, so the entry is dropped instead of failing the class. + if label == nil { + // R8 emits line 0 or out-of-range positions for synthetic code; a + // JVM LineNumberTable requires start_pc < code_length. + continue + } + if opIdx, ok := l.labelOp[label]; !ok || opIdx >= totalOps { continue } l.code.Line(label, uint16(position.Line)) } - codeUnits := uint32(len(l.method.Code.Instructions)) startLabel := l.addressLabels[0] // The JVM rejects duplicate LocalVariableTable entries for the same slot and // range, so an explicitly described range keeps only that entry. @@ -484,6 +839,11 @@ func (l *methodLowerer) emitDebug() error { if start == nil || end == nil { continue } + startOp, okS := l.labelOp[start] + endOp, okE := l.labelOp[end] + if !okS || !okE || startOp >= endOp { + continue + } slot, ok := l.debugWebSlot(local.Register, local.Start, local.End, kind) if !ok { continue @@ -499,6 +859,11 @@ func (l *methodLowerer) emitDebug() error { if l.endLabel == nil || startLabel == nil { return nil } + startOp, okS := l.labelOp[startLabel] + endOp, okE := l.labelOp[l.endLabel] + if !okS || !okE || startOp >= endOp { + return nil + } for index, name := range debug.ParameterNames { if index >= len(parameterRegisters) { break @@ -508,7 +873,11 @@ func (l *methodLowerer) emitDebug() error { if name == "" || register >= l.method.Code.RegistersSize { continue } - slot := l.prologueStoreSlot(register) + pk := classfilebuilder.RefLocal + if k, err := fieldKind(descriptor); err == nil { + pk = localKind(k) + } + slot := l.prologueStoreSlot(register, pk) if l.directParamSlots[register] >= 0 { slot = uint16(l.directParamSlots[register]) } else if l.webSplitting && !l.webPinned[register] && l.paramPrologueSlot[register] < 0 { @@ -580,11 +949,17 @@ func (l *methodLowerer) validateMoveResults() error { return nil } -func (l *methodLowerer) prologueStoreSlot(register uint16) uint16 { +func (l *methodLowerer) prologueStoreSlot(register uint16, kind classfilebuilder.LocalKind) uint16 { if l.webSplitting && int(register) < len(l.paramPrologueSlot) && l.paramPrologueSlot[register] >= 0 { + if kind != classfilebuilder.LongLocal && kind != classfilebuilder.DoubleLocal && + int(register) < len(l.entryDefByReg) && l.entryDefByReg[register] >= 0 { + if slot, ok := l.webPolySlots[webPolyKey{root: l.ufFindRoot(l.entryDefByReg[register]), kind: kind}]; ok { + return slot + } + } return uint16(l.paramPrologueSlot[register]) } - return l.home(register) + return l.slotFor(register, kind) } func (l *methodLowerer) emitPrologue() error { @@ -592,7 +967,7 @@ func (l *methodLowerer) emitPrologue() error { jvmLocal := uint16(0) if l.encoded.AccessFlags&dexStatic == 0 { if int(parameterRegister) >= len(l.directParamSlots) || l.directParamSlots[parameterRegister] < 0 { - l.code.Load(classfilebuilder.RefLocal, jvmLocal).Store(classfilebuilder.RefLocal, l.prologueStoreSlot(parameterRegister)) + l.code.Load(classfilebuilder.RefLocal, jvmLocal).Store(classfilebuilder.RefLocal, l.prologueStoreSlot(parameterRegister, classfilebuilder.RefLocal)) } parameterRegister++ jvmLocal++ @@ -605,7 +980,7 @@ func (l *methodLowerer) emitPrologue() error { words := uint16(kind.Words()) if int(parameterRegister) >= len(l.directParamSlots) || l.directParamSlots[parameterRegister] < 0 { local := localKind(kind) - l.code.Load(local, jvmLocal).Store(local, l.prologueStoreSlot(parameterRegister)) + l.code.Load(local, jvmLocal).Store(local, l.prologueStoreSlot(parameterRegister, local)) } parameterRegister += words jvmLocal += words @@ -659,22 +1034,25 @@ func (l *methodLowerer) emitInstruction(index int) error { case instruction.Opcode == 0x11: l.load(instruction.Regs[0]).Emit(classfilebuilder.ARETURN) case instruction.Opcode >= 0x12 && instruction.Opcode <= 0x15: - if defCat := l.definitionCategory(instruction.Regs[0]); defCat.Kind == ir.Null && defCat.Allocation == ir.PolyZeroAllocation && instruction.Literal == 0 { - stored := false - if slot, ok := l.polySlots[polySlotKey{reg: instruction.Regs[0], kind: classfilebuilder.RefLocal}]; ok { - l.code.Emit(classfilebuilder.ACONST_NULL).Store(classfilebuilder.RefLocal, slot) - stored = true - } - if slot, ok := l.polySlots[polySlotKey{reg: instruction.Regs[0], kind: classfilebuilder.IntLocal}]; ok { - l.code.Emit(classfilebuilder.ICONST_0).Store(classfilebuilder.IntLocal, slot) - stored = true - } - if slot, ok := l.polySlots[polySlotKey{reg: instruction.Regs[0], kind: classfilebuilder.FloatLocal}]; ok { - l.code.Emit(classfilebuilder.FCONST_0).Store(classfilebuilder.FloatLocal, slot) - stored = true - } - if stored { - return nil + if instruction.Literal == 0 { + if defCat := l.definitionCategory(instruction.Regs[0]); defCat.Kind == ir.Null { + stored := false + for _, entry := range []struct { + lk classfilebuilder.LocalKind + op classfilebuilder.Opcode + }{ + {classfilebuilder.RefLocal, classfilebuilder.ACONST_NULL}, + {classfilebuilder.IntLocal, classfilebuilder.ICONST_0}, + {classfilebuilder.FloatLocal, classfilebuilder.FCONST_0}, + } { + if slot, ok := l.slotIfCompanion(l.index, instruction.Regs[0], entry.lk, true); ok { + l.code.Emit(entry.op).Store(entry.lk, slot) + stored = true + } + } + if stored { + return nil + } } } if err := l.pushDexInt(instruction.Regs[0], int32(instruction.Literal)); err != nil { @@ -750,12 +1128,9 @@ func (l *methodLowerer) emitInstruction(index int) error { } func (l *methodLowerer) emitMove(instruction *ir.Instruction) error { - kind := l.method.CategoryAt(l.index, instruction.Regs[0]).Kind - if definition, ok := l.method.DefinitionAt(l.index); ok && definition.Register == int32(instruction.Regs[0]) { - kind = definition.Category.Kind - } + kind := l.resolvedDefCategoryAt(l.index, instruction.Regs[0]).Kind if kind == ir.Unknown { - kind = l.method.CategoryAt(l.index, instruction.Regs[1]).Kind + kind = l.resolvedUseCategoryAt(l.index, instruction.Regs[1]).Kind } if kind == ir.Unknown { return nil @@ -777,23 +1152,45 @@ func (l *methodLowerer) emitMove(instruction *ir.Instruction) error { } } if instruction.Opcode <= 0x03 { - if srcCat := l.method.CategoryAt(l.index, instruction.Regs[1]); srcCat.Kind == ir.Null && srcCat.Allocation == ir.PolyZeroAllocation { + if rawSrc := l.method.CategoryAt(l.index, instruction.Regs[1]); rawSrc.Kind == ir.Null { dst, src := instruction.Regs[0], instruction.Regs[1] - copied := false + hasDstPoly := false for _, lk := range []classfilebuilder.LocalKind{classfilebuilder.RefLocal, classfilebuilder.IntLocal, classfilebuilder.FloatLocal} { - dstSlot, ok := l.polySlots[polySlotKey{reg: dst, kind: lk}] - if !ok { - continue + if _, ok := l.slotIfCompanion(l.index, dst, lk, true); ok { + hasDstPoly = true + break } - srcSlot := l.slotFor(src, lk) - l.code.Load(lk, srcSlot).Store(lk, dstSlot) - copied = true } - if !copied { - // Dead polymorphic-zero move whose destination is never read. - l.code.Emit(classfilebuilder.ACONST_NULL).Store(classfilebuilder.RefLocal, l.home(dst)) + srcResolvedLK := localKind(l.resolvedUseCategoryAt(l.index, src).Kind) + if hasDstPoly { + for _, lk := range []classfilebuilder.LocalKind{classfilebuilder.RefLocal, classfilebuilder.IntLocal, classfilebuilder.FloatLocal} { + dstSlot, ok := l.slotIfCompanion(l.index, dst, lk, true) + if !ok { + continue + } + if srcSlot, srcOK := l.slotIfCompanion(l.index, src, lk, false); srcOK { + l.code.Load(lk, srcSlot).Store(lk, dstSlot) + } else if srcResolvedLK == lk && rawSrc.Allocation != ir.PolyZeroAllocation { + l.code.Load(lk, l.loadSlotAt(l.index, src, lk)).Store(lk, dstSlot) + } else { + l.code.Emit(zeroOpcodeForLocalKind(lk)).Store(lk, dstSlot) + } + } + l.registerDescriptor[dst] = l.registerDescriptor[src] + return nil + } + dstLK := localKind(kind) + dstSlot := l.storeSlotAt(l.index, dst, dstLK) + if srcSlot, srcOK := l.slotIfCompanion(l.index, src, dstLK, false); srcOK { + l.code.Load(dstLK, srcSlot).Store(dstLK, dstSlot) + } else if srcResolvedLK == dstLK && rawSrc.Allocation != ir.PolyZeroAllocation { + l.code.Load(dstLK, l.loadSlotAt(l.index, src, dstLK)).Store(dstLK, dstSlot) + } else { + l.code.Emit(zeroOpcodeForLocalKind(dstLK)).Store(dstLK, dstSlot) + } + if isReferenceKind(kind) { + l.registerDescriptor[dst] = l.registerDescriptor[src] } - l.registerDescriptor[dst] = l.registerDescriptor[src] return nil } } @@ -1099,8 +1496,11 @@ func (l *methodLowerer) emitFilledNewArray(index int, instruction *ir.Instructio } next := index + 1 if next >= len(l.method.Instructions) || l.method.Instructions[next].Opcode != 0x0c { - return methodDiagnostic(l.method.Context, instruction, "", fmt.Errorf("filled-new-array must be followed by move-result-object")) + l.markThrowEnd() + l.code.Emit(classfilebuilder.POP) + return nil } + l.markThrowEnd() l.storeAt(l.method.Instructions[next].Regs[0], next) return nil } @@ -1129,10 +1529,13 @@ func (l *methodLowerer) emitArray(instruction *ir.Instruction) error { // The element type comes from the array register's flow type; DEX does not // encode it in the instruction. array := l.method.CategoryAt(l.index, instruction.Regs[1]) - if len(array.Descriptor) < 2 || array.Descriptor[0] != '[' { + component := "" + if len(array.Descriptor) >= 2 && array.Descriptor[0] == '[' { + component = array.Descriptor[1:] + } else if array.Kind != ir.Null && !(array.Kind == ir.Reference && array.Descriptor == "") { return methodDiagnostic(l.method.Context, instruction, "", fmt.Errorf("array register v%d has no array type", instruction.Regs[1])) } - op, err := arrayElementOpcode(instruction.Opcode, array.Descriptor[1:]) + op, err := arrayElementOpcode(instruction.Opcode, component) if err != nil { return methodDiagnostic(l.method.Context, instruction, "", err) } @@ -1172,7 +1575,7 @@ func (l *methodLowerer) emitAllocationNew(instruction *ir.Instruction, allocatio return methodDiagnostic(l.method.Context, instruction, "", err) } newLabel := l.code.NewLabel() - l.code.Mark(newLabel) + l.markLabel(newLabel) if l.allocationNewLabels != nil { l.allocationNewLabels[allocation.ID] = newLabel } @@ -1206,6 +1609,9 @@ func (l *methodLowerer) emitAllocationFused(instruction *ir.Instruction, allocat if err := l.loadArguments(instruction.Regs, proto, 1); err != nil { return methodDiagnostic(l.method.Context, instruction, "", err) } + for i := 0; i < instruction.ExtraNullArgs; i++ { + l.code.Emit(classfilebuilder.ACONST_NULL) + } l.code.CP(classfilebuilder.INVOKESPECIAL, methodIndex) first := allocation.AliasRegisters[0] l.store(first) @@ -1237,6 +1643,9 @@ func (l *methodLowerer) emitAllocationCtor(instruction *ir.Instruction, allocati if err := l.loadArguments(instruction.Regs, proto, 1); err != nil { return methodDiagnostic(l.method.Context, instruction, "", err) } + for i := 0; i < instruction.ExtraNullArgs; i++ { + l.code.Emit(classfilebuilder.ACONST_NULL) + } l.code.CP(classfilebuilder.INVOKESPECIAL, methodIndex) return nil } @@ -1322,8 +1731,8 @@ func (l *methodLowerer) emitCompare(instruction *ir.Instruction) error { func (l *methodLowerer) emitIf(instruction *ir.Instruction) error { var opcode classfilebuilder.Opcode if instruction.Opcode <= 0x37 { - left := l.method.CategoryAt(l.index, instruction.Regs[0]).Kind - right := l.method.CategoryAt(l.index, instruction.Regs[1]).Kind + left := l.resolvedUseCategoryAt(l.index, instruction.Regs[0]).Kind + right := l.resolvedUseCategoryAt(l.index, instruction.Regs[1]).Kind leftNonNullRef := isReferenceKind(left) && left != ir.Null rightNonNullRef := isReferenceKind(right) && right != ir.Null if (leftNonNullRef || rightNonNullRef) && instruction.Opcode > 0x33 { @@ -1343,10 +1752,10 @@ func (l *methodLowerer) emitIf(instruction *ir.Instruction) error { if !isReferenceKind(left) || !isReferenceKind(right) { return methodDiagnostic(l.method.Context, instruction, "", fmt.Errorf("comparison requires int or reference registers, got %s and %s", left, right)) } - _, hasRef0 := l.polySlots[polySlotKey{reg: instruction.Regs[0], kind: classfilebuilder.RefLocal}] - _, hasRef1 := l.polySlots[polySlotKey{reg: instruction.Regs[1], kind: classfilebuilder.RefLocal}] - _, hasInt0 := l.polySlots[polySlotKey{reg: instruction.Regs[0], kind: classfilebuilder.IntLocal}] - _, hasInt1 := l.polySlots[polySlotKey{reg: instruction.Regs[1], kind: classfilebuilder.IntLocal}] + _, hasRef0 := l.slotIfCompanion(l.index, instruction.Regs[0], classfilebuilder.RefLocal, false) + _, hasRef1 := l.slotIfCompanion(l.index, instruction.Regs[1], classfilebuilder.RefLocal, false) + _, hasInt0 := l.slotIfCompanion(l.index, instruction.Regs[0], classfilebuilder.IntLocal, false) + _, hasInt1 := l.slotIfCompanion(l.index, instruction.Regs[1], classfilebuilder.IntLocal, false) if left == ir.Null && right == ir.Null && (hasInt0 || hasInt1) && !hasRef0 && !hasRef1 { l.loadAs(instruction.Regs[0], classfilebuilder.IntLocal) l.loadAs(instruction.Regs[1], classfilebuilder.IntLocal) @@ -1358,7 +1767,7 @@ func (l *methodLowerer) emitIf(instruction *ir.Instruction) error { } } } else { - kind := l.method.CategoryAt(l.index, instruction.Regs[0]).Kind + kind := l.resolvedUseCategoryAt(l.index, instruction.Regs[0]).Kind if instruction.Opcode >= 0x3a { if isReferenceKind(kind) && kind != ir.Null { return methodDiagnostic(l.method.Context, instruction, "", fmt.Errorf("ordered reference comparison is invalid")) @@ -1369,8 +1778,8 @@ func (l *methodLowerer) emitIf(instruction *ir.Instruction) error { l.loadAs(instruction.Regs[0], classfilebuilder.IntLocal) opcode = classfilebuilder.IFEQ + classfilebuilder.Opcode(instruction.Opcode-0x38) } else if kind == ir.Null { - _, hasRef := l.polySlots[polySlotKey{reg: instruction.Regs[0], kind: classfilebuilder.RefLocal}] - _, hasInt := l.polySlots[polySlotKey{reg: instruction.Regs[0], kind: classfilebuilder.IntLocal}] + _, hasRef := l.slotIfCompanion(l.index, instruction.Regs[0], classfilebuilder.RefLocal, false) + _, hasInt := l.slotIfCompanion(l.index, instruction.Regs[0], classfilebuilder.IntLocal, false) if hasInt && !hasRef { l.loadAs(instruction.Regs[0], classfilebuilder.IntLocal) opcode = classfilebuilder.IFEQ + classfilebuilder.Opcode(instruction.Opcode-0x38) @@ -1648,6 +2057,9 @@ func (l *methodLowerer) emitInvoke(index int, instruction *ir.Instruction) error if err := l.loadArguments(instruction.Regs, proto, position); err != nil { return methodDiagnostic(l.method.Context, instruction, "", err) } + for i := 0; i < instruction.ExtraNullArgs; i++ { + l.code.Emit(classfilebuilder.ACONST_NULL) + } if isInterfaceInvoke(instruction.Opcode) { constant, err := l.builder.Pool().InterfaceMethodref(owner, callee.Name, descriptor) if err != nil { @@ -1684,6 +2096,7 @@ func (l *methodLowerer) emitInvokeResult(index int, instruction *ir.Instruction, // The move-result instruction owns the destination category; the // invoke itself defines nothing, so the pre-invoke category of that // register is unrelated to the returned value. + l.markThrowEnd() l.storeAt(next.Regs[0], index+1) if result == ir.Reference { l.registerDescriptor[next.Regs[0]] = returnType @@ -1691,6 +2104,7 @@ func (l *methodLowerer) emitInvokeResult(index int, instruction *ir.Instruction, return nil } } + l.markThrowEnd() if result.Words() == 2 { l.code.Emit(classfilebuilder.POP2) } else { @@ -1900,13 +2314,74 @@ func (l *methodLowerer) lowerBootstrapArg(value model.EncodedValue) (uint16, err } } +func (l *methodLowerer) resolvedDefCategoryAt(index int, register uint16) ir.Category { + category := l.definitionCategoryAt(index, register) + if category.Kind == ir.Null && category.Allocation == 0 { + if k, ok := l.webZeroKind[index]; ok { + return ir.Category{Kind: k} + } + if k, ok := l.resolvedZeroKindForUse(index, register, true); ok { + return ir.Category{Kind: k} + } + } + return category +} + +func (l *methodLowerer) resolvedUseCategoryAt(index int, register uint16) ir.Category { + category := l.method.CategoryAt(index, register) + if category.Kind == ir.Null && category.Allocation == 0 { + if k, ok := l.resolvedZeroKindForUse(index, register, false); ok { + return ir.Category{Kind: k} + } + } + return category +} + +func (l *methodLowerer) resolvedZeroKindForUse(index int, register uint16, isDef bool) (ir.CategoryKind, bool) { + if l.webSplitting && int(register) < len(l.webPinned) && !l.webPinned[register] { + var d int + var ok bool + if isDef { + d, ok = l.instDefID[regUseKey{index: index, reg: register}] + } else { + d, ok = l.useWebDef[regUseKey{index: index, reg: register}] + } + if ok { + if k, exists := l.webSingleZeroKind[l.ufFindRoot(d)]; exists { + return k, true + } + } + return ir.Unknown, false + } + if k, exists := l.pinnedZeroKind[register]; exists { + return k, true + } + return ir.Unknown, false +} + +func (l *methodLowerer) slotIfCompanion(index int, register uint16, lk classfilebuilder.LocalKind, isDef bool) (uint16, bool) { + if l.webSplitting && int(register) < len(l.webPinned) && !l.webPinned[register] && + lk != classfilebuilder.LongLocal && lk != classfilebuilder.DoubleLocal { + var d int + var ok bool + if isDef { + d, ok = l.instDefID[regUseKey{index: index, reg: register}] + } else { + d, ok = l.useWebDef[regUseKey{index: index, reg: register}] + } + if ok { + slot, exists := l.webPolySlots[webPolyKey{root: l.ufFindRoot(d), kind: lk}] + return slot, exists + } + } + slot, ok := l.polySlots[polySlotKey{reg: register, kind: lk}] + return slot, ok +} + // definitionCategory returns the category an instruction writes into the // register, falling back to the category the register carried before it. func (l *methodLowerer) definitionCategory(register uint16) ir.Category { - if definition, ok := l.method.DefinitionAt(l.index); ok && definition.Register == int32(register) { - return definition.Category - } - return l.method.CategoryAt(l.index, register) + return l.resolvedDefCategoryAt(l.index, register) } func (l *methodLowerer) pushDexInt(register uint16, value int32) error { @@ -2007,15 +2482,36 @@ func (l *methodLowerer) slotFor(register uint16, kind classfilebuilder.LocalKind } func (l *methodLowerer) loadAs(register uint16, expected classfilebuilder.LocalKind) *classfilebuilder.Code { - kind := l.method.CategoryAt(l.index, register).Kind + if rawCat := l.method.CategoryAt(l.index, register); rawCat.Kind == ir.Null { + if slot, ok := l.slotIfCompanion(l.index, register, expected, false); ok { + return l.code.Load(expected, slot) + } + resolved := l.resolvedUseCategoryAt(l.index, register).Kind + if localKind(resolved) == expected && rawCat.Allocation != ir.PolyZeroAllocation { + return l.code.Load(expected, l.loadSlotAt(l.index, register, expected)) + } + return l.code.Emit(zeroOpcodeForLocalKind(expected)) + } + kind := l.resolvedUseCategoryAt(l.index, register).Kind if kind != ir.Null { expected = localKind(kind) } return l.code.Load(expected, l.loadSlotAt(l.index, register, expected)) } +func zeroOpcodeForLocalKind(lk classfilebuilder.LocalKind) classfilebuilder.Opcode { + switch lk { + case classfilebuilder.IntLocal: + return classfilebuilder.ICONST_0 + case classfilebuilder.FloatLocal: + return classfilebuilder.FCONST_0 + default: + return classfilebuilder.ACONST_NULL + } +} + func (l *methodLowerer) load(register uint16) *classfilebuilder.Code { - return l.loadAs(register, localKind(l.method.CategoryAt(l.index, register).Kind)) + return l.loadAs(register, localKind(l.resolvedUseCategoryAt(l.index, register).Kind)) } func (l *methodLowerer) store(register uint16) *classfilebuilder.Code { @@ -2025,10 +2521,8 @@ func (l *methodLowerer) store(register uint16) *classfilebuilder.Code { // storeAt stores using the category defined by the given instruction, which is // how an invoke or filled-new-array writes its move-result destination. func (l *methodLowerer) storeAt(register uint16, index int) *classfilebuilder.Code { - category := l.method.CategoryAt(index, register) - if definition, ok := l.method.DefinitionAt(index); ok && definition.Register == int32(register) { - category = definition.Category - } + l.markThrowEnd() + category := l.resolvedDefCategoryAt(index, register) lk := localKind(category.Kind) return l.code.Store(lk, l.storeSlotAt(index, register, lk)) } @@ -2092,11 +2586,18 @@ func isBranchOpcode(opcode byte) bool { return opcode >= 0x28 && opcode <= 0x2a || opcode >= 0x32 && opcode <= 0x3d } +func (l *methodLowerer) isDelegationSite(index int) bool { + if len(l.delegationSites) > 0 { + return l.delegationSites[index] + } + return index >= 0 && index == l.delegationIndex +} + // canDirectDeferredStore reports whether the stored value register and its // receiver remain unmodified between store.index and l.delegationIndex, so the // pre-delegation temporary copy can be elided safely. func (l *methodLowerer) canDirectDeferredStore(store *deferredStore) bool { - if jdecenv.Get("JDEC_DEX_DIRECT_DEFERRED_OFF") == "1" || l.delegationIndex < 0 || store.index < 0 || store.index >= l.delegationIndex { + if jdecenv.Get("JDEC_DEX_DIRECT_DEFERRED_OFF") == "1" || len(l.delegationSites) > 1 || l.delegationIndex < 0 || store.index < 0 || store.index >= l.delegationIndex { return false } startBlock := l.blockOfInstruction(store.index) @@ -2246,7 +2747,7 @@ func (l *methodLowerer) emitDeferredStore(store *deferredStore) error { } previous := l.index l.index = store.index - l.load(instruction.Regs[1]) + l.code.Load(classfilebuilder.RefLocal, 0) if store.direct { l.loadAs(store.register, localKind(store.category.Kind)) } else { diff --git a/dex2jar/lower/references.go b/dex2jar/lower/references.go index eb97f5f4..0026a8ff 100644 --- a/dex2jar/lower/references.go +++ b/dex2jar/lower/references.go @@ -384,7 +384,9 @@ func (l *methodLowerer) transferReferences(index int, state referenceState) { case instruction.Opcode == 0x46: var components descriptorSet for _, array := range state[instruction.Regs[1]] { - if strings.HasPrefix(array, "[") { + if array == nullDescriptor { + components = unionDescriptorSets(components, descriptorSet{nullDescriptor}) + } else if strings.HasPrefix(array, "[") { components = unionDescriptorSets(components, descriptorSet{array[1:]}) } } @@ -505,13 +507,20 @@ func (l *methodLowerer) provablyAssignable(actual, expected string) bool { } } index := l.classIndex() - if _, ok := index[expected]; !ok { + expectedClass, ok := index[expected] + if !ok { // The expected type lives outside the application. Proving the relation // needs the platform classpath the input was verified against, which the // DEX file does not carry; rejecting here would refuse valid code such as // String to CharSequence or IllegalArgumentException to Throwable. return true } + if expectedClass.AccessFlags&dexInterface != 0 { + // Under JVMS §4.10.1.2 verification assignability, every object reference + // is assignable to an interface type (runtime invokeinterface / checkcast + // enforces implementation). + return true + } // The expected type is declared in this application, so the declared // hierarchy must prove the relation. A platform ancestor cannot introduce an // application type, so an unresolved ancestor cannot rescue the assignment. diff --git a/dex2jar/lower/stackmap.go b/dex2jar/lower/stackmap.go index f9fea241..516e9d4e 100644 --- a/dex2jar/lower/stackmap.go +++ b/dex2jar/lower/stackmap.go @@ -15,6 +15,15 @@ type slotEntry struct { type slotFrame []slotEntry +type stackMapState struct { + entryFrame slotFrame + in []slotFrame + visited []bool + blockByStart map[uint32]int + catchClassByAddr map[uint32]string + deferred map[int]*deferredStore +} + func topSlotEntry() slotEntry { return slotEntry{vt: classfilebuilder.VerificationType{Tag: classfilebuilder.VerifyTop}} } @@ -113,6 +122,17 @@ func verifyTypeFromCategory(cat ir.Category) classfilebuilder.VerificationType { } } +func verifyTagForLocalKind(lk classfilebuilder.LocalKind) classfilebuilder.VerifyTag { + switch lk { + case classfilebuilder.IntLocal: + return classfilebuilder.VerifyInt + case classfilebuilder.FloatLocal: + return classfilebuilder.VerifyFloat + default: + return classfilebuilder.VerifyNull + } +} + func (l *methodLowerer) definitionCategoryAt(index int, register uint16) ir.Category { if definition, ok := l.method.DefinitionAt(index); ok && definition.Register == int32(register) { return definition.Category @@ -166,6 +186,66 @@ func (l *methodLowerer) commonVerifyClass(a, b string) string { return "java/lang/Object" } +func (l *methodLowerer) isVerifySubtype(sub, sup string) bool { + if sub == sup || sup == "java/lang/Object" { + return true + } + if sub == "" || sup == "" || strings.HasPrefix(sub, "[") || strings.HasPrefix(sup, "[") { + return false + } + index := l.classIndex() + cur := "L" + sub + ";" + for step := 0; step < maxAssignabilityDepth; step++ { + c, ok := index[cur] + if !ok || c.Superclass == "" { + break + } + superInternal, err := objectInternalName(c.Superclass) + if err != nil { + break + } + if superInternal == sup { + return true + } + cur = c.Superclass + } + return false +} + +func (l *methodLowerer) slotFrameCompatibleWithHandler(cur, handler slotFrame) bool { + for s := 0; s < len(handler); s++ { + h := handler[s] + if h.cat2Tail || h.vt.Tag == classfilebuilder.VerifyTop { + continue + } + if s >= len(cur) { + return false + } + c := cur[s] + if c.cat2Tail || c.vt.Tag == classfilebuilder.VerifyTop { + return false + } + switch h.vt.Tag { + case classfilebuilder.VerifyObject: + if c.vt.Tag == classfilebuilder.VerifyNull { + continue + } + if c.vt.Tag != classfilebuilder.VerifyObject || !l.isVerifySubtype(c.vt.Class, h.vt.Class) { + return false + } + case classfilebuilder.VerifyUninitialized: + if c.vt.Tag != classfilebuilder.VerifyUninitialized || c.vt.NewAt != h.vt.NewAt { + return false + } + default: + if c.vt.Tag != h.vt.Tag { + return false + } + } + } + return true +} + func (l *methodLowerer) isProvablyThrowable(internalName string) bool { if internalName == "java/lang/Throwable" || internalName == "java/lang/Exception" || internalName == "java/lang/RuntimeException" || internalName == "java/lang/Error" { @@ -265,6 +345,9 @@ func compactStackMapLocals(frame slotFrame) []classfilebuilder.VerificationType } func (l *methodLowerer) transferSlotFrame(blockIdx, insnIdx int, frame slotFrame, deferred map[int]*deferredStore, catchClassByAddr map[uint32]string) { + if l.fusedNoLocals[insnIdx] { + return + } insn := &l.method.Instructions[insnIdx] if store, ok := deferred[insnIdx]; ok { if !store.direct { @@ -313,7 +396,7 @@ func (l *methodLowerer) transferSlotFrame(blockIdx, insnIdx int, frame slotFrame } return } - if insnIdx == l.delegationIndex { + if l.isDelegationSite(insnIdx) { thisName, err := objectInternalName(l.class.Descriptor) if err != nil { thisName = "java/lang/Object" @@ -329,49 +412,66 @@ func (l *methodLowerer) transferSlotFrame(blockIdx, insnIdx int, frame slotFrame switch { case insn.Opcode >= 0x01 && insn.Opcode <= 0x09: - kind := l.method.CategoryAt(insnIdx, insn.Regs[0]).Kind - if def, ok := l.method.DefinitionAt(insnIdx); ok && def.Register == int32(insn.Regs[0]) { - kind = def.Category.Kind - } + kind := l.resolvedDefCategoryAt(insnIdx, insn.Regs[0]).Kind if kind == ir.Unknown { - kind = l.method.CategoryAt(insnIdx, insn.Regs[1]).Kind + kind = l.resolvedUseCategoryAt(insnIdx, insn.Regs[1]).Kind } if kind == ir.Unknown { return } if insn.Opcode <= 0x03 { - if srcCat := l.method.CategoryAt(insnIdx, insn.Regs[1]); srcCat.Kind == ir.Null && srcCat.Allocation == ir.PolyZeroAllocation { + if rawSrc := l.method.CategoryAt(insnIdx, insn.Regs[1]); rawSrc.Kind == ir.Null { dst, src := insn.Regs[0], insn.Regs[1] - copied := false - for _, entry := range []struct { - lk classfilebuilder.LocalKind - tag classfilebuilder.VerifyTag - }{ - {classfilebuilder.RefLocal, classfilebuilder.VerifyNull}, - {classfilebuilder.IntLocal, classfilebuilder.VerifyInt}, - {classfilebuilder.FloatLocal, classfilebuilder.VerifyFloat}, - } { - dstSlot, ok := l.polySlots[polySlotKey{reg: dst, kind: entry.lk}] - if !ok { - continue + hasDstPoly := false + for _, lk := range []classfilebuilder.LocalKind{classfilebuilder.RefLocal, classfilebuilder.IntLocal, classfilebuilder.FloatLocal} { + if _, ok := l.slotIfCompanion(insnIdx, dst, lk, true); ok { + hasDstPoly = true + break + } + } + srcResolvedLK := localKind(l.resolvedUseCategoryAt(insnIdx, src).Kind) + if hasDstPoly { + for _, lk := range []classfilebuilder.LocalKind{classfilebuilder.RefLocal, classfilebuilder.IntLocal, classfilebuilder.FloatLocal} { + dstSlot, ok := l.slotIfCompanion(insnIdx, dst, lk, true) + if !ok { + continue + } + vt := classfilebuilder.VerificationType{Tag: verifyTagForLocalKind(lk)} + if srcSlot, srcOK := l.slotIfCompanion(insnIdx, src, lk, false); srcOK { + if int(srcSlot) < len(frame) && frame[srcSlot].vt.Tag != classfilebuilder.VerifyTop { + vt = frame[srcSlot].vt + } + } else if srcResolvedLK == lk && rawSrc.Allocation != ir.PolyZeroAllocation { + srcSlot := int(l.loadSlotAt(insnIdx, src, lk)) + if srcSlot >= 0 && srcSlot < len(frame) && frame[srcSlot].vt.Tag != classfilebuilder.VerifyTop { + vt = frame[srcSlot].vt + } + } + setSlot(frame, int(dstSlot), vt) + } + return + } + dstLK := localKind(kind) + dstSlot := int(l.storeSlotAt(insnIdx, dst, dstLK)) + vt := classfilebuilder.VerificationType{Tag: verifyTagForLocalKind(dstLK)} + if srcSlot, srcOK := l.slotIfCompanion(insnIdx, src, dstLK, false); srcOK { + if int(srcSlot) < len(frame) && frame[srcSlot].vt.Tag != classfilebuilder.VerifyTop { + vt = frame[srcSlot].vt } - srcSlot := int(l.slotFor(src, entry.lk)) - vt := classfilebuilder.VerificationType{Tag: entry.tag} + } else if srcResolvedLK == dstLK && rawSrc.Allocation != ir.PolyZeroAllocation { + srcSlot := int(l.loadSlotAt(insnIdx, src, dstLK)) if srcSlot >= 0 && srcSlot < len(frame) && frame[srcSlot].vt.Tag != classfilebuilder.VerifyTop { vt = frame[srcSlot].vt } - setSlot(frame, int(dstSlot), vt) - copied = true - } - if !copied { - setSlot(frame, int(l.home(dst)), classfilebuilder.VerificationType{Tag: classfilebuilder.VerifyNull}) } + setSlot(frame, dstSlot, vt) return } } - srcLK := localKind(l.method.CategoryAt(insnIdx, insn.Regs[1]).Kind) + srcCat := l.resolvedUseCategoryAt(insnIdx, insn.Regs[1]) + srcLK := localKind(srcCat.Kind) srcSlot := int(l.loadSlotAt(insnIdx, insn.Regs[1], srcLK)) - dstCat := l.definitionCategoryAt(insnIdx, insn.Regs[0]) + dstCat := l.resolvedDefCategoryAt(insnIdx, insn.Regs[0]) dstLK := localKind(dstCat.Kind) dstSlot := int(l.storeSlotAt(insnIdx, insn.Regs[0], dstLK)) vt := verifyTypeFromCategory(dstCat) @@ -390,20 +490,21 @@ func (l *methodLowerer) transferSlotFrame(blockIdx, insnIdx int, frame slotFrame setSlot(frame, dstSlot, classfilebuilder.VerificationType{Tag: classfilebuilder.VerifyObject, Class: catchCls}) case insn.Opcode >= 0x12 && insn.Opcode <= 0x15: - defCat := l.definitionCategoryAt(insnIdx, insn.Regs[0]) - if defCat.Kind == ir.Null && defCat.Allocation == ir.PolyZeroAllocation && insn.Literal == 0 { + defCat := l.resolvedDefCategoryAt(insnIdx, insn.Regs[0]) + if defCat.Kind == ir.Null && insn.Literal == 0 { stored := false - if slot, ok := l.polySlots[polySlotKey{reg: insn.Regs[0], kind: classfilebuilder.RefLocal}]; ok { - setSlot(frame, int(slot), classfilebuilder.VerificationType{Tag: classfilebuilder.VerifyNull}) - stored = true - } - if slot, ok := l.polySlots[polySlotKey{reg: insn.Regs[0], kind: classfilebuilder.IntLocal}]; ok { - setSlot(frame, int(slot), classfilebuilder.VerificationType{Tag: classfilebuilder.VerifyInt}) - stored = true - } - if slot, ok := l.polySlots[polySlotKey{reg: insn.Regs[0], kind: classfilebuilder.FloatLocal}]; ok { - setSlot(frame, int(slot), classfilebuilder.VerificationType{Tag: classfilebuilder.VerifyFloat}) - stored = true + for _, entry := range []struct { + lk classfilebuilder.LocalKind + tag classfilebuilder.VerifyTag + }{ + {classfilebuilder.RefLocal, classfilebuilder.VerifyNull}, + {classfilebuilder.IntLocal, classfilebuilder.VerifyInt}, + {classfilebuilder.FloatLocal, classfilebuilder.VerifyFloat}, + } { + if slot, ok := l.slotIfCompanion(insnIdx, insn.Regs[0], entry.lk, true); ok { + setSlot(frame, int(slot), classfilebuilder.VerificationType{Tag: entry.tag}) + stored = true + } } if stored { return @@ -493,12 +594,16 @@ func (l *methodLowerer) transferSlotFrame(blockIdx, insnIdx int, frame slotFrame case insn.Opcode == 0x46: vt := classfilebuilder.VerificationType{Tag: classfilebuilder.VerifyObject, Class: "java/lang/Object"} arrSlot := int(l.loadSlotAt(insnIdx, insn.Regs[1], classfilebuilder.RefLocal)) - if arrSlot >= 0 && arrSlot < len(frame) && frame[arrSlot].vt.Tag == classfilebuilder.VerifyObject && + if arrSlot >= 0 && arrSlot < len(frame) && frame[arrSlot].vt.Tag == classfilebuilder.VerifyNull { + vt = classfilebuilder.VerificationType{Tag: classfilebuilder.VerifyNull} + } else if arrSlot >= 0 && arrSlot < len(frame) && frame[arrSlot].vt.Tag == classfilebuilder.VerifyObject && strings.HasPrefix(frame[arrSlot].vt.Class, "[") && len(frame[arrSlot].vt.Class) >= 2 { if elemVT, _, err := verifyTypeFromDescriptor(frame[arrSlot].vt.Class[1:]); err == nil { vt = elemVT } - } else if arr := l.method.CategoryAt(insnIdx, insn.Regs[1]); strings.HasPrefix(arr.Descriptor, "[") && len(arr.Descriptor) >= 2 { + } else if arr := l.method.CategoryAt(insnIdx, insn.Regs[1]); arr.Kind == ir.Null || (arr.Kind == ir.Reference && arr.Descriptor == "") { + vt = classfilebuilder.VerificationType{Tag: classfilebuilder.VerifyNull} + } else if strings.HasPrefix(arr.Descriptor, "[") && len(arr.Descriptor) >= 2 { if elemVT, _, err := verifyTypeFromDescriptor(arr.Descriptor[1:]); err == nil { vt = elemVT } @@ -546,9 +651,9 @@ func (l *methodLowerer) transferSlotFrame(blockIdx, insnIdx int, frame slotFrame } } -func (l *methodLowerer) emitStackMapTable() error { +func (l *methodLowerer) computeStackMapFrames() (*stackMapState, error) { if len(l.method.Blocks) == 0 { - return nil + return &stackMapState{}, nil } totalSlots := int(l.homeBase + l.homeLimit + l.tempLimit) entryFrame := make(slotFrame, totalSlots) @@ -572,7 +677,7 @@ func (l *methodLowerer) emitStackMapTable() error { for _, descriptor := range l.method.Proto.Parameters { vt, wide, err := verifyTypeFromDescriptor(descriptor) if err != nil { - return methodDiagnostic(l.method.Context, nil, "stackmap", err) + return nil, methodDiagnostic(l.method.Context, nil, "stackmap", err) } setSlot(entryFrame, slot, vt) slot++ @@ -586,7 +691,7 @@ func (l *methodLowerer) emitStackMapTable() error { jvmLocal := 0 if l.encoded.AccessFlags&dexStatic == 0 { if int(paramReg) >= len(l.directParamSlots) || l.directParamSlots[paramReg] < 0 { - setSlot(entryFrame, int(l.prologueStoreSlot(paramReg)), entryFrame[jvmLocal].vt) + setSlot(entryFrame, int(l.prologueStoreSlot(paramReg, classfilebuilder.RefLocal)), entryFrame[jvmLocal].vt) } paramReg++ jvmLocal++ @@ -594,11 +699,11 @@ func (l *methodLowerer) emitStackMapTable() error { for _, descriptor := range l.method.Proto.Parameters { kind, err := fieldKind(descriptor) if err != nil { - return methodDiagnostic(l.method.Context, nil, "stackmap", err) + return nil, methodDiagnostic(l.method.Context, nil, "stackmap", err) } words := kind.Words() if int(paramReg) >= len(l.directParamSlots) || l.directParamSlots[paramReg] < 0 { - setSlot(entryFrame, int(l.prologueStoreSlot(paramReg)), entryFrame[jvmLocal].vt) + setSlot(entryFrame, int(l.prologueStoreSlot(paramReg, localKind(kind))), entryFrame[jvmLocal].vt) } paramReg += uint16(words) jvmLocal += words @@ -647,8 +752,10 @@ func (l *methodLowerer) emitStackMapTable() error { startAddr := try.StartAddress endAddr := try.StartAddress + uint32(try.InstructionCount) for idx := range l.method.Instructions { - off := l.method.Instructions[idx].Offset - if off >= startAddr && off < endAddr { + insn := &l.method.Instructions[idx] + off := insn.Offset + alloc, isNew := l.allocationByNew[idx] + if off >= startAddr && off < endAddr && ir.MayThrow(insn.Opcode) && !(isNew && alloc.Fused) && !l.deferredInsn[idx] { for _, addr := range tryHandlers { if hb, ok := blockByStart[addr]; ok { handlersForInsn[idx] = append(handlersForInsn[idx], hb) @@ -669,12 +776,12 @@ func (l *methodLowerer) emitStackMapTable() error { worklist := []int{0} inQueue[0] = true - maxSteps := numBlocks*32 + 256 + maxSteps := numBlocks*64 + 1024 steps := 0 for len(worklist) > 0 { steps++ if steps > maxSteps { - return methodDiagnostic(l.method.Context, nil, "stackmap", fmt.Errorf("stack map frame analysis did not converge")) + return nil, methodDiagnostic(l.method.Context, nil, "stackmap", fmt.Errorf("stack map frame analysis did not converge")) } b := worklist[0] worklist = worklist[1:] @@ -692,7 +799,7 @@ func (l *methodLowerer) emitStackMapTable() error { exState[i] = topSlotEntry() } } - } else if insnIdx == l.delegationIndex { + } else if l.isDelegationSite(insnIdx) { exState = cloneSlotFrame(st) for i := range exState { if exState[i].vt.Tag == classfilebuilder.VerifyUninitializedThis { @@ -727,6 +834,35 @@ func (l *methodLowerer) emitStackMapTable() error { } } + return &stackMapState{ + entryFrame: entryFrame, + in: in, + visited: visited, + blockByStart: blockByStart, + catchClassByAddr: catchClassByAddr, + deferred: deferred, + }, nil +} + +func (l *methodLowerer) emitStackMapTable(state *stackMapState) error { + if len(l.method.Blocks) == 0 { + return nil + } + if state == nil { + var err error + state, err = l.computeStackMapFrames() + if err != nil { + return err + } + } + entryFrame := state.entryFrame + in := state.in + visited := state.visited + blockByStart := state.blockByStart + catchClassByAddr := state.catchClassByAddr + deferred := state.deferred + numBlocks := len(l.method.Blocks) + blockEmitsBytes := make([]bool, numBlocks) for b, block := range l.method.Blocks { for _, insnIdx := range block.Instructions { diff --git a/dex2jar/lower/validate.go b/dex2jar/lower/validate.go index 3b1e242d..96feca54 100644 --- a/dex2jar/lower/validate.go +++ b/dex2jar/lower/validate.go @@ -8,12 +8,7 @@ import ( ) func (l *methodLowerer) validateInvokes() error { - delegation := -1 - thisRegister := uint16(0) isConstructor := l.encoded.Method.Name == "" - if isConstructor { - thisRegister = l.method.Code.RegistersSize - l.method.Code.InsSize - } for index := range l.method.Instructions { instruction := &l.method.Instructions[index] if instruction.Opcode == 0xfa || instruction.Opcode == 0xfb { @@ -51,24 +46,6 @@ func (l *methodLowerer) validateInvokes() error { } return methodDiagnostic(l.method.Context, instruction, "", fmt.Errorf("constructor receiver v%d is not a fused new-instance allocation", instruction.Regs[0])) } - // The receiver may name any register that still aliases uninitialized - // this; d8 moves this into a low register for range invokes. - aliases := l.thisAliasSet(index, thisRegister) - if !aliases[instruction.Regs[0]] { - return methodDiagnostic(l.method.Context, instruction, "", fmt.Errorf("constructor receiver v%d is initialized; delegation requires uninitialized this v%d", instruction.Regs[0], thisRegister)) - } - if callee.Class != l.class.Descriptor && callee.Class != l.class.Superclass { - return methodDiagnostic(l.method.Context, instruction, "", fmt.Errorf("uninitialized this may only delegate to %s. or %s.", l.class.Descriptor, l.class.Superclass)) - } - for _, argument := range instruction.Regs[1:] { - if aliases[argument] { - return methodDiagnostic(l.method.Context, instruction, "", fmt.Errorf("uninitialized this v%d is also a constructor argument", argument)) - } - } - if delegation >= 0 { - return methodDiagnostic(l.method.Context, instruction, "", fmt.Errorf("constructor initializes this more than once")) - } - delegation = index continue } switch instruction.Opcode { @@ -88,10 +65,464 @@ func (l *methodLowerer) validateInvokes() error { if !isConstructor { return nil } - if delegation < 0 { + return l.validateConstructorDelegations() +} + +type thisInitState uint8 + +const ( + thisUninit thisInitState = iota + thisInit + thisMixed +) + +func joinThisInit(a, b thisInitState) thisInitState { + if a == b { + return a + } + return thisMixed +} + +func cloneRegSet(src map[uint16]bool) map[uint16]bool { + out := make(map[uint16]bool, len(src)) + for k, v := range src { + if v { + out[k] = true + } + } + return out +} + +func intersectRegSets(a, b map[uint16]bool) map[uint16]bool { + out := make(map[uint16]bool) + for k := range a { + if b[k] { + out[k] = true + } + } + return out +} + +func unionRegSets(a, b map[uint16]bool) map[uint16]bool { + out := cloneRegSet(a) + for k := range b { + out[k] = true + } + return out +} + +func regSetsEqual(a, b map[uint16]bool) bool { + if len(a) != len(b) { + return false + } + for k := range a { + if !b[k] { + return false + } + } + return true +} + +func (l *methodLowerer) isConstructorDelegationInsn(index int) (model.MethodID, bool) { + instruction := &l.method.Instructions[index] + if !isInvoke(instruction.Opcode) || !isDirectInvoke(instruction.Opcode) { + return model.MethodID{}, false + } + if _, ok := l.allocationByCtor[index]; ok { + return model.MethodID{}, false + } + callee := l.file.Methods[instruction.Index] + if callee.Name != "" { + return model.MethodID{}, false + } + return callee, true +} + +func (l *methodLowerer) validateConstructorDelegations() error { + if len(l.method.Blocks) == 0 { return methodDiagnostic(l.method.Context, nil, "constructor", fmt.Errorf("constructor does not initialize this or delegate")) } - return l.validateDelegationShape(delegation, thisRegister) + thisRegister := l.method.Code.RegistersSize - l.method.Code.InsSize + numBlocks := len(l.method.Blocks) + + blockOf := make([]int, len(l.method.Instructions)) + for i := range blockOf { + blockOf[i] = -1 + } + blockByOffset := make(map[uint32]int, numBlocks) + for b := range l.method.Blocks { + blockByOffset[l.method.Blocks[b].Start] = b + for _, idx := range l.method.Blocks[b].Instructions { + blockOf[idx] = b + } + } + + handlersForInsn := make([][]int, len(l.method.Instructions)) + for _, try := range l.method.Code.Tries { + startAddr := try.StartAddress + endAddr := try.StartAddress + uint32(try.InstructionCount) + var hbs []int + seenHB := make(map[int]bool) + for _, h := range try.Handler.Handlers { + if hb, ok := blockByOffset[h.Address]; ok && !seenHB[hb] { + seenHB[hb] = true + hbs = append(hbs, hb) + } + } + if try.Handler.CatchAllAddress != nil { + if hb, ok := blockByOffset[*try.Handler.CatchAllAddress]; ok && !seenHB[hb] { + seenHB[hb] = true + hbs = append(hbs, hb) + } + } + if len(hbs) == 0 { + continue + } + for idx := range l.method.Instructions { + insn := &l.method.Instructions[idx] + if insn.Offset >= startAddr && insn.Offset < endAddr && ir.MayThrow(insn.Opcode) { + handlersForInsn[idx] = append(handlersForInsn[idx], hbs...) + } + } + } + + inState := make([]thisInitState, numBlocks) + inMust := make([]map[uint16]bool, numBlocks) + inMay := make([]map[uint16]bool, numBlocks) + visited := make([]bool, numBlocks) + + visited[0] = true + inState[0] = thisUninit + inMust[0] = map[uint16]bool{thisRegister: true} + inMay[0] = map[uint16]bool{thisRegister: true} + + worklist := []int{0} + inQueue := make([]bool, numBlocks) + inQueue[0] = true + + propagate := func(succ int, st thisInitState, must, may map[uint16]bool) { + if !visited[succ] { + visited[succ] = true + inState[succ] = st + inMust[succ] = cloneRegSet(must) + inMay[succ] = cloneRegSet(may) + inQueue[succ] = true + worklist = append(worklist, succ) + return + } + js := joinThisInit(inState[succ], st) + jMust := intersectRegSets(inMust[succ], must) + jMay := unionRegSets(inMay[succ], may) + if js != inState[succ] || !regSetsEqual(jMust, inMust[succ]) || !regSetsEqual(jMay, inMay[succ]) { + inState[succ] = js + inMust[succ] = jMust + inMay[succ] = jMay + if !inQueue[succ] { + inQueue[succ] = true + worklist = append(worklist, succ) + } + } + } + + transferAliases := func(index int, must, may map[uint16]bool) { + instruction := &l.method.Instructions[index] + if instruction.Opcode >= 0x01 && instruction.Opcode <= 0x09 && len(instruction.Regs) >= 2 { + dst, src := instruction.Regs[0], instruction.Regs[1] + if must[src] { + must[dst] = true + } else { + delete(must, dst) + } + if may[src] { + may[dst] = true + } else { + delete(may, dst) + } + return + } + _, defs := l.method.EffectsAt(index) + for _, r := range defs { + delete(must, r) + delete(may, r) + } + } + + maxSteps := numBlocks*64 + 1024 + for steps := 0; len(worklist) > 0 && steps < maxSteps; steps++ { + b := worklist[0] + worklist = worklist[1:] + inQueue[b] = false + + st := inState[b] + must := cloneRegSet(inMust[b]) + may := cloneRegSet(inMay[b]) + + for _, idx := range l.method.Blocks[b].Instructions { + insn := &l.method.Instructions[idx] + if _, isCtorCall := l.isConstructorDelegationInsn(idx); isCtorCall && len(insn.Regs) > 0 && must[insn.Regs[0]] { + if len(handlersForInsn[idx]) > 0 { + for _, hb := range handlersForInsn[idx] { + propagate(hb, thisUninit, map[uint16]bool{}, map[uint16]bool{}) + } + } + st = thisInit + continue + } + if ir.MayThrow(insn.Opcode) && len(handlersForInsn[idx]) > 0 { + for _, hb := range handlersForInsn[idx] { + propagate(hb, st, must, may) + } + } + transferAliases(idx, must, may) + } + + for _, succ := range l.method.Blocks[b].Successors { + if l.blockHasNormalEdgeTo(b, succ) { + propagate(succ, st, must, may) + } + } + } + + findRepeatBranch := func(fromIdx, targetIdx int) (*ir.Instruction, bool) { + fromBlock := blockOf[fromIdx] + targetBlock := blockOf[targetIdx] + if fromBlock < 0 || targetBlock < 0 { + return nil, false + } + past := false + for _, idx := range l.method.Blocks[fromBlock].Instructions { + if idx == fromIdx { + past = true + continue + } + if past && idx == targetIdx { + return &l.method.Instructions[idx], true + } + } + seen := make([]bool, numBlocks) + var q []int + lastInsn := func(b int) *ir.Instruction { + ins := l.method.Blocks[b].Instructions + if len(ins) == 0 { + return nil + } + return &l.method.Instructions[ins[len(ins)-1]] + } + for _, succ := range l.method.Blocks[fromBlock].Successors { + if !l.blockHasNormalEdgeTo(fromBlock, succ) { + otherThrows := false + if len(handlersForInsn) > 0 { + pastFrom := false + for _, idx := range l.method.Blocks[fromBlock].Instructions { + if idx == fromIdx { + pastFrom = true + continue + } + if pastFrom { + for _, hb := range handlersForInsn[idx] { + if hb == succ { + otherThrows = true + break + } + } + } + if otherThrows { + break + } + } + } + if !otherThrows { + continue + } + } + if succ == targetBlock { + return lastInsn(fromBlock), true + } + if !seen[succ] { + seen[succ] = true + q = append(q, succ) + } + } + for len(q) > 0 { + cur := q[0] + q = q[1:] + for _, succ := range l.method.Blocks[cur].Successors { + if succ == targetBlock { + return lastInsn(cur), true + } + if !seen[succ] { + seen[succ] = true + q = append(q, succ) + } + } + } + return nil, false + } + + delegationSites := make(map[int]bool) + deferredSeen := make(map[int]bool) + l.deferredStores = nil + + for b := range l.method.Blocks { + if !visited[b] || !l.method.Blocks[b].Reachable { + continue + } + st := inState[b] + must := cloneRegSet(inMust[b]) + may := cloneRegSet(inMay[b]) + + for _, idx := range l.method.Blocks[b].Instructions { + insn := &l.method.Instructions[idx] + if callee, isCtorCall := l.isConstructorDelegationInsn(idx); isCtorCall { + recv := insn.Regs[0] + if !must[recv] { + return methodDiagnostic(l.method.Context, insn, "", fmt.Errorf("constructor receiver v%d is initialized; delegation requires uninitialized this v%d", recv, thisRegister)) + } + if callee.Class != l.class.Descriptor && callee.Class != l.class.Superclass { + return methodDiagnostic(l.method.Context, insn, "", fmt.Errorf("uninitialized this may only delegate to %s. or %s.", l.class.Descriptor, l.class.Superclass)) + } + if st != thisInit { + for _, arg := range insn.Regs[1:] { + if may[arg] { + return methodDiagnostic(l.method.Context, insn, "", fmt.Errorf("uninitialized this v%d is also a constructor argument", arg)) + } + } + } + if st == thisInit { + return methodDiagnostic(l.method.Context, insn, "", fmt.Errorf("constructor initializes this more than once")) + } + if st == thisMixed { + if edgeInsn, repeated := findRepeatBranch(idx, idx); repeated { + if edgeInsn == nil { + edgeInsn = insn + } + return methodDiagnostic(l.method.Context, edgeInsn, "", fmt.Errorf("control flow may repeat constructor delegation")) + } + return methodDiagnostic(l.method.Context, insn, "", fmt.Errorf("constructor initializes this more than once")) + } + delegationSites[idx] = true + st = thisInit + continue + } + + if st != thisInit { + uses, _ := l.method.EffectsAt(idx) + aliasMove := insn.Opcode >= 0x01 && insn.Opcode <= 0x09 && len(insn.Regs) >= 2 && may[insn.Regs[1]] + if isBranchOpcode(insn.Opcode) { + for _, r := range uses { + if may[r] { + return l.uninitializedThisUse(insn, r) + } + } + continue + } + usesThis := false + aliased := uint16(0) + for _, r := range uses { + if may[r] { + usesThis = true + aliased = r + break + } + } + if usesThis { + switch { + case aliasMove: + case insn.Opcode >= 0x59 && insn.Opcode <= 0x5f && st == thisUninit && must[insn.Regs[1]] && !may[insn.Regs[0]]: + if !deferredSeen[idx] { + deferredSeen[idx] = true + l.deferredStores = append(l.deferredStores, deferredStore{index: idx, register: insn.Regs[0]}) + } + default: + return l.uninitializedThisUse(insn, aliased) + } + } + } + + if insn.Opcode >= 0x0e && insn.Opcode <= 0x11 && st != thisInit { + return methodDiagnostic(l.method.Context, insn, "", fmt.Errorf("constructor does not initialize this or delegate")) + } + transferAliases(idx, must, may) + } + } + + l.delegationSites = delegationSites + l.delegationIndex = -1 + if len(delegationSites) == 1 { + for idx := range delegationSites { + l.delegationIndex = idx + } + } + l.deferredByDelegation = make(map[int][]int, len(delegationSites)) + + for storePos := range l.deferredStores { + store := &l.deferredStores[storePos] + storeBlock := blockOf[store.index] + if storeBlock < 0 { + return l.uninitializedThisUse(&l.method.Instructions[store.index], l.method.Instructions[store.index].Regs[1]) + } + var targets []int + seenTarget := make(map[int]bool) + stoppedInStart := false + pastStore := false + for _, idx := range l.method.Blocks[storeBlock].Instructions { + if idx == store.index { + pastStore = true + continue + } + if pastStore && delegationSites[idx] { + targets = append(targets, idx) + seenTarget[idx] = true + stoppedInStart = true + break + } + } + if !stoppedInStart { + seenBlk := map[int]bool{storeBlock: true} + var q []int + for _, succ := range l.method.Blocks[storeBlock].Successors { + if l.method.Blocks[succ].Reachable && !seenBlk[succ] { + seenBlk[succ] = true + q = append(q, succ) + } + } + for len(q) > 0 { + cur := q[0] + q = q[1:] + hitDelegation := false + for _, idx := range l.method.Blocks[cur].Instructions { + if delegationSites[idx] { + if !seenTarget[idx] { + seenTarget[idx] = true + targets = append(targets, idx) + } + hitDelegation = true + break + } + } + if hitDelegation { + continue + } + for _, succ := range l.method.Blocks[cur].Successors { + if l.method.Blocks[succ].Reachable && !seenBlk[succ] { + seenBlk[succ] = true + q = append(q, succ) + } + } + } + } + if len(targets) == 0 { + return l.uninitializedThisUse(&l.method.Instructions[store.index], l.method.Instructions[store.index].Regs[1]) + } + for _, d := range targets { + dBlock := blockOf[d] + if dBlock < 0 || (storeBlock == dBlock && store.index > d) || (storeBlock != dBlock && !l.dominates(storeBlock, dBlock)) { + return methodDiagnostic(l.method.Context, &l.method.Instructions[store.index], "", fmt.Errorf("field store before delegation is not on every path to the constructor call")) + } + l.deferredByDelegation[d] = append(l.deferredByDelegation[d], storePos) + } + } + return nil } func (l *methodLowerer) validateFusedConstructor(instruction *ir.Instruction, allocation ir.Allocation) error { @@ -136,27 +567,6 @@ func (l *methodLowerer) isSuperclass(target string) bool { return false } -// thisAliasSet returns the registers that alias uninitialized this after the -// instructions before limit. A move-object from a known alias creates one; -// defining the register with anything else destroys it. -func (l *methodLowerer) thisAliasSet(limit int, thisRegister uint16) map[uint16]bool { - aliases := map[uint16]bool{thisRegister: true} - for index := 0; index < limit && index < len(l.method.Instructions); index++ { - instruction := &l.method.Instructions[index] - if instruction.Opcode >= 0x01 && instruction.Opcode <= 0x09 && aliases[instruction.Regs[1]] { - aliases[instruction.Regs[0]] = true - continue - } - _, definitions := l.method.EffectsAt(index) - for _, register := range definitions { - if register != thisRegister { - delete(aliases, register) - } - } - } - return aliases -} - // blockOfInstruction returns the index of the block containing an instruction. func (l *methodLowerer) blockOfInstruction(instructionIndex int) int { for index := range l.method.Blocks { @@ -196,83 +606,6 @@ func (l *methodLowerer) dominates(beforeBlock, afterBlock int) bool { return true } -func (l *methodLowerer) validateDelegationShape(delegation int, thisRegister uint16) error { - delegationOffset := l.method.Instructions[delegation].Offset - l.delegationIndex = delegation - aliases := map[uint16]bool{thisRegister: true} - isThis := func(register uint16) bool { return aliases[register] } - hasBranch := false - for index := range l.method.Instructions { - instruction := &l.method.Instructions[index] - if index < delegation { - uses, definitions := l.method.EffectsAt(index) - aliasMove := instruction.Opcode >= 0x01 && instruction.Opcode <= 0x09 && isThis(instruction.Regs[1]) - if isBranchOpcode(instruction.Opcode) { - // Branches before delegation are argument computation; they may - // not touch uninitialized this, and deferred stores must still - // dominate the constructor call. - for _, register := range uses { - if isThis(register) { - return l.uninitializedThisUse(instruction, register) - } - } - hasBranch = true - continue - } - // Only the registers the instruction reads matter; defining an alias - // register (for example moving a parameter into it) retires the alias. - usesThis := false - aliased := uint16(0) - for _, register := range uses { - if isThis(register) { - usesThis = true - aliased = register - break - } - } - if usesThis { - switch { - case aliasMove: - // Aliasing uninitialized this is inert; the alias is only - // meaningful once it is used, which is checked separately. - case instruction.Opcode >= 0x59 && instruction.Opcode <= 0x5f && isThis(instruction.Regs[1]) && !isThis(instruction.Regs[0]): - // DEX permits field stores on uninitialized this before - // super(). The JVM does not, so the value is captured at the - // original position and the store is emitted after delegation. - l.deferredStores = append(l.deferredStores, deferredStore{index: index, register: instruction.Regs[0]}) - default: - return l.uninitializedThisUse(instruction, aliased) - } - } - if aliasMove { - aliases[instruction.Regs[0]] = true - } else { - for _, register := range definitions { - if register != thisRegister { - delete(aliases, register) - } - } - } - } - if index > delegation && instruction.Target >= 0 && uint32(instruction.Target) <= delegationOffset { - return methodDiagnostic(l.method.Context, instruction, "", fmt.Errorf("control flow may repeat constructor delegation")) - } - } - if hasBranch { - delegationBlock := l.blockOfInstruction(delegation) - for _, store := range l.deferredStores { - storeBlock := l.blockOfInstruction(store.index) - if storeBlock < 0 || delegationBlock < 0 || storeBlock == delegationBlock && store.index > delegation { - return methodDiagnostic(l.method.Context, &l.method.Instructions[store.index], "", fmt.Errorf("field store before delegation is not on every path to the constructor call")) - } - if storeBlock != delegationBlock && !l.dominates(storeBlock, delegationBlock) { - return methodDiagnostic(l.method.Context, &l.method.Instructions[store.index], "", fmt.Errorf("field store before delegation is not on every path to the constructor call")) - } - } - } - return nil -} - // isAllocationAlias reports whether the register still aliases an allocation // of the given class. A direct constructor call on such a register is a second // initialization site on another path. diff --git a/dex2jar/lower/wave1_soundness_test.go b/dex2jar/lower/wave1_soundness_test.go new file mode 100644 index 00000000..814e873f --- /dev/null +++ b/dex2jar/lower/wave1_soundness_test.go @@ -0,0 +1,342 @@ +package lower + +import ( + "encoding/binary" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + javaclassparser "github.com/yaklang/javajive/classparser" + "github.com/yaklang/javajive/dex2jar/model" +) + +func TestLowerClampsDebugPositionsAndEmptyLocals(t *testing.T) { + const owner = "Ldex/DebugClamp;" + file := &model.File{ + Entry: "classes.dex", + Types: []model.Type{{Descriptor: "I"}, {Descriptor: owner}, {Descriptor: "Ljava/lang/Object;"}}, + Protos: []model.Proto{{ReturnType: "I", Parameters: []string{"I"}, ParameterTypes: []uint32{0}}}, + Methods: []model.MethodID{{ + Class: owner, + Name: "probe", + ProtoIndex: 0, + }}, + } + class := &model.Class{ + Descriptor: owner, + Superclass: "Ljava/lang/Object;", + AccessFlags: dexPublic, + DirectMethods: []model.EncodedMethod{{ + MethodIndex: 0, + AccessFlags: dexPublic | dexStatic, + Method: file.Methods[0], + Code: &model.Code{ + RegistersSize: 2, + InsSize: 1, + Instructions: []uint16{ + 0x7012, // const/4 v0, #7 + 0x000f, // return v0 + }, + Debug: &model.DebugInfo{ + LineStart: 10, + ParameterNames: []string{"p"}, + Positions: []model.DebugPosition{ + {Address: 0, Line: 10}, + {Address: 1, Line: 11}, + {Address: 2, Line: 99}, + {Address: 50, Line: 100}, + }, + Locals: []model.DebugLocal{ + {Register: 0, Name: "valid", Type: "I", Start: 0, End: 2}, + {Register: 0, Name: "empty", Type: "I", Start: 1, End: 1}, + {Register: 1, Name: "oob", Type: "I", Start: 5, End: 10}, + }, + }, + }, + }}, + } + + raw, err := Class(file, class) + if err != nil { + t.Fatalf("Class failed on out-of-range debug entries: %v", err) + } + parsed, err := javaclassparser.Parse(raw) + if err != nil { + t.Fatalf("Parse generated class failed: %v", err) + } + var code *javaclassparser.CodeAttribute + for _, m := range parsed.Methods { + if parsed.ConstantPoolManager.GetUtf8(int(m.NameIndex)).Value == "probe" { + for _, attr := range m.Attributes { + if c, ok := attr.(*javaclassparser.CodeAttribute); ok { + code = c + } + } + } + } + if code == nil { + t.Fatal("probe Code attribute missing") + } + + var lines []uint16 + var localNames []string + for _, attr := range code.Attributes { + switch a := attr.(type) { + case *javaclassparser.LineNumberTableAttribute: + for _, entry := range a.LineNumberTable { + if int(entry.StartPc) >= len(code.Code) { + t.Fatalf("line entry start_pc %d >= code_length %d", entry.StartPc, len(code.Code)) + } + lines = append(lines, entry.LineNumber) + } + case *javaclassparser.UnparsedAttribute: + if a.Name == "LocalVariableTable" && len(a.Info) >= 2 { + count := int(binary.BigEndian.Uint16(a.Info[:2])) + for i := 0; i < count && 2+(i+1)*10 <= len(a.Info); i++ { + entry := a.Info[2+i*10 : 2+(i+1)*10] + startPC := int(binary.BigEndian.Uint16(entry[0:2])) + length := int(binary.BigEndian.Uint16(entry[2:4])) + nameIdx := int(binary.BigEndian.Uint16(entry[4:6])) + if length == 0 || startPC+length > len(code.Code) { + t.Fatalf("local entry has out-of-bounds range [%d, +%d) vs code_length %d", startPC, length, len(code.Code)) + } + localNames = append(localNames, parsed.ConstantPoolManager.GetUtf8(nameIdx).Value) + } + } + } + } + if len(lines) != 2 || lines[0] != 10 || lines[1] != 11 { + t.Fatalf("LineNumberTable lines = %v, want [10 11]", lines) + } + joinedLocals := strings.Join(localNames, ",") + if !strings.Contains(joinedLocals, "valid") || strings.Contains(joinedLocals, "empty") || strings.Contains(joinedLocals, "oob") { + t.Fatalf("LocalVariableTable names = %v, want valid without empty/oob", localNames) + } +} + +func TestLowerNarrowsTryCatchExceptionTableAndStackmapOverNonThrowingMoves(t *testing.T) { + const owner = "Ldex/TryNarrow;" + protos := []model.Proto{ + {ReturnType: "V"}, + {ReturnType: "I"}, + {ReturnType: "Ljava/lang/Object;", Parameters: []string{"Ljava/lang/Object;"}, ParameterTypes: []uint32{0}}, + {ReturnType: "V", Parameters: []string{"[Ljava/lang/String;"}, ParameterTypes: []uint32{1}}, + {ReturnType: "Z", Parameters: []string{"Ljava/lang/Object;"}, ParameterTypes: []uint32{0}}, + } + methods := []model.MethodID{ + {Class: "Ljava/lang/Object;", Name: "", ProtoIndex: 0}, + {Class: "Ljava/lang/Object;", Name: "hashCode", ProtoIndex: 1}, + {Class: owner, Name: "probe", ProtoIndex: 2}, + {Class: owner, Name: "main", ProtoIndex: 3}, + {Class: "Ljava/lang/Object;", Name: "equals", ProtoIndex: 4}, + } + + file := &model.File{ + Entry: "classes.dex", + Strings: []string{"fallback", "ok", "x"}, + Types: []model.Type{ + {Descriptor: "Ljava/lang/Object;"}, + {Descriptor: "[Ljava/lang/String;"}, + {Descriptor: owner}, + {Descriptor: "Ljava/lang/NullPointerException;"}, + }, + Protos: protos, + Methods: methods, + } + class := &model.Class{ + Descriptor: owner, + Superclass: "Ljava/lang/Object;", + AccessFlags: dexPublic, + DirectMethods: []model.EncodedMethod{ + { + MethodIndex: 2, + AccessFlags: dexPublic | dexStatic, + Method: methods[2], + Code: &model.Code{ + RegistersSize: 3, InsSize: 1, OutsSize: 1, + Instructions: []uint16{ + 0x001a, 0x0000, // PC 0..1: const-string v0, "fallback" + 0x2107, // PC 2: move-object v1, v2 (non-throwing leading insn inside try) + 0x106e, 0x0001, 0x0001, // PC 3..5: invoke-virtual {v1}, Object.hashCode()I (throwing) + 0x000a, // PC 6: move-result v0 (non-throwing overwrite of v0 from Object to int!) + 0x001a, 0x0001, // PC 7..8: const-string v0, "ok" + 0x0011, // PC 9: return-object v0 + 0x010d, // PC 10: move-exception v1 (handler) + 0x0011, // PC 11: return-object v0 (expects v0 still Object, NOT int) + }, + Tries: []model.Try{{ + StartAddress: 2, + InstructionCount: 5, + Handler: model.CatchHandler{ + Handlers: []model.TypedHandler{{ + TypeIndex: 3, + Type: "Ljava/lang/NullPointerException;", + Address: 10, + }}, + }, + }}, + }, + }, + { + MethodIndex: 3, + AccessFlags: dexPublic | dexStatic, + Method: methods[3], + Code: &model.Code{ + RegistersSize: 3, InsSize: 1, OutsSize: 2, + Instructions: []uint16{ + 0x001a, 0x0002, // PC 0..1: const-string v0, "x" + 0x1071, 0x0002, 0x0000, // PC 2..4: invoke-static {v0}, probe + 0x000c, // PC 5: move-result-object v0 + 0x011a, 0x0001, // PC 6..7: const-string v1, "ok" + 0x206e, 0x0004, 0x0010, // PC 8..10: invoke-virtual {v0, v1}, Object.equals(Object)Z + 0x000a, // PC 11: move-result v0 + 0x0039, 0x0004, // PC 12..13: if-nez v0, +4 (PC 16) + 0x0012, // PC 14: const/4 v0, #0 + 0x0027, // PC 15: throw v0 + 0x0012, // PC 16: const/4 v0, #0 + 0x1071, 0x0002, 0x0000, // PC 17..19: invoke-static {v0}, probe(null) + 0x000c, // PC 20: move-result-object v0 + 0x011a, 0x0000, // PC 21..22: const-string v1, "fallback" + 0x206e, 0x0004, 0x0010, // PC 23..25: invoke-virtual {v0, v1}, Object.equals(Object)Z + 0x000a, // PC 26: move-result v0 + 0x0039, 0x0004, // PC 27..28: if-nez v0, +4 (PC 31) + 0x0012, // PC 29: const/4 v0, #0 + 0x0027, // PC 30: throw v0 + 0x000e, // PC 31: return-void + }, + }, + }, + }, + } + + raw, err := Class(file, class) + if err != nil { + t.Fatalf("Class failed: %v", err) + } + parsed, err := javaclassparser.Parse(raw) + if err != nil { + t.Fatalf("Parse generated class failed: %v", err) + } + var probeCode *javaclassparser.CodeAttribute + for _, m := range parsed.Methods { + if parsed.ConstantPoolManager.GetUtf8(int(m.NameIndex)).Value == "probe" { + for _, attr := range m.Attributes { + if c, ok := attr.(*javaclassparser.CodeAttribute); ok { + probeCode = c + } + } + } + } + if probeCode == nil || len(probeCode.ExceptionTable) != 1 { + t.Fatalf("probe ExceptionTable = %#v, want 1 narrowed entry", probeCode) + } + exc := probeCode.ExceptionTable[0] + if int(exc.EndPc) >= len(probeCode.Code)-4 || exc.StartPc == 0 { + t.Fatalf("ExceptionTable entry [%d, %d) not narrowed tightly around invokevirtual (code_length=%d)", + exc.StartPc, exc.EndPc, len(probeCode.Code)) + } + + java, err := exec.LookPath("java") + if err != nil { + return + } + dir := t.TempDir() + path := filepath.Join(dir, "dex", "TryNarrow.class") + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, raw, 0o644); err != nil { + t.Fatal(err) + } + if out, err := exec.Command(java, "-Xverify:all", "-cp", dir, "dex.TryNarrow").CombinedOutput(); err != nil { + t.Fatalf("java -Xverify:all execution failed: %v\n%s", err, out) + } +} + +func TestLowerConstructorThisAliasOverwriteAndDeferredIput(t *testing.T) { + const owner = "Ldex/AliasCtor;" + field := model.FieldID{Class: owner, Name: "x", Type: "I"} + protos := []model.Proto{ + {ReturnType: "V"}, + {ReturnType: "V", Parameters: []string{"[Ljava/lang/String;"}, ParameterTypes: []uint32{1}}, + } + methods := []model.MethodID{ + {Class: "Ljava/lang/Object;", Name: "", ProtoIndex: 0}, + {Class: owner, Name: "", ProtoIndex: 0}, + {Class: owner, Name: "main", ProtoIndex: 1}, + } + file := &model.File{ + Entry: "classes.dex", + Types: []model.Type{{Descriptor: "Ljava/lang/Object;"}, {Descriptor: "[Ljava/lang/String;"}, {Descriptor: owner}}, + Protos: protos, + Fields: []model.FieldID{field}, + Methods: methods, + } + class := &model.Class{ + Descriptor: owner, + Superclass: "Ljava/lang/Object;", + AccessFlags: dexPublic, + InstanceFields: []model.EncodedField{{FieldIndex: 0, AccessFlags: dexPrivate, Field: field}}, + DirectMethods: []model.EncodedMethod{ + { + MethodIndex: 1, + AccessFlags: dexPublic | dexConstructor, + Method: methods[1], + Code: &model.Code{ + RegistersSize: 3, InsSize: 1, OutsSize: 1, + Instructions: []uint16{ + 0x2007, // PC 0: move-object v0, v2 (alias uninit this from thisRegister v2) + 0x5212, // PC 1: const/4 v2, #5 (overwrite thisRegister v2!) + 0x0259, 0x0000, // PC 2..3: iput v2, v0, Foo.x (deferred store on v0) + 0x1070, 0x0000, 0x0000, // PC 4..6: invoke-direct {v0}, Object.()V + 0x000e, // PC 7: return-void + }, + }, + }, + { + MethodIndex: 2, + AccessFlags: dexPublic | dexStatic, + Method: methods[2], + Code: &model.Code{ + RegistersSize: 3, InsSize: 1, OutsSize: 1, + Instructions: []uint16{ + 0x0022, 0x0002, // PC 0..1: new-instance v0, Ldex/AliasCtor; + 0x1070, 0x0001, 0x0000, // PC 2..4: invoke-direct {v0}, AliasCtor.()V + 0x0052, 0x0000, // PC 5..6: iget v0, v0, Foo.x + 0x5112, // PC 7: const/4 v1, #5 + 0x1032, 0x0004, // PC 8..9: if-eq v0, v1, +4 (PC 12) + 0x0012, // PC 10: const/4 v0, #0 + 0x0027, // PC 11: throw v0 + 0x000e, // PC 12: return-void + }, + }, + }, + }, + } + + raw, err := Class(file, class) + if err != nil { + t.Fatalf("Class failed on aliased/overwritten this constructor: %v", err) + } + if _, err := javaclassparser.Parse(raw); err != nil { + t.Fatalf("Parse generated class failed: %v", err) + } + + java, err := exec.LookPath("java") + if err != nil { + return + } + dir := t.TempDir() + path := filepath.Join(dir, "dex", "AliasCtor.class") + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, raw, 0o644); err != nil { + t.Fatal(err) + } + if out, err := exec.Command(java, "-Xverify:all", "-cp", dir, "dex.AliasCtor").CombinedOutput(); err != nil { + t.Fatalf("java -Xverify:all execution failed: %v\n%s", err, out) + } +} diff --git a/dex2jar/lower/wave2_soundness_test.go b/dex2jar/lower/wave2_soundness_test.go new file mode 100644 index 00000000..6f625ba2 --- /dev/null +++ b/dex2jar/lower/wave2_soundness_test.go @@ -0,0 +1,716 @@ +package lower + +import ( + "bytes" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + javaclassparser "github.com/yaklang/javajive/classparser" + "github.com/yaklang/javajive/dex2jar/model" +) + +func findWave2MethodCode(t *testing.T, raw []byte, name string) *javaclassparser.CodeAttribute { + t.Helper() + parsed, err := javaclassparser.Parse(raw) + if err != nil { + t.Fatalf("Parse failed: %v", err) + } + for _, m := range parsed.Methods { + if parsed.ConstantPoolManager.GetUtf8(int(m.NameIndex)).Value != name { + continue + } + for _, attr := range m.Attributes { + if c, ok := attr.(*javaclassparser.CodeAttribute); ok { + return c + } + } + } + t.Fatalf("method %q Code attribute not found", name) + return nil +} + +func runMainWithVerify(t *testing.T, raw []byte, className string) { + t.Helper() + if _, err := javaclassparser.Parse(raw); err != nil { + t.Fatalf("Parse(%s) failed: %v", className, err) + } + java, err := exec.LookPath("java") + if err != nil { + return + } + dir := t.TempDir() + path := filepath.Join(dir, strings.ReplaceAll(className, ".", "/")+".class") + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, raw, 0o644); err != nil { + t.Fatal(err) + } + if out, err := exec.Command(java, "-Xverify:all", "-cp", dir, className).CombinedOutput(); err != nil { + t.Fatalf("java -Xverify:all %s failed: %v\n%s", className, err, out) + } +} + +func TestWave2ExceptionTableCoalescingAndIncompatibleSplit(t *testing.T) { + const owner = "Ldex/CoalesceTry;" + file := &model.File{ + Entry: "classes.dex", + Types: []model.Type{ + {Descriptor: owner}, + {Descriptor: "Ljava/lang/Throwable;"}, + {Descriptor: "Ljava/lang/String;"}, + {Descriptor: "V"}, + {Descriptor: "I"}, + {Descriptor: "[Ljava/lang/String;"}, + }, + Protos: []model.Proto{ + {ReturnType: "I", Parameters: []string{"I"}, ParameterTypes: []uint32{4}}, + {ReturnType: "V"}, + {ReturnType: "V", Parameters: []string{"[Ljava/lang/String;"}, ParameterTypes: []uint32{5}}, + {ReturnType: "I", Parameters: []string{"Ljava/lang/Object;", "Ljava/lang/String;", "I"}, ParameterTypes: []uint32{6, 2, 4}}, + {ReturnType: "I"}, + }, + Methods: []model.MethodID{ + {Class: owner, Name: "coalesceSafe", ProtoIndex: 0}, + {Class: owner, Name: "splitIncompatible", ProtoIndex: 3}, + {Class: owner, Name: "boom", ProtoIndex: 1}, + {Class: owner, Name: "main", ProtoIndex: 2}, + {Class: "Ljava/lang/String;", Name: "length", ProtoIndex: 4}, + {Class: "Ljava/lang/String;", Name: "", ProtoIndex: 1}, + }, + } + file.Types = append(file.Types, model.Type{Descriptor: "Ljava/lang/Object;"}) + + cls := &model.Class{ + Descriptor: owner, + Superclass: "Ljava/lang/Object;", + AccessFlags: dexPublic, + DirectMethods: []model.EncodedMethod{ + { + MethodIndex: 2, + AccessFlags: dexPublic | dexStatic, + Method: file.Methods[2], + Code: &model.Code{ + RegistersSize: 1, + Instructions: []uint16{ + 0x0012, // const/4 v0, 0 (null) + 0x0027, // throw v0 + }, + }, + }, + // coalesceSafe(I)I: two protected slices separated by a non-throwing `const/4 v0, 1` + // where v1 (the handler-live local) stays VerifyInt before, during, and after the gap. + { + MethodIndex: 0, + AccessFlags: dexPublic | dexStatic, + Method: file.Methods[0], + Code: &model.Code{ + RegistersSize: 3, InsSize: 1, OutsSize: 0, + Instructions: []uint16{ + 0x0112, // 0: const/4 v1, #0 + 0x0071, 0x0002, 0x0000, // 1..3: invoke-static {}, boom()V + 0x1012, // 4: const/4 v0, #1 (non-throwing intermediate outside try) + 0x0071, 0x0002, 0x0000, // 5..7: invoke-static {}, boom()V + 0x000f, // 8: return v0 + 0x000d, // 9: move-exception v0 (handler) + 0x010f, // 10: return v1 + }, + Tries: []model.Try{ + { + StartAddress: 1, InstructionCount: 7, + Handler: model.CatchHandler{Handlers: []model.TypedHandler{{TypeIndex: 1, Type: "Ljava/lang/Throwable;", Address: 9}}}, + }, + }, + }, + }, + // splitIncompatible(I)I: gap writes a String (reference) into v1 while handler uses v1 after + // catch; coalescing across the intermediate range would make the handler frame invalid. + { + MethodIndex: 1, + AccessFlags: dexPublic | dexStatic, + Method: file.Methods[1], + Code: &model.Code{ + RegistersSize: 3, InsSize: 1, OutsSize: 0, + Instructions: []uint16{ + 0x1112, // 0: const/4 v1, #1 (int) + 0x0071, 0x0002, 0x0000, // 1..3: invoke-static {}, boom()V (try 1) + 0x0112, // 4: const/4 v1, #0 (null -> overwritten with String below) + 0x1207, // 5: move-object v1, v2 (v2=incoming int? Wait: use const-string for incompatible Ref!) + 0x000f, // 6: return v0 (replaced below) + }, + }, + }, + { + MethodIndex: 3, + AccessFlags: dexPublic | dexStatic, + Method: file.Methods[3], + Code: &model.Code{ + RegistersSize: 4, InsSize: 1, OutsSize: 3, + Instructions: []uint16{ + 0x2012, // 0: const/4 v0, #2 + 0x1071, 0x0000, 0x0000, // 1..3: invoke-static {v0}, coalesceSafe + 0x0012, // 4: const/4 v0, #0 (null Object) + 0x011a, 0x0000, // 5..6: const-string v1, "x" + 0x1212, // 7: const/4 v2, #1 (flag=1) + 0x3071, 0x0001, 0x0210, // 8..10: invoke-static {v0, v1, v2}, splitIncompatible + 0x000e, // 11: return-void + }, + }, + }, + }, + } + + file.Strings = []string{"x"} + cls.DirectMethods[2].Code = &model.Code{ + RegistersSize: 5, InsSize: 3, OutsSize: 1, // v2=Object, v3=String, v4=flag + Instructions: []uint16{ + 0x0439, 0x0009, // 0..1: if-nez v4, +9 -> 9 + 0x0122, 0x0002, // 2..3: new-instance v1, String (pins v1!) + 0x1070, 0x0005, 0x0001, // 4..6: invoke-direct {v1}, String.()V + 0x0012, // 7: const/4 v0, #0 + 0x000f, // 8: return v0 + 0x3107, // 9: move-object v1, v3 (v1=String) + 0x0071, 0x0002, 0x0000, // 10..12: invoke-static {}, boom()V (Try start = 10) + 0x2107, // 13: move-object v1, v2 (gap: v1 becomes java/lang/Object!) + 0x3107, // 14: move-object v1, v3 (gap: v1 restored to String without throwing) + 0x0071, 0x0002, 0x0000, // 15..17: invoke-static {}, boom()V (Try end = 18) + 0x0012, // 18: const/4 v0, #0 + 0x000f, // 19: return v0 + 0x000d, // 20: move-exception v0 (handler!) + 0x106e, 0x0004, 0x0001, // 21..23: invoke-virtual {v1}, String.length()I + 0x000a, // 24: move-result v0 + 0x000f, // 25: return v0 + }, + Tries: []model.Try{ + { + StartAddress: 10, InstructionCount: 8, + Handler: model.CatchHandler{Handlers: []model.TypedHandler{{TypeIndex: 1, Type: "Ljava/lang/Throwable;", Address: 20}}}, + }, + }, + } + + raw, err := Class(file, cls) + if err != nil { + t.Fatalf("Class failed: %v", err) + } + safeCode := findWave2MethodCode(t, raw, "coalesceSafe") + if len(safeCode.ExceptionTable) != 1 { + t.Fatalf("coalesceSafe ExceptionTable len = %d, want 1 coalesced entry", len(safeCode.ExceptionTable)) + } + splitCode := findWave2MethodCode(t, raw, "splitIncompatible") + if len(splitCode.ExceptionTable) != 2 { + t.Fatalf("splitIncompatible ExceptionTable len = %d, want 2 split entries across incompatible Ref store", len(splitCode.ExceptionTable)) + } + runMainWithVerify(t, raw, "dex.CoalesceTry") +} + +func TestWave2MultiKindWebPrologueAndUntypedZeroVerify(t *testing.T) { + // Checks that an incoming float parameter register overwritten with int AND untyped-zero `0` + // across float/int/ref uses gets distinct companion slots (prologueStoreSlot + resolvedZeroKind) + // and passes `java -Xverify:all`. + const owner = "Ldex/PolyPrologue;" + file := &model.File{ + Entry: "classes.dex", + Types: []model.Type{ + {Descriptor: owner}, + {Descriptor: "F"}, + {Descriptor: "I"}, + {Descriptor: "Ljava/lang/String;"}, + {Descriptor: "V"}, + {Descriptor: "[Ljava/lang/String;"}, + }, + Protos: []model.Proto{ + {ReturnType: "I", Parameters: []string{"F", "I"}, ParameterTypes: []uint32{1, 2}}, + {ReturnType: "V", Parameters: []string{"[Ljava/lang/String;"}, ParameterTypes: []uint32{5}}, + }, + Methods: []model.MethodID{ + {Class: owner, Name: "poly", ProtoIndex: 0}, + {Class: owner, Name: "main", ProtoIndex: 1}, + }, + } + cls := &model.Class{ + Descriptor: owner, + Superclass: "Ljava/lang/Object;", + AccessFlags: dexPublic, + DirectMethods: []model.EncodedMethod{ + { + MethodIndex: 0, + AccessFlags: dexPublic | dexStatic, + Method: file.Methods[0], + // v2=float p, v3=int flag; reuse p (v2) as int AND return float/int/null via shared zero reg v0 + Code: &model.Code{ + RegistersSize: 4, InsSize: 2, OutsSize: 0, + Instructions: []uint16{ + 0x0012, // 0: const/4 v0, #0 (untyped zero used as both 0F and 0 int) + 0x0338, 0x0004, // 1..2: if-eqz v3, +4 -> 5 + 0x0087, // 3: wait? No, float-to-int v2, v2 (0x87: float-to-int vA, vB => (B<<12)|(A<<8)|0x87) + 0x2287, // replace above word cleanly below + }, + }, + }, + { + MethodIndex: 1, + AccessFlags: dexPublic | dexStatic, + Method: file.Methods[1], + Code: &model.Code{ + RegistersSize: 3, InsSize: 1, OutsSize: 2, + Instructions: []uint16{ + 0x0015, 0x3f80, // 0..1: const/high16 v0, 1.0f + 0x1112, // 2: const/4 v1, #1 + 0x2071, 0x0000, 0x0010, // 3..5: invoke-static {v0, v1}, poly(FI)I + 0x000e, // 6: return-void + }, + }, + }, + }, + } + cls.DirectMethods[0].Code.Instructions = []uint16{ + 0x0012, // 0: const/4 v0, #0 (untyped 0!) + 0x0338, 0x0004, // 1..2: if-eqz v3, +4 -> 5 + 0x2287, // 3: float-to-int v2, v2 (reads v2 as float, overwrites v2 with int!) + 0x0228, // 4: goto +2 -> 6 + 0x02b0, // 5: add-int/2addr v2, v0 (reads v0 as INT zero AND overwrites v2) -> actually cmpg-float? let's use add-float/2addr v2, v0 (0xa6: add-float/2addr v2, v0 => 0x02a6)! + 0x000f, // 6: return v0 (returns v0 as INT!) + } + cls.DirectMethods[0].Code.Instructions[4] = 0x0228 // goto +2 -> 6 + cls.DirectMethods[0].Code.Instructions[5] = 0x02a6 // add-float/2addr v2, v0 (uses v0 as FLOAT zero + v2 as float!) + // Wait: after branch, merge on v2: add 0x2001 move v0, v2 (uses v2? Wait in branch 1 v2 is int, branch 2 v2 is float? Don't merge different types directly in v2; instead v1 receives zero float vs int!) + cls.DirectMethods[0].Code.Instructions = []uint16{ + 0x0012, // 0: const/4 v0, #0 (untyped zero used as BOTH float 0.0f and int 0!) + 0x0338, 0x0004, // 1..2: if-eqz v3, +4 -> 5 + 0x2287, // 3: float-to-int v2, v2 (v2 reused from Float param -> Int) + 0x0328, // 4: goto +3 -> 7 + 0x02c6, // 5: add-float/2addr v2, v0 (reads v0 as Float) + 0x2287, // 6: float-to-int v2, v2 (v2 now Int on both paths) + 0x0090, 0x0002, // 7..8: add-int v0, v2, v0 (reads v0 as Int!) + 0x000f, // 9: return v0 + } + + raw, err := Class(file, cls) + if err != nil { + t.Fatalf("Class failed on poly prologue / untyped zero: %v", err) + } + runMainWithVerify(t, raw, "dex.PolyPrologue") +} + +func TestWave2CFGConstructorShapesAliasNonLeakThrowOnlyAndBranching(t *testing.T) { + const owner = "Ldex/BranchCtor;" + file := &model.File{ + Entry: "classes.dex", + Types: []model.Type{ + {Descriptor: owner}, + {Descriptor: "Ljava/lang/Object;"}, + {Descriptor: "Ljava/lang/RuntimeException;"}, + {Descriptor: "I"}, + {Descriptor: "V"}, + {Descriptor: "[Ljava/lang/String;"}, + }, + Fields: []model.FieldID{ + {Class: owner, Name: "flag", Type: "I"}, + }, + Protos: []model.Proto{ + {ReturnType: "V"}, + {ReturnType: "V", Parameters: []string{"I"}, ParameterTypes: []uint32{3}}, + {ReturnType: "V", Parameters: []string{"I", "I"}, ParameterTypes: []uint32{3, 3}}, + {ReturnType: "V", Parameters: []string{"[Ljava/lang/String;"}, ParameterTypes: []uint32{5}}, + }, + Methods: []model.MethodID{ + {Class: "Ljava/lang/Object;", Name: "", ProtoIndex: 0}, + {Class: "Ljava/lang/RuntimeException;", Name: "", ProtoIndex: 0}, + {Class: owner, Name: "", ProtoIndex: 1}, // branching + deferred store + goto non-leak + {Class: owner, Name: "", ProtoIndex: 2}, // throw-only ctor + {Class: owner, Name: "main", ProtoIndex: 3}, + }, + } + + cls := &model.Class{ + Descriptor: owner, + Superclass: "Ljava/lang/Object;", + AccessFlags: dexPublic, + InstanceFields: []model.EncodedField{{FieldIndex: 0, AccessFlags: dexPublic, Field: file.Fields[0]}}, + DirectMethods: []model.EncodedMethod{ + // Branching (I) with: + // - deferred store `iput v4, v2, flag` before `if-eqz` + // - branch 1 aliasing v1=v2 (`this`) and jumping around branch 2 (`goto +3`) + // - branch 2 moving `v0 = v1` (v1 is NOT uninitialized `this` in branch 2!) + // - mutually exclusive `Object.(v2)` on both branches! + { + MethodIndex: 2, + AccessFlags: dexPublic | dexConstructor, + Method: file.Methods[2], + Code: &model.Code{ + RegistersSize: 4, InsSize: 2, OutsSize: 1, // v2=this, v3=int p + Instructions: []uint16{ + 0x0012, // 0: const/4 v0, #0 + 0x0112, // 1: const/4 v1, #0 + 0x2359, 0x0000, // 2..3: iput v3, v2, BranchCtor.flag (deferred store) + 0x0338, 0x0006, // 4..5: if-eqz v3, +6 -> 10 (branch 2) + 0x2107, // 6: move-object v1, v2 (Branch 1 ONLY: v1 aliases this!) + 0x1070, 0x0000, 0x0001, // 7..9: invoke-direct {v1}, Object.()V + 0x000e, // 10-? Wait: branch 1 needs goto over branch 2 -> adjust offsets below! + }, + }, + }, + // Throw-only (I, I): 0 delegations, 0 reachable return-voids -> throws RuntimeException. + { + MethodIndex: 3, + AccessFlags: dexPublic | dexConstructor, + Method: file.Methods[3], + Code: &model.Code{ + RegistersSize: 4, InsSize: 3, OutsSize: 1, + Instructions: []uint16{ + 0x0022, 0x0002, // 0..1: new-instance v0, RuntimeException + 0x1070, 0x0001, 0x0000, // 2..4: invoke-direct {v0}, RuntimeException.()V + 0x0027, // 5: throw v0 + }, + }, + }, + { + MethodIndex: 4, + AccessFlags: dexPublic | dexStatic, + Method: file.Methods[4], + Code: &model.Code{ + RegistersSize: 3, InsSize: 1, OutsSize: 2, + Instructions: []uint16{ + 0x0022, 0x0000, // 0..1: new-instance v0, BranchCtor + 0x5112, // 2: const/4 v1, #5 + 0x2070, 0x0002, 0x0010, // 3..5: wait regs D=1, C=0 -> 0x10 + 0x000e, // 6: return-void + }, + }, + }, + }, + } + cls.DirectMethods[0].Code.Instructions = []uint16{ + 0x0012, // 0: const/4 v0, #0 + 0x0112, // 1: const/4 v1, #0 + 0x2359, 0x0000, // 2..3: iput v3, v2, BranchCtor.flag + 0x0338, 0x0007, // 4..5: if-eqz v3, +7 -> 11 (branch 2) + 0x2107, // 6: move-object v1, v2 (branch 1 only!) + 0x1070, 0x0000, 0x0001, // 7..9: invoke-direct {v1}, Object.()V + 0x0528, // 10: goto +5 -> 15 (exit) + 0x1001, // 11: move v0, v1 (branch 2: reads v1 which was NOT this in branch 2!) + 0x1070, 0x0000, 0x0002, // 12..14: invoke-direct {v2}, Object.()V + 0x000e, // 15: return-void + } + cls.DirectMethods[2].Code.Instructions = []uint16{ + 0x0022, 0x0000, // 0..1: new-instance v0, BranchCtor + 0x5112, // 2: const/4 v1, #5 + 0x2070, 0x0002, 0x0010, // 3..5: invoke-direct {v0, v1}, BranchCtor.(I)V + 0x000e, // 6: return-void + } + + raw, err := Class(file, cls) + if err != nil { + t.Fatalf("Class failed on CFG branching/alias/throw-only ctors: %v", err) + } + runMainWithVerify(t, raw, "dex.BranchCtor") +} + +func TestWave2DiscardedFilledNewArray(t *testing.T) { + const owner = "Ldex/DiscardFilledArray;" + file := &model.File{ + Entry: "classes.dex", + Types: []model.Type{ + {Descriptor: owner}, + {Descriptor: "[I"}, + {Descriptor: "[Ljava/lang/String;"}, + {Descriptor: "V"}, + }, + Protos: []model.Proto{ + {ReturnType: "V", Parameters: []string{"[Ljava/lang/String;"}, ParameterTypes: []uint32{2}}, + }, + Methods: []model.MethodID{ + {Class: owner, Name: "main", ProtoIndex: 0}, + }, + } + cls := &model.Class{ + Descriptor: owner, + Superclass: "Ljava/lang/Object;", + AccessFlags: dexPublic, + DirectMethods: []model.EncodedMethod{{ + MethodIndex: 0, + AccessFlags: dexPublic | dexStatic, + Method: file.Methods[0], + Code: &model.Code{ + RegistersSize: 2, InsSize: 1, OutsSize: 0, + Instructions: []uint16{ + 0x7012, // 0: const/4 v0, #7 + 0x1024, 0x0001, 0x0000, // 1..3: filled-new-array {v0}, [I (result discarded!) + 0x000e, // 4: return-void + }, + }, + }}, + } + raw, err := Class(file, cls) + if err != nil { + t.Fatalf("Class failed on discarded filled-new-array: %v", err) + } + runMainWithVerify(t, raw, "dex.DiscardFilledArray") +} + +func TestWave2RecoverConstructorParameterAnnotationsAndStrictRejection(t *testing.T) { + const owner = "Ldex/ParamAnnot;" + file := &model.File{ + Entry: "classes.dex", + Types: []model.Type{ + {Descriptor: owner}, + {Descriptor: "Ljava/lang/Object;"}, + {Descriptor: "Ljava/lang/Deprecated;"}, + {Descriptor: "Ljava/lang/String;"}, + {Descriptor: "I"}, + {Descriptor: "V"}, + }, + Protos: []model.Proto{ + {ReturnType: "V"}, + {ReturnType: "V", Parameters: []string{"Ljava/lang/String;", "I"}, ParameterTypes: []uint32{3, 4}}, + }, + Methods: []model.MethodID{ + {Class: "Ljava/lang/Object;", Name: "", ProtoIndex: 0}, + {Class: owner, Name: "", ProtoIndex: 1}, + }, + } + cls := &model.Class{ + Descriptor: owner, + Superclass: "Ljava/lang/Object;", + AccessFlags: dexPublic, + DirectMethods: []model.EncodedMethod{{ + MethodIndex: 1, + AccessFlags: dexPublic | dexConstructor, + Method: file.Methods[1], + Code: &model.Code{ + RegistersSize: 3, InsSize: 3, OutsSize: 1, + Instructions: []uint16{ + 0x1070, 0x0000, 0x0000, + 0x000e, + }, + }, + }}, + ParameterAnnotations: []model.ParameterAnnotation{{ + MethodIndex: 1, + Parameters: [][]model.Annotation{ + // Only 1 entry for a 2-param constructor (synthetic outer-this entry stripped by R8): + {{Visibility: model.AnnotationRuntime, Type: "Ljava/lang/Deprecated;"}}, + }, + }}, + ParameterAnnotationIndex: map[uint32]int{1: 0}, + } + + if _, err := ClassWithPolicy(file, cls, ClassOptions{}, Strict); err == nil { + t.Fatal("Strict unexpectedly accepted mismatched constructor parameter annotations") + } + res, err := ClassWithPolicy(file, cls, ClassOptions{}, Recover) + if err != nil { + t.Fatalf("Recover failed: %v", err) + } + parsed, err := javaclassparser.Parse(res.Bytes) + if err != nil { + t.Fatalf("Parse failed: %v", err) + } + var rvpa *javaclassparser.RuntimeVisibleParameterAnnotationsAttribute + for _, m := range parsed.Methods { + if parsed.ConstantPoolManager.GetUtf8(int(m.NameIndex)).Value != "" { + continue + } + for _, attr := range m.Attributes { + if pa, ok := attr.(*javaclassparser.RuntimeVisibleParameterAnnotationsAttribute); ok && !pa.IsInvisible { + rvpa = pa + } + } + } + if rvpa == nil { + t.Fatal("expected right-aligned RuntimeVisibleParameterAnnotations attribute") + } + if len(rvpa.ParameterAnnotations) != 2 { + t.Fatalf("num_parameters = %d, want 2 (prepended empty entry for leading param)", len(rvpa.ParameterAnnotations)) + } + if len(rvpa.ParameterAnnotations[0]) != 0 || len(rvpa.ParameterAnnotations[1]) != 1 { + t.Fatalf("aligned annotation counts = [%d, %d], want [0, 1]", len(rvpa.ParameterAnnotations[0]), len(rvpa.ParameterAnnotations[1])) + } +} + +func TestWave2EnumOrdinalOrderRestoresRealEnum(t *testing.T) { + const owner = "Ldex/OrderColor;" + const arrayOwner = "[Ldex/OrderColor;" + file := &model.File{ + Entry: "classes.dex", + Strings: []string{"ZEBRA", "ALPHA"}, + Types: []model.Type{ + {Descriptor: owner}, + {Descriptor: "Ljava/lang/Enum;"}, + {Descriptor: "Ljava/lang/String;"}, + {Descriptor: "I"}, + {Descriptor: "V"}, + {Descriptor: arrayOwner}, + }, + Fields: []model.FieldID{ + // Alphabetically sorted in DEX: ALPHA (field 0) before ZEBRA (field 1), plus $VALUES (field 2), + // while constructs ZEBRA at ordinal 0 and ALPHA at ordinal 1! + {Class: owner, Name: "ALPHA", Type: owner}, + {Class: owner, Name: "ZEBRA", Type: owner}, + {Class: owner, Name: "$VALUES", Type: arrayOwner}, + }, + Protos: []model.Proto{ + {ReturnType: "V", Parameters: []string{"Ljava/lang/String;", "I"}, ParameterTypes: []uint32{2, 3}}, + {ReturnType: "V"}, + {ReturnType: arrayOwner}, + {ReturnType: owner, Parameters: []string{"Ljava/lang/String;"}, ParameterTypes: []uint32{2}}, + }, + Methods: []model.MethodID{ + {Class: "Ljava/lang/Enum;", Name: "", ProtoIndex: 0}, + {Class: owner, Name: "", ProtoIndex: 0}, + {Class: owner, Name: "", ProtoIndex: 1}, + {Class: owner, Name: "values", ProtoIndex: 2}, + {Class: arrayOwner, Name: "clone", ProtoIndex: 1}, // placeholder replaced below + {Class: owner, Name: "valueOf", ProtoIndex: 3}, + {Class: "Ljava/lang/Enum;", Name: "valueOf", ProtoIndex: 3}, + }, + } + // Replace file.Types/Protos/Methods cleanly for clone():()Ljava/lang/Object; and Enum.valueOf(Class, String) + file.Types = append(file.Types, model.Type{Descriptor: "Ljava/lang/Object;"}, model.Type{Descriptor: "Ljava/lang/Class;"}) + file.Protos = append(file.Protos, + model.Proto{ReturnType: "Ljava/lang/Object;"}, + model.Proto{ReturnType: "Ljava/lang/Enum;", Parameters: []string{"Ljava/lang/Class;", "Ljava/lang/String;"}, ParameterTypes: []uint32{7, 2}}, + ) + file.Methods[4] = model.MethodID{Class: arrayOwner, Name: "clone", ProtoIndex: 4} + file.Methods[6] = model.MethodID{Class: "Ljava/lang/Enum;", Name: "valueOf", ProtoIndex: 5} + + cls := &model.Class{ + Descriptor: owner, + Superclass: "Ljava/lang/Enum;", + AccessFlags: dexPublic | dexFinal | dexEnum, + StaticFields: []model.EncodedField{ + {FieldIndex: 0, AccessFlags: dexPublic | dexStatic | dexFinal | dexEnum, Field: file.Fields[0]}, // ALPHA first in DEX + {FieldIndex: 1, AccessFlags: dexPublic | dexStatic | dexFinal | dexEnum, Field: file.Fields[1]}, // ZEBRA second in DEX + {FieldIndex: 2, AccessFlags: dexPrivate | dexStatic | dexFinal | dexSynthetic, Field: file.Fields[2]}, + }, + DirectMethods: []model.EncodedMethod{ + { + MethodIndex: 1, // (String, I) + AccessFlags: dexPrivate | dexConstructor, + Method: file.Methods[1], + Code: &model.Code{ + RegistersSize: 3, InsSize: 3, OutsSize: 3, // v0=this, v1=name, v2=ord + Instructions: []uint16{ + 0x3070, 0x0000, 0x0100, // invoke-direct {v0, v1, v2}, Enum.(String,I)V + 0x000e, // return-void + }, + }, + }, + { + MethodIndex: 2, // () + AccessFlags: dexStatic | dexConstructor, + Method: file.Methods[2], + Code: &model.Code{ + RegistersSize: 4, InsSize: 0, OutsSize: 3, + Instructions: []uint16{ + // ZEBRA at ordinal 0 + 0x0022, 0x0000, // 0..1: new-instance v0, OrderColor + 0x011a, 0x0000, // 2..3: const-string v1, "ZEBRA" + 0x0212, // 4: const/4 v2, #0 + 0x3070, 0x0001, 0x1000, // 5..7: invoke-direct {v0, v1, v2}, OrderColor.(String,I)V -> G=2 + 0x0069, 0x0001, // 8..9: sput-object v0, ZEBRA (field 1) + // ALPHA at ordinal 1 + 0x0022, 0x0000, // 10..11: new-instance v0, OrderColor + 0x011a, 0x0001, // 12..13: const-string v1, "ALPHA" + 0x1212, // 14: const/4 v2, #1 + 0x3070, 0x0001, 0x1000, // 15..17: invoke-direct {v0, v1, v2}, OrderColor.(String,I)V + 0x0069, 0x0000, // 18..19: sput-object v0, ALPHA (field 0) + // $VALUES = new OrderColor[]{ZEBRA, ALPHA} + 0x2312, // 20: const/4 v3, #2 + 0x3023, 0x0005, // 21..22: new-array v0, v3, [Ldex/OrderColor; + 0x0162, 0x0001, // 23..24: sget-object v1, ZEBRA + 0x0212, // 25: const/4 v2, #0 + 0x014d, 0x0200, // 26..27: aput-object v1, v0[v2] + 0x0162, 0x0000, // 28..29: sget-object v1, ALPHA + 0x1212, // 30: const/4 v2, #1 + 0x014d, 0x0200, // 31..32: aput-object v1, v0[v2] + 0x0069, 0x0002, // 33..34: sput-object v0, $VALUES + 0x000e, // 35: return-void + }, + }, + }, + { + MethodIndex: 3, // values() + AccessFlags: dexPublic | dexStatic, + Method: file.Methods[3], + Code: &model.Code{ + RegistersSize: 1, InsSize: 0, OutsSize: 1, + Instructions: []uint16{ + 0x0062, 0x0002, // sget-object v0, $VALUES + 0x106e, 0x0004, 0x0000, // invoke-virtual {v0}, clone() + 0x000c, // move-result-object v0 + 0x001f, 0x0005, // check-cast v0, [Ldex/OrderColor; + 0x0011, // return-object v0 + }, + }, + }, + { + MethodIndex: 5, // valueOf(String) + AccessFlags: dexPublic | dexStatic, + Method: file.Methods[5], + Code: &model.Code{ + RegistersSize: 2, InsSize: 1, OutsSize: 2, // v1=String + Instructions: []uint16{ + 0x001c, 0x0000, // const-class v0, OrderColor + 0x2071, 0x0006, 0x0010, // invoke-static {v0, v1}, Enum.valueOf(Class, String) + 0x000c, // move-result-object v0 + 0x001f, 0x0000, // check-cast v0, OrderColor + 0x0011, // return-object v0 + }, + }, + }, + }, + } + // Fix 35c encoding on words with count=3: byte1 = (G<<4)|count=2?! + // DEX 35c format: word0 = (count<<12)|(G<<8)|op, word1 = methodIdx, word2 = (F<<12)|(E<<8)|(D<<4)|C + // For count=3 {v0, v1, v2}: count=3, G unused (0), C=0, D=1, E=2 -> word0=(3<<12)|op, word2=(2<<8)|(1<<4)|0 = 0x0210! + cls.DirectMethods[0].Code.Instructions[0] = 0x3070 + cls.DirectMethods[0].Code.Instructions[2] = 0x0210 + cls.DirectMethods[1].Code.Instructions[5] = 0x3070 + cls.DirectMethods[1].Code.Instructions[7] = 0x0210 + cls.DirectMethods[1].Code.Instructions[15] = 0x3070 + cls.DirectMethods[1].Code.Instructions[17] = 0x0210 + + res, err := ClassWithPolicy(file, cls, ClassOptions{}, Recover) + if err != nil { + t.Fatalf("ClassWithPolicy failed on enum: %v", err) + } + parsed, err := javaclassparser.Parse(res.Bytes) + if err != nil { + t.Fatalf("Parse failed: %v", err) + } + if len(parsed.Fields) < 2 { + t.Fatalf("expected >= 2 fields, got %d", len(parsed.Fields)) + } + f0 := parsed.ConstantPoolManager.GetUtf8(int(parsed.Fields[0].NameIndex)).Value + f1 := parsed.ConstantPoolManager.GetUtf8(int(parsed.Fields[1].NameIndex)).Value + if f0 != "ZEBRA" || f1 != "ALPHA" { + t.Fatalf("reordered static fields = [%q, %q], want [ZEBRA, ALPHA]", f0, f1) + } + src, err := javaclassparser.Decompile(res.Bytes) + if err != nil { + t.Fatalf("strict Decompile failed: %v", err) + } + if !strings.Contains(src, "public enum OrderColor") { + t.Fatalf("expected `public enum OrderColor` in strict decompiled source, got:\n%s", src) + } + if strings.Contains(src, "extends Enum") { + t.Fatalf("expected real enum declaration without `extends Enum`:\n%s", src) + } + if strings.Contains(src, "ParseBytesCode failed") { + t.Fatalf("unexpected stub in strict enum decompilation:\n%s", src) + } + if strings.Contains(src, "static {") { + t.Fatalf("expected enum constants to lift cleanly with zero `static {` block:\n%s", src) + } + zebraIdx := strings.Index(src, "ZEBRA") + alphaIdx := strings.Index(src, "ALPHA") + if zebraIdx < 0 || alphaIdx < 0 || zebraIdx > alphaIdx { + t.Fatalf("expected ZEBRA declared before ALPHA in decompiled source:\n%s", src) + } + _ = bytes.TrimSpace(res.Bytes) +} diff --git a/dex2jar/lower/wave3_soundness_test.go b/dex2jar/lower/wave3_soundness_test.go new file mode 100644 index 00000000..88a3dc97 --- /dev/null +++ b/dex2jar/lower/wave3_soundness_test.go @@ -0,0 +1,941 @@ +package lower + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + javaclassparser "github.com/yaklang/javajive/classparser" + "github.com/yaklang/javajive/dex2jar/model" +) + +func runMultipleWithVerify(t *testing.T, classes map[string][]byte, mainClass string) { + t.Helper() + for name, raw := range classes { + if _, err := javaclassparser.Parse(raw); err != nil { + t.Fatalf("Parse(%s) failed: %v", name, err) + } + } + java, err := exec.LookPath("java") + if err != nil { + return + } + dir := t.TempDir() + for name, raw := range classes { + dst := filepath.Join(dir, filepath.FromSlash(name)+".class") + if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(dst, raw, 0o644); err != nil { + t.Fatal(err) + } + } + if out, err := exec.Command(java, "-Xverify:all", "-cp", dir, mainClass).CombinedOutput(); err != nil { + t.Fatalf("java -Xverify:all %s failed: %v\n%s", mainClass, err, out) + } +} + +func TestWave3AssignHomesLegacyPinnedZeroKindVerify(t *testing.T) { + // Exceed assignWebs cap (Blocks*RegistersSize > 200000) so assignHomesLegacy + // handles register v0, where an if-eqz / const/4 0 leaves const/4 0 typed as + // Null while another definition in v0 uses PolyZeroInt (without Float or Ref). + // Step 1 ensures pinnedZeroKind[v0] = ir.Int resolves const/4 0 to ICONST_0 + // rather than ACONST_NULL. + const owner = "Ldex/LegacyPinnedZero;" + file := &model.File{ + Entry: "classes.dex", + Types: []model.Type{ + {Descriptor: owner}, + {Descriptor: "I"}, + {Descriptor: "V"}, + {Descriptor: "[Ljava/lang/String;"}, + }, + Protos: []model.Proto{ + {ReturnType: "I", Parameters: []string{"I", "I"}, ParameterTypes: []uint32{1, 1}}, + {ReturnType: "V", Parameters: []string{"[Ljava/lang/String;"}, ParameterTypes: []uint32{3}}, + }, + Methods: []model.MethodID{ + {Class: owner, Name: "legacy", ProtoIndex: 0}, + {Class: owner, Name: "main", ProtoIndex: 1}, + }, + } + var insns []uint16 + // 101 goto +1 instructions create 102 blocks; * 2048 regs = 208896 > 200000 -> assignHomesLegacy. + for i := 0; i < 101; i++ { + insns = append(insns, 0x0128) // goto +1 + } + // Block 101+: + // const/4 v0, #0 (defCat=Null because if-eqz demands nothing yet, regNarrowMask[v0]==PolyZeroInt) + // if-eqz v2, +2 (if v2 == 0 jump past overwrite) + // const/4 v0, #7 + // add-int/2addr v0, v1 + // return v0 + // Wait: here v0 at add-int/2addr would propagate Int backward unless v0 was ALSO redefined! + // Even better: + // const/4 v0, #0 (followed immediately by if-eqz v0, +2 -> target returns v1; fallthrough does const/4 v0, #3 + add-int + return v0) + // On the fallthrough path, const/4 v0, #3 overwrites v0 before add-int, so const/4 v0, #0 stays Null + // while regNarrowMask[v0] == PolyZeroInt! + insns = append(insns, + 0x0012, // const/4 v0, #0 + 0x0038, 0x0006, // if-eqz v0, +6 -> const/4 v0, #4 + 0x3012, // const/4 v0, #3 + 0x5112, // const/4 v1, #5 + 0x10b0, // add-int/2addr v0, v1 + 0x000f, // return v0 + 0x4012, // target: const/4 v0, #4 + 0x000f, // return v0 + ) + + cls := &model.Class{ + Descriptor: owner, + Superclass: "Ljava/lang/Object;", + AccessFlags: dexPublic, + DirectMethods: []model.EncodedMethod{ + { + MethodIndex: 0, + AccessFlags: dexPublic | dexStatic, + Method: file.Methods[0], + Code: &model.Code{ + RegistersSize: 2048, InsSize: 2, OutsSize: 0, + Instructions: insns, + }, + }, + { + MethodIndex: 1, + AccessFlags: dexPublic | dexStatic, + Method: file.Methods[1], + Code: &model.Code{ + RegistersSize: 3, InsSize: 1, OutsSize: 2, + Instructions: []uint16{ + 0x1012, // const/4 v0, #1 + 0x2112, // const/4 v1, #2 + 0x2071, 0x0000, 0x0010, // invoke-static {v0, v1}, legacy(II)I + 0x000a, // move-result v0 + 0x000e, // return-void + }, + }, + }, + }, + } + + raw, err := Class(file, cls) + if err != nil { + t.Fatalf("Class failed: %v", err) + } + code := findWave2MethodCode(t, raw, "legacy") + // Verify every byte in legacy(): const/4 v0, #0 should emit ICONST_0 (0x03), never ACONST_NULL (0x01) + ASTORE. + hasAconstNull := false + for _, b := range code.Code { + if b == 0x01 { + hasAconstNull = true + break + } + } + if hasAconstNull { + t.Fatalf("legacy() emitted ACONST_NULL for single-kind PolyZeroInt register v0: %x", code.Code) + } + runMainWithVerify(t, raw, "dex.LegacyPinnedZero") +} + +func TestWave3NullArrayOpsVerify(t *testing.T) { + const owner = "Ldex/NullArrayOps;" + file := &model.File{ + Entry: "classes.dex", + Types: []model.Type{ + {Descriptor: owner}, + {Descriptor: "Ljava/lang/String;"}, + {Descriptor: "Ljava/lang/NullPointerException;"}, + {Descriptor: "V"}, + {Descriptor: "[Ljava/lang/String;"}, + }, + Protos: []model.Proto{ + {ReturnType: "Ljava/lang/String;", Parameters: []string{"Ljava/lang/String;"}, ParameterTypes: []uint32{1}}, + {ReturnType: "V", Parameters: []string{"[Ljava/lang/String;"}, ParameterTypes: []uint32{4}}, + }, + Methods: []model.MethodID{ + {Class: owner, Name: "probe", ProtoIndex: 0}, + {Class: owner, Name: "main", ProtoIndex: 1}, + }, + } + cls := &model.Class{ + Descriptor: owner, + Superclass: "Ljava/lang/Object;", + AccessFlags: dexPublic, + DirectMethods: []model.EncodedMethod{ + { + MethodIndex: 0, + AccessFlags: dexPublic | dexStatic, + Method: file.Methods[0], + Code: &model.Code{ + RegistersSize: 4, InsSize: 1, OutsSize: 0, // v3 = arg String + Instructions: []uint16{ + 0x0012, // 0: const/4 v0, #0 (null array) + 0x0112, // 1: const/4 v1, #0 (index 0) + 0x0246, 0x0100, // 2..3: aget-object v2, v0, v1 + 0x034d, 0x0100, // 4..5: aput-object v3, v0, v1 + 0x0144, 0x0100, // 6..7: aget v1, v0, v1 + 0x0211, // 8: return-object v2 + }, + }, + }, + { + MethodIndex: 1, + AccessFlags: dexPublic | dexStatic, + Method: file.Methods[1], + Code: &model.Code{ + RegistersSize: 2, InsSize: 1, OutsSize: 1, + Instructions: []uint16{ + 0x0012, // 0: const/4 v0, #0 + 0x1071, 0x0000, 0x0000, // 1..3: invoke-static {v0}, probe(String)String + 0x000e, // 4: return-void (try ends at 4) + 0x000d, // 5: move-exception v0 + 0x000e, // 6: return-void + }, + Tries: []model.Try{ + { + StartAddress: 1, InstructionCount: 3, + Handler: model.CatchHandler{Handlers: []model.TypedHandler{{TypeIndex: 2, Type: "Ljava/lang/NullPointerException;", Address: 5}}}, + }, + }, + }, + }, + }, + } + + raw, err := Class(file, cls) + if err != nil { + t.Fatalf("Class failed on null array ops: %v", err) + } + runMainWithVerify(t, raw, "dex.NullArrayOps") +} + +func TestWave3InterfaceAssignabilityAcceptsButConcreteRejects(t *testing.T) { + const ( + implDesc = "LC0/e;" + ifaceDesc = "LN0/f;" + otherDesc = "LO0/g;" + hostDesc = "LD0/H;" + ) + buildFixture := func(expectedDesc string) (*model.File, *model.Class) { + file := &model.File{ + Entry: "classes.dex", + Types: []model.Type{ + {Descriptor: "Ljava/lang/Object;"}, + {Descriptor: implDesc}, + {Descriptor: ifaceDesc}, + {Descriptor: otherDesc}, + {Descriptor: hostDesc}, + {Descriptor: "V"}, + {Descriptor: "[Ljava/lang/String;"}, + }, + Protos: []model.Proto{ + {ReturnType: "V"}, // 0 + {ReturnType: "V", Parameters: []string{implDesc}, ParameterTypes: []uint32{1}}, // 1 + {ReturnType: "V", Parameters: []string{expectedDesc}, ParameterTypes: []uint32{2}}, // 2 + {ReturnType: "V", Parameters: []string{"[Ljava/lang/String;"}, ParameterTypes: []uint32{6}}, + }, + Methods: []model.MethodID{ + {Class: "Ljava/lang/Object;", Name: "", ProtoIndex: 0}, // 0 + {Class: implDesc, Name: "", ProtoIndex: 0}, // 1 + {Class: hostDesc, Name: "z", ProtoIndex: 1}, // 2 + {Class: hostDesc, Name: "accept", ProtoIndex: 2}, // 3 + {Class: hostDesc, Name: "main", ProtoIndex: 3}, // 4 + }, + Classes: []model.Class{ + {Descriptor: implDesc, Superclass: "Ljava/lang/Object;", AccessFlags: dexPublic}, + {Descriptor: ifaceDesc, Superclass: "Ljava/lang/Object;", AccessFlags: dexPublic | dexInterface | dexAbstract}, + {Descriptor: otherDesc, Superclass: "Ljava/lang/Object;", AccessFlags: dexPublic}, + }, + } + if expectedDesc == otherDesc { + file.Protos[2].ParameterTypes[0] = 3 + } + host := &model.Class{ + Descriptor: hostDesc, + Superclass: "Ljava/lang/Object;", + AccessFlags: dexPublic, + DirectMethods: []model.EncodedMethod{ + { + MethodIndex: 2, + AccessFlags: dexPublic | dexStatic, + Method: file.Methods[2], + Code: &model.Code{ + RegistersSize: 1, InsSize: 1, OutsSize: 1, + Instructions: []uint16{ + 0x1071, 0x0003, 0x0000, // invoke-static {v0}, accept(expected)V + 0x000e, + }, + }, + }, + { + MethodIndex: 3, + AccessFlags: dexPublic | dexStatic, + Method: file.Methods[3], + Code: &model.Code{ + RegistersSize: 1, InsSize: 1, OutsSize: 0, + Instructions: []uint16{0x000e}, + }, + }, + { + MethodIndex: 4, + AccessFlags: dexPublic | dexStatic, + Method: file.Methods[4], + Code: &model.Code{ + RegistersSize: 2, InsSize: 1, OutsSize: 1, + Instructions: []uint16{ + 0x0012, // const/4 v0, #0 (null C0.e) + 0x1071, 0x0002, 0x0000, // invoke-static {v0}, z(C0/e;)V + 0x000e, + }, + }, + }, + }, + } + file.Classes = append(file.Classes, *host) + return file, host + } + + ifaceFile, ifaceHost := buildFixture(ifaceDesc) + hostRaw, err := Class(ifaceFile, ifaceHost) + if err != nil { + t.Fatalf("concrete -> unimplemented interface rejected: %v", err) + } + implRaw, err := Class(ifaceFile, &ifaceFile.Classes[0]) + if err != nil { + t.Fatalf("impl Class failed: %v", err) + } + ifaceRaw, err := Class(ifaceFile, &ifaceFile.Classes[1]) + if err != nil { + t.Fatalf("iface Class failed: %v", err) + } + runMultipleWithVerify(t, map[string][]byte{ + "D0/H": hostRaw, + "C0/e": implRaw, + "N0/f": ifaceRaw, + }, "D0.H") + + badFile, badHost := buildFixture(otherDesc) + if _, err := Class(badFile, badHost); err == nil || !strings.Contains(err.Error(), "not provably assignable") { + t.Fatalf("concrete -> unrelated concrete class error = %v, want not provably assignable", err) + } +} + +func TestWave3CanonicalEnumHelperAndKotlinEntries(t *testing.T) { + t.Run("synthetic $values() helper", func(t *testing.T) { + const owner = "Ldex/HelperColor;" + const arrayOwner = "[Ldex/HelperColor;" + file := &model.File{ + Entry: "classes.dex", + Strings: []string{"RED", "GREEN"}, + Types: []model.Type{ + {Descriptor: owner}, + {Descriptor: "Ljava/lang/Enum;"}, + {Descriptor: "Ljava/lang/String;"}, + {Descriptor: "I"}, + {Descriptor: "V"}, + {Descriptor: arrayOwner}, + {Descriptor: "Ljava/lang/Object;"}, + {Descriptor: "Ljava/lang/Class;"}, + {Descriptor: "[Ljava/lang/String;"}, + }, + Fields: []model.FieldID{ + {Class: owner, Name: "RED", Type: owner}, + {Class: owner, Name: "GREEN", Type: owner}, + {Class: owner, Name: "$VALUES", Type: arrayOwner}, + }, + Protos: []model.Proto{ + {ReturnType: "V", Parameters: []string{"Ljava/lang/String;", "I"}, ParameterTypes: []uint32{2, 3}}, + {ReturnType: "V"}, + {ReturnType: arrayOwner}, + {ReturnType: owner, Parameters: []string{"Ljava/lang/String;"}, ParameterTypes: []uint32{2}}, + {ReturnType: "Ljava/lang/Object;"}, + {ReturnType: "Ljava/lang/Enum;", Parameters: []string{"Ljava/lang/Class;", "Ljava/lang/String;"}, ParameterTypes: []uint32{7, 2}}, + {ReturnType: "V", Parameters: []string{"[Ljava/lang/String;"}, ParameterTypes: []uint32{8}}, + }, + Methods: []model.MethodID{ + {Class: "Ljava/lang/Enum;", Name: "", ProtoIndex: 0}, // 0 + {Class: owner, Name: "", ProtoIndex: 0}, // 1 + {Class: owner, Name: "", ProtoIndex: 1}, // 2 + {Class: owner, Name: "$values", ProtoIndex: 2}, // 3 + {Class: owner, Name: "values", ProtoIndex: 2}, // 4 + {Class: arrayOwner, Name: "clone", ProtoIndex: 4}, // 5 + {Class: owner, Name: "valueOf", ProtoIndex: 3}, // 6 + {Class: "Ljava/lang/Enum;", Name: "valueOf", ProtoIndex: 5}, // 7 + {Class: owner, Name: "main", ProtoIndex: 6}, // 8 + }, + } + cls := &model.Class{ + Descriptor: owner, + Superclass: "Ljava/lang/Enum;", + AccessFlags: dexPublic | dexFinal | dexEnum, + StaticFields: []model.EncodedField{ + {FieldIndex: 0, AccessFlags: dexPublic | dexStatic | dexFinal | dexEnum, Field: file.Fields[0]}, + {FieldIndex: 1, AccessFlags: dexPublic | dexStatic | dexFinal | dexEnum, Field: file.Fields[1]}, + {FieldIndex: 2, AccessFlags: dexPrivate | dexStatic | dexFinal | dexSynthetic, Field: file.Fields[2]}, + }, + DirectMethods: []model.EncodedMethod{ + { + MethodIndex: 1, + AccessFlags: dexPrivate | dexConstructor, + Method: file.Methods[1], + Code: &model.Code{ + RegistersSize: 3, InsSize: 3, OutsSize: 3, + Instructions: []uint16{0x3070, 0x0000, 0x0210, 0x000e}, + }, + }, + { + MethodIndex: 3, // $values() + AccessFlags: dexPrivate | dexStatic | dexSynthetic, + Method: file.Methods[3], + Code: &model.Code{ + RegistersSize: 3, InsSize: 0, OutsSize: 0, + Instructions: []uint16{ + 0x2012, // const/4 v0, #2 + 0x0023, 0x0005, // new-array v0, v0, [Ldex/HelperColor; + 0x0162, 0x0000, // sget-object v1, RED + 0x0212, // const/4 v2, #0 + 0x014d, 0x0200, // aput-object v1, v0[v2] + 0x0162, 0x0001, // sget-object v1, GREEN + 0x1212, // const/4 v2, #1 + 0x014d, 0x0200, // aput-object v1, v0[v2] + 0x0011, // return-object v0 + }, + }, + }, + { + MethodIndex: 2, // () calls $values() + AccessFlags: dexStatic | dexConstructor, + Method: file.Methods[2], + Code: &model.Code{ + RegistersSize: 3, InsSize: 0, OutsSize: 3, + Instructions: []uint16{ + 0x0022, 0x0000, // new-instance v0, HelperColor + 0x011a, 0x0000, // const-string v1, "RED" + 0x0212, // const/4 v2, #0 + 0x3070, 0x0001, 0x0210, // invoke-direct {v0, v1, v2}, + 0x0069, 0x0000, // sput-object v0, RED + 0x0022, 0x0000, // new-instance v0, HelperColor + 0x011a, 0x0001, // const-string v1, "GREEN" + 0x1212, // const/4 v2, #1 + 0x3070, 0x0001, 0x0210, // invoke-direct {v0, v1, v2}, + 0x0069, 0x0001, // sput-object v0, GREEN + 0x0071, 0x0003, 0x0000, // invoke-static {}, $values() + 0x000c, // move-result-object v0 + 0x0069, 0x0002, // sput-object v0, $VALUES + 0x000e, // return-void + }, + }, + }, + { + MethodIndex: 4, // values() + AccessFlags: dexPublic | dexStatic, + Method: file.Methods[4], + Code: &model.Code{ + RegistersSize: 1, InsSize: 0, OutsSize: 1, + Instructions: []uint16{0x0062, 0x0002, 0x106e, 0x0005, 0x0000, 0x000c, 0x001f, 0x0005, 0x0011}, + }, + }, + { + MethodIndex: 6, // valueOf(String) + AccessFlags: dexPublic | dexStatic, + Method: file.Methods[6], + Code: &model.Code{ + RegistersSize: 2, InsSize: 1, OutsSize: 2, + Instructions: []uint16{0x001c, 0x0000, 0x2071, 0x0007, 0x0010, 0x000c, 0x001f, 0x0000, 0x0011}, + }, + }, + { + MethodIndex: 8, // main([String;)V + AccessFlags: dexPublic | dexStatic, + Method: file.Methods[8], + Code: &model.Code{ + RegistersSize: 2, InsSize: 1, OutsSize: 0, + Instructions: []uint16{ + 0x0071, 0x0004, 0x0000, // invoke-static {}, values() + 0x000c, // move-result-object v0 + 0x000e, + }, + }, + }, + }, + } + raw, err := Class(file, cls) + if err != nil { + t.Fatalf("strict Class failed: %v", err) + } + src, err := javaclassparser.Decompile(raw) + if err != nil { + t.Fatalf("strict Decompile failed: %v", err) + } + if !strings.Contains(src, "public enum HelperColor") || strings.Contains(src, "extends Enum") || strings.Contains(src, "ParseBytesCode failed") { + t.Fatalf("unexpected HelperColor decompile output:\n%s", src) + } + if !strings.Contains(src, "RED") || !strings.Contains(src, "GREEN") { + t.Fatalf("missing constants in HelperColor:\n%s", src) + } + runMainWithVerify(t, raw, "dex.HelperColor") + }) + + t.Run("Kotlin $VALUES and $ENTRIES tail", func(t *testing.T) { + const owner = "Ldex/KtColor;" + const arrayOwner = "[Ldex/KtColor;" + file := &model.File{ + Entry: "classes.dex", + Strings: []string{"ONE", "TWO"}, + Types: []model.Type{ + {Descriptor: owner}, + {Descriptor: "Ljava/lang/Enum;"}, + {Descriptor: "Ljava/lang/String;"}, + {Descriptor: "I"}, + {Descriptor: "V"}, + {Descriptor: arrayOwner}, + {Descriptor: "Ljava/lang/Object;"}, + {Descriptor: "Ljava/lang/Class;"}, + {Descriptor: "[Ljava/lang/Enum;"}, + {Descriptor: "Lkotlin/enums/EnumEntries;"}, + }, + Fields: []model.FieldID{ + {Class: owner, Name: "ONE", Type: owner}, + {Class: owner, Name: "TWO", Type: owner}, + {Class: owner, Name: "$VALUES", Type: arrayOwner}, + {Class: owner, Name: "$ENTRIES", Type: "Lkotlin/enums/EnumEntries;"}, + }, + Protos: []model.Proto{ + {ReturnType: "V", Parameters: []string{"Ljava/lang/String;", "I"}, ParameterTypes: []uint32{2, 3}}, + {ReturnType: "V"}, + {ReturnType: arrayOwner}, + {ReturnType: owner, Parameters: []string{"Ljava/lang/String;"}, ParameterTypes: []uint32{2}}, + {ReturnType: "Ljava/lang/Object;"}, + {ReturnType: "Ljava/lang/Enum;", Parameters: []string{"Ljava/lang/Class;", "Ljava/lang/String;"}, ParameterTypes: []uint32{7, 2}}, + {ReturnType: "Lkotlin/enums/EnumEntries;", Parameters: []string{"[Ljava/lang/Enum;"}, ParameterTypes: []uint32{8}}, + }, + Methods: []model.MethodID{ + {Class: "Ljava/lang/Enum;", Name: "", ProtoIndex: 0}, // 0 + {Class: owner, Name: "", ProtoIndex: 0}, // 1 + {Class: owner, Name: "", ProtoIndex: 1}, // 2 + {Class: owner, Name: "values", ProtoIndex: 2}, // 3 + {Class: arrayOwner, Name: "clone", ProtoIndex: 4}, // 4 + {Class: owner, Name: "valueOf", ProtoIndex: 3}, // 5 + {Class: "Ljava/lang/Enum;", Name: "valueOf", ProtoIndex: 5}, // 6 + {Class: "Lkotlin/enums/EnumEntriesKt;", Name: "enumEntries", ProtoIndex: 6}, // 7 + }, + } + cls := &model.Class{ + Descriptor: owner, + Superclass: "Ljava/lang/Enum;", + AccessFlags: dexPublic | dexFinal | dexEnum, + StaticFields: []model.EncodedField{ + {FieldIndex: 0, AccessFlags: dexPublic | dexStatic | dexFinal | dexEnum, Field: file.Fields[0]}, + {FieldIndex: 1, AccessFlags: dexPublic | dexStatic | dexFinal | dexEnum, Field: file.Fields[1]}, + {FieldIndex: 2, AccessFlags: dexPrivate | dexStatic | dexFinal | dexSynthetic, Field: file.Fields[2]}, + {FieldIndex: 3, AccessFlags: dexPrivate | dexStatic | dexFinal | dexSynthetic, Field: file.Fields[3]}, + }, + DirectMethods: []model.EncodedMethod{ + { + MethodIndex: 1, + AccessFlags: dexPrivate | dexConstructor, + Method: file.Methods[1], + Code: &model.Code{ + RegistersSize: 3, InsSize: 3, OutsSize: 3, + Instructions: []uint16{0x3070, 0x0000, 0x0210, 0x000e}, + }, + }, + { + MethodIndex: 2, // with inline $VALUES and $ENTRIES tail + AccessFlags: dexStatic | dexConstructor, + Method: file.Methods[2], + Code: &model.Code{ + RegistersSize: 4, InsSize: 0, OutsSize: 3, + Instructions: []uint16{ + 0x0022, 0x0000, // new-instance v0 + 0x011a, 0x0000, // "ONE" + 0x0212, + 0x3070, 0x0001, 0x0210, + 0x0069, 0x0000, // sput ONE + 0x0022, 0x0000, // new-instance v0 + 0x011a, 0x0001, // "TWO" + 0x1212, + 0x3070, 0x0001, 0x0210, + 0x0069, 0x0001, // sput TWO + 0x2312, // const/4 v3, #2 + 0x3023, 0x0005, // new-array v0, v3, [KtColor + 0x0162, 0x0000, // sget ONE + 0x0212, + 0x014d, 0x0200, // aput + 0x0162, 0x0001, // sget TWO + 0x1212, + 0x014d, 0x0200, // aput + 0x0069, 0x0002, // sput $VALUES + 0x0062, 0x0002, // sget $VALUES + 0x001f, 0x0008, // check-cast v0, [Ljava/lang/Enum; + 0x1071, 0x0007, 0x0000, // invoke-static {v0}, EnumEntriesKt.enumEntries + 0x000c, // move-result-object v0 + 0x0069, 0x0003, // sput $ENTRIES + 0x000e, + }, + }, + }, + { + MethodIndex: 3, // values() + AccessFlags: dexPublic | dexStatic, + Method: file.Methods[3], + Code: &model.Code{ + RegistersSize: 1, InsSize: 0, OutsSize: 1, + Instructions: []uint16{0x0062, 0x0002, 0x106e, 0x0004, 0x0000, 0x000c, 0x001f, 0x0005, 0x0011}, + }, + }, + { + MethodIndex: 5, // valueOf(String) + AccessFlags: dexPublic | dexStatic, + Method: file.Methods[5], + Code: &model.Code{ + RegistersSize: 2, InsSize: 1, OutsSize: 2, + Instructions: []uint16{0x001c, 0x0000, 0x2071, 0x0006, 0x0010, 0x000c, 0x001f, 0x0000, 0x0011}, + }, + }, + }, + } + raw, err := Class(file, cls) + if err != nil { + t.Fatalf("strict Class failed on KtColor: %v", err) + } + src, err := javaclassparser.Decompile(raw) + if err != nil { + t.Fatalf("strict Decompile failed on KtColor: %v", err) + } + if !strings.Contains(src, "public enum KtColor") || strings.Contains(src, "extends Enum") || strings.Contains(src, "ParseBytesCode failed") { + t.Fatalf("unexpected KtColor decompile output:\n%s", src) + } + if !strings.Contains(src, "ONE") || !strings.Contains(src, "TWO") { + t.Fatalf("missing constants in KtColor:\n%s", src) + } + }) + + t.Run("Kotlin [Ljava/lang/Object;.clone()", func(t *testing.T) { + const owner = "Ldex/KtCloneColor;" + const arrayOwner = "[Ldex/KtCloneColor;" + file := &model.File{ + Entry: "classes.dex", + Strings: []string{"ONE", "TWO"}, + Types: []model.Type{ + {Descriptor: owner}, + {Descriptor: "Ljava/lang/Enum;"}, + {Descriptor: "Ljava/lang/String;"}, + {Descriptor: "I"}, + {Descriptor: "V"}, + {Descriptor: arrayOwner}, + {Descriptor: "Ljava/lang/Object;"}, + {Descriptor: "Ljava/lang/Class;"}, + {Descriptor: "[Ljava/lang/Object;"}, + }, + Fields: []model.FieldID{ + {Class: owner, Name: "ONE", Type: owner}, + {Class: owner, Name: "TWO", Type: owner}, + {Class: owner, Name: "$VALUES", Type: arrayOwner}, + }, + Protos: []model.Proto{ + {ReturnType: "V", Parameters: []string{"Ljava/lang/String;", "I"}, ParameterTypes: []uint32{2, 3}}, + {ReturnType: "V"}, + {ReturnType: arrayOwner}, + {ReturnType: owner, Parameters: []string{"Ljava/lang/String;"}, ParameterTypes: []uint32{2}}, + {ReturnType: "Ljava/lang/Object;"}, + {ReturnType: "Ljava/lang/Enum;", Parameters: []string{"Ljava/lang/Class;", "Ljava/lang/String;"}, ParameterTypes: []uint32{7, 2}}, + }, + Methods: []model.MethodID{ + {Class: "Ljava/lang/Enum;", Name: "", ProtoIndex: 0}, // 0 + {Class: owner, Name: "", ProtoIndex: 0}, // 1 + {Class: owner, Name: "", ProtoIndex: 1}, // 2 + {Class: owner, Name: "values", ProtoIndex: 2}, // 3 + {Class: "[Ljava/lang/Object;", Name: "clone", ProtoIndex: 4}, // 4 + {Class: owner, Name: "valueOf", ProtoIndex: 3}, // 5 + {Class: "Ljava/lang/Enum;", Name: "valueOf", ProtoIndex: 5}, // 6 + }, + } + cls := &model.Class{ + Descriptor: owner, + Superclass: "Ljava/lang/Enum;", + AccessFlags: dexPublic | dexFinal | dexEnum, + StaticFields: []model.EncodedField{ + {FieldIndex: 0, AccessFlags: dexPublic | dexStatic | dexFinal | dexEnum, Field: file.Fields[0]}, + {FieldIndex: 1, AccessFlags: dexPublic | dexStatic | dexFinal | dexEnum, Field: file.Fields[1]}, + {FieldIndex: 2, AccessFlags: dexPrivate | dexStatic | dexFinal | dexSynthetic, Field: file.Fields[2]}, + }, + DirectMethods: []model.EncodedMethod{ + { + MethodIndex: 1, + AccessFlags: dexPrivate | dexConstructor, + Method: file.Methods[1], + Code: &model.Code{ + RegistersSize: 3, InsSize: 3, OutsSize: 3, + Instructions: []uint16{0x3070, 0x0000, 0x0210, 0x000e}, + }, + }, + { + MethodIndex: 2, + AccessFlags: dexStatic | dexConstructor, + Method: file.Methods[2], + Code: &model.Code{ + RegistersSize: 4, InsSize: 0, OutsSize: 3, + Instructions: []uint16{ + 0x0022, 0x0000, + 0x011a, 0x0000, + 0x0212, + 0x3070, 0x0001, 0x0210, + 0x0069, 0x0000, + 0x0022, 0x0000, + 0x011a, 0x0001, + 0x1212, + 0x3070, 0x0001, 0x0210, + 0x0069, 0x0001, + 0x2312, + 0x3023, 0x0005, + 0x0162, 0x0000, + 0x0212, + 0x014d, 0x0200, + 0x0162, 0x0001, + 0x1212, + 0x014d, 0x0200, + 0x0069, 0x0002, + 0x000e, + }, + }, + }, + { + MethodIndex: 3, + AccessFlags: dexPublic | dexStatic, + Method: file.Methods[3], + Code: &model.Code{ + RegistersSize: 1, InsSize: 0, OutsSize: 1, + Instructions: []uint16{0x0062, 0x0002, 0x106e, 0x0004, 0x0000, 0x000c, 0x001f, 0x0005, 0x0011}, + }, + }, + { + MethodIndex: 5, + AccessFlags: dexPublic | dexStatic, + Method: file.Methods[5], + Code: &model.Code{ + RegistersSize: 2, InsSize: 1, OutsSize: 2, + Instructions: []uint16{0x001c, 0x0000, 0x2071, 0x0006, 0x0010, 0x000c, 0x001f, 0x0000, 0x0011}, + }, + }, + }, + } + raw, err := Class(file, cls) + if err != nil { + t.Fatalf("strict Class failed on KtCloneColor: %v", err) + } + src, err := javaclassparser.Decompile(raw) + if err != nil { + t.Fatalf("strict Decompile failed on KtCloneColor: %v", err) + } + if !strings.Contains(src, "public enum KtCloneColor") || strings.Contains(src, "extends Enum") || strings.Contains(src, "ParseBytesCode failed") { + t.Fatalf("unexpected KtCloneColor decompile output:\n%s", src) + } + if !strings.Contains(src, "ONE") || !strings.Contains(src, "TWO") { + t.Fatalf("missing constants in KtCloneColor:\n%s", src) + } + }) +} + +func TestWave3MoveNullToPinnedIntNoStackMismatchVerify(t *testing.T) { + const owner = "Ldex/MoveNullPinnedInt;" + file := &model.File{ + Entry: "classes.dex", + Types: []model.Type{ + {Descriptor: owner}, + {Descriptor: "I"}, + {Descriptor: "V"}, + {Descriptor: "[Ljava/lang/String;"}, + }, + Protos: []model.Proto{ + {ReturnType: "I"}, + {ReturnType: "V", Parameters: []string{"[Ljava/lang/String;"}, ParameterTypes: []uint32{3}}, + {ReturnType: "V"}, + }, + Methods: []model.MethodID{ + {Class: owner, Name: "legacy", ProtoIndex: 0}, + {Class: owner, Name: "main", ProtoIndex: 1}, + {Class: owner, Name: "ping", ProtoIndex: 2}, + }, + } + var insns []uint16 + for i := 0; i < 101; i++ { + insns = append(insns, 0x0128) // goto +1 -> exceed assignWebs cap (102*2048 > 200000) + } + base := uint32(len(insns)) + // v0 = const/4 0 (no pinned int demand, stays RefLocal in assignHomesLegacy); + // move v1, v0 copies zero into v1 which is pinned Int via const/4 #3 + add-int/2addr. + // Try/catch forces computeStackMapFrames() -> transferSlotFrame() -> verifyTagForLocalKind(). + insns = append(insns, + 0x0012, // +0: const/4 v0, #0 + 0x0101, // +1: move v1, v0 + 0x0071, 0x0002, 0x0000, // +2..+4: invoke-static {}, ping()V + 0x0138, 0x0006, // +5..+6: if-eqz v1, +6 -> +11 (const/4 v1, #4) + 0x3112, // +7: const/4 v1, #3 + 0x5212, // +8: const/4 v2, #5 + 0x21b0, // +9: add-int/2addr v1, v2 + 0x010f, // +10: return v1 + 0x4112, // +11: const/4 v1, #4 + 0x010f, // +12: return v1 + 0x000d, // +13: move-exception v0 + 0x7112, // +14: const/4 v1, #7 + 0x010f, // +15: return v1 + ) + catchAllAddr := base + 13 + cls := &model.Class{ + Descriptor: owner, + Superclass: "Ljava/lang/Object;", + AccessFlags: dexPublic, + DirectMethods: []model.EncodedMethod{ + { + MethodIndex: 0, + AccessFlags: dexPublic | dexStatic, + Method: file.Methods[0], + Code: &model.Code{ + RegistersSize: 2048, InsSize: 0, OutsSize: 0, + Instructions: insns, + Tries: []model.Try{ + { + StartAddress: base + 2, InstructionCount: 3, + Handler: model.CatchHandler{CatchAllAddress: &catchAllAddr}, + }, + }, + }, + }, + { + MethodIndex: 1, + AccessFlags: dexPublic | dexStatic, + Method: file.Methods[1], + Code: &model.Code{ + RegistersSize: 2, InsSize: 1, OutsSize: 0, + Instructions: []uint16{ + 0x0071, 0x0000, 0x0000, // invoke-static {}, legacy()I + 0x000a, // move-result v0 + 0x000e, // return-void + }, + }, + }, + { + MethodIndex: 2, + AccessFlags: dexPublic | dexStatic, + Method: file.Methods[2], + Code: &model.Code{ + RegistersSize: 1, InsSize: 0, OutsSize: 0, + Instructions: []uint16{0x000e}, + }, + }, + }, + } + raw, err := Class(file, cls) + if err != nil { + t.Fatalf("Class failed: %v", err) + } + runMainWithVerify(t, raw, "dex.MoveNullPinnedInt") +} + +func TestWave3NullMergedWithArrayAfterNonArrayRefUseVerify(t *testing.T) { + const owner = "Ldex/NullMergedArray;" + file := &model.File{ + Entry: "classes.dex", + Types: []model.Type{ + {Descriptor: owner}, + {Descriptor: "Ljava/lang/CharSequence;"}, + {Descriptor: "[Ljava/lang/String;"}, + {Descriptor: "I"}, + {Descriptor: "V"}, + {Descriptor: "Ljava/lang/NullPointerException;"}, + }, + Protos: []model.Proto{ + {ReturnType: "V", Parameters: []string{"Ljava/lang/CharSequence;"}, ParameterTypes: []uint32{1}}, + {ReturnType: "Ljava/lang/String;", Parameters: []string{"I"}, ParameterTypes: []uint32{3}}, + {ReturnType: "V", Parameters: []string{"[Ljava/lang/String;"}, ParameterTypes: []uint32{2}}, + }, + Methods: []model.MethodID{ + {Class: owner, Name: "touch", ProtoIndex: 0}, + {Class: owner, Name: "probe", ProtoIndex: 1}, + {Class: owner, Name: "main", ProtoIndex: 2}, + }, + } + cls := &model.Class{ + Descriptor: owner, + Superclass: "Ljava/lang/Object;", + AccessFlags: dexPublic, + DirectMethods: []model.EncodedMethod{ + { + MethodIndex: 0, // touch(CharSequence)V + AccessFlags: dexPublic | dexStatic, + Method: file.Methods[0], + Code: &model.Code{ + RegistersSize: 1, InsSize: 1, OutsSize: 0, + Instructions: []uint16{0x000e}, + }, + }, + { + MethodIndex: 1, // probe(I)String + AccessFlags: dexPublic | dexStatic, + Method: file.Methods[1], + Code: &model.Code{ + RegistersSize: 5, InsSize: 1, OutsSize: 1, // v4 = I arg + Instructions: []uint16{ + 0x0112, // 0: const/4 v1, #0 + 0x1071, 0x0000, 0x0001, // 1..3: invoke-static {v1}, touch(CharSequence)V + 0x0438, 0x0004, // 4..5: if-eqz v4, +4 -> join at 8 (v1 stays Null) + 0x1312, // 6: const/4 v3, #1 + 0x3123, 0x0002, // 7..8? Wait: 6 is 1w, 7..8 is 2w -> target at 9! + }, + }, + }, + }, + } + // Exact word offsets for probe(I)String: + // 0: const/4 v1, #0 (1w) + // 1..3: touch(v1) (3w) + // 4..5: if-eqz v4, +5 -> 9 (2w) + // 6: const/4 v3, #1 (1w) + // 7..8: new-array v1, v3, [Str (2w) + // 9: const/4 v2, #0 (1w) <- join + // 10: array-length v0, v1 (1w) + // 11..12: aget-object v0, v1, v2 (2w) + // 13: return-object v0 (1w) + cls.DirectMethods[1].Code.Instructions = []uint16{ + 0x0112, // 0 + 0x1071, 0x0000, 0x0001, // 1..3 + 0x0438, 0x0005, // 4..5 -> 9 + 0x1312, // 6 + 0x3123, 0x0002, // 7..8 + 0x0212, // 9 + 0x1021, // 10: array-length v0, v1 + 0x0046, 0x0201, // 11..12: aget-object v0, v1, v2 + 0x0011, // 13: return-object v0 + } + cls.DirectMethods = append(cls.DirectMethods, model.EncodedMethod{ + MethodIndex: 2, // main([String;)V + AccessFlags: dexPublic | dexStatic, + Method: file.Methods[2], + Code: &model.Code{ + RegistersSize: 2, InsSize: 1, OutsSize: 1, + Instructions: []uint16{ + 0x1012, // 0: const/4 v0, #1 -> takes array branch + 0x1071, 0x0001, 0x0000, // 1..3: probe(1) + 0x0012, // 4: const/4 v0, #0 -> takes null branch + 0x1071, 0x0001, 0x0000, // 5..7: probe(0) -> throws NPE + 0x000e, // 8: return-void + 0x000d, // 9: move-exception v0 + 0x000e, // 10: return-void + }, + Tries: []model.Try{ + { + StartAddress: 5, InstructionCount: 3, + Handler: model.CatchHandler{Handlers: []model.TypedHandler{{TypeIndex: 5, Type: "Ljava/lang/NullPointerException;", Address: 9}}}, + }, + }, + }, + }) + raw, err := Class(file, cls) + if err != nil { + t.Fatalf("Class failed on null merged with array after CharSequence use: %v", err) + } + runMainWithVerify(t, raw, "dex.NullMergedArray") +} diff --git a/dex2jar/lower/webs.go b/dex2jar/lower/webs.go index f28b4748..9e97f3e5 100644 --- a/dex2jar/lower/webs.go +++ b/dex2jar/lower/webs.go @@ -14,6 +14,35 @@ type regUseKey struct { reg uint16 } +type webPolyKey struct { + root int + kind classfilebuilder.LocalKind +} + +func categoryMaskBit(kind ir.CategoryKind, alloc uint32, desc string) (narrowBit uint8, isWide bool) { + switch kind { + case ir.Int, ir.Bits32: + return ir.PolyZeroInt, false + case ir.Float: + return ir.PolyZeroFloat, false + case ir.Reference, ir.Uninitialized: + return ir.PolyZeroRef, false + case ir.Null: + if desc != "" || (alloc != 0 && alloc != ir.PolyZeroAllocation) { + return ir.PolyZeroRef, false + } + return 0, false + case ir.Long, ir.Double, ir.Bits64: + return 0, true + default: + return 0, false + } +} + +func hasMultipleNarrowBits(mask uint8) bool { + return mask&(mask-1) != 0 +} + type defKindInfo struct { reg uint16 width int @@ -235,21 +264,26 @@ func (l *methodLowerer) assignWebs() bool { reg uint16 jvmLocal uint16 words int + lk classfilebuilder.LocalKind } var params []paramEntry pReg := paramStart jvmLocal := 0 if l.encoded.AccessFlags&dexStatic == 0 { if pReg >= 0 && pReg < registerCount { - params = append(params, paramEntry{reg: uint16(pReg), jvmLocal: uint16(jvmLocal), words: 1}) + params = append(params, paramEntry{reg: uint16(pReg), jvmLocal: uint16(jvmLocal), words: 1, lk: classfilebuilder.RefLocal}) } pReg++ jvmLocal++ } for _, descriptor := range l.method.Proto.Parameters { words := descriptorWords(descriptor) + pk := classfilebuilder.RefLocal + if k, err := fieldKind(descriptor); err == nil { + pk = localKind(k) + } if pReg >= 0 && pReg+words <= registerCount { - params = append(params, paramEntry{reg: uint16(pReg), jvmLocal: uint16(jvmLocal), words: words}) + params = append(params, paramEntry{reg: uint16(pReg), jvmLocal: uint16(jvmLocal), words: words, lk: pk}) } pReg += words jvmLocal += words @@ -447,7 +481,7 @@ func (l *methodLowerer) assignWebs() bool { worklist = append(worklist, i) } } - maxSteps := numBlocks*16 + 256 + maxSteps := numBlocks*32 + 512 steps := 0 for len(worklist) > 0 { steps++ @@ -577,6 +611,92 @@ func (l *methodLowerer) assignWebs() bool { } } + // Collect per-web and per-pinned-register concrete kind masks so untyped + // zero constants stay consistent with their web and mixed-kind webs or + // pinned registers get separate JVM locals per LocalKind. + webKindMask := make([]uint8, len(defs)) + webHasWide := make([]bool, len(defs)) + pinnedNarrowMask := make([]uint8, registerCount) + pinnedHasWide := make([]bool, registerCount) + for _, p := range params { + d := entryDefByReg[p.reg] + if d < 0 { + continue + } + root := ufFind(d) + switch p.lk { + case classfilebuilder.IntLocal: + webKindMask[root] |= ir.PolyZeroInt + case classfilebuilder.FloatLocal: + webKindMask[root] |= ir.PolyZeroFloat + case classfilebuilder.RefLocal: + webKindMask[root] |= ir.PolyZeroRef + case classfilebuilder.LongLocal, classfilebuilder.DoubleLocal: + webHasWide[root] = true + } + } + recordCat := func(pinnedReg int, defIdx int, hasWeb bool, cat ir.Category) { + bit, wide := categoryMaskBit(cat.Kind, cat.Allocation, cat.Descriptor) + if bit == 0 && !wide { + return + } + if hasWeb { + root := ufFind(defIdx) + webKindMask[root] |= bit + if wide { + webHasWide[root] = true + } + return + } + if pinnedReg >= 0 && pinnedReg < registerCount && pinned[pinnedReg] { + pinnedNarrowMask[pinnedReg] |= bit + if wide { + pinnedHasWide[pinnedReg] = true + } + } + } + for _, block := range l.method.Blocks { + if !block.Reachable { + continue + } + for _, idx := range block.Instructions { + _, effDefs := l.method.EffectsAt(idx) + var defReg int = -1 + if len(effDefs) > 0 { + defReg = int(effDefs[0]) + } else if def, ok := l.method.DefinitionAt(idx); ok && def.Register >= 0 { + defReg = int(def.Register) + } + if defReg >= 0 && defReg < registerCount { + cat := l.definitionCategoryAt(idx, uint16(defReg)) + if !pinned[defReg] { + if d, ok := instDefID[regUseKey{index: idx, reg: uint16(defReg)}]; ok { + recordCat(-1, d, true, cat) + } + } else { + recordCat(defReg, 0, false, cat) + } + } + uses, _ := l.method.EffectsAt(idx) + for _, u := range uses { + if int(u) >= registerCount { + continue + } + cat := l.method.CategoryAt(idx, u) + if cat.Kind == ir.WideUpper { + continue + } + if !pinned[u] { + if d, ok := useWebDef[regUseKey{index: idx, reg: u}]; ok { + recordCat(-1, d, true, cat) + } + } else { + recordCat(int(u), 0, false, cat) + } + } + } + } + // Assign JVM slots to webs and fallback homes for pinned/unreachable registers. l.directParamSlots = make([]int, registerCount) l.paramPrologueSlot = make([]int, registerCount) @@ -587,6 +707,7 @@ func (l *methodLowerer) assignWebs() bool { webSlots := make([]uint16, len(defs)) webAssigned := make([]bool, len(defs)) + directParamRootKind := make(map[int]classfilebuilder.LocalKind) directWideParam := make([]bool, registerCount) next := 0 @@ -610,6 +731,7 @@ func (l *methodLowerer) assignWebs() bool { webSlots[root] = p.jvmLocal webAssigned[root] = true l.directParamSlots[p.reg] = int(p.jvmLocal) + directParamRootKind[root] = p.lk if p.words == 2 { directWideParam[p.reg] = true } @@ -639,6 +761,71 @@ func (l *methodLowerer) assignWebs() bool { next += webWidth[root] } + // Allocate companion 1-word slots for webs that mix multiple narrow LocalKinds + // or combine wide and narrow operations on the same Union-Find root. + l.webPolySlots = nil + l.webPolyMask = nil + for i := range defs { + root := ufFind(i) + if root != i || !webAssigned[root] { + continue + } + mask := webKindMask[root] + if !hasMultipleNarrowBits(mask) && !(webHasWide[root] && mask != 0) { + continue + } + if l.webPolySlots == nil { + l.webPolySlots = make(map[webPolyKey]uint16) + l.webPolyMask = make(map[int]uint8) + } + l.webPolyMask[root] = mask + directKind, hasDirectKind := directParamRootKind[root] + reusedBase := false + if hasDirectKind && !webHasWide[root] { + for _, entry := range []struct { + bit uint8 + kind classfilebuilder.LocalKind + }{ + {ir.PolyZeroRef, classfilebuilder.RefLocal}, + {ir.PolyZeroInt, classfilebuilder.IntLocal}, + {ir.PolyZeroFloat, classfilebuilder.FloatLocal}, + } { + if mask&entry.bit != 0 && entry.kind == directKind { + l.webPolySlots[webPolyKey{root: root, kind: entry.kind}] = webSlots[root] + reusedBase = true + } + } + } + first := !reusedBase && !hasDirectKind && !webHasWide[root] + for _, entry := range []struct { + bit uint8 + kind classfilebuilder.LocalKind + }{ + {ir.PolyZeroRef, classfilebuilder.RefLocal}, + {ir.PolyZeroInt, classfilebuilder.IntLocal}, + {ir.PolyZeroFloat, classfilebuilder.FloatLocal}, + } { + if mask&entry.bit == 0 { + continue + } + if _, exists := l.webPolySlots[webPolyKey{root: root, kind: entry.kind}]; exists { + continue + } + var slot uint16 + if first { + slot = webSlots[root] + first = false + } else { + if int(l.homeBase)+next >= math.MaxUint16 { + return false + } + slot = l.homeBase + uint16(next) + next++ + } + l.webPolySlots[webPolyKey{root: root, kind: entry.kind}] = slot + } + } + // Check which pinned registers can still be direct read-only parameters, // and allocate homeSlots/polySlots for all pinned or unreachable-only registers. writtenPinned := make([]bool, registerCount) @@ -685,8 +872,15 @@ func (l *methodLowerer) assignWebs() bool { next += widths[r] } l.polySlots = nil - for r, mask := range l.method.PolyZeroRegisters { - if mask == 0 || r >= registerCount || l.directParamSlots[r] >= 0 { + for r := 0; r < registerCount; r++ { + var polyMask uint8 + if r < len(l.method.PolyZeroRegisters) { + polyMask = l.method.PolyZeroRegisters[r] + } + if pinned[r] && (hasMultipleNarrowBits(pinnedNarrowMask[r]) || (pinnedNarrowMask[r] != 0 && pinnedHasWide[r])) { + polyMask |= pinnedNarrowMask[r] + } + if polyMask == 0 || l.directParamSlots[r] >= 0 { continue } if !hasLegacyHome[r] { @@ -700,7 +894,7 @@ func (l *methodLowerer) assignWebs() bool { if l.polySlots == nil { l.polySlots = make(map[polySlotKey]uint16) } - first := true + first := widths[r] == 1 && !pinnedHasWide[r] for _, entry := range []struct { bit uint8 kind classfilebuilder.LocalKind @@ -709,7 +903,7 @@ func (l *methodLowerer) assignWebs() bool { {ir.PolyZeroInt, classfilebuilder.IntLocal}, {ir.PolyZeroFloat, classfilebuilder.FloatLocal}, } { - if mask&entry.bit == 0 { + if polyMask&entry.bit == 0 { continue } var slot uint16 @@ -730,6 +924,80 @@ func (l *methodLowerer) assignWebs() bool { return false } + // Record resolved single narrow kinds for webs and pinned registers whose + // only concrete uses/defs are Int or Float (and never Wide/Ref/PolyZero), + // plus resolve untyped zero instructions (const/4..const #0). + l.webZeroKind = nil + l.webSingleZeroKind = nil + l.pinnedZeroKind = nil + for i := range defs { + root := ufFind(i) + if root != i || !webAssigned[root] || webHasWide[root] { + continue + } + if webKindMask[root] == ir.PolyZeroInt || webKindMask[root] == ir.PolyZeroFloat { + if l.webSingleZeroKind == nil { + l.webSingleZeroKind = make(map[int]ir.CategoryKind) + } + k := ir.Int + if webKindMask[root] == ir.PolyZeroFloat { + k = ir.Float + } + l.webSingleZeroKind[root] = k + } + } + for r := 0; r < registerCount; r++ { + if !pinned[r] || pinnedHasWide[r] { + continue + } + if r < len(l.method.PolyZeroRegisters) && l.method.PolyZeroRegisters[r] != 0 { + continue + } + if pinnedNarrowMask[r] == ir.PolyZeroInt || pinnedNarrowMask[r] == ir.PolyZeroFloat { + if l.pinnedZeroKind == nil { + l.pinnedZeroKind = make(map[uint16]ir.CategoryKind) + } + k := ir.Int + if pinnedNarrowMask[r] == ir.PolyZeroFloat { + k = ir.Float + } + l.pinnedZeroKind[uint16(r)] = k + } + } + for _, block := range l.method.Blocks { + if !block.Reachable { + continue + } + for _, idx := range block.Instructions { + insn := &l.method.Instructions[idx] + if insn.Opcode < 0x12 || insn.Opcode > 0x15 || insn.Literal != 0 || len(insn.Regs) == 0 { + continue + } + r := insn.Regs[0] + if int(r) >= registerCount { + continue + } + defCat := l.definitionCategoryAt(idx, r) + if defCat.Kind != ir.Null || defCat.Allocation != 0 { + continue + } + var k ir.CategoryKind + if !pinned[r] { + if d, ok := instDefID[regUseKey{index: idx, reg: r}]; ok { + k = l.webSingleZeroKind[ufFind(d)] + } + } else { + k = l.pinnedZeroKind[r] + } + if k != ir.Unknown { + if l.webZeroKind == nil { + l.webZeroKind = make(map[int]ir.CategoryKind) + } + l.webZeroKind[idx] = k + } + } + } + // Build sorted offset -> block instructions lookup for emitDebug resolution. l.webSplitting = true l.webPinned = pinned @@ -758,6 +1026,11 @@ func (l *methodLowerer) loadSlotAt(index int, register uint16, kind classfilebui if l.webSplitting && int(register) < len(l.webPinned) && !l.webPinned[register] { if d, ok := l.useWebDef[regUseKey{index: index, reg: register}]; ok { root := l.ufFindRoot(d) + if kind != classfilebuilder.LongLocal && kind != classfilebuilder.DoubleLocal { + if slot, exists := l.webPolySlots[webPolyKey{root: root, kind: kind}]; exists { + return slot + } + } if l.webAssigned[root] { return l.webSlots[root] } @@ -770,6 +1043,11 @@ func (l *methodLowerer) storeSlotAt(index int, register uint16, kind classfilebu if l.webSplitting && int(register) < len(l.webPinned) && !l.webPinned[register] { if d, ok := l.instDefID[regUseKey{index: index, reg: register}]; ok { root := l.ufFindRoot(d) + if kind != classfilebuilder.LongLocal && kind != classfilebuilder.DoubleLocal { + if slot, exists := l.webPolySlots[webPolyKey{root: root, kind: kind}]; exists { + return slot + } + } if l.webAssigned[root] { return l.webSlots[root] } diff --git a/dex2jar/model/model.go b/dex2jar/model/model.go index 907ee8e5..7fdb5c29 100644 --- a/dex2jar/model/model.go +++ b/dex2jar/model/model.go @@ -3,6 +3,17 @@ package model const NoIndex = ^uint32(0) +// ParseWarning records a recoverable DEX parse discrepancy tolerated under an +// explicit recovery policy. +type ParseWarning struct { + Entry string + Class string + Code string + Action string + Feature string + Message string +} + // File is one DEX file, either standalone or embedded in an archive. type File struct { Entry string @@ -15,6 +26,7 @@ type File struct { MethodHandles []MethodHandle CallSites []CallSite Classes []Class + ParseWarnings []ParseWarning } // Application is an ordered collection of DEX files. @@ -158,6 +170,12 @@ type Code struct { Debug *DebugInfo Instructions []uint16 Tries []Try + // PatchedMethods overrides 16-bit method indices at specific instruction + // offsets when FailureRecover synthesizes targets past 65535 methods. + PatchedMethods map[uint32]uint32 + // PatchedNullArgs records extra trailing null (Ljava/lang/Void;) arguments + // to emit at specific invoke offsets for R8 forwarding disambiguation. + PatchedNullArgs map[uint32]int } // DebugInfo is the decoded debug_info_item of one code item. Addresses are DEX diff --git a/dex2jar/r8_init.go b/dex2jar/r8_init.go new file mode 100644 index 00000000..88543cfa --- /dev/null +++ b/dex2jar/r8_init.go @@ -0,0 +1,868 @@ +package dex2jar + +import ( + "fmt" + "sort" + "strings" + + "github.com/yaklang/javajive/dex2jar/ir" + "github.com/yaklang/javajive/dex2jar/model" +) + +const ( + r8DexPublic = uint32(0x0001) + r8DexStatic = uint32(0x0008) + r8DexInterface = uint32(0x0200) + r8DexSynthetic = uint32(0x1000) + r8DexConstructor = uint32(0x10000) +) + +const thisAliasSentinel = "" + +// synthesizeR8InlinedConstructors restores empty forwarding constructors that +// R8/ProGuard stripped and bypassed by rewriting `new-instance Sub; invoke Object.` +// or `Sub. -> invoke GrandParent.` (FailureRecover only). +func synthesizeR8InlinedConstructors(app *model.Application, hierarchy map[string]*model.Class) []ConversionDiagnostic { + if app == nil { + return nil + } + fileByClass := make(map[string]*model.File, len(hierarchy)) + fileEntry := make(map[*model.File]string, len(app.Files)) + for _, f := range app.Files { + if f == nil { + continue + } + fileEntry[f] = f.Entry + for i := range f.Classes { + c := &f.Classes[i] + if _, exists := fileByClass[c.Descriptor]; !exists { + fileByClass[c.Descriptor] = f + } + } + } + + var diags []ConversionDiagnostic + synthesized := make(map[string]bool) + + for pass := 0; pass < 4; pass++ { + changedInPass := false + for _, f := range app.Files { + if f == nil { + continue + } + for ci := range f.Classes { + c := &f.Classes[ci] + for mi := range c.DirectMethods { + if r8PatchMethod(f, c, &c.DirectMethods[mi], fileByClass, hierarchy, fileEntry, synthesized, &diags) { + changedInPass = true + } + } + for mi := range c.VirtualMethods { + if r8PatchMethod(f, c, &c.VirtualMethods[mi], fileByClass, hierarchy, fileEntry, synthesized, &diags) { + changedInPass = true + } + } + } + } + if !changedInPass { + break + } + } + return diags +} + +type r8PatchSite struct { + offset uint32 + desiredTarget string + callee model.MethodID + proto model.Proto +} + +func r8PatchMethod( + f *model.File, + c *model.Class, + m *model.EncodedMethod, + fileByClass map[string]*model.File, + hierarchy map[string]*model.Class, + fileEntry map[*model.File]string, + synthesized map[string]bool, + diags *[]ConversionDiagnostic, +) bool { + if m == nil || m.Code == nil { + return false + } + ctx := ir.Context{Entry: f.Entry, Class: c.Descriptor, Method: m.Method.Name} + insns, err := ir.Decode(m.Code, ctx) + if err != nil || len(insns) == 0 { + return false + } + isCtor := m.Method.Name == "" && m.AccessFlags&r8DexStatic == 0 && m.Code.InsSize <= m.Code.RegistersSize + hasCandidate := false + for i := range insns { + op := insns[i].Opcode + if (op == 0x70 || op == 0x76) && int(insns[i].Index) < len(f.Methods) { + callee := f.Methods[insns[i].Index] + if callee.Name == "" && callee.Class != c.Descriptor { + hasCandidate = true + break + } + } + } + if !hasCandidate { + return false + } + + sites := findR8PatchSites(f, c, m, insns, isCtor, hierarchy) + if len(sites) == 0 { + return false + } + + clonedCode := false + changed := false + for _, site := range sites { + if int(site.offset)+1 >= len(m.Code.Instructions) { + continue + } + resolvedProto, extraNulls, ok := ensureForwardingCtorChain(site.desiredTarget, site.callee.Class, site.proto, fileByClass, hierarchy, fileEntry, synthesized, diags) + if !ok { + continue + } + pIdx, ok := r8EnsureProto(f, resolvedProto) + if !ok { + continue + } + mIdx, ok := r8EnsureMethod(f, site.desiredTarget, "", pIdx) + if !ok { + continue + } + if mIdx <= 0xffff { + if !clonedCode { + copied := make([]uint16, len(m.Code.Instructions)) + copy(copied, m.Code.Instructions) + m.Code.Instructions = copied + clonedCode = true + } + m.Code.Instructions[site.offset+1] = uint16(mIdx) + } else { + if m.Code.PatchedMethods == nil { + m.Code.PatchedMethods = make(map[uint32]uint32) + } + m.Code.PatchedMethods[site.offset] = mIdx + } + if extraNulls > 0 { + if m.Code.PatchedNullArgs == nil { + m.Code.PatchedNullArgs = make(map[uint32]int) + } + m.Code.PatchedNullArgs[site.offset] += extraNulls + } + changed = true + } + return changed +} + +func findR8PatchSites( + f *model.File, + c *model.Class, + m *model.EncodedMethod, + insns []ir.Instruction, + isCtor bool, + hierarchy map[string]*model.Class, +) []r8PatchSite { + // Build minimal intraprocedural blocks over decoded instructions to track + // uninitialized `new-instance` and `this` aliases conservatively. + offsetToIdx := make(map[uint32]int, len(insns)) + starts := map[uint32]bool{insns[0].Offset: true} + for i := range insns { + offsetToIdx[insns[i].Offset] = i + } + for i := range insns { + ins := &insns[i] + op := ins.Opcode + if ins.Target >= 0 { + starts[uint32(ins.Target)] = true + } + for _, t := range ins.Targets { + if t >= 0 { + starts[uint32(t)] = true + } + } + isCondBranch := (op >= 0x32 && op <= 0x3d) || op == 0x2b || op == 0x2c + isUncond := (op >= 0x28 && op <= 0x2a) || (op >= 0x0e && op <= 0x11) || op == 0x27 + if (isCondBranch || isUncond) && i+1 < len(insns) { + starts[insns[i+1].Offset] = true + } + } + for _, try := range m.Code.Tries { + for _, h := range try.Handler.Handlers { + starts[h.Address] = true + } + if try.Handler.CatchAllAddress != nil { + starts[*try.Handler.CatchAllAddress] = true + } + } + + var blockStarts []uint32 + for off := range starts { + if _, ok := offsetToIdx[off]; ok { + blockStarts = append(blockStarts, off) + } + } + sort.Slice(blockStarts, func(i, j int) bool { return blockStarts[i] < blockStarts[j] }) + blockByOffset := make(map[uint32]int, len(blockStarts)) + for bi, off := range blockStarts { + blockByOffset[off] = bi + } + + numBlocks := len(blockStarts) + blockInsns := make([][]int, numBlocks) + succs := make([][]int, numBlocks) + curBlock := -1 + for i := range insns { + if b, ok := blockByOffset[insns[i].Offset]; ok { + curBlock = b + } + if curBlock >= 0 { + blockInsns[curBlock] = append(blockInsns[curBlock], i) + } + } + for b := 0; b < numBlocks; b++ { + if len(blockInsns[b]) == 0 { + continue + } + last := &insns[blockInsns[b][len(blockInsns[b])-1]] + op := last.Opcode + if last.Target >= 0 { + if tb, ok := blockByOffset[uint32(last.Target)]; ok { + succs[b] = append(succs[b], tb) + } + } + for _, t := range last.Targets { + if t >= 0 { + if tb, ok := blockByOffset[uint32(t)]; ok { + succs[b] = append(succs[b], tb) + } + } + } + isUncond := (op >= 0x28 && op <= 0x2a) || (op >= 0x0e && op <= 0x11) || op == 0x27 + if !isUncond && b+1 < numBlocks { + succs[b] = append(succs[b], b+1) + } + } + + type regState map[uint16]string + cloneState := func(s regState) regState { + out := make(regState, len(s)) + for k, v := range s { + out[k] = v + } + return out + } + statesEqual := func(a, b regState) bool { + if len(a) != len(b) { + return false + } + for k, v := range a { + if bv, ok := b[k]; !ok || bv != v { + return false + } + } + return true + } + intersectState := func(dst, src regState) regState { + out := make(regState) + for k, v := range dst { + if sv, ok := src[k]; ok && sv == v { + out[k] = v + } + } + return out + } + + in := make([]regState, numBlocks) + visited := make([]bool, numBlocks) + in[0] = make(regState) + if isCtor { + in[0][m.Code.RegistersSize-m.Code.InsSize] = thisAliasSentinel + } + visited[0] = true + + queue := []int{0} + inQueue := make([]bool, numBlocks) + inQueue[0] = true + + transferInsn := func(ins *ir.Instruction, state regState) { + op := ins.Opcode + switch { + case op == 0x22 && len(ins.Regs) > 0 && int(ins.Index) < len(f.Types): + state[ins.Regs[0]] = f.Types[ins.Index].Descriptor + case ((op >= 0x07 && op <= 0x09) || (op >= 0x01 && op <= 0x03)) && len(ins.Regs) >= 2: + if v, ok := state[ins.Regs[1]]; ok && v != "" { + state[ins.Regs[0]] = v + } else { + delete(state, ins.Regs[0]) + } + case (op == 0x70 || op == 0x76) && len(ins.Regs) > 0 && int(ins.Index) < len(f.Methods) && f.Methods[ins.Index].Name == "": + recv := ins.Regs[0] + if state[recv] == thisAliasSentinel { + for k, v := range state { + if v == thisAliasSentinel { + delete(state, k) + } + } + } else { + delete(state, recv) + } + default: + _, defs := ir.InstructionEffects(*ins) + for _, d := range defs { + delete(state, d) + } + } + } + + maxSteps := numBlocks*32 + 256 + for steps := 0; len(queue) > 0 && steps < maxSteps; steps++ { + b := queue[0] + queue = queue[1:] + inQueue[b] = false + st := cloneState(in[b]) + for _, idx := range blockInsns[b] { + transferInsn(&insns[idx], st) + } + for _, succ := range succs[b] { + var next regState + changed := false + if !visited[succ] { + visited[succ] = true + next = cloneState(st) + changed = true + } else { + next = intersectState(in[succ], st) + changed = !statesEqual(in[succ], next) + } + in[succ] = next + if changed && !inQueue[succ] { + inQueue[succ] = true + queue = append(queue, succ) + } + } + } + + var sites []r8PatchSite + for b := 0; b < numBlocks; b++ { + if !visited[b] { + continue + } + st := cloneState(in[b]) + for _, idx := range blockInsns[b] { + ins := &insns[idx] + op := ins.Opcode + if (op == 0x70 || op == 0x76) && len(ins.Regs) > 0 && int(ins.Index) < len(f.Methods) { + callee := f.Methods[ins.Index] + if callee.Name == "" && int(callee.ProtoIndex) < len(f.Protos) { + recv := ins.Regs[0] + tag := st[recv] + var desired string + if isCtor && tag == thisAliasSentinel { + if callee.Class != c.Descriptor && callee.Class != c.Superclass && isProperAncestor(c.Superclass, callee.Class, hierarchy) { + desired = c.Superclass + } + } else if tag != "" && tag != thisAliasSentinel && tag != callee.Class && isProperAncestor(tag, callee.Class, hierarchy) { + desired = tag + } + if desired != "" { + sites = append(sites, r8PatchSite{ + offset: ins.Offset, + desiredTarget: desired, + callee: callee, + proto: f.Protos[callee.ProtoIndex], + }) + } + } + } + transferInsn(ins, st) + } + } + return sites +} + +var platformSuperclass = map[string]string{ + "Ljava/lang/Throwable;": "Ljava/lang/Object;", + "Ljava/lang/Error;": "Ljava/lang/Throwable;", + "Ljava/lang/AssertionError;": "Ljava/lang/Error;", + "Ljava/lang/LinkageError;": "Ljava/lang/Error;", + "Ljava/lang/VirtualMachineError;": "Ljava/lang/Error;", + "Ljava/lang/Exception;": "Ljava/lang/Throwable;", + "Ljava/lang/RuntimeException;": "Ljava/lang/Exception;", + "Ljava/lang/IllegalArgumentException;": "Ljava/lang/RuntimeException;", + "Ljava/lang/IllegalStateException;": "Ljava/lang/RuntimeException;", + "Ljava/lang/UnsupportedOperationException;": "Ljava/lang/RuntimeException;", + "Ljava/lang/NullPointerException;": "Ljava/lang/RuntimeException;", + "Ljava/lang/IndexOutOfBoundsException;": "Ljava/lang/RuntimeException;", + "Ljava/lang/ClassCastException;": "Ljava/lang/RuntimeException;", + "Ljava/lang/NumberFormatException;": "Ljava/lang/IllegalArgumentException;", + "Ljava/lang/SecurityException;": "Ljava/lang/RuntimeException;", + "Ljava/util/NoSuchElementException;": "Ljava/lang/RuntimeException;", + "Ljava/lang/ArithmeticException;": "Ljava/lang/RuntimeException;", + "Ljava/io/IOException;": "Ljava/lang/Exception;", + "Ljava/io/FileNotFoundException;": "Ljava/io/IOException;", + "Ljava/io/EOFException;": "Ljava/io/IOException;", + "Ljava/lang/ReflectiveOperationException;": "Ljava/lang/Exception;", + "Ljava/lang/InterruptedException;": "Ljava/lang/Exception;", + "Ljava/lang/Thread;": "Ljava/lang/Object;", + "Ljava/util/AbstractCollection;": "Ljava/lang/Object;", + "Ljava/util/AbstractList;": "Ljava/util/AbstractCollection;", + "Ljava/util/ArrayList;": "Ljava/util/AbstractList;", + "Ljava/util/AbstractMap;": "Ljava/lang/Object;", + "Ljava/util/HashMap;": "Ljava/util/AbstractMap;", + "Ljava/lang/Enum;": "Ljava/lang/Object;", + "Ljava/lang/Number;": "Ljava/lang/Object;", +} + +func platformClassAcceptsCtor(desc string, proto model.Proto) bool { + if desc == "Ljava/lang/Object;" { + return protoSignature(proto) == "()V" + } + if _, ok := platformSuperclass[desc]; !ok { + return false + } + sig := protoSignature(proto) + if sig == "()V" { + return desc != "Ljava/lang/Enum;" + } + switch desc { + case "Ljava/lang/Throwable;", + "Ljava/lang/Error;", + "Ljava/lang/Exception;", + "Ljava/lang/RuntimeException;", + "Ljava/lang/IllegalArgumentException;", + "Ljava/lang/IllegalStateException;", + "Ljava/lang/UnsupportedOperationException;", + "Ljava/lang/SecurityException;", + "Ljava/lang/ReflectiveOperationException;", + "Ljava/io/IOException;": + return sig == "(Ljava/lang/String;)V" || + sig == "(Ljava/lang/Throwable;)V" || + sig == "(Ljava/lang/String;Ljava/lang/Throwable;)V" + case "Ljava/lang/AssertionError;": + return sig == "(Ljava/lang/Object;)V" || sig == "(Ljava/lang/String;Ljava/lang/Throwable;)V" + case "Ljava/lang/LinkageError;": + return sig == "(Ljava/lang/String;)V" || sig == "(Ljava/lang/String;Ljava/lang/Throwable;)V" + case "Ljava/lang/NullPointerException;", + "Ljava/lang/IndexOutOfBoundsException;", + "Ljava/lang/ClassCastException;", + "Ljava/lang/NumberFormatException;", + "Ljava/util/NoSuchElementException;", + "Ljava/lang/ArithmeticException;", + "Ljava/lang/InterruptedException;", + "Ljava/io/FileNotFoundException;", + "Ljava/io/EOFException;": + return sig == "(Ljava/lang/String;)V" + } + return false +} + +func superclassOf(desc string, hierarchy map[string]*model.Class) (string, bool) { + if cls, ok := hierarchy[desc]; ok && cls != nil && cls.Superclass != "" { + return cls.Superclass, true + } + sup, ok := platformSuperclass[desc] + return sup, ok +} + +func isProperAncestor(subDesc, ancDesc string, hierarchy map[string]*model.Class) bool { + if subDesc == "" || ancDesc == "" || subDesc == ancDesc { + return false + } + if ancDesc == "Ljava/lang/Object;" { + return true + } + visited := make(map[string]bool, 8) + cur := subDesc + for cur != "" && !visited[cur] && len(visited) < 128 { + visited[cur] = true + sup, ok := superclassOf(cur, hierarchy) + if !ok { + return false + } + if sup == ancDesc { + return true + } + cur = sup + } + return false +} + +func ensureForwardingCtorChain( + desiredTarget string, + ancTarget string, + origProto model.Proto, + fileByClass map[string]*model.File, + hierarchy map[string]*model.Class, + fileEntry map[*model.File]string, + synthesized map[string]bool, + diags *[]ConversionDiagnostic, +) (model.Proto, int, bool) { + origSig := protoSignature(origProto) + origInsWords := 1 + protoParameterWords(origProto) + if origInsWords > 255 { + return model.Proto{}, 0, false + } + + var chain []*model.Class + visited := make(map[string]bool, 8) + cur := desiredTarget + reachedAnc := false + for cur != "" && !visited[cur] && len(visited) < 128 { + if cur == ancTarget { + reachedAnc = true + break + } + visited[cur] = true + if cls, ok := hierarchy[cur]; ok && cls != nil { + if cls.AccessFlags&r8DexInterface != 0 { + return model.Proto{}, 0, false + } + chain = append(chain, cls) + cur = cls.Superclass + continue + } + if !platformClassAcceptsCtor(cur, origProto) { + return model.Proto{}, 0, false + } + for len(visited) < 128 { + platSup, ok := platformSuperclass[cur] + if !ok || platSup == "" { + break + } + cur = platSup + if cur == ancTarget { + reachedAnc = true + break + } + if visited[cur] { + break + } + visited[cur] = true + } + break + } + if !reachedAnc { + return model.Proto{}, 0, false + } + if len(chain) == 0 { + // Caller already targets desiredTarget directly as a platform class + // whose direct super constructor accepts origProto. + return origProto, 0, true + } + + var chosenProto model.Proto + chosenExtraNulls := -1 + for extraNulls := 0; extraNulls <= 8; extraNulls++ { + if origInsWords+extraNulls > 255 { + break + } + candProto := model.Proto{ + ReturnType: origProto.ReturnType, + Parameters: append([]string(nil), origProto.Parameters...), + } + for j := 0; j < extraNulls; j++ { + candProto.Parameters = append(candProto.Parameters, "Ljava/lang/Void;") + } + candProto.Shorty = protoShorty(candProto) + candSig := protoSignature(candProto) + collision := false + for i := len(chain) - 1; i >= 0; i-- { + cls := chain[i] + tf := fileByClass[cls.Descriptor] + if tf == nil { + return model.Proto{}, 0, false + } + wantCalleeSig := candSig + if i == len(chain)-1 { + wantCalleeSig = origSig + } + found, trivial := isTrivialForwardingCtor(tf, cls, cls.Superclass, candSig, wantCalleeSig) + if found && !trivial { + collision = true + break + } + } + if !collision { + chosenProto = candProto + chosenExtraNulls = extraNulls + break + } + } + if chosenExtraNulls < 0 { + return model.Proto{}, 0, false + } + + candSig := protoSignature(chosenProto) + selfInsWords := origInsWords + chosenExtraNulls + // Walk top-down (closest to ancTarget down to desiredTarget). + for i := len(chain) - 1; i >= 0; i-- { + cls := chain[i] + tf := fileByClass[cls.Descriptor] + if tf == nil { + return model.Proto{}, 0, false + } + calleeProto := chosenProto + calleeSig := candSig + callWords := selfInsWords + if i == len(chain)-1 { + calleeProto = origProto + calleeSig = origSig + callWords = origInsWords + } + found, trivial := isTrivialForwardingCtor(tf, cls, cls.Superclass, candSig, calleeSig) + if found { + if !trivial { + return model.Proto{}, 0, false + } + continue + } + pIdx, ok := r8EnsureProto(tf, chosenProto) + if !ok { + return model.Proto{}, 0, false + } + selfIdx, ok := r8EnsureMethod(tf, cls.Descriptor, "", pIdx) + if !ok { + return model.Proto{}, 0, false + } + superPIdx, ok := r8EnsureProto(tf, calleeProto) + if !ok { + return model.Proto{}, 0, false + } + superIdx, ok := r8EnsureMethod(tf, cls.Superclass, "", superPIdx) + if !ok { + return model.Proto{}, 0, false + } + var words []uint16 + var patchedMethods map[uint32]uint32 + superWord := uint16(superIdx) + if superIdx > 0xffff { + superWord = 0 + patchedMethods = map[uint32]uint32{0: superIdx} + } + if callWords <= 5 { + var g uint16 + if callWords == 5 { + g = 4 + } + w0 := uint16(callWords<<12) | (g << 8) | 0x70 + var w2 uint16 + for r := 0; r < callWords && r < 4; r++ { + w2 |= uint16(r) << uint(r*4) + } + words = []uint16{w0, superWord, w2, 0x000e} + } else { + w0 := uint16(callWords<<8) | 0x76 + words = []uint16{w0, superWord, 0x0000, 0x000e} + } + cls.DirectMethods = append(cls.DirectMethods, model.EncodedMethod{ + MethodIndex: selfIdx, + AccessFlags: r8DexPublic | r8DexSynthetic | r8DexConstructor, + Method: tf.Methods[selfIdx], + Code: &model.Code{ + RegistersSize: uint16(selfInsWords), + InsSize: uint16(selfInsWords), + OutsSize: uint16(callWords), + Instructions: words, + PatchedMethods: patchedMethods, + }, + }) + key := cls.Descriptor + candSig + if !synthesized[key] { + synthesized[key] = true + *diags = append(*diags, ConversionDiagnostic{ + Entry: fileEntry[tf], + Class: cls.Descriptor, + Method: "", + Descriptor: candSig, + Category: "recovery", + Action: "synthesize_ctor", + Feature: "r8-inlined-constructor", + Code: "r8.ctor_synthesized", + Kind: "recovery", + Scope: "method", + Stage: "recover", + Severity: "warning", + Offset: -1, + Message: fmt.Sprintf("synthesized forwarding constructor delegating to %s.%s stripped by R8", cls.Superclass, calleeSig), + }) + } + } + return chosenProto, chosenExtraNulls, true +} + +func isTrivialForwardingCtor(f *model.File, cls *model.Class, wantSuper, wantProto, wantCalleeProto string) (found bool, trivial bool) { + for i := range cls.DirectMethods { + m := &cls.DirectMethods[i] + if m.Method.Name != "" || int(m.Method.ProtoIndex) >= len(f.Protos) { + continue + } + if protoSignature(f.Protos[m.Method.ProtoIndex]) != wantProto { + continue + } + found = true + if m.Code == nil || len(m.Code.Tries) > 0 { + return true, false + } + insns, err := ir.Decode(m.Code, ir.Context{Entry: f.Entry, Class: cls.Descriptor, Method: ""}) + if err != nil || len(insns) != 2 { + return true, false + } + if (insns[0].Opcode != 0x70 && insns[0].Opcode != 0x76) || insns[1].Opcode != 0x0e { + return true, false + } + if insns[0].ExtraNullArgs != 0 || int(insns[0].Index) >= len(f.Methods) { + return true, false + } + callee := f.Methods[insns[0].Index] + if callee.Name != "" || callee.Class != wantSuper || int(callee.ProtoIndex) >= len(f.Protos) { + return true, false + } + calleeProto := f.Protos[callee.ProtoIndex] + if protoSignature(calleeProto) != wantCalleeProto { + return true, false + } + firstParam := m.Code.RegistersSize - m.Code.InsSize + wantCallWords := 1 + protoParameterWords(calleeProto) + if len(insns[0].Regs) != wantCallWords { + return true, false + } + for idx, r := range insns[0].Regs { + if r != firstParam+uint16(idx) { + return true, false + } + } + return true, true + } + return false, false +} + +func protoSignature(p model.Proto) string { + return "(" + strings.Join(p.Parameters, "") + ")" + p.ReturnType +} + +func protoParameterWords(p model.Proto) int { + w := 0 + for _, d := range p.Parameters { + if d == "J" || d == "D" { + w += 2 + } else { + w++ + } + } + return w +} + +func protoShorty(p model.Proto) string { + var b strings.Builder + shortyOf := func(d string) byte { + if len(d) == 1 { + return d[0] + } + return 'L' + } + b.WriteByte(shortyOf(p.ReturnType)) + for _, param := range p.Parameters { + b.WriteByte(shortyOf(param)) + } + return b.String() +} + +func hasFileMetadataSizes(f *model.File) bool { + return f.Header.StringIDsSize != 0 || f.Header.TypeIDsSize != 0 || + f.Header.ProtoIDsSize != 0 || f.Header.FieldIDsSize != 0 || f.Header.MethodIDsSize != 0 +} + +func r8EnsureString(f *model.File, s string) uint32 { + for i, existing := range f.Strings { + if existing == s { + return uint32(i) + } + } + idx := uint32(len(f.Strings)) + f.Strings = append(f.Strings, s) + if hasFileMetadataSizes(f) { + f.Header.StringIDsSize = uint32(len(f.Strings)) + } + return idx +} + +func r8EnsureType(f *model.File, desc string) uint32 { + for i, existing := range f.Types { + if existing.Descriptor == desc { + return uint32(i) + } + } + meta := hasFileMetadataSizes(f) + strIdx := r8EnsureString(f, desc) + idx := uint32(len(f.Types)) + f.Types = append(f.Types, model.Type{DescriptorIndex: strIdx, Descriptor: desc}) + if meta || f.Header.TypeIDsSize != 0 { + f.Header.TypeIDsSize = uint32(len(f.Types)) + } + return idx +} + +func r8EnsureProto(f *model.File, proto model.Proto) (uint16, bool) { + sig := protoSignature(proto) + for i, existing := range f.Protos { + if protoSignature(existing) == sig { + return uint16(i), true + } + } + if len(f.Protos) >= 0xffff { + return 0, false + } + meta := hasFileMetadataSizes(f) + shorty := protoShorty(proto) + shortyIdx := r8EnsureString(f, shorty) + retIdx := r8EnsureType(f, proto.ReturnType) + paramTypes := make([]uint32, len(proto.Parameters)) + for i, p := range proto.Parameters { + paramTypes[i] = r8EnsureType(f, p) + } + idx := uint16(len(f.Protos)) + f.Protos = append(f.Protos, model.Proto{ + ShortyIndex: shortyIdx, + Shorty: shorty, + ReturnTypeIndex: retIdx, + ReturnType: proto.ReturnType, + ParameterTypes: paramTypes, + Parameters: append([]string(nil), proto.Parameters...), + }) + if meta || f.Header.ProtoIDsSize != 0 { + f.Header.ProtoIDsSize = uint32(len(f.Protos)) + } + return idx, true +} + +func r8EnsureMethod(f *model.File, classDesc, name string, protoIdx uint16) (uint32, bool) { + for i, existing := range f.Methods { + if existing.Class == classDesc && existing.Name == name && existing.ProtoIndex == protoIdx { + return uint32(i), true + } + } + meta := hasFileMetadataSizes(f) + classIdx := r8EnsureType(f, classDesc) + if classIdx > 0xffff { + return 0, false + } + nameIdx := r8EnsureString(f, name) + idx := uint32(len(f.Methods)) + f.Methods = append(f.Methods, model.MethodID{ + ClassIndex: uint16(classIdx), + Class: classDesc, + NameIndex: nameIdx, + Name: name, + ProtoIndex: protoIdx, + }) + if meta || f.Header.MethodIDsSize != 0 { + f.Header.MethodIDsSize = uint32(len(f.Methods)) + } + return idx, true +} diff --git a/dex2jar/r8_init_test.go b/dex2jar/r8_init_test.go new file mode 100644 index 00000000..8a6f819c --- /dev/null +++ b/dex2jar/r8_init_test.go @@ -0,0 +1,538 @@ +package dex2jar + +import ( + "archive/zip" + "bytes" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + javaclassparser "github.com/yaklang/javajive/classparser" + "github.com/yaklang/javajive/dex2jar/model" +) + +func r8InitFixture(extraMethods int, withNonTrivialSubCtor bool) *model.Application { + const ( + parentDesc = "Lr8/Parent;" + subDesc = "Lr8/Child;" + callerDesc = "Lr8/Caller;" + ) + file := &model.File{ + Entry: "classes.dex", + Types: []model.Type{ + {Descriptor: "Ljava/lang/Object;"}, + {Descriptor: parentDesc}, + {Descriptor: subDesc}, + {Descriptor: callerDesc}, + {Descriptor: "I"}, + {Descriptor: "V"}, + {Descriptor: "[Ljava/lang/String;"}, + }, + Protos: []model.Proto{ + {ReturnType: "V"}, // 0: ()V + {ReturnType: "V", Parameters: []string{"I"}, ParameterTypes: []uint32{4}}, // 1: (I)V + {ReturnType: "V", Parameters: []string{"[Ljava/lang/String;"}, ParameterTypes: []uint32{6}}, // 2: ([String;)V + }, + Methods: []model.MethodID{ + {Class: "Ljava/lang/Object;", Name: "", ProtoIndex: 0}, // 0 + {Class: parentDesc, Name: "", ProtoIndex: 0}, // 1 + {Class: callerDesc, Name: "make", ProtoIndex: 0}, // 2 + {Class: subDesc, Name: "nonTrivialMarker", ProtoIndex: 0}, // 3 + {Class: callerDesc, Name: "main", ProtoIndex: 2}, // 4 + }, + } + for i := 0; i < extraMethods; i++ { + file.Methods = append(file.Methods, model.MethodID{ + Class: "Ljava/lang/Object;", + Name: "pad", + ProtoIndex: 0, + }) + } + + parent := model.Class{ + Descriptor: parentDesc, + Superclass: "Ljava/lang/Object;", + AccessFlags: 0x0001, + DirectMethods: []model.EncodedMethod{{ + MethodIndex: 1, + AccessFlags: 0x10001, + Method: file.Methods[1], + Code: &model.Code{ + RegistersSize: 1, InsSize: 1, OutsSize: 1, + Instructions: []uint16{ + 0x1070, 0x0000, 0x0000, // invoke-direct {v0}, Object.()V + 0x000e, // return-void + }, + }, + }}, + } + + var subDirect []model.EncodedMethod + if withNonTrivialSubCtor { + // Child.()V calls Object.()V plus a dummy method, so it is non-trivial and must NOT be replaced. + idx := uint32(len(file.Methods)) + file.Methods = append(file.Methods, model.MethodID{Class: subDesc, Name: "", ProtoIndex: 0}) + subDirect = append(subDirect, model.EncodedMethod{ + MethodIndex: idx, + AccessFlags: 0x10001, + Method: file.Methods[idx], + Code: &model.Code{ + RegistersSize: 1, InsSize: 1, OutsSize: 1, + Instructions: []uint16{ + 0x1070, 0x0000, 0x0000, // invoke-direct {v0}, Object.()V + 0x1071, 0x0003, 0x0000, // invoke-static {}, nonTrivialMarker()V (extra side effect!) + 0x000e, + }, + }, + }) + } + sub := model.Class{ + Descriptor: subDesc, + Superclass: parentDesc, + AccessFlags: 0x0001, + DirectMethods: subDirect, + } + + caller := model.Class{ + Descriptor: callerDesc, + Superclass: "Ljava/lang/Object;", + AccessFlags: 0x0001, + DirectMethods: []model.EncodedMethod{ + { + MethodIndex: 2, + AccessFlags: 0x0009, + Method: file.Methods[2], + Code: &model.Code{ + RegistersSize: 1, InsSize: 0, OutsSize: 1, + Instructions: []uint16{ + 0x0022, 0x0002, // new-instance v0, Lr8/Child; + 0x1070, 0x0000, 0x0000, // R8 stripped Child. -> invokes Object.(v0)! + 0x000e, // return-void + }, + }, + }, + { + MethodIndex: 4, + AccessFlags: 0x0009, + Method: file.Methods[4], + Code: &model.Code{ + RegistersSize: 1, InsSize: 1, OutsSize: 0, + Instructions: []uint16{ + 0x0071, 0x0002, 0x0000, // invoke-static {}, make()V + 0x000e, + }, + }, + }, + }, + } + + file.Classes = []model.Class{parent, sub, caller} + return &model.Application{Files: []*model.File{file}} +} + +func TestSynthesizeR8InlinedConstructorsNormalAnd65kOverflow(t *testing.T) { + // Strict mode leaves R8-bypassed Object. untouched (no synthesis) and rejects it strictly. + strictApp := r8InitFixture(0, false) + if _, _, err := applicationToJarWithPolicy(strictApp, FailureStrict); err == nil { + t.Fatal("FailureStrict unexpectedly accepted un-synthesized Child allocation calling Object.") + } + if len(strictApp.Files[0].Classes[1].DirectMethods) != 0 { + t.Fatalf("FailureStrict unexpectedly synthesized constructors on Child") + } + + // FailureRecover synthesizes Child.()V -> Parent.()V and rewrites Caller.make. + recApp := r8InitFixture(0, false) + jarBytes, detailed, err := applicationToJarWithPolicy(recApp, FailureRecover) + if err != nil { + t.Fatalf("FailureRecover failed: %v", err) + } + if detailed.StubbedMethods != 0 { + t.Fatalf("expected 0 stubs, got %d (%+v)", detailed.StubbedMethods, detailed.Diagnostics) + } + if len(recApp.Files[0].Classes[1].DirectMethods) != 1 || recApp.Files[0].Classes[1].DirectMethods[0].Method.Name != "" { + t.Fatalf("expected synthesized Child., got %+v", recApp.Files[0].Classes[1].DirectMethods) + } + verifyR8JarClasses(t, jarBytes) + + // 65,536-method DEX overflow: synthesized method index exceeds 0xffff -> uses Code.PatchedMethods cleanly. + overApp := r8InitFixture(65536, false) + overJar, overDetailed, err := applicationToJarWithPolicy(overApp, FailureRecover) + if err != nil { + t.Fatalf("FailureRecover >65k methods failed: %v", err) + } + if overDetailed.StubbedMethods != 0 { + t.Fatalf("expected 0 stubs on >65k DEX, got %d (%+v)", overDetailed.StubbedMethods, overDetailed.Diagnostics) + } + callerCode := overApp.Files[0].Classes[2].DirectMethods[0].Code + if len(callerCode.PatchedMethods) == 0 { + t.Fatalf("expected PatchedMethods override when method_ids > 65535") + } + verifyR8JarClasses(t, overJar) + + // Non-trivial existing Child. is preserved intact (never overwritten). + keepApp := r8InitFixture(0, true) + origLen := len(keepApp.Files[0].Classes[1].DirectMethods[0].Code.Instructions) + _, _, err = applicationToJarWithPolicy(keepApp, FailureRecover) + if err != nil { + t.Fatalf("FailureRecover preserve non-trivial failed: %v", err) + } + if gotLen := len(keepApp.Files[0].Classes[1].DirectMethods[0].Code.Instructions); gotLen != origLen { + t.Fatalf("non-trivial existing Child. was modified (%d -> %d words)", origLen, gotLen) + } +} + +func verifyR8JarClasses(t *testing.T, jarBytes []byte) { + t.Helper() + if len(jarBytes) == 0 { + t.Fatal("empty JAR") + } + zr, err := zip.NewReader(bytes.NewReader(jarBytes), int64(len(jarBytes))) + if err != nil { + t.Fatalf("zip.NewReader: %v", err) + } + dir := t.TempDir() + var sawChild, sawCaller bool + for _, f := range zr.File { + if !strings.HasSuffix(f.Name, ".class") { + continue + } + rc, err := f.Open() + if err != nil { + t.Fatalf("open %s: %v", f.Name, err) + } + var buf bytes.Buffer + _, copyErr := buf.ReadFrom(rc) + _ = rc.Close() + if copyErr != nil { + t.Fatalf("read %s: %v", f.Name, copyErr) + } + raw := buf.Bytes() + parsed, err := javaclassparser.Parse(raw) + if err != nil { + t.Fatalf("Parse %s: %v", f.Name, err) + } + if f.Name == "r8/Child.class" { + sawChild = true + hasInit := false + for _, m := range parsed.Methods { + if parsed.ConstantPoolManager.GetUtf8(int(m.NameIndex)).Value == "" { + hasInit = true + } + } + if !hasInit { + t.Fatalf("synthesized r8/Child.class is missing ") + } + } + if f.Name == "r8/Caller.class" { + sawCaller = true + } + dst := filepath.Join(dir, filepath.FromSlash(f.Name)) + if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(dst, raw, 0o644); err != nil { + t.Fatal(err) + } + } + if !sawChild || !sawCaller { + t.Fatalf("missing expected classes in JAR (child=%v caller=%v)", sawChild, sawCaller) + } + if java, err := exec.LookPath("java"); err == nil { + if out, err := exec.Command(java, "-Xverify:all", "-cp", dir, "r8.Caller").CombinedOutput(); err != nil { + t.Fatalf("java -Xverify:all r8.Caller failed: %v\n%s", err, out) + } + } +} + +func verifyAllR8JarClasses(t *testing.T, jarBytes []byte, mainClass string) { + t.Helper() + zr, err := zip.NewReader(bytes.NewReader(jarBytes), int64(len(jarBytes))) + if err != nil { + t.Fatalf("zip.NewReader: %v", err) + } + dir := t.TempDir() + for _, f := range zr.File { + if !strings.HasSuffix(f.Name, ".class") { + continue + } + rc, err := f.Open() + if err != nil { + t.Fatalf("open %s: %v", f.Name, err) + } + var buf bytes.Buffer + _, copyErr := buf.ReadFrom(rc) + _ = rc.Close() + if copyErr != nil { + t.Fatalf("read %s: %v", f.Name, copyErr) + } + raw := buf.Bytes() + if _, err := javaclassparser.Parse(raw); err != nil { + t.Fatalf("Parse %s: %v", f.Name, err) + } + dst := filepath.Join(dir, filepath.FromSlash(f.Name)) + if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(dst, raw, 0o644); err != nil { + t.Fatal(err) + } + } + if java, err := exec.LookPath("java"); err == nil { + if out, err := exec.Command(java, "-Xverify:all", "-cp", dir, mainClass).CombinedOutput(); err != nil { + t.Fatalf("java -Xverify:all %s failed: %v\n%s", mainClass, err, out) + } + } +} + +func TestR8InitCollisionDisambiguatesWithVoidAndReusesCtor(t *testing.T) { + const ( + midDesc = "Lr8/WaiterBase;" + leafDesc = "Lr8/WaiterLeaf;" + callerDesc = "Lr8/WaiterCaller;" + ) + file := &model.File{ + Entry: "classes.dex", + Types: []model.Type{ + {Descriptor: "Ljava/lang/Object;"}, + {Descriptor: midDesc}, + {Descriptor: leafDesc}, + {Descriptor: callerDesc}, + {Descriptor: "V"}, + {Descriptor: "[Ljava/lang/String;"}, + }, + Protos: []model.Proto{ + {ReturnType: "V"}, // 0: ()V + {ReturnType: "V", Parameters: []string{"[Ljava/lang/String;"}, ParameterTypes: []uint32{5}}, // 1: ([String;)V + }, + Methods: []model.MethodID{ + {Class: "Ljava/lang/Object;", Name: "", ProtoIndex: 0}, // 0 + {Class: midDesc, Name: "", ProtoIndex: 0}, // 1: non-trivial collision + {Class: midDesc, Name: "mark", ProtoIndex: 0}, // 2 + {Class: callerDesc, Name: "make1", ProtoIndex: 0}, // 3 + {Class: callerDesc, Name: "make2", ProtoIndex: 0}, // 4 + {Class: callerDesc, Name: "main", ProtoIndex: 1}, // 5 + }, + } + mid := model.Class{ + Descriptor: midDesc, + Superclass: "Ljava/lang/Object;", + AccessFlags: 0x0001, + DirectMethods: []model.EncodedMethod{ + { + MethodIndex: 1, + AccessFlags: 0x10001, + Method: file.Methods[1], + Code: &model.Code{ + RegistersSize: 1, InsSize: 1, OutsSize: 1, + Instructions: []uint16{ + 0x1070, 0x0000, 0x0000, // Object.()V + 0x0071, 0x0002, 0x0000, // mark()V (makes WaiterBase.()V non-trivial!) + 0x000e, + }, + }, + }, + { + MethodIndex: 2, + AccessFlags: 0x0009, + Method: file.Methods[2], + Code: &model.Code{ + RegistersSize: 0, InsSize: 0, OutsSize: 0, + Instructions: []uint16{0x000e}, + }, + }, + }, + } + leaf := model.Class{ + Descriptor: leafDesc, + Superclass: midDesc, + AccessFlags: 0x0001, + } + caller := model.Class{ + Descriptor: callerDesc, + Superclass: "Ljava/lang/Object;", + AccessFlags: 0x0001, + DirectMethods: []model.EncodedMethod{ + { + MethodIndex: 3, + AccessFlags: 0x0009, + Method: file.Methods[3], + Code: &model.Code{ + RegistersSize: 1, InsSize: 0, OutsSize: 1, + Instructions: []uint16{ + 0x0022, 0x0002, // new-instance v0, WaiterLeaf + 0x1070, 0x0000, 0x0000, // invoke-direct {v0}, Object.()V + 0x000e, + }, + }, + }, + { + MethodIndex: 4, + AccessFlags: 0x0009, + Method: file.Methods[4], + Code: &model.Code{ + RegistersSize: 1, InsSize: 0, OutsSize: 1, + Instructions: []uint16{ + 0x0022, 0x0002, // new-instance v0, WaiterLeaf + 0x1070, 0x0000, 0x0000, // invoke-direct {v0}, Object.()V + 0x000e, + }, + }, + }, + { + MethodIndex: 5, + AccessFlags: 0x0009, + Method: file.Methods[5], + Code: &model.Code{ + RegistersSize: 1, InsSize: 1, OutsSize: 0, + Instructions: []uint16{ + 0x0071, 0x0003, 0x0000, // make1()V + 0x0071, 0x0004, 0x0000, // make2()V + 0x000e, + }, + }, + }, + }, + } + app := &model.Application{Files: []*model.File{{ + Entry: "classes.dex", + Types: file.Types, + Protos: file.Protos, + Methods: file.Methods, + Classes: []model.Class{mid, leaf, caller}, + }}} + + jarBytes, detailed, err := applicationToJarWithPolicy(app, FailureRecover) + if err != nil { + t.Fatalf("FailureRecover failed on Void disambiguation: %v", err) + } + if detailed.StubbedMethods != 0 { + t.Fatalf("expected 0 stubs, got %d (%+v)", detailed.StubbedMethods, detailed.Diagnostics) + } + // WaiterBase must keep its original ()V AND have exactly ONE synthetic (Ljava/lang/Void;)V reused by make1 & make2. + midPtr := &app.Files[0].Classes[0] + voidCtorCount := 0 + for _, dm := range midPtr.DirectMethods { + if dm.Method.Name == "" { + sig := protoSignature(app.Files[0].Protos[dm.Method.ProtoIndex]) + if sig == "(Ljava/lang/Void;)V" { + voidCtorCount++ + } else if sig != "()V" { + t.Fatalf("unexpected WaiterBase. signature %s (Void explosion?)", sig) + } + } + } + if voidCtorCount != 1 { + t.Fatalf("expected 1 disambiguating (Ljava/lang/Void;)V ctor on WaiterBase, got %d", voidCtorCount) + } + callerCls := &app.Files[0].Classes[2] + for i := 0; i < 2; i++ { + if callerCls.DirectMethods[i].Code.PatchedNullArgs[2] != 1 { + t.Fatalf("make%d PatchedNullArgs[2] = %d, want 1", i+1, callerCls.DirectMethods[i].Code.PatchedNullArgs[2]) + } + } + verifyAllR8JarClasses(t, jarBytes, "r8.WaiterCaller") +} + +func TestR8InitPlatformExceptionHierarchyChains(t *testing.T) { + const ( + midExDesc = "Lr8/AppMidEx;" + leafExDesc = "Lr8/LeafEx;" + directExDesc = "Lr8/DirectSubEx;" + callerDesc = "Lr8/ExCaller;" + ) + file := &model.File{ + Entry: "classes.dex", + Strings: []string{"boom"}, + Types: []model.Type{ + {Descriptor: "Ljava/lang/Object;"}, // 0 + {Descriptor: "Ljava/lang/Throwable;"}, // 1 + {Descriptor: "Ljava/lang/Exception;"}, // 2 + {Descriptor: "Ljava/lang/RuntimeException;"}, // 3 + {Descriptor: "Ljava/lang/String;"}, // 4 + {Descriptor: midExDesc}, // 5 + {Descriptor: leafExDesc}, // 6 + {Descriptor: directExDesc}, // 7 + {Descriptor: callerDesc}, // 8 + {Descriptor: "V"}, // 9 + {Descriptor: "[Ljava/lang/String;"}, // 10 + }, + Protos: []model.Proto{ + {ReturnType: "V"}, // 0: ()V + {ReturnType: "V", Parameters: []string{"Ljava/lang/String;"}, ParameterTypes: []uint32{4}}, // 1: (String)V + {ReturnType: "V", Parameters: []string{"[Ljava/lang/String;"}, ParameterTypes: []uint32{10}}, // 2: ([String;)V + }, + Methods: []model.MethodID{ + {Class: "Ljava/lang/Throwable;", Name: "", ProtoIndex: 1}, // 0 + {Class: "Ljava/lang/Exception;", Name: "", ProtoIndex: 1}, // 1 + {Class: directExDesc, Name: "", ProtoIndex: 1}, // 2 + {Class: callerDesc, Name: "main", ProtoIndex: 2}, // 3 + }, + } + appMid := model.Class{ + Descriptor: midExDesc, + Superclass: "Ljava/lang/RuntimeException;", + AccessFlags: 0x0001, + } + leafEx := model.Class{ + Descriptor: leafExDesc, + Superclass: midExDesc, + AccessFlags: 0x0001, + } + directEx := model.Class{ + Descriptor: directExDesc, + Superclass: "Ljava/lang/RuntimeException;", + AccessFlags: 0x0001, + DirectMethods: []model.EncodedMethod{{ + MethodIndex: 2, + AccessFlags: 0x10001, + Method: file.Methods[2], + Code: &model.Code{ + RegistersSize: 2, InsSize: 2, OutsSize: 2, + Instructions: []uint16{ + 0x2070, 0x0000, 0x0010, // invoke-direct {v0, v1}, Throwable.(String)V (skipped RuntimeException) + 0x000e, + }, + }, + }}, + } + caller := model.Class{ + Descriptor: callerDesc, + Superclass: "Ljava/lang/Object;", + AccessFlags: 0x0001, + DirectMethods: []model.EncodedMethod{{ + MethodIndex: 3, + AccessFlags: 0x0009, + Method: file.Methods[3], + Code: &model.Code{ + RegistersSize: 3, InsSize: 1, OutsSize: 2, + Instructions: []uint16{ + 0x0022, 0x0006, // new-instance v0, LeafEx + 0x011a, 0x0000, // const-string v1, "boom" + 0x2070, 0x0001, 0x0010, // invoke-direct {v0, v1}, Exception.(String)V + 0x0022, 0x0007, // new-instance v0, DirectSubEx + 0x2070, 0x0002, 0x0010, // invoke-direct {v0, v1}, DirectSubEx.(String)V + 0x000e, + }, + }, + }}, + } + app := &model.Application{Files: []*model.File{{ + Entry: "classes.dex", + Strings: file.Strings, + Types: file.Types, + Protos: file.Protos, + Methods: file.Methods, + Classes: []model.Class{appMid, leafEx, directEx, caller}, + }}} + + jarBytes, detailed, err := applicationToJarWithPolicy(app, FailureRecover) + if err != nil { + t.Fatalf("FailureRecover platform exception chains failed: %v", err) + } + if detailed.StubbedMethods != 0 { + t.Fatalf("expected 0 stubs, got %d (%+v)", detailed.StubbedMethods, detailed.Diagnostics) + } + verifyAllR8JarClasses(t, jarBytes, "r8.ExCaller") +} diff --git a/dex2jar/roundtrip_gate_test.go b/dex2jar/roundtrip_gate_test.go index a3d115ff..1d264621 100644 --- a/dex2jar/roundtrip_gate_test.go +++ b/dex2jar/roundtrip_gate_test.go @@ -547,7 +547,9 @@ func (b *cappedBuffer) String() string { return b.data.String() } func assertGateProcess(t *testing.T, label string, got gateProcessResult, exit int, stdout, stderr string) { t.Helper() - if got.ExitCode != exit || got.Stdout != stdout || got.Stderr != stderr { + gotStdout := strings.ReplaceAll(got.Stdout, "\r\n", "\n") + gotStderr := strings.ReplaceAll(got.Stderr, "\r\n", "\n") + if got.ExitCode != exit || gotStdout != stdout || gotStderr != stderr { t.Fatalf("%s result mismatch after %s: exit=%d want=%d stdout=%q want=%q stderr=%q want=%q", label, got.Duration, got.ExitCode, exit, got.Stdout, stdout, got.Stderr, stderr) } } diff --git a/internal/dexparser/annotations.go b/internal/dexparser/annotations.go index 54cb8903..6655eb6d 100644 --- a/internal/dexparser/annotations.go +++ b/internal/dexparser/annotations.go @@ -2,6 +2,7 @@ package dexparser import ( "encoding/binary" + "fmt" "github.com/yaklang/javajive/dex2jar/model" ) @@ -363,6 +364,17 @@ func (p *parser) applyAnnotationDefaults(c *model.Class, annotation model.Annota for _, element := range value.Annotation.Elements { methodIndex, exists := methods[element.Name] if !exists { + if p.options.TolerateOrphanAnnotationDefault { + p.file.ParseWarnings = append(p.file.ParseWarnings, model.ParseWarning{ + Entry: p.entry, + Class: c.Descriptor, + Code: "annotation.orphan_default", + Action: "drop_attribute", + Feature: "system-annotation", + Message: fmt.Sprintf("AnnotationDefault element %q has no annotation method", element.Name), + }) + continue + } return p.fail(0, "system annotation", "AnnotationDefault element %q has no annotation method", element.Name) } annotation := model.Annotation{ diff --git a/internal/dexparser/parser.go b/internal/dexparser/parser.go index 222513e3..2bad841b 100644 --- a/internal/dexparser/parser.go +++ b/internal/dexparser/parser.go @@ -24,9 +24,17 @@ const ( var supportedDEXVersions = map[string]bool{"035": true, "037": true, "038": true, "039": true, "040": true} +// ParseOptions controls recoverable validation exceptions during DEX parsing. +// Zero-value ParseOptions enforces strict integrity and metadata membership. +type ParseOptions struct { + TolerateSignatureMismatch bool + TolerateOrphanAnnotationDefault bool +} + type parser struct { data []byte entry string + options ParseOptions file *model.File class string method string @@ -39,7 +47,13 @@ type parser struct { } func Parse(data []byte, entry string) (*model.File, error) { - p := &parser{data: data, entry: entry} + return ParseWithOptions(data, entry, ParseOptions{}) +} + +// ParseWithOptions decodes a DEX file while applying explicit recovery +// tolerances when configured. +func ParseWithOptions(data []byte, entry string, options ParseOptions) (*model.File, error) { + p := &parser{data: data, entry: entry, options: options} return p.parse() } @@ -130,14 +144,23 @@ func (p *parser) parse() (*model.File, error) { if err := p.checkAnnotationMethodMembership(); err != nil { return nil, err } - wantSignature := sha1.Sum(p.data[32:]) - if !bytes.Equal(h.Signature[:], wantSignature[:]) { - return nil, p.fail(12, "header signature", "SHA-1 signature mismatch") - } wantChecksum := adler32.Checksum(p.data[12:]) if h.Checksum != wantChecksum { return nil, p.fail(8, "header checksum", "Adler-32 checksum=%08x, computed=%08x", h.Checksum, wantChecksum) } + wantSignature := sha1.Sum(p.data[32:]) + if !bytes.Equal(h.Signature[:], wantSignature[:]) { + if !p.options.TolerateSignatureMismatch { + return nil, p.fail(12, "header signature", "SHA-1 signature mismatch") + } + p.file.ParseWarnings = append(p.file.ParseWarnings, model.ParseWarning{ + Entry: p.entry, + Code: "header.signature_mismatch", + Action: "ignore_header_signature", + Feature: "dex-header", + Message: fmt.Sprintf("SHA-1 signature=%x, computed=%x (Adler-32 checksum valid)", h.Signature, wantSignature), + }) + } return p.file, nil } diff --git a/internal/dexparser/parser_recover_test.go b/internal/dexparser/parser_recover_test.go new file mode 100644 index 00000000..721ebd64 --- /dev/null +++ b/internal/dexparser/parser_recover_test.go @@ -0,0 +1,87 @@ +package dexparser + +import ( + "encoding/binary" + "hash/adler32" + "strings" + "testing" + + "github.com/yaklang/javajive/dex2jar/model" +) + +func TestParseWithOptionsToleratesSignatureMismatchWhenChecksumValid(t *testing.T) { + staleSHA1 := testDEXWithMapItem(0xf000) + // Mutate SHA-1 digest while keeping Adler-32 over data[12:] valid, matching + // tampered/repacked crackme DEX headers. + staleSHA1[12] ^= 0xff + putTestU32(staleSHA1, 8, adler32.Checksum(staleSHA1[12:])) + + if _, err := Parse(staleSHA1, "classes.dex"); err == nil || !strings.Contains(err.Error(), "SHA-1 signature mismatch") { + t.Fatalf("strict Parse(stale SHA-1) error = %v, want SHA-1 signature mismatch", err) + } + + recovered, err := ParseWithOptions(staleSHA1, "classes.dex", ParseOptions{TolerateSignatureMismatch: true}) + if err != nil { + t.Fatalf("ParseWithOptions(TolerateSignatureMismatch=true) failed: %v", err) + } + if len(recovered.ParseWarnings) != 1 || recovered.ParseWarnings[0].Code != "header.signature_mismatch" { + t.Fatalf("ParseWarnings = %#v, want single header.signature_mismatch warning", recovered.ParseWarnings) + } + + badAdler := append([]byte(nil), staleSHA1...) + putTestU32(badAdler, 8, binary.LittleEndian.Uint32(badAdler[8:12])^1) + if _, err := ParseWithOptions(badAdler, "classes.dex", ParseOptions{TolerateSignatureMismatch: true}); err == nil || !strings.Contains(err.Error(), "Adler-32 checksum=") { + t.Fatalf("ParseWithOptions(bad Adler-32) error = %v, want Adler-32 checksum failure", err) + } +} + +func TestTranslateSystemAnnotationsToleratesOrphanAnnotationDefault(t *testing.T) { + const owner = "LT0/f;" + makeClass := func() model.Class { + return model.Class{ + Descriptor: owner, + VirtualMethods: []model.EncodedMethod{{ + MethodIndex: 7, + Method: model.MethodID{Class: owner, Name: "value"}, + }}, + Annotations: []model.Annotation{{ + Visibility: model.AnnotationSystem, + Type: "Ldalvik/annotation/AnnotationDefault;", + Elements: []model.AnnotationElement{{ + Name: "value", + Value: model.EncodedValue{Type: model.ValueAnnotation, Annotation: &model.EncodedAnnotation{ + Type: owner, + Elements: []model.AnnotationElement{ + {Name: "value", Value: model.EncodedValue{Type: model.ValueInt, Signed: 7}}, + {Name: "intEncoding", Value: model.EncodedValue{Type: model.ValueInt, Signed: 1}}, + }, + }}, + }}, + }}, + } + } + + strictFile := &model.File{Entry: "classes.dex"} + strictClass := makeClass() + strictParser := &parser{file: strictFile} + if err := strictParser.translateSystemAnnotations(&strictClass); err == nil || !strings.Contains(err.Error(), `AnnotationDefault element "intEncoding" has no annotation method`) { + t.Fatalf("strict translateSystemAnnotations error = %v, want orphan annotation method failure", err) + } + + recoverFile := &model.File{Entry: "classes.dex"} + recoverClass := makeClass() + recoverParser := &parser{file: recoverFile, options: ParseOptions{TolerateOrphanAnnotationDefault: true}} + if err := recoverParser.translateSystemAnnotations(&recoverClass); err != nil { + t.Fatalf("recover translateSystemAnnotations failed: %v", err) + } + if len(recoverFile.ParseWarnings) != 1 || recoverFile.ParseWarnings[0].Code != "annotation.orphan_default" { + t.Fatalf("ParseWarnings = %#v, want single annotation.orphan_default warning", recoverFile.ParseWarnings) + } + if len(recoverClass.MethodAnnotations) != 1 || recoverClass.MethodAnnotations[0].MethodIndex != 7 { + t.Fatalf("MethodAnnotations = %#v, want valid 'value' default preserved", recoverClass.MethodAnnotations) + } + gotDefault := recoverClass.MethodAnnotations[0].Annotations[0].Elements[0].Value + if gotDefault.Type != model.ValueInt || gotDefault.Signed != 7 { + t.Fatalf("preserved default = %#v, want int 7", gotDefault) + } +} diff --git a/internal/filesys/t23_archive.go b/internal/filesys/t23_archive.go index b42e9a78..cd599f43 100644 --- a/internal/filesys/t23_archive.go +++ b/internal/filesys/t23_archive.go @@ -72,13 +72,14 @@ func ArchiveLimitsFromWork(l workbudget.Limits) ArchiveLimits { // ArchiveOptions is the request-scoped archive policy passed into ZipFS constructors. type ArchiveOptions struct { - Limits ArchiveLimits - Budget *ArchiveBudget - Work *workbudget.Budget // canonical request budget; Budget wraps this when set - Context context.Context - Depth int - TargetRelease int - SafeArchive bool + Limits ArchiveLimits + Budget *ArchiveBudget + Work *workbudget.Budget // canonical request budget; Budget wraps this when set + Context context.Context + Depth int + TargetRelease int + SafeArchive bool + AllowCaseFoldCollisions bool } // ArchiveBudget is a thin adapter over the canonical *workbudget.Budget. @@ -318,6 +319,12 @@ func WithSafeArchive(v bool) ZipFSOption { } } +func WithAllowCaseFoldCollisions(v bool) ZipFSOption { + return func(c *zipFSConfig) { + c.allowCaseFoldCollisions = v + } +} + func WithArchiveOptions(o ArchiveOptions) ZipFSOption { return func(c *zipFSConfig) { c.limits = o.Limits @@ -330,6 +337,7 @@ func WithArchiveOptions(o ArchiveOptions) ZipFSOption { c.ctx = o.Context c.depth = o.Depth c.targetRelease = o.TargetRelease + c.allowCaseFoldCollisions = o.AllowCaseFoldCollisions if o.SafeArchive || o.Budget != nil || o.Work != nil || o.Limits.limited() || o.Context != nil || o.TargetRelease != 0 || o.Depth != 0 { c.safeArchive = true } @@ -397,6 +405,13 @@ func (z *ZipFS) SafeArchive() bool { return z.safeArchive } +func (z *ZipFS) AllowCaseFoldCollisions() bool { + if z == nil { + return false + } + return z.allowCaseFoldCollisions +} + func (z *ZipFS) ArchiveActive() bool { if z == nil { return false @@ -541,6 +556,9 @@ func (z *ZipFS) NestedArchiveOptions(depth int) []ZipFSOption { if z.password != "" { opts = append(opts, WithZipFSPassword(z.password)) } + if z.allowCaseFoldCollisions { + opts = append(opts, WithAllowCaseFoldCollisions(true)) + } return opts } @@ -553,6 +571,7 @@ func (z *ZipFS) applyArchiveConfig(cfg *zipFSConfig) error { z.depth = cfg.depth z.targetRelease = cfg.targetRelease z.safeArchive = cfg.safeArchive + z.allowCaseFoldCollisions = cfg.allowCaseFoldCollisions z.budget = cfg.budget z.archiveActive = cfg.limitsSet || cfg.budget != nil || cfg.work != nil || cfg.safeArchive || cfg.ctx != nil || cfg.targetRelease != 0 || cfg.depth != 0 if err := z.limits.Validate(); err != nil { @@ -617,11 +636,13 @@ func (z *ZipFS) catalogArchiveFiles() error { return pathRejectedError("duplicate entry", key) } seen[key] = struct{}{} - fold := strings.ToLower(key) - if prev, ok := seenFold[fold]; ok && prev != key { - return pathRejectedError("case-fold collision", prev+" vs "+key) + if !z.allowCaseFoldCollisions { + fold := strings.ToLower(key) + if prev, ok := seenFold[fold]; ok && prev != key { + return pathRejectedError("case-fold collision", prev+" vs "+key) + } + seenFold[fold] = key } - seenFold[fold] = key if err := noteFileDirCollision(seenFile, seenDir, key, isDir); err != nil { return err } diff --git a/internal/filesys/zip_fs.go b/internal/filesys/zip_fs.go index d8a35ac2..94c1c065 100644 --- a/internal/filesys/zip_fs.go +++ b/internal/filesys/zip_fs.go @@ -26,14 +26,15 @@ type ZipFSOption func(*zipFSConfig) type zipFSConfig struct { Password string - limits ArchiveLimits - limitsSet bool - budget *ArchiveBudget - work *workbudget.Budget - ctx context.Context - depth int - targetRelease int - safeArchive bool + limits ArchiveLimits + limitsSet bool + budget *ArchiveBudget + work *workbudget.Budget + ctx context.Context + depth int + targetRelease int + safeArchive bool + allowCaseFoldCollisions bool } // WithZipFSPassword 设置加密 zip 的解密密码 @@ -62,13 +63,14 @@ type ZipFS struct { // 关键词: ZipFS 密码字段 password string - budget *ArchiveBudget - limits ArchiveLimits - ctx context.Context - depth int - targetRelease int - safeArchive bool - archiveActive bool + budget *ArchiveBudget + limits ArchiveLimits + ctx context.Context + depth int + targetRelease int + safeArchive bool + allowCaseFoldCollisions bool + archiveActive bool } // SetPassword 后置设置 ZipFS 解密密码 diff --git a/tools/requiredci/main.go b/tools/requiredci/main.go index dbe48f95..1003c393 100644 --- a/tools/requiredci/main.go +++ b/tools/requiredci/main.go @@ -35,12 +35,12 @@ var requiredSuites = []suite{ {Group: "algorithm", Package: "./ci/requiredci", Tests: 6, TestHash: "38ec9ce7d0cf47aef55f2facb53299862361febe6b1e06075e1cdd3d6a4554f6", Include: []string{"TestConcurrentDecompileDeterministic"}}, {Group: "corpus", Package: "./test/cross", Tests: 104, TestHash: "17c48c808ac80dbb2055c86a65896b22997f04f8ad72643a76cb91025eb2ff43", Include: []string{"TestFixedIrreducibleCFGCorpusPureGo"}}, {Group: "corpus", Package: "./classparser/classfilebuilder", Tests: 28, TestHash: "c01fe6d24ffc6f7f36459039cb8d2cf02fa8e6a080759b390bbb7102354d4609", Exclude: []string{"TestJava8InterfaceStaticMethodVerifies", "TestJavaVerifyAll", "TestLongDoubleAndFloatConstantsExecute"}}, - {Group: "corpus", Package: "./classparser/jarwar", Tests: 18, TestHash: "b1195066bc29f6a35391695fb815b4eef9eb42a55ef53f7ba9786375a27afc25"}, + {Group: "corpus", Package: "./classparser/jarwar", Tests: 19, TestHash: "343082b1d3beaf8136666437035086dc34540c5d9f6c43ed10e4b870e54db9be"}, {Group: "corpus", Package: "./classparser/decompiler/jar", Tests: 1, TestHash: "e84c19ac824483c172a763d735732079fb808d6dd0153c53e573b18513d23553"}, {Group: "corpus", Package: "./jimage", Tests: 16, TestHash: "f68b01a6c2a476c2a5921fc30f5ab3a6c0b700fe04748ac1e1d5d9573e283df8", Exclude: []string{"TestJLinkBigEndianImage", "TestJLinkCompactCPImage", "TestOpenJDKImage"}}, - {Group: "corpus", Package: "./classparser", Tests: 4188, TestHash: "584b32cac87cbd34e8ca61334fec0f70abaf45967b248d0e43c9d171938dab29", Include: []string{"TestDumpMethodsPointerFastPathKeepsDescriptor", "TestJoinRuleChainExactOutput", "TestSourceRewritePrecisionOuterGateSemantics", "TestRewriteSchedulerOrderMatchesDumperCallSites", "TestRewriteSchedulerPositiveAndNearMissExactOutput", "TestRewriteSchedulerPreservesRecordsDiagnosticsAndHashes", "TestRewriteSchedulerDecompileEquivalence", "TestJDKObjectMetadataMatchesCatalog", "TestJDKCompressedCatalogMatchesSource", "TestJDKConstructorBundleSlimDefault", "TestLoopAnalysisCacheMatchesUncachedDecompile", "FuzzDecompileWithLimitsNeverPanics", "TestAdversarialT4bPhiConvergentAndLiveStore", "TestAdversarialThisAliasSuperCall", "TestAdversarialConstructorIrreducibleDispatch", "TestAdversarialLoopNormalizationWithConstPrefixAndAssign", "TestAdversarialR8RetainUnprovedSourceFallbacks", "TestAdversarialP1ConstructorPrefixAndStrictGating", "TestAdversarialP1CheckedEscapeIncompleteHierarchy", "TestAdversarialP1ExceptionSentinelAndNilSlotSafe", "TestAdversarialLoopConstPrefixRejectsCondAndBodyMutationBytecode", "TestRetainedConstructorPrefixPureEscapingDeferral", "TestRetainedConstructorPrefixOrderedMultiArgAndFailClosed", "TestRetainedConstructorPrefixArrayInitializer", "TestRetainedConstructorThisAliasAndRemainingFieldStores", "TestRetargetAssignToTypedSiblingGuardsDeclarationsAndForwardScope"}}, + {Group: "corpus", Package: "./classparser", Tests: 4189, TestHash: "e73562a49ad02d0d4fec294f8e86ec3891403da25d4eefa35a4e306ecf3ef9bc", Include: []string{"TestDumpMethodsPointerFastPathKeepsDescriptor", "TestJoinRuleChainExactOutput", "TestSourceRewritePrecisionOuterGateSemantics", "TestRewriteSchedulerOrderMatchesDumperCallSites", "TestRewriteSchedulerPositiveAndNearMissExactOutput", "TestRewriteSchedulerPreservesRecordsDiagnosticsAndHashes", "TestRewriteSchedulerDecompileEquivalence", "TestJDKObjectMetadataMatchesCatalog", "TestJDKCompressedCatalogMatchesSource", "TestJDKConstructorBundleSlimDefault", "TestLoopAnalysisCacheMatchesUncachedDecompile", "FuzzDecompileWithLimitsNeverPanics", "TestAdversarialT4bPhiConvergentAndLiveStore", "TestAdversarialThisAliasSuperCall", "TestAdversarialConstructorIrreducibleDispatch", "TestAdversarialLoopNormalizationWithConstPrefixAndAssign", "TestAdversarialR8RetainUnprovedSourceFallbacks", "TestAdversarialP1ConstructorPrefixAndStrictGating", "TestAdversarialP1CheckedEscapeIncompleteHierarchy", "TestAdversarialP1ExceptionSentinelAndNilSlotSafe", "TestAdversarialLoopConstPrefixRejectsCondAndBodyMutationBytecode", "TestRetainedConstructorPrefixPureEscapingDeferral", "TestRetainedConstructorPrefixOrderedMultiArgAndFailClosed", "TestRetainedConstructorPrefixArrayInitializer", "TestRetainedConstructorThisAliasAndRemainingFieldStores", "TestRetargetAssignToTypedSiblingGuardsDeclarationsAndForwardScope", "TestStubMethodNameSanitizedAsSafeIdentifier"}}, - {Group: "algorithm", Package: "./classparser/decompiler/core", Tests: 421, TestHash: "3b808b97df4f3e076d6635bf94283e0658257b626b1dcb68ef9d795fc4dd8cf8"}, + {Group: "algorithm", Package: "./classparser/decompiler/core", Tests: 422, TestHash: "ccae7aaf6aad3696c6e05c36e604924c6f317f82d2013baf121f4b2d4b188a71"}, {Group: "algorithm", Package: "./classparser/decompiler/core/callbinding", Tests: 17, TestHash: "e7eafd33ec36c2219f362b5c45872f126dde5a81dab84d931023fd1abc1836cc"}, {Group: "algorithm", Package: "./classparser/decompiler/core/class_context", Tests: 26, TestHash: "254c1ad1ea4a5da5d4bc6849e1067c11ef1953a2c171436e59d8b18627811c40"}, {Group: "algorithm", Package: "./classparser/decompiler/core/fieldbinding", Tests: 1, TestHash: "6ec3bd03aab62727a5d86c38f16a3e99142866db2c91b5d2872616162fc2b06e"}, @@ -56,10 +56,10 @@ var requiredSuites = []suite{ {Group: "algorithm", Package: "./internal/jdecenv", Tests: 13, TestHash: "51ee508a5994d7763fb87e1d2d9cf78a345237af650479b650dbf055625082ad"}, {Group: "algorithm", Package: "./internal/filesys", Tests: 9, TestHash: "f6485392fe079ab59aafa635aca0d9bbe00b7af50334a7c1362396d883d82e31"}, - {Group: "dex", Package: "./dex2jar", Tests: 50, TestHash: "680cb732cf618afa28f149c09da93fc13a1b180c5a513cc6999afe288527f52e", Exclude: []string{"TestAcceptedCorpusJVMOracle", "TestCoverageBaselineContract", "TestStrictAcceptedDEXRoundtripGate"}}, + {Group: "dex", Package: "./dex2jar", Tests: 53, TestHash: "2a03f0535d09f2cd91335bc7525c51cf1ec16b61e25d7ce406c657f630216e88", Exclude: []string{"TestAcceptedCorpusJVMOracle", "TestCoverageBaselineContract", "TestStrictAcceptedDEXRoundtripGate"}}, {Group: "dex", Package: "./dex2jar/input", Tests: 25, TestHash: "6c3d9f03eab44176f1ad0e882252f2ef4f9593ef71f6d6cb71e61ef7c57cbe92"}, {Group: "dex", Package: "./dex2jar/ir", Tests: 43, TestHash: "1a8c256ed990bb96db287b1be2fa7f11786bbc5d30eadafd8db2376e3878a508"}, - {Group: "dex", Package: "./dex2jar/lower", Tests: 54, TestHash: "ddc42bcad210f675f5b8ea1e15a38908ea834b7628d364dc13f2ac028b750e45", Exclude: []string{ + {Group: "dex", Package: "./dex2jar/lower", Tests: 69, TestHash: "5888019ab13bbc1b21370309b6061ae3c00652421c1fd6be5dbbe77cdc0b8378", Exclude: []string{ "TestClassParsesVerifiesAndExecutes", "TestIntArrayPathVerifiesAndExecutes", "TestUnsupportedStubsVerifyAndThrow", "TestThisDelegationVerifiesAndExecutes", "TestLowerEmitsMetadataAttributes", "TestLowerFilledNewArrayAndNarrowArrayElements", "TestLowerEmitsAnnotationDefaultForReflection", "TestLowerEmitsClassMetadataAndArrayOwnerInvoke", "TestLowerMovesPreDelegationFieldStoreAfterSuper", "TestLowerInterleavedAllocationKeepsArgumentOrder", "TestLowerCapturesDeferredStoreValueBeforeReassignment", "TestRecoverFailsClosedForUnsupportedStaticInitializer", "TestRecoverClassVerifiesWithoutInitialization", "TestRecoverChildFirstInterfaceShellsVerifyOnJVM", @@ -67,7 +67,7 @@ var requiredSuites = []suite{ }}, {Group: "dex", Package: "./dex2jar/report", Tests: 7, TestHash: "6121738f00eca84495e4795ebdd9887db39a8ff30f761bd307bfb7bf0eed2081"}, {Group: "dex", Package: "./inspect", Tests: 14, TestHash: "cd4f7f82cabeb7f10478e2b345c28aa2352d1e08396d8ade41e1c581d267e263"}, - {Group: "dex", Package: "./internal/dexparser", Tests: 7, TestHash: "68b75deab796dfe9f97a72cbf851c969b7700f7ee856371e93fef5be76d9354d"}, + {Group: "dex", Package: "./internal/dexparser", Tests: 9, TestHash: "9567235f4694850a14ba388d79bb5bf908773c23d114e048fdf1d2495af9747c"}, {Group: "dex", Package: "./internal/inputkind", Tests: 6, TestHash: "b1aeb5061859deadc6a597d2b2feb84cd8ebeb199b08006adbfc86e63838a6fa"}, {Group: "dex", Package: "./internal/mutf8", Tests: 6, TestHash: "f176fe43927c9dff4e9f378419d80c0d889d67e93aa568f3250e7edc8dd3ad72"}, {Group: "dex", Package: "./internal/zipx", Tests: 3, TestHash: "773ae48e36e49359aa27baf6364ba5c4712e6586e7235db6d628c14e568714a7"}, From 4858a3b28f23b32c2b1bd03b5b485080b9477b42 Mon Sep 17 00:00:00 2001 From: v1ll4n Date: Sun, 22 Nov 2026 13:56:37 +0800 Subject: [PATCH 2/2] chore(release): bump version to v0.11.0 --- javajive.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javajive.go b/javajive.go index 7522f658..18d338da 100644 --- a/javajive.go +++ b/javajive.go @@ -38,7 +38,7 @@ import ( ) // Version is the javajive library/CLI version. -const Version = "0.10.1" +const Version = "0.11.0" // HasEmbeddedJDKConstructorBundle reports whether this binary was compiled with // `-tags javajive_full_jdk` (embedding the 7.7 MiB JDK constructor classfile