/
MethodCall.java
2337 lines (2058 loc) · 94.3 KB
/
MethodCall.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.implementation;
import net.bytebuddy.description.enumeration.EnumerationDescription;
import net.bytebuddy.description.field.FieldDescription;
import net.bytebuddy.description.field.FieldList;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.method.ParameterDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.description.type.TypeList;
import net.bytebuddy.dynamic.scaffold.InstrumentedType;
import net.bytebuddy.implementation.bytecode.*;
import net.bytebuddy.implementation.bytecode.assign.Assigner;
import net.bytebuddy.implementation.bytecode.constant.*;
import net.bytebuddy.implementation.bytecode.member.FieldAccess;
import net.bytebuddy.implementation.bytecode.member.MethodInvocation;
import net.bytebuddy.implementation.bytecode.member.MethodReturn;
import net.bytebuddy.implementation.bytecode.member.MethodVariableAccess;
import net.bytebuddy.utility.JavaInstance;
import net.bytebuddy.utility.JavaType;
import net.bytebuddy.utility.RandomString;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static net.bytebuddy.matcher.ElementMatchers.named;
import static net.bytebuddy.utility.ByteBuddyCommons.*;
/**
* This {@link Implementation} allows the invocation of a specified method while
* providing explicit arguments to this method.
*/
public class MethodCall implements Implementation {
/**
* Indicates that an assignment should only consider the static type of a variable.
*/
private static final boolean DO_NOT_CONSIDER_RUNTIME_TYPE = false;
/**
* The method locator to use.
*/
protected final MethodLocator methodLocator;
/**
* The target handler to use.
*/
protected final TargetHandler targetHandler;
/**
* The argument loader to load arguments onto the operand stack in their application order.
*/
protected final List<ArgumentLoader> argumentLoaders;
/**
* The method invoker to use.
*/
protected final MethodInvoker methodInvoker;
/**
* The termination handler to use.
*/
protected final TerminationHandler terminationHandler;
/**
* The assigner to use.
*/
protected final Assigner assigner;
/**
* {@code true} if a return value of the called method should be attempted to be type-casted to the return
* type of the instrumented method.
*/
protected final boolean dynamicallyTyped;
/**
* Creates a new method call implementation.
*
* @param methodLocator The method locator to use.
* @param targetHandler The target handler to use.
* @param argumentLoaders The argument loader to load arguments onto the operand stack in
* their application order.
* @param methodInvoker The method invoker to use.
* @param terminationHandler The termination handler to use.
* @param assigner The assigner to use.
* @param dynamicallyTyped {@code true} if a return value of the called method should be attempted
* to be type-casted to the return type of the instrumented method.
*/
protected MethodCall(MethodLocator methodLocator,
TargetHandler targetHandler,
List<ArgumentLoader> argumentLoaders,
MethodInvoker methodInvoker,
TerminationHandler terminationHandler,
Assigner assigner,
boolean dynamicallyTyped) {
this.methodLocator = methodLocator;
this.targetHandler = targetHandler;
this.argumentLoaders = argumentLoaders;
this.methodInvoker = methodInvoker;
this.terminationHandler = terminationHandler;
this.assigner = assigner;
this.dynamicallyTyped = dynamicallyTyped;
}
/**
* Invokes the given method. Without further specification, the method is invoked without any arguments on
* the instance of the instrumented class or statically, if the given method is {@code static}.
*
* @param method The method to invoke.
* @return A method call implementation that invokes the given method without providing any arguments.
*/
public static WithoutSpecifiedTarget invoke(Method method) {
return invoke(new MethodDescription.ForLoadedMethod(nonNull(method)));
}
/**
* Invokes the given constructor on the instance of the instrumented type.
*
* @param constructor The constructor to invoke.
* @return A method call implementation that invokes the given constructor without providing any arguments.
*/
public static WithoutSpecifiedTarget invoke(Constructor<?> constructor) {
return invoke(new MethodDescription.ForLoadedConstructor(nonNull(constructor)));
}
/**
* Invokes the given method. If the method description describes a constructor, it is automatically invoked as
* a special method invocation on the instance of the instrumented type. The same is true for {@code private}
* methods. Finally, {@code static} methods are invoked statically.
*
* @param methodDescription The method to invoke.
* @return A method call implementation that invokes the given method without providing any arguments.
*/
public static WithoutSpecifiedTarget invoke(MethodDescription methodDescription) {
return invoke(new MethodLocator.ForExplicitMethod(nonNull(methodDescription)));
}
/**
* Invokes a method using the provided method locator.
*
* @param methodLocator The method locator to apply for locating the method to invoke given the instrumented
* method.
* @return A method call implementation that uses the provided method locator for resolving the method
* to be invoked.
*/
public static WithoutSpecifiedTarget invoke(MethodLocator methodLocator) {
return new WithoutSpecifiedTarget(nonNull(methodLocator));
}
/**
* Invokes the given constructor in order to create an instance.
*
* @param constructor The constructor to invoke.
* @return A method call that invokes the given constructor without providing any arguments.
*/
public static MethodCall construct(Constructor<?> constructor) {
return construct(new MethodDescription.ForLoadedConstructor(nonNull(constructor)));
}
/**
* Invokes the given constructor in order to create an instance.
*
* @param methodDescription A description of the constructor to invoke.
* @return A method call that invokes the given constructor without providing any arguments.
*/
public static MethodCall construct(MethodDescription methodDescription) {
if (!methodDescription.isConstructor()) {
throw new IllegalArgumentException("Not a constructor: " + methodDescription);
}
return new MethodCall(new MethodLocator.ForExplicitMethod(methodDescription),
TargetHandler.ForConstructingInvocation.INSTANCE,
Collections.<ArgumentLoader>emptyList(),
MethodInvoker.ForStandardInvocation.INSTANCE,
TerminationHandler.ForMethodReturn.INSTANCE,
Assigner.DEFAULT,
DO_NOT_CONSIDER_RUNTIME_TYPE);
}
/**
* Invokes the method that is instrumented by the returned instance by a super method invocation.
*
* @return A method call that invokes the method being instrumented.
*/
public static MethodCall invokeSuper() {
return new WithoutSpecifiedTarget(MethodLocator.ForInterceptedMethod.INSTANCE).onSuper();
}
/**
* Defines a number of arguments to be handed to the method that is being invoked by this implementation. Any
* wrapper type instances for primitive values, instances of {@link java.lang.String} or {@code null} are loaded
* directly onto the operand stack. This might corrupt referential identity for these values. Any other values
* are stored within a {@code static} field that is added to the instrumented type.
*
* @param argument The arguments to provide to the method that is being called in their order.
* @return A method call that hands the provided arguments to the invoked method.
*/
public MethodCall with(Object... argument) {
List<ArgumentLoader> argumentLoaders = new ArrayList<ArgumentLoader>(argument.length);
for (Object anArgument : argument) {
argumentLoaders.add(ArgumentLoader.ForStaticField.of(anArgument));
}
return new MethodCall(methodLocator,
targetHandler,
join(this.argumentLoaders, argumentLoaders),
methodInvoker,
terminationHandler,
assigner,
dynamicallyTyped);
}
/**
* Defines the given types to be provided as arguments to the invoked method where the represented types
* are stored in the generated class's constant pool.
*
* @param typeDescription The type descriptions to provide as arguments.
* @return A method call that hands the provided arguments to the invoked method.
*/
public MethodCall with(TypeDescription... typeDescription) {
List<ArgumentLoader> argumentLoaders = new ArrayList<ArgumentLoader>(typeDescription.length);
for (TypeDescription aTypeDescription : typeDescription) {
argumentLoaders.add(new ArgumentLoader.ForClassConstant(nonNull(aTypeDescription)));
}
return new MethodCall(methodLocator,
targetHandler,
join(this.argumentLoaders, argumentLoaders),
methodInvoker,
terminationHandler,
assigner,
dynamicallyTyped);
}
/**
* Defines the given enumeration values to be provided as arguments to the invoked method where the values
* are read from the enumeration class on demand.
*
* @param enumerationDescription The enumeration descriptions to provide as arguments.
* @return A method call that hands the provided arguments to the invoked method.
*/
public MethodCall with(EnumerationDescription... enumerationDescription) {
List<ArgumentLoader> argumentLoaders = new ArrayList<ArgumentLoader>(enumerationDescription.length);
for (EnumerationDescription anEnumerationDescription : enumerationDescription) {
argumentLoaders.add(new ArgumentLoader.ForEnumerationValue(nonNull(anEnumerationDescription)));
}
return new MethodCall(methodLocator,
targetHandler,
join(this.argumentLoaders, argumentLoaders),
methodInvoker,
terminationHandler,
assigner,
dynamicallyTyped);
}
/**
* Defines the given Java instances to be provided as arguments to the invoked method where the given
* instances are stored in the generated class's constant pool.
*
* @param javaInstance The Java instances to provide as arguments.
* @return A method call that hands the provided arguments to the invoked method.
*/
public MethodCall with(JavaInstance... javaInstance) {
List<ArgumentLoader> argumentLoaders = new ArrayList<ArgumentLoader>(javaInstance.length);
for (JavaInstance aJavaInstance : javaInstance) {
argumentLoaders.add(new ArgumentLoader.ForJavaInstance(nonNull(aJavaInstance)));
}
return new MethodCall(methodLocator,
targetHandler,
join(this.argumentLoaders, argumentLoaders),
methodInvoker,
terminationHandler,
assigner,
dynamicallyTyped);
}
/**
* Defines a number of arguments to be handed to the method that is being invoked by this implementation. Any
* value is stored within a field in order to preserve referential identity. As an exception, the {@code null}
* value is not stored within a field.
*
* @param argument The arguments to provide to the method that is being called in their order.
* @return A method call that hands the provided arguments to the invoked method.
*/
public MethodCall withReference(Object... argument) {
List<ArgumentLoader> argumentLoaders = new ArrayList<ArgumentLoader>(argument.length);
for (Object anArgument : argument) {
argumentLoaders.add(anArgument == null
? ArgumentLoader.ForNullConstant.INSTANCE
: new ArgumentLoader.ForStaticField(anArgument));
}
return new MethodCall(methodLocator,
targetHandler,
join(this.argumentLoaders, argumentLoaders),
methodInvoker,
terminationHandler,
assigner,
dynamicallyTyped);
}
/**
* Defines a number of arguments of the instrumented method by their parameter indices to be handed
* to the invoked method as an argument.
*
* @param index The parameter indices of the instrumented method to be handed to the invoked method as an
* argument in their order. The indices are zero-based.
* @return A method call that hands the provided arguments to the invoked method.
*/
public MethodCall withArgument(int... index) {
List<ArgumentLoader> argumentLoaders = new ArrayList<ArgumentLoader>(index.length);
for (int anIndex : index) {
if (anIndex < 0) {
throw new IllegalArgumentException("Negative index: " + anIndex);
}
argumentLoaders.add(new ArgumentLoader.ForMethodParameter(anIndex));
}
return new MethodCall(methodLocator,
targetHandler,
join(this.argumentLoaders, argumentLoaders),
methodInvoker,
terminationHandler,
assigner,
dynamicallyTyped);
}
/**
* Assigns the {@code this} reference to the next parameter.
*
* @return This method call where the next parameter is a assigned a reference to the {@code this} reference
* of the instance of the intercepted method.
*/
public MethodCall withThis() {
return new MethodCall(methodLocator,
targetHandler,
join(argumentLoaders, ArgumentLoader.ForThisReference.INSTANCE),
methodInvoker,
terminationHandler,
assigner,
dynamicallyTyped);
}
/**
* Assigns the {@link java.lang.Class} value of the instrumented type.
*
* @return This method call where the next parameter is a assigned a reference to the {@link java.lang.Class}
* value of the instrumented type.
*/
public MethodCall withOwnType() {
return new MethodCall(methodLocator,
targetHandler,
join(argumentLoaders, ArgumentLoader.ForOwnType.INSTANCE),
methodInvoker,
terminationHandler,
assigner,
dynamicallyTyped);
}
/**
* Defines a method call which fetches a value from an instance field. The value of the field needs to be
* defined manually and is initialized with {@code null}. The field itself is defined by this implementation.
*
* @param type The type of the field.
* @param name The name of the field.
* @return A method call which assigns the next parameter to the value of the instance field.
*/
public MethodCall withInstanceField(Class<?> type, String name) {
return withInstanceField(new TypeDescription.ForLoadedType(nonNull(type)), name);
}
/**
* Defines a method call which fetches a value from an instance field. The value of the field needs to be
* defined manually and is initialized with {@code null}. The field itself is defined by this implementation.
*
* @param typeDescription The type of the field.
* @param name The name of the field.
* @return A method call which assigns the next parameter to the value of the instance field.
*/
public MethodCall withInstanceField(TypeDescription typeDescription, String name) {
return new MethodCall(methodLocator,
targetHandler,
join(argumentLoaders, new ArgumentLoader.ForInstanceField(nonNull(typeDescription), nonNull(name))),
methodInvoker,
terminationHandler,
assigner,
dynamicallyTyped);
}
/**
* Defines a method call which fetches a value from an existing field. The field is not defines by this
* implementation.
*
* @param fieldName The name of the field.
* @return A method call which assigns the next parameter to the value of the given field.
*/
public MethodCall withField(String... fieldName) {
List<ArgumentLoader> argumentLoaders = new ArrayList<ArgumentLoader>(fieldName.length);
for (String aFieldName : fieldName) {
argumentLoaders.add(new ArgumentLoader.ForExistingField(aFieldName));
}
return new MethodCall(methodLocator,
targetHandler,
join(this.argumentLoaders, argumentLoaders),
methodInvoker,
terminationHandler,
assigner,
dynamicallyTyped);
}
/**
* Defines an assigner to be used for assigning values to the parameters of the invoked method. This assigner
* is also used for assigning the invoked method's return value to the return type of the instrumented method,
* if this method is not chained with
* {@link net.bytebuddy.implementation.MethodCall#andThen(Implementation)} such
* that a return value of this method call is discarded.
*
* @param assigner The assigner to use.
* @param dynamicallyTyped {@code true} if the return value assignment should attempt a type casting when
* assigning incompatible values.
* @return This method call using the provided assigner.
*/
public MethodCall withAssigner(Assigner assigner, boolean dynamicallyTyped) {
return new MethodCall(methodLocator,
targetHandler,
argumentLoaders,
methodInvoker,
terminationHandler,
nonNull(assigner),
dynamicallyTyped);
}
/**
* Applies another implementation after invoking this method call. A return value that is the result of this
* method call is dropped.
*
* @param implementation The implementation that is to be applied after applying this method call implementation.
* @return An implementation that first applies this method call and the given implementation right after.
*/
public Implementation andThen(Implementation implementation) {
return new Implementation.Compound(new MethodCall(methodLocator,
targetHandler,
argumentLoaders,
methodInvoker,
TerminationHandler.ForChainedInvocation.INSTANCE,
assigner,
dynamicallyTyped), nonNull(implementation));
}
@Override
public InstrumentedType prepare(InstrumentedType instrumentedType) {
for (ArgumentLoader argumentLoader : argumentLoaders) {
instrumentedType = argumentLoader.prepare(instrumentedType);
}
return targetHandler.prepare(instrumentedType);
}
@Override
public ByteCodeAppender appender(Target implementationTarget) {
return new Appender(implementationTarget);
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (!(other instanceof MethodCall)) return false;
MethodCall that = (MethodCall) other;
return dynamicallyTyped == that.dynamicallyTyped
&& argumentLoaders.equals(that.argumentLoaders)
&& assigner.equals(that.assigner)
&& methodInvoker.equals(that.methodInvoker)
&& methodLocator.equals(that.methodLocator)
&& targetHandler.equals(that.targetHandler)
&& terminationHandler.equals(that.terminationHandler);
}
@Override
public int hashCode() {
int result = methodLocator.hashCode();
result = 31 * result + targetHandler.hashCode();
result = 31 * result + argumentLoaders.hashCode();
result = 31 * result + methodInvoker.hashCode();
result = 31 * result + terminationHandler.hashCode();
result = 31 * result + assigner.hashCode();
result = 31 * result + (dynamicallyTyped ? 1 : 0);
return result;
}
@Override
public String toString() {
return "MethodCall{" +
"methodLocator=" + methodLocator +
", targetHandler=" + targetHandler +
", argumentLoaders=" + argumentLoaders +
", methodInvoker=" + methodInvoker +
", terminationHandler=" + terminationHandler +
", assigner=" + assigner +
", dynamicallyTyped=" + dynamicallyTyped +
'}';
}
/**
* A method locator is responsible for identifying the method that is to be invoked
* by a {@link net.bytebuddy.implementation.MethodCall}.
*/
public interface MethodLocator {
/**
* Resolves the method to be invoked.
*
* @param instrumentedMethod The method being instrumented.
* @return The method to invoke.
*/
MethodDescription resolve(MethodDescription instrumentedMethod);
/**
* A method locator that simply returns the intercepted method.
*/
enum ForInterceptedMethod implements MethodLocator {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public MethodDescription resolve(MethodDescription instrumentedMethod) {
return instrumentedMethod;
}
@Override
public String toString() {
return "MethodCall.MethodLocator.ForInterceptedMethod." + name();
}
}
/**
* Invokes a given method.
*/
class ForExplicitMethod implements MethodLocator {
/**
* The method to be invoked.
*/
private final MethodDescription methodDescription;
/**
* Creates a new method locator for a given method.
*
* @param methodDescription The method to be invoked.
*/
public ForExplicitMethod(MethodDescription methodDescription) {
this.methodDescription = methodDescription;
}
@Override
public MethodDescription resolve(MethodDescription instrumentedMethod) {
return methodDescription;
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& methodDescription.equals(((ForExplicitMethod) other).methodDescription);
}
@Override
public int hashCode() {
return methodDescription.hashCode();
}
@Override
public String toString() {
return "MethodCall.MethodLocator.ForExplicitMethod{" +
"methodDescription=" + methodDescription +
'}';
}
}
}
/**
* A target handler is responsible for invoking a method for a
* {@link net.bytebuddy.implementation.MethodCall}.
*/
protected interface TargetHandler {
/**
* Creates a stack manipulation that represents the method's invocation.
*
* @param methodDescription The method to be invoked.
* @param instrumentedType The instrumented type.
* @return A stack manipulation that invokes the method.
*/
StackManipulation resolve(MethodDescription methodDescription, TypeDescription instrumentedType);
/**
* Prepares the instrumented type in order to allow for the represented invocation.
*
* @param instrumentedType The instrumented type.
* @return The prepared instrumented type.
*/
InstrumentedType prepare(InstrumentedType instrumentedType);
/**
* A target handler that invokes a method either on the instance of the instrumented
* type or as a static method.
*/
enum ForSelfOrStaticInvocation implements TargetHandler {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public StackManipulation resolve(MethodDescription methodDescription, TypeDescription instrumentedType) {
return new StackManipulation.Compound(
methodDescription.isStatic()
? StackManipulation.LegalTrivial.INSTANCE
: MethodVariableAccess.REFERENCE.loadOffset(0),
methodDescription.isConstructor()
? Duplication.SINGLE
: StackManipulation.LegalTrivial.INSTANCE
);
}
@Override
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return instrumentedType;
}
@Override
public String toString() {
return "MethodCall.TargetHandler.ForSelfOrStaticInvocation." + name();
}
}
/**
* Invokes a method in order to construct a new instance.
*/
enum ForConstructingInvocation implements TargetHandler {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public StackManipulation resolve(MethodDescription methodDescription, TypeDescription instrumentedType) {
return new StackManipulation.Compound(TypeCreation.forType(methodDescription.getDeclaringType()), Duplication.SINGLE);
}
@Override
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return instrumentedType;
}
@Override
public String toString() {
return "MethodCall.TargetHandler.ForConstructingInvocation." + name();
}
}
/**
* A target handler that invokes a method on an instance that is stored in a static field.
*/
class ForStaticField implements TargetHandler {
/**
* The name prefix of the field to store the instance.
*/
private static final String FIELD_PREFIX = "invocationTarget";
/**
* The modifiers of the static field to store the instance.
*/
private static final int FIELD_MODIFIERS = Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC | Opcodes.ACC_SYNTHETIC;
/**
* The target on which the method is to be invoked.
*/
private final Object target;
/**
* The name of the field to store the target.
*/
private final String fieldName;
/**
* Creates a new target handler for a static field.
*
* @param target The target on which the method is to be invoked.
*/
public ForStaticField(Object target) {
this.target = target;
fieldName = String.format("%s$%s", FIELD_PREFIX, RandomString.make());
}
@Override
public StackManipulation resolve(MethodDescription methodDescription, TypeDescription instrumentedType) {
if (methodDescription.isStatic() || !methodDescription.getDeclaringType().isInstance(target)) {
throw new IllegalStateException("Cannot invoke " + methodDescription + " on " + target);
}
return FieldAccess.forField(instrumentedType.getDeclaredFields()
.filter(named(fieldName)).getOnly()).getter();
}
@Override
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return instrumentedType
.withField(fieldName, new TypeDescription.ForLoadedType(target.getClass()), FIELD_MODIFIERS)
.withInitializer(LoadedTypeInitializer.ForStaticField.nonAccessible(fieldName, target));
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& target.equals(((ForStaticField) other).target);
}
@Override
public int hashCode() {
return target.hashCode();
}
@Override
public String toString() {
return "MethodCall.TargetHandler.ForStaticField{" +
"target=" + target +
", fieldName='" + fieldName + '\'' +
'}';
}
}
/**
* Creates a target handler that stores the instance to invoke a method on in an instance field.
*/
class ForInstanceField implements TargetHandler {
/**
* The modifiers of the field.
*/
private static final int FIELD_MODIFIERS = Opcodes.ACC_PRIVATE | Opcodes.ACC_SYNTHETIC;
/**
* The name of the field.
*/
private final String fieldName;
/**
* The type of the field.
*/
private final TypeDescription fieldType;
/**
* Creates a new target handler for storing a method invocation target in an
* instance field.
*
* @param fieldName The name of the field.
* @param fieldType The type of the field.
*/
public ForInstanceField(String fieldName, TypeDescription fieldType) {
this.fieldName = fieldName;
this.fieldType = fieldType;
}
@Override
public StackManipulation resolve(MethodDescription methodDescription, TypeDescription instrumentedType) {
if (methodDescription.isStatic() || !methodDescription.isInvokableOn(fieldType)) {
throw new IllegalStateException("Cannot invoke " + methodDescription + " on " + fieldType);
}
return new StackManipulation.Compound(
methodDescription.isStatic()
? StackManipulation.LegalTrivial.INSTANCE
: MethodVariableAccess.REFERENCE.loadOffset(0),
FieldAccess.forField(instrumentedType.getDeclaredFields().filter(named(fieldName)).getOnly()).getter());
}
@Override
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return instrumentedType.withField(fieldName, fieldType, FIELD_MODIFIERS);
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass()) && fieldName
.equals(((ForInstanceField) other).fieldName) && fieldType
.equals(((ForInstanceField) other).fieldType);
}
@Override
public int hashCode() {
int result = fieldName.hashCode();
result = 31 * result + fieldType.hashCode();
return result;
}
@Override
public String toString() {
return "MethodCall.TargetHandler.ForInstanceField{" +
"fieldName='" + fieldName + '\'' +
", fieldType=" + fieldType +
'}';
}
}
}
/**
* An argument loader is responsible for loading an argument for an invoked method
* onto the operand stack.
*/
protected interface ArgumentLoader {
/**
* Loads the argument that is represented by this instance onto the operand stack.
*
* @param instrumentedType The instrumented type.
* @param interceptedMethod The method being intercepted.
* @param targetType The target type.
* @param assigner The assigner to be used.
* @param dynamicallyTyped {@code true} if an assignment should be consider type castings.
* @return The stack manipulation that loads the represented argument onto the stack.
*/
StackManipulation resolve(TypeDescription instrumentedType,
MethodDescription interceptedMethod,
TypeDescription targetType,
Assigner assigner,
boolean dynamicallyTyped);
/**
* Prepares the instrumented type in order to allow the loading of the represented argument.
*
* @param instrumentedType The instrumented type.
* @return The prepared instrumented type.
*/
InstrumentedType prepare(InstrumentedType instrumentedType);
/**
* An argument loader that loads the {@code null} value onto the operand stack.
*/
enum ForNullConstant implements ArgumentLoader {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public StackManipulation resolve(TypeDescription instrumentedType,
MethodDescription interceptedMethod,
TypeDescription targetType,
Assigner assigner,
boolean dynamicallyTyped) {
if (targetType.isPrimitive()) {
throw new IllegalStateException("Cannot assign null to " + targetType);
}
return NullConstant.INSTANCE;
}
@Override
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return instrumentedType;
}
@Override
public String toString() {
return "MethodCall.ArgumentLoader.ForNullConstant." + name();
}
}
/**
* An argument loader that assigns the {@code this} reference to a parameter.
*/
enum ForThisReference implements ArgumentLoader {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public StackManipulation resolve(TypeDescription instrumentedType,
MethodDescription interceptedMethod,
TypeDescription targetType,
Assigner assigner,
boolean dynamicallyTyped) {
if (interceptedMethod.isStatic()) {
throw new IllegalStateException(interceptedMethod + " has no instance");
}
StackManipulation stackManipulation = new StackManipulation.Compound(
MethodVariableAccess.REFERENCE.loadOffset(0),
assigner.assign(instrumentedType, targetType, dynamicallyTyped));
if (!stackManipulation.isValid()) {
throw new IllegalStateException("Cannot assign " + instrumentedType + " to " + targetType);
}
return stackManipulation;
}
@Override
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return instrumentedType;
}
@Override
public String toString() {
return "MethodCall.ArgumentLoader.ForThisReference." + name();
}
}
/**
* Loads the instrumented type onto the operand stack.
*/
enum ForOwnType implements ArgumentLoader {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public StackManipulation resolve(TypeDescription instrumentedType,
MethodDescription interceptedMethod,
TypeDescription targetType,
Assigner assigner,
boolean dynamicallyTyped) {
StackManipulation stackManipulation = new StackManipulation.Compound(
ClassConstant.of(instrumentedType),
assigner.assign(TypeDescription.CLASS, targetType, dynamicallyTyped));
if (!stackManipulation.isValid()) {
throw new IllegalStateException("Cannot assign Class value to " + targetType);
}
return stackManipulation;
}
@Override
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return instrumentedType;
}
@Override
public String toString() {
return "MethodCall.ArgumentLoader.ForOwnType." + name();
}
}
/**
* Loads a parameter of the instrumented method onto the operand stack.
*/
class ForMethodParameter implements ArgumentLoader {
/**
* The index of the parameter to be loaded onto the operand stack.
*/
private final int index;
/**
* Creates an argument loader for a parameter of the instrumented method.
*
* @param index The index of the parameter to be loaded onto the operand stack.
*/
public ForMethodParameter(int index) {
this.index = index;
}
@Override
public StackManipulation resolve(TypeDescription instrumentedType,
MethodDescription interceptedMethod,
TypeDescription targetType,
Assigner assigner,
boolean dynamicallyTyped) {
if (index >= interceptedMethod.getParameters().size()) {
throw new IllegalStateException(interceptedMethod + " does not have a parameter with index " + index);
}
ParameterDescription parameterDescription = interceptedMethod.getParameters().get(index);
StackManipulation stackManipulation = new StackManipulation.Compound(
MethodVariableAccess.forType(parameterDescription.getType()).loadOffset(parameterDescription.getOffset()),
assigner.assign(parameterDescription.getType(), targetType, dynamicallyTyped));
if (!stackManipulation.isValid()) {
throw new IllegalStateException("Cannot assign " + parameterDescription + " to " + targetType + " for " + interceptedMethod);
}
return stackManipulation;
}
@Override
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return instrumentedType;
}
@Override
public boolean equals(Object other) {
return this == other || !(other == null || getClass() != other.getClass())
&& index == ((ForMethodParameter) other).index;
}
@Override
public int hashCode() {
return index;
}
@Override