byte-buddy icon indicating copy to clipboard operation
byte-buddy copied to clipboard

Do we need to sort the Map<String,byte[]> when ClassInjector#injectRaw(Map<String,byte[]> ?

Open leihuazhe opened this issue 2 years ago • 3 comments

Map<? extends String, byte[]> types

Here is my practice.

Map<String, Class<?>> injectRaw(Map<? extends String, byte[]> types);
image

I have A, B,C,D class. and A is extends B.

if in the ClassInjector#injectRaw method, A is before then B. when use ClassInjector defineClass A, JVM will go to find the B, because A is extends B, but now B isn't defined yet.

So should I use a LinkedMap to keep the B's byte arrray defintion is before then A. so the JVM can load B,then load A,it goes will.

otherwise, it will throw NoClassDefFoundError.

Thanks for guiding me, ignore the grammer mistakes.

leihuazhe avatar Aug 09 '22 17:08 leihuazhe

Added:

My bytebuddy version is 1.12.13

I loaded A,B's class from a jar separately, then put them to the Map<String,byte[]> classesTypeMap: ("A" -> byte[]) ("B" -> byte[]),the byte[] only on behalf of the A or B's compiled class file content.

then called:

ClassInjector.UsingUnsafe.Factory factory = ClassInjector.UsingUnsafe.Factory.resolve(instrumentation);

factory.make(null, null).injectRaw(classesTypeMap);

similar codes can find in: https://github.com/apache/skywalking-java/blob/main/apm-sniffer/apm-agent-core/src/main/java/org/apache/skywalking/apm/agent/core/plugin/bootstrap/BootstrapInstrumentBoost.java

leihuazhe avatar Aug 09 '22 17:08 leihuazhe

The injector injects classes in the order that is provided. If there is a dependency, you need to inject the classes in the required order.

If this is not feasible, injection does not work unfortunately as you cannot inject multiple classes at the same time. In this case, you'd need yo use UsingInstrumentation if you are targeting the boot or system loader. For all other class loaders, the only other option is a wrapper.

raphw avatar Aug 11 '22 17:08 raphw

Thanks a lot. It helps me a lot.

leihuazhe avatar Aug 16 '22 02:08 leihuazhe