use of org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.description.type.TypeDescription in project incubator-skywalking by apache.
the class SkyWalkingAgent method premain.
/**
* Main entrance.
* Use byte-buddy transform to enhance all classes, which define in plugins.
*
* @param agentArgs
* @param instrumentation
* @throws PluginException
*/
public static void premain(String agentArgs, Instrumentation instrumentation) throws PluginException {
final PluginFinder pluginFinder;
try {
SnifferConfigInitializer.initialize();
pluginFinder = new PluginFinder(new PluginBootstrap().loadPlugins());
ServiceManager.INSTANCE.boot();
} catch (Exception e) {
logger.error(e, "Skywalking agent initialized failure. Shutting down.");
return;
}
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
ServiceManager.INSTANCE.shutdown();
}
}, "skywalking service shutdown thread"));
new AgentBuilder.Default().type(pluginFinder.buildMatch()).transform(new AgentBuilder.Transformer() {
@Override
public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription, ClassLoader classLoader, JavaModule module) {
List<AbstractClassEnhancePluginDefine> pluginDefines = pluginFinder.find(typeDescription, classLoader);
if (pluginDefines.size() > 0) {
DynamicType.Builder<?> newBuilder = builder;
EnhanceContext context = new EnhanceContext();
for (AbstractClassEnhancePluginDefine define : pluginDefines) {
DynamicType.Builder<?> possibleNewBuilder = define.define(typeDescription.getTypeName(), newBuilder, classLoader, context);
if (possibleNewBuilder != null) {
newBuilder = possibleNewBuilder;
}
}
if (context.isEnhanced()) {
logger.debug("Finish the prepare stage for {}.", typeDescription.getName());
}
return newBuilder;
}
logger.debug("Matched class {}, but ignore by finding mechanism.", typeDescription.getTypeName());
return builder;
}
}).with(new AgentBuilder.Listener() {
@Override
public void onDiscovery(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded) {
}
@Override
public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded, DynamicType dynamicType) {
if (logger.isDebugEnable()) {
logger.debug("On Transformation class {}.", typeDescription.getName());
}
InstrumentDebuggingClass.INSTANCE.log(typeDescription, dynamicType);
}
@Override
public void onIgnored(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded) {
}
@Override
public void onError(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded, Throwable throwable) {
logger.error("Enhance class " + typeName + " error.", throwable);
}
@Override
public void onComplete(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded) {
}
}).installOn(instrumentation);
}
use of org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.description.type.TypeDescription in project neo4j by neo4j.
the class ProcedureJarLoaderTest method shouldLogHelpfullyWhenJarContainsClassTriggeringVerifyError.
@Test
void shouldLogHelpfullyWhenJarContainsClassTriggeringVerifyError() throws Exception {
String className = "BrokenProcedureClass";
// generate a class that is broken and would not normally compile
DynamicType.Unloaded<Object> unloaded = new ByteBuddy().with(new NamingStrategy.AbstractBase() {
@Override
protected String name(TypeDescription superClass) {
return className;
}
}).subclass(Object.class).defineMethod("get", String.class).intercept(// String is not assignable from int -- this triggers a VerifyError when the class is loaded
MethodCall.invoke(Integer.class.getMethod("valueOf", int.class)).with(42).withAssigner((source, target, typing) -> StackManipulation.Trivial.INSTANCE, Assigner.Typing.STATIC)).make();
URL jar = unloaded.toJar(testDirectory.createFile(new Random().nextInt() + ".jar").toFile()).toURI().toURL();
AssertableLogProvider logProvider = new AssertableLogProvider(true);
ProcedureJarLoader jarloader = new ProcedureJarLoader(procedureCompiler(), logProvider.getLog(ProcedureJarLoader.class));
jarloader.loadProceduresFromDir(parentDir(jar));
assertThat(logProvider).containsMessages(format("Failed to load `%s` from plugin jar `%s`: %s", className, jar.getFile(), "Bad return type"));
}
use of org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.description.type.TypeDescription in project beam by apache.
the class ByteBuddyUtils method createCollectionTransformFunction.
// When processing a container (e.g. List<T>) we need to recursively process the element type.
// This function
// generates a subclass of Function that can be used to recursively transform each element of the
// container.
static Class createCollectionTransformFunction(Type fromType, Type toType, Function<StackManipulation, StackManipulation> convertElement) {
// Generate a TypeDescription for the class we want to generate.
TypeDescription.Generic functionGenericType = TypeDescription.Generic.Builder.parameterizedType(Function.class, Primitives.wrap((Class) fromType), Primitives.wrap((Class) toType)).build();
DynamicType.Builder<Function> builder = (DynamicType.Builder<Function>) BYTE_BUDDY.with(new InjectPackageStrategy((Class) fromType)).subclass(functionGenericType).method(ElementMatchers.named("apply")).intercept(new Implementation() {
@Override
public ByteCodeAppender appender(Target target) {
return (methodVisitor, implementationContext, instrumentedMethod) -> {
// this + method parameters.
int numLocals = 1 + instrumentedMethod.getParameters().size();
StackManipulation readValue = MethodVariableAccess.REFERENCE.loadFrom(1);
StackManipulation stackManipulation = new StackManipulation.Compound(convertElement.apply(readValue), MethodReturn.REFERENCE);
StackManipulation.Size size = stackManipulation.apply(methodVisitor, implementationContext);
return new ByteCodeAppender.Size(size.getMaximalSize(), numLocals);
};
}
@Override
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return instrumentedType;
}
});
return builder.visit(new AsmVisitorWrapper.ForDeclaredMethods().writerFlags(ClassWriter.COMPUTE_FRAMES)).make().load(ReflectHelpers.findClassLoader(((Class) fromType).getClassLoader()), ClassLoadingStrategy.Default.INJECTION).getLoaded();
}
use of org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.description.type.TypeDescription in project hibernate-orm by hibernate.
the class FieldReaderAppender method apply.
@Override
public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext, MethodDescription instrumentedMethod) {
TypeDescription dispatcherType = persistentField.getType().isPrimitive() ? persistentField.getType().asErasure() : TypeDescription.OBJECT;
// if ( this.$$_hibernate_getInterceptor() != null )
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, managedCtClass.getInternalName(), EnhancerConstants.INTERCEPTOR_GETTER_NAME, Type.getMethodDescriptor(Type.getType(PersistentAttributeInterceptor.class)), false);
Label skip = new Label();
methodVisitor.visitJumpInsn(Opcodes.IFNULL, skip);
// this (for field write)
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
// this.$$_hibernate_getInterceptor();
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, managedCtClass.getInternalName(), EnhancerConstants.INTERCEPTOR_GETTER_NAME, Type.getMethodDescriptor(Type.getType(PersistentAttributeInterceptor.class)), false);
// .readXXX( self, fieldName, field );
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
methodVisitor.visitLdcInsn(persistentField.getName());
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
fieldRead(methodVisitor);
methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PersistentAttributeInterceptor.class), "read" + EnhancerImpl.capitalize(dispatcherType.getSimpleName()), Type.getMethodDescriptor(Type.getType(dispatcherType.getDescriptor()), Type.getType(Object.class), Type.getType(String.class), Type.getType(dispatcherType.getDescriptor())), true);
// field = (cast) XXX
if (!dispatcherType.isPrimitive()) {
methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, persistentField.getType().asErasure().getInternalName());
}
fieldWrite(methodVisitor);
// end if
methodVisitor.visitLabel(skip);
if (implementationContext.getClassFileVersion().isAtLeast(ClassFileVersion.JAVA_V6)) {
methodVisitor.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
}
// return field
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
fieldRead(methodVisitor);
methodVisitor.visitInsn(Type.getType(persistentField.getType().asErasure().getDescriptor()).getOpcode(Opcodes.IRETURN));
return new Size(4 + persistentField.getType().getStackSize().getSize(), instrumentedMethod.getStackSize());
}
use of org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.description.type.TypeDescription in project hibernate-orm by hibernate.
the class FieldWriterAppender method apply.
@Override
public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext, MethodDescription instrumentedMethod) {
TypeDescription dispatcherType = persistentField.getType().isPrimitive() ? persistentField.getType().asErasure() : TypeDescription.OBJECT;
// if ( this.$$_hibernate_getInterceptor() != null )
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, managedCtClass.getInternalName(), EnhancerConstants.INTERCEPTOR_GETTER_NAME, Type.getMethodDescriptor(Type.getType(PersistentAttributeInterceptor.class)), false);
Label noInterceptor = new Label();
methodVisitor.visitJumpInsn(Opcodes.IFNULL, noInterceptor);
// this (for field write)
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
// this.$$_hibernate_getInterceptor();
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, managedCtClass.getInternalName(), EnhancerConstants.INTERCEPTOR_GETTER_NAME, Type.getMethodDescriptor(Type.getType(PersistentAttributeInterceptor.class)), false);
// .writeXXX( self, fieldName, field, arg1 );
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
methodVisitor.visitLdcInsn(persistentField.getName());
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
fieldRead(methodVisitor);
methodVisitor.visitVarInsn(Type.getType(dispatcherType.getDescriptor()).getOpcode(Opcodes.ILOAD), 1);
methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PersistentAttributeInterceptor.class), "write" + EnhancerImpl.capitalize(dispatcherType.getSimpleName()), Type.getMethodDescriptor(Type.getType(dispatcherType.getDescriptor()), Type.getType(Object.class), Type.getType(String.class), Type.getType(dispatcherType.getDescriptor()), Type.getType(dispatcherType.getDescriptor())), true);
// arg1 = (cast) XXX
if (!dispatcherType.isPrimitive()) {
methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, persistentField.getType().asErasure().getInternalName());
}
fieldWrite(methodVisitor);
// return
methodVisitor.visitInsn(Opcodes.RETURN);
// else
methodVisitor.visitLabel(noInterceptor);
if (implementationContext.getClassFileVersion().isAtLeast(ClassFileVersion.JAVA_V6)) {
methodVisitor.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
}
// this (for field write)
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
// arg1 = (cast) XXX
methodVisitor.visitVarInsn(Type.getType(dispatcherType.getDescriptor()).getOpcode(Opcodes.ILOAD), 1);
if (!dispatcherType.isPrimitive()) {
methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, persistentField.getType().asErasure().getInternalName());
}
fieldWrite(methodVisitor);
// return
methodVisitor.visitInsn(Opcodes.RETURN);
return new Size(4 + 2 * persistentField.getType().getStackSize().getSize(), instrumentedMethod.getStackSize());
}
Aggregations