Kri*_*sen 2 java bytecode java-bytecode-asm
你好。
我想找到方法调用开始和结束之间的指令范围。
我不想简单地更改方法调用所有者/名称/描述。
有了预期的结果,我希望能够做到:
我一直在尝试不同的技术来实现这一目标:
start和end
我会给你一些我想要什么的例子,以防这里有任何混淆。
首先,看看我下面的测试代码,然后回到这里。
我希望找到/删除整个方法调用anotherMethod4并将其替换为一个简单的true,从而生成以下代码:
System.out.println(
anotherMethod1(
anotherMethod2("a", "b") ?
"c" : anotherMethod3("d", "e") ? "f" : "g",
true ? "j" : "k"
) ? "l" : "m"
);
Run Code Online (Sandbox Code Playgroud)
我希望找到/删除整个方法调用anotherMethod1并将其替换为一个简单的false,从而生成以下代码:
System.out.println(
false ? "l" : "m"
);
Run Code Online (Sandbox Code Playgroud)
我希望删除对 的整个方法调用System.out.println,从而生成以下代码:
private Main()
{
}
Run Code Online (Sandbox Code Playgroud)
这一定是可能的吗?
这是我当前的测试代码:
private Main()
{
System.out.println(
anotherMethod1(
anotherMethod2("a", "b") ?
"c" : anotherMethod3("d", "e") ? "f" : "g",
anotherMethod4("h", "i") ? "j" : "k"
) ? "l" : "m"
);
}
boolean anotherMethod1(String str, String oof)
{
return true;
}
boolean anotherMethod2(String str, String oof)
{
return true;
}
boolean anotherMethod3(String str, String oof)
{
return true;
}
boolean anotherMethod4(String str, String oof)
{
return true;
}
Run Code Online (Sandbox Code Playgroud)
方法调用的参数可能有副作用,例如method(variable = value),它甚至可能无法删除,例如,何时会导致在删除调用后访问未初始化的变量。在字节码级别,属于参数评估的指令可以与任意不相关的指令交错。
但是当我们限制范围时,我们可以有一个解决方案。在您的示例中,所有调用都是invokevirtual对字段的隐含this值或值调用的指令static。对于这些调用,我们确实可以使用 ASM 的AnalyzerwithSourceInterpreter来识别初始aload或getstatic指令,并假设来自该指令和调用指令的所有指令都属于方法调用表达式。
我们可以使用像这样的代码
public class IdentifyCall {
static IdentifyCall getInputs(
String internalClassName, MethodNode toAnalyze) throws AnalyzerException {
Map<AbstractInsnNode, Set<AbstractInsnNode>> sources = new HashMap<>();
SourceInterpreter i = new SourceInterpreter();
Analyzer<SourceValue> analyzer = new Analyzer<>(i);
return new IdentifyCall(toAnalyze.instructions, analyzer.analyze(internalClassName, toAnalyze));
}
private final InsnList instructions;
private final Frame<SourceValue>[] frames;
private IdentifyCall(InsnList il, Frame<SourceValue>[] analyzed) {
instructions = il;
frames = analyzed;
}
int[] getSpan(AbstractInsnNode i) {
MethodInsnNode mn = (MethodInsnNode)i;
// can't use getArgumentsAndReturnSizes, as for the frame, double and long do not count as 2
int nArg = mn.desc.startsWith("()")? 0: Type.getArgumentTypes(mn.desc).length;
int end = instructions.indexOf(mn);
Frame<SourceValue> f = frames[end];
SourceValue receiver = f.getStack(f.getStackSize() - nArg - 1);
if(receiver.insns.size() != 1) throw new UnsupportedOperationException();
AbstractInsnNode n = receiver.insns.iterator().next();
if(n.getOpcode() != Opcodes.ALOAD && n.getOpcode() != Opcodes.GETSTATIC)
throw new UnsupportedOperationException(""+n.getOpcode());
return new int[] { instructions.indexOf(n), end };
}
}
Run Code Online (Sandbox Code Playgroud)
并通过以下示例进行演示
public class IdentifyCallExample {
private void toAnalyze() {
System.out.println(
anotherMethod1(
anotherMethod2("a", "b") ?
"c" : anotherMethod3("d", "e") ? "f" : "g",
anotherMethod4("h", "i") ? "j" : "k"
) ? "l" : "m"
);
}
boolean anotherMethod1(String str, String oof) {
return true;
}
boolean anotherMethod2(String str, String oof) {
return true;
}
boolean anotherMethod3(String str, String oof) {
return true;
}
boolean anotherMethod4(String str, String oof) {
return true;
}
public static void main(String[] args) throws AnalyzerException, IOException {
Class<?> me = MethodHandles.lookup().lookupClass();
ClassReader r = new ClassReader(me.getResourceAsStream(me.getSimpleName()+".class"));
ClassNode cn = new ClassNode();
r.accept(cn, ClassReader.SKIP_DEBUG|ClassReader.SKIP_FRAMES);
MethodNode toAnalyze = null;
for(MethodNode mn: cn.methods)
if(mn.name.equals("toAnalyze")) {
toAnalyze = mn;
break;
}
List<int[]> invocations = new ArrayList<>();
final InsnList instructions = toAnalyze.instructions;
IdentifyCall identifyCall
= IdentifyCall.getInputs(me.getName().replace('.', '/'), toAnalyze);
for(int ix = 0, num = instructions.size(); ix < num; ix++) {
AbstractInsnNode instr = instructions.get(ix);
if(instr.getOpcode()!= Opcodes.INVOKEVIRTUAL) continue;
invocations.add(identifyCall.getSpan(instr));
}
printIt(invocations, instructions);
}
private static void printIt(List<int[]> invocations, final InsnList instructions) {
List<Level> levels = toTree(invocations);
Textifier toText = new Textifier();
TraceMethodVisitor tmv = new TraceMethodVisitor(toText);
for(int ix = 0, num = instructions.size(); ix < num; ix++) {
AbstractInsnNode instr = instructions.get(ix);
boolean line = false;
level: for(Level l: levels) {
if(ix >= l.lo && ix <= l.hi) {
for(int[] b: l.branches) {
if(ix < b[0] || ix > b[1]) continue;
System.out.print(line?
(b[0] == ix? b[1] == ix? "?[": "??": b[1] == ix? "??": "??"):
(b[0] == ix? b[1] == ix? " [": "??": b[1] == ix? "??": "? "));
line |= b[0] == ix || b[1] == ix;
continue level;
}
}
System.out.print(line? "??": " ");
}
instr.accept(tmv);
System.out.print(toText.text.get(0));
toText.text.clear();
}
}
static class Level {
int lo, hi;
ArrayDeque<int[]> branches=new ArrayDeque<>();
Level(int[] b) { lo=b[0]; hi=b[1]; branches.add(b); }
boolean insert(int[] b) {
if(b[1]<=lo) { branches.addFirst(b); lo=b[0]; }
else if(b[0]>=hi) { branches.addLast(b); hi=b[1]; }
else return b[0]>lo && b[1] < hi
&& (b[0]+b[1])>>1 > (lo+hi)>>1? tryTail(b, lo, hi): tryHead(b, lo, hi);
return true;
}
private boolean tryHead(int[] b, int lo, int hi) {
int[] head=branches.removeFirst();
try {
if(head[1] > b[0]) return false;
if(branches.isEmpty() || (lo=branches.getFirst()[0])>=b[1]) {
branches.addFirst(b);
return true;
}
else return b[0]>lo && b[1] < hi
&& (b[0]+b[1])>>1 > (lo+hi)>>1? tryTail(b, lo, hi): tryHead(b, lo, hi);
} finally { branches.addFirst(head); }
}
private boolean tryTail(int[] b, int lo, int hi) {
int[] tail=branches.removeLast();
try {
if(tail[0] < b[1]) return false;
if(branches.isEmpty() || (hi=branches.getLast()[1])<=b[0]) {
branches.addLast(b);
return true;
}
else return b[0]>lo && b[1] < hi
&& (b[0]+b[1])>>1 > (lo+hi)>>1? tryTail(b, lo, hi): tryHead(b, lo, hi);
} finally { branches.addLast(tail); }
}
}
static List<Level> toTree(List<int[]> list) {
if(list.isEmpty()) return Collections.emptyList();
if(list.size()==1) return Collections.singletonList(new Level(list.get(0)));
list.sort(Comparator.comparingInt(b -> b[1] - b[0]));
ArrayList<Level> l=new ArrayList<>();
insert: for(int[] b: list) {
for(Level level: l) if(level.insert(b)) continue insert;
l.add(new Level(b));
}
if(l.size() > 1) Collections.reverse(l);
return l;
}
}
Run Code Online (Sandbox Code Playgroud)
这将打印
public class IdentifyCall {
static IdentifyCall getInputs(
String internalClassName, MethodNode toAnalyze) throws AnalyzerException {
Map<AbstractInsnNode, Set<AbstractInsnNode>> sources = new HashMap<>();
SourceInterpreter i = new SourceInterpreter();
Analyzer<SourceValue> analyzer = new Analyzer<>(i);
return new IdentifyCall(toAnalyze.instructions, analyzer.analyze(internalClassName, toAnalyze));
}
private final InsnList instructions;
private final Frame<SourceValue>[] frames;
private IdentifyCall(InsnList il, Frame<SourceValue>[] analyzed) {
instructions = il;
frames = analyzed;
}
int[] getSpan(AbstractInsnNode i) {
MethodInsnNode mn = (MethodInsnNode)i;
// can't use getArgumentsAndReturnSizes, as for the frame, double and long do not count as 2
int nArg = mn.desc.startsWith("()")? 0: Type.getArgumentTypes(mn.desc).length;
int end = instructions.indexOf(mn);
Frame<SourceValue> f = frames[end];
SourceValue receiver = f.getStack(f.getStackSize() - nArg - 1);
if(receiver.insns.size() != 1) throw new UnsupportedOperationException();
AbstractInsnNode n = receiver.insns.iterator().next();
if(n.getOpcode() != Opcodes.ALOAD && n.getOpcode() != Opcodes.GETSTATIC)
throw new UnsupportedOperationException(""+n.getOpcode());
return new int[] { instructions.indexOf(n), end };
}
}
Run Code Online (Sandbox Code Playgroud)
当我们想要支持更复杂的接收器表达式或static方法时,它们的第一个参数可以是任意表达式,事情就会变得更加复杂。该Frame<SourceValue>使我们能够识别推电流值操作数栈的指令,但是在这样一个表达的情况下a + b,这将是iadd唯一的指令,我们就来分析一下iadd指令的框架,以获取其输入。与其为每一种指令都实现这一点Map,不如扩展解释器,获取信息并将其存储,例如在 a 中,就像Analyzer已经完成的这项工作一样。然后,我们可以递归地收集所有输入。
但这仅提供直接和间接输入源,但在条件表达式的情况下,我们还需要条件的输入。为此,我们必须识别和存储条件分支。每当报告输入可能来自不同的源指令时,我们必须检查相关分支并添加它们的条件。
然后我们再次使用简化假设,即第一个和最后一个之间的所有指令也属于调用表达式。
更详细的代码看起来像
public class IdentifyCall {
private final InsnList instructions;
private final Map<AbstractInsnNode, Set<SourceValue>> sources;
private final TreeMap<int[],AbstractInsnNode> conditionals;
private IdentifyCall(InsnList il,
Map<AbstractInsnNode, Set<SourceValue>> s, TreeMap<int[], AbstractInsnNode> c) {
instructions = il;
sources = s;
conditionals = c;
}
Set<AbstractInsnNode> getAllInputsOf(AbstractInsnNode instr) {
Set<AbstractInsnNode> source = new HashSet<>();
List<SourceValue> pending = new ArrayList<>(sources.get(instr));
for (int pIx = 0; pIx < pending.size(); pIx++) {
SourceValue sv = pending.get(pIx);
final boolean branch = sv.insns.size() > 1;
for(AbstractInsnNode in: sv.insns) {
if(source.add(in))
pending.addAll(sources.getOrDefault(in, Collections.emptySet()));
if(branch) {
int ix = instructions.indexOf(in);
conditionals.forEach((b,i) -> {
if(b[0] <= ix && b[1] >= ix && source.add(i))
pending.addAll(sources.getOrDefault(i, Collections.emptySet()));
});
}
}
}
return source;
}
static IdentifyCall getInputs(
String internalClassName, MethodNode toAnalyze) throws AnalyzerException {
InsnList instructions = toAnalyze.instructions;
Map<AbstractInsnNode, Set<SourceValue>> sources = new HashMap<>();
SourceInterpreter i = new SourceInterpreter() {
@Override
public SourceValue unaryOperation(AbstractInsnNode insn, SourceValue value) {
sources.computeIfAbsent(insn, x -> new HashSet<>()).add(value);
return super.unaryOperation(insn, value);
}
@Override
public SourceValue binaryOperation(AbstractInsnNode insn, SourceValue v1, SourceValue v2) {
addAll(insn, Arrays.asList(v1, v2));
return super.binaryOperation(insn, v1, v2);
}
@Override
public SourceValue ternaryOperation(AbstractInsnNode insn, SourceValue v1, SourceValue v2, SourceValue v3) {
addAll(insn, Arrays.asList(v1, v2, v3));
return super.ternaryOperation(insn, v1, v2, v3);
}
@Override
public SourceValue naryOperation(AbstractInsnNode insn, List<? extends SourceValue> values) {
addAll(insn, values);
return super.naryOperation(insn, values);
}
private void addAll(AbstractInsnNode insn, List<? extends SourceValue> values) {
sources.computeIfAbsent(insn, x -> new HashSet<>()).addAll(values);
}
};
TreeMap<int[],AbstractInsnNode> conditionals = new TreeMap<>(
Comparator.comparingInt((int[] a) -> a[0]).thenComparingInt(a -> a[1]));
Analyzer<SourceValue> analyzer = new Analyzer<>(i) {
@Override
protected void newControlFlowEdge(int insn, int successor) {
if(insn != successor - 1) {
AbstractInsnNode instruction = instructions.get(insn);
Set<SourceValue> dep = sources.get(instruction);
if(dep != null && !dep.isEmpty())
conditionals.put(new int[]{ insn, successor }, instruction);
}
}
};
analyzer.analyze(internalClassName, toAnalyze);
return new IdentifyCall(instructions, sources, conditionals);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,我们还使用了更详细的示例代码:
public class IdentifyCallExample {
private void toAnalyze() {
(Math.random()>0.5? System.out: System.err).println(
anotherMethod1(
anotherMethod2("a", "b") ?
"c" : anotherMethod3("d", "e") ? "f" : "g",
anotherMethod4("h", "i") ? "j" : "k"
) ? "l" : "m"
);
}
static boolean anotherMethod1(String str, String oof) {
return true;
}
static boolean anotherMethod2(String str, String oof) {
return true;
}
static boolean anotherMethod3(String str, String oof) {
return true;
}
static boolean anotherMethod4(String str, String oof) {
return true;
}
public static void main(String[] args) throws AnalyzerException, IOException {
Class<?> me = MethodHandles.lookup().lookupClass();
ClassReader r = new ClassReader(me.getResourceAsStream(me.getSimpleName()+".class"));
ClassNode cn = new ClassNode();
r.accept(cn, ClassReader.SKIP_DEBUG|ClassReader.SKIP_FRAMES);
MethodNode toAnalyze = null;
for(MethodNode mn: cn.methods)
if(mn.name.equals("toAnalyze")) {
toAnalyze = mn;
break;
}
List<int[]> invocations = new ArrayList<>();
final InsnList instructions = toAnalyze.instructions;
IdentifyCall sources = IdentifyCall.getInputs(me.getName().replace('.', '/'), toAnalyze);
for(int ix = 0, num = instructions.size(); ix < num; ix++) {
AbstractInsnNode instr = instructions.get(ix);
if(instr.getType() != AbstractInsnNode.METHOD_INSN) continue;
IntSummaryStatistics s = sources.getAllInputsOf(instr).stream()
.mapToInt(instructions::indexOf).summaryStatistics();
s.accept(ix);
invocations.add(new int[]{s.getMin(), s.getMax()});
}
printIt(invocations, instructions);
}
// remainder as in the simple variant
Run Code Online (Sandbox Code Playgroud)
现在将打印
public class IdentifyCallExample {
private void toAnalyze() {
System.out.println(
anotherMethod1(
anotherMethod2("a", "b") ?
"c" : anotherMethod3("d", "e") ? "f" : "g",
anotherMethod4("h", "i") ? "j" : "k"
) ? "l" : "m"
);
}
boolean anotherMethod1(String str, String oof) {
return true;
}
boolean anotherMethod2(String str, String oof) {
return true;
}
boolean anotherMethod3(String str, String oof) {
return true;
}
boolean anotherMethod4(String str, String oof) {
return true;
}
public static void main(String[] args) throws AnalyzerException, IOException {
Class<?> me = MethodHandles.lookup().lookupClass();
ClassReader r = new ClassReader(me.getResourceAsStream(me.getSimpleName()+".class"));
ClassNode cn = new ClassNode();
r.accept(cn, ClassReader.SKIP_DEBUG|ClassReader.SKIP_FRAMES);
MethodNode toAnalyze = null;
for(MethodNode mn: cn.methods)
if(mn.name.equals("toAnalyze")) {
toAnalyze = mn;
break;
}
List<int[]> invocations = new ArrayList<>();
final InsnList instructions = toAnalyze.instructions;
IdentifyCall identifyCall
= IdentifyCall.getInputs(me.getName().replace('.', '/'), toAnalyze);
for(int ix = 0, num = instructions.size(); ix < num; ix++) {
AbstractInsnNode instr = instructions.get(ix);
if(instr.getOpcode()!= Opcodes.INVOKEVIRTUAL) continue;
invocations.add(identifyCall.getSpan(instr));
}
printIt(invocations, instructions);
}
private static void printIt(List<int[]> invocations, final InsnList instructions) {
List<Level> levels = toTree(invocations);
Textifier toText = new Textifier();
TraceMethodVisitor tmv = new TraceMethodVisitor(toText);
for(int ix = 0, num = instructions.size(); ix < num; ix++) {
AbstractInsnNode instr = instructions.get(ix);
boolean line = false;
level: for(Level l: levels) {
if(ix >= l.lo && ix <= l.hi) {
for(int[] b: l.branches) {
if(ix < b[0] || ix > b[1]) continue;
System.out.print(line?
(b[0] == ix? b[1] == ix? "?[": "??": b[1] == ix? "??": "??"):
(b[0] == ix? b[1] == ix? " [": "??": b[1] == ix? "??": "? "));
line |= b[0] == ix || b[1] == ix;
continue level;
}
}
System.out.print(line? "??": " ");
}
instr.accept(tmv);
System.out.print(toText.text.get(0));
toText.text.clear();
}
}
static class Level {
int lo, hi;
ArrayDeque<int[]> branches=new ArrayDeque<>();
Level(int[] b) { lo=b[0]; hi=b[1]; branches.add(b); }
boolean insert(int[] b) {
if(b[1]<=lo) { branches.addFirst(b); lo=b[0]; }
else if(b[0]>=hi) { branches.addLast(b); hi=b[1]; }
else return b[0]>lo && b[1] < hi
&& (b[0]+b[1])>>1 > (lo+hi)>>1? tryTail(b, lo, hi): tryHead(b, lo, hi);
return true;
}
private boolean tryHead(int[] b, int lo, int hi) {
int[] head=branches.removeFirst();
try {
if(head[1] > b[0]) return false;
if(branches.isEmpty() || (lo=branches.getFirst()[0])>=b[1]) {
branches.addFirst(b);
return true;
}
else return b[0]>lo && b[1] < hi
&& (b[0]+b[1])>>1 > (lo+hi)>>1? tryTail(b, lo, hi): tryHead(b, lo, hi);
} finally { branches.addFirst(head); }
}
private boolean tryTail(int[] b, int lo, int hi) {
int[] tail=branches.removeLast();
try {
if(tail[0] < b[1]) return false;
if(branches.isEmpty() || (hi=branches.getLast()[1])<=b[0]) {
branches.addLast(b);
return true;
}
else return b[0]>lo && b[1] < hi
&& (b[0]+b[1])>>1 > (lo+hi)>>1? tryTail(b, lo, hi): tryHead(b, lo, hi);
} finally { branches.addLast(tail); }
}
}
static List<Level> toTree(List<int[]> list) {
if(list.isEmpty()) return Collections.emptyList();
if(list.size()==1) return Collections.singletonList(new Level(list.get(0)));
list.sort(Comparator.comparingInt(b -> b[1] - b[0]));
ArrayList<Level> l=new ArrayList<>();
insert: for(int[] b: list) {
for(Level level: l) if(level.insert(b)) continue insert;
l.add(new Level(b));
}
if(l.size() > 1) Collections.reverse(l);
return l;
}
}
Run Code Online (Sandbox Code Playgroud)
这可能仍然无法捕获所有可能的情况,但对于您的用例来说已经足够了。
| 归档时间: |
|
| 查看次数: |
578 次 |
| 最近记录: |