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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
126 changes: 122 additions & 4 deletions classparser/constructor_retain_prefix.go
Original file line number Diff line number Diff line change
Expand Up @@ -993,6 +993,83 @@ func tryFoldCtorArrayInit(prefix []statements.Statement, idx int, arrID *coreuti
return &cp, consumed, endIdx, true
}

func canCommitWithRemainingThisFieldStores(remaining []statements.Statement, remRewriteByAssign map[*statements.AssignStatement]values.JavaValue, env map[*coreutils.VariableId]values.JavaValue, newArgs []values.JavaValue, delegate *values.FunctionCallExpression, superClass string, ctx *class_context.ClassContext) bool {
if len(remaining) == 0 || delegate == nil || ctx == nil {
return false
}
allRHSIDs := map[*coreutils.VariableId]bool{}
for _, st := range remaining {
if st == nil {
continue
}
switch st.(type) {
case *statements.MiddleStatement, *statements.StackAssignStatement:
continue
}
as := ctorAssignStmt(st)
if as == nil || as.ArrayMember != nil || as.IsDeclare || as.JavaValue == nil {
return false
}
rm, isField := values.UnpackSoltValue(as.LeftValue).(*values.RefMember)
if !isField || rm == nil {
return false
}
recv, isRef := values.UnpackSoltValue(rm.Object).(*values.JavaRef)
if !isRef || recv == nil || !recv.IsThis {
return false
}
rhs := as.JavaValue
if rewritten, ok := remRewriteByAssign[as]; ok && rewritten != nil {
rhs = rewritten
}
if eff, _ := values.InspectValue(rhs); eff&values.BarrierEffects != 0 {
return false
}
rhsIDs := map[*coreutils.VariableId]bool{}
collectValueVarReads(rhs, ctx, rhsIDs, nil, nil, 0)
for id := range rhsIDs {
if _, inEnv := env[id]; inEnv {
return false
}
allRHSIDs[id] = true
}
}
argWritten := map[*coreutils.VariableId]bool{}
for _, arg := range newArgs {
acc := values.InspectAccess(arg)
if len(allRHSIDs) > 0 && acc.Effects&values.EffectOpaque != 0 {
return false
}
for wRef := range acc.Writes {
if wRef != nil && wRef.Id != nil {
argWritten[wRef.Id] = true
}
}
}
for id := range allRHSIDs {
if argWritten[id] {
return false
}
}
if len(newArgs) == 0 && strings.ReplaceAll(delegate.ClassName, ".", "/") == superClass {
return true
}
remWritten := map[*coreutils.VariableId]bool{}
collectStmtVars(remaining, ctx, nil, remWritten, nil, nil, 0)
if len(remWritten) > 0 {
argIDs := map[*coreutils.VariableId]bool{}
for _, arg := range newArgs {
collectValueVarReads(arg, ctx, argIDs, nil, nil, 0)
}
for id := range remWritten {
if argIDs[id] {
return false
}
}
}
return true
}

func (c *ClassObjectDumper) foldRetainedConstructorPrefix(p *constructorSourceBoundary, postSuper []statements.Statement) {
if c == nil || p == nil || len(p.prefix) == 0 || p.delegate == nil {
return
Expand Down Expand Up @@ -1021,6 +1098,12 @@ func (c *ClassObjectDumper) foldRetainedConstructorPrefix(p *constructorSourceBo
hasRemainingBarrier := false
inlinedAnyBarrier := false

type remainingAssignRewrite struct {
assign *statements.AssignStatement
newRHS values.JavaValue
}
var remRewrites []remainingAssignRewrite
remRewriteByAssign := map[*statements.AssignStatement]values.JavaValue{}
type deferredEntry struct {
prefixIdx int
st statements.Statement
Expand Down Expand Up @@ -1142,12 +1225,30 @@ func (c *ClassObjectDumper) foldRetainedConstructorPrefix(p *constructorSourceBo
assignStmt := ctorAssignStmt(st)
lhs, rhs, ok := ctorRefLHS(st)
if !ok {
var pendingAssign *statements.AssignStatement
var pendingRHS values.JavaValue
if assignStmt != nil && assignStmt.ArrayMember == nil && assignStmt.JavaValue != nil && len(env) > 0 {
if rm, isField := values.UnpackSoltValue(assignStmt.LeftValue).(*values.RefMember); isField && rm != nil {
if recv, isRef := values.UnpackSoltValue(rm.Object).(*values.JavaRef); isRef && recv != nil && recv.IsThis {
if subVal, subOK := substCtorValue(assignStmt.JavaValue, env, c.FuncCtx, 0); subOK && subVal != assignStmt.JavaValue {
if eff, _ := values.InspectValue(subVal); eff&values.BarrierEffects == 0 {
pendingAssign = assignStmt
pendingRHS = subVal
}
}
}
}
}
written := map[*coreutils.VariableId]bool{}
collectStmtVars([]statements.Statement{st}, c.FuncCtx, nil, written, nil, nil, 0)
for id := range written {
delete(env, id)
}
appendRemaining(idx, st)
if pendingAssign != nil && pendingRHS != nil {
remRewrites = append(remRewrites, remainingAssignRewrite{assign: pendingAssign, newRHS: pendingRHS})
remRewriteByAssign[pendingAssign] = pendingRHS
}
continue
}
if rhs == nil {
Expand All @@ -1166,6 +1267,18 @@ func (c *ClassObjectDumper) foldRetainedConstructorPrefix(p *constructorSourceBo
appendRemaining(idx, st)
continue
}
// Dead `this`-alias receiver local (`T alias = this;`) used solely as the
// constructor delegation receiver (`this(...)`/`super(...)` renders without it).
if c.getenv("JDEC_THIS_ALIAS_SUPER_OFF") == "" && lhs.IsThisAlias && !postIDs[lhs.Id] && useCount[lhs.Id] == 0 {
if rhsRef, isRef := values.UnpackSoltValue(subRHS).(*values.JavaRef); isRef && rhsRef != nil && (rhsRef.IsThis || rhsRef.IsThisAlias) {
tailIDs := map[*coreutils.VariableId]bool{}
collectStmtVars(p.prefix[idx+1:], c.FuncCtx, tailIDs, nil, nil, nil, 0)
if !tailIDs[lhs.Id] {
folded[st] = true
continue
}
}
}
if !hasRemainingBarrier && !postIDs[lhs.Id] && paramByID[lhs.Id] == nil && useCount[lhs.Id] == 1 && !condUsed[lhs.Id] {
if r, hasRank := useRank[lhs.Id]; hasRank && r > lastInlinedBarrierRank && (firstOrigBarrier < 0 || r < firstOrigBarrier) {
if ne, isNew := values.UnpackSoltValue(subRHS).(*values.NewExpression); isNew && ne != nil && ne.IsArray() {
Expand Down Expand Up @@ -1354,10 +1467,7 @@ func (c *ClassObjectDumper) foldRetainedConstructorPrefix(p *constructorSourceBo
}
}

if hasRemainingBarrier && inlinedAnyBarrier {
return
}
if len(folded) == 0 && !mutatedDelegate && len(deferred) == 0 {
if len(folded) == 0 && !mutatedDelegate && len(deferred) == 0 && len(remRewrites) == 0 {
return
}
newArgs := make([]values.JavaValue, len(delegateArgs))
Expand All @@ -1368,6 +1478,14 @@ func (c *ClassObjectDumper) foldRetainedConstructorPrefix(p *constructorSourceBo
}
newArgs[i] = sub
}
if hasRemainingBarrier && inlinedAnyBarrier && !canCommitWithRemainingThisFieldStores(remaining, remRewriteByAssign, env, newArgs, p.delegate, c.obj.GetSupperClassName(), c.FuncCtx) {
return
}
for _, rw := range remRewrites {
if rw.assign != nil && rw.newRHS != nil {
rw.assign.JavaValue = rw.newRHS
}
}
for _, d := range deferred {
if d.newRHS != nil && d.assign != nil {
d.assign.JavaValue = d.newRHS
Expand Down
186 changes: 186 additions & 0 deletions classparser/constructor_retain_prefix_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ import (
"testing"

"github.com/yaklang/javajive/classparser/classfilebuilder"
"github.com/yaklang/javajive/classparser/decompiler/core/class_context"
"github.com/yaklang/javajive/classparser/decompiler/core/statements"
coreutils "github.com/yaklang/javajive/classparser/decompiler/core/utils"
"github.com/yaklang/javajive/classparser/decompiler/core/values"
"github.com/yaklang/javajive/classparser/decompiler/core/values/types"
)

func TestRetainedConstructorPrefixPureEscapingDeferral(t *testing.T) {
Expand Down Expand Up @@ -318,3 +323,184 @@ func TestRetainedConstructorPrefixArrayInitializer(t *testing.T) {
}
})
}

func TestRetainedConstructorThisAliasAndRemainingFieldStores(t *testing.T) {
t.Run("this_alias_this_delegation", func(t *testing.T) {
c := classfilebuilder.NewClass("adv/ThisAliasSelfCtor", "java/lang/Object", 0x0021)
c.AddField(0x0018, "STYLE", "I")
styleField, err := c.Pool().Fieldref("adv/ThisAliasSelfCtor", "STYLE", "I")
if err != nil {
t.Fatal(err)
}
intCtor, err := c.Pool().Methodref("adv/ThisAliasSelfCtor", "<init>", "(II)V")
if err != nil {
t.Fatal(err)
}
objCtor, err := c.Pool().Methodref("java/lang/Object", "<init>", "()V")
if err != nil {
t.Fatal(err)
}
c.AddMethod(0x0001, "<init>", "(II)V").Code().
Load(classfilebuilder.RefLocal, 0).
CP(classfilebuilder.INVOKESPECIAL, objCtor).
Emit(classfilebuilder.RETURN)
// Place a prefix barrier after aliasing `this` so `var1` stays a distinct IsThisAlias local.
c.AddMethod(0x0001, "<init>", "(I)V").Code().
Load(classfilebuilder.RefLocal, 0).
Store(classfilebuilder.RefLocal, 2).
CP(classfilebuilder.GETSTATIC, styleField).
Store(classfilebuilder.IntLocal, 3).
Load(classfilebuilder.RefLocal, 2).
Load(classfilebuilder.IntLocal, 1).
Load(classfilebuilder.IntLocal, 3).
CP(classfilebuilder.INVOKESPECIAL, intCtor).
Emit(classfilebuilder.RETURN)

raw := mustBuildClass(t, c)

strictRes, err := DecompileWithOptions(raw, DecompileOptions{Mode: Precision})
if err != nil {
t.Fatalf("strict DecompileWithOptions failed: %v", err)
}
if len(strictRes.StubMethods) == 0 && !strings.Contains(strictRes.Source, DecompileStubMarker) {
t.Fatalf("expected Precision mode to reject unproved IsThisAlias prefix:\n%s", strictRes.Source)
}

t.Setenv("JDEC_THIS_ALIAS_SUPER_OFF", "")
t.Setenv("JDEC_CTOR_RETAIN_PREFIX_OFF", "")
res, err := DecompileWithOptions(raw, DecompileOptions{
Mode: Compatibility,
RetainUnprovedSource: true,
})
if err != nil {
t.Fatalf("retained DecompileWithOptions failed: %v", err)
}
if len(res.StubMethods) != 0 || !strings.Contains(res.Source, "this(var1,") {
t.Fatalf("expected this(var1, ...); with 0 stubs, got stubs=%v:\n%s", res.StubMethods, res.Source)
}
if strings.Contains(res.Source, "= this;") {
t.Fatalf("expected dead this-alias copy dropped:\n%s", res.Source)
}

t.Setenv("JDEC_THIS_ALIAS_SUPER_OFF", "1")
offRes, err := DecompileWithOptions(raw, DecompileOptions{
Mode: Compatibility,
RetainUnprovedSource: true,
})
if err != nil {
t.Fatalf("kill-switch DecompileWithOptions failed: %v", err)
}
if strings.Contains(offRes.Source, "this(var1,") {
t.Fatalf("JDEC_THIS_ALIAS_SUPER_OFF=1 did not disable IsThisAlias this(...) delegation:\n%s", offRes.Source)
}
})

t.Run("this_alias_super_with_pre_super_barrier_and_field_capture", func(t *testing.T) {
c := classfilebuilder.NewClass("adv/ThisAliasSuperCap", "adv/BaseCap", 0x0021)
c.AddField(0x0010, "m", "Ljava/lang/Object;")
c.AddField(0x0018, "STYLE", "I")
styleField, err := c.Pool().Fieldref("adv/ThisAliasSuperCap", "STYLE", "I")
if err != nil {
t.Fatal(err)
}
capField, err := c.Pool().Fieldref("adv/ThisAliasSuperCap", "m", "Ljava/lang/Object;")
if err != nil {
t.Fatal(err)
}
superCtor, err := c.Pool().Methodref("adv/BaseCap", "<init>", "(II)V")
if err != nil {
t.Fatal(err)
}
c.AddMethod(0x0001, "<init>", "(Ljava/lang/Object;I)V").Code().
Load(classfilebuilder.RefLocal, 0).
Load(classfilebuilder.RefLocal, 1).
CP(classfilebuilder.PUTFIELD, capField).
Load(classfilebuilder.RefLocal, 0).
Store(classfilebuilder.RefLocal, 4).
CP(classfilebuilder.GETSTATIC, styleField).
Store(classfilebuilder.IntLocal, 3).
Load(classfilebuilder.RefLocal, 4).
Load(classfilebuilder.IntLocal, 2).
Load(classfilebuilder.IntLocal, 3).
CP(classfilebuilder.INVOKESPECIAL, superCtor).
Emit(classfilebuilder.RETURN)

raw := mustBuildClass(t, c)
t.Setenv("JDEC_THIS_ALIAS_SUPER_OFF", "")
t.Setenv("JDEC_CTOR_RETAIN_PREFIX_OFF", "")
res, err := DecompileWithOptions(raw, DecompileOptions{
Mode: Compatibility,
RetainUnprovedSource: true,
})
if err != nil {
t.Fatalf("DecompileWithOptions failed: %v", err)
}
if len(res.StubMethods) != 0 || strings.Contains(res.Source, DecompileStubMarker) {
t.Fatalf("expected 0 stubs, got stubs=%v:\n%s", res.StubMethods, res.Source)
}
superIdx := strings.Index(res.Source, "super(")
fieldIdx := strings.Index(res.Source, "this.m =")
if superIdx < 0 || fieldIdx < 0 || superIdx >= fieldIdx {
t.Fatalf("expected super(...) before this.m = ...:\n%s", res.Source)
}

strictRes, err := DecompileWithOptions(raw, DecompileOptions{Mode: Precision})
if err != nil {
t.Fatalf("strict DecompileWithOptions failed: %v", err)
}
if len(strictRes.StubMethods) == 0 || !strings.Contains(strictRes.Source, DecompileStubMarker) {
t.Fatalf("expected Precision mode to reject escaping pre-super field store + alias:\n%s", strictRes.Source)
}

t.Setenv("JDEC_THIS_ALIAS_SUPER_OFF", "1")
offRes, err := DecompileWithOptions(raw, DecompileOptions{
Mode: Compatibility,
RetainUnprovedSource: true,
})
if err != nil {
t.Fatalf("kill-switch DecompileWithOptions failed: %v", err)
}
if !strings.Contains(offRes.Source, "= this;") {
t.Fatalf("JDEC_THIS_ALIAS_SUPER_OFF=1 did not disable IsThisAlias alias folding/boundary recognition:\n%s", offRes.Source)
}
})

t.Run("canCommitWithRemainingThisFieldStores_fail_closed", func(t *testing.T) {
ctx := &class_context.ClassContext{ClassName: "adv.Sub"}
thisRef := values.NewJavaRef(coreutils.NewRootVariableId().Next(), nil, types.NewJavaClass("adv.Sub"))
thisRef.IsThis = true
pID := coreutils.NewRootVariableId().Next()
pID.SetName("var1")
pRef := values.NewJavaRef(pID, nil, types.NewJavaPrimer(types.JavaInteger))
pRef.IsParam = true
tmpID := coreutils.NewRootVariableId().Next()
tmpID.SetName("var3")
tmpRef := values.NewJavaRef(tmpID, nil, types.NewJavaPrimer(types.JavaInteger))

fieldStore := statements.NewAssignStatement(&values.RefMember{Object: thisRef, Member: "m"}, pRef, false)
delegate := &values.FunctionCallExpression{ClassName: "adv.Base", FunctionName: "<init>", Kind: values.InvokeSpecial}

if !canCommitWithRemainingThisFieldStores([]statements.Statement{fieldStore}, nil, map[*coreutils.VariableId]values.JavaValue{}, []values.JavaValue{values.NewJavaLiteral(1, pRef.Type())}, delegate, "adv/Base", ctx) {
t.Fatal("pure this.m = param remaining store should commit")
}

// Negative 1: non-this-field barrier in remaining.
callStmt := statements.NewExpressionStatement(&values.FunctionCallExpression{ClassName: "adv.Sub", FunctionName: "tick", Kind: values.InvokeStatic})
if canCommitWithRemainingThisFieldStores([]statements.Statement{callStmt}, nil, map[*coreutils.VariableId]values.JavaValue{}, nil, delegate, "adv/Base", ctx) {
t.Fatal("non-field call in remaining must fail closed")
}

// Negative 2: super argument writes parameter read by remaining this.m store.
mutArg := values.NewAssignmentExpression(pRef, values.NewJavaLiteral(9, pRef.Type()), -1, nil)
if canCommitWithRemainingThisFieldStores([]statements.Statement{fieldStore}, nil, map[*coreutils.VariableId]values.JavaValue{}, []values.JavaValue{mutArg}, delegate, "adv/Base", ctx) {
t.Fatal("remaining store reading arg-mutated parameter must fail closed")
}

// Negative 3: remaining store reads a folded local still in env.
foldedStore := statements.NewAssignStatement(&values.RefMember{Object: thisRef, Member: "m"}, tmpRef, false)
env := map[*coreutils.VariableId]values.JavaValue{tmpID: pRef}
if canCommitWithRemainingThisFieldStores([]statements.Statement{foldedStore}, nil, env, nil, delegate, "adv/Base", ctx) {
t.Fatal("remaining store referencing folded local must fail closed")
}
})
}
3 changes: 2 additions & 1 deletion classparser/constructor_source_boundary.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,8 @@ func (c *ClassObjectDumper) planConstructorSourceBoundary(code *CodeAttribute, b
continue
}
ref, ok := values.UnpackSoltValue(call.Object).(*values.JavaRef)
if !ok || ref == nil || !ref.IsThis {
isThisRecv := ok && ref != nil && (ref.IsThis || (c.getenv("JDEC_THIS_ALIAS_SUPER_OFF") == "" && ref.IsThisAlias))
if !isThisRecv {
continue
}
if p.delegate != nil {
Expand Down
3 changes: 3 additions & 0 deletions classparser/decompiler/rewriter/declaration_barriers.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,9 @@ func DeclarationInsertionBarriers(root []statements.Statement, ctx *class_contex
continue
}
seen[st] = true
if as, _ := unwrapAssignStatement(st); as != nil {
st = as
}
switch s := st.(type) {
case *statements.AssignStatement:
if s != nil && (s.IsFirst || s.IsDeclare) && s.ArrayMember == nil {
Expand Down
Loading
Loading