List of usage examples for org.objectweb.asm ClassVisitor ClassVisitor
public ClassVisitor(final int api, final ClassVisitor classVisitor)
From source file:co.cask.cdap.internal.app.runtime.adapter.PluginTest.java
License:Apache License
private static File generateClass(Class<?> fromClass, final String className, File directory) throws IOException { // Generate a class dynamically using ASM from another class, but use a different class name, // so that it won't be in the test class path. try (InputStream byteCode = fromClass.getClassLoader() .getResourceAsStream(Type.getInternalName(fromClass) + ".class")) { ClassReader reader = new ClassReader(byteCode); ClassWriter writer = new ClassWriter(0); reader.accept(new ClassVisitor(Opcodes.ASM5, writer) { @Override/*from w w w . ja v a 2 s.co m*/ public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { super.visit(version, access, className.replace('.', '/'), signature, superName, interfaces); } }, 0); File target = new File(directory, className.replace('.', File.separatorChar) + ".class"); DirUtils.mkdirs(target.getParentFile()); Files.write(writer.toByteArray(), target); return target; } }
From source file:co.cask.cdap.internal.app.runtime.batch.distributed.MapReduceContainerHelper.java
License:Apache License
/** * Rewrites the TwillLauncher bytecode as described * in {@link #saveLauncher(Configuration, File, List)}. * * @param hConf the hadoop configuration * @param sourceByteCode the original bytecode of the TwillLauncher * @param output output stream for writing the modified bytecode. * @throws IOException//from w w w. java 2 s . c om */ private static void rewriteLauncher(Configuration hConf, InputStream sourceByteCode, OutputStream output) throws IOException { URI frameworkURI = getFrameworkURI(hConf); if (frameworkURI == null) { ByteStreams.copy(sourceByteCode, output); return; } // It is localized as archive, and due to TWILL-144, a suffix is added. We need to reverse the effect of it // by creating an extra symlink as the first line in the TwillLauncher.main() method. String ext = Paths.getExtension(frameworkURI.getPath()); if (ext.isEmpty()) { ByteStreams.copy(sourceByteCode, output); return; } final String sourceName = frameworkURI.getFragment(); final String targetName = sourceName + "." + ext; ClassReader cr = new ClassReader(sourceByteCode); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); cr.accept(new ClassVisitor(Opcodes.ASM5, cw) { @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions); if (!name.equals("main")) { return mv; } Type[] argTypes = Type.getArgumentTypes(desc); if (argTypes.length != 1) { return mv; } Type argType = argTypes[0]; if (argType.getSort() != Type.ARRAY || !String.class.getName().equals(argType.getElementType().getClassName())) { return mv; } return new AdviceAdapter(Opcodes.ASM5, mv, access, name, desc) { @Override protected void onMethodEnter() { visitLdcInsn(sourceName); visitLdcInsn(targetName); invokeStatic(Type.getType(MapReduceContainerSymLinker.class), Methods.getMethod(void.class, "symlink", String.class, String.class)); } }; } }, ClassReader.EXPAND_FRAMES); output.write(cw.toByteArray()); }
From source file:co.paralleluniverse.fibers.instrument.JavaAgent.java
License:Open Source License
public static byte[] crazyClojureOnceDisable(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { if (!Boolean.parseBoolean(System.getProperty("co.paralleluniverse.pulsar.disableOnce", "false"))) return classfileBuffer; ClassReader cr = new ClassReader(classfileBuffer); ClassWriter cw = new ClassWriter(cr, 0); ClassVisitor cv = new ClassVisitor(Opcodes.ASM4, cw) { @Override/*from ww w . j a v a 2 s. c om*/ public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { return new MethodVisitor(api, super.visitMethod(access, name, desc, signature, exceptions)) { @Override public void visitLdcInsn(Object cst) { if (cst instanceof String && cst.equals("once")) { super.visitLdcInsn("once$disabled-by-pulsar"); } else super.visitLdcInsn(cst); } }; } }; cr.accept(cv, 0); return cw.toByteArray(); }
From source file:co.paralleluniverse.fibers.instrument.ModuleFilterTask.java
License:Open Source License
private void filter(File file) { try {//from w w w . j a va 2s . co m ClassWriter cw = null; try (FileInputStream fis = new FileInputStream(file)) { ClassReader cr = new ClassReader(fis); cw = new ClassWriter(cr, 0); cr.accept(new ClassVisitor(Opcodes.ASM7, cw) { @Override public ModuleVisitor visitModule(String name, int access, String version) { return new ModuleVisitor(Opcodes.ASM7, super.visitModule(name, access, version)) { @Override public void visitRequire(String module, int access, String version) { if (!module.contains(mod)) { super.visitRequire(module, access, version); } } }; } }, 0); } try (FileOutputStream fos = new FileOutputStream(file)) { fos.write(cw.toByteArray()); } } catch (IOException ex) { throw new BuildException("Filterin module-info file " + file, ex); } }
From source file:co.paralleluniverse.vtime.VirtualTimeClassTransformer.java
License:Open Source License
private ClassVisitor createVisitor(ClassVisitor next) { int api;//from w ww . j a va 2s. c om if (System.getProperty("java.version").startsWith("1.8")) { api = Opcodes.ASM5; } else if (System.getProperty("java.version").startsWith("10")) { api = Opcodes.ASM6; } else { api = Opcodes.ASM7; } return new ClassVisitor(api, next) { @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { return new MethodVisitor(api, super.visitMethod(access, name, desc, signature, exceptions)) { @Override public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) { if (!captureTimeCall(owner, name, desc)) { super.visitMethodInsn(opcode, owner, name, desc, itf); } } private boolean captureTimeCall(String owner, String name, String desc) { switch (owner) { case "java/lang/Object": if ("wait".equals(name)) { return callClockMethod("Object_wait", instanceToStatic(owner, desc)); } break; case "java/lang/System": switch (name) { case "nanoTime": return callClockMethod("System_nanoTime", desc); case "currentTimeMillis": return callClockMethod("System_currentTimeMillis", desc); } break; case "java/lang/Thread": if ("sleep".equals(name)) { return callClockMethod("Thread_sleep", desc); } break; case "sun/misc/Unsafe": if ("park".equals(name)) { return callClockMethod("Unsafe_park", instanceToStatic(owner, desc)); } break; case "java/lang/management/RuntimeMXBean": if ("getStartTime".equals(name)) { return callClockMethod("RuntimeMXBean_getStartTime", instanceToStatic(owner, desc)); } break; } return false; } private boolean callClockMethod(String name, String desc) { if (includedMethods == null || includedMethods.contains(name)) { super.visitMethodInsn(Opcodes.INVOKESTATIC, CLOCK, name, desc, false); return true; } else { return false; } } private String instanceToStatic(String owner, String desc) { return "(L" + owner + ";" + desc.substring(1); } }; } }; }
From source file:com.android.build.gradle.integration.application.ExternalBuildPluginTest.java
License:Apache License
private static byte[] hotswapChange(byte[] inputClass) { ClassReader cr = new ClassReader(inputClass); ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_FRAMES); ClassVisitor cv = new ClassVisitor(Opcodes.ASM5, cw) { @Override//from ww w . ja va 2 s . c om public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions); return new MethodVisitor(Opcodes.ASM5, mv) { @Override public void visitCode() { // add a useless logging to the method. mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); mv.visitLdcInsn("test changed !"); mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false); super.visitCode(); } }; } }; cr.accept(cv, ClassReader.EXPAND_FRAMES); return cw.toByteArray(); }
From source file:com.android.build.gradle.tasks.annotations.TypedefRemover.java
License:Apache License
/** * Rewrites the outer classes containing the typedefs such that they no longer refer to * the (now removed) typedef annotation inner classes *//*from w ww. j a va 2s. c om*/ private void rewriteOuterClasses() { for (File file : mAnnotationOuterClassFiles) { byte[] bytes; try { bytes = Files.toByteArray(file); } catch (IOException e) { Extractor.error("Could not read " + file + ": " + e.getLocalizedMessage()); continue; } ClassWriter classWriter = new ClassWriter(ASM5); ClassVisitor classVisitor = new ClassVisitor(ASM5, classWriter) { @Override public void visitInnerClass(String name, String outerName, String innerName, int access) { if (!mAnnotationNames.contains(name)) { super.visitInnerClass(name, outerName, innerName, access); } } }; ClassReader reader = new ClassReader(bytes); reader.accept(classVisitor, 0); byte[] rewritten = classWriter.toByteArray(); try { Files.write(rewritten, file); } catch (IOException e) { Extractor.error("Could not write " + file + ": " + e.getLocalizedMessage()); //noinspection UnnecessaryContinue continue; } } }
From source file:com.android.ide.eclipse.adt.internal.resources.manager.ProjectClassLoader.java
License:Open Source License
/** * Rewrites the given class to the given target class file version. *//*from w w w .j a v a 2 s.c om*/ public static byte[] rewriteClass(byte[] classData, final int maxVersion, final int minVersion) { assert maxVersion >= minVersion; ClassWriter classWriter = new ClassWriter(0); ClassVisitor classVisitor = new ClassVisitor(Opcodes.ASM5, classWriter) { @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { if (version > maxVersion) { version = maxVersion; } if (version < minVersion) { version = minVersion; } super.visit(version, access, name, signature, superName, interfaces); } }; ClassReader reader = new ClassReader(classData); reader.accept(classVisitor, 0); return classWriter.toByteArray(); }
From source file:com.android.tools.lint.psi.extract.ExtractPsi.java
License:Apache License
public byte[] computeClass(final CgClass clazz) throws IOException { assert clazz.isReachable(); ClassWriter classWriter = new ClassWriter(ASM5); ClassVisitor classVisitor = new ClassVisitor(ASM5, classWriter) { @Override/*from www . j a va 2 s . co m*/ public void visitInnerClass(String name, String outerName, String innerName, int access) { CgClass clz = findClass(name); if (clz != null && clz.isReachable()) { super.visitInnerClass(name, outerName, innerName, access); } } @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { // TODO: Filter out interfaces if they're not used? super.visit(version, access, name, signature, superName, interfaces); } @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { // Special cases: strip out method bodies for // (1) PsiElementVisitor#visitElement(PsiElement element) - // its current implementation is just // ProgressIndicatorProvider.checkCanceled(); // which we *don't* want (service lookup for that provider etc) // (2) Remove the constructor body of PsiDisjunctionType; remove the // myManager field, and the newDisjunctionType(final List<PsiType> types) // method. These don't work outside of // TODO: What about inner classes? Here the class name won't be right! CgMethod method = findMethod(clazz.getName(), name, desc); if (method != null && method.isReachable()) { if (method.toString().equals( "com/intellij/psi/PsiDisjunctionType#<init>(Ljava/util/List;Lcom/intellij/psi/PsiManager;)V")) { // Strip off the PsiManager parameter. The method body referencing it // has already been wiped out. desc = "(Ljava/util/List;)V"; signature = "(Ljava/util/List<Lcom/intellij/psi/PsiType;>;)V"; method.mMethodNode.invisibleParameterAnnotations = null; ArrayList<Object> parameters = new ArrayList<Object>(); parameters.add(method.mMethodNode.localVariables.get(0)); parameters.add(method.mMethodNode.localVariables.get(1)); method.mMethodNode.localVariables = parameters; } return super.visitMethod(access, name, desc, signature, exceptions); } return null; } @Override public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { CgField method = findField(clazz.getName(), name); if (method != null && method.isReachable()) { return super.visitField(access, name, desc, signature, value); } return null; } }; clazz.mClassNode.accept(classVisitor); return classWriter.toByteArray(); }
From source file:com.android.tools.rmtypedefs.RmTypeDefs.java
License:Apache License
/** * Rewrites the outer classes containing the typedefs such that they no longer refer to * the (now removed) typedef annotation inner classes *//* ww w . j a v a2 s . c om*/ private void rewriteOuterClasses() { for (File file : mAnnotationOuterClassFiles) { byte[] bytes; try { bytes = Files.toByteArray(file); } catch (IOException e) { System.err.println("Could not read " + file + ": " + e.getLocalizedMessage()); mHaveError = true; continue; } ClassWriter classWriter = new ClassWriter(ASM5); ClassVisitor classVisitor = new ClassVisitor(ASM5, classWriter) { @Override public void visitInnerClass(String name, String outerName, String innerName, int access) { if (!mAnnotationNames.contains(name)) { super.visitInnerClass(name, outerName, innerName, access); } } }; ClassReader reader = new ClassReader(bytes); reader.accept(classVisitor, 0); byte[] rewritten = classWriter.toByteArray(); try { Files.write(rewritten, file); } catch (IOException e) { System.err.println("Could not write " + file + ": " + e.getLocalizedMessage()); mHaveError = true; //noinspection UnnecessaryContinue continue; } } }