Java Code Examples for org.objectweb.asm.ClassWriter#toByteArray()
The following examples show how to use
org.objectweb.asm.ClassWriter#toByteArray() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ReflectiveFunctorFactory.java From maple-ir with GNU General Public License v3.0 | 6 votes |
private <T> EvaluationFunctor<T> buildBridge(MethodNode m) { ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); ClassNode owner = m.owner; owner.node.accept(cw); byte[] bytes = cw.toByteArray(); Class<?> clazz = classLoader.make(owner.getName(), bytes); for(Method method : clazz.getDeclaredMethods()) { if(method.getName().equals("eval")) { EvaluationFunctor<T> f = new ReflectiveFunctor<>(method); cache.put(owner.getName(), f); return f; } } throw new UnsupportedOperationException(); }
Example 2
Source File: Java9HackClassFileTransformer.java From glowroot with Apache License 2.0 | 6 votes |
@Override public byte /*@Nullable*/ [] transform(@Nullable ClassLoader loader, @Nullable String className, @Nullable Class<?> classBeingRedefined, @Nullable ProtectionDomain protectionDomain, byte[] bytes) { try { if ("org/glowroot/agent/weaving/WeavingClassFileTransformer".equals(className)) { ClassWriter cw = new ClassWriter(0); ClassVisitor cv = new Java9HackClassVisitor(cw); ClassReader cr = new ClassReader(bytes); cr.accept(cv, 0); return cw.toByteArray(); } } catch (Throwable t) { logger.error(t.getMessage(), t); } return null; }
Example 3
Source File: JavassistCoverageInterceptor.java From pitest with Apache License 2.0 | 6 votes |
private static byte[] transformBytes(final ClassLoader loader, final String className, final byte[] classfileBuffer) { final ClassReader reader = new ClassReader(classfileBuffer); final ClassWriter writer = new ComputeClassWriter( new ClassloaderByteArraySource(loader), COMPUTE_CACHE, FrameOptions.pickFlags(classfileBuffer)); // The transformed classes will be given a different id than the one already loaded. // Not clear if this is desirable or not. At the point of writing this comment // pitest will merge coverage of all classes with the same fully qualified name. // If this changes this might become a bug, however it would also probably not be possible // to support powermock if this assumption changed, so this code would most likely be deleted. final int id = CodeCoverageStore.registerClass(className); try { reader.accept(new CoverageClassVisitor(id, writer), ClassReader.EXPAND_FRAMES); return writer.toByteArray(); } catch (AlreadyInstrumentedException ex) { return null; } }
Example 4
Source File: ClassNameRemapper.java From Concurnas with MIT License | 6 votes |
public static byte[] remapClass(byte[] resource, String nameFrom, String nameTo) { ClassReader reader = new ClassReader(resource); ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); ClassVisitor visitor = new RemappingClassAdapter(writer, new Remapper() { @Override public String map(String from) { if (from.equals(nameFrom)) { return nameTo; } return from; } }); reader.accept(visitor, ClassReader.EXPAND_FRAMES); return writer.toByteArray(); }
Example 5
Source File: PatchGuiTextfield.java From The-5zig-Mod with MIT License | 5 votes |
@Override public byte[] transform(String s, String s1, byte[] bytes) { LogUtil.startClass("GuiTextfield (%s)", Names.guiTextfield.getName()); ClassReader reader = new ClassReader(bytes); ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_MAXS); ClassPatcher visitor = new ClassPatcher(writer); reader.accept(visitor, 0); LogUtil.endClass(); return writer.toByteArray(); }
Example 6
Source File: GenNerdClass.java From cs652 with BSD 3-Clause "New" or "Revised" License | 5 votes |
public static void main(String[] args) throws Exception { ClassWriter cw = new ClassWriter(0); TraceClassVisitor tracer = new TraceClassVisitor(cw, new PrintWriter(System.out)); ClassVisitor cv = tracer; String name = "Nerd"; String generics = null; String superName = "java/lang/Object"; String[] interfaces = null; int access = ACC_PUBLIC + ACC_INTERFACE; int version = V1_5; cv.visit(version, access, name, generics, superName, interfaces); int fieldAccess = ACC_PUBLIC + ACC_FINAL + ACC_STATIC; String shortDescriptor = Type.SHORT_TYPE.getDescriptor(); FieldVisitor hair = cv.visitField(fieldAccess, "hair", shortDescriptor, null, new Integer(0)); hair.visitEnd(); MethodVisitor playVideoGame = cv.visitMethod(ACC_PUBLIC + ACC_ABSTRACT, "playVideoGame", "()V", null, null); // no code to define, just finish it up playVideoGame.visitEnd(); cv.visitEnd(); // prints if using tracer byte[] b = cw.toByteArray(); // can define or write to file: // defineClass(name, b, 0, b.length) // from findClass() in subclass of ClassLoader FileOutputStream fos = new FileOutputStream("Nerd.class"); fos.write(b); fos.close(); }
Example 7
Source File: PatchNetworkManager.java From The-5zig-Mod with MIT License | 5 votes |
@Override public byte[] transform(String s, String s1, byte[] bytes) { ClassReader reader = new ClassReader(bytes); ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_MAXS); ClassPatcher visitor = new ClassPatcher(writer); reader.accept(visitor, 0); LogUtil.endClass(); return writer.toByteArray(); }
Example 8
Source File: Transformer.java From Kettle with GNU General Public License v3.0 | 5 votes |
/** * Convert code from using Class.X methods to our remapped versions */ public static byte[] transform(byte[] code) { ClassReader reader = new ClassReader(code); // Turn from bytes into visitor ClassNode node = new ClassNode(); reader.accept(node, 0); // Visit using ClassNode for (MethodNode method : node.methods) { // Taken from SpecialSource ListIterator<AbstractInsnNode> insnIterator = method.instructions.iterator(); while (insnIterator.hasNext()) { AbstractInsnNode insn = insnIterator.next(); if (!(insn instanceof MethodInsnNode)) { continue; } MethodInsnNode mi = (MethodInsnNode) insn; switch (mi.getOpcode()) { case Opcodes.INVOKEVIRTUAL: remapVirtual(mi); break; case Opcodes.INVOKESTATIC: remapForName(mi); break; } } } ClassWriter writer = new ClassWriter(0); node.accept(writer); return writer.toByteArray(); }
Example 9
Source File: PatchGuiConnecting.java From The-5zig-Mod with MIT License | 5 votes |
@Override public byte[] transform(String s, String s1, byte[] bytes) { LogUtil.startClass("GuiConnecting (%s)", Names.guiConnecting.getName()); ClassReader reader = new ClassReader(bytes); ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_MAXS); ClassPatcher visitor = new ClassPatcher(writer); reader.accept(visitor, 0); LogUtil.endClass(); return writer.toByteArray(); }
Example 10
Source File: CallSiteGenerator.java From groovy with Apache License 2.0 | 5 votes |
public static byte[] genPojoMetaMethodSite(CachedMethod cachedMethod, ClassWriter cw, String name) { String internalName = name.replace('.', '/'); classHeader(cw, internalName, "org/codehaus/groovy/runtime/callsite/PojoMetaMethodSite"); cw.visitField(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, "__constructor__", "Ljava/lang/reflect/Constructor;", null, null); genConstructor(cw, "org/codehaus/groovy/runtime/callsite/PojoMetaMethodSite", internalName); genCallXxxWithArray(cw, "", "org/codehaus/groovy/runtime/callsite/PojoMetaMethodSite", cachedMethod, "java/lang/Object"); genCallWithFixedParams(cw, "", "org/codehaus/groovy/runtime/callsite/PojoMetaMethodSite", cachedMethod, "java/lang/Object"); cw.visitEnd(); return cw.toByteArray(); }
Example 11
Source File: ObjectCodeGenerator.java From OpenPeripheral with MIT License | 5 votes |
@Override public byte[] generate(String clsName, Class<?> targetClass, Set<Class<?>> exposedInterfaces, IndexedMethodMap methods, int methodsId) { ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); writer.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC | Opcodes.ACC_SUPER, clsName, null, BASE_TYPE.getInternalName(), Utils.getInterfaces(exposedInterfaces)); Type targetType = Type.getType(targetClass); CommonMethodsBuilder builder = new CommonMethodsBuilder(writer, clsName, targetType); builder.addTargetField(); builder.addMethodsField(); builder.addClassInit(methodsId); createConstructors(writer, clsName, targetType); final Map<Method, Type> exposedMethods = Utils.getExposedMethods(exposedInterfaces); for (Map.Entry<Method, Type> e : exposedMethods.entrySet()) builder.addExposedMethodBypass(e.getKey(), e.getValue()); for (int i = 0; i < methods.size(); i++) { String name = methods.getMethodName(i); IMethodExecutor executor = methods.getMethod(i); builder.createScriptMethodWrapper(name, i, executor); } writer.visitEnd(); return writer.toByteArray(); }
Example 12
Source File: PatchNetworkManager.java From The-5zig-Mod with MIT License | 5 votes |
@Override public byte[] transform(String s, String s1, byte[] bytes) { ClassReader reader = new ClassReader(bytes); ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_MAXS); ClassPatcher visitor = new ClassPatcher(writer); reader.accept(visitor, 0); LogUtil.endClass(); return writer.toByteArray(); }
Example 13
Source File: ScottClassTransformer.java From scott with MIT License | 5 votes |
/** * Perform the given instrumentation actions on a class. * @param classfileBuffer class to be transformed * @param instrumentationActions instrumentation actions to be applied * @return instrumented class */ private byte[] transform(byte[] classfileBuffer, InstrumentationActions instrumentationActions) { ClassReader classReader = new ClassReader(classfileBuffer); ClassWriter classWriter = new ClassWriter(classReader, ClassWriter.COMPUTE_FRAMES); ClassVisitor localVariableStateEmitterTestClassVisitor = new StateTrackingClassVisitor(classWriter, instrumentationActions); classReader.accept(localVariableStateEmitterTestClassVisitor, 0); return classWriter.toByteArray(); }
Example 14
Source File: PatchGuiGameOver.java From The-5zig-Mod with MIT License | 5 votes |
@Override public byte[] transform(String s, String s1, byte[] bytes) { LogUtil.startClass("GuiGameOver (%s)", Names.guiGameOver.getName()); ClassReader reader = new ClassReader(bytes); ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); ClassPatcher visitor = new ClassPatcher(writer); reader.accept(visitor, 0); LogUtil.endClass(); return writer.toByteArray(); }
Example 15
Source File: ASMTest.java From bistoury with GNU General Public License v3.0 | 5 votes |
/** * 主方法 */ public static void main(String[] args) throws Exception { try { final String source = "/Users/leix.xie/workspace/opensource/bistoury/bistoury-instrument-client/target/test-classes/qunar/tc/test/Test.class"; final ClassReader classReader = new ClassReader(new FileInputStream(source)); final ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES); final ClassVisitor classVisitor = new ASMTest(new CheckClassAdapter(classWriter), source); classReader.accept(classVisitor, ClassReader.EXPAND_FRAMES); byte[] bytes = classWriter.toByteArray(); print(bytes); } catch (Throwable t) { t.printStackTrace(); } //startReport(); }
Example 16
Source File: DebuggerClassFileTransformer.java From bistoury with GNU General Public License v3.0 | 5 votes |
@Override protected byte[] transform(final String className, final Class<?> classBeingRedefined, final ProtectionDomain protectionDomain, final byte[] classBytes) throws IllegalClassFormatException { if (!Objects.equals(className, debugClassName)) { return null; } LOG.info("debug class: {}", className); Lock lock = classFileBuffer.getLock(); lock.lock(); try { final ClassReader classReader = new ClassReader(classFileBuffer.getClassBuffer(classBeingRedefined, classBytes)); final ClassMetadata classMetadata = new ClassMetadata(); classReader.accept(new MetadataCollector(classMetadata), ClassReader.SKIP_FRAMES); final ClassWriter classWriter = new ClassWriter(computeFlag(classReader)); final ClassVisitor classVisitor = new DebuggerClassVisitor(new CheckClassAdapter(classWriter), source, classMetadata); classReader.accept(classVisitor, ClassReader.SKIP_FRAMES); byte[] bytes = classWriter.toByteArray(); classFileBuffer.setClassBuffer(classBeingRedefined, bytes); return bytes; } finally { lock.unlock(); } }
Example 17
Source File: GroovyClassLoader.java From groovy with Apache License 2.0 | 4 votes |
protected Class onClassNode(ClassWriter classWriter, ClassNode classNode) { byte[] code = classWriter.toByteArray(); return createClass(code, classNode); }
Example 18
Source File: CacheonixAgent.java From cacheonix-core with GNU Lesser General Public License v2.1 | 4 votes |
public byte[] transform(final ClassLoader loader, final String className, final Class<?> classBeingRedefined, final ProtectionDomain protectionDomain, final byte[] classfileBuffer) throws IllegalClassFormatException { String strClassName = className; try { // if (className.startsWith("java") // || className.startsWith("cacheonix/")) // { // return null; // } // else if (className.startsWith("org/cacheonix/impl") // && !className.startsWith("org/cacheonix/impl/examples") // && !className.startsWith("org/cacheonix/impl/annotations/test") ) // { // return null; // } // else if (className.startsWith("sun/nio") // || className.startsWith("sun/reflect") // || className.startsWith("sun/misc")) // { // return null; // } // // System.out.println("Processing -- " + className.replace('/', // '.')); final boolean b1 = className.endsWith("CacheAnnotatedTest"); final boolean b2 = className.endsWith("CacheAnnotationsTest"); if (!b1 && !b2) { return null; } strClassName = className.replace('/', '.'); final ClassReader creader = new ClassReader(classfileBuffer); final CacheonixClassReader classCollector = new CacheonixClassReader(); creader.accept(classCollector, ClassReader.SKIP_CODE | ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG); final Map<String, AnnotationParameter> classLevelInfo = classCollector .getClassLevelAnnotationInfo(); final Map<String, MethodMetaData> methodsInfo = classCollector .getMethodsInfo(); if (!classLevelInfo.isEmpty() || !methodsInfo.isEmpty()) { // annotated fields present, generate the toString() method // Temporary System.out.println("Modifying " + strClassName); final ClassWriter writer = new ClassWriter( ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); final CacheonixClassAdapter gen = new CacheonixClassAdapter( writer, strClassName, classLevelInfo, methodsInfo); creader.accept(gen, 0); // ClassReader.SKIP_DEBUG return writer.toByteArray(); } } catch (final IllegalStateException e) { throw new IllegalClassFormatException("Error: " + e.getMessage() + // NOPMD " on class " + strClassName); // NOPMD } return null; }
Example 19
Source File: Engine.java From JReFrameworker with MIT License | 4 votes |
private byte[] mergeClasses(byte[] baseClass, byte[] classToMerge) throws IOException { // read the classes into ClassNode objects ClassNode baseClassNode = BytecodeUtils.getClassNode(baseClass); ClassNode classToMergeClassNode = BytecodeUtils.getClassNode(classToMerge); // get a list of base methods conflicting with methods to merge BaseMethodsIdentifier baseMethodsIdentifier = new BaseMethodsIdentifier(baseClassNode); LinkedList<MethodNode> baseMethods = baseMethodsIdentifier.getBaseMethods(); // identify methods to insert or replace DefineIdentifier defineMethodsIdentifier = new DefineIdentifier(classToMergeClassNode); LinkedList<DefineMethodAnnotation> methodsToDefine = defineMethodsIdentifier.getDefineMethodAnnotations(); // identify methods to merge MergeIdentifier mergeIdentifier = new MergeIdentifier(classToMergeClassNode); LinkedList<MergeMethodAnnotation> methodToMergeAnnotations = mergeIdentifier.getMergeMethodAnnotations(); // rename base methods that should be preserved LinkedList<String> renamedMethods = new LinkedList<String>(); for(MergeMethodAnnotation methodToMergeAnnotation : methodToMergeAnnotations){ MethodNode methodToMerge = methodToMergeAnnotation.getMethodNode(); boolean foundTargetMethod = false; for(MethodNode baseMethod : baseMethods){ if(methodToMerge.signature != null && baseMethod.signature != null){ if(methodToMerge.signature.equals(baseMethod.signature)){ if(methodToMerge.name.equals(baseMethod.name) && methodToMerge.desc.equals(baseMethod.desc)){ renamedMethods.add(baseClassNode.name + "." + renameMethod(baseMethod)); foundTargetMethod = true; continue; } } } else { // signature was null, fall back to name and description only if(methodToMerge.name.equals(baseMethod.name) && methodToMerge.desc.equals(baseMethod.desc)){ renamedMethods.add(baseClassNode.name + "." + renameMethod(baseMethod)); foundTargetMethod = true; continue; } } } if(!foundTargetMethod){ Log.warning("Target method " + methodToMerge.desc.toString() + " does not exist! Runtime behavior may not be correct."); } } // purge defined methods that were already there // adapt a ClassWriter with the PurgeAdapter ClassWriter classWriter = new ClassLoadingClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); Set<MethodNode> methodsToPurge = new HashSet<MethodNode>(); for(DefineMethodAnnotation methodToDefine : methodsToDefine){ methodsToPurge.add(methodToDefine.getMethodNode()); } Set<FieldNode> fieldsToPurge = new HashSet<FieldNode>(); PurgeAdapter purgeAdapter = new PurgeAdapter(classWriter, methodsToPurge, fieldsToPurge); ClassReader purgedBaseClassReader = new ClassReader(BytecodeUtils.writeClass(baseClassNode)); purgedBaseClassReader.accept(purgeAdapter, ClassReader.EXPAND_FRAMES); baseClassNode = BytecodeUtils.getClassNode(classWriter.toByteArray()); // merge the classes // adapt a ClassWriter with the MergeAdapter // modifiedBaseClass, classToMerge -> MergeAdapter -> ClassWriter classWriter = new ClassLoadingClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); MergeAdapter mergeAdapter = new MergeAdapter(classWriter, classToMergeClassNode, mergeRenamePrefix, renamedMethods); ClassReader modifiedBaseClassReader = new ClassReader(BytecodeUtils.writeClass(baseClassNode)); modifiedBaseClassReader.accept(mergeAdapter, ClassReader.EXPAND_FRAMES); return classWriter.toByteArray(); }
Example 20
Source File: InstrumentUtil.java From jumbune with GNU Lesser General Public License v3.0 | 3 votes |
/** * <p> * This method instruments the given bytes and return the modified bytes. * </p> * * @param inputBytes * bytes to be instrumented * @param cv * Class Visitor * @param cw * Class Writer * @return Modified bytes * @throws FileNotFoundException * An error occurred during the operation * @throws IOException * An error occurred during the operation */ public static byte[] instrumentBytes(byte[] inputBytes, ClassVisitor cv, ClassVisitor cw) throws IOException { LOGGER.debug(MessageFormat.format(InstrumentationMessageLoader .getMessage(MessageConstants.INSTRUMENT_USING), cv.getClass() .getSimpleName())); ClassReader cr = new ClassReader(inputBytes); cr.accept(cv, ClassReader.SKIP_FRAMES); ClassWriter cw1 = (ClassWriter) cw; return cw1.toByteArray(); }