/
Advice.java
9857 lines (8756 loc) · 476 KB
/
Advice.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.asm;
import net.bytebuddy.ClassFileVersion;
import net.bytebuddy.description.annotation.AnnotationDescription;
import net.bytebuddy.description.field.FieldDescription;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.method.MethodList;
import net.bytebuddy.description.method.ParameterDescription;
import net.bytebuddy.description.method.ParameterList;
import net.bytebuddy.description.type.TypeDefinition;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.description.type.TypeList;
import net.bytebuddy.dynamic.ClassFileLocator;
import net.bytebuddy.dynamic.scaffold.FieldLocator;
import net.bytebuddy.dynamic.scaffold.InstrumentedType;
import net.bytebuddy.implementation.Implementation;
import net.bytebuddy.implementation.SuperMethodCall;
import net.bytebuddy.implementation.bytecode.ByteCodeAppender;
import net.bytebuddy.implementation.bytecode.StackSize;
import net.bytebuddy.matcher.ElementMatcher;
import net.bytebuddy.utility.CompoundList;
import net.bytebuddy.utility.JavaType;
import net.bytebuddy.utility.visitor.ExceptionTableSensitiveMethodVisitor;
import net.bytebuddy.utility.visitor.LineNumberPrependingMethodVisitor;
import net.bytebuddy.utility.visitor.StackAwareMethodVisitor;
import org.objectweb.asm.*;
import java.io.*;
import java.lang.annotation.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
import static net.bytebuddy.matcher.ElementMatchers.named;
/**
* <p>
* Advice wrappers copy the code of blueprint methods to be executed before and/or after a matched method. To achieve this, a {@code static}
* method of a class is annotated by {@link OnMethodEnter} and/or {@link OnMethodExit} and provided to an instance of this class.
* </p>
* <p>
* A method that is annotated with {@link OnMethodEnter} can annotate its parameters with {@link Argument} where field access to this parameter
* is substituted with access to the specified argument of the instrumented method. Alternatively, a parameter can be annotated by {@link This}
* where the {@code this} reference of the instrumented method is read when the parameter is accessed. This mechanism can also be used to assign a
* new value to the {@code this} reference of an instrumented method. If no annotation is used on a parameter, it is assigned the {@code n}-th
* parameter of the instrumented method for the {@code n}-th parameter of the advice method. All parameters must declare the exact same type as
* the parameters of the instrumented type or the method's declaring type for the {@link This} reference respectively if they are not marked as
* <i>read-only</i>. In the latter case, it suffices that a parameter type is a super type of the corresponding type of the instrumented method.
* </p>
* <p>
* A method that is annotated with {@link OnMethodExit} can equally annotate its parameters with {@link Argument} and {@link This}. Additionally,
* it can annotate a parameter with {@link Return} to receive the original method's return value. By reassigning the return value, it is possible
* to replace the returned value. If an instrumented method does not return a value, this annotation must not be used. If a method returns
* exceptionally, the parameter is set to its default value, i.e. to {@code 0} for primitive types and to {@code null} for reference types. The
* parameter's type must be equal to the instrumented method's return type if it is not set to <i>read-only</i> where it suffices to declare the
* parameter type to be of any super type to the instrumented method's return type. An exception can be read by annotating a parameter of type
* {@link Throwable} annotated with {@link Thrown} which is assigned the thrown {@link Throwable} or {@code null} if a method returns normally.
* Doing so, it is possible to exchange a thrown exception with any checked or unchecked exception.Finally, if a method annotated with
* {@link OnMethodEnter} exists and this method returns a value, this value can be accessed by a parameter annotated with {@link Enter}.
* This parameter must declare the same type as type being returned by the method annotated with {@link OnMethodEnter}. If the parameter is marked
* to be <i>read-only</i>, it suffices that the annotated parameter is of a super type of the return type of the method annotated by
* {@link OnMethodEnter}. If no such method exists or this method returns {@code void}, no such parameter must be declared. Any return value
* of a method that is annotated by {@link OnMethodExit} is discarded.
* </p>
* <p>
* If any advice method throws an exception, the method is terminated prematurely. If the method annotated by {@link OnMethodEnter} throws an exception,
* the method annotated by {@link OnMethodExit} method is not invoked. If the instrumented method throws an exception, the method that is annotated by
* {@link OnMethodExit} is only invoked if the {@link OnMethodExit#onThrowable()} property is set to {@code true} what is the default. If this property
* is set to {@code false}, the {@link Thrown} annotation must not be used on any parameter.
* </p>
* <p>
* Byte Buddy does not assert the visibility of any types that are referenced within an inlined advice method. It is the responsibility of
* the user of this class to assure that all types referenced within the advice methods are visible to the instrumented class. Failing to
* do so results in a {@link IllegalAccessError} at the instrumented class's runtime.
* </p>
* <p>
* Advice can be used either as a {@link AsmVisitorWrapper} where any declared methods of the currently instrumented type are enhanced without
* replacing an existing implementation. Alternatively, advice can function as an {@link Implementation} where, by default, the original super
* or default method of the instrumented method is invoked. If this is not possible or undesired, the delegate implementation can be changed
* by specifying a wrapped implementation explicitly by {@link Advice#wrap(Implementation)}.
* </p>
* <p>
* When using an advice class as a visitor wrapper, native or abstract methods which are silently skipped when advice matches such a method.
* </p>
* <p>
* <b>Important</b>: Since Java 6, class files contain <i>stack map frames</i> embedded into a method's byte code. When advice methods are compiled
* with a class file version less then Java 6 but are used for a class file that was compiled to Java 6 or newer, these stack map frames must be
* computed by ASM by using the {@link ClassWriter#COMPUTE_FRAMES} option. If the advice methods do not contain any branching instructions, this is
* not required. No action is required if the advice methods are at least compiled with Java 6 but are used on classes older than Java 6. This
* limitation only applies to advice methods that are inlined. Also, it is the responsibility of this class's user to assure that the advice method
* does not contain byte code constructs that are not supported by the class containing the instrumented method. In particular, pre Java-5
* try-finally blocks cannot be inlined into classes with newer byte code levels as the <i>jsr</i> instruction was deprecated. Also, classes prior
* to Java 7 do not support the <i>invokedynamic</i> command which must not be contained by an advice method if the instrumented method targets an
* older class file format version.
* </p>
* <p>
* <b>Note</b>: For the purpose of inlining, Java 5 and Java 6 byte code can be seen as the best candidate for advice methods. These versions do
* no longer allow subroutines, neither do they already allow invokedynamic instructions or method handles. This way, Java 5 and Java 6 byte
* code is compatible to both older and newer versions. One exception for backwards-incompatible byte code is the possibility to load type references
* from the constant pool onto the operand stack. These instructions can however easily be transformerd for classes compiled to Java 4 and older
* by registering a {@link TypeConstantAdjustment} <b>before</b> the advice visitor.
* </p>
* <p>
* <b>Note</b>: It is not possible to trigger break points in inlined advice methods as the debugging information of the inlined advice is not
* preserved. It is not possible in Java to reference more than one source file per class what makes translating such debugging information
* impossible. It is however possible to set break points in advice methods when invoking the original advice target. This allows debugging
* of advice code within unit tests that invoke the advice method without instrumentation. As a conequence of not transferring debugging information,
* the names of the parameters of an advice method do not matter when inlining, neither does any meta information on the advice method's body
* such as annotations or parameter modifiers.
* </p>
* <p>
* <b>Note</b>: The behavior of this component is undefined if it is supplied with invalid byte code what might result in runtime exceptions.
* </p>
*
* @see DynamicValue
* @see OnMethodEnter
* @see OnMethodExit
*/
public class Advice implements AsmVisitorWrapper.ForDeclaredMethods.MethodVisitorWrapper, Implementation {
/**
* Indicates that no class reader is available to an adice method.
*/
private static final ClassReader UNDEFINED = null;
/**
* A reference to the {@link OnMethodEnter#inline()} method.
*/
private static final MethodDescription.InDefinedShape INLINE_ENTER;
/**
* A reference to the {@link OnMethodEnter#suppress()} method.
*/
private static final MethodDescription.InDefinedShape SUPPRESS_ENTER;
/**
* A reference to the {@link OnMethodEnter#prependLineNumber()} method.
*/
private static final MethodDescription.InDefinedShape PREPEND_LINE_NUMBER;
/**
* A reference to the {@link OnMethodEnter#skipOn()} method.
*/
private static final MethodDescription.InDefinedShape SKIP_ON;
/**
* A reference to the {@link OnMethodExit#inline()} method.
*/
private static final MethodDescription.InDefinedShape INLINE_EXIT;
/**
* A reference to the {@link OnMethodExit#suppress()} method.
*/
private static final MethodDescription.InDefinedShape SUPPRESS_EXIT;
/**
* A reference to the {@link OnMethodExit#onThrowable()} method.
*/
private static final MethodDescription.InDefinedShape ON_THROWABLE;
/*
* Extracts the annotation values for the enter and exit advice annotations.
*/
static {
MethodList<MethodDescription.InDefinedShape> enter = new TypeDescription.ForLoadedType(OnMethodEnter.class).getDeclaredMethods();
INLINE_ENTER = enter.filter(named("inline")).getOnly();
SUPPRESS_ENTER = enter.filter(named("suppress")).getOnly();
SKIP_ON = enter.filter(named("skipOn")).getOnly();
PREPEND_LINE_NUMBER = enter.filter(named("prependLineNumber")).getOnly();
MethodList<MethodDescription.InDefinedShape> exit = new TypeDescription.ForLoadedType(OnMethodExit.class).getDeclaredMethods();
INLINE_EXIT = exit.filter(named("inline")).getOnly();
SUPPRESS_EXIT = exit.filter(named("suppress")).getOnly();
ON_THROWABLE = exit.filter(named("onThrowable")).getOnly();
}
/**
* The dispatcher for instrumenting the instrumented method upon entering.
*/
private final Dispatcher.Resolved.ForMethodEnter methodEnter;
/**
* The dispatcher for instrumenting the instrumented method upon exiting.
*/
private final Dispatcher.Resolved.ForMethodExit methodExit;
/**
* The delegate implementation to apply if this advice is used as an instrumentation.
*/
private final Implementation delegate;
/**
* Creates a new advice.
*
* @param methodEnter The dispatcher for instrumenting the instrumented method upon entering.
* @param methodExit The dispatcher for instrumenting the instrumented method upon exiting.
*/
protected Advice(Dispatcher.Resolved.ForMethodEnter methodEnter, Dispatcher.Resolved.ForMethodExit methodExit) {
this(methodEnter, methodExit, SuperMethodCall.INSTANCE);
}
/**
* Creates a new advice.
*
* @param methodEnter The dispatcher for instrumenting the instrumented method upon entering.
* @param methodExit The dispatcher for instrumenting the instrumented method upon exiting.
* @param delegate The delegate implementation to apply if this advice is used as an instrumentation.
*/
private Advice(Dispatcher.Resolved.ForMethodEnter methodEnter, Dispatcher.Resolved.ForMethodExit methodExit, Implementation delegate) {
this.methodEnter = methodEnter;
this.methodExit = methodExit;
this.delegate = delegate;
}
/**
* Implements advice where every matched method is advised by the given type's advisory methods. The advices binary representation is
* accessed by querying the class loader of the supplied class for a class file.
*
* @param advice The type declaring the advice.
* @return A method visitor wrapper representing the supplied advice.
*/
public static Advice to(Class<?> advice) {
return to(advice, ClassFileLocator.ForClassLoader.of(advice.getClassLoader()));
}
/**
* Implements advice where every matched method is advised by the given type's advisory methods.
*
* @param advice The type declaring the advice.
* @param classFileLocator The class file locator for locating the advisory class's class file.
* @return A method visitor wrapper representing the supplied advice.
*/
public static Advice to(Class<?> advice, ClassFileLocator classFileLocator) {
return to(new TypeDescription.ForLoadedType(advice), classFileLocator);
}
/**
* Implements advice where every matched method is advised by the given type's advisory methods. Using this method, a non-operational
* class file locator is specified for the advice target. This implies that only advice targets with the <i>inline</i> target set
* to {@code false} are resolvable by the returned instance.
*
* @param advice The type declaring the advice.
* @return A method visitor wrapper representing the supplied advice.
*/
public static Advice to(TypeDescription advice) {
return to(advice, ClassFileLocator.NoOp.INSTANCE);
}
/**
* Implements advice where every matched method is advised by the given type's advisory methods.
*
* @param advice A description of the type declaring the advice.
* @param classFileLocator The class file locator for locating the advisory class's class file.
* @return A method visitor wrapper representing the supplied advice.
*/
public static Advice to(TypeDescription advice, ClassFileLocator classFileLocator) {
return to(advice, classFileLocator, Collections.<Dispatcher.OffsetMapping.Factory>emptyList());
}
/**
* Creates a new advice.
*
* @param advice A description of the type declaring the advice.
* @param classFileLocator The class file locator for locating the advisory class's class file.
* @param userFactories A list of custom factories for user generated offset mappings.
* @return A method visitor wrapper representing the supplied advice.
*/
protected static Advice to(TypeDescription advice, ClassFileLocator classFileLocator, List<? extends Dispatcher.OffsetMapping.Factory> userFactories) {
Dispatcher.Unresolved methodEnter = Dispatcher.Inactive.INSTANCE, methodExit = Dispatcher.Inactive.INSTANCE;
for (MethodDescription.InDefinedShape methodDescription : advice.getDeclaredMethods()) {
methodEnter = locate(OnMethodEnter.class, INLINE_ENTER, methodEnter, methodDescription);
methodExit = locate(OnMethodExit.class, INLINE_EXIT, methodExit, methodDescription);
}
if (!methodEnter.isAlive() && !methodExit.isAlive()) {
throw new IllegalArgumentException("No advice defined by " + advice);
}
try {
ClassReader classReader = methodEnter.isBinary() || methodExit.isBinary()
? new ClassReader(classFileLocator.locate(advice.getName()).resolve())
: UNDEFINED;
Dispatcher.Resolved.ForMethodEnter resolved = methodEnter.asMethodEnter(userFactories, classReader);
return new Advice(resolved, methodExit.asMethodExitTo(userFactories, classReader, resolved));
} catch (IOException exception) {
throw new IllegalStateException("Error reading class file of " + advice, exception);
}
}
/**
* Implements advice where every matched method is advised by the given type's advisory methods. The advices binary representation is
* accessed by querying the class loader of the supplied class for a class file.
*
* @param enterAdvice The type declaring the enter advice.
* @param exitAdvice The type declaring the exit advice.
* @return A method visitor wrapper representing the supplied advice.
*/
public static Advice to(Class<?> enterAdvice, Class<?> exitAdvice) {
ClassLoader enterLoader = enterAdvice.getClassLoader(), exitLoader = exitAdvice.getClassLoader();
return to(enterAdvice, exitAdvice, enterLoader == exitLoader
? ClassFileLocator.ForClassLoader.of(enterLoader)
: new ClassFileLocator.Compound(ClassFileLocator.ForClassLoader.of(enterLoader), ClassFileLocator.ForClassLoader.of(exitLoader)));
}
/**
* Implements advice where every matched method is advised by the given type's advisory methods.
*
* @param enterAdvice The type declaring the enter advice.
* @param exitAdvice The type declaring the exit advice.
* @param classFileLocator The class file locator for locating the advisory class's class file.
* @return A method visitor wrapper representing the supplied advice.
*/
public static Advice to(Class<?> enterAdvice, Class<?> exitAdvice, ClassFileLocator classFileLocator) {
return to(new TypeDescription.ForLoadedType(enterAdvice), new TypeDescription.ForLoadedType(exitAdvice), classFileLocator);
}
/**
* Implements advice where every matched method is advised by the given type's advisory methods. Using this method, a non-operational
* class file locator is specified for the advice target. This implies that only advice targets with the <i>inline</i> target set
* to {@code false} are resolvable by the returned instance.
*
* @param enterAdvice The type declaring the enter advice.
* @param exitAdvice The type declaring the exit advice.
* @return A method visitor wrapper representing the supplied advice.
*/
public static Advice to(TypeDescription enterAdvice, TypeDescription exitAdvice) {
return to(enterAdvice, exitAdvice, ClassFileLocator.NoOp.INSTANCE);
}
/**
* Implements advice where every matched method is advised by the given type's advisory methods.
*
* @param enterAdvice The type declaring the enter advice.
* @param exitAdvice The type declaring the exit advice.
* @param classFileLocator The class file locator for locating the advisory class's class file.
* @return A method visitor wrapper representing the supplied advice.
*/
public static Advice to(TypeDescription enterAdvice, TypeDescription exitAdvice, ClassFileLocator classFileLocator) {
return to(enterAdvice, exitAdvice, classFileLocator, Collections.<Dispatcher.OffsetMapping.Factory>emptyList());
}
/**
* Creates a new advice.
*
* @param enterAdvice The type declaring the enter advice.
* @param exitAdvice The type declaring the exit advice.
* @param classFileLocator The class file locator for locating the advisory class's class file.
* @param userFactories A list of custom factories for user generated offset mappings.
* @return A method visitor wrapper representing the supplied advice.
*/
protected static Advice to(TypeDescription enterAdvice,
TypeDescription exitAdvice,
ClassFileLocator classFileLocator,
List<? extends Dispatcher.OffsetMapping.Factory> userFactories) {
Dispatcher.Unresolved methodEnter = Dispatcher.Inactive.INSTANCE, methodExit = Dispatcher.Inactive.INSTANCE;
for (MethodDescription.InDefinedShape methodDescription : enterAdvice.getDeclaredMethods()) {
methodEnter = locate(OnMethodEnter.class, INLINE_ENTER, methodEnter, methodDescription);
}
if (!methodEnter.isAlive()) {
throw new IllegalArgumentException("No enter advice defined by " + enterAdvice);
}
for (MethodDescription.InDefinedShape methodDescription : exitAdvice.getDeclaredMethods()) {
methodExit = locate(OnMethodExit.class, INLINE_EXIT, methodExit, methodDescription);
}
if (!methodExit.isAlive()) {
throw new IllegalArgumentException("No enter advice defined by " + exitAdvice);
}
try {
Dispatcher.Resolved.ForMethodEnter resolved = methodEnter.asMethodEnter(userFactories, methodEnter.isBinary()
? new ClassReader(classFileLocator.locate(enterAdvice.getName()).resolve())
: UNDEFINED);
return new Advice(resolved, methodExit.asMethodExitTo(userFactories, methodExit.isBinary()
? new ClassReader(classFileLocator.locate(exitAdvice.getName()).resolve())
: UNDEFINED, resolved));
} catch (IOException exception) {
throw new IllegalStateException("Error reading class file of " + enterAdvice + " or " + exitAdvice, exception);
}
}
/**
* Locates a dispatcher for the method if available.
*
* @param type The annotation type that indicates a given form of advice that is currently resolved.
* @param property An annotation property that indicates if the advice method should be inlined.
* @param dispatcher Any previous dispatcher that was discovered or {@code null} if no such dispatcher was yet found.
* @param methodDescription The method description that is considered as an advice method.
* @return A resolved dispatcher or {@code null} if no dispatcher was resolved.
*/
private static Dispatcher.Unresolved locate(Class<? extends Annotation> type,
MethodDescription.InDefinedShape property,
Dispatcher.Unresolved dispatcher,
MethodDescription.InDefinedShape methodDescription) {
AnnotationDescription annotation = methodDescription.getDeclaredAnnotations().ofType(type);
if (annotation == null) {
return dispatcher;
} else if (dispatcher.isAlive()) {
throw new IllegalStateException("Duplicate advice for " + dispatcher + " and " + methodDescription);
} else if (!methodDescription.isStatic()) {
throw new IllegalStateException("Advice for " + methodDescription + " is not static");
} else {
return annotation.getValue(property).resolve(Boolean.class)
? new Dispatcher.Inlining(methodDescription)
: new Dispatcher.Delegating(methodDescription);
}
}
/**
* Allows for the configuration of custom annotations that are then bound to a dynamically computed, constant value.
*
* @return A builder for an {@link Advice} instrumentation with custom values.
* @see DynamicValue
*/
public static WithCustomMapping withCustomMapping() {
return new WithCustomMapping();
}
/**
* Returns an ASM visitor wrapper that matches the given matcher and applies this advice to the matched methods.
*
* @param matcher The matcher identifying methods to apply the advice to.
* @return A suitable ASM visitor wrapper with the <i>compute frames</i> option enabled.
*/
public AsmVisitorWrapper.ForDeclaredMethods on(ElementMatcher<? super MethodDescription.InDefinedShape> matcher) {
return new AsmVisitorWrapper.ForDeclaredMethods().method(matcher, this);
}
@Override
public MethodVisitor wrap(TypeDescription instrumentedType,
MethodDescription.InDefinedShape instrumentedMethod,
MethodVisitor methodVisitor,
ClassFileVersion classFileVersion,
int writerFlags,
int readerFlags) {
return instrumentedMethod.isAbstract() || instrumentedMethod.isNative()
? methodVisitor
: doWrap(instrumentedType, instrumentedMethod, methodVisitor, classFileVersion, writerFlags, readerFlags);
}
/**
* Wraps the method visitor to implement this advice.
*
* @param instrumentedType The instrumented type.
* @param instrumentedMethod The instrumented method.
* @param methodVisitor The method visitor to write to.
* @param classFileVersion The current class file version.
* @param writerFlags The ASM writer flags to use.
* @param readerFlags The ASM reader flags to use.
* @return A method visitor that applies this advice.
*/
protected MethodVisitor doWrap(TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
MethodVisitor methodVisitor,
ClassFileVersion classFileVersion,
int writerFlags,
int readerFlags) {
methodVisitor = methodEnter.isPrependLineNumber()
? new LineNumberPrependingMethodVisitor(methodVisitor)
: methodVisitor;
if (!methodExit.isAlive()) {
return new AdviceVisitor.WithoutExitAdvice(methodVisitor,
instrumentedType,
instrumentedMethod,
methodEnter,
classFileVersion,
writerFlags,
readerFlags);
} else if (methodExit.getTriggeringThrowable().represents(NoExceptionHandler.class)) {
return new AdviceVisitor.WithExitAdvice.WithoutExceptionHandling(methodVisitor,
instrumentedType,
instrumentedMethod,
methodEnter,
methodExit,
classFileVersion,
writerFlags,
readerFlags);
} else if (instrumentedMethod.isConstructor()) {
throw new IllegalStateException("Cannot catch exception during constructor call for " + instrumentedMethod);
} else {
return new AdviceVisitor.WithExitAdvice.WithExceptionHandling(methodVisitor,
instrumentedType,
instrumentedMethod,
methodEnter,
methodExit,
classFileVersion,
writerFlags,
readerFlags,
methodExit.getTriggeringThrowable());
}
}
@Override
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return delegate.prepare(instrumentedType);
}
@Override
public ByteCodeAppender appender(Target implementationTarget) {
return new Appender(this, implementationTarget, delegate.appender(implementationTarget));
}
/**
* Wraps the supplied implementation to have this advice applied around it.
*
* @param implementation The implementation to wrap.
* @return An implementation that applies the supplied implementation and wraps it with this advice.
*/
public Implementation wrap(Implementation implementation) {
return new Advice(methodEnter, methodExit, implementation);
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null || getClass() != other.getClass()) {
return false;
}
Advice advice = (Advice) other;
return methodEnter.equals(advice.methodEnter)
&& methodExit.equals(advice.methodExit)
&& delegate.equals(advice.delegate);
}
@Override
public int hashCode() {
int result = methodEnter.hashCode();
result = 31 * result + methodExit.hashCode();
result = 31 * result + delegate.hashCode();
return result;
}
@Override
public String toString() {
return "Advice{" +
"methodEnter=" + methodEnter +
", methodExit=" + methodExit +
", delegate=" + delegate +
'}';
}
/**
* A handler for computing the instrumented method's size.
*/
protected interface MethodSizeHandler {
/**
* Indicates that a size is not computed but handled directly by ASM.
*/
int UNDEFINED_SIZE = Short.MAX_VALUE;
/**
* Requires a minimum length of the local variable array.
*
* @param localVariableLength The minimal required length of the local variable array.
*/
void requireLocalVariableLength(int localVariableLength);
/**
* A method size handler for the instrumented method.
*/
interface ForInstrumentedMethod extends MethodSizeHandler {
/**
* Binds a method size handler for the entry advice.
*
* @param adviceMethod The method representing the entry advice.
* @return A method size handler for the entry advice.
*/
ForAdvice bindEntry(MethodDescription.InDefinedShape adviceMethod);
/**
* Binds the method size handler for the exit advice.
*
* @param adviceMethod The method representing the exit advice.
* @param skipThrowable {@code true} if the exit advice is not invoked on an exception.
* @return A method size handler for the exit advice.
*/
ForAdvice bindExit(MethodDescription.InDefinedShape adviceMethod, boolean skipThrowable);
/**
* Computes a compound stack size for the advice and the translated instrumented method.
*
* @param stackSize The required stack size of the instrumented method before translation.
* @return The stack size required by the instrumented method and its advice methods.
*/
int compoundStackSize(int stackSize);
/**
* Computes a compound local variable array length for the advice and the translated instrumented method.
*
* @param localVariableLength The required local variable array length of the instrumented method before translation.
* @return The local variable length required by the instrumented method and its advice methods.
*/
int compoundLocalVariableLength(int localVariableLength);
}
/**
* A method size handler for an advice method.
*/
interface ForAdvice extends MethodSizeHandler {
/**
* Records a minimum stack size required by the represented advice method.
*
* @param stackSize The minimum size required by the represented advice method.
*/
void requireStackSize(int stackSize);
/**
* Records the maximum values for stack size and local variable array which are required by the advice method
* for its individual execution without translation.
*
* @param stackSize The minimum required stack size.
* @param localVariableLength The minimum required length of the local variable array.
*/
void recordMaxima(int stackSize, int localVariableLength);
/**
* Records a minimum padding additionally to the computed stack size that is required for implementing this advice method.
*
* @param padding The minimum required padding.
*/
void recordPadding(int padding);
}
/**
* A non-operational method size handler.
*/
enum NoOp implements ForInstrumentedMethod, ForAdvice {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public ForAdvice bindEntry(MethodDescription.InDefinedShape adviceMethod) {
return this;
}
@Override
public ForAdvice bindExit(MethodDescription.InDefinedShape adviceMethod, boolean skipThrowable) {
return this;
}
@Override
public int compoundStackSize(int stackSize) {
return UNDEFINED_SIZE;
}
@Override
public int compoundLocalVariableLength(int localVariableLength) {
return UNDEFINED_SIZE;
}
@Override
public void requireLocalVariableLength(int localVariableLength) {
/* do nothing */
}
@Override
public void requireStackSize(int stackSize) {
/* do nothing */
}
@Override
public void recordMaxima(int stackSize, int localVariableLength) {
/* do nothing */
}
@Override
public void recordPadding(int padding) {
/* do nothing */
}
@Override
public String toString() {
return "Advice.MethodSizeHandler.NoOp." + name();
}
}
/**
* A default implementation for a method size handler.
*/
class Default implements MethodSizeHandler.ForInstrumentedMethod {
/**
* The instrumented method.
*/
private final MethodDescription instrumentedMethod;
/**
* The list of types that the instrumented method requires in addition to the method parameters.
*/
private final TypeList requiredTypes;
/**
* A list of types that are yielded by the instrumented method and available to the exit advice.
*/
private final TypeList yieldedTypes;
/**
* The maximum stack size required by a visited advice method.
*/
private int stackSize;
/**
* The maximum length of the local variable array required by a visited advice method.
*/
private int localVariableLength;
/**
* Creates a new default meta data handler that recomputes the space requirements of an instrumented method.
*
* @param instrumentedMethod The instrumented method.
* @param requiredTypes The types this meta data handler expects to be available additionally to the instrumented method's parameters.
* @param yieldedTypes The types that are expected to be added after the instrumented method returns.
*/
protected Default(MethodDescription instrumentedMethod, TypeList requiredTypes, TypeList yieldedTypes) {
this.instrumentedMethod = instrumentedMethod;
this.requiredTypes = requiredTypes;
this.yieldedTypes = yieldedTypes;
}
/**
* Creates a method size handler applicable for the given instrumented method.
*
* @param instrumentedMethod The instrumented method.
* @param requiredTypes The list of types that the instrumented method requires in addition to the method parameters.
* @param yieldedTypes A list of types that are yielded by the instrumented method and available to the exit advice.
* @param writerFlags The flags supplied to the ASM class writer.
* @return An appropriate method size handler.
*/
protected static MethodSizeHandler.ForInstrumentedMethod of(MethodDescription instrumentedMethod,
List<? extends TypeDescription> requiredTypes,
List<? extends TypeDescription> yieldedTypes,
int writerFlags) {
return (writerFlags & (ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES)) != 0
? NoOp.INSTANCE
: new Default(instrumentedMethod, new TypeList.Explicit(requiredTypes), new TypeList.Explicit(yieldedTypes));
}
@Override
public MethodSizeHandler.ForAdvice bindEntry(MethodDescription.InDefinedShape adviceMethod) {
stackSize = Math.max(stackSize, adviceMethod.getReturnType().getStackSize().getSize());
return new ForAdvice(adviceMethod, new TypeList.Empty(), new TypeList.Explicit(requiredTypes));
}
@Override
public MethodSizeHandler.ForAdvice bindExit(MethodDescription.InDefinedShape adviceMethod, boolean skipThrowable) {
stackSize = Math.max(stackSize, adviceMethod.getReturnType().getStackSize().maximum(skipThrowable
? StackSize.ZERO
: StackSize.SINGLE).getSize());
return new ForAdvice(adviceMethod, new TypeList.Explicit(CompoundList.of(requiredTypes, yieldedTypes)), new TypeList.Empty());
}
@Override
public int compoundStackSize(int stackSize) {
return Math.max(this.stackSize, stackSize);
}
@Override
public int compoundLocalVariableLength(int localVariableLength) {
return Math.max(this.localVariableLength, localVariableLength
+ requiredTypes.getStackSize()
+ yieldedTypes.getStackSize());
}
@Override
public void requireLocalVariableLength(int localVariableLength) {
this.localVariableLength = Math.max(this.localVariableLength, localVariableLength);
}
@Override
public String toString() {
return "Advice.MethodSizeHandler.Default{" +
"instrumentedMethod=" + instrumentedMethod +
", requiredTypes=" + requiredTypes +
", yieldedTypes=" + yieldedTypes +
", stackSize=" + stackSize +
", localVariableLength=" + localVariableLength +
'}';
}
/**
* A method size handler for an advice method.
*/
protected class ForAdvice implements MethodSizeHandler.ForAdvice {
/**
* The advice method.
*/
private final MethodDescription.InDefinedShape adviceMethod;
/**
* A list of types required by this advice method.
*/
private final TypeList requiredTypes;
/**
* A list of types yielded by this advice method.
*/
private final TypeList yieldedTypes;
/**
* The padding that this advice method requires additionally to its computed size.
*/
private int padding;
/**
* Creates a new method size handler for an advice method.
*
* @param adviceMethod The advice method.
* @param requiredTypes A list of types required by this advice method.
* @param yieldedTypes A list of types yielded by this advice method.
*/
protected ForAdvice(MethodDescription.InDefinedShape adviceMethod, TypeList requiredTypes, TypeList yieldedTypes) {
this.adviceMethod = adviceMethod;
this.requiredTypes = requiredTypes;
this.yieldedTypes = yieldedTypes;
stackSize = Math.max(stackSize, adviceMethod.getReturnType().getStackSize().getSize());
}
@Override
public void requireLocalVariableLength(int localVariableLength) {
Default.this.requireLocalVariableLength(localVariableLength);
}
@Override
public void requireStackSize(int stackSize) {
Default.this.stackSize = Math.max(Default.this.stackSize, stackSize);
}
@Override
public void recordMaxima(int stackSize, int localVariableLength) {
Default.this.stackSize = Math.max(Default.this.stackSize, stackSize) + padding;
Default.this.localVariableLength = Math.max(Default.this.localVariableLength, localVariableLength
- adviceMethod.getStackSize()
+ instrumentedMethod.getStackSize()
+ requiredTypes.getStackSize()
+ yieldedTypes.getStackSize());
}
@Override
public void recordPadding(int padding) {
this.padding = Math.max(this.padding, padding);
}
@Override
public String toString() {
return "Advice.MethodSizeHandler.Default.ForAdvice{" +
"adviceMethod=" + adviceMethod +
", requiredTypes=" + requiredTypes +
", yieldedTypes=" + yieldedTypes +
", padding=" + padding +
'}';
}
}
}
}
/**
* A handler for computing and translating stack map frames.
*/
protected interface StackMapFrameHandler {
/**
* Translates a frame.
*
* @param methodVisitor The method visitor to write the frame to.
* @param frameType The frame's type.
* @param localVariableLength The local variable length.
* @param localVariable An array containing the types of the current local variables.
* @param stackSize The size of the operand stack.
* @param stack An array containing the types of the current operand stack.
*/
void translateFrame(MethodVisitor methodVisitor, int frameType, int localVariableLength, Object[] localVariable, int stackSize, Object[] stack);
/**
* Injects a frame indicating the beginning of a return value handler for the currently handled method.
*
* @param methodVisitor The method visitor onto which to apply the stack map frame.
*/
void injectReturnFrame(MethodVisitor methodVisitor);
/**
* Injects a frame indicating the beginning of an exception handler for the currently handled method.
*
* @param methodVisitor The method visitor onto which to apply the stack map frame.
*/
void injectExceptionFrame(MethodVisitor methodVisitor);
/**
* Injects a frame indicating the completion of the currently handled method, i.e. all yielded types were added.
*
* @param methodVisitor The method visitor onto which to apply the stack map frame.
* @param secondary {@code true} if another completion frame for this method was written previously.
*/
void injectCompletionFrame(MethodVisitor methodVisitor, boolean secondary);
/**
* A stack map frame handler for an instrumented method.
*/
interface ForInstrumentedMethod extends StackMapFrameHandler {
/**
* Binds this meta data handler for the entry advice.
*
* @param adviceMethod The entry advice method.
* @return An appropriate meta data handler for the enter method.
*/
ForAdvice bindEntry(MethodDescription.InDefinedShape adviceMethod);
/**
* Binds this meta data handler for the exit advice.
*
* @param adviceMethod The exit advice method.
* @return An appropriate meta data handler for the enter method.
*/
ForAdvice bindExit(MethodDescription.InDefinedShape adviceMethod);
/**
* Returns a hint to supply to a {@link ClassReader} when parsing an advice method.
*
* @return The reader hint to supply to an ASM class reader.
*/
int getReaderHint();
}
/**
* A stack map frame handler for an advice method.
*/
interface ForAdvice extends StackMapFrameHandler {
/* marker interface */
}
/**
* A non-operational stack map frame handler.
*/
enum NoOp implements ForInstrumentedMethod, ForAdvice {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public StackMapFrameHandler.ForAdvice bindEntry(MethodDescription.InDefinedShape adviceMethod) {
return this;
}
@Override
public StackMapFrameHandler.ForAdvice bindExit(MethodDescription.InDefinedShape adviceMethod) {
return this;
}
@Override
public int getReaderHint() {
return ClassReader.SKIP_FRAMES;
}
@Override
public void translateFrame(MethodVisitor methodVisitor,
int frameType,
int localVariableLength,
Object[] localVariable,
int stackSize,
Object[] stack) {
/* do nothing */
}
@Override
public void injectReturnFrame(MethodVisitor methodVisitor) {
/* do nothing */
}
@Override
public void injectExceptionFrame(MethodVisitor methodVisitor) {
/* do nothing */
}
@Override
public void injectCompletionFrame(MethodVisitor methodVisitor, boolean secondary) {
/* do nothing */
}
@Override
public String toString() {
return "Advice.StackMapFrameHandler.NoOp." + name();
}
}
/**
* A default implementation of a stack map frame handler for an instrumented method.
*/
class Default implements ForInstrumentedMethod {
/**
* An empty array indicating an empty frame.
*/