List of usage examples for org.objectweb.asm.tree ClassNode ClassNode
public ClassNode()
From source file:ivorius.ivtoolkit.asm.IvClassTransformer.java
License:Apache License
public byte[] transform(String actualClassName, String srgClassName, byte[] data, boolean obf) { ClassNode classNode = null;/* w w w . ja va 2 s . c o m*/ boolean didChange = false; try { classNode = new ClassNode(); ClassReader classReader = new ClassReader(data); classReader.accept(classNode, 0); } catch (Exception ex) { logger.error("Error patching class PRE " + actualClassName + " (" + srgClassName + ")!", ex); return data; } try { didChange = transform(actualClassName.replaceAll("\\.", "/"), classNode, obf); } catch (Exception ex) { logger.error("Error patching class MAIN " + actualClassName + " (" + srgClassName + ")!", ex); return data; } if (didChange) { try { ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); // ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); // Compute Frames can crash sometimes... classNode.accept(writer); return writer.toByteArray(); } catch (Exception ex) { logger.error("Error patching class POST " + actualClassName + " (" + srgClassName + ")!", ex); return data; } } return data; }
From source file:jar2xml.JavaArchive.java
License:Open Source License
void getPackages(HashMap<String, JavaPackage> packages, JarFile file) { Enumeration<JarEntry> entries = file.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String name = entry.getName(); if (name.endsWith(".class")) { name = name.substring(0, name.length() - 6); try { InputStream stream = file.getInputStream(entry); ClassReader reader = new ClassReader(stream); ClassNode node = new ClassNode(); reader.accept(node, 0);//from www . j av a 2 s. c om JavaClass.asmClasses.put(node.name, node); Class c = loader.loadClass(name.replace('/', '.')); //String pkgname = c.getPackage ().getName (); String pkgname = name.substring(0, name.lastIndexOf('/')).replace('/', '.'); JavaPackage pkg = packages.get(pkgname); if (pkg == null) { pkg = new JavaPackage(pkgname); packages.put(pkgname, pkg); } pkg.addClass(new JavaClass(c, node)); } catch (Throwable t) { t.printStackTrace(); System.err.println("warning J2X9001: Couldn't load class " + name + " : " + t); } } } }
From source file:jaspex.speculation.SpeculativeTransformer.java
License:Open Source License
public byte[] insertSpeculationCode(final ClassReader cr) { ClassVisitor cv;/* ww w . j ava2 s . com*/ // 1 Pass: Fazer tentativamente modificaes para especulao, concretizar todos os Futures, // e guardar o resultado num ClassNode ClassNode firstPassNode = new ClassNode(); cv = firstPassNode; // Colocao das chamadas ao get do future cv = new GenericMethodVisitorAdapter(cv, DelayGetFutureMethodVisitor.class, currentClass); // Modificaes para chamar o spawnSpeculation cv = new GenericMethodVisitorAdapter(cv, InsertContinuationSpeculationMethodVisitor.class, currentClass); cr.accept(cv, ClassReader.EXPAND_FRAMES); // 1.5 Pass: Detectar overspeculation -- casos onde a distncia entre a especulao e a sua // concretizao demasiado pequena Map<InfoMethod, UtilList<Integer>> rejectedSpecIdsMap = new HashMap<InfoMethod, UtilList<Integer>>(); RemoveOverspeculation.scanOverspeculation(currentClass, firstPassNode, rejectedSpecIdsMap); ClassNode removeOverspecNode; ClassReader finalPassReader; // Nota: Originalmente no era efectuado um loop aqui. O loop feito porque o // RemoveOverspeculation que executado depois do FixFutureMultipleControlFlows pode // detectar casos adicionais de overspeculation, e portanto temos que repetir o processo // para os excluir. // Alm disso, o processo pode demorar vrias iteraes a convergir, como no caso do // NewSpecExample72.test17() em que na primeira iterao detectada overspeculation num // dos casos, o cdigo re-gerado sem essa especulao, e s no final da segunda // iterao que detectado que os restantes casos tambm so overspeculation // (e portanto feita uma terceira iterao que ser a final, naquele caso). // Finalmente, de notar que o RemoveOverspeculation opcional, ou seja o ciclo at pode // ser comentado, voltando verso anterior em que o cdigo s fazia uma iterao. do { // 2 Pass: Repetir modificaes, tomando em conta os resultados do RemoveOverspeculation ClassNode secondPassNode = new ClassNode(); cv = secondPassNode; // Adicionar NOPs antes de todas as Labels, para facilitar o trabalho do FixFutureMultipleControlFlows cv = new GenericMethodVisitorAdapter(cv, NopAddBeforeLabelMethodVisitor.class); // Modificaes para chamar o spawnSpeculation cv = new GenericMethodVisitorAdapter(cv, InsertContinuationSpeculationMethodVisitor.class, currentClass, rejectedSpecIdsMap); cr.accept(cv, ClassReader.EXPAND_FRAMES); // 3 Pass: Deteco e resoluo de problemas devido a Futures e mltiplos fluxos de controlo // e gerao de lista de frames do mtodo a usar no DelayGetFutureMethodVisitor // Obter verso original dos mtodos antes das alteraes para especulao, para que o // computeControlFlowGraph possa fazer revert caso no consiga corrigi-los ClassNode origMethods = new ClassNode(); cr.accept(origMethods, ClassReader.EXPAND_FRAMES); FixFutureMultipleControlFlows.computeControlFlowGraph(secondPassNode, origMethods); // 4 Pass: Gerar classe final, limpar metadados extra ClassWriter cw = new jaspex.util.ClassWriter(ClassWriter.COMPUTE_FRAMES); cv = cw; // Remover NOPs de novo cv = new GenericMethodVisitorAdapter(cv, NopRemoveMethodVisitor.class); // Colocao das chamadas ao get do future cv = new GenericMethodVisitorAdapter(cv, DelayGetFutureMethodVisitor.class, currentClass); // Gerar classe a partir do ClassNode secondPassNode.accept(cv); finalPassReader = new ClassReader(cw.toByteArray()); // 4.5 Pass: Re-executar RemoveOverspeculation. Isto pode originar resultados diferentes do // pass original porque esse executado sem frames correctas e sem o // FixFutureMultipleControlFlows (ver comentrio antes do ciclo acima) removeOverspecNode = new ClassNode(); finalPassReader.accept(removeOverspecNode, 0); } while (RemoveOverspeculation.scanOverspeculation(currentClass, removeOverspecNode, rejectedSpecIdsMap)); // 5 Pass: Hack: Se houverem labels diferentes mas que esto seguidas (como no NewSpecExample8), // o RemoveUnusedTryCatchBlockMethodVisitor no funciona correctamente. Uma nova passagem // por um ClassWriter elimina labels repetidas. // A alternativa a fazer esta passagem seria criar um MethodVisitor que removesse labels // repetidas. ClassWriter cw = new jaspex.util.ClassWriter(ClassWriter.COMPUTE_FRAMES); cv = cw; // Retirar informao extra que passada dentro do tipo dos futures cv = new GenericMethodVisitorAdapter(cv, CleanupFutureTypeInfoMethodVisitor.class); // Remover marcadores de inlining da transactificao cv = new GenericMethodVisitorAdapter(cv, RemoveInlineMarkerMethodVisitor.class); // Remover entradas na exception table no usadas cv = new GenericMethodVisitorAdapter(cv, RemoveUnusedTryCatchBlockMethodVisitor.class); // (Potencialmente) corrigir problemas com blocos try/catch vazios (BUG/LIMITAO ASM) cv = new GenericMethodVisitorAdapter(cv, FixDeadTryCatchBlockMethodVisitor.class); finalPassReader.accept(cv, 0); return cw.toByteArray(); }
From source file:jaspex.transactifier.ChangeClinitMethodVisitor.java
License:Open Source License
private static boolean clinitIsSafe(Type t) { try {/*from w w w .j a v a 2s . c o m*/ ClassReader cr = new ClassReader(t.commonName()); ClassNode cNode = new ClassNode(); cr.accept(cNode, 0); for (MethodNode method : cNode.methods) { if (!method.name.equals("<clinit>")) continue; // Examinar instruces Iterator<AbstractInsnNode> it = method.instructions.iterator(); while (it.hasNext()) { AbstractInsnNode insn = it.next(); switch (insn.getType()) { case AbstractInsnNode.FRAME: case AbstractInsnNode.INT_INSN: case AbstractInsnNode.JUMP_INSN: case AbstractInsnNode.LABEL: case AbstractInsnNode.LDC_INSN: case AbstractInsnNode.LINE: case AbstractInsnNode.LOOKUPSWITCH_INSN: case AbstractInsnNode.MULTIANEWARRAY_INSN: case AbstractInsnNode.TABLESWITCH_INSN: case AbstractInsnNode.TYPE_INSN: case AbstractInsnNode.VAR_INSN: break; case AbstractInsnNode.FIELD_INSN: FieldInsnNode fieldInsn = (FieldInsnNode) insn; if (fieldInsn.getOpcode() != PUTSTATIC) { // GETSTATIC, GETFIELD, PUTFIELD return false; } break; case AbstractInsnNode.IINC_INSN: return false; case AbstractInsnNode.INSN: if (unsafeInsnBytecodes.contains(insn.getOpcode())) { Log.debug(t.commonName() + ".<clinit>() is unsafe " + "because of bytecode " + insn.getOpcode()); return false; } break; case AbstractInsnNode.METHOD_INSN: MethodInsnNode methodInsn = (MethodInsnNode) insn; if (!ClassFilter.isMethodWhitelisted(Type.fromAsm(methodInsn.owner), methodInsn.name, methodInsn.desc)) { Log.debug(t.commonName() + ".<clinit>() is unsafe " + "because it invokes " + Type.fromAsm(methodInsn.owner).commonName() + "." + methodInsn.name); return false; } break; default: throw new Error("Unexpected bytecode " + insn); } } //Log.debug(t.commonName() + ".<clinit>() for " + t + " is safe"); return true; } return false; } catch (IOException e) { throw new Error(e); } }
From source file:me.qmx.jitescript.JiteClass.java
License:Apache License
/** * Convert this class representation to JDK bytecode * * @param version the desired JDK version * @return the bytecode representation of this class *///from w ww . j ava 2 s . co m public byte[] toBytes(JDKVersion version) { ClassNode node = new ClassNode(); node.version = version.getVer(); node.access = this.access | ACC_SUPER; node.name = this.className; node.superName = this.superClassName; node.sourceFile = this.sourceFile; node.sourceDebug = this.sourceDebug; if (parentClassName != null) { node.visitOuterClass(parentClassName, null, null); } for (ChildEntry child : childClasses) { node.visitInnerClass(child.getClassName(), className, child.getInnerName(), child.getAccess()); } if (!this.interfaces.isEmpty()) { node.interfaces.addAll(this.interfaces); } for (MethodDefinition def : methods) { node.methods.add(def.getMethodNode()); } for (FieldDefinition def : fields) { node.fields.add(def.getFieldNode()); } if (node.visibleAnnotations == null) { node.visibleAnnotations = new ArrayList<AnnotationNode>(); } for (VisibleAnnotation a : annotations) { node.visibleAnnotations.add(a.getNode()); } ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); node.accept(cw); return cw.toByteArray(); }
From source file:naftoreiclag.dontdigleft.transformer.ResizePlayerBoudingBox.java
License:Open Source License
@Override public byte[] transform(String name, String transformedName, byte[] basicClass) { if (name.equals("net.minecraft.entity.player.EntityPlayer") || name.equals("xl")) { ClassNode classNode = new ClassNode(); ClassReader classReader = new ClassReader(basicClass); classReader.accept(classNode, 0); MethodNode mv = new MethodNode(ASM4, ACC_PROTECTED, "setSize", "(FF)V", null, null); mv.visitCode();/*from w w w . j a v a 2 s . c o m*/ Label l0 = new Label(); mv.visitLabel(l0); mv.visitVarInsn(FLOAD, 1); mv.visitLdcInsn(new Float("0.6")); mv.visitInsn(FCMPL); Label l1 = new Label(); mv.visitJumpInsn(IFNE, l1); mv.visitVarInsn(FLOAD, 2); mv.visitLdcInsn(new Float("1.8")); mv.visitInsn(FCMPL); mv.visitJumpInsn(IFNE, l1); Label l2 = new Label(); mv.visitLabel(l2); mv.visitLdcInsn(new Float("0.6")); mv.visitVarInsn(FSTORE, 1); Label l3 = new Label(); mv.visitLabel(l3); mv.visitLdcInsn(new Float("0.6")); mv.visitVarInsn(FSTORE, 2); mv.visitLabel(l1); mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(FLOAD, 1); mv.visitVarInsn(FLOAD, 2); mv.visitMethodInsn(INVOKESPECIAL, "net/minecraft/entity/Entity", "setSize", "(FF)V"); Label l4 = new Label(); mv.visitLabel(l4); mv.visitInsn(RETURN); Label l5 = new Label(); mv.visitLabel(l5); mv.visitLocalVariable("this", "Lnet/minecraft/entity/player/EntityPlayer;", null, l0, l5, 0); mv.visitLocalVariable("par1", "F", null, l0, l5, 1); mv.visitLocalVariable("par2", "F", null, l0, l5, 2); mv.visitMaxs(3, 3); mv.visitEnd(); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); classNode.accept(cw); mv.accept(cw); return cw.toByteArray(); } else { return basicClass; } }
From source file:nallar.tickthreading.patcher.remapping.Deobfuscator.java
License:Open Source License
private String getFieldType(String owner, String name) { if (fieldDescriptions.containsKey(owner)) { return fieldDescriptions.get(owner).get(name); }//from w w w . j av a 2 s. co m synchronized (fieldDescriptions) { byte[] classBytes = getClassBytes(owner); if (classBytes == null) { return null; } ClassReader cr = new ClassReader(classBytes); ClassNode classNode = new ClassNode(); cr.accept(classNode, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); Map<String, String> resMap = Maps.newHashMap(); for (FieldNode fieldNode : classNode.fields) { resMap.put(fieldNode.name, fieldNode.desc); } fieldDescriptions.put(owner, resMap); return resMap.get(name); } }
From source file:name.martingeisse.minimal.simulation.MCodeMain.java
License:Open Source License
/** * The main method.//from w ww . ja v a 2s.c om * @param args command-line arguments * @throws Exception ... */ public static void main(final String[] args) throws Exception { // compile ImmutableList<MCodeEntry> code = null; { final ClassNode node = new ClassNode(); new ClassReader(Experiment1.class.getName()).accept(node, Opcodes.ASM5); for (final Object untypedMethodNode : node.methods) { final MethodNode methodNode = (MethodNode) untypedMethodNode; if (methodNode.name.equals("main")) { final Compiler compiler = new Compiler(); code = compiler.compile(methodNode); break; } } if (code == null) { throw new RuntimeException("could not find main method to compile"); } } // run final LwjglWindow window = new LwjglWindow(800, 600); final Subject subject = new FullySimulatedSubject(window); final DirectMCodeEngine engine = new DirectMCodeEngine(ImmutableList.copyOf(code), new SubjectNativeCallHandler(subject)); engine.run(); }
From source file:net.afterchat.mocap.MocapClassTransformer.java
License:Open Source License
public byte[] patchClassASM(String name, byte[] bytes) { ClassNode classNode = new ClassNode(); ClassReader classReader = new ClassReader(bytes); classReader.accept(classNode, 0);/*www.j a v a 2 s . c o m*/ Iterator<MethodNode> methods = classNode.methods.iterator(); while (methods.hasNext()) { MethodNode m = methods.next(); if ((m.name.equals("onBlockPlacedBy")) || (m.name.equals("a") && m.desc.equals("(Lahb;IIILsv;Ladd;)V"))) { logger.info("** MOCAP - Patching onBlockPlacedBy: " + m.name); AbstractInsnNode currentNode = null; Iterator<AbstractInsnNode> iter = m.instructions.iterator(); int index = -1; while (iter.hasNext()) { index++; currentNode = iter.next(); /** * Just prior to the original empty function return, inject code to trigger * our custom block place event. */ if (currentNode.getOpcode() == RETURN) { InsnList toInject = new InsnList(); toInject.add(new TypeInsnNode(NEW, "net/afterchat/mocap/LivingPlaceBlockEvent")); toInject.add(new InsnNode(DUP)); toInject.add(new VarInsnNode(ALOAD, 5)); toInject.add(new VarInsnNode(ALOAD, 6)); toInject.add(new VarInsnNode(ILOAD, 2)); toInject.add(new VarInsnNode(ILOAD, 3)); toInject.add(new VarInsnNode(ILOAD, 4)); toInject.add(new MethodInsnNode(INVOKESPECIAL, "net/afterchat/mocap/LivingPlaceBlockEvent", "<init>", "(Lnet/minecraft/entity/EntityLivingBase;Lnet/minecraft/item/ItemStack;III)V")); toInject.add(new VarInsnNode(ASTORE, 7)); toInject.add(new FieldInsnNode(GETSTATIC, "net/minecraftforge/common/MinecraftForge", "EVENT_BUS", "Lcpw/mods/fml/common/eventhandler/EventBus;")); toInject.add(new VarInsnNode(ALOAD, 7)); toInject.add(new MethodInsnNode(INVOKEVIRTUAL, "cpw/mods/fml/common/eventhandler/EventBus", "post", "(Lcpw/mods/fml/common/eventhandler/Event;)Z")); toInject.add(new InsnNode(POP)); m.instructions.insertBefore(currentNode, toInject); } } } } ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); classNode.accept(writer); return writer.toByteArray(); }
From source file:net.cazzar.corelib.asm.BasicTransformer.java
License:Open Source License
@Override public final byte[] transform(String name, String transformedName, byte[] bytes) { if (!classes.contains(transformedName)) { return bytes; }//from ww w . j ava 2 s.com logger.info("Inserting hooks into {} ({}) for {}", name, transformedName, this.getClass().getCanonicalName()); ClassNode classNode = new ClassNode(); ClassReader classReader = new ClassReader(bytes); classReader.accept(classNode, 0); transform(classNode, transformedName); ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); classNode.accept(writer); // CheckClassAdapter.verify(new ClassReader(writer.toByteArray()), false, new PrintWriter(System.err)); return writer.toByteArray(); }