java.lang.instrument.UnmodifiableClassException Java Examples

The following examples show how to use java.lang.instrument.UnmodifiableClassException. 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: ConstructorInstrumenter.java    From allocation-instrumenter with Apache License 2.0 6 votes vote down vote up
/**
 * Ensures that the given sampler will be invoked every time a constructor for class c is invoked.
 *
 * @param c The class to be tracked
 * @param sampler the code to be invoked when an instance of c is constructed
 * @throws UnmodifiableClassException if c cannot be modified.
 */
public static void instrumentClass(Class<?> c, ConstructorCallback<?> sampler)
    throws UnmodifiableClassException {
  // IMPORTANT: Don't forget that other threads may be accessing this
  // class while this code is running.  Specifically, the class may be
  // executed directly after the retransformClasses is called.  Thus, we need
  // to be careful about what happens after the retransformClasses call.
  synchronized (samplerPutAtomicityLock) {
    List<ConstructorCallback<?>> list = samplerMap.get(c);
    if (list == null) {
      CopyOnWriteArrayList<ConstructorCallback<?>> samplerList =
          new CopyOnWriteArrayList<ConstructorCallback<?>>();
      samplerList.add(sampler);
      samplerMap.put(c, samplerList);
      Instrumentation inst = AllocationRecorder.getInstrumentation();
      Class<?>[] cs = new Class<?>[1];
      cs[0] = c;
      inst.retransformClasses(c);
    } else {
      list.add(sampler);
    }
  }
}
 
Example #2
Source File: TestJDWPAgentDebug.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testBadModification2() throws ClassNotFoundException, AgentLoadException, AgentInitializationException, IOException, AttachNotSupportedException, UnmodifiableClassException, IllegalConnectorArgumentsException {
    // Rewrite method
    DynamicModification badModification = new DynamicModification() {
        public Collection<String> affects() {
            return Lists.newArrayList(TestJDWPAgentDebug.class.getName());
        }
        public void apply(ClassPool arg0) throws NotFoundException, CannotCompileException {
            CtClass cls = arg0.getCtClass(TestJDWPAgentDebug.class.getName());
            cls.getMethods()[0].insertBefore("definitely not code...");
        }
    };
    JDWPAgent dynamic = JDWPAgent.get();
    // Modification should just be ignored since it throws a notfoundexception
    try {
        dynamic.install(badModification);
        fail();
    } catch (CannotCompileException e) {
    }
}
 
Example #3
Source File: TestJVMAgent.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testBadModification2() throws ClassNotFoundException, AgentLoadException, AgentInitializationException, IOException, AttachNotSupportedException, UnmodifiableClassException {
    // Rewrite method
    DynamicModification badModification = new DynamicModification() {
        public Collection<String> affects() {
            return Lists.newArrayList(TestJVMAgent.class.getName());
        }
        public void apply(ClassPool arg0) throws NotFoundException, CannotCompileException {
            CtClass cls = arg0.getCtClass(TestJVMAgent.class.getName());
            cls.getMethods()[0].insertBefore("definitely not code...");
        }
    };
    JVMAgent dynamic = JVMAgent.get();
    // Modification should just be ignored since it throws a notfoundexception
    try {
        dynamic.install(badModification);
        fail();
    } catch (CannotCompileException e) {
    }
}
 
Example #4
Source File: InstrumentationResource.java    From Recaf with MIT License 6 votes vote down vote up
/**
 * Saves changed by retransforming classes.
 *
 * @throws ClassNotFoundException
 * 		When the modified class couldn't be found.
 * @throws UnmodifiableClassException
 * 		When the modified class is not allowed to be modified.
 * @throws ClassFormatError
 * 		When the modified class is not valid.
 */
public void save() throws ClassNotFoundException, UnmodifiableClassException, ClassFormatError {
	// Classes to update
	Set<String> dirty = new HashSet<>(getDirtyClasses());
	if(dirty.isEmpty()) {
		Log.info("There are no classes to redefine.", dirty.size());
		return;
	}
	Log.info("Preparing to redefine {} classes", dirty.size());
	ClassDefinition[] definitions = new ClassDefinition[dirty.size()];
	int i = 0;
	for (String name : dirty) {
		String clsName = name.replace('/', '.');
		Class<?> cls = Class.forName(clsName, false, ClasspathUtil.scl);
		byte[] value = getClasses().get(name);
		if (value == null)
			throw new IllegalStateException("Failed to fetch code for class: " + name);
		definitions[i] = new ClassDefinition(cls, value);
		i++;
	}
	// Apply new definitions
	instrumentation.redefineClasses(definitions);
	// We don't want to continually re-apply changes that don't need to be updated
	getDirtyClasses().clear();
	Log.info("Successfully redefined {} classes", definitions.length);
}
 
Example #5
Source File: Agent.java    From javan-warty-pig with MIT License 6 votes vote down vote up
protected void init(boolean retransformBootstrapped) {
  // Add self as transfomer
  inst.addTransformer(this, inst.isRetransformClassesSupported());

  // Retransform all non-ignored classes
  if (retransformBootstrapped && inst.isRetransformClassesSupported()) {
    List<Class<?>> classesToRetransform = new ArrayList<>();
    for (Class<?> cls : inst.getAllLoadedClasses()) {
      if (inst.isModifiableClass(cls) && !isClassIgnored(cls)) classesToRetransform.add(cls);
    }
    if (!classesToRetransform.isEmpty()) {
      try {
        inst.retransformClasses(classesToRetransform.toArray(new Class<?>[classesToRetransform.size()]));
      } catch (UnmodifiableClassException e) {
        System.out.println("Failed retransforming classes: " + e);
      }
    }
  }
}
 
Example #6
Source File: TestMethodRewriteModification.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testBadTracepoint() throws ClassNotFoundException, UnmodifiableClassException, CannotCompileException {
    // Create and register dummy advice
    PTAgentForTest test = new PTAgentForTest();
    AdviceImplForTest advice = new AdviceImplForTest();
    int lookupId = test.agent.adviceManager.register(advice);

    // Method under test
    MethodTracepointSpec t1 = TracepointsTestUtils.getMethodSpec(getClass(), "method");
    MethodTracepointSpec tbad = MethodTracepointSpec.newBuilder(t1).setMethodName("badmethod").build();

    // Invoke method - should do nothing before rewrite
    method("hi");
    advice.expectSize(0);

    // Rewrite method
    MethodRewriteModification mod = new MethodRewriteModification(tbad, lookupId);

    test.agent.dynamic.clear().add(mod).install();
    advice.expectSize(0);

    method("hi");
    advice.expectSize(0);
}
 
Example #7
Source File: MainAgent.java    From COLA with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static void agentmain(String agentArgs, Instrumentation inst)
    throws ClassNotFoundException, UnmodifiableClassException,
    InterruptedException {
    final ColaTransformer transformer = new ColaTransformer(convert(agentArgs));
    if(!isLock(transformer)){
        return;
    }
    try {
        inst.addTransformer(transformer, true);
        Set<Class<?>> oriClassSet = searchClass(inst, transformer.getArgs().getClassName(), 1000);
        final Class<?>[] classArray = new Class<?>[oriClassSet.size()];
        System.arraycopy(oriClassSet.toArray(), 0, classArray, 0, oriClassSet.size());
        inst.retransformClasses(classArray);
    }finally {
        inst.removeTransformer(transformer);
    }
    System.out.println("agentmain DONE");
}
 
Example #8
Source File: TestLambdaFormRetransformation.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void premain(String args, Instrumentation instrumentation) {
    if (!instrumentation.isRetransformClassesSupported()) {
        System.out.println("Class retransformation is not supported.");
        return;
    }
    System.out.println("Calling lambda to ensure that lambda forms were created");

    Agent.lambda.run();

    System.out.println("Registering class file transformer");

    instrumentation.addTransformer(new Agent());

    for (Class c : instrumentation.getAllLoadedClasses()) {
        if (c.getName().contains("LambdaForm") &&
            instrumentation.isModifiableClass(c)) {
            System.out.format("We've found a modifiable lambda form: %s%n", c.getName());
            try {
                instrumentation.retransformClasses(c);
            } catch (UnmodifiableClassException e) {
                throw new AssertionError("Modification of modifiable class " +
                                         "caused UnmodifiableClassException", e);
            }
        }
    }
}
 
Example #9
Source File: ConstructorInstrumenter.java    From allocation-instrumenter with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public byte[] transform(
    ClassLoader loader,
    String className,
    Class<?> classBeingRedefined,
    ProtectionDomain protectionDomain,
    byte[] classfileBuffer) {
  if ((classBeingRedefined == null) || (!samplerMap.containsKey(classBeingRedefined))) {
    return null;
  }
  if (!AllocationInstrumenter.canRewriteClass(className, loader)) {
    throw new RuntimeException(new UnmodifiableClassException("cannot instrument " + className));
  }
  return instrument(classfileBuffer, classBeingRedefined);
}
 
Example #10
Source File: ConstructorInstrumenter.java    From allocation-instrumenter with Apache License 2.0 6 votes vote down vote up
/** Inserts the appropriate INVOKESTATIC call */
@Override
public void visitInsn(int opcode) {
  if ((opcode == Opcodes.ARETURN)
      || (opcode == Opcodes.IRETURN)
      || (opcode == Opcodes.LRETURN)
      || (opcode == Opcodes.FRETURN)
      || (opcode == Opcodes.DRETURN)) {
    throw new RuntimeException(
        new UnmodifiableClassException("Constructors are supposed to return void"));
  }
  if (opcode == Opcodes.RETURN) {
    super.visitVarInsn(Opcodes.ALOAD, 0);
    super.visitMethodInsn(
        Opcodes.INVOKESTATIC,
        "com/google/monitoring/runtime/instrumentation/ConstructorInstrumenter",
        "invokeSamplers",
        "(Ljava/lang/Object;)V",
        false);
  }
  super.visitInsn(opcode);
}
 
Example #11
Source File: ConstructorInstrumenterTest.java    From allocation-instrumenter with Apache License 2.0 6 votes vote down vote up
@Test
public void testThreads() throws UnmodifiableClassException {
  final BasicFunctions bf = new BasicFunctions();
  ConstructorInstrumenter.instrumentClass(
      Thread.class,
      new ConstructorCallback<Thread>() {
        @Override
        public void sample(Thread t) {
          bf.count++;
        }
      });
  int numThreads = 10;
  for (int i = 0; i < numThreads; i++) {
    Thread unused = new Thread();
  }
  assertEquals("Did not see correct number of Threads", numThreads, bf.count);
}
 
Example #12
Source File: ConstructorInstrumenterTest.java    From allocation-instrumenter with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasicFunctionality() throws UnmodifiableClassException {
  final BasicFunctions bf = new BasicFunctions();
  ConstructorInstrumenter.instrumentClass(
      BasicFunctions.class,
      new ConstructorCallback<BasicFunctions>() {
        @Override
        public void sample(BasicFunctions newBf) {
          bf.count++;
        }
      });
  int numBFs = 10;
  for (int i = 0; i < numBFs; i++) {
    BasicFunctions unused = new BasicFunctions();
  }
  assertEquals("Did not see correct number of BasicFunctions", numBFs, bf.count);
}
 
Example #13
Source File: ConstructorInstrumenterTest.java    From allocation-instrumenter with Apache License 2.0 6 votes vote down vote up
@Test
public void testSubclassesAlso() throws UnmodifiableClassException {
  final BasicFunctions bf = new BasicFunctions();
  ConstructorInstrumenter.instrumentClass(
      BasicFunctions.class,
      new ConstructorCallback<BasicFunctions>() {
        @Override
        public void sample(BasicFunctions newBf) {
          bf.count++;
        }
      });

  int numBFs = 2;
  new SubclassOfBasicFunctions();
  new BasicFunctions() {};
  assertEquals("Did not see correct number of BasicFunctions", numBFs, bf.count);
}
 
Example #14
Source File: DefaultDebugger.java    From bistoury with GNU General Public License v3.0 6 votes vote down vote up
private boolean instrument(String source, Location realLocation, ResolvedSourceLocation location) throws UnmodifiableClassException, ClassNotFoundException {
    if (instrumented.contains(realLocation)) {
        return true;
    }

    ClassFileTransformer transformer = new DebuggerClassFileTransformer(instrumentInfo.getClassFileBuffer(), source, location);
    try {
        Class<?> clazz = instrumentInfo.signatureToClass(location.getClassSignature());
        inst.addTransformer(transformer, true);
        inst.retransformClasses(clazz);
        instrumented.add(realLocation);
        instrumentInfo.addTransformedClasses(clazz);
        return true;
    } finally {
        inst.removeTransformer(transformer);
    }
}
 
Example #15
Source File: Hotswaper.java    From Voovan with Apache License 2.0 6 votes vote down vote up
/**
 * 重新热加载Class
 * @param clazzDefines 有过变更的文件信息
 * @throws UnmodifiableClassException  不可修改的 Class 异常
 * @throws ClassNotFoundException Class未找到异常
 */
public static void reloadClass(Map<Class, byte[]> clazzDefines) throws UnmodifiableClassException, ClassNotFoundException {

    for(Map.Entry<Class, byte[]> clazzDefine : clazzDefines.entrySet()){
        Class clazz = clazzDefine.getKey();
        byte[] classBytes = clazzDefine.getValue();

        ClassDefinition classDefinition = new ClassDefinition(clazz, classBytes);
        try {
            Logger.info("[HOTSWAP] class:" + clazz + " will reload.");
            TEnv.instrumentation.redefineClasses(classDefinition);
        } catch (Exception e) {
            Logger.error("[HOTSWAP] class:" + clazz + " reload failed", e);
        }
    }
}
 
Example #16
Source File: Hotswaper.java    From Voovan with Apache License 2.0 5 votes vote down vote up
/**
 * 重新热加载Class
 * @param changedFiles 有过变更的文件信息
 * @throws UnmodifiableClassException  不可修改的 Class 异常
 * @throws ClassNotFoundException Class未找到异常
 */
public void reloadClass(List<ClassFileInfo> changedFiles) throws UnmodifiableClassException, ClassNotFoundException {
    HashMap<Class, byte[]> classDefines = new HashMap<Class, byte[]>();
    for(ClassFileInfo classFileInfo : changedFiles) {
        classDefines.put(classFileInfo.getClazz(), classFileInfo.getBytes());
    }

    reloadClass(classDefines);
}
 
Example #17
Source File: TestMethodRewriteModification.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testBadTracepoint2() throws ClassNotFoundException, UnmodifiableClassException {
    // Create and register dummy advice
    PTAgentForTest test = new PTAgentForTest();
    AdviceImplForTest advice = new AdviceImplForTest();
    int lookupId = test.agent.adviceManager.register(advice);

    // Method under test
    MethodTracepointSpec t1 = TracepointsTestUtils.getMethodSpec(getClass(), "method");
    Builder tbad = MethodTracepointSpec.newBuilder(t1);
    tbad.addAdviceArgBuilder().setLiteral("definitely a bad literal");

    // Invoke method - should do nothing before rewrite
    method("hi");
    advice.expectSize(0);

    // Rewrite method
    MethodRewriteModification mod = new MethodRewriteModification(tbad.build(), lookupId);
    boolean expectedExceptionThrown = false;
    try {
        test.agent.dynamic.clear().add(mod).install();
    } catch (CannotCompileException e) {
        expectedExceptionThrown = true;
    } finally {
        if (!expectedExceptionThrown) {
            fail();
        }
    }
    advice.expectSize(0);

    method("hi");
    advice.expectSize(0);
}
 
Example #18
Source File: TestMethodRewriteModification.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Rewrite a method with collection args, configure advice invocation as collection */
@Test
public void testCollectionRewriteModification()
        throws ClassNotFoundException, UnmodifiableClassException, CannotCompileException {
    // Create and register dummy advice
    PTAgentForTest test = new PTAgentForTest();
    AdviceImplForTest advice = new AdviceImplForTest();
    int lookupId = test.agent.adviceManager.register(advice);

    // Method under test
    MethodTracepointSpec t1 = TracepointsTestUtils.getMethodSpec(getClass(), "collectionMethod");

    // Invoke method - should do nothing before rewrite
    collectionMethod(Lists.newArrayList("beeee", "hi"), "aaa");
    advice.expectSize(0);

    // Instrument method
    MethodRewriteModification mod = new MethodRewriteModification(t1, lookupId);

    test.agent.dynamic.clear().add(mod).install();
    advice.expectSize(0);

    collectionMethod(Lists.newArrayList("beeee"), "hello?");
    advice.expectSize(1);
    advice.expect(0, "beeee", "hello?");

    collectionMethod(Lists.<String> newArrayList(), "three");
    advice.expectSize(1);
    advice.expect(0, "beeee", "hello?");

    collectionMethod(Lists.newArrayList("one", "two"), "three");
    advice.expectSize(3);
    advice.expect(1, "one", "three");
    advice.expect(2, "two", "three");
}
 
Example #19
Source File: RedefineAnnotations.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private void testTransformAndVerify()
    throws NoSuchFieldException, NoSuchMethodException {

    Class<TypeAnnotatedTestClass> c = TypeAnnotatedTestClass.class;
    Class<?> myClass = c;

    /*
     * Verify that the expected annotations are where they should be before transform.
     */
    verifyClassTypeAnnotations(c);
    verifyFieldTypeAnnotations(c);
    verifyMethodTypeAnnotations(c);

    try {
        inst.addTransformer(new Transformer(), true);
        inst.retransformClasses(myClass);
    } catch (UnmodifiableClassException e) {
        throw new RuntimeException(e);
    }

    /*
     * Verify that the expected annotations are where they should be after transform.
     * Also verify that before and after are equal.
     */
    verifyClassTypeAnnotations(c);
    verifyFieldTypeAnnotations(c);
    verifyMethodTypeAnnotations(c);
}
 
Example #20
Source File: TestMethodRewriteModification.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Simple method rewrite with primitive args, make sure they are boxed */
@Test
public void testPrimitiveRewriteModification()
        throws ClassNotFoundException, UnmodifiableClassException, CannotCompileException {
    // Create and register dummy advice
    PTAgentForTest test = new PTAgentForTest();
    AdviceImplForTest advice = new AdviceImplForTest();
    int lookupId = test.agent.adviceManager.register(advice);

    // Method under test
    MethodTracepointSpec t1 = TracepointsTestUtils.getMethodSpec(getClass(), "primitive");

    // Invoke method - should do nothing before rewrite
    method("hi");
    advice.expectSize(0);

    // Rewrite method
    MethodRewriteModification mod = new MethodRewriteModification(t1, lookupId);
    test.agent.dynamic.add(mod).install();;
    advice.expectSize(0);

    int count = 0;
    for (int i = 0; i < 100; i++) {
        advice.expectSize(count++);
        primitive(i * 2);
        advice.expectSize(count);
        for (int j = 0; j < count; j++) {
            advice.expect(j, j * 2);
        }
    }
}
 
Example #21
Source File: TestJDWPAgentDebug.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testBadModification() throws ClassNotFoundException, AgentLoadException, AgentInitializationException, IOException, AttachNotSupportedException, UnmodifiableClassException, CannotCompileException, IllegalConnectorArgumentsException {
    // Rewrite method
    DynamicModification badModification = new DynamicModification() {
        public Collection<String> affects() {
            return Lists.newArrayList(TestJDWPAgentDebug.class.getName());
        }
        public void apply(ClassPool arg0) throws NotFoundException, CannotCompileException {
            arg0.getCtClass("edu.brown.cs.systems.pivottracing.dynamicinstrumentation.NotaRealClass");
        }
    };
    JDWPAgent dynamic = JDWPAgent.get();
    // Modification should just be ignored since it throws a notfoundexception
    dynamic.install(badModification);
}
 
Example #22
Source File: JVMAgent.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Do the transformation */
public void transform() throws UnmodifiableClassException {
    instrumentation.addTransformer(this, true);
    try {
        Class<?>[] classList = classdata.keySet().toArray(new Class<?>[classdata.size()]);
        instrumentation.retransformClasses(classList);
    } finally {
        instrumentation.removeTransformer(this);
    }
}
 
Example #23
Source File: DynamicManager.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void install() throws CannotCompileException, UnmodifiableClassException {
    if (agent != null) {
        problems.clear();
        agent.install(pending.changes(), problems);
        pending.persist();
    }
}
 
Example #24
Source File: Enhancer.java    From bistoury with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 重置指定的Class
 *
 * @param inst             inst
 * @param classNameMatcher 类名匹配
 * @return 增强影响范围
 * @throws UnmodifiableClassException
 */
public static synchronized EnhancerAffect reset(
        final Instrumentation inst,
        final Matcher classNameMatcher) throws UnmodifiableClassException {

    final EnhancerAffect affect = new EnhancerAffect();
    final Set<Class<?>> enhanceClassSet = new HashSet<Class<?>>();

    for (Class<?> classInCache : classBytesCache.keySet()) {
        if (classNameMatcher.matching(classInCache.getName())) {
            enhanceClassSet.add(classInCache);
        }
    }

    final ClassFileTransformer resetClassFileTransformer = new ClassFileTransformer() {
        @Override
        public byte[] transform(
                ClassLoader loader,
                String className,
                Class<?> classBeingRedefined,
                ProtectionDomain protectionDomain,
                byte[] classfileBuffer) throws IllegalClassFormatException {
            return null;
        }
    };

    try {
        enhance(inst, resetClassFileTransformer, enhanceClassSet);
        logger.info("Success to reset classes: " + enhanceClassSet);
    } finally {
        for (Class<?> resetClass : enhanceClassSet) {
            classBytesCache.remove(resetClass);
            affect.cCnt(1);
        }
    }

    return affect;
}
 
Example #25
Source File: Agent.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Install the provided modifications.  If a class is unknown, its modification is ignored, but if the provided modifications
 * cannot compile then exceptions will be thrown */
public void install(Map<String, Collection<DynamicModification>> modifications, Collection<Throwable> problems) throws CannotCompileException, UnmodifiableClassException {
    Installation i = new Installation();
    i.modifyAll(modifications, problems);
    if (!i.reloadMap.isEmpty()) {
        log.info("Reloading {} classes: {}", modifications.size(), modifications.keySet());
        reload(i.reloadMap);
    }
}
 
Example #26
Source File: Agent.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Install the provided modifications, deriving the affected classes from the modifications */
public void install(Collection<? extends DynamicModification> modifications) throws UnmodifiableClassException, CannotCompileException {
    Multimap<String, DynamicModification> modificationsByClass = HashMultimap.create();
    for (DynamicModification modification : modifications) {
        for (String className : modification.affects()) {
            modificationsByClass.put(className, modification);
        }
    }
    install(modificationsByClass.asMap());
}
 
Example #27
Source File: Agent.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Reload original class definition */
public void reset(Collection<String> classNames) throws UnmodifiableClassException, CannotCompileException {
    Map<String, Collection<DynamicModification>> modifications = Maps.newHashMap();
    for (String className : classNames) {
        modifications.put(className, new HashSet<DynamicModification>());
    }
    install(modifications);
}
 
Example #28
Source File: TestMethodRewriteModification.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Simple method rewrite */
@Test
public void testMethodRewriteModification()
        throws ClassNotFoundException, UnmodifiableClassException, CannotCompileException {
    // Create and register dummy advice
    PTAgentForTest test = new PTAgentForTest();
    AdviceImplForTest advice = new AdviceImplForTest();
    int lookupId = test.agent.adviceManager.register(advice);

    // Method under test
    MethodTracepointSpec t1 = TracepointsTestUtils.getMethodSpec(getClass(), "method");

    // Invoke method - should do nothing before rewrite
    method("hi");
    advice.expectSize(0);

    // Rewrite method
    MethodRewriteModification mod = new MethodRewriteModification(t1, lookupId);
    test.agent.dynamic.clear().add(mod).install();
    advice.expectSize(0);

    String[] testStrings = { "hello", "a", "bbbbb", "c", "bbbbb", "xyz", "#(@F", "hello" };
    int count = 0;
    for (String testString : testStrings) {
        advice.expectSize(count++);
        method(testString);
        advice.expectSize(count);
        for (int i = 0; i < count; i++) {
            advice.expect(i, testStrings[i]);
        }
    }
}
 
Example #29
Source File: RedefineAnnotations.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void testTransformAndVerify()
    throws NoSuchFieldException, NoSuchMethodException {

    Class<TypeAnnotatedTestClass> c = TypeAnnotatedTestClass.class;
    Class<?> myClass = c;

    /*
     * Verify that the expected annotations are where they should be before transform.
     */
    verifyClassTypeAnnotations(c);
    verifyFieldTypeAnnotations(c);
    verifyMethodTypeAnnotations(c);

    try {
        inst.addTransformer(new Transformer(), true);
        inst.retransformClasses(myClass);
    } catch (UnmodifiableClassException e) {
        throw new RuntimeException(e);
    }

    /*
     * Verify that the expected annotations are where they should be after transform.
     * Also verify that before and after are equal.
     */
    verifyClassTypeAnnotations(c);
    verifyFieldTypeAnnotations(c);
    verifyMethodTypeAnnotations(c);
}
 
Example #30
Source File: RedefineAnnotations.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private void testTransformAndVerify()
    throws NoSuchFieldException, NoSuchMethodException {

    Class<TypeAnnotatedTestClass> c = TypeAnnotatedTestClass.class;
    Class<?> myClass = c;

    /*
     * Verify that the expected annotations are where they should be before transform.
     */
    verifyClassTypeAnnotations(c);
    verifyFieldTypeAnnotations(c);
    verifyMethodTypeAnnotations(c);

    try {
        inst.addTransformer(new Transformer(), true);
        inst.retransformClasses(myClass);
    } catch (UnmodifiableClassException e) {
        throw new RuntimeException(e);
    }

    /*
     * Verify that the expected annotations are where they should be after transform.
     * Also verify that before and after are equal.
     */
    verifyClassTypeAnnotations(c);
    verifyFieldTypeAnnotations(c);
    verifyMethodTypeAnnotations(c);
}