List of usage examples for org.objectweb.asm.tree ClassNode accept
public void accept(final ClassVisitor classVisitor)
From source file:org.evosuite.instrumentation.BytecodeInstrumentation.java
License:Open Source License
/** * <p>/*from w ww. ja va 2 s . c o m*/ * transformBytes * </p> * * @param className * a {@link java.lang.String} object. * @param reader * a {@link org.objectweb.asm.ClassReader} object. * @return an array of byte. */ public byte[] transformBytes(ClassLoader classLoader, String className, ClassReader reader) { int readFlags = ClassReader.SKIP_FRAMES; if (Properties.INSTRUMENTATION_SKIP_DEBUG) readFlags |= ClassReader.SKIP_DEBUG; String classNameWithDots = ResourceList.getClassNameFromResourcePath(className); if (!checkIfCanInstrument(classNameWithDots)) { throw new RuntimeException("Should not transform a shared class (" + classNameWithDots + ")! Load by parent (JVM) classloader."); } TransformationStatistics.reset(); /* * To use COMPUTE_FRAMES we need to remove JSR commands. Therefore, we * have a JSRInlinerAdapter in NonTargetClassAdapter as well as * CFGAdapter. */ int asmFlags = ClassWriter.COMPUTE_FRAMES; ClassWriter writer = new ComputeClassWriter(asmFlags); ClassVisitor cv = writer; if (logger.isDebugEnabled()) { cv = new TraceClassVisitor(cv, new PrintWriter(System.err)); } if (Properties.RESET_STATIC_FIELDS) { cv = new StaticAccessClassAdapter(cv, className); } if (Properties.PURE_INSPECTORS) { CheapPurityAnalyzer purityAnalyzer = CheapPurityAnalyzer.getInstance(); cv = new PurityAnalysisClassVisitor(cv, className, purityAnalyzer); } if (Properties.MAX_LOOP_ITERATIONS >= 0) { cv = new LoopCounterClassAdapter(cv); } // Apply transformations to class under test and its owned classes if (DependencyAnalysis.shouldAnalyze(classNameWithDots)) { logger.debug("Applying target transformation to class " + classNameWithDots); if (!Properties.TEST_CARVING && Properties.MAKE_ACCESSIBLE) { cv = new AccessibleClassAdapter(cv, className); } cv = new RemoveFinalClassAdapter(cv); cv = new ExecutionPathClassAdapter(cv, className); cv = new CFGClassAdapter(classLoader, cv, className); if (Properties.EXCEPTION_BRANCHES) { cv = new ExceptionTransformationClassAdapter(cv, className); } if (Properties.ERROR_BRANCHES) { cv = new ErrorConditionClassAdapter(cv, className); } } else { logger.debug("Not applying target transformation"); cv = new NonTargetClassAdapter(cv, className); if (Properties.MAKE_ACCESSIBLE) { cv = new AccessibleClassAdapter(cv, className); } // If we are doing testability transformation on all classes we need // to create the CFG first if (Properties.TT && classNameWithDots.startsWith(Properties.CLASS_PREFIX)) { cv = new CFGClassAdapter(classLoader, cv, className); } } // Collect constant values for the value pool cv = new PrimitiveClassAdapter(cv, className); if (Properties.RESET_STATIC_FIELDS) { cv = handleStaticReset(className, cv); } // Mock instrumentation (eg File and TCP). if (TestSuiteWriterUtils.needToUseAgent()) { cv = new MethodCallReplacementClassAdapter(cv, className); } // Testability Transformations if (classNameWithDots.startsWith(Properties.PROJECT_PREFIX) || (!Properties.TARGET_CLASS_PREFIX.isEmpty() && classNameWithDots.startsWith(Properties.TARGET_CLASS_PREFIX)) || shouldTransform(classNameWithDots)) { ClassNode cn = new AnnotatedClassNode(); reader.accept(cn, readFlags); logger.info("Starting transformation of " + className); if (Properties.STRING_REPLACEMENT) { StringTransformation st = new StringTransformation(cn); if (isTargetClassName(classNameWithDots) || shouldTransform(classNameWithDots)) cn = st.transform(); } ComparisonTransformation cmp = new ComparisonTransformation(cn); if (isTargetClassName(classNameWithDots) || shouldTransform(classNameWithDots)) { cn = cmp.transform(); ContainerTransformation ct = new ContainerTransformation(cn); cn = ct.transform(); } if (shouldTransform(classNameWithDots)) { logger.info("Testability Transforming " + className); BooleanTestabilityTransformation tt = new BooleanTestabilityTransformation(cn, classLoader); try { cn = tt.transform(); } catch (Throwable t) { throw new Error(t); } logger.info("Testability Transformation done: " + className); } // ----- cn.accept(cv); if (Properties.TEST_CARVING && TransformerUtil.isClassConsideredForInstrumentation(className)) { return handleCarving(className, writer); } } else { reader.accept(cv, readFlags); } return writer.toByteArray(); }
From source file:org.evosuite.instrumentation.BytecodeInstrumentation.java
License:Open Source License
private byte[] handleCarving(String className, ClassWriter writer) { ClassReader cr = new ClassReader(writer.toByteArray()); ClassNode cn2 = new ClassNode(); cr.accept(cn2, ClassReader.EXPAND_FRAMES); this.testCarvingInstrumenter.transformClassNode(cn2, className); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); cn2.accept(cw); if (logger.isDebugEnabled()) { final StringWriter sw = new StringWriter(); cn2.accept(new TraceClassVisitor(new PrintWriter(sw))); logger.debug("test carving instrumentation result:\n{}", sw); }/*from w ww . j a v a2 s . c o m*/ return cw.toByteArray(); }
From source file:org.evosuite.instrumentation.testability.TestabilityTransformationClassLoader.java
License:Open Source License
private Class<?> instrumentClass(String fullyQualifiedTargetClass) throws ClassNotFoundException { logger.info("Instrumenting class '" + fullyQualifiedTargetClass + "'."); try {//from ww w . ja va2 s . c o m String className = fullyQualifiedTargetClass.replace('.', '/'); InputStream is = ResourceList.getInstance(TestGenerationContext.getInstance().getClassLoaderForSUT()) .getClassAsStream(className); if (is == null) { throw new ClassNotFoundException("Class '" + className + ".class" + "' should be in target project, but could not be found!"); } ClassReader reader = new ClassReader(is); ClassNode classNode = new ClassNode(); reader.accept(classNode, ClassReader.SKIP_FRAMES); ClassVisitor cv = new CFGClassAdapter(classLoader, null, className); classNode.accept(cv); BooleanTestabilityTransformation tt = new BooleanTestabilityTransformation(classNode, this); // cv = new TraceClassVisitor(writer, new // PrintWriter(System.out)); //cv = new TraceClassVisitor(cv, new PrintWriter(System.out)); //cv = new CheckClassAdapter(cv); try { //tt.transform().accept(cv); //if (isTargetClassName(classNameWithDots)) classNode = tt.transform(); } catch (Throwable t) { throw new Error(t); } ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES); classNode.accept(writer); byte[] byteBuffer = writer.toByteArray(); Class<?> result = defineClass(fullyQualifiedTargetClass, byteBuffer, 0, byteBuffer.length); classes.put(fullyQualifiedTargetClass, result); logger.info("Keeping class: " + fullyQualifiedTargetClass); return result; } catch (Throwable t) { throw new ClassNotFoundException(t.getMessage(), t); } }
From source file:org.evosuite.instrumentation.TestabilityTransformationClassLoader.java
License:Open Source License
private Class<?> instrumentClass(String fullyQualifiedTargetClass) throws ClassNotFoundException { logger.info("Instrumenting class '{}'.", fullyQualifiedTargetClass); try {// w w w. java 2 s . c o m String className = fullyQualifiedTargetClass.replace('.', '/'); InputStream is = ResourceList.getClassAsStream(className); if (is == null) { throw new ClassNotFoundException("Class '" + className + ".class" + "' should be in target project, but could not be found!"); } ClassReader reader = new ClassReader(is); ClassNode classNode = new ClassNode(); reader.accept(classNode, ClassReader.SKIP_FRAMES); ClassVisitor cv = new CFGClassAdapter(classLoader, null, className); classNode.accept(cv); BooleanTestabilityTransformation tt = new BooleanTestabilityTransformation(classNode, this); // cv = new TraceClassVisitor(writer, new // PrintWriter(System.out)); //cv = new TraceClassVisitor(cv, new PrintWriter(System.out)); //cv = new CheckClassAdapter(cv); try { //tt.transform().accept(cv); //if (isTargetClassName(classNameWithDots)) classNode = tt.transform(); } catch (Throwable t) { throw new Error(t); } ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES); classNode.accept(writer); byte[] byteBuffer = writer.toByteArray(); Class<?> result = defineClass(fullyQualifiedTargetClass, byteBuffer, 0, byteBuffer.length); classes.put(fullyQualifiedTargetClass, result); logger.info("Keeping class: {}", fullyQualifiedTargetClass); return result; } catch (Throwable t) { throw new ClassNotFoundException(t.getMessage(), t); } }
From source file:org.evosuite.runtime.instrumentation.RuntimeInstrumentation.java
License:Open Source License
public byte[] transformBytes(ClassLoader classLoader, String className, ClassReader reader, boolean skipInstrumentation) { String classNameWithDots = className.replace('/', '.'); if (!checkIfCanInstrument(classNameWithDots)) { throw new IllegalArgumentException("Should not transform a shared class (" + classNameWithDots + ")! Load by parent (JVM) classloader."); }/*from w w w . ja v a2 s . c o m*/ int asmFlags = ClassWriter.COMPUTE_FRAMES; ClassWriter writer = new ComputeClassWriter(asmFlags); ClassVisitor cv = writer; if (!skipInstrumentation) { if (RuntimeSettings.resetStaticState && !retransformingMode) { /* * FIXME: currently reset does add a new method, but that does no work * when retransformingMode :( */ CreateClassResetClassAdapter resetClassAdapter = new CreateClassResetClassAdapter(cv, className, true); cv = resetClassAdapter; } if (RuntimeSettings.isUsingAnyMocking()) { cv = new MethodCallReplacementClassAdapter(cv, className, !retransformingMode); } cv = new KillSwitchClassAdapter(cv); cv = new RemoveFinalClassAdapter(cv); if (RuntimeSettings.maxNumberOfIterationsPerLoop >= 0) { cv = new LoopCounterClassAdapter(cv); } } ClassNode cn = new AnnotatedClassNode(); int readFlags = ClassReader.SKIP_FRAMES; reader.accept(cn, readFlags); cv = new JSRInlinerClassVisitor(cv); try { cn.accept(cv); } catch (Throwable ex) { logger.error("Error while instrumenting class " + className + ": " + ex.getMessage(), ex); } return writer.toByteArray(); }
From source file:org.evosuite.testcarver.extraction.CarvingClassLoader.java
License:Open Source License
private Class<?> instrumentClass(String fullyQualifiedTargetClass) throws ClassNotFoundException { logger.warn("Instrumenting class '" + fullyQualifiedTargetClass + "'."); try {//from ww w.j av a 2 s . com String className = fullyQualifiedTargetClass.replace('.', '/'); InputStream is = ResourceList.getInstance(TestGenerationContext.getInstance().getClassLoaderForSUT()) .getClassAsStream(className); if (is == null) { throw new ClassNotFoundException("Class '" + className + ".class" + "' should be in target project, but could not be found!"); } ClassReader reader = new ClassReader(is); ClassNode classNode = new ClassNode(); reader.accept(classNode, ClassReader.SKIP_FRAMES); instrumenter.transformClassNode(classNode, className); ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES); classNode.accept(new JSRInlinerClassVisitor(writer)); //classNode.accept(writer); byte[] byteBuffer = writer.toByteArray(); Class<?> result = defineClass(fullyQualifiedTargetClass, byteBuffer, 0, byteBuffer.length); if (Modifier.isPrivate(result.getModifiers())) { logger.info("REPLACING PRIVATE CLASS " + fullyQualifiedTargetClass); result = super.loadClass(fullyQualifiedTargetClass); } classes.put(fullyQualifiedTargetClass, result); logger.info("Keeping class: " + fullyQualifiedTargetClass); return result; } catch (Throwable t) { logger.info("Error: " + t); for (StackTraceElement e : t.getStackTrace()) { logger.info(e.toString()); } throw new ClassNotFoundException(t.getMessage(), t); } }
From source file:org.evosuite.testcarver.instrument.Instrumenter.java
License:Open Source License
public byte[] instrument(final String className, final byte[] classfileBuffer) throws IllegalClassFormatException { logger.debug("Start instrumenting class {}", className); final ClassReader cr = new ClassReader(classfileBuffer); final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); final ClassNode cn = new ClassNode(); cr.accept(cn, ClassReader.SKIP_DEBUG); if (!TransformerUtil.isClassConsideredForInstrumentation(className)) { logger.debug("Class {} has not been instrumented because its name is on the blacklist", className); return classfileBuffer; }// w w w.j av a2s . c om try { this.transformClassNode(cn, className); cn.accept(cw); return cw.toByteArray(); } catch (final Throwable t) { logger.error("An error occurred while instrumenting class {} -> returning unmodified version", className, t); return classfileBuffer; } }
From source file:org.evosuite.testcarver.instrument.Instrumenter.java
License:Open Source License
@SuppressWarnings("unchecked") public void transformClassNode(ClassNode cn, final String internalClassName) { if (!TransformerUtil.isClassConsideredForInstrumentation(internalClassName)) { logger.debug("Class {} has not been instrumented because its name is on the blacklist", internalClassName);/*w w w . j av a 2 s .com*/ return; } // consider only public and protected classes which are not interfaces if ((cn.access & Opcodes.ACC_INTERFACE) != 0) { return; } // No private if ((cn.access & Opcodes.ACC_PRIVATE) != 0) { // TODO: Why is this not detecting $DummyIntegrator? logger.debug("Ignoring private class {}", cn.name); return; } String packageName = internalClassName.replace('/', '.'); if (packageName.contains(".")) packageName = packageName.substring(0, packageName.lastIndexOf('.')); // ASM has some problem with the access of inner classes // so we check if the inner class name is the current class name // and if so, check if the inner class is actually accessible List<InnerClassNode> in = cn.innerClasses; for (InnerClassNode inc : in) { if (cn.name.equals(inc.name)) { logger.info("ASM Bug: Inner class equals class."); if ((inc.access & Opcodes.ACC_PROTECTED) == Opcodes.ACC_PROTECTED) { if (!Properties.CLASS_PREFIX.equals(packageName)) { return; } } if ((inc.access & Opcodes.ACC_PRIVATE) == Opcodes.ACC_PRIVATE) { return; } logger.debug("Can use inner class {}", inc.name); } } logger.info("Checking package {} for class {}", packageName, cn.name); // Protected/default only if in same package if ((cn.access & Opcodes.ACC_PUBLIC) == 0) { if (!Properties.CLASS_PREFIX.equals(packageName)) { logger.info("Not using protected/default class because package name does not match"); return; } else { logger.info("Using protected/default class because package name matches"); } } /* if( (cn.access & Opcodes.ACC_PUBLIC) == 0 && (cn.access & Opcodes.ACC_PROTECTED) == 0) { return; } */ final ArrayList<MethodNode> wrappedMethods = new ArrayList<MethodNode>(); MethodNode methodNode; final Iterator<MethodNode> methodIter = cn.methods.iterator(); while (methodIter.hasNext()) { methodNode = methodIter.next(); // consider only public methods which are not abstract or native if (!TransformerUtil.isPrivate(methodNode.access) && !TransformerUtil.isAbstract(methodNode.access) && !TransformerUtil.isNative(methodNode.access) && !methodNode.name.equals("<clinit>")) { if (!TransformerUtil.isPublic(methodNode.access)) { //if(!Properties.CLASS_PREFIX.equals(packageName)) { transformWrapperCalls(methodNode); continue; //} } if (methodNode.name.equals("<init>")) { if (TransformerUtil.isAbstract(cn.access)) { // We cannot invoke constructors of abstract classes directly continue; } this.addFieldRegistryRegisterCall(methodNode); } this.instrumentPUTXXXFieldAccesses(cn, internalClassName, methodNode); this.instrumentGETXXXFieldAccesses(cn, internalClassName, methodNode); this.instrumentMethod(cn, internalClassName, methodNode, wrappedMethods); } else { transformWrapperCalls(methodNode); } } final int numWM = wrappedMethods.size(); for (int i = 0; i < numWM; i++) { cn.methods.add(wrappedMethods.get(i)); } TraceClassVisitor tcv = new TraceClassVisitor(new PrintWriter(System.err)); cn.accept(tcv); }
From source file:org.evosuite.testcarver.instrument.Transformer.java
License:Open Source License
@Override public byte[] transform(final ClassLoader loader, final String className, final Class<?> classBeingRedefined, final ProtectionDomain protectionDomain, final byte[] classFileBuffer) throws IllegalClassFormatException { logger.debug("transforming {}", className); if (!Capturer.isCapturing()) { logger.debug("class {} has not been transformed because Capturer is not active", className); return classFileBuffer; }/*from www .j av a 2 s.c o m*/ if (!TransformerUtil.isClassConsideredForInstrumenetation(className)) { logger.debug("class {} has not been instrumented because its name is on the blacklist", className); return classFileBuffer; } final ClassReader cr = new ClassReader(classFileBuffer); final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); final ClassNode cn = new ClassNode(); cr.accept(cn, ClassReader.SKIP_DEBUG); this.instrumenter.instrument(className, cn); cn.accept(cw); return cw.toByteArray(); }
From source file:org.friz.bytecode.refactor.Refactorer.java
License:Open Source License
private byte[] getClassNodeBytes(ClassNode cn) { ClassWriter cw = new ClassWriter(0); cn.accept(cw); byte[] b = cw.toByteArray(); return b;//from w ww. java 2 s. c o m }