List of usage examples for org.objectweb.asm.tree ClassNode ClassNode
public ClassNode()
From source file:org.apache.sling.maven.bundlesupport.GenerateAdapterMetadataMojo.java
License:Apache License
public void execute() throws MojoExecutionException, MojoFailureException { try {//www. j a va2 s . c om final JSONObject descriptor = new JSONObject(); final AnnotationDB annotationDb = new AnnotationDB(); annotationDb.scanArchives(buildOutputDirectory.toURI().toURL()); final Set<String> annotatedClassNames = new HashSet<String>(); addAnnotatedClasses(annotationDb, annotatedClassNames, Adaptable.class); addAnnotatedClasses(annotationDb, annotatedClassNames, Adaptables.class); for (final String annotatedClassName : annotatedClassNames) { getLog().info(String.format("found adaptable annotation on %s", annotatedClassName)); final String pathToClassFile = annotatedClassName.replace('.', '/') + ".class"; final File classFile = new File(buildOutputDirectory, pathToClassFile); final FileInputStream input = new FileInputStream(classFile); final ClassReader classReader; try { classReader = new ClassReader(input); } finally { input.close(); } final ClassNode classNode = new ClassNode(); classReader.accept(classNode, SKIP_CODE | SKIP_DEBUG | SKIP_FRAMES); @SuppressWarnings("unchecked") final List<AnnotationNode> annotations = classNode.invisibleAnnotations; for (final AnnotationNode annotation : annotations) { if (ADAPTABLE_DESC.equals(annotation.desc)) { parseAdaptableAnnotation(annotation, classNode, descriptor); } else if (ADAPTABLES_DESC.equals(annotation.desc)) { parseAdaptablesAnnotation(annotation, classNode, descriptor); } } } final File outputFile = new File(outputDirectory, fileName); outputFile.getParentFile().mkdirs(); final FileWriter writer = new FileWriter(outputFile); try { IOUtil.copy(descriptor.toString(JSON_INDENTATION), writer); } finally { IOUtil.close(writer); } addResource(); } catch (IOException e) { throw new MojoExecutionException("Unable to generate metadata", e); } catch (JSONException e) { throw new MojoExecutionException("Unable to generate metadata", e); } }
From source file:org.ballerinalang.compiler.backend.jvm.ClassVerifier.java
License:Open Source License
/** * This method is an extension of//from w ww . jav a 2 s.c o m * {@code jdk.internal.org.objectweb.asm.util.CheckClassAdapter#verify(ClassReader, boolean, java.io.PrintWriter)}. * * @param bytes Bytes stream of the class to be verified. * @return An optional error, if there are verification errors. */ private static Optional<ErrorValue> verify(byte[] bytes, ClassLoader classLoader) { ClassReader classReader = new ClassReader(bytes); ClassNode classNode = new ClassNode(); classReader.accept(new CheckClassAdapter(Opcodes.ASM7, classNode, false) { }, ClassReader.SKIP_DEBUG); Type syperType = classNode.superName == null ? null : Type.getObjectType(classNode.superName); List<MethodNode> methods = classNode.methods; List<Type> interfaces = new ArrayList<>(); for (String interfaceName : classNode.interfaces) { interfaces.add(Type.getObjectType(interfaceName)); } for (MethodNode method : methods) { SimpleVerifier verifier = new SimpleVerifier(Type.getObjectType(classNode.name), syperType, interfaces, (classNode.access & Opcodes.ACC_INTERFACE) != 0); Analyzer<BasicValue> analyzer = new Analyzer<>(verifier); if (classLoader != null) { verifier.setClassLoader(classLoader); } try { analyzer.analyze(classNode.name, method); } catch (AnalyzerException e) { return Optional.of(BallerinaErrors.createError(e.getMessage())); } } return Optional.empty(); }
From source file:org.brutusin.instrumentation.Instrumentator.java
License:Apache License
public byte[] modifyClass() { if (!this.interceptor.interceptClass(className, originalClassFileBuffer)) { return originalClassFileBuffer; }/*from w ww . j a v a 2 s.c o m*/ ClassReader cr = new ClassReader(originalClassFileBuffer); this.cn = new ClassNode(); cr.accept(cn, 0); this.classType = Type.getType("L" + cn.name + ";"); List<MethodNode> methods = cn.methods; boolean transformed = false; for (MethodNode node : methods) { if (modifyMethod(node) == true) { transformed = true; } } if (!transformed) { return originalClassFileBuffer; } ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); cn.accept(cw); return cw.toByteArray(); }
From source file:org.brutusin.instrumentation.utils.Helper.java
License:Apache License
public static void viewByteCode(byte[] bytecode) { ClassReader cr = new ClassReader(bytecode); ClassNode cn = new ClassNode(); cr.accept(cn, 0);//w w w. java 2 s . com final List<MethodNode> mns = cn.methods; Printer printer = new Textifier(); TraceMethodVisitor mp = new TraceMethodVisitor(printer); for (MethodNode mn : mns) { InsnList inList = mn.instructions; System.out.println(mn.name); for (int i = 0; i < inList.size(); i++) { inList.get(i).accept(mp); StringWriter sw = new StringWriter(); printer.print(new PrintWriter(sw)); printer.getText().clear(); System.out.print(sw.toString()); } } }
From source file:org.classdump.luna.compiler.gen.asm.ASMBytecodeEmitter.java
License:Apache License
public ASMBytecodeEmitter(IRFunc fn, SlotAllocInfo slots, TypeInfo types, DependencyInfo deps, CompilerSettings compilerSettings, ClassNameTranslator classNameTranslator, String sourceFile) { this.fn = Objects.requireNonNull(fn); this.slots = Objects.requireNonNull(slots); this.types = Objects.requireNonNull(types); this.deps = Objects.requireNonNull(deps); this.compilerSettings = Objects.requireNonNull(compilerSettings); this.classNameTranslator = Objects.requireNonNull(classNameTranslator); this.sourceFile = Objects.requireNonNull(sourceFile); classNode = new ClassNode(); this.fields = new ArrayList<>(); upvalueFieldNames = new HashMap<>(); String s = System.getProperty("org.classdump.luna.compiler.VerifyAndPrint"); verifyAndPrint = s != null && "true".equals(s.trim().toLowerCase()); }
From source file:org.codehaus.groovy.ant.VerifyClass.java
License:Apache License
private boolean readClass(String clazz) throws IOException { ClassReader cr = new ClassReader(new FileInputStream(clazz)); ClassNode ca = new ClassNode() { public void visitEnd() { //accept(cv); }/* w ww.ja va2s . co m*/ }; cr.accept(new CheckClassAdapter(ca), ClassWriter.COMPUTE_MAXS); boolean failed = false; List methods = ca.methods; for (int i = 0; i < methods.size(); ++i) { MethodNode method = (MethodNode) methods.get(i); if (method.instructions.size() > 0) { Analyzer a = new Analyzer(new SimpleVerifier()); try { a.analyze(ca.name, method); continue; } catch (Exception e) { e.printStackTrace(); } if (!failed) { failed = true; log("verifying of class " + clazz + " failed"); } if (verbose) log(method.name + method.desc); TraceMethodVisitor mv = new TraceMethodVisitor(null); /*= new TraceMethodVisitor(null) { public void visitMaxs(int maxStack, int maxLocals) { StringBuffer buffer = new StringBuffer(); for (int i = 0; i < text.size(); ++i) { String s = frames[i] == null ? "null" : frames[i].toString(); while (s.length() < maxStack + maxLocals + 1) { s += " "; } buffer.append(Integer.toString(i + 100000).substring(1)); buffer.append(" "); buffer.append(s); buffer.append(" : "); buffer.append(text.get(i)); } if (verbose) log(buffer.toString()); } };*/ for (int j = 0; j < method.instructions.size(); ++j) { Object insn = method.instructions.get(j); if (insn instanceof AbstractInsnNode) { ((AbstractInsnNode) insn).accept(mv); } else { mv.visitLabel((Label) insn); } } mv.visitMaxs(method.maxStack, method.maxLocals); } } return !failed; }
From source file:org.coldswap.util.ByteCodeGenerator.java
License:Open Source License
/** * Creates a new class containing the new static field. * * @param classNode containing the old class. * @param fieldNode containing the old field. * @param initInstructions a list of instructions that goes into <clinit>. * @param className the name of the new class to be generated. * @return an array of bytes which builds the new class. *//* www .ja v a 2 s.co m*/ @SuppressWarnings("unchecked") public static byte[] newFieldClass(ClassNode classNode, FieldNode fieldNode, InsnList initInstructions, String className) { ClassNode newClass = new ClassNode(); newClass.version = classNode.version; newClass.access = Opcodes.ACC_PUBLIC; newClass.signature = "L" + className + ";"; newClass.name = className; newClass.superName = "java/lang/Object"; newClass.fields.add( new FieldNode(fieldNode.access, fieldNode.name, fieldNode.desc, fieldNode.desc, fieldNode.value)); if (initInstructions != null) { if (initInstructions.size() > 0) { MethodNode mn = new MethodNode(Opcodes.ACC_STATIC, "<clinit>", "()V", null, null); InsnList il = mn.instructions; il.add(new LabelNode()); il.add(initInstructions); il.add(new FieldInsnNode(Opcodes.PUTSTATIC, className, fieldNode.name, fieldNode.desc)); il.add(new InsnNode(Opcodes.RETURN)); newClass.methods.add(mn); } } ClassWriter newCWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); newClass.accept(newCWriter); return newCWriter.toByteArray(); }
From source file:org.copperengine.core.wfrepo.AbstractWorkflowRepository.java
License:Apache License
void instrumentWorkflows(File adaptedTargetDir, Map<String, Clazz> clazzMap, Map<String, ClassInfo> classInfos, File compileTargetDir) throws IOException { logger.info("Instrumenting classfiles"); URLClassLoader tmpClassLoader = new URLClassLoader(new URL[] { compileTargetDir.toURI().toURL() }, Thread.currentThread().getContextClassLoader()); for (Clazz clazz : clazzMap.values()) { byte[] bytes; FileInputStream fis = new FileInputStream(clazz.classfile); try {//from w ww .j av a 2 s . c o m ClassReader cr2 = new ClassReader(fis); ClassNode cn = new ClassNode(); cr2.accept(cn, flags); // Now content of ClassNode can be modified and then serialized back into bytecode: new TryCatchBlockHandler().instrument(cn); ClassWriter cw2 = new ClassWriter(0); cn.accept(cw2); bytes = cw2.toByteArray(); if (logger.isTraceEnabled()) { StringWriter sw = new StringWriter(); new ClassReader(bytes).accept(new TraceClassVisitor(new PrintWriter(sw)), 0); logger.trace(sw.toString()); } ClassReader cr = new ClassReader(bytes); ClassWriter cw = new ClassWriter(0); ScottyClassAdapter cv = new ScottyClassAdapter(cw, clazz.aggregatedInterruptableMethods); cr.accept(cv, flags); classInfos.put(clazz.classname, cv.getClassInfo()); bytes = cw.toByteArray(); // Recompute frames, etc. ClassReader cr3 = new ClassReader(bytes); ClassWriter cw3 = new ClassWriter(ClassWriter.COMPUTE_FRAMES); cr3.accept(cw3, ClassReader.SKIP_FRAMES); bytes = cw3.toByteArray(); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); CheckClassAdapter.verify(new ClassReader(cw.toByteArray()), tmpClassLoader, false, pw); if (sw.toString().length() != 0) { logger.error("CheckClassAdapter.verify failed for class " + cn.name + ":\n" + sw.toString()); } else { logger.info("CheckClassAdapter.verify succeeded for class " + cn.name); } } finally { fis.close(); } File adaptedClassfileName = new File(adaptedTargetDir, clazz.classname + ".class"); adaptedClassfileName.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(adaptedClassfileName); try { fos.write(bytes); } finally { fos.close(); } } }
From source file:org.devinprogress.YAIF.Transformer.ASMHelper.java
public byte[] transform(String obfClassName, String className, byte[] bytes) { if (!map.containsKey(className)) return bytes; Map<String, Method> transMap = map.get(className); ClassReader cr = new ClassReader(bytes); ClassNode cn = new ClassNode(); cr.accept(cn, 0);/* ww w. j a v a 2s. c o m*/ for (MethodNode mn : cn.methods) { //System.out.println(String.format("Examing Method: %s%s",mn.name,mn.desc)); String methodName = FMLDeobfuscatingRemapper.INSTANCE.mapMethodName(obfClassName, mn.name, mn.desc); String methodDesc = FMLDeobfuscatingRemapper.INSTANCE.mapMethodDesc(mn.desc); if (transMap.containsKey(methodName + methodDesc)) { try { //System.out.println(String.format("Invoking Method: %s%s",mn.name,mn.desc)); transMap.get(methodName + methodDesc).invoke(obj, mn); } catch (Exception e) { e.printStackTrace(); return bytes; } } } ClassWriter cw = new ClassWriter(0); cn.accept(cw); return cw.toByteArray(); }
From source file:org.eclipse.pde.api.tools.internal.builder.ReferenceExtractor.java
License:Open Source License
/** * Constructor//from www . ja va 2 s. c o m * * @param type the type to extract references from * @param collector the listing of references to annotate from this pass * @param referenceKinds kinds of references to extract as defined by * {@link ReferenceModifiers} */ public ReferenceExtractor(IApiType type, Set<Reference> collector, int referenceKinds) { super(Opcodes.ASM5, new ClassNode()); fType = type; this.collector = collector; fReferenceKinds = referenceKinds; fIsVisitMembers = (VISIT_MEMBERS_MASK & fReferenceKinds) > 0; fieldtracker = new FieldTracker(this); }