Initial Commit

This commit is contained in:
Chicken Bones committed 2013-07-16 17:58:02 +10:00
1 parent 397135f687
commit 0f32dd8620
82 files changed
+10693

No files matched your search

+332
View File
@@ -0,0 +1,332 @@
package codechicken.lib.asm;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Label;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.LabelNode;
import org.objectweb.asm.tree.LocalVariableNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.TryCatchBlockNode;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import codechicken.lib.asm.InstructionComparator.InsnListSection;
public class ASMHelper
{
public static class CodeBlock
{
public Label start = new Label();
public Label end = new Label();
}
public static class ForBlock extends CodeBlock
{
public Label cmp = new Label();
public Label inc = new Label();
public Label body = new Label();
}
public static abstract class MethodAltercator
{
public final ObfMapping method;
public MethodAltercator(ObfMapping method)
{
this.method = method;
}
public abstract void alter(MethodNode mv);
}
public static abstract class MethodWriter
{
public final int access;
public final ObfMapping method;
public final String[] exceptions;
public MethodWriter(int access, ObfMapping method)
{
this(access, method, null);
}
public MethodWriter(int access, ObfMapping method, String[] exceptions)
{
this.access = access;
this.method = method;
this.exceptions = exceptions;
}
public abstract void write(MethodNode mv);
}
public static class MethodInjector
{
public final ObfMapping method;
public final InsnList needle;
public final InsnList injection;
public final boolean before;
public MethodInjector(ObfMapping method, InsnList needle, InsnList injection, boolean before)
{
this.method = method;
this.needle = needle;
this.injection = injection;
this.before = before;
}
}
public static MethodNode findMethod(ObfMapping methodmap, ClassNode cnode)
{
for(MethodNode mnode : cnode.methods)
if(methodmap.matches(mnode))
return mnode;
return null;
}
public static FieldNode findField(ObfMapping fieldmap, ClassNode cnode)
{
for(FieldNode fnode : cnode.fields)
if(fieldmap.matches(fnode))
return fnode;
return null;
}
public static ClassNode createClassNode(byte[] bytes)
{
return createClassNode(bytes, 0);
}
public static ClassNode createClassNode(byte[] bytes, int flags)
{
ClassNode cnode = new ClassNode();
ClassReader reader = new ClassReader(bytes);
reader.accept(cnode, flags);
return cnode;
}
public static byte[] createBytes(ClassNode cnode, int flags)
{
ClassWriter cw = new CC_ClassWriter(flags);
cnode.accept(cw);
return cw.toByteArray();
}
public static byte[] writeMethods(String name, byte[] bytes, Multimap<String, MethodWriter> writers)
{
if(writers.containsKey(name))
{
ClassNode cnode = createClassNode(bytes);
for(MethodWriter mw : writers.get(name))
{
MethodNode mv = findMethod(mw.method, cnode);
if(mv == null)
mv = (MethodNode) cnode.visitMethod(mw.access, mw.method.s_name, mw.method.s_desc, null, mw.exceptions);
mv.access = mw.access;
mv.instructions.clear();
mw.write(mv);
}
bytes = createBytes(cnode, ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
}
return bytes;
}
public static byte[] injectMethods(String name, byte[] bytes, Multimap<String, MethodInjector> injectors)
{
if(injectors.containsKey(name))
{
ClassNode cnode = createClassNode(bytes);
for(MethodInjector injector : injectors.get(name))
{
MethodNode method = findMethod(injector.method, cnode);
if(method == null)
throw new RuntimeException("Method not found: "+injector.method);
System.out.println("Injecting into " + injector.method + "\n" + printInsnList(injector.injection));
List<AbstractInsnNode> callNodes;
if(injector.before)
callNodes = InstructionComparator.insnListFindStart(method.instructions, injector.needle);
else
callNodes = InstructionComparator.insnListFindEnd(method.instructions, injector.needle);
if(callNodes.size() == 0)
{
throw new RuntimeException("Needle not found in Haystack: " + injector.method+"\n" + printInsnList(injector.needle));
}
for(AbstractInsnNode node : callNodes)
{
if(injector.before)
{
System.out.println("Injected before: "+printInsn(node));
method.instructions.insertBefore(node, cloneInsnList(injector.injection));
}
else
{
System.out.println("Injected after: "+printInsn(node));
method.instructions.insert(node, cloneInsnList(injector.injection));
}
}
}
bytes = createBytes(cnode, ClassWriter.COMPUTE_FRAMES);
}
return bytes;
}
public static String printInsnList(InsnList list)
{
InsnListPrinter p = new InsnListPrinter();
p.visitInsnList(list);
return p.textString();
}
public static String printInsn(AbstractInsnNode insn)
{
InsnListPrinter p = new InsnListPrinter();
p.visitInsn(insn);
return p.textString();
}
public static Map<LabelNode, LabelNode> cloneLabels(InsnList insns)
{
HashMap<LabelNode, LabelNode> labelMap = new HashMap<LabelNode, LabelNode>();
for(AbstractInsnNode insn = insns.getFirst(); insn != null; insn = insn.getNext())
if(insn.getType() == 8)
labelMap.put((LabelNode) insn, new LabelNode());
return labelMap;
}
public static InsnList cloneInsnList(InsnList insns)
{
return cloneInsnList(cloneLabels(insns), insns);
}
public static InsnList cloneInsnList(Map<LabelNode, LabelNode> labelMap, InsnList insns)
{
InsnList clone = new InsnList();
for(AbstractInsnNode insn = insns.getFirst(); insn != null; insn = insn.getNext())
clone.add(insn.clone(labelMap));
return clone;
}
public static List<TryCatchBlockNode> cloneTryCatchBlocks(Map<LabelNode, LabelNode> labelMap, List<TryCatchBlockNode> tcblocks)
{
ArrayList<TryCatchBlockNode> clone = new ArrayList<TryCatchBlockNode>();
for(TryCatchBlockNode node : tcblocks)
clone.add(new TryCatchBlockNode(
labelMap.get(node.start),
labelMap.get(node.end),
labelMap.get(node.handler),
node.type));
return clone;
}
public static List<LocalVariableNode> cloneLocals(Map<LabelNode, LabelNode> labelMap, List<LocalVariableNode> locals)
{
ArrayList<LocalVariableNode> clone = new ArrayList<LocalVariableNode>();
for(LocalVariableNode node : locals)
clone.add(new LocalVariableNode(
node.name, node.desc, node.signature,
labelMap.get(node.start),
labelMap.get(node.end),
node.index));
return clone;
}
public static void copy(MethodNode src, MethodNode dst)
{
Map<LabelNode, LabelNode> labelMap = cloneLabels(src.instructions);
dst.instructions = cloneInsnList(labelMap, src.instructions);
dst.tryCatchBlocks = cloneTryCatchBlocks(labelMap, src.tryCatchBlocks);
if(src.localVariables != null)
dst.localVariables = cloneLocals(labelMap, src.localVariables);
dst.visibleAnnotations = src.visibleAnnotations;
dst.invisibleAnnotations = src.invisibleAnnotations;
dst.visitMaxs(src.maxStack, src.maxLocals);
}
public static byte[] alterMethods(String name, byte[] bytes, HashMultimap<String, MethodAltercator> altercators)
{
if(altercators.containsKey(name))
{
ClassNode cnode = createClassNode(bytes);
for(MethodAltercator injector : altercators.get(name))
{
MethodNode method = findMethod(injector.method, cnode);
if(method == null)
throw new RuntimeException("Method not found: "+injector.method);
injector.alter(method);
}
bytes = createBytes(cnode, ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
}
return bytes;
}
public static String printInsnList(InsnListSection subsection)
{
InsnListPrinter p = new InsnListPrinter();
p.visitInsnList(subsection);
return p.textString();
}
public static int getLocal(List<LocalVariableNode> list, String name)
{
int found = -1;
for(LocalVariableNode node : list)
{
if(node.name.equals(name))
{
if(found >= 0)
throw new RuntimeException("Duplicate local variable: "+name+" not coded to handle this scenario.");
found = node.index;
}
}
return found;
}
public static void replaceMethodCode(MethodNode original, MethodNode replacement)
{
original.instructions.clear();
if(original.localVariables != null)
original.localVariables.clear();
if(original.tryCatchBlocks != null)
original.tryCatchBlocks.clear();
replacement.accept(original);
}
public static void removeBlock(InsnList insns, InsnListSection block)
{
AbstractInsnNode insn = block.first;
while(true)
{
AbstractInsnNode next = insn.getNext();
insns.remove(insn);
if(insn == block.last)
break;
insn = next;
}
}
}
+364
View File
@@ -0,0 +1,364 @@
package codechicken.lib.asm;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.IincInsnNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.IntInsnNode;
import org.objectweb.asm.tree.JumpInsnNode;
import org.objectweb.asm.tree.LabelNode;
import org.objectweb.asm.tree.LdcInsnNode;
import org.objectweb.asm.tree.LineNumberNode;
import org.objectweb.asm.tree.MultiANewArrayInsnNode;
import org.objectweb.asm.tree.VarInsnNode;
import com.google.common.collect.ImmutableMap;
import static org.objectweb.asm.Opcodes.*;
import static org.objectweb.asm.tree.AbstractInsnNode.*;
public class ASMReader
{
public static class ASMBlock
{
public InsnList insns = new InsnList();
private HashMap<String, LabelNode> labels = new HashMap<String, LabelNode>();
public LabelNode getOrAdd(String s)
{
LabelNode l = get(s);
if(l == null)
labels.put(s, l = new LabelNode());
return l;
}
public LabelNode get(String s)
{
return labels.get(s);
}
public void replace(String s, LabelNode l)
{
LabelNode old = get(s);
if(old != null)
{
Map<LabelNode, LabelNode> map = ImmutableMap.of(old, l);
for(AbstractInsnNode insn = insns.getFirst(); insn != null; insn = insn.getNext())
{
switch(insn.getType())
{
case JUMP_INSN:
case FRAME:
case LOOKUPSWITCH_INSN:
case TABLESWITCH_INSN:
case LABEL:
insns.insert(insn, insn.clone(map));
insns.remove(insn);
}
}
}
labels.put(s, l);
}
}
public static Map<String, Integer> opCodes = new HashMap<String, Integer>();
public static byte[] TYPE;
static
{
opCodes.put("NOP", NOP);
opCodes.put("ACONST_NULL", ACONST_NULL);
opCodes.put("ICONST_M1", ICONST_M1);
opCodes.put("ICONST_0", ICONST_0);
opCodes.put("ICONST_1", ICONST_1);
opCodes.put("ICONST_2", ICONST_2);
opCodes.put("ICONST_3", ICONST_3);
opCodes.put("ICONST_4", ICONST_4);
opCodes.put("ICONST_5", ICONST_5);
opCodes.put("LCONST_0", LCONST_0);
opCodes.put("LCONST_1", LCONST_1);
opCodes.put("FCONST_0", FCONST_0);
opCodes.put("FCONST_1", FCONST_1);
opCodes.put("FCONST_2", FCONST_2);
opCodes.put("DCONST_0", DCONST_0);
opCodes.put("DCONST_1", DCONST_1);
opCodes.put("BIPUSH", BIPUSH);
opCodes.put("SIPUSH", SIPUSH);
opCodes.put("LDC", LDC);
opCodes.put("ILOAD", ILOAD);
opCodes.put("LLOAD", LLOAD);
opCodes.put("FLOAD", FLOAD);
opCodes.put("DLOAD", DLOAD);
opCodes.put("ALOAD", ALOAD);
opCodes.put("IALOAD", IALOAD);
opCodes.put("LALOAD", LALOAD);
opCodes.put("FALOAD", FALOAD);
opCodes.put("DALOAD", DALOAD);
opCodes.put("AALOAD", AALOAD);
opCodes.put("BALOAD", BALOAD);
opCodes.put("CALOAD", CALOAD);
opCodes.put("SALOAD", SALOAD);
opCodes.put("ISTORE", ISTORE);
opCodes.put("LSTORE", LSTORE);
opCodes.put("FSTORE", FSTORE);
opCodes.put("DSTORE", DSTORE);
opCodes.put("ASTORE", ASTORE);
opCodes.put("IASTORE", IASTORE);
opCodes.put("LASTORE", LASTORE);
opCodes.put("FASTORE", FASTORE);
opCodes.put("DASTORE", DASTORE);
opCodes.put("AASTORE", AASTORE);
opCodes.put("BASTORE", BASTORE);
opCodes.put("CASTORE", CASTORE);
opCodes.put("SASTORE", SASTORE);
opCodes.put("POP", POP);
opCodes.put("POP2", POP2);
opCodes.put("DUP", DUP);
opCodes.put("DUP_X1", DUP_X1);
opCodes.put("DUP_X2", DUP_X2);
opCodes.put("DUP2", DUP2);
opCodes.put("DUP2_X1", DUP2_X1);
opCodes.put("DUP2_X2", DUP2_X2);
opCodes.put("SWAP", SWAP);
opCodes.put("IADD", IADD);
opCodes.put("LADD", LADD);
opCodes.put("FADD", FADD);
opCodes.put("DADD", DADD);
opCodes.put("ISUB", ISUB);
opCodes.put("LSUB", LSUB);
opCodes.put("FSUB", FSUB);
opCodes.put("DSUB", DSUB);
opCodes.put("IMUL", IMUL);
opCodes.put("LMUL", LMUL);
opCodes.put("FMUL", FMUL);
opCodes.put("DMUL", DMUL);
opCodes.put("IDIV", IDIV);
opCodes.put("LDIV", LDIV);
opCodes.put("FDIV", FDIV);
opCodes.put("DDIV", DDIV);
opCodes.put("IREM", IREM);
opCodes.put("LREM", LREM);
opCodes.put("FREM", FREM);
opCodes.put("DREM", DREM);
opCodes.put("INEG", INEG);
opCodes.put("LNEG", LNEG);
opCodes.put("FNEG", FNEG);
opCodes.put("DNEG", DNEG);
opCodes.put("ISHL", ISHL);
opCodes.put("LSHL", LSHL);
opCodes.put("ISHR", ISHR);
opCodes.put("LSHR", LSHR);
opCodes.put("IUSHR", IUSHR);
opCodes.put("LUSHR", LUSHR);
opCodes.put("IAND", IAND);
opCodes.put("LAND", LAND);
opCodes.put("IOR", IOR);
opCodes.put("LOR", LOR);
opCodes.put("IXOR", IXOR);
opCodes.put("LXOR", LXOR);
opCodes.put("IINC", IINC);
opCodes.put("I2L", I2L);
opCodes.put("I2F", I2F);
opCodes.put("I2D", I2D);
opCodes.put("L2I", L2I);
opCodes.put("L2F", L2F);
opCodes.put("L2D", L2D);
opCodes.put("F2I", F2I);
opCodes.put("F2L", F2L);
opCodes.put("F2D", F2D);
opCodes.put("D2I", D2I);
opCodes.put("D2L", D2L);
opCodes.put("D2F", D2F);
opCodes.put("I2B", I2B);
opCodes.put("I2C", I2C);
opCodes.put("I2S", I2S);
opCodes.put("LCMP", LCMP);
opCodes.put("FCMPL", FCMPL);
opCodes.put("FCMPG", FCMPG);
opCodes.put("DCMPL", DCMPL);
opCodes.put("DCMPG", DCMPG);
opCodes.put("IFEQ", IFEQ);
opCodes.put("IFNE", IFNE);
opCodes.put("IFLT", IFLT);
opCodes.put("IFGE", IFGE);
opCodes.put("IFGT", IFGT);
opCodes.put("IFLE", IFLE);
opCodes.put("IF_ICMPEQ", IF_ICMPEQ);
opCodes.put("IF_ICMPNE", IF_ICMPNE);
opCodes.put("IF_ICMPLT", IF_ICMPLT);
opCodes.put("IF_ICMPGE", IF_ICMPGE);
opCodes.put("IF_ICMPGT", IF_ICMPGT);
opCodes.put("IF_ICMPLE", IF_ICMPLE);
opCodes.put("IF_ACMPEQ", IF_ACMPEQ);
opCodes.put("IF_ACMPNE", IF_ACMPNE);
opCodes.put("GOTO", GOTO);
opCodes.put("JSR", JSR);
opCodes.put("RET", RET);
opCodes.put("TABLESWITCH", TABLESWITCH);
opCodes.put("LOOKUPSWITCH", LOOKUPSWITCH);
opCodes.put("IRETURN", IRETURN);
opCodes.put("LRETURN", LRETURN);
opCodes.put("FRETURN", FRETURN);
opCodes.put("DRETURN", DRETURN);
opCodes.put("ARETURN", ARETURN);
opCodes.put("RETURN", RETURN);
opCodes.put("GETSTATIC", GETSTATIC);
opCodes.put("PUTSTATIC", PUTSTATIC);
opCodes.put("GETFIELD", GETFIELD);
opCodes.put("PUTFIELD", PUTFIELD);
opCodes.put("INVOKEVIRTUAL", INVOKEVIRTUAL);
opCodes.put("INVOKESPECIAL", INVOKESPECIAL);
opCodes.put("INVOKESTATIC", INVOKESTATIC);
opCodes.put("INVOKEINTERFACE", INVOKEINTERFACE);
opCodes.put("INVOKEDYNAMIC", INVOKEDYNAMIC);
opCodes.put("NEW", NEW);
opCodes.put("NEWARRAY", NEWARRAY);
opCodes.put("ANEWARRAY", ANEWARRAY);
opCodes.put("ARRAYLENGTH", ARRAYLENGTH);
opCodes.put("ATHROW", ATHROW);
opCodes.put("CHECKCAST", CHECKCAST);
opCodes.put("INSTANCEOF", INSTANCEOF);
opCodes.put("MONITORENTER", MONITORENTER);
opCodes.put("MONITOREXIT", MONITOREXIT);
opCodes.put("MULTIANEWARRAY", MULTIANEWARRAY);
opCodes.put("IFNULL", IFNULL);
opCodes.put("IFNONNULL", IFNONNULL);
//derived from classWriter, mapped to AbstractInsnNode
TYPE = new byte[200];
String s = "AAAAAAAAAAAAAAAABBJ__CCCCC____________________AAAAAAAACC"
+ "CCC____________________AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+ "AAAAAAAAAAAAAAAAAKAAAAAAAAAAAAAAAAAAAAHHHHHHHHHHHHHHHHCLMAA"
+ "AAAAEEEEFFFFGDBDAADDAA_NHH";
for (int i = 0; i < s.length(); i++)
TYPE[i] = (byte) (s.charAt(i) - 'A');
}
public static Map<String, ASMBlock> loadResource(String res)
{
return loadResource(ASMHelper.class.getResourceAsStream(res), res);
}
public static Map<String, ASMBlock> loadResource(InputStream in, String res)
{
HashMap<String, ASMBlock> blocks = new HashMap<String, ASMBlock>();
String current = "unnamed";
ASMBlock block = new ASMBlock();
try
{
BufferedReader r = new BufferedReader(new InputStreamReader(in));
String line;
while((line = r.readLine()) != null)
{
{
int hpos = line.indexOf('#');
if(hpos >= 0) line = line.substring(0, hpos);
}
line = line.trim();
if(line.length() == 0) continue;
if(line.startsWith("list "))
{
if(block.insns.size() > 0) blocks.put(current, block);
current = line.substring(5);
block = new ASMBlock();
continue;
}
try
{
AbstractInsnNode insn = null;
String[] split = line.replace(" : ", ":").split(" ");
Integer i_opcode = opCodes.get(split[0]);
if(i_opcode == null)
{
if(split[0].equals("LINENUMBER"))
insn = new LineNumberNode(Integer.parseInt(split[1]), block.getOrAdd(split[2]));
else if(split[0].startsWith("L"))
insn = block.getOrAdd(split[0]);
else
throw new Exception("Unknown opcode " + split[0]);
}
else
{
int opcode = i_opcode;
switch(TYPE[opcode])
{
case INSN:
insn = new InsnNode(opcode);
break;
case INT_INSN:
insn = new IntInsnNode(opcode, Integer.parseInt(split[1]));
break;
case VAR_INSN:
insn = new VarInsnNode(opcode, Integer.parseInt(split[1]));
break;
case TYPE_INSN:
insn = new ObfMapping(split[1]).toInsn(opcode);
break;
case FIELD_INSN:
case METHOD_INSN:
insn = ObfMapping.fromDesc(split[1]).toInsn(opcode);
break;
case INVOKE_DYNAMIC_INSN:
throw new Exception("Found INVOKEDYNAMIC while reading");
case JUMP_INSN:
insn = new JumpInsnNode(opcode, block.getOrAdd(split[1]));
break;
case LDC_INSN:
String cst = split[1];
if(cst.contains(""))
insn = new LdcInsnNode(cst.substring(1, cst.length()-1));
else if(cst.endsWith("L"))
insn = new LdcInsnNode(Long.valueOf(cst.substring(0, cst.length()-1)));
else if(cst.endsWith("F"))
insn = new LdcInsnNode(Float.valueOf(cst.substring(0, cst.length()-1)));
else if(cst.endsWith("D"))
insn = new LdcInsnNode(Double.valueOf(cst.substring(0, cst.length()-1)));
else
insn = new LdcInsnNode(Integer.valueOf(cst));
break;
case IINC_INSN:
insn = new IincInsnNode(opcode, Integer.parseInt(split[1]));
break;
case LABEL:
throw new Exception("Use L# for labels");
case TABLESWITCH_INSN:
case LOOKUPSWITCH_INSN:
throw new Exception("I don't know how to deal with this insn type");
case MULTIANEWARRAY_INSN:
insn = new MultiANewArrayInsnNode(split[1], Integer.parseInt(split[2]));
break;
case FRAME:
throw new Exception("Use ClassWriter.COMPUTE_FRAMES");
}
}
if(insn != null)
block.insns.add(insn);
}
catch(Exception e)
{
System.err.println("Error while reading ASM Block "+
current+" from "+res+", line: "+line);
e.printStackTrace();
}
}
r.close();
if(block.insns.size() > 0) blocks.put(current, block);
}
catch(IOException e)
{
throw new RuntimeException("Failed to read ASM resource: "+res, e);
}
return blocks;
}
}
+29
View File
@@ -0,0 +1,29 @@
package codechicken.lib.asm;
import org.objectweb.asm.ClassWriter;
public class CC_ClassWriter extends ClassWriter
{
public CC_ClassWriter(int flags)
{
super(flags);
}
@Override
protected String getCommonSuperClass(String type1, String type2)
{
String c = type1.replace('/', '.');
String d = type2.replace('/', '.');
if(ClassHeirachyManager.classExtends(d, c))
return type1;
if(ClassHeirachyManager.classExtends(c, d))
return type2;
do
{
c = ClassHeirachyManager.getSuperClass(c);
}
while(!ClassHeirachyManager.classExtends(d, c));
return c.replace('.', '/');
}
}
@@ -0,0 +1,124 @@
package codechicken.lib.asm;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import org.objectweb.asm.tree.ClassNode;
import net.minecraft.launchwrapper.IClassTransformer;
import net.minecraft.launchwrapper.LaunchClassLoader;
/**
* This is added as a class transformer if CodeChickenCore is installed. Adding it as a class transformer will speed evaluation up slightly by automatically caching superclasses when they are first loaded.
*/
public class ClassHeirachyManager implements IClassTransformer
{
public static HashSet<String> knownClasses = new HashSet<String>();
public static HashMap<String, ArrayList<String>> superclasses = new HashMap<String, ArrayList<String>>();
private static LaunchClassLoader cl = (LaunchClassLoader)ClassHeirachyManager.class.getClassLoader();
/**
* Returns true if clazz extends, either directly or indirectly, superclass.
* @param clazz The class in question
* @param superclass The class being extended
* @param bytes The bytes for the clazz. Only needed if not already defined.
* @return
*/
public static boolean classExtends(String clazz, String superclass, byte[] bytes)
{
if(!knownClasses.contains(clazz))
new ClassHeirachyManager().transform(clazz, clazz, bytes);
return classExtends(clazz, superclass);
}
public static boolean classExtends(String clazz, String superclass)
{
if(clazz.equals(superclass))
return true;
if(clazz.equals("java.lang.Object"))
return false;
declareClass(clazz);
if(!superclasses.containsKey(clazz))//just can't handle this
return false;
for(String s : superclasses.get(clazz))
if(classExtends(s, superclass))
return true;
return false;
}
private static void declareClass(String clazz)
{
try
{
if(!knownClasses.contains(clazz))
{
try
{
byte[] bytes = cl.getClassBytes(clazz);
if(bytes != null)
new ClassHeirachyManager().transform(clazz, clazz, bytes);
}
catch(Exception e)
{
}
if(!knownClasses.contains(clazz))
{
Class<?> aclass = Class.forName(clazz);
knownClasses.add(clazz);
if(aclass.isInterface())
addSuperclass(clazz, "java.lang.Object");
else
addSuperclass(clazz, aclass.getSuperclass().getName());
for(Class<?> iclass : aclass.getInterfaces())
addSuperclass(clazz, iclass.getName());
}
}
}
catch(ClassNotFoundException e)
{
}
}
@Override
public byte[] transform(String name, String tname, byte[] bytes)
{
if (bytes == null) return null;
if(!knownClasses.contains(name))
{
ClassNode node = ASMHelper.createClassNode(bytes);
knownClasses.add(name);
addSuperclass(name, node.superName.replace('/', '.'));
for(String iclass : node.interfaces)
addSuperclass(name, iclass.replace('/', '.'));
}
return bytes;
}
private static void addSuperclass(String name, String superclass)
{
ArrayList<String> supers = superclasses.get(name);
if(supers == null)
superclasses.put(name, supers = new ArrayList<String>());
supers.add(superclass);
supers.add(new ObfMapping(superclass).toRuntime().javaClass());
}
public static String getSuperClass(String c)
{
declareClass(c);
if(!knownClasses.contains(c))
return "java.lang.Object";
return superclasses.get(c).get(0);
}
}
+214
View File
@@ -0,0 +1,214 @@
package codechicken.lib.asm;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import org.objectweb.asm.Label;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.FrameNode;
import org.objectweb.asm.tree.IincInsnNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.IntInsnNode;
import org.objectweb.asm.tree.InvokeDynamicInsnNode;
import org.objectweb.asm.tree.JumpInsnNode;
import org.objectweb.asm.tree.LabelNode;
import org.objectweb.asm.tree.LdcInsnNode;
import org.objectweb.asm.tree.LineNumberNode;
import org.objectweb.asm.tree.LookupSwitchInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MultiANewArrayInsnNode;
import org.objectweb.asm.tree.TableSwitchInsnNode;
import org.objectweb.asm.tree.TypeInsnNode;
import org.objectweb.asm.tree.VarInsnNode;
import org.objectweb.asm.util.Textifier;
import codechicken.lib.asm.InstructionComparator.InsnListSection;
public class InsnListPrinter extends Textifier
{
private boolean buildingLabelMap = false;
public void visitInsnList(InsnList list)
{
text.clear();
if(labelNames == null)
labelNames = new HashMap<Label, String>();
else
labelNames.clear();
buildingLabelMap = true;
for(AbstractInsnNode insn = list.getFirst(); insn != null; insn = insn.getNext())
if(insn.getType() == 8)
visitLabel(((LabelNode)insn).getLabel());
text.clear();
buildingLabelMap = false;
for(AbstractInsnNode insn = list.getFirst(); insn != null; insn = insn.getNext())
_visitInsn(insn);
}
public void visitInsnList(InsnListSection subsection)
{
text.clear();
if(labelNames == null)
labelNames = new HashMap<Label, String>();
else
labelNames.clear();
buildingLabelMap = true;
{
AbstractInsnNode insn = subsection.first;
while(true)
{
if(insn.getType() == 8)
visitLabel(((LabelNode)insn).getLabel());
if(insn == subsection.last)
break;
insn = insn.getNext();
}
}
text.clear();
buildingLabelMap = false;
{
AbstractInsnNode insn = subsection.first;
while(true)
{
_visitInsn(insn);
if(insn == subsection.last)
break;
insn = insn.getNext();
}
}
}
public void visitInsn(AbstractInsnNode insn)
{
text.clear();
if(labelNames == null)
labelNames = new HashMap<Label, String>();
else
labelNames.clear();
_visitInsn(insn);
}
private void _visitInsn(AbstractInsnNode insn)
{
switch(insn.getType())
{
case 0:
visitInsn(insn.getOpcode());
break;
case 1:
IntInsnNode iinsn = (IntInsnNode)insn;
visitIntInsn(iinsn.getOpcode(), iinsn.operand);
break;
case 2:
VarInsnNode vinsn = (VarInsnNode)insn;
visitVarInsn(vinsn.getOpcode(), vinsn.var);
break;
case 3:
TypeInsnNode tinsn = (TypeInsnNode)insn;
visitTypeInsn(tinsn.getOpcode(), tinsn.desc);
break;
case 4:
FieldInsnNode finsn = (FieldInsnNode)insn;
visitFieldInsn(finsn.getOpcode(), finsn.owner, finsn.name, finsn.desc);
break;
case 5:
MethodInsnNode minsn = (MethodInsnNode)insn;
visitMethodInsn(minsn.getOpcode(), minsn.owner, minsn.name, minsn.desc);
break;
case 6:
InvokeDynamicInsnNode idinsn = (InvokeDynamicInsnNode)insn;
visitInvokeDynamicInsn(idinsn.name, idinsn.desc, idinsn.bsm, idinsn.bsmArgs);
break;
case 7:
JumpInsnNode jinsn = (JumpInsnNode)insn;
visitJumpInsn(jinsn.getOpcode(), jinsn.label.getLabel());
break;
case 8:
LabelNode linsn = (LabelNode)insn;
visitLabel(linsn.getLabel());
break;
case 9:
LdcInsnNode ldcinsn = (LdcInsnNode)insn;
visitLdcInsn(ldcinsn.cst);
break;
case 10:
IincInsnNode iiinsn = (IincInsnNode)insn;
visitIincInsn(iiinsn.var, iiinsn.incr);
break;
case 11:
TableSwitchInsnNode tsinsn = (TableSwitchInsnNode)insn;
Label[] tslables = new Label[tsinsn.labels.size()];
for(int i = 0; i < tslables.length; i++)
tslables[i] = tsinsn.labels.get(i).getLabel();
visitTableSwitchInsn(tsinsn.min, tsinsn.max, tsinsn.dflt.getLabel(), tslables);
break;
case 12:
LookupSwitchInsnNode lsinsn = (LookupSwitchInsnNode)insn;
Label[] lslables = new Label[lsinsn.labels.size()];
for(int i = 0; i < lslables.length; i++)
lslables[i] = lsinsn.labels.get(i).getLabel();
int[] lskeys = new int[lsinsn.keys.size()];
for(int i = 0; i < lskeys.length; i++)
lskeys[i] = lsinsn.keys.get(i);
visitLookupSwitchInsn(lsinsn.dflt.getLabel(), lskeys, lslables);
break;
case 13:
MultiANewArrayInsnNode ainsn = (MultiANewArrayInsnNode)insn;
visitMultiANewArrayInsn(ainsn.desc, ainsn.dims);
break;
case 14:
FrameNode fnode = (FrameNode)insn;
switch(fnode.type)
{
case -1:
case 0:
visitFrame(fnode.type, fnode.local.size(), fnode.local.toArray(), fnode.stack.size(), fnode.stack.toArray());
break;
case 1:
visitFrame(fnode.type, fnode.local.size(), fnode.local.toArray(), 0, null);
break;
case 2:
visitFrame(fnode.type, fnode.local.size(), null, 0, null);
break;
case 3:
visitFrame(fnode.type, 0, null, 0, null);
break;
case 4:
visitFrame(fnode.type, 0, null, 1, fnode.stack.toArray());
}
break;
case 15:
LineNumberNode lnode = (LineNumberNode)insn;
visitLineNumber(lnode.line, lnode.start.getLabel());
break;
}
}
@Override
public void visitLabel(Label label)
{
if(!buildingLabelMap && !labelNames.containsKey(label))
{
labelNames.put(label, "LEXT"+labelNames.size());
}
super.visitLabel(label);
}
public String textString()
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
print(pw);
pw.flush();
return sw.toString();
}
}
@@ -0,0 +1,254 @@
package codechicken.lib.asm;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.IincInsnNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.IntInsnNode;
import org.objectweb.asm.tree.JumpInsnNode;
import org.objectweb.asm.tree.LabelNode;
import org.objectweb.asm.tree.LdcInsnNode;
import org.objectweb.asm.tree.LineNumberNode;
import org.objectweb.asm.tree.LookupSwitchInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.TableSwitchInsnNode;
import org.objectweb.asm.tree.TypeInsnNode;
import org.objectweb.asm.tree.VarInsnNode;
import static org.objectweb.asm.tree.AbstractInsnNode.*;
import codechicken.lib.asm.ObfMapping;
public class InstructionComparator
{
public static class InsnListSection
{
public InsnListSection(AbstractInsnNode first, AbstractInsnNode last)
{
this.first = first;
this.last = last;
}
public InsnListSection(InsnList haystack, int start, int end)
{
this(haystack.get(start), haystack.get(end));
}
public AbstractInsnNode first;
public AbstractInsnNode last;
}
public static boolean varInsnEqual(VarInsnNode insn1, VarInsnNode insn2)
{
if(insn1.var == -1 || insn2.var == -1)
return true;
return insn1.var == insn2.var;
}
public static boolean methodInsnEqual(AbstractInsnNode absnode, int Opcode, ObfMapping method)
{
if(!(absnode instanceof MethodInsnNode) || absnode.getOpcode() != Opcode)
return false;
return method.matches((MethodInsnNode)absnode);
}
public static boolean methodInsnEqual(MethodInsnNode insn1, MethodInsnNode insn2)
{
return insn1.owner.equals(insn2.owner) && insn1.name.equals(insn2.name) && insn1.desc.equals(insn2.desc);
}
public static boolean fieldInsnEqual(FieldInsnNode insn1, FieldInsnNode insn2)
{
return insn1.owner.equals(insn2.owner) && insn1.name.equals(insn2.name) && insn1.desc.equals(insn2.desc);
}
public static boolean ldcInsnEqual(LdcInsnNode insn1, LdcInsnNode insn2)
{
if(insn1.cst.equals("~") || insn2.cst.equals("~"))
return true;
return insn1.cst.equals(insn2.cst);
}
public static boolean typeInsnEqual(TypeInsnNode insn1, TypeInsnNode insn2)
{
if(insn1.desc.equals("~") || insn2.desc.equals("~"))
return true;
return insn1.desc.equals(insn2.desc);
}
public static boolean iincInsnEqual(IincInsnNode node1, IincInsnNode node2)
{
return node1.var == node2.var && node1.incr == node2.incr;
}
public static boolean intInsnEqual(IntInsnNode node1, IntInsnNode node2)
{
if(node1.operand == -1 || node2.operand == -1)
return true;
return node1.operand == node2.operand;
}
public static boolean insnEqual(AbstractInsnNode node1, AbstractInsnNode node2)
{
if(node1.getOpcode() != node2.getOpcode())
return false;
switch(node2.getType())
{
case VAR_INSN:
return varInsnEqual((VarInsnNode) node1, (VarInsnNode) node2);
case TYPE_INSN:
return typeInsnEqual((TypeInsnNode) node1, (TypeInsnNode) node2);
case FIELD_INSN:
return fieldInsnEqual((FieldInsnNode) node1, (FieldInsnNode) node2);
case METHOD_INSN:
return methodInsnEqual((MethodInsnNode) node1, (MethodInsnNode) node2);
case LDC_INSN:
return ldcInsnEqual((LdcInsnNode) node1, (LdcInsnNode) node2);
case IINC_INSN:
return iincInsnEqual((IincInsnNode) node1, (IincInsnNode) node2);
case INT_INSN:
return intInsnEqual((IntInsnNode)node1, (IntInsnNode)node2);
default:
return true;
}
}
public static InsnList getImportantList(InsnList list)
{
if(list.size() == 0)
return list;
HashMap<LabelNode, LabelNode> labels = new HashMap<LabelNode, LabelNode>();
for(AbstractInsnNode insn = list.getFirst(); insn != null; insn = insn.getNext())
{
if(insn instanceof LabelNode)
labels.put((LabelNode)insn, (LabelNode)insn);
}
InsnList importantNodeList = new InsnList();
for(AbstractInsnNode insn = list.getFirst(); insn != null; insn = insn.getNext())
{
if(insn instanceof LabelNode || insn instanceof LineNumberNode)
continue;
importantNodeList.add(insn.clone(labels));
}
return importantNodeList;
}
public static boolean insnListMatches(InsnList haystack, InsnList needle, int start)
{
if(haystack.size()-start < needle.size())
return false;
for(int i = 0; i < needle.size(); i++)
{
if(!insnEqual(haystack.get(i+start), needle.get(i)))
return false;
}
return true;
}
public static List<Integer> insnListFind(InsnList haystack, InsnList needle)
{
LinkedList<Integer> list = new LinkedList<Integer>();
for(int start = 0; start <= haystack.size()-needle.size(); start++)
if(insnListMatches(haystack, needle, start))
list.add(start);
return list;
}
public static List<AbstractInsnNode> insnListFindStart(InsnList haystack, InsnList needle)
{
LinkedList<AbstractInsnNode> callNodes = new LinkedList<AbstractInsnNode>();
for(int callPoint : insnListFind(haystack, needle))
callNodes.add(haystack.get(callPoint));
return callNodes;
}
public static List<AbstractInsnNode> insnListFindEnd(InsnList haystack, InsnList needle)
{
LinkedList<AbstractInsnNode> callNodes = new LinkedList<AbstractInsnNode>();
for(int callPoint : insnListFind(haystack, needle))
callNodes.add(haystack.get(callPoint+needle.size()-1));
return callNodes;
}
public static List<InsnListSection> insnListFindL(InsnList haystack, InsnList needle)
{
HashSet<LabelNode> controlFlowLabels = new HashSet<LabelNode>();
for(AbstractInsnNode insn = haystack.getFirst(); insn != null; insn = insn.getNext())
{
switch(insn.getType())
{
case 8:
case 15:
break;
case 7:
JumpInsnNode jinsn = (JumpInsnNode)insn;
controlFlowLabels.add(jinsn.label);
break;
case 11:
TableSwitchInsnNode tsinsn = (TableSwitchInsnNode)insn;
for(LabelNode label : tsinsn.labels)
controlFlowLabels.add(label);
break;
case 12:
LookupSwitchInsnNode lsinsn = (LookupSwitchInsnNode)insn;
for(LabelNode label : lsinsn.labels)
controlFlowLabels.add(label);
break;
}
}
LinkedList<InsnListSection> list = new LinkedList<InsnListSection>();
nextsection: for(int start = 0; start <= haystack.size()-needle.size(); start++)
{
InsnListSection section = insnListMatchesL(haystack, needle, start, controlFlowLabels);
if(section != null)
{
for(InsnListSection asection : list)
if(asection.last == section.last)
continue nextsection;
list.add(section);
}
}
return list;
}
private static InsnListSection insnListMatchesL(InsnList haystack, InsnList needle, int start, HashSet<LabelNode> controlFlowLabels)
{
int h = start, n = 0;
for(;h < haystack.size() && n < needle.size(); h++)
{
AbstractInsnNode insn = haystack.get(h);
if(insn.getType() == 15)
continue;
if(insn.getType() == 8 && !controlFlowLabels.contains(insn))
continue;
if(!insnEqual(haystack.get(h), needle.get(n)))
return null;
n++;
}
if(n != needle.size())
return null;
return new InsnListSection(haystack, start, h-1);
}
}
+225
View File
@@ -0,0 +1,225 @@
package codechicken.lib.asm;
import java.io.IOException;
import net.minecraft.launchwrapper.LaunchClassLoader;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.commons.Remapper;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.TypeInsnNode;
import com.google.common.base.Objects;
import cpw.mods.fml.common.asm.transformers.deobf.FMLDeobfuscatingRemapper;
public class ObfMapping
{
/**
* CCC will deal with this.
*/
public static Remapper runtimeMapper = FMLDeobfuscatingRemapper.INSTANCE;
public static Remapper mcpMapper = null;
public static final boolean obfuscated;
static
{
boolean obf = true;
try
{
obf = ((LaunchClassLoader)ObfMapping.class.getClassLoader()).getClassBytes("net.minecraft.world.World") == null;
}
catch(IOException iox) {}
obfuscated = obf;
}
public String s_owner;
public String s_name;
public String s_desc;
public boolean runtime;
public ObfMapping(String owner)
{
this(owner, null, null);
}
public ObfMapping(String owner, String name, String desc)
{
this.s_owner = owner;
this.s_name = name;
this.s_desc = desc;
if(s_owner.contains("."))
throw new IllegalArgumentException(s_owner);
if(mcpMapper != null)
map(mcpMapper);
}
public ObfMapping(ObfMapping descmap, String subclass)
{
this(subclass, descmap.s_name, descmap.s_desc);
}
public static ObfMapping fromDesc(String s)
{
int lastDot = s.lastIndexOf('.');
if(lastDot < 0)
return new ObfMapping(s, "", "");
int sep = s.indexOf('(');//methods
int sep_end = sep;
if(sep < 0) {
sep = s.indexOf(' ');//some stuffs
sep_end = sep+1;
}
if(sep < 0) {
sep = s.indexOf(':');//fields
sep_end = sep+1;
}
if(sep < 0)
return new ObfMapping(s.substring(0, lastDot), s.substring(lastDot + 1), "");
return new ObfMapping(s.substring(0, lastDot), s.substring(lastDot+1, sep), s.substring(sep_end));
}
public ObfMapping subclass(String subclass)
{
return new ObfMapping(this, subclass);
}
public boolean matches(MethodNode node)
{
return s_name.equals(node.name) && s_desc.equals(node.desc);
}
public boolean matches(MethodInsnNode node)
{
return s_owner.equals(node.owner) && s_name.equals(node.name) && s_desc.equals(node.desc);
}
public AbstractInsnNode toInsn(int opcode)
{
if(isClass())
return new TypeInsnNode(opcode, s_owner);
else if(isMethod())
return new MethodInsnNode(opcode, s_owner, s_name, s_desc);
else
return new FieldInsnNode(opcode, s_owner, s_name, s_desc);
}
public void visitTypeInsn(MethodVisitor mv, int opcode)
{
mv.visitTypeInsn(opcode, s_owner);
}
public void visitMethodInsn(MethodVisitor mv, int opcode)
{
mv.visitMethodInsn(opcode, s_owner, s_name, s_desc);
}
public void visitFieldInsn(MethodVisitor mv, int opcode)
{
mv.visitFieldInsn(opcode, s_owner, s_name, s_desc);
}
public boolean isClass(String name)
{
return name.replace('.', '/').equals(s_owner);
}
public boolean matches(String name, String desc)
{
return s_name.equals(name) && s_desc.equals(desc);
}
public boolean matches(FieldNode node)
{
return s_name.equals(node.name) && s_desc.equals(node.desc);
}
public boolean matches(FieldInsnNode node)
{
return s_owner.equals(node.owner) && s_name.equals(node.name) && s_desc.equals(node.desc);
}
public String javaClass()
{
return s_owner.replace('/', '.');
}
@Override
public boolean equals(Object obj)
{
if(!(obj instanceof ObfMapping))
return false;
ObfMapping desc = (ObfMapping)obj;
return s_owner.equals(desc.s_owner) && s_name.equals(desc.s_name) && s_desc.equals(desc.s_desc);
}
@Override
public int hashCode()
{
return Objects.hashCode(s_desc, s_name, s_owner);
}
@Override
public String toString()
{
if(s_name.length() == 0)
return "["+s_owner+"]";
if(s_desc.length() == 0)
return "["+s_owner+"."+s_name+"]";
return "["+s_owner+"."+s_name+s_desc+"]";
}
public boolean isClass()
{
return s_name.length() == 0;
}
public boolean isMethod()
{
return s_desc.contains("(");
}
public boolean isField()
{
return !isClass() && !isMethod();
}
public ObfMapping map(Remapper mapper)
{
if(isMethod())
s_name = mapper.mapMethodName(s_owner, s_name, s_desc);
else if(isField())
s_name = mapper.mapFieldName(s_owner, s_name, s_desc);
s_owner = mapper.mapType(s_owner);
if(!isClass())
s_desc = mapper.mapDesc(s_desc);
return this;
}
public ObfMapping toRuntime()
{
if(!runtime)
map(runtimeMapper);
runtime = true;
return this;
}
public ObfMapping copy()
{
return new ObfMapping(s_owner, s_name, s_desc);
}
}