net.bytebuddy.agent.builder.AgentBuilder.RedefinitionStrategy Java Examples

The following examples show how to use net.bytebuddy.agent.builder.AgentBuilder.RedefinitionStrategy. 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: ElasticApmAgent.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
/**
 * Reverts instrumentation of classes and re-transforms them to their state without the agent.
 * <p>
 * NOTE: THIS IS ONLY TO BE USED FOR UNIT TESTS
 * NOTE2: THIS METHOD MUST BE CALLED AFTER AGENT WAS INITIALIZED
 * </p>
 */
public static synchronized void reset() {
    if (instrumentation == null) {
        return;
    }

    if (resettableClassFileTransformer == null) {
        throw new IllegalStateException("Reset was called before init");
    }
    dynamicallyInstrumentedClasses.clear();
    resettableClassFileTransformer.reset(instrumentation, RedefinitionStrategy.RETRANSFORMATION);
    resettableClassFileTransformer = null;
    for (ResettableClassFileTransformer transformer : dynamicClassFileTransformers) {
        transformer.reset(instrumentation, RedefinitionStrategy.RETRANSFORMATION);
    }
    dynamicClassFileTransformers.clear();
    instrumentation = null;
}
 
Example #2
Source File: ByteBuddyManager.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
private AgentBuilder newBuilder(final Instrumentation inst, final PluginManifest pluginManifest, final Event[] events) {
  // Prepare the builder to be used to implement transformations in AgentRule(s)
  AgentBuilder agentBuilder = new Default(byteBuddy);
  if (Adapter.tracerClassLoader != null)
    agentBuilder = agentBuilder.ignore(any(), is(Adapter.tracerClassLoader));

  agentBuilder = agentBuilder
    .ignore(nameStartsWith("net.bytebuddy.").or(nameStartsWith("sun.reflect.")).or(isSynthetic()), any(), any())
    .disableClassFormatChanges()
    .with(RedefinitionStrategy.RETRANSFORMATION)
    .with(InitializationStrategy.NoOp.INSTANCE)
    .with(TypeStrategy.Default.REDEFINE)
    .with(bootFallbackLocationStrategy);

  if (inst == null)
    return agentBuilder;

  if (pluginManifest != null)
    return agentBuilder.with(new TransformationListener(inst, pluginManifest, events));

  if (transformationListener == null)
    transformationListener = new TransformationListener(inst, null, events);

  return agentBuilder.with(transformationListener);
}
 
Example #3
Source File: ElasticApmAgent.java    From apm-agent-java with Apache License 2.0 4 votes vote down vote up
private static AgentBuilder getAgentBuilder(final ByteBuddy byteBuddy, final CoreConfiguration coreConfiguration, Logger logger, AgentBuilder.DescriptionStrategy descriptionStrategy, boolean premain) {
    AgentBuilder.LocationStrategy locationStrategy = AgentBuilder.LocationStrategy.ForClassLoader.WEAK;
    if (agentJarFile != null) {
        try {
            locationStrategy =
                ((AgentBuilder.LocationStrategy.ForClassLoader) locationStrategy).withFallbackTo(
                    ClassFileLocator.ForJarFile.of(agentJarFile),
                    new RootPackageCustomLocator("java.", ClassFileLocator.ForClassLoader.ofBootLoader())
                );
        } catch (IOException e) {
            logger.warn("Failed to add ClassFileLocator for the agent jar. Some instrumentations may not work", e);
        }
    }
    return new AgentBuilder.Default(byteBuddy)
        .with(RedefinitionStrategy.RETRANSFORMATION)
        // when runtime attaching, only retransform up to 100 classes at once and sleep 100ms in-between as retransformation causes a stop-the-world pause
        .with(premain ? RedefinitionStrategy.BatchAllocator.ForTotal.INSTANCE : RedefinitionStrategy.BatchAllocator.ForFixedSize.ofSize(100))
        .with(premain ? RedefinitionStrategy.Listener.NoOp.INSTANCE : RedefinitionStrategy.Listener.Pausing.of(100, TimeUnit.MILLISECONDS))
        .with(descriptionStrategy)
        .with(locationStrategy)
        .with(new ErrorLoggingListener())
        // ReaderMode.FAST as we don't need to read method parameter names
        .with(coreConfiguration.isTypePoolCacheEnabled()
            ? new SoftlyReferencingTypePoolCache(TypePool.Default.ReaderMode.FAST, 1, isReflectionClassLoader())
            : AgentBuilder.PoolStrategy.Default.FAST)
        .ignore(any(), isReflectionClassLoader())
        .or(any(), classLoaderWithName("org.codehaus.groovy.runtime.callsite.CallSiteClassLoader"))
        // ideally, those bootstrap classpath inclusions should be set at plugin level, see issue #952
        .or(nameStartsWith("java.")
            .and(
                not(
                    nameEndsWith("URLConnection")
                        .or(nameStartsWith("java.util.concurrent."))
                        .or(named("java.lang.ProcessBuilder"))
                        .or(named("java.lang.ProcessImpl"))
                        .or(named("java.lang.Process"))
                        .or(named("java.lang.UNIXProcess"))
                )
            )
        )
        .or(nameStartsWith("com.sun.")
            .and(
                not(
                    nameStartsWith("com.sun.faces.")
                        .or(nameEndsWith("URLConnection"))
                )
            )
        )
        .or(nameStartsWith("sun")
            .and(
                not(nameEndsWith("URLConnection"))
            )
        )
        .or(nameStartsWith("co.elastic.apm.agent.shaded"))
        .or(nameStartsWith("org.aspectj."))
        .or(nameStartsWith("org.groovy."))
        .or(nameStartsWith("com.p6spy."))
        .or(nameStartsWith("net.bytebuddy."))
        .or(nameStartsWith("org.stagemonitor."))
        .or(nameStartsWith("com.newrelic."))
        .or(nameStartsWith("com.dynatrace."))
        // AppDynamics
        .or(nameStartsWith("com.singularity."))
        .or(nameStartsWith("com.instana."))
        .or(nameStartsWith("datadog."))
        .or(nameStartsWith("org.glowroot."))
        .or(nameStartsWith("com.compuware."))
        .or(nameStartsWith("io.sqreen."))
        .or(nameStartsWith("com.contrastsecurity."))
        .or(nameContains("javassist"))
        .or(nameContains(".asm."))
        .or(anyMatch(coreConfiguration.getDefaultClassesExcludedFromInstrumentation()))
        .or(anyMatch(coreConfiguration.getClassesExcludedFromInstrumentation()))
        .disableClassFormatChanges();
}
 
Example #4
Source File: BlockHound.java    From BlockHound with Apache License 2.0 4 votes vote down vote up
private void instrument(Instrumentation instrumentation) {
    ClassFileTransformer transformer = new NativeWrappingClassFileTransformer(blockingMethods);
    instrumentation.addTransformer(transformer, true);
    instrumentation.setNativeMethodPrefix(transformer, PREFIX);

    new AgentBuilder.Default()
            .with(RedefinitionStrategy.RETRANSFORMATION)
            // Explicit strategy is almost 2 times faster than SinglePass
            // TODO https://github.com/raphw/byte-buddy/issues/715
            .with(new DiscoveryStrategy.Explicit(
                    Stream
                            .of(instrumentation.getAllLoadedClasses())
                            .filter(it -> it.getName() != null)
                            .filter(it -> {
                                if (allowances.containsKey(it.getName())) {
                                    return true;
                                }

                                String internalClassName = it.getName().replace(".", "/");
                                if (blockingMethods.containsKey(internalClassName)) {
                                    return true;
                                }

                                return false;
                            })
                            .toArray(Class[]::new)
            ))
            .with(TypeStrategy.Default.DECORATE)
            .with(InitializationStrategy.NoOp.INSTANCE)
            // this DescriptionStrategy is required to force ByteBuddy to parse the bytes
            // and not cache them, since we run another transformer (see NativeWrappingClassFileTransformer)
            // before ByteBuddy
            .with(DescriptionStrategy.Default.POOL_FIRST)
            // Override PoolStrategy because the default one will cache java.lang.Object,
            // and we need to instrument it.
            .with((PoolStrategy) (classFileLocator, classLoader) -> new TypePool.Default(
                    new CacheProvider.Simple(),
                    classFileLocator,
                    TypePool.Default.ReaderMode.FAST
            ))
            .with(AgentBuilder.Listener.StreamWriting.toSystemError().withErrorsOnly())

            // Do not ignore JDK classes
            .ignore(ElementMatchers.none())

            // Instrument blocking calls
            .type(it -> blockingMethods.containsKey(it.getInternalName()))
            .transform(new BlockingCallsByteBuddyTransformer(blockingMethods))
            .asTerminalTransformation()

            // Instrument allowed/disallowed methods
            .type(it -> allowances.containsKey(it.getName()))
            .transform(new AllowancesByteBuddyTransformer(allowances))
            .asTerminalTransformation()

            .installOn(instrumentation);
}