/
FieldBackedProvider.java
1047 lines (956 loc) · 40.2 KB
/
FieldBackedProvider.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
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.javaagent.tooling.context;
import static io.opentelemetry.javaagent.tooling.bytebuddy.matcher.AgentElementMatchers.safeHasSuperType;
import static io.opentelemetry.javaagent.tooling.bytebuddy.matcher.ClassLoaderMatcher.BOOTSTRAP_CLASSLOADER;
import static net.bytebuddy.matcher.ElementMatchers.named;
import io.opentelemetry.instrumentation.api.config.Config;
import io.opentelemetry.javaagent.bootstrap.FieldBackedContextStoreAppliedMarker;
import io.opentelemetry.javaagent.instrumentation.api.ContextStore;
import io.opentelemetry.javaagent.instrumentation.api.InstrumentationContext;
import io.opentelemetry.javaagent.instrumentation.api.WeakMap;
import io.opentelemetry.javaagent.tooling.HelperInjector;
import io.opentelemetry.javaagent.tooling.InstrumentationModule;
import io.opentelemetry.javaagent.tooling.TransformSafeLogger;
import io.opentelemetry.javaagent.tooling.Utils;
import java.lang.reflect.Method;
import java.security.ProtectionDomain;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.ClassFileVersion;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.asm.AsmVisitorWrapper;
import net.bytebuddy.description.field.FieldDescription;
import net.bytebuddy.description.field.FieldList;
import net.bytebuddy.description.method.MethodList;
import net.bytebuddy.description.modifier.TypeManifestation;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.Implementation;
import net.bytebuddy.jar.asm.ClassVisitor;
import net.bytebuddy.jar.asm.ClassWriter;
import net.bytebuddy.jar.asm.FieldVisitor;
import net.bytebuddy.jar.asm.Label;
import net.bytebuddy.jar.asm.MethodVisitor;
import net.bytebuddy.jar.asm.Opcodes;
import net.bytebuddy.jar.asm.Type;
import net.bytebuddy.pool.TypePool;
import net.bytebuddy.utility.JavaModule;
/**
* InstrumentationContextProvider which stores context in a field that is injected into a class and
* falls back to global map if field was not injected.
*
* <p>This is accomplished by
*
* <ol>
* <li>Injecting a Dynamic Interface that provides getter and setter for context field
* <li>Applying Dynamic Interface to a type needing context, implementing interface methods and
* adding context storage field
* <li>Injecting a Dynamic Class created from {@link ContextStoreImplementationTemplate} to use
* injected field or fall back to a static map
* <li>Rewriting calls to the context-store to access the specific dynamic {@link
* ContextStoreImplementationTemplate}
* </ol>
*
* <p>Example:<br>
* <em>InstrumentationContext.get(Runnable.class, RunnableState.class)")</em><br>
* is rewritten to:<br>
* <em>FieldBackedProvider$ContextStore$Runnable$RunnableState12345.getContextStore(runnableRunnable.class,
* RunnableState.class)</em>
*/
public class FieldBackedProvider implements InstrumentationContextProvider {
private static final TransformSafeLogger log =
TransformSafeLogger.getLogger(FieldBackedProvider.class);
/**
* Note: the value here has to be inside on of the prefixes in
* io.opentelemetry.javaagent.tooling.Constants#BOOTSTRAP_PACKAGE_PREFIXES. This ensures that
* 'isolating' (or 'module') classloaders like jboss and osgi see injected classes. This works
* because we instrument those classloaders to load everything inside bootstrap packages.
*/
private static final String DYNAMIC_CLASSES_PACKAGE =
"io.opentelemetry.javaagent.bootstrap.instrumentation.context.";
private static final String INJECTED_FIELDS_MARKER_CLASS_NAME =
Utils.getInternalName(FieldBackedContextStoreAppliedMarker.class);
private static final Method CONTEXT_GET_METHOD;
private static final Method GET_CONTEXT_STORE_METHOD;
static {
try {
CONTEXT_GET_METHOD = InstrumentationContext.class.getMethod("get", Class.class, Class.class);
GET_CONTEXT_STORE_METHOD =
ContextStoreImplementationTemplate.class.getMethod(
"getContextStore", Class.class, Class.class);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
private static final boolean FIELD_INJECTION_ENABLED =
Config.get().getBooleanProperty("otel.javaagent.experimental.field-injection.enabled", true);
private final Class<?> instrumenterClass;
private final ByteBuddy byteBuddy;
private final Map<String, String> contextStore;
// fields-accessor-interface-name -> fields-accessor-interface-dynamic-type
private final Map<String, DynamicType.Unloaded<?>> fieldAccessorInterfaces;
private final AgentBuilder.Transformer fieldAccessorInterfacesInjector;
// context-store-type-name -> context-store-type-name-dynamic-type
private final Map<String, DynamicType.Unloaded<?>> contextStoreImplementations;
private final AgentBuilder.Transformer contextStoreImplementationsInjector;
public FieldBackedProvider(Class<?> instrumenterClass, Map<String, String> contextStore) {
this.instrumenterClass = instrumenterClass;
this.contextStore = contextStore;
byteBuddy = new ByteBuddy();
fieldAccessorInterfaces = generateFieldAccessorInterfaces();
fieldAccessorInterfacesInjector = bootstrapHelperInjector(fieldAccessorInterfaces.values());
contextStoreImplementations = generateContextStoreImplementationClasses();
contextStoreImplementationsInjector =
bootstrapHelperInjector(contextStoreImplementations.values());
}
@Override
public AgentBuilder.Identified.Extendable instrumentationTransformer(
AgentBuilder.Identified.Extendable builder) {
if (!contextStore.isEmpty()) {
/*
* Install transformer that rewrites accesses to context store with specialized bytecode that
* invokes appropriate storage implementation.
*/
builder =
builder.transform(getTransformerForAsmVisitor(getContextStoreReadsRewritingVisitor()));
builder = injectHelpersIntoBootstrapClassloader(builder);
}
return builder;
}
private AsmVisitorWrapper getContextStoreReadsRewritingVisitor() {
return new AsmVisitorWrapper() {
@Override
public int mergeWriter(int flags) {
return flags | ClassWriter.COMPUTE_MAXS;
}
@Override
public int mergeReader(int flags) {
return flags;
}
@Override
public ClassVisitor wrap(
TypeDescription instrumentedType,
ClassVisitor classVisitor,
Implementation.Context implementationContext,
TypePool typePool,
FieldList<FieldDescription.InDefinedShape> fields,
MethodList<?> methods,
int writerFlags,
int readerFlags) {
return new ClassVisitor(Opcodes.ASM7, classVisitor) {
@Override
public void visit(
int version,
int access,
String name,
String signature,
String superName,
String[] interfaces) {
super.visit(version, access, name, signature, superName, interfaces);
}
@Override
public MethodVisitor visitMethod(
int access, String name, String descriptor, String signature, String[] exceptions) {
MethodVisitor mv = super.visitMethod(access, name, descriptor, signature, exceptions);
return new MethodVisitor(Opcodes.ASM7, mv) {
/** The most recent objects pushed to the stack. */
private final Object[] stack = {null, null};
/** Most recent instructions. */
private final int[] insnStack = {-1, -1, -1};
@Override
public void visitMethodInsn(
int opcode, String owner, String name, String descriptor, boolean isInterface) {
pushOpcode(opcode);
if (Utils.getInternalName(CONTEXT_GET_METHOD.getDeclaringClass()).equals(owner)
&& CONTEXT_GET_METHOD.getName().equals(name)
&& Type.getMethodDescriptor(CONTEXT_GET_METHOD).equals(descriptor)) {
log.trace("Found context-store access in {}", instrumenterClass.getName());
/*
The idea here is that the rest if this method visitor collects last three instructions in `insnStack`
variable. Once we get here we check if those last three instructions constitute call that looks like
`InstrumentationContext.get(K.class, V.class)`. If it does the inside of this if rewrites it to call
dynamically injected context store implementation instead.
*/
if ((insnStack[0] == Opcodes.INVOKESTATIC
&& insnStack[1] == Opcodes.LDC
&& insnStack[2] == Opcodes.LDC)
&& (stack[0] instanceof Type && stack[1] instanceof Type)) {
String contextClassName = ((Type) stack[0]).getClassName();
String keyClassName = ((Type) stack[1]).getClassName();
TypeDescription contextStoreImplementationClass =
getContextStoreImplementation(keyClassName, contextClassName);
if (log.isTraceEnabled()) {
log.trace(
"Rewriting context-store map fetch for instrumenter {}: {} -> {}",
instrumenterClass.getName(),
keyClassName,
contextClassName);
}
if (contextStoreImplementationClass == null) {
throw new IllegalStateException(
String.format(
"Incorrect Context Api Usage detected. Cannot find map holder class for %s context %s. Was that class defined in contextStore for instrumentation %s?",
keyClassName, contextClassName, instrumenterClass.getName()));
}
if (!contextClassName.equals(contextStore.get(keyClassName))) {
throw new IllegalStateException(
String.format(
"Incorrect Context Api Usage detected. Incorrect context class %s, expected %s for instrumentation %s",
contextClassName,
contextStore.get(keyClassName),
instrumenterClass.getName()));
}
// stack: contextClass | keyClass
mv.visitMethodInsn(
Opcodes.INVOKESTATIC,
contextStoreImplementationClass.getInternalName(),
GET_CONTEXT_STORE_METHOD.getName(),
Type.getMethodDescriptor(GET_CONTEXT_STORE_METHOD),
false);
return;
}
throw new IllegalStateException(
"Incorrect Context Api Usage detected. Key and context class must be class-literals. Example of correct usage: InstrumentationContext.get(Runnable.class, RunnableContext.class)");
} else {
super.visitMethodInsn(opcode, owner, name, descriptor, isInterface);
}
}
/** Tracking the most recently used opcodes to assert proper api usage. */
private void pushOpcode(int opcode) {
System.arraycopy(insnStack, 0, insnStack, 1, insnStack.length - 1);
insnStack[0] = opcode;
}
/**
* Tracking the most recently pushed objects on the stack to assert proper api usage.
*/
private void pushStack(Object o) {
System.arraycopy(stack, 0, stack, 1, stack.length - 1);
stack[0] = o;
}
@Override
public void visitInsn(int opcode) {
pushOpcode(opcode);
super.visitInsn(opcode);
}
@Override
public void visitJumpInsn(int opcode, Label label) {
pushOpcode(opcode);
super.visitJumpInsn(opcode, label);
}
@Override
public void visitIntInsn(int opcode, int operand) {
pushOpcode(opcode);
super.visitIntInsn(opcode, operand);
}
@Override
public void visitVarInsn(int opcode, int var) {
pushOpcode(opcode);
pushStack(var);
super.visitVarInsn(opcode, var);
}
@Override
public void visitLdcInsn(Object value) {
pushOpcode(Opcodes.LDC);
pushStack(value);
super.visitLdcInsn(value);
}
};
}
};
}
};
}
private AgentBuilder.Identified.Extendable injectHelpersIntoBootstrapClassloader(
AgentBuilder.Identified.Extendable builder) {
/*
* We inject into bootstrap classloader because field accessor interfaces are needed by context
* store implementations. Unfortunately this forces us to remove stored type checking because
* actual classes may not be available at this point.
*/
builder = builder.transform(fieldAccessorInterfacesInjector);
/*
* We inject context store implementation into bootstrap classloader because same implementation
* may be used by different instrumentations and it has to use same static map in case of
* fallback to map-backed storage.
*/
builder = builder.transform(contextStoreImplementationsInjector);
return builder;
}
/** Get transformer that forces helper injection onto bootstrap classloader. */
private AgentBuilder.Transformer bootstrapHelperInjector(
final Collection<DynamicType.Unloaded<?>> helpers) {
// TODO: Better to pass through the context of the Instrumenter
return new AgentBuilder.Transformer() {
final HelperInjector injector =
HelperInjector.forDynamicTypes(getClass().getSimpleName(), helpers);
@Override
public DynamicType.Builder<?> transform(
DynamicType.Builder<?> builder,
TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module) {
return injector.transform(
builder,
typeDescription,
// context store implementation classes will always go to the bootstrap
BOOTSTRAP_CLASSLOADER,
module);
}
};
}
/*
Set of pairs (context holder, context class) for which we have matchers installed.
We use this to make sure we do not install matchers repeatedly for cases when same
context class is used by multiple instrumentations.
*/
private static final Set<Map.Entry<String, String>> INSTALLED_CONTEXT_MATCHERS = new HashSet<>();
/** Clear set that prevents multiple matchers for same context class. */
public static void resetContextMatchers() {
synchronized (INSTALLED_CONTEXT_MATCHERS) {
INSTALLED_CONTEXT_MATCHERS.clear();
}
}
@Override
public AgentBuilder.Identified.Extendable additionalInstrumentation(
AgentBuilder.Identified.Extendable builder) {
if (FIELD_INJECTION_ENABLED) {
for (Map.Entry<String, String> entry : contextStore.entrySet()) {
/*
* For each context store defined in a current instrumentation we create an agent builder
* that injects necessary fields.
* Note: this synchronization should not have any impact on performance
* since this is done when agent builder is being made, it doesn't affect actual
* class transformation.
*/
synchronized (INSTALLED_CONTEXT_MATCHERS) {
if (INSTALLED_CONTEXT_MATCHERS.contains(entry)) {
log.trace("Skipping builder for {} {}", instrumenterClass.getName(), entry);
continue;
}
log.trace("Making builder for {} {}", instrumenterClass.getName(), entry);
INSTALLED_CONTEXT_MATCHERS.add(entry);
/*
* For each context store defined in a current instrumentation we create an agent builder
* that injects necessary fields.
*/
builder =
builder
.type(safeHasSuperType(named(entry.getKey())))
.and(safeToInjectFieldsMatcher())
.and(InstrumentationModule.NOT_DECORATOR_MATCHER)
.transform(NoOpTransformer.INSTANCE);
/*
* We inject helpers here as well as when instrumentation is applied to ensure that
* helpers are present even if instrumented classes are not loaded, but classes with state
* fields added are loaded (e.g. sun.net.www.protocol.https.HttpsURLConnectionImpl).
*/
builder = injectHelpersIntoBootstrapClassloader(builder);
builder =
builder.transform(
getTransformerForAsmVisitor(
getFieldInjectionVisitor(entry.getKey(), entry.getValue())));
}
}
}
return builder;
}
private static AgentBuilder.RawMatcher safeToInjectFieldsMatcher() {
return new AgentBuilder.RawMatcher() {
@Override
public boolean matches(
TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain) {
/*
* The idea here is that we can add fields if class is just being loaded
* (classBeingRedefined == null) and we have to add same fields again if class we added
* fields before is being transformed again. Note: here we assume that Class#getInterfaces()
* returns list of interfaces defined immediately on a given class, not inherited from its
* parents. It looks like current JVM implementation does exactly this but javadoc is not
* explicit about that.
*/
return classBeingRedefined == null
|| Arrays.asList(classBeingRedefined.getInterfaces())
.contains(FieldBackedContextStoreAppliedMarker.class);
}
};
}
private AsmVisitorWrapper getFieldInjectionVisitor(
final String keyClassName, final String contextClassName) {
return new AsmVisitorWrapper() {
@Override
public int mergeWriter(int flags) {
return flags | ClassWriter.COMPUTE_MAXS;
}
@Override
public int mergeReader(int flags) {
return flags;
}
@Override
public ClassVisitor wrap(
final TypeDescription instrumentedType,
ClassVisitor classVisitor,
Implementation.Context implementationContext,
TypePool typePool,
FieldList<FieldDescription.InDefinedShape> fields,
MethodList<?> methods,
int writerFlags,
int readerFlags) {
return new ClassVisitor(Opcodes.ASM7, classVisitor) {
// We are using Object class name instead of contextClassName here because this gets
// injected onto Bootstrap classloader where context class may be unavailable
private final TypeDescription contextType =
new TypeDescription.ForLoadedType(Object.class);
private final String fieldName = getContextFieldName(keyClassName);
private final String getterMethodName = getContextGetterName(keyClassName);
private final String setterMethodName = getContextSetterName(keyClassName);
private final TypeDescription interfaceType =
getFieldAccessorInterface(keyClassName, contextClassName);
private boolean foundField = false;
private boolean foundGetter = false;
private boolean foundSetter = false;
@Override
public void visit(
int version,
int access,
String name,
String signature,
String superName,
String[] interfaces) {
if (interfaces == null) {
interfaces = new String[] {};
}
Set<String> set = new LinkedHashSet<>(Arrays.asList(interfaces));
set.add(INJECTED_FIELDS_MARKER_CLASS_NAME);
set.add(interfaceType.getInternalName());
super.visit(version, access, name, signature, superName, set.toArray(new String[] {}));
}
@Override
public FieldVisitor visitField(
int access, String name, String descriptor, String signature, Object value) {
if (name.equals(fieldName)) {
foundField = true;
}
return super.visitField(access, name, descriptor, signature, value);
}
@Override
public MethodVisitor visitMethod(
int access, String name, String descriptor, String signature, String[] exceptions) {
if (name.equals(getterMethodName)) {
foundGetter = true;
}
if (name.equals(setterMethodName)) {
foundSetter = true;
}
return super.visitMethod(access, name, descriptor, signature, exceptions);
}
@Override
public void visitEnd() {
// Checking only for field existence is not enough as libraries like CGLIB only copy
// public/protected methods and not fields (neither public nor private ones) when
// they enhance a class.
// For this reason we check separately for the field and for the two accessors.
if (!foundField) {
cv.visitField(
// Field should be transient to avoid being serialized with the object.
Opcodes.ACC_PRIVATE | Opcodes.ACC_TRANSIENT,
fieldName,
contextType.getDescriptor(),
null,
null);
}
if (!foundGetter) {
addGetter();
}
if (!foundSetter) {
addSetter();
}
super.visitEnd();
}
// just 'standard' getter implementation
private void addGetter() {
MethodVisitor mv = getAccessorMethodVisitor(getterMethodName);
mv.visitCode();
mv.visitVarInsn(Opcodes.ALOAD, 0);
mv.visitFieldInsn(
Opcodes.GETFIELD,
instrumentedType.getInternalName(),
fieldName,
contextType.getDescriptor());
mv.visitInsn(Opcodes.ARETURN);
mv.visitMaxs(0, 0);
mv.visitEnd();
}
// just 'standard' setter implementation
private void addSetter() {
MethodVisitor mv = getAccessorMethodVisitor(setterMethodName);
mv.visitCode();
mv.visitVarInsn(Opcodes.ALOAD, 0);
mv.visitVarInsn(Opcodes.ALOAD, 1);
mv.visitFieldInsn(
Opcodes.PUTFIELD,
instrumentedType.getInternalName(),
fieldName,
contextType.getDescriptor());
mv.visitInsn(Opcodes.RETURN);
mv.visitMaxs(0, 0);
mv.visitEnd();
}
private MethodVisitor getAccessorMethodVisitor(String methodName) {
return cv.visitMethod(
Opcodes.ACC_PUBLIC,
methodName,
Utils.getMethodDefinition(interfaceType, methodName).getDescriptor(),
null,
null);
}
};
}
};
}
private TypeDescription getContextStoreImplementation(
String keyClassName, String contextClassName) {
DynamicType.Unloaded<?> type =
contextStoreImplementations.get(
getContextStoreImplementationClassName(keyClassName, contextClassName));
if (type == null) {
return null;
} else {
return type.getTypeDescription();
}
}
private Map<String, DynamicType.Unloaded<?>> generateContextStoreImplementationClasses() {
Map<String, DynamicType.Unloaded<?>> contextStoreImplementations =
new HashMap<>(contextStore.size());
for (Map.Entry<String, String> entry : contextStore.entrySet()) {
DynamicType.Unloaded<?> type =
makeContextStoreImplementationClass(entry.getKey(), entry.getValue());
contextStoreImplementations.put(type.getTypeDescription().getName(), type);
}
return Collections.unmodifiableMap(contextStoreImplementations);
}
/**
* Generate an 'implementation' of a context store class for given key class name and context
* class name.
*
* @param keyClassName key class name
* @param contextClassName context class name
* @return unloaded dynamic type containing generated class
*/
private DynamicType.Unloaded<?> makeContextStoreImplementationClass(
String keyClassName, String contextClassName) {
return byteBuddy
.rebase(ContextStoreImplementationTemplate.class)
.modifiers(Visibility.PUBLIC, TypeManifestation.FINAL)
.name(getContextStoreImplementationClassName(keyClassName, contextClassName))
.visit(getContextStoreImplementationVisitor(keyClassName, contextClassName))
.make();
}
/**
* Returns a visitor that 'fills in' missing methods into concrete implementation of
* ContextStoreImplementationTemplate for given key class name and context class name.
*
* @param keyClassName key class name
* @param contextClassName context class name
* @return visitor that adds implementation for methods that need to be generated
*/
private AsmVisitorWrapper getContextStoreImplementationVisitor(
final String keyClassName, final String contextClassName) {
return new AsmVisitorWrapper() {
@Override
public int mergeWriter(int flags) {
return flags | ClassWriter.COMPUTE_MAXS;
}
@Override
public int mergeReader(int flags) {
return flags;
}
@Override
public ClassVisitor wrap(
final TypeDescription instrumentedType,
ClassVisitor classVisitor,
final Implementation.Context implementationContext,
TypePool typePool,
FieldList<FieldDescription.InDefinedShape> fields,
MethodList<?> methods,
int writerFlags,
int readerFlags) {
return new ClassVisitor(Opcodes.ASM7, classVisitor) {
private final TypeDescription accessorInterface =
getFieldAccessorInterface(keyClassName, contextClassName);
private final String accessorInterfaceInternalName = accessorInterface.getInternalName();
private final String instrumentedTypeInternalName = instrumentedType.getInternalName();
private final boolean frames =
implementationContext.getClassFileVersion().isAtLeast(ClassFileVersion.JAVA_V6);
@Override
public MethodVisitor visitMethod(
int access, String name, String descriptor, String signature, String[] exceptions) {
if ("realGet".equals(name)) {
generateRealGetMethod(name);
return null;
} else if ("realPut".equals(name)) {
generateRealPutMethod(name);
return null;
} else if ("realSynchronizeInstance".equals(name)) {
generateRealSynchronizeInstanceMethod(name);
return null;
} else {
return super.visitMethod(access, name, descriptor, signature, exceptions);
}
}
/**
* Provides implementation for {@code realGet} method that looks like below.
*
* <blockquote>
*
* <pre>
* private Object realGet(final Object key) {
* if (key instanceof $accessorInterfaceInternalName) {
* return (($accessorInterfaceInternalName) key).$getterName();
* } else {
* return mapGet(key);
* }
* }
* </pre>
*
* </blockquote>
*
* @param name name of the method being visited
*/
private void generateRealGetMethod(String name) {
String getterName = getContextGetterName(keyClassName);
Label elseLabel = new Label();
MethodVisitor mv = getMethodVisitor(name);
mv.visitCode();
mv.visitVarInsn(Opcodes.ALOAD, 1);
mv.visitTypeInsn(Opcodes.INSTANCEOF, accessorInterfaceInternalName);
mv.visitJumpInsn(Opcodes.IFEQ, elseLabel);
mv.visitVarInsn(Opcodes.ALOAD, 1);
mv.visitTypeInsn(Opcodes.CHECKCAST, accessorInterfaceInternalName);
mv.visitMethodInsn(
Opcodes.INVOKEINTERFACE,
accessorInterfaceInternalName,
getterName,
Utils.getMethodDefinition(accessorInterface, getterName).getDescriptor(),
true);
mv.visitInsn(Opcodes.ARETURN);
mv.visitLabel(elseLabel);
if (frames) {
mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
}
mv.visitVarInsn(Opcodes.ALOAD, 0);
mv.visitVarInsn(Opcodes.ALOAD, 1);
mv.visitMethodInsn(
Opcodes.INVOKESPECIAL,
instrumentedTypeInternalName,
"mapGet",
Utils.getMethodDefinition(instrumentedType, "mapGet").getDescriptor(),
false);
mv.visitInsn(Opcodes.ARETURN);
mv.visitMaxs(0, 0);
mv.visitEnd();
}
/**
* Provides implementation for {@code realPut} method that looks like below.
*
* <blockquote>
*
* <pre>
* private void realPut(final Object key, final Object value) {
* if (key instanceof $accessorInterfaceInternalName) {
* (($accessorInterfaceInternalName) key).$setterName(value);
* } else {
* mapPut(key, value);
* }
* }
* </pre>
*
* </blockquote>
*
* @param name name of the method being visited
*/
private void generateRealPutMethod(String name) {
String setterName = getContextSetterName(keyClassName);
Label elseLabel = new Label();
Label endLabel = new Label();
MethodVisitor mv = getMethodVisitor(name);
mv.visitCode();
mv.visitVarInsn(Opcodes.ALOAD, 1);
mv.visitTypeInsn(Opcodes.INSTANCEOF, accessorInterfaceInternalName);
mv.visitJumpInsn(Opcodes.IFEQ, elseLabel);
mv.visitVarInsn(Opcodes.ALOAD, 1);
mv.visitTypeInsn(Opcodes.CHECKCAST, accessorInterfaceInternalName);
mv.visitVarInsn(Opcodes.ALOAD, 2);
mv.visitMethodInsn(
Opcodes.INVOKEINTERFACE,
accessorInterfaceInternalName,
setterName,
Utils.getMethodDefinition(accessorInterface, setterName).getDescriptor(),
true);
mv.visitJumpInsn(Opcodes.GOTO, endLabel);
mv.visitLabel(elseLabel);
if (frames) {
mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
}
mv.visitVarInsn(Opcodes.ALOAD, 0);
mv.visitVarInsn(Opcodes.ALOAD, 1);
mv.visitVarInsn(Opcodes.ALOAD, 2);
mv.visitMethodInsn(
Opcodes.INVOKESPECIAL,
instrumentedTypeInternalName,
"mapPut",
Utils.getMethodDefinition(instrumentedType, "mapPut").getDescriptor(),
false);
mv.visitLabel(endLabel);
if (frames) {
mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
}
mv.visitInsn(Opcodes.RETURN);
mv.visitMaxs(0, 0);
mv.visitEnd();
}
/**
* Provides implementation for {@code realSynchronizeInstance} method that looks like
* below.
*
* <blockquote>
*
* <pre>
* private Object realSynchronizeInstance(final Object key) {
* if (key instanceof $accessorInterfaceInternalName) {
* return key;
* } else {
* return mapSynchronizeInstance(key);
* }
* }
* </pre>
*
* </blockquote>
*
* @param name name of the method being visited
*/
private void generateRealSynchronizeInstanceMethod(String name) {
MethodVisitor mv = getMethodVisitor(name);
mv.visitCode();
mv.visitVarInsn(Opcodes.ALOAD, 1);
mv.visitTypeInsn(Opcodes.INSTANCEOF, accessorInterfaceInternalName);
Label elseLabel = new Label();
mv.visitJumpInsn(Opcodes.IFEQ, elseLabel);
mv.visitVarInsn(Opcodes.ALOAD, 1);
mv.visitInsn(Opcodes.ARETURN);
mv.visitLabel(elseLabel);
if (frames) {
mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
}
mv.visitVarInsn(Opcodes.ALOAD, 0);
mv.visitVarInsn(Opcodes.ALOAD, 1);
mv.visitMethodInsn(
Opcodes.INVOKESPECIAL,
instrumentedTypeInternalName,
"mapSynchronizeInstance",
Utils.getMethodDefinition(instrumentedType, "mapSynchronizeInstance")
.getDescriptor(),
false);
mv.visitInsn(Opcodes.ARETURN);
mv.visitMaxs(0, 0);
mv.visitEnd();
}
private MethodVisitor getMethodVisitor(String methodName) {
return cv.visitMethod(
Opcodes.ACC_PRIVATE,
methodName,
Utils.getMethodDefinition(instrumentedType, methodName).getDescriptor(),
null,
null);
}
};
}
};
}
/**
* Template class used to generate the class that accesses stored context using either key
* instance's own injected field or global hash map if field is not available.
*/
private static final class ContextStoreImplementationTemplate
implements ContextStore<Object, Object> {
private static final ContextStoreImplementationTemplate INSTANCE =
new ContextStoreImplementationTemplate(WeakMap.Provider.newWeakMap());
private final WeakMap map;
private ContextStoreImplementationTemplate(WeakMap map) {
this.map = map;
}
@Override
public Object get(Object key) {
return realGet(key);
}
@Override
public Object putIfAbsent(Object key, Object context) {
Object existingContext = realGet(key);
if (null != existingContext) {
return existingContext;
}
synchronized (realSynchronizeInstance(key)) {
existingContext = realGet(key);
if (null != existingContext) {
return existingContext;
}
realPut(key, context);
return context;
}
}
@Override
public Object putIfAbsent(Object key, Factory<Object> contextFactory) {
Object existingContext = realGet(key);
if (null != existingContext) {
return existingContext;
}
synchronized (realSynchronizeInstance(key)) {
existingContext = realGet(key);
if (null != existingContext) {
return existingContext;
}
Object context = contextFactory.create();
realPut(key, context);
return context;
}
}
@Override
public void put(Object key, Object context) {
realPut(key, context);
}
private Object realGet(Object key) {
// to be generated
return null;
}
private void realPut(Object key, Object value) {
// to be generated
}
private Object realSynchronizeInstance(Object key) {
// to be generated
return null;
}
private Object mapGet(Object key) {
return map.get(key);
}
private void mapPut(Object key, Object value) {
if (value == null) {
map.remove(key);
} else {
map.put(key, value);
}
}
private Object mapSynchronizeInstance(Object key) {
return map;
}
public static ContextStore getContextStore(Class keyClass, Class contextClass) {
// We do not actually check the keyClass here - but that should be fine since compiler would
// check things for us.
return INSTANCE;
}
}
private TypeDescription getFieldAccessorInterface(String keyClassName, String contextClassName) {
DynamicType.Unloaded<?> type =
fieldAccessorInterfaces.get(
getContextAccessorInterfaceName(keyClassName, contextClassName));
if (type == null) {
return null;
} else {
return type.getTypeDescription();
}
}
private Map<String, DynamicType.Unloaded<?>> generateFieldAccessorInterfaces() {
Map<String, DynamicType.Unloaded<?>> fieldAccessorInterfaces =
new HashMap<>(contextStore.size());
for (Map.Entry<String, String> entry : contextStore.entrySet()) {
DynamicType.Unloaded<?> type = makeFieldAccessorInterface(entry.getKey(), entry.getValue());
fieldAccessorInterfaces.put(type.getTypeDescription().getName(), type);
}
return Collections.unmodifiableMap(fieldAccessorInterfaces);
}
/**
* Generate an interface that provides field accessor methods for given key class name and context
* class name.
*
* @param keyClassName key class name
* @param contextClassName context class name
* @return unloaded dynamic type containing generated interface
*/
private DynamicType.Unloaded<?> makeFieldAccessorInterface(
String keyClassName, String contextClassName) {
// We are using Object class name instead of contextClassName here because this gets injected
// onto Bootstrap classloader where context class may be unavailable
TypeDescription contextType = new TypeDescription.ForLoadedType(Object.class);
return byteBuddy
.makeInterface()
.name(getContextAccessorInterfaceName(keyClassName, contextClassName))
.defineMethod(getContextGetterName(keyClassName), contextType, Visibility.PUBLIC)
.withoutCode()
.defineMethod(getContextSetterName(keyClassName), TypeDescription.VOID, Visibility.PUBLIC)
.withParameter(contextType, "value")
.withoutCode()
.make();
}
private AgentBuilder.Transformer getTransformerForAsmVisitor(final AsmVisitorWrapper visitor) {
return new AgentBuilder.Transformer() {
@Override
public DynamicType.Builder<?> transform(
DynamicType.Builder<?> builder,
TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module) {
return builder.visit(visitor);
}
};