/
AgentBuilder.java
3310 lines (2909 loc) · 147 KB
/
AgentBuilder.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package net.bytebuddy.agent.builder;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.ClassFileLocator;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.dynamic.loading.ClassInjector;
import net.bytebuddy.dynamic.scaffold.inline.MethodRebaseResolver;
import net.bytebuddy.implementation.Implementation;
import net.bytebuddy.implementation.LoadedTypeInitializer;
import net.bytebuddy.implementation.auxiliary.AuxiliaryType;
import net.bytebuddy.implementation.bytecode.ByteCodeAppender;
import net.bytebuddy.implementation.bytecode.Removal;
import net.bytebuddy.implementation.bytecode.StackManipulation;
import net.bytebuddy.implementation.bytecode.collection.ArrayFactory;
import net.bytebuddy.implementation.bytecode.constant.ClassConstant;
import net.bytebuddy.implementation.bytecode.constant.IntegerConstant;
import net.bytebuddy.implementation.bytecode.constant.NullConstant;
import net.bytebuddy.implementation.bytecode.constant.TextConstant;
import net.bytebuddy.implementation.bytecode.member.MethodInvocation;
import net.bytebuddy.matcher.ElementMatcher;
import net.bytebuddy.pool.TypePool;
import org.objectweb.asm.MethodVisitor;
import java.io.File;
import java.io.PrintStream;
import java.lang.instrument.ClassDefinition;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.ProtectionDomain;
import java.util.*;
import static net.bytebuddy.matcher.ElementMatchers.*;
/**
* <p>
* An agent builder provides a convenience API for defining a
* <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/instrument/package-summary.html">Java agent</a>. By default,
* this transformation is applied by rebasing the type if not specified otherwise by setting a
* {@link TypeStrategy}.
* </p>
* <p>
* When defining several {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s, the agent builder always
* applies the transformers that were supplied with the last applicable matcher. Therefore, more general transformers
* should be defined first.
* </p>
*/
public interface AgentBuilder {
/**
* Matches a type being loaded in order to apply the supplied
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s before loading this type.
*
* @param matcher A matcher that decides if the entailed
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s should be applied for a type that
* is being loaded.
* @return A definable that represents this agent builder which allows for the definition of one or several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s to be applied when the given {@code matcher}
* indicates a match.
*/
Identified type(RawMatcher matcher);
/**
* Matches a type being loaded in order to apply the supplied
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s before loading this type.
*
* @param typeMatcher An {@link net.bytebuddy.matcher.ElementMatcher} that is applied on the type being loaded that
* decides if the entailed
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s should be applied for that
* type.
* @return A definable that represents this agent builder which allows for the definition of one or several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s to be applied when the given {@code typeMatcher}
* indicates a match.
*/
Identified type(ElementMatcher<? super TypeDescription> typeMatcher);
/**
* Matches a type being loaded in order to apply the supplied
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s before loading this type.
*
* @param typeMatcher An {@link net.bytebuddy.matcher.ElementMatcher} that is applied on the type being
* loaded that decides if the entailed
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s should be applied for
* that type.
* @param classLoaderMatcher An {@link net.bytebuddy.matcher.ElementMatcher} that is applied to the
* {@link java.lang.ClassLoader} that is loading the type being loaded. This matcher
* is always applied first where the type matcher is not applied in case that this
* matcher does not indicate a match.
* @return A definable that represents this agent builder which allows for the definition of one or several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s to be applied when both the given
* {@code typeMatcher} and {@code classLoaderMatcher} indicate a match.
*/
Identified type(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher);
/**
* Defines the given {@link net.bytebuddy.ByteBuddy} instance to be used by the created agent.
*
* @param byteBuddy The Byte Buddy instance to be used.
* @return A new instance of this agent builder which makes use of the given {@code byteBuddy} instance.
*/
AgentBuilder withByteBuddy(ByteBuddy byteBuddy);
/**
* Defines the given {@link net.bytebuddy.agent.builder.AgentBuilder.Listener} to be notified by the created agent.
* The given listener is notified after any other listener that is already registered. If a listener is registered
* twice, it is also notified twice.
*
* @param listener The listener to be notified.
* @return A new instance of this agent builder which creates an agent that informs the given listener about
* events.
*/
AgentBuilder withListener(Listener listener);
/**
* Defines the use of the given binary locator for locating binary data to given class names.
*
* @param binaryLocator The binary locator to use.
* @return A new instance of this agent builder which uses the given binary locator for looking up class files.
*/
AgentBuilder withBinaryLocator(BinaryLocator binaryLocator);
/**
* Defines the use of the given definition handler that determines if a type should be rebased or redefined.
*
* @param typeStrategy The definition handler to use.
* @return A new instance of this agent builder which uses the given definition handler.
*/
AgentBuilder withTypeStrategy(TypeStrategy typeStrategy);
/**
* Enables the use of the given native method prefix for instrumented methods. Note that this prefix is also
* applied when preserving non-native methods. The use of this prefix is also registered when installing the
* final agent with an {@link java.lang.instrument.Instrumentation}.
*
* @param prefix The prefix to be used.
* @return A new instance of this agent builder which uses the given native method prefix.
*/
AgentBuilder withNativeMethodPrefix(String prefix);
/**
* Disables the use of a native method prefix for instrumented methods.
*
* @return A new instance of this agent builder which does not use a native method prefix.
*/
AgentBuilder withoutNativeMethodPrefix();
/**
* Defines classes to be loaded using the given access control context.
*
* @param accessControlContext The access control context to be used for loading classes.
* @return A new instance of this agent builder which uses the given access control context for class loading.
*/
AgentBuilder withAccessControlContext(AccessControlContext accessControlContext);
/**
* Defines a given initialization strategy to be applied to generated types. An initialization strategy is responsible
* for setting up a type after it was loaded. This initialization must be performed after the transformation because
* a Java agent is only invoked before loading a type. By default, the initialization logic is added to a class's type
* initializer which queries a global object for any objects that are to be injected into the generated type.
*
* @param initializationStrategy The initialization strategy to use.
* @return A new instance of this agent builder that applies the given initialization strategy.
*/
AgentBuilder withInitializationStrategy(InitializationStrategy initializationStrategy);
/**
* Specifies a strategy for modifying existing types.
*
* @param redefinitionStrategy The redefinition strategy to apply.
* @return A new instance of this agent builder that applies the given redefinition strategy.
*/
AgentBuilder withRedefinitionStrategy(RedefinitionStrategy redefinitionStrategy);
/**
* Enables class injection of auxiliary classes into the bootstrap class loader.
*
* @param folder The folder in which jar files of the injected classes are to be stored.
* @param instrumentation The instrumentation instance that is used for appending jar files to the
* bootstrap class path.
* @return An agent builder with bootstrap class loader class injection enabled.
*/
AgentBuilder enableBootstrapInjection(File folder, Instrumentation instrumentation);
/**
* Disables injection of auxiliary classes into the bootstrap class path.
*
* @return An agent builder with bootstrap class loader class injection disabled.
*/
AgentBuilder disableBootstrapInjection();
/**
* Creates a {@link java.lang.instrument.ClassFileTransformer} that implements the configuration of this
* agent builder.
*
* @return A class file transformer that implements the configuration of this agent builder.
*/
ClassFileTransformer makeRaw();
/**
* Creates and installs a {@link java.lang.instrument.ClassFileTransformer} that implements the configuration of
* this agent builder with a given {@link java.lang.instrument.Instrumentation}. If retransformation is enabled,
* the installation also causes all loaded types to be retransformed.
*
* @param instrumentation The instrumentation on which this agent builder's configuration is to be installed.
* @return The installed class file transformer.
*/
ClassFileTransformer installOn(Instrumentation instrumentation);
/**
* Creates and installs a {@link java.lang.instrument.ClassFileTransformer} that implements the configuration of
* this agent builder with the Byte Buddy-agent which must be installed prior to calling this method.
*
* @return The installed class file transformer.
*/
ClassFileTransformer installOnByteBuddyAgent();
/**
* Describes an {@link net.bytebuddy.agent.builder.AgentBuilder} which was handed a matcher for identifying
* types to instrumented in order to supply one or several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s.
*/
interface Identified {
/**
* Applies the given transformer for the already supplied matcher.
*
* @param transformer The transformer to apply.
* @return This agent builder with the transformer being applied when the previously supplied matcher
* identified a type for instrumentation which also allows for the registration of subsequent transformers.
*/
Extendable transform(Transformer transformer);
/**
* This interface is used to allow for optionally providing several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer} to applied when a matcher identifies a type
* to be instrumented. Any subsequent transformers are applied in the order they are registered.
*/
interface Extendable extends AgentBuilder, Identified {
/* this is merely a unionizing interface that does not declare methods */
}
}
/**
* A matcher that allows to determine if a {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}
* should be applied during the execution of a {@link java.lang.instrument.ClassFileTransformer} that was
* generated by an {@link net.bytebuddy.agent.builder.AgentBuilder}.
*/
interface RawMatcher {
/**
* Decides if the given {@code typeDescription} should be instrumented with the entailed
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s.
*
* @param typeDescription A description of the type to be instrumented.
* @param classLoader The class loader of the instrumented type. Might be {@code null} if this class
* loader represents the bootstrap class loader.
* @param classBeingRedefined The class being redefined which is only not {@code null} if a retransformation
* is applied.
* @param protectionDomain The protection domain of the type being transformed.
* @return {@code true} if the entailed {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s should
* be applied for the given {@code typeDescription}.
*/
boolean matches(TypeDescription typeDescription,
ClassLoader classLoader,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain);
/**
* A raw matcher implementation that checks a {@link TypeDescription}
* and its {@link java.lang.ClassLoader} against two suitable matchers in order to determine if the matched
* type should be instrumented.
*/
class ForElementMatcherPair implements RawMatcher {
/**
* The type matcher to apply to a {@link TypeDescription}.
*/
private final ElementMatcher<? super TypeDescription> typeMatcher;
/**
* The class loader to apply to a {@link java.lang.ClassLoader}.
*/
private final ElementMatcher<? super ClassLoader> classLoaderMatcher;
/**
* Creates a new {@link net.bytebuddy.agent.builder.AgentBuilder.RawMatcher} that only matches the
* supplied {@link TypeDescription} and its {@link java.lang.ClassLoader} against two matcher in order
* to decided if an instrumentation should be conducted.
*
* @param typeMatcher The type matcher to apply to a
* {@link TypeDescription}.
* @param classLoaderMatcher The class loader to apply to a {@link java.lang.ClassLoader}.
*/
public ForElementMatcherPair(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher) {
this.typeMatcher = typeMatcher;
this.classLoaderMatcher = classLoaderMatcher;
}
@Override
public boolean matches(TypeDescription typeDescription,
ClassLoader classLoader,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain) {
return classLoaderMatcher.matches(classLoader) && typeMatcher.matches(typeDescription);
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& classLoaderMatcher.equals(((ForElementMatcherPair) other).classLoaderMatcher)
&& typeMatcher.equals(((ForElementMatcherPair) other).typeMatcher);
}
@Override
public int hashCode() {
int result = typeMatcher.hashCode();
result = 31 * result + classLoaderMatcher.hashCode();
return result;
}
@Override
public String toString() {
return "AgentBuilder.RawMatcher.ForElementMatcherPair{" +
"typeMatcher=" + typeMatcher +
", classLoaderMatcher=" + classLoaderMatcher +
'}';
}
}
}
/**
* A type strategy is responsible for creating a type builder for a type that is being instrumented.
*/
interface TypeStrategy {
/**
* Creates a type builder for a given type.
*
* @param typeDescription The type being instrumented.
* @param byteBuddy The Byte Buddy configuration.
* @param classFileLocator The class file locator to use.
* @param methodNameTransformer The method name transformer to use.
* @return A type builder for the given arguments.
*/
DynamicType.Builder<?> builder(TypeDescription typeDescription,
ByteBuddy byteBuddy,
ClassFileLocator classFileLocator,
MethodRebaseResolver.MethodNameTransformer methodNameTransformer);
/**
* Default implementations of type strategies.
*/
enum Default implements TypeStrategy {
/**
* A definition handler that performs a rebasing for all types.
*/
REBASE {
@Override
public DynamicType.Builder<?> builder(TypeDescription typeDescription,
ByteBuddy byteBuddy,
ClassFileLocator classFileLocator,
MethodRebaseResolver.MethodNameTransformer methodNameTransformer) {
return byteBuddy.rebase(typeDescription, classFileLocator, methodNameTransformer);
}
},
/**
* A definition handler that performs a redefinition for all types.
*/
REDEFINE {
@Override
public DynamicType.Builder<?> builder(TypeDescription typeDescription,
ByteBuddy byteBuddy,
ClassFileLocator classFileLocator,
MethodRebaseResolver.MethodNameTransformer methodNameTransformer) {
return byteBuddy.redefine(typeDescription, classFileLocator);
}
};
@Override
public String toString() {
return "AgentBuilder.TypeStrategy.Default." + name();
}
}
}
/**
* A transformer allows to apply modifications to a {@link net.bytebuddy.dynamic.DynamicType}. Such a modification
* is then applied to any instrumented type that was matched by the preceding matcher.
*/
interface Transformer {
/**
* Allows for a transformation of a {@link net.bytebuddy.dynamic.DynamicType.Builder}.
*
* @param builder The dynamic builder to transform.
* @param typeDescription The description of the type currently being instrumented.
* @return A transformed version of the supplied {@code builder}.
*/
DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription);
/**
* A no-op implementation of a {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer} that does
* not modify the supplied dynamic type.
*/
enum NoOp implements Transformer {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription) {
return builder;
}
@Override
public String toString() {
return "AgentBuilder.Transformer.NoOp." + name();
}
}
/**
* A compound transformer that allows to group several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s as a single transformer.
*/
class Compound implements Transformer {
/**
* The transformers to apply in their application order.
*/
private final Transformer[] transformer;
/**
* Creates a new compound transformer.
*
* @param transformer The transformers to apply in their application order.
*/
public Compound(Transformer... transformer) {
this.transformer = transformer;
}
@Override
public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription) {
for (Transformer transformer : this.transformer) {
builder = transformer.transform(builder, typeDescription);
}
return builder;
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& Arrays.equals(transformer, ((Compound) other).transformer);
}
@Override
public int hashCode() {
return Arrays.hashCode(transformer);
}
@Override
public String toString() {
return "AgentBuilder.Transformer.Compound{" +
"transformer=" + Arrays.toString(transformer) +
'}';
}
}
}
/**
* A binary locator allows to specify how binary data is located by an
* {@link net.bytebuddy.agent.builder.AgentBuilder}.
*/
interface BinaryLocator {
/**
* Creates a class file locator for the given class loader.
*
* @param classLoader The class loader for which a class file locator should be created.
* Can be {@code null} to represent the bootstrap class loader.
* @return An appropriate class file locator.
*/
ClassFileLocator classFileLocator(ClassLoader classLoader);
/**
* Creates a type pool for a given class file locator.
*
* @param classFileLocator The class file locator to use.
* @param classLoader The class loader for which the class file locator was created.
* @return A type pool for the supplied class file locator.
*/
TypePool typePool(ClassFileLocator classFileLocator, ClassLoader classLoader);
/**
* A default implementation of a {@link net.bytebuddy.agent.builder.AgentBuilder.BinaryLocator} that
* is using a {@link net.bytebuddy.pool.TypePool.Default} with a
* {@link net.bytebuddy.pool.TypePool.CacheProvider.Simple} and a
* {@link net.bytebuddy.dynamic.ClassFileLocator.ForClassLoader}.
*/
enum Default implements BinaryLocator {
/**
* A binary locator that parses the code segment of each method for extracting information about parameter
* names even if they are not explicitly included in a class file.
*
* @see net.bytebuddy.pool.TypePool.Default.ReaderMode#EXTENDED
*/
EXTENDED(TypePool.Default.ReaderMode.EXTENDED),
/**
* A binary locator that skips the code segment of each method and does therefore not extract information
* about parameter names. Parameter names are still included if they are explicitly included in a class file.
*
* @see net.bytebuddy.pool.TypePool.Default.ReaderMode#FAST
*/
FAST(TypePool.Default.ReaderMode.FAST);
/**
* The reader mode to apply by this binary locator.
*/
private final TypePool.Default.ReaderMode readerMode;
/**
* Creates a new binary locator.
*
* @param readerMode The reader mode to apply by this binary locator.
*/
Default(TypePool.Default.ReaderMode readerMode) {
this.readerMode = readerMode;
}
@Override
public ClassFileLocator classFileLocator(ClassLoader classLoader) {
return ClassFileLocator.ForClassLoader.of(classLoader);
}
@Override
public TypePool typePool(ClassFileLocator classFileLocator, ClassLoader classLoader) {
return new TypePool.LazyFacade(TypePool.Default.Precomputed.withObjectType(new TypePool.CacheProvider.Simple(), classFileLocator, readerMode));
}
@Override
public String toString() {
return "AgentBuilder.BinaryLocator.Default." + name();
}
}
/**
* <p>
* A binary locator that loads referenced classes instead of describing unloaded versions.
* </p>
* <p>
* <b>Important</b>: It is important to never query this binary locator for the currently instrumented type as this will yield a class
* loading circularity which aborts any instrumentation with an error.
* </p>
* <p>
* <b>Warning</b>: Warning, this binary locator <i>cannot be used for applying a redefinition</i> as it works on loaded classes only and
* is agnostic of any way to locate a class file.
* </p>
*/
enum ClassLoading implements BinaryLocator {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public ClassFileLocator classFileLocator(ClassLoader classLoader) {
return ClassFileLocator.NoOp.INSTANCE;
}
@Override
public TypePool typePool(ClassFileLocator classFileLocator, ClassLoader classLoader) {
return new TypePool.LazyFacade(TypePool.Default.ClassLoading.of(classFileLocator, classLoader));
}
@Override
public String toString() {
return "AgentBuilder.BinaryLocator.ClassLoading." + name();
}
}
}
/**
* A listener that is informed about events that occur during an instrumentation process.
*/
interface Listener {
/**
* Invoked right before a successful transformation is applied.
*
* @param typeDescription The type that is being transformed.
* @param dynamicType The dynamic type that was created.
*/
void onTransformation(TypeDescription typeDescription, DynamicType dynamicType);
/**
* Invoked when a type is not transformed but ignored.
*
* @param typeDescription The type being ignored.
*/
void onIgnored(TypeDescription typeDescription);
/**
* Invoked when an error has occurred.
*
* @param typeName The binary name of the instrumented type.
* @param throwable The occurred error.
*/
void onError(String typeName, Throwable throwable);
/**
* Invoked after a class was attempted to be loaded, independently of its treatment.
*
* @param typeName The binary name of the instrumented type.
*/
void onComplete(String typeName);
/**
* A no-op implementation of a {@link net.bytebuddy.agent.builder.AgentBuilder.Listener}.
*/
enum NoOp implements Listener {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public void onTransformation(TypeDescription typeDescription, DynamicType dynamicType) {
/* do nothing */
}
@Override
public void onIgnored(TypeDescription typeDescription) {
/* do nothing */
}
@Override
public void onError(String typeName, Throwable throwable) {
/* do nothing */
}
@Override
public void onComplete(String typeName) {
/* do nothing */
}
@Override
public String toString() {
return "AgentBuilder.Listener.NoOp." + name();
}
}
/**
* A listener that writes events to a {@link PrintStream}. This listener prints a line per event, including the event type and
* the name of the type in question.
*/
class StreamWriting implements Listener {
/**
* The prefix that is appended to all written messages.
*/
protected static final String PREFIX = "[Byte Buddy]";
/**
* The print stream written to.
*/
private final PrintStream printStream;
/**
* Creates a new stream writing listener.
*
* @param printStream The print stream written to.
*/
public StreamWriting(PrintStream printStream) {
this.printStream = printStream;
}
/**
* Creates a new stream writing listener that writes to {@link System#out}.
*
* @return A listener writing events to the standard output stream.
*/
public static Listener toSystemOut() {
return new StreamWriting(System.out);
}
@Override
public void onTransformation(TypeDescription typeDescription, DynamicType dynamicType) {
printStream.println(PREFIX + " TRANSFORM " + typeDescription.getName());
}
@Override
public void onIgnored(TypeDescription typeDescription) {
printStream.println(PREFIX + " IGNORE " + typeDescription.getName());
}
@Override
public void onError(String typeName, Throwable throwable) {
printStream.println(PREFIX + " ERROR " + typeName);
throwable.printStackTrace(printStream);
}
@Override
public void onComplete(String typeName) {
printStream.println(PREFIX + " COMPLETE " + typeName);
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& printStream.equals(((StreamWriting) other).printStream);
}
@Override
public int hashCode() {
return printStream.hashCode();
}
@Override
public String toString() {
return "AgentBuilder.Listener.StreamWriting{" +
"printStream=" + printStream +
'}';
}
}
/**
* A compound listener that allows to group several listeners in one instance.
*/
class Compound implements Listener {
/**
* The listeners that are represented by this compound listener in their application order.
*/
private final List<? extends Listener> listeners;
/**
* Creates a new compound listener.
*
* @param listener The listeners to apply in their application order.
*/
public Compound(Listener... listener) {
this(Arrays.asList(listener));
}
/**
* Creates a new compound listener.
*
* @param listeners The listeners to apply in their application order.
*/
public Compound(List<? extends Listener> listeners) {
this.listeners = listeners;
}
@Override
public void onTransformation(TypeDescription typeDescription, DynamicType dynamicType) {
for (Listener listener : listeners) {
listener.onTransformation(typeDescription, dynamicType);
}
}
@Override
public void onIgnored(TypeDescription typeDescription) {
for (Listener listener : listeners) {
listener.onIgnored(typeDescription);
}
}
@Override
public void onError(String typeName, Throwable throwable) {
for (Listener listener : listeners) {
listener.onError(typeName, throwable);
}
}
@Override
public void onComplete(String typeName) {
for (Listener listener : listeners) {
listener.onComplete(typeName);
}
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& listeners.equals(((Compound) other).listeners);
}
@Override
public int hashCode() {
return listeners.hashCode();
}
@Override
public String toString() {
return "AgentBuilder.Listener.Compound{" +
"listeners=" + listeners +
'}';
}
}
}
/**
* An initialization strategy which determines the handling of {@link net.bytebuddy.implementation.LoadedTypeInitializer}s
* and the loading of auxiliary types.
*/
interface InitializationStrategy {
/**
* Creates a new dispatcher for injecting this initialization strategy during a transformation process.
*
* @return The dispatcher to be used.
*/
Dispatcher dispatcher();
/**
* A dispatcher for changing a class file to adapt a self-initialization strategy.
*/
interface Dispatcher {
/**
* Transforms the instrumented type to implement an appropriate initialization strategy.
*
* @param builder The builder which should implement the initialization strategy.
* @return The given {@code builder} with the initialization strategy applied.
*/
DynamicType.Builder<?> apply(DynamicType.Builder<?> builder);
/**
* Registers a dynamic type for initialization and/or begins the initialization process.
*
* @param dynamicType The dynamic type that is created.
* @param classLoader The class loader of the dynamic type.
* @param injectorFactory The injector factory
*/
void register(DynamicType dynamicType, ClassLoader classLoader, InjectorFactory injectorFactory);
/**
* A factory for creating a {@link ClassInjector} only if it is required.
*/
interface InjectorFactory {
/**
* Resolves the class injector for this factory.
*
* @return The class injector for this factory.
*/
ClassInjector resolve();
}
}
/**
* A non-initializing initialization strategy.
*/
enum NoOp implements InitializationStrategy, Dispatcher {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public Dispatcher dispatcher() {
return this;
}
@Override
public DynamicType.Builder<?> apply(DynamicType.Builder<?> builder) {
return builder;
}
@Override
public void register(DynamicType dynamicType, ClassLoader classLoader, InjectorFactory injectorFactory) {
/* do nothing */
}
@Override
public String toString() {
return "AgentBuilder.InitializationStrategy.NoOp." + name();
}
}
/**
* An initialization strategy that adds a code block to an instrumented type's type initializer which
* then calls a specific class that is responsible for the explicit initialization.
*/
enum SelfInjection implements InitializationStrategy {
/**
* A form of self-injection where auxiliary types that are a subtype of the instrumented type are loaded lazily and
* any other auxiliary type is loaded eagerly.
*/
SPLIT {
@Override
public InitializationStrategy.Dispatcher dispatcher() {
return new SelfInjection.Dispatcher.Split(random.nextInt());
}
},
/**
* A form of self-injection where any auxiliary type is loaded lazily.
*/
LAZY {
@Override
public InitializationStrategy.Dispatcher dispatcher() {
return new SelfInjection.Dispatcher.Lazy(random.nextInt());
}
},
/**
* A form of self-injection where any auxiliary type is loaded eagerly.
*/
EAGER {
@Override
public InitializationStrategy.Dispatcher dispatcher() {
return new SelfInjection.Dispatcher.Eager(random.nextInt());
}
};
/**
* A generator for random identification values.
*/
protected final Random random;
/**
* Creates the self-injection strategy.
*/
SelfInjection() {
random = new Random();
}
@Override
public String toString() {
return "AgentBuilder.InitializationStrategy.SelfInjection." + name();
}
/**
* A dispatcher for a self-initialization strategy.
*/
protected abstract static class Dispatcher implements InitializationStrategy.Dispatcher {
/**
* A random identification for the applied self-initialization.
*/
protected final int identification;
/**
* Creates a new dispatcher.
*
* @param identification A random identification for the applied self-initialization.
*/
protected Dispatcher(int identification) {
this.identification = identification;
}
@Override
public DynamicType.Builder<?> apply(DynamicType.Builder<?> builder) {
return builder.initializer(NexusAccessor.INSTANCE.identifiedBy(identification));
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& identification == ((Dispatcher) other).identification;
}
@Override
public int hashCode() {
return identification;
}
/**
* A dispatcher for the {@link net.bytebuddy.agent.builder.AgentBuilder.InitializationStrategy.SelfInjection#SPLIT} strategy.
*/
protected static class Split extends Dispatcher {
/**
* Creates a new split dispatcher.
*
* @param identification A random identification for the applied self-initialization.
*/
protected Split(int identification) {
super(identification);
}
@Override