/** * Check to see if a class is well-formed. * * @param logger the logger to write to if a problem is found * @param logTag a tag to print to the log if a problem is found * @param classNode the class to check * @return true if the class is ok, false otherwise */ public static boolean isClassOk(final Logger logger, final String logTag, final ClassNode classNode) { final StringWriter sw = new StringWriter(); final ClassWriter verifyWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES); classNode.accept(verifyWriter); final ClassReader ver = new ClassReader(verifyWriter.toByteArray()); try { DrillCheckClassAdapter.verify(ver, false, new PrintWriter(sw)); } catch(final Exception e) { logger.info("Caught exception verifying class:"); logClass(logger, logTag, classNode); throw e; } final String output = sw.toString(); if (!output.isEmpty()) { logger.info("Invalid class:\n" + output); return false; } return true; }
private void generateClosureClass(TContext closure_ctx) throws CompileException { ClassWriter cw = ((TContextClosure) closure_ctx).getClassWriter(); Debug.assertion(cw != null, "cw should be valid"); // write class file try { LOG.debug("Writing Class File(" + closure_ctx.getName() + ")"); //byte[] code = cpLoader.writeClassFile(cw, closure_ctx.getName()); cpLoader.writeClassFile(cw, closure_ctx.getName()); } catch (Exception e) { // e.printStackTrace(); CompileException excp = new CompileException("Exception occurred in writing class file"); excp.setTargetException(e); throw excp; } }
private void registerClassMemberVar(TContextClass class_ctx, Container container) throws CompileException { ClassWriter cw = class_ctx.getClassWriter(); Debug.assertion(cw != null, "ClassWriter should not be null"); AbsType field_type = container.getType(); Debug.assertion(field_type != null, "Container Type should not be null"); //// Compiled Instruction LOG.debug( "Adding Field(" + container.name + ":" + field_type.getMthdDscStr() + ") in (" + class_ctx.getName() + ")"); int access = 0; access |= Opcodes.ACC_PUBLIC; // access |= Opcodes.ACC_PROTECTED; if (container.isSingleton()) { access |= Opcodes.ACC_STATIC; } cw.visitField(access, container.name, field_type.getMthdDscStr(), null, null).visitEnd(); //// End }
private static void createMainMethod(ClassWriter cw) { MethodVisitor mv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null); mv.visitCode(); Label l0 = new Label(); mv.visitLabel(l0); for (SysProp type : SysProp.values()) { if (type != SysProp.Z_ERROR) { dumpProperty(mv, type.sysProp); } } mv.visitInsn(RETURN); Label l3 = new Label(); mv.visitLabel(l3); mv.visitLocalVariable("args", "[Ljava/lang/String;", null, l0, l3, 0); mv.visitMaxs(3, 1); mv.visitEnd(); }
private void generateProxyClass(ClassWriter visitor, StructSchema<?> viewSchema, StructBindings<?> bindings, Collection<String> interfacesToImplement, Collection<ModelType<?>> viewTypes, Type generatedType, Type superclassType, Class<? extends GeneratedViewState> backingStateType) { Class<?> viewClass = viewSchema.getType().getConcreteClass(); StructSchema<?> delegateSchema = bindings.getDelegateSchema(); declareClass(visitor, interfacesToImplement, generatedType, superclassType); declareStateField(visitor); declareTypeConverterField(visitor); declareManagedTypeField(visitor); declareCanCallSettersField(visitor); writeStaticConstructor(visitor, generatedType, viewClass); writeConstructor(visitor, generatedType, superclassType, delegateSchema, Type.getType(backingStateType)); writeToString(visitor, generatedType, viewClass, delegateSchema); writeGeneratedViewMethods(visitor, generatedType); if (backingStateType == ModelElementState.class) { writeManagedInstanceMethods(visitor, generatedType); } writeGroovyMethods(visitor, viewClass); writeViewMethods(visitor, generatedType, viewTypes, bindings); writeHashCodeMethod(visitor, generatedType); writeEqualsMethod(visitor, generatedType); visitor.visitEnd(); }
/** * Generates an implementation of the given managed type. * * <p>The generated type will:</p> * * <ul> * <li>extend the given implementation class</li> * <li>implement the given public interface</li> * <li>override each public constructor of the given implementation class</li> * </ul> */ public Class<?> generate(Class<?> implClass, Class<?> publicContractType) { ClassWriter visitor = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); String generatedTypeName = publicContractType.getName() + "_Impl"; Type generatedType = Type.getType("L" + generatedTypeName.replaceAll("\\.", "/") + ";"); Type superclassType = Type.getType(implClass); Type publicType = Type.getType(publicContractType); generateClass(visitor, generatedType, superclassType, publicType); generateConstructors(visitor, implClass, superclassType); visitor.visitEnd(); return defineClass(visitor, publicContractType.getClassLoader(), generatedTypeName); }
private <T> void generateConstructors(ClassWriter visitor, Class<? extends T> implClass, Type superclassType) { for (Constructor<?> constructor : implClass.getConstructors()) { Type[] paramTypes = new Type[constructor.getParameterTypes().length]; for (int i = 0; i < paramTypes.length; i++) { paramTypes[i] = Type.getType(constructor.getParameterTypes()[i]); } String methodDescriptor = Type.getMethodDescriptor(Type.VOID_TYPE, paramTypes); MethodVisitor constructorVisitor = visitor.visitMethod(Opcodes.ACC_PUBLIC, CONSTRUCTOR_NAME, methodDescriptor, CONCRETE_SIGNATURE, NO_EXCEPTIONS); constructorVisitor.visitCode(); putThisOnStack(constructorVisitor); for (int i = 0; i < paramTypes.length; i++) { constructorVisitor.visitVarInsn(paramTypes[i].getOpcode(Opcodes.ILOAD), i + 1); } constructorVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superclassType.getInternalName(), CONSTRUCTOR_NAME, methodDescriptor, false); finishVisitingMethod(constructorVisitor); } }
public byte[] transform(String name, byte[] basicClass) { int i = 0; while (i < transformers.size()) { if (transformers.get(i).is(name)) { ClassNode classNode = new ClassNode(); ClassReader classReader = new ClassReader(basicClass); classReader.accept(classNode, 0); transformers.get(i).transform(classNode); ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES); classNode.accept(writer); basicClass = writer.toByteArray(); System.out.println("[" + MineCamera.MODID + "] Patched " + transformers.get(i).className + " ..."); transformers.get(i).done(); i++; // transformers.remove(i); } else i++; } return basicClass; }
@Override public byte[] transform(String name, String transformedName, byte[] basicClass) { List<ITransformer> transformers = getTransformers(transformedName); if (!transformers.isEmpty()) { ClassNode cn = getClassNode(basicClass); if (cn == null) return basicClass; // Run all transformers on the Class transformers.forEach(transformer -> transformer.transform(cn)); // Return transformed class bytecode ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); cn.accept(cw); return cw.toByteArray(); } return basicClass; }
public byte[] serializeClass(ClassInstance cls, boolean mapped) { ClassNode cn = cls.getMergedAsmNode(); if (cn == null) throw new IllegalArgumentException("cls without asm node: "+cls); ClassWriter writer = new ClassWriter(0); synchronized (Util.asmNodeSync) { if (mapped) { AsmClassRemapper.process(cn, remapper, writer); } else { cn.accept(writer); } } return writer.toByteArray(); }
@Override public void run() { if (!hasWorkingJavac()) { ClassWriter w = new ClassWriter(0); w.visit(Opcodes.V1_8, Opcodes.ACC_ABSTRACT | Opcodes.ACC_PUBLIC, "com/sun/tools/javac/code/Scope$WriteableScope", null, "com/sun/tools/javac/code/Scope", null); byte[] classData = w.toByteArray(); try { Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe"); theUnsafe.setAccessible(true); Unsafe unsafe = (Unsafe) theUnsafe.get(null); Class scopeClass = Class.forName("com.sun.tools.javac.code.Scope"); unsafe.defineClass("com.sun.tools.javac.code.Scope$WriteableScope", classData, 0, classData.length, scopeClass.getClassLoader(), scopeClass.getProtectionDomain()); } catch (Throwable t) { //ignore... Logger.getLogger(NoJavacHelper.class.getName()).log(Level.FINE, null, t); } } }
@Override public void proceed() { ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); writer.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC | Opcodes.ACC_SUPER, RSymbols.R_STYLEABLES_CLASS_NAME, null, "java/lang/Object", null); for (String name : symbols.getStyleables().keySet()) { writer.visitField(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL, name, "[I", null, null); } writeClinit(writer); writer.visitEnd(); byte[] bytes = writer.toByteArray(); try { if (!dir.isDirectory() && !dir.mkdirs()) { throw new RuntimeException("Cannot mkdir " + dir); } Files.write(dir.toPath().resolve(RSymbols.R_STYLEABLES_CLASS_NAME + ".class"), bytes); } catch (IOException e) { throw new UncheckedIOException(e); } }
private static byte[] generateClass(Class<? extends TileEntity> baseClass, String className, String contentId) { ClassWriter cw = new ClassWriter(0); cw.visit(V1_7, ACC_PUBLIC + ACC_SUPER, className, null, Type.getInternalName(baseClass), null); // Constructor MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); mv.visitVarInsn(ALOAD, 0); mv.visitLdcInsn(contentId); mv.visitMethodInsn(INVOKESPECIAL, Type.getInternalName(baseClass), "<init>", "(Ljava/lang/String;)V", false); mv.visitInsn(RETURN); mv.visitMaxs(2, 1); mv.visitEnd(); return cw.toByteArray(); }
/** * Writes a modified *.class file to the output JAR file. */ private void rewriteClass( JarEntry entry, InputStream inputStream, JarOutputStream outputStream) throws IOException { ClassReader classReader = new ClassReader(inputStream); ClassNode classNode = new ClassNode(Opcodes.ASM5); classReader.accept(classNode, EMPTY_FLAGS); modifyClass(classNode); ClassWriter classWriter = new ClassWriter(0); classNode.accept(classWriter); outputStream.putNextEntry(new ZipEntry(entry.getName())); outputStream.write(classWriter.toByteArray()); }
public AsmFlagsPanel() { //@formatter:off setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); JPanel p1 = new JPanel(); p1.setBorder(BorderFactory.createTitledBorder("Input Flags")); p1.setLayout(new GridLayout(0, 2)); p1.add(inE = new ActionCheckBox("Expand Frames", Access.hasAccess(getOptions().classFlagsInput, ClassReader.EXPAND_FRAMES), (b) -> update())); p1.add(inD = new ActionCheckBox("Skip Debug", Access.hasAccess(getOptions().classFlagsInput, ClassReader.SKIP_DEBUG), (b) -> update())); p1.add(inF = new ActionCheckBox("Skip Frames", Access.hasAccess(getOptions().classFlagsInput, ClassReader.SKIP_FRAMES), (b) -> update())); p1.add(inC = new ActionCheckBox("Skip Code", Access.hasAccess(getOptions().classFlagsInput, ClassReader.SKIP_CODE), (b) -> update())); JPanel p2 = new JPanel(); p2.setBorder(BorderFactory.createTitledBorder("Output Flags")); p2.setLayout(new GridLayout(0, 2)); p2.add(outF = new ActionCheckBox("Compute Frames", Access.hasAccess(getOptions().classFlagsOutput, ClassWriter.COMPUTE_FRAMES), (b) -> update())); p2.add(outM = new ActionCheckBox("Compute Maxs", Access.hasAccess(getOptions().classFlagsOutput, ClassWriter.COMPUTE_MAXS), (b) -> update())); add(p1); add(p2); //@formatter:on }
@Override public void write(File file) throws IOException { JarOutputStream jos = new JarOutputStream(new FileOutputStream(file)); try { for (Iterator<ClassNode> itr = iterator(); itr.hasNext(); ) { ClassNode node = itr.next(); ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); node.accept(new CheckClassAdapter(writer, true)); byte[] bytes = writer.toByteArray(); jos.putNextEntry(new JarEntry(node.name.concat(".class"))); jos.write(bytes); } } finally { jos.close(); } }
@Override public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { if(className.startsWith(TransformConfig.getInstance().getPackageScan())) { logger.log(Level.INFO, "-------------------CLASS---------------------"); logger.log(Level.INFO, "className: " + className); ClassReader cr = new ClassReader(classfileBuffer); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); ClassVisitor classVisitor = new HookClassAdapter(Opcodes.ASM5, cw); cr.accept(classVisitor, ClassReader.SKIP_FRAMES); // try { // FileOutputStream fos = new FileOutputStream(new File("classMod.class")); // fos.write(cw.toByteArray()); // fos.close(); // } catch (IOException e) { // e.printStackTrace(); // } return cw.toByteArray(); } return null; }
public byte[] transformCode(String className, byte[] fb) { this.className = className; ClassReader cr = new ClassReader(fb); // ClassReader cr = new ClassReader(className); ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_MAXS); ClassVisitor cv = new ClassInsert(cw); cr.accept(cv, ClassReader.EXPAND_FRAMES); /*byte[] code = cw.toByteArray(); File file = new File("Idtk.class"); try { FileUtils.writeByteArrayToFile(file,code); }catch (IOException e){ System.out.println("=======IOException======="); }*/ return cw.toByteArray(); }
private byte[] classNodeToBytes(ClassNode classNode) { ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); classNode.accept(writer); byte[] bytes = writer.toByteArray(); // verify bytecode if (verifyAndPrint) { ClassReader reader = new ClassReader(bytes); ClassVisitor tracer = new TraceClassVisitor(new PrintWriter(System.out)); ClassVisitor checker = new CheckClassAdapter(tracer, true); reader.accept(checker, 0); } return bytes; }
public static void rewriteDataBinderMapper(File dir, String fromName, String toName, File Clazz) throws IOException { FileInputStream fileInputStream = new FileInputStream(Clazz); ClassReader in1 = new ClassReader(fileInputStream); ClassWriter cw = new ClassWriter(0); Set<String> renames = new HashSet<String>(); renames.add(fromName); in1.accept(new ClassRenamer(cw, renames, toName), 8); File destClass = new File(dir, toName + ".class"); destClass.getParentFile().mkdirs(); FileOutputStream fileOutputStream = new FileOutputStream(destClass); fileOutputStream.write(cw.toByteArray()); IOUtils.closeQuietly(fileOutputStream); IOUtils.closeQuietly(fileInputStream); }
@Override protected void handleClazz(JarFile jarFile, JarOutputStream jos, JarEntry ze, String pathName) { // logger.log(pathName); if (reMapping.containsKey(pathName.substring(0, pathName.length() - 6))) { logger.info("[ClazzReplacer] remove class " + pathName + " form " + jarFile); return; } try { InputStream in = jarFile.getInputStream(ze); ClassReader cr = new ClassReader(in); ClassWriter cw = new ClassWriter(0); RemappingClassAdapter remappingClassAdapter = new RemappingClassAdapter(cw, new SimpleRemapper(reMapping)); cr.accept(remappingClassAdapter, ClassReader.EXPAND_FRAMES); InputStream inputStream = new ByteArrayInputStream(cw.toByteArray()); copyStreamToJar(inputStream, jos, pathName, ze.getTime()); } catch (Throwable e) { System.err.println("[ClazzReplacer] rewrite error > " + pathName); justCopy(jarFile, jos, ze, pathName); } }
@NotNull @SuppressWarnings("unchecked") static <T extends IClassTransformer> Class<T> convert(@NotNull Class<? extends OrionTransformer> transformer) { if(Arrays.asList(transformer.getInterfaces()).contains(IClassTransformer.class)) return (Class<T>) transformer; /* no-op */ // Orion transformer name String rawTransformerName = transformer.getName().replace('.', '/'); // New wrapper class name String newWrapperName = getNewName(transformer); // Start generating new TransformerWrapper ClassReader cr = new ClassReader(TW_DATA); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); ClassNode cn = new ClassNode(); cr.accept(cn, 0); cn.accept(new WrapperGenerator(cw, TW_TYPE.getInternalName(), newWrapperName.replace('.', '/'), rawTransformerName)); return requireNonNull((Class<T>) ClassLoaderTools.defineClass(Launch.classLoader, newWrapperName, cw.toByteArray())); }
public byte[] transformCode(byte[] b1, String className) throws IOException { ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); ClassReader cr = new ClassReader(b1); ClassNode classNode = new ClassNode(); Map<String, Boolean> methodInstructionTypeMap = new HashMap<>(); cr.accept(classNode, 0); final List<MethodNode> methods = classNode.methods; for (MethodNode m : methods) { InsnList inList = m.instructions; boolean isMethodInvoke = false; for (int i = 0; i < inList.size(); i++) { if (inList.get(i).getType() == AbstractInsnNode.METHOD_INSN) { isMethodInvoke = true; } } methodInstructionTypeMap.put(m.name + m.desc, isMethodInvoke); } InsertMethodBodyAdapter insertMethodBodyAdapter = new InsertMethodBodyAdapter(cw, className, methodInstructionTypeMap); cr.accept(insertMethodBodyAdapter, ClassReader.EXPAND_FRAMES); return cw.toByteArray(); }
private static void publicize(Path inPath, Path outPath) throws IOException { try (JarInputStream in = new JarInputStream(Files.newInputStream(inPath))) { try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(outPath))) { JarEntry entry; while ((entry = in.getNextJarEntry()) != null) { if (entry.isDirectory()) { continue; } String name = entry.getName(); out.putNextEntry(new JarEntry(name)); if (name.endsWith(".class")) { ClassWriter writer = new ClassWriter(0); ClassReader reader = new ClassReader(in); reader.accept(new CheckClassAdapter(new ClassDefinalizer(new ClassPublicizer(writer)), true), 0); out.write(writer.toByteArray()); } else { ByteStreams.copy(in, out); } } } } }
@Override public byte[] transform(String name, String transformedName, byte[] bytes) { if (bytes == null) { return null; } if (!markers.containsKey(name)) { return bytes; } ClassNode classNode = new ClassNode(); ClassReader classReader = new ClassReader(bytes); classReader.accept(classNode, 0); for (String marker : markers.get(name)) { classNode.interfaces.add(marker); } ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); classNode.accept(writer); return writer.toByteArray(); }
public byte[] generate(){ String className = "eu.mikroskeem.test.shuriken.common.classtools.gen.InvalidGeneratedClass"; String classNameInternal = className.replaceAll("\\.", "/"); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES); cw.visit( V1_8, ACC_PUBLIC + ACC_SUPER, classNameInternal, null, Type.getInternalName(Object.class), null); FieldVisitor fv = cw.visitField(ACC_PRIVATE + ACC_STATIC, "test", Type.getDescriptor(String.class), null, "hey"); fv.visitEnd(); MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKESPECIAL, Type.getInternalName(Object.class), "<init>", "()V", false); mv.visitInsn(RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); cw.visitEnd(); return cw.toByteArray(); }
@Override public byte[] handler(byte[] pClass) { ClassReader cr=new ClassReader(pClass); ClassNode cn=new ClassNode(); cr.accept(cn, 0); for (MethodNode mv:cn.methods){ if(mv.name.equals("accept")){ AbstractInsnNode node=mv.instructions.getFirst(); do{ if(node instanceof MethodInsnNode){ if(node.getOpcode()==INVOKESTATIC){ if(((MethodInsnNode) node).name.equals("revertToFrozen")){ mv.instructions.remove(node); break; } } } }while ((node=node.getNext())!=null); break; } } ClassWriter cw=new ClassWriter(0); cn.accept(cw); return cw.toByteArray(); }
private static void generateUpdateMethod(ClassWriter cw, String selfClassInternalName, String selfClassDescriptor, String argsClassInternalName, String constDesc, Parameter[] parameters) { MethodVisitor mv; mv = cw.visitMethod(ACC_PUBLIC, "update", "()Lio/primeval/reflex/arguments/Arguments;", null, null); mv.visitCode(); Label l0 = new Label(); mv.visitLabel(l0); mv.visitTypeInsn(NEW, argsClassInternalName); mv.visitInsn(DUP); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, selfClassInternalName, "parameters", "Ljava/util/List;"); for (int i = 0; i < parameters.length; i++) { Parameter parameter = parameters[i]; mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, selfClassInternalName, parameter.getName(), Type.getDescriptor(parameter.getType())); } mv.visitMethodInsn(INVOKESPECIAL, argsClassInternalName, "<init>", constDesc, false); mv.visitInsn(ARETURN); Label l1 = new Label(); mv.visitLabel(l1); mv.visitLocalVariable("this", selfClassDescriptor, null, l0, l1, 0); mv.visitMaxs(-1, -1); mv.visitEnd(); }
public byte[] compile(String className, Class<?> clazz) throws IOException, CompilerException { ClassWriter cw = new ClassWriter(0); Type clazzType = Type.getType(clazz); String internalName = className.replace('.', '/'); String classDesc = "L" + internalName + ";"; String signature = BytecodeGenerator.OBJECT.getDescriptor() + "L" + BytecodeGenerator.OBJECT_TEMPLATE.getInternalName() + "<" + clazzType.getDescriptor() + ">;"; cw.visit(52, ACC_PUBLIC + ACC_SUPER, internalName, signature, BytecodeGenerator.OBJECT.getInternalName(), new String[]{BytecodeGenerator.OBJECT_TEMPLATE.getInternalName()}); cw.visitSource(templateName, null); createConstructor(cw, classDesc); createObjectRender(cw, internalName, classDesc, clazzType); DataManager getter = new ClassDataManager(clazz, clazzType); generator = new BytecodeGenerator(this, cw, getter, internalName, classDesc); generator.insertMethodStart("render"); parser.parse(); generator.insertMethodEnd(); cw.visitEnd(); return cw.toByteArray(); }
public void setClassWriter(ClassWriter classWriter) throws CompileException { if (!isForm(FORM_CLASS)) { throw new CompileException("ClassWriter should be set on ContextClass"); } this.classWriter = classWriter; }
/** * Extracts an API class from a given original class. * * @param originalClassReader the reader containing the original class * @return bytecode of the API class extracted from the original class */ public byte[] extractApiClassFrom(ClassReader originalClassReader) { ClassWriter apiClassWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS); originalClassReader.accept( new ApiMemberSelector(new MethodStubbingApiMemberAdapter(apiClassWriter), apiIncludesPackagePrivateMembers), ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); return apiClassWriter.toByteArray(); }
public static byte[] apply(final @Nonnull byte[] bytes, final @Nonnull String name, final @Nonnull TransformProvider context) { Validate.notNull(bytes); final ClassReader cr = new ClassReader(bytes); final ClassWriter cw = new ClassWriter(cr, context.flags); final ClassVisitor mod = context.createVisitor(name, cw); try { cr.accept(mod, 0); return cw.toByteArray(); } catch (final StopTransforming e) { return bytes; } }
private static void createConstructor(ClassWriter cw) { MethodVisitor mv; mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); mv.visitCode(); Label l0 = new Label(); mv.visitLabel(l0); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false); mv.visitInsn(RETURN); Label l1 = new Label(); mv.visitLabel(l1); mv.visitLocalVariable("this", "LJavaProbe;", null, l0, l1, 0); mv.visitMaxs(1, 1); mv.visitEnd(); }
private void createConstructor(ClassWriter cw, String classDesc) { Label start = new Label(); Label end = new Label(); MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); mv.visitCode(); mv.visitLabel(start); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESPECIAL, BytecodeGenerator.OBJECT.getInternalName(), "<init>", "()V", false); mv.visitInsn(RETURN); mv.visitLabel(end); mv.visitLocalVariable("this", classDesc, null, start, end, 0); mv.visitMaxs(1, 1); mv.visitEnd(); }
private byte[] remapClass(String className, byte[] bytes) { ClassReader classReader = new ClassReader(bytes); ClassWriter classWriter = new ClassWriter(0); ClassVisitor remappingVisitor = new ShadingClassRemapper(classWriter, remapper); try { classReader.accept(remappingVisitor, ClassReader.EXPAND_FRAMES); } catch (Exception e) { throw new GradleException("Error in ASM processing class: " + className, e); } return classWriter.toByteArray(); }
private ClassBuilderImpl(Class<T> type, ClassMetaData classMetaData) { this.type = type; visitor = new ClassWriter(ClassWriter.COMPUTE_MAXS); typeName = type.getName() + "_Decorated"; generatedType = Type.getType("L" + typeName.replaceAll("\\.", "/") + ";"); superclassType = Type.getType(type); extensible = classMetaData.isExtensible(); conventionAware = classMetaData.isConventionAware(); providesOwnDynamicObject = classMetaData.providesDynamicObjectImplementation(); }
@Override public byte[] generateSyntheticClass(String name) { ClassWriter visitor = new ClassWriter(0); visitor.visit(Opcodes.V1_7, Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC | Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT, name.replace('.', '/'), null, OBJECT_TYPE.getInternalName(), null); visitor.visitEnd(); return visitor.toByteArray(); }
@Override public byte[] apply(byte[] origin) { ClassReader reader = new ClassReader(origin); PredicateClassVisitor precondition = new PredicateClassVisitor(); reader.accept(precondition, SKIP_DEBUG | SKIP_FRAMES); if (!precondition.isAttemptToVisitR()) { return origin; } // don't pass reader to the writer. // or it will copy 'CONSTANT POOL' that contains no used entries to lead proguard running failed! ClassWriter writer = new ClassWriter(0); ClassVisitor visitor = new ShrinkRClassVisitor(writer, rSymbols); reader.accept(visitor, 0); return writer.toByteArray(); }
@Override public byte[] transform(String name, String transformedName, byte[] bytes) { if (bytes == null) { return null; } ClassReader classReader = new ClassReader(bytes); ClassWriter classWriter = new ClassWriter(WRITER_FLAGS); RemappingClassAdapter remapAdapter = new FMLRemappingAdapter(classWriter); classReader.accept(remapAdapter, READER_FLAGS); return classWriter.toByteArray(); }