diff --git a/field-inject/src/glue/java/datadog/instrument/glue/ObjectStoreGlueGenerator.java b/field-inject/src/glue/java/datadog/instrument/glue/ObjectStoreGlueGenerator.java
index 75eda10..58b8e7f 100644
--- a/field-inject/src/glue/java/datadog/instrument/glue/ObjectStoreGlueGenerator.java
+++ b/field-inject/src/glue/java/datadog/instrument/glue/ObjectStoreGlueGenerator.java
@@ -20,7 +20,6 @@
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
-import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Handle;
@@ -31,7 +30,17 @@
import org.objectweb.asm.commons.Remapper;
import org.objectweb.asm.commons.SimpleRemapper;
-/** Generates local and bootstrap object-store dispatch. */
+/**
+ * Generates key-accessor interfaces and dispatch methods for field-injected object stores. Local
+ * bytecode is written as class resources. Bootstrap bytecode is encoded as ISO-8859-1 strings and
+ * written as constants inside a Java class at build-time.
+ *
+ *
At runtime the bootstrap glue is decoded and injected into the bootstrap class-loader. Its
+ * fallback calls bind to the original {@code GlobalObjectStore} through constant call sites.
+ *
+ *
Both versions share the same emitters; bootstrap names are relocated into {@code java.lang}
+ * for accessibility reasons.
+ */
final class ObjectStoreGlueGenerator {
// generated dispatch glue
private static final String KEY_CLASS = "datadog/instrument/fieldinject/KeyWithValue";
@@ -42,17 +51,20 @@ final class ObjectStoreGlueGenerator {
private static final String BOOT_DISPATCH_CLASS = "java/lang/$Datadog$ObjectStoreDispatch";
// fallback dispatch target
- private static final String GLOBALOBJECTSTORE_CLASS =
+ private static final String GLOBAL_STORE_CLASS =
"datadog/instrument/fieldinject/GlobalObjectStore";
private static final String OBJECT_CLASS = "java/lang/Object";
private static final String FUNCTION_CLASS = "java/util/function/Function";
private static final String LOOKUP_CLASS = "java/lang/invoke/MethodHandles$Lookup";
+ private static final String CONSTANTCALLSITE_CLASS = "java/lang/invoke/ConstantCallSite";
private static final String LOOKUP_DESCRIPTOR = "L" + LOOKUP_CLASS + ";";
private static final String BOOTSTRAP_DESCRIPTOR =
"("
+ LOOKUP_DESCRIPTOR
+ "Ljava/lang/String;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;";
+ private static final Handle BOOTSTRAP_HANDLE =
+ new Handle(H_INVOKESTATIC, DISPATCH_CLASS, "bootstrap", BOOTSTRAP_DESCRIPTOR, false);
private static final String INJECTED_STORE_MARKER = "__dd_instrument$";
@@ -69,9 +81,34 @@ final class ObjectStoreGlueGenerator {
"(L" + OBJECT_CLASS + ";IL" + FUNCTION_CLASS + ";)L" + OBJECT_CLASS + ";";
private static final String REMOVE_DESCRIPTOR = "(L" + OBJECT_CLASS + ";I)L" + OBJECT_CLASS + ";";
+ // argument slots shared by all static dispatch methods; VALUE_ARG may hold a mapping function
+ private static final int KEY_ARG = 0;
+ private static final int STORE_ID_ARG = 1;
+ private static final int VALUE_ARG = 2;
+
private static final String FUNCTION_APPLY_DESCRIPTOR =
"(L" + OBJECT_CLASS + ";)L" + OBJECT_CLASS + ";";
+ /** Emits only the invocation; argument loading and return instructions are shared. */
+ @FunctionalInterface
+ private interface Call {
+ void emit(MethodVisitor mv, String method, String descriptor);
+ }
+
+ private static final Call GLOBAL_CALL =
+ (mv, method, descriptor) ->
+ mv.visitMethodInsn(INVOKESTATIC, GLOBAL_STORE_CLASS, method, descriptor, false);
+
+ // Checked get/put share the terminal indy instructions in weakGet/weakPut.
+ private static final Call WEAK_CALL =
+ (mv, method, descriptor) -> {
+ final String weakMethod = method.equals("get") ? "weakGet" : "weakPut";
+ mv.visitMethodInsn(INVOKESTATIC, DISPATCH_CLASS, weakMethod, descriptor, false);
+ };
+
+ private static final Call INDY_CALL =
+ (mv, method, descriptor) -> mv.visitInvokeDynamicInsn(method, descriptor, BOOTSTRAP_HANDLE);
+
private ObjectStoreGlueGenerator() {}
/**
@@ -83,27 +120,21 @@ private ObjectStoreGlueGenerator() {}
* @see GlueGenerator#main
*/
public static void generateGlue(Path resourcePath, Path javaPath) throws IOException {
- byte[] keyWithValueBytecode = generateKey();
- byte[] objectStoreDispatchBytecode = generateLocalDispatch();
+ Path objectStoreGlue = javaPath.resolve("ObjectStoreGlue.java");
// first generate dispatch glue for the field-inject package
- Path fieldInjectPackagePath = resourcePath.resolveSibling("fieldinject");
- Files.createDirectories(fieldInjectPackagePath);
- writeClassResource(fieldInjectPackagePath, KEY_CLASS, keyWithValueBytecode);
- writeClassResource(fieldInjectPackagePath, DISPATCH_CLASS, objectStoreDispatchBytecode);
+ Path fieldInjectPackage = resourcePath.resolveSibling("fieldinject");
+ Files.createDirectories(fieldInjectPackage);
+ writeClassResource(fieldInjectPackage, KEY_CLASS, generateLocalKey());
+ writeClassResource(fieldInjectPackage, DISPATCH_CLASS, generateLocalDispatch());
// generate bootstrap dispatch glue that binds fallback calls via invokedynamic
- Remapper remapper = bootRemapper();
List lines = new ArrayList<>();
classHeader(lines, "ObjectStoreGlue");
- packGlue(lines, "KEY", BOOT_KEY_CLASS, relocate(remapper, keyWithValueBytecode));
- packGlue(
- lines,
- "DISPATCH",
- BOOT_DISPATCH_CLASS,
- generateBootDispatch(objectStoreDispatchBytecode, remapper));
+ packGlue(lines, "KEY", BOOT_KEY_CLASS, generateBootKey());
+ packGlue(lines, "DISPATCH", BOOT_DISPATCH_CLASS, generateBootDispatch());
lines.add("}");
- Files.write(javaPath.resolve("ObjectStoreGlue.java"), lines, StandardCharsets.UTF_8);
+ Files.write(objectStoreGlue, lines, StandardCharsets.UTF_8);
}
private static Remapper bootRemapper() {
@@ -114,178 +145,174 @@ private static Remapper bootRemapper() {
}
/** Generates bytecode for the {@code KeyWithValue} marker interface. */
- static byte[] generateKey() {
+ static byte[] generateLocalKey() {
ClassWriter cw = new ClassWriter(0);
- cw.visit(
+ emitKey(cw);
+ cw.visitEnd();
+ return cw.toByteArray();
+ }
+
+ private static byte[] generateBootKey() {
+ ClassWriter cw = new ClassWriter(0);
+ ClassVisitor cv = new ClassRemapper(cw, bootRemapper());
+ emitKey(cv);
+ cv.visitEnd();
+ return cw.toByteArray();
+ }
+
+ private static void emitKey(ClassVisitor cv) {
+ cv.visit(
V1_8,
ACC_PUBLIC | ACC_INTERFACE | ACC_ABSTRACT | ACC_SYNTHETIC,
KEY_CLASS,
null,
OBJECT_CLASS,
null);
- cw.visitMethod(ACC_PUBLIC | ACC_ABSTRACT, GET_ACCESSOR, GET_ACCESSOR_DESCRIPTOR, null, null)
+ cv.visitMethod(ACC_PUBLIC | ACC_ABSTRACT, GET_ACCESSOR, GET_ACCESSOR_DESCRIPTOR, null, null)
.visitEnd();
- cw.visitMethod(ACC_PUBLIC | ACC_ABSTRACT, PUT_ACCESSOR, PUT_ACCESSOR_DESCRIPTOR, null, null)
+ cv.visitMethod(ACC_PUBLIC | ACC_ABSTRACT, PUT_ACCESSOR, PUT_ACCESSOR_DESCRIPTOR, null, null)
.visitEnd();
- cw.visitEnd();
- return cw.toByteArray();
}
/** Generates bytecode for {@code ObjectStoreDispatch}. */
static byte[] generateLocalDispatch() {
ClassWriter cw = new ClassWriter(COMPUTE_FRAMES);
- cw.visit(
+ emitDispatch(cw, GLOBAL_CALL, GLOBAL_CALL);
+ cw.visitEnd();
+ return cw.toByteArray();
+ }
+
+ /** Generates the bootstrap object-store dispatcher and its initialization methods. */
+ private static byte[] generateBootDispatch() {
+ ClassWriter cw = new ClassWriter(COMPUTE_FRAMES);
+ ClassVisitor cv = new ClassRemapper(cw, bootRemapper());
+ emitDispatch(cv, WEAK_CALL, INDY_CALL);
+ emitBootstrap(cv);
+ cv.visitEnd();
+ return cw.toByteArray();
+ }
+
+ private static void emitDispatch(ClassVisitor cv, Call checkedCall, Call storeCall) {
+ cv.visit(
V1_8, ACC_PUBLIC | ACC_FINAL | ACC_SYNTHETIC, DISPATCH_CLASS, null, OBJECT_CLASS, null);
// no constructor: this class is only ever used via its static dispatch methods
// simple two-way dispatch: fast path calls the accessor directly, otherwise fall back
- generateCheckedDispatch(cw, "get", GET_DESCRIPTOR);
- generateCheckedDispatch(cw, "put", PUT_DESCRIPTOR);
+ emitChecked(cv, "get", GET_DESCRIPTOR, checkedCall);
+ emitChecked(cv, "put", PUT_DESCRIPTOR, checkedCall);
// double-checked get-then-put dispatch, shared by getOrPut/getOrCompute/remove
- generateDoubleCheckedDispatch(
- cw, "getOrPut", GETORPUT_DESCRIPTOR, mv -> mv.visitVarInsn(ALOAD, 2));
- generateDoubleCheckedDispatch(
- cw,
+ emitDoubleChecked(
+ cv, "getOrPut", GETORPUT_DESCRIPTOR, storeCall, mv -> mv.visitVarInsn(ALOAD, VALUE_ARG));
+ emitDoubleChecked(
+ cv,
"getOrCompute",
GETORCOMPUTE_DESCRIPTOR,
+ storeCall,
mv -> {
- mv.visitVarInsn(ALOAD, 2);
- mv.visitVarInsn(ALOAD, 0);
+ mv.visitVarInsn(ALOAD, VALUE_ARG);
+ mv.visitVarInsn(ALOAD, KEY_ARG);
mv.visitMethodInsn(
INVOKEINTERFACE, FUNCTION_CLASS, "apply", FUNCTION_APPLY_DESCRIPTOR, true);
});
- generateDoubleCheckedDispatch(cw, "remove", REMOVE_DESCRIPTOR, mv -> mv.visitInsn(ACONST_NULL));
+ emitDoubleChecked(cv, "remove", REMOVE_DESCRIPTOR, storeCall, mv -> mv.visitInsn(ACONST_NULL));
- // pass-through access to clean-up method
- generateForwardDispatch(cw, "removeStaleEntries", "removeStaleEntries", "()I");
-
- // weakGet/weakPut skip the fast-path accessor and always go straight to the global store
- generateForwardDispatch(cw, "weakGet", "get", GET_DESCRIPTOR);
- generateForwardDispatch(cw, "weakPut", "put", PUT_DESCRIPTOR);
-
- cw.visitEnd();
- return cw.toByteArray();
- }
-
- /** Relocates dispatch and rewrites fallbacks to {@code invokedynamic}. */
- private static byte[] generateBootDispatch(byte[] local, Remapper remapper) {
- ClassWriter cw = new ClassWriter(0);
- Handle bootstrap =
- new Handle(H_INVOKESTATIC, BOOT_DISPATCH_CLASS, "bootstrap", BOOTSTRAP_DESCRIPTOR, false);
- new ClassReader(local)
- .accept(
- new ClassRemapper(
- new ClassVisitor(ASM9, cw) {
- @Override
- public MethodVisitor visitMethod(
- int access,
- String name,
- String descriptor,
- String signature,
- String[] exceptions) {
- return new MethodVisitor(
- ASM9, super.visitMethod(access, name, descriptor, signature, exceptions)) {
- @Override
- public void visitMethodInsn(
- int opcode,
- String owner,
- String name,
- String descriptor,
- boolean isInterface) {
- if (opcode == INVOKESTATIC && GLOBALOBJECTSTORE_CLASS.equals(owner)) {
- super.visitInvokeDynamicInsn(name, descriptor, bootstrap);
- } else {
- super.visitMethodInsn(opcode, owner, name, descriptor, isInterface);
- }
- }
- };
- }
-
- @Override
- public void visitEnd() {}
- },
- remapper),
- 0);
- generateBootstrap(cw);
- cw.visitEnd();
- return cw.toByteArray();
+ // weakGet/weakPut skip the fast-path accessor and use the terminal store call
+ emitForward(cv, "weakGet", "get", GET_DESCRIPTOR, storeCall);
+ emitForward(cv, "weakPut", "put", PUT_DESCRIPTOR, storeCall);
}
/**
- * Generates bootstrap initialization and linkage.
+ * Emits bootstrap initialization and linkage.
*
*
Inject the glue, then initialize it with a lookup scoped to the {@code GlobalObjectStore}.
* Wait for initialization to succeed before you redirect {@code ObjectStore} or call dispatch.
*
- *
The first binding is permanent. Initialization links all fallback sites before it returns.
- * It links {@code remove} before {@code getOrCompute} so cleanup needs no further linkage.
+ *
The first binding is permanent.
*/
- private static void generateBootstrap(ClassWriter cw) {
- cw.visitField(
+ private static void emitBootstrap(ClassVisitor cv) {
+ cv.visitField(
ACC_PRIVATE | ACC_STATIC | ACC_VOLATILE, "globalLookup", LOOKUP_DESCRIPTOR, null, null)
.visitEnd();
- cw.visitField(ACC_PRIVATE | ACC_STATIC, "linked", "Z", null, null).visitEnd();
+ cv.visitField(ACC_PRIVATE | ACC_STATIC, "linked", "Z", null, null).visitEnd();
+
+ emitInitialize(cv);
+ emitBootstrapMethod(cv);
+ }
- // keep the first binding so later initialization cannot split the call sites across stores
+ /** Emits initialization that binds the global lookup and prelinks all fallback sites. */
+ private static void emitInitialize(ClassVisitor cv) {
MethodVisitor mv =
- cw.visitMethod(
+ cv.visitMethod(
ACC_PUBLIC | ACC_STATIC | ACC_SYNCHRONIZED,
"initialize",
"(" + LOOKUP_DESCRIPTOR + ")V",
null,
null);
+
+ // bytecode positions
+ final Label lookupBound = new Label();
+ final Label returnInitialized = new Label();
+
+ // bytecode variables
+ final int lookup = 0;
+ final int key = 1;
+
mv.visitCode();
- Label bound = new Label();
- mv.visitFieldInsn(GETSTATIC, BOOT_DISPATCH_CLASS, "globalLookup", LOOKUP_DESCRIPTOR);
- mv.visitJumpInsn(IFNONNULL, bound);
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(PUTSTATIC, BOOT_DISPATCH_CLASS, "globalLookup", LOOKUP_DESCRIPTOR);
- mv.visitLabel(bound);
- mv.visitFrame(F_SAME, 0, null, 0, null);
-
- Label initialized = new Label();
- mv.visitFieldInsn(GETSTATIC, BOOT_DISPATCH_CLASS, "linked", "Z");
- mv.visitJumpInsn(IFNE, initialized);
-
- // link every actual fallback instruction before ObjectStore is redirected to this glue,
- // null writes leave the store untouched; getOrCompute's identity result is removed last
+
+ // use one lookup for every fallback so call sites cannot bind to different stores
+ mv.visitFieldInsn(GETSTATIC, DISPATCH_CLASS, "globalLookup", LOOKUP_DESCRIPTOR);
+ mv.visitJumpInsn(IFNONNULL, lookupBound);
+ mv.visitVarInsn(ALOAD, lookup);
+ mv.visitFieldInsn(PUTSTATIC, DISPATCH_CLASS, "globalLookup", LOOKUP_DESCRIPTOR);
+ mv.visitLabel(lookupBound);
+
+ mv.visitFieldInsn(GETSTATIC, DISPATCH_CLASS, "linked", "Z");
+ mv.visitJumpInsn(IFNE, returnInitialized);
+
+ // null writes leave the store untouched; prelink remove before getOrCompute
+ // so its temporary entry can be removed without triggering further linkage
mv.visitTypeInsn(NEW, OBJECT_CLASS);
mv.visitInsn(DUP);
mv.visitMethodInsn(INVOKESPECIAL, OBJECT_CLASS, "", "()V", false);
- mv.visitVarInsn(ASTORE, 1);
- emitPrelinkCall(mv, "put", PUT_DESCRIPTOR);
- emitPrelinkCall(mv, "get", GET_DESCRIPTOR);
- emitPrelinkCall(mv, "getOrPut", GETORPUT_DESCRIPTOR);
- emitPrelinkCall(mv, "weakGet", GET_DESCRIPTOR);
- emitPrelinkCall(mv, "weakPut", PUT_DESCRIPTOR);
- // pre-link remove so linkage failures can't leave getOrCompute's temporary entry behind
- emitPrelinkCall(mv, "remove", REMOVE_DESCRIPTOR);
- emitPrelinkCall(mv, "removeStaleEntries", "()I");
- emitPrelinkCall(mv, "getOrCompute", GETORCOMPUTE_DESCRIPTOR);
- // finally remove the temporary entry from the store through the already-linked fallback
- emitPrelinkCall(mv, "remove", REMOVE_DESCRIPTOR);
+ mv.visitVarInsn(ASTORE, key);
+ emitPrelinkCall(mv, key, "weakPut", PUT_DESCRIPTOR);
+ emitPrelinkCall(mv, key, "weakGet", GET_DESCRIPTOR);
+ emitPrelinkCall(mv, key, "getOrPut", GETORPUT_DESCRIPTOR);
+ emitPrelinkCall(mv, key, "remove", REMOVE_DESCRIPTOR);
+ emitPrelinkCall(mv, key, "getOrCompute", GETORCOMPUTE_DESCRIPTOR);
+ // remove getOrCompute's temporary entry
+ emitPrelinkCall(mv, key, "remove", REMOVE_DESCRIPTOR);
// leave linked unset on failure so later calls fail again rather than report success
mv.visitInsn(ICONST_1);
- mv.visitFieldInsn(PUTSTATIC, BOOT_DISPATCH_CLASS, "linked", "Z");
- mv.visitLabel(initialized);
- mv.visitFrame(F_SAME, 0, null, 0, null);
+ mv.visitFieldInsn(PUTSTATIC, DISPATCH_CLASS, "linked", "Z");
+ mv.visitLabel(returnInitialized);
mv.visitInsn(RETURN);
- mv.visitMaxs(3, 2);
+ mv.visitMaxs(-1, -1);
mv.visitEnd();
+ }
+
+ /** Emits the bootstrap method that binds a fallback to a constant call site. */
+ private static void emitBootstrapMethod(ClassVisitor cv) {
+ MethodVisitor mv =
+ cv.visitMethod(ACC_PRIVATE | ACC_STATIC, "bootstrap", BOOTSTRAP_DESCRIPTOR, null, null);
+
+ // bytecode variables
+ final int methodName = 1;
+ final int methodType = 2;
- // use the stored lookup to bind each fallback by name and type in a ConstantCallSite
- mv = cw.visitMethod(ACC_PRIVATE | ACC_STATIC, "bootstrap", BOOTSTRAP_DESCRIPTOR, null, null);
mv.visitCode();
- mv.visitTypeInsn(NEW, "java/lang/invoke/ConstantCallSite");
+
+ // bind each fallback by name and type using the stored lookup
+ mv.visitTypeInsn(NEW, CONSTANTCALLSITE_CLASS);
mv.visitInsn(DUP);
- mv.visitFieldInsn(GETSTATIC, BOOT_DISPATCH_CLASS, "globalLookup", LOOKUP_DESCRIPTOR);
+ mv.visitFieldInsn(GETSTATIC, DISPATCH_CLASS, "globalLookup", LOOKUP_DESCRIPTOR);
mv.visitInsn(DUP);
mv.visitMethodInsn(INVOKEVIRTUAL, LOOKUP_CLASS, "lookupClass", "()Ljava/lang/Class;", false);
- mv.visitVarInsn(ALOAD, 1);
- mv.visitVarInsn(ALOAD, 2);
+ mv.visitVarInsn(ALOAD, methodName);
+ mv.visitVarInsn(ALOAD, methodType);
mv.visitMethodInsn(
INVOKEVIRTUAL,
LOOKUP_CLASS,
@@ -294,31 +321,29 @@ private static void generateBootstrap(ClassWriter cw) {
false);
mv.visitMethodInsn(
INVOKESPECIAL,
- "java/lang/invoke/ConstantCallSite",
+ CONSTANTCALLSITE_CLASS,
"",
"(Ljava/lang/invoke/MethodHandle;)V",
false);
mv.visitInsn(ARETURN);
- mv.visitMaxs(6, 3);
+ mv.visitMaxs(-1, -1);
mv.visitEnd();
}
- /** Calls a dispatch method on the temporary key in local 1 to link its fallback instruction. */
- private static void emitPrelinkCall(MethodVisitor mv, String method, String descriptor) {
+ /** Calls a dispatch method on the temporary key to link its fallback instruction. */
+ private static void emitPrelinkCall(MethodVisitor mv, int key, String method, String descriptor) {
Type[] args = Type.getArgumentTypes(descriptor);
- if (args.length > 0) {
- mv.visitVarInsn(ALOAD, 1);
- mv.visitInsn(ICONST_0);
- if (args.length > 2) {
- if (FUNCTION_CLASS.equals(args[2].getInternalName())) {
- mv.visitMethodInsn(
- INVOKESTATIC, FUNCTION_CLASS, "identity", "()Ljava/util/function/Function;", true);
- } else {
- mv.visitInsn(ACONST_NULL);
- }
+ mv.visitVarInsn(ALOAD, key);
+ mv.visitInsn(ICONST_0);
+ if (args.length > 2) {
+ if (FUNCTION_CLASS.equals(args[2].getInternalName())) {
+ mv.visitMethodInsn(
+ INVOKESTATIC, FUNCTION_CLASS, "identity", "()Ljava/util/function/Function;", true);
+ } else {
+ mv.visitInsn(ACONST_NULL);
}
}
- mv.visitMethodInsn(INVOKESTATIC, BOOT_DISPATCH_CLASS, method, descriptor, false);
+ mv.visitMethodInsn(INVOKESTATIC, DISPATCH_CLASS, method, descriptor, false);
if (Type.getReturnType(descriptor).getSort() != Type.VOID) {
mv.visitInsn(POP);
}
@@ -329,29 +354,28 @@ private static boolean hasValueArg(String descriptor) {
return Type.getArgumentTypes(descriptor).length > 2;
}
- /** Generates a method that unconditionally delegates to {@code GlobalObjectStore}. */
- private static void generateForwardDispatch(
- ClassWriter cw, String method, String forwardMethod, String descriptor) {
- final MethodVisitor mv =
- cw.visitMethod(ACC_PUBLIC | ACC_STATIC, method, descriptor, null, null);
+ /** Emits a method that unconditionally delegates through the supplied call strategy. */
+ private static void emitForward(
+ ClassVisitor cv, String method, String forwardMethod, String descriptor, Call call) {
+ MethodVisitor mv = cv.visitMethod(ACC_PUBLIC | ACC_STATIC, method, descriptor, null, null);
mv.visitCode();
- emitFallback(mv, forwardMethod, descriptor, 0);
+ emitFallback(mv, call, forwardMethod, descriptor, 0);
mv.visitMaxs(-1, -1);
mv.visitEnd();
}
- /** Generates a getter or putter that dispatches to the fast-path accessor or the fallback. */
- private static void generateCheckedDispatch(ClassWriter cw, String method, String descriptor) {
+ /** Emits a getter or putter that dispatches to the fast-path accessor or the fallback. */
+ private static void emitChecked(ClassVisitor cv, String method, String descriptor, Call call) {
final boolean hasValueArg = hasValueArg(descriptor);
final int returnOpcode = Type.getReturnType(descriptor).getOpcode(IRETURN);
final String accessorMethod = hasValueArg ? PUT_ACCESSOR : GET_ACCESSOR;
final String accessorDescriptor =
hasValueArg ? PUT_ACCESSOR_DESCRIPTOR : GET_ACCESSOR_DESCRIPTOR;
- final MethodVisitor mv =
- cw.visitMethod(ACC_PUBLIC | ACC_STATIC, method, descriptor, null, null);
+ MethodVisitor mv = cv.visitMethod(ACC_PUBLIC | ACC_STATIC, method, descriptor, null, null);
+ // bytecode positions
final Label fallback = new Label();
mv.visitCode();
@@ -359,38 +383,37 @@ private static void generateCheckedDispatch(ClassWriter cw, String method, Strin
// fast path: ((KeyWithValue) key).accessorMethod(storeId[, value])
mv.visitTypeInsn(CHECKCAST, KEY_CLASS);
- mv.visitVarInsn(ILOAD, 1);
+ mv.visitVarInsn(ILOAD, STORE_ID_ARG);
if (hasValueArg) {
- mv.visitVarInsn(ALOAD, 2);
+ mv.visitVarInsn(ALOAD, VALUE_ARG);
}
mv.visitMethodInsn(INVOKEINTERFACE, KEY_CLASS, accessorMethod, accessorDescriptor, true);
mv.visitInsn(returnOpcode);
mv.visitLabel(fallback);
- emitFallback(mv, method, descriptor, 1);
+ emitFallback(mv, call, method, descriptor, 1);
mv.visitMaxs(-1, -1);
mv.visitEnd();
}
/**
- * Generates the double-checked get/put dispatch shared by {@code getOrPut}, {@code getOrCompute}
- * and {@code remove}; {@code valueToStore} emits the value to put on the slow path.
+ * Emits the double-checked get/put dispatch shared by {@code getOrPut}, {@code getOrCompute} and
+ * {@code remove}; {@code valueToStore} emits the value to put on the slow path.
*/
- private static void generateDoubleCheckedDispatch(
- ClassWriter cw, String method, String descriptor, Consumer valueToStore) {
+ private static void emitDoubleChecked(
+ ClassVisitor cv,
+ String method,
+ String descriptor,
+ Call call,
+ Consumer valueToStore) {
final boolean hasValueArg = hasValueArg(descriptor);
- final int accessorLocal = hasValueArg ? 3 : 2;
- final int existingLocal = accessorLocal + 1;
- // getOrPut and getOrCompute return the newly stored value when they write,
- // remove stores null in a separate slot so it can return the previous value
- final int storedLocal = hasValueArg ? existingLocal : existingLocal + 1;
final int skipToReturnOpcode = hasValueArg ? IFNONNULL : IFNULL;
- final MethodVisitor mv =
- cw.visitMethod(ACC_PUBLIC | ACC_STATIC, method, descriptor, null, null);
+ MethodVisitor mv = cv.visitMethod(ACC_PUBLIC | ACC_STATIC, method, descriptor, null, null);
+ // bytecode positions
final Label fallback = new Label();
final Label returnExisting = new Label();
final Label skipPut = new Label();
@@ -398,6 +421,12 @@ private static void generateDoubleCheckedDispatch(
final Label monitorExited = new Label();
final Label unlockAndRethrow = new Label();
+ // bytecode variables
+ final int accessor = hasValueArg ? VALUE_ARG + 1 : VALUE_ARG;
+ final int existing = accessor + 1;
+ // getOrPut/getOrCompute return the newly stored value; remove returns the previous value
+ final int stored = hasValueArg ? existing : existing + 1;
+
mv.visitCode();
mv.visitTryCatchBlock(monitorEntered, monitorExited, unlockAndRethrow, null);
@@ -405,60 +434,60 @@ private static void generateDoubleCheckedDispatch(
// KeyWithValue accessor = (KeyWithValue) key;
mv.visitTypeInsn(CHECKCAST, KEY_CLASS);
- mv.visitVarInsn(ASTORE, accessorLocal);
+ mv.visitVarInsn(ASTORE, accessor);
// Object existing = accessor.$get$__dd_instrument$(storeId);
- emitAccessorGet(mv, accessorLocal, existingLocal);
+ emitAccessorGet(mv, accessor, existing);
// if (existing [is/isn't] null) return existing;
- mv.visitVarInsn(ALOAD, existingLocal);
+ mv.visitVarInsn(ALOAD, existing);
mv.visitJumpInsn(skipToReturnOpcode, returnExisting);
// synchronized (accessor) {
- mv.visitVarInsn(ALOAD, accessorLocal);
+ mv.visitVarInsn(ALOAD, accessor);
mv.visitInsn(MONITORENTER);
mv.visitLabel(monitorEntered);
// existing = accessor.$get$__dd_instrument$(storeId); (recheck under the lock)
- emitAccessorGet(mv, accessorLocal, existingLocal);
+ emitAccessorGet(mv, accessor, existing);
- mv.visitVarInsn(ALOAD, existingLocal);
+ mv.visitVarInsn(ALOAD, existing);
mv.visitJumpInsn(skipToReturnOpcode, skipPut);
// stored = ; accessor.$put$__dd_instrument$(storeId, stored);
valueToStore.accept(mv);
- mv.visitVarInsn(ASTORE, storedLocal);
- mv.visitVarInsn(ALOAD, accessorLocal);
- mv.visitVarInsn(ILOAD, 1);
- mv.visitVarInsn(ALOAD, storedLocal);
+ mv.visitVarInsn(ASTORE, stored);
+ mv.visitVarInsn(ALOAD, accessor);
+ mv.visitVarInsn(ILOAD, STORE_ID_ARG);
+ mv.visitVarInsn(ALOAD, stored);
mv.visitMethodInsn(INVOKEINTERFACE, KEY_CLASS, PUT_ACCESSOR, PUT_ACCESSOR_DESCRIPTOR, true);
mv.visitLabel(skipPut);
- mv.visitVarInsn(ALOAD, accessorLocal);
+ mv.visitVarInsn(ALOAD, accessor);
mv.visitInsn(MONITOREXIT);
mv.visitLabel(monitorExited);
mv.visitJumpInsn(GOTO, returnExisting);
// } unlock and rethrow if anything above failed
mv.visitLabel(unlockAndRethrow);
- mv.visitVarInsn(ALOAD, accessorLocal);
+ mv.visitVarInsn(ALOAD, accessor);
mv.visitInsn(MONITOREXIT);
mv.visitInsn(ATHROW);
mv.visitLabel(returnExisting);
- mv.visitVarInsn(ALOAD, existingLocal);
+ mv.visitVarInsn(ALOAD, existing);
mv.visitInsn(ARETURN);
mv.visitLabel(fallback);
- emitFallback(mv, method, descriptor, 1);
+ emitFallback(mv, call, method, descriptor, 1);
mv.visitMaxs(-1, -1);
mv.visitEnd();
}
- /** Loads the remaining arguments, then calls the global store. */
+ /** Loads the remaining arguments, emits the selected call, and returns its result. */
private static void emitFallback(
- MethodVisitor mv, String method, String descriptor, int loadedArguments) {
+ MethodVisitor mv, Call call, String method, String descriptor, int loadedArguments) {
Type[] arguments = Type.getArgumentTypes(descriptor);
int local = 0;
for (int i = 0; i < arguments.length; i++) {
@@ -468,27 +497,27 @@ private static void emitFallback(
}
local += argument.getSize();
}
- mv.visitMethodInsn(INVOKESTATIC, GLOBALOBJECTSTORE_CLASS, method, descriptor, false);
+ call.emit(mv, method, descriptor);
mv.visitInsn(Type.getReturnType(descriptor).getOpcode(IRETURN));
}
/**
* Emits {@code if (!(key instanceof KeyWithValue)) goto notInjected;} leaving the key reference
- * on the stack, so callers don't need to reload it with {@code ALOAD 0}.
+ * on the stack, so callers don't need to reload the key.
*/
private static void emitInstanceOfCheck(MethodVisitor mv, Label notInjected) {
- mv.visitVarInsn(ALOAD, 0);
+ mv.visitVarInsn(ALOAD, KEY_ARG);
mv.visitInsn(DUP);
mv.visitTypeInsn(INSTANCEOF, KEY_CLASS);
mv.visitJumpInsn(IFEQ, notInjected);
}
/** Emits {@code existing = accessor.$get$__dd_instrument$(storeId);} */
- private static void emitAccessorGet(MethodVisitor mv, int accessorLocal, int existingLocal) {
- mv.visitVarInsn(ALOAD, accessorLocal);
- mv.visitVarInsn(ILOAD, 1);
+ private static void emitAccessorGet(MethodVisitor mv, int accessor, int existing) {
+ mv.visitVarInsn(ALOAD, accessor);
+ mv.visitVarInsn(ILOAD, STORE_ID_ARG);
mv.visitMethodInsn(INVOKEINTERFACE, KEY_CLASS, GET_ACCESSOR, GET_ACCESSOR_DESCRIPTOR, true);
- mv.visitVarInsn(ASTORE, existingLocal);
+ mv.visitVarInsn(ASTORE, existing);
}
private static void packGlue(
@@ -500,14 +529,6 @@ private static void packGlue(
packBytecode(lines, bytecode);
}
- /** Relocates the given bytecode with the given remapper. */
- private static byte[] relocate(Remapper remapper, byte[] originalBytecode) {
- ClassReader cr = new ClassReader(originalBytecode);
- ClassWriter cw = new ClassWriter(0);
- cr.accept(new ClassRemapper(cw, remapper), 0);
- return cw.toByteArray();
- }
-
/** Writes the given bytecode as a resource class file under the given package path. */
private static void writeClassResource(Path packagePath, String internalName, byte[] bytecode)
throws IOException {
diff --git a/field-inject/src/jmh/java/datadog/instrument/fieldinject/DispatchBenchmarkSupport.java b/field-inject/src/jmh/java/datadog/instrument/fieldinject/DispatchBenchmarkSupport.java
index b9dbbf3..e5aa253 100644
--- a/field-inject/src/jmh/java/datadog/instrument/fieldinject/DispatchBenchmarkSupport.java
+++ b/field-inject/src/jmh/java/datadog/instrument/fieldinject/DispatchBenchmarkSupport.java
@@ -9,6 +9,7 @@
import static org.objectweb.asm.Opcodes.*;
import datadog.instrument.classinject.ClassInjector;
+import datadog.instrument.glue.ObjectStoreGlue;
import datadog.instrument.testing.TestAgent;
import java.io.IOException;
import java.lang.instrument.ClassFileTransformer;
@@ -16,6 +17,7 @@
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
+import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.security.ProtectionDomain;
@@ -48,19 +50,20 @@ final class DispatchBenchmarkSupport {
private DispatchBenchmarkSupport() {}
- static synchronized void install(String variant) throws Exception {
+ static synchronized String install(String variant) throws Exception {
+ String dispatchClass =
+ variant.equals("direct") ? DIRECT_DISPATCH : BOOT_PREFIX + "ObjectStoreDispatch_" + variant;
if (installed != null) {
if (!installed.equals(variant)) {
throw new IllegalStateException("Use a separate JMH fork for each variant");
}
- return;
+ return dispatchClass;
}
Instrumentation inst = TestAgent.getInstrumentation();
ClassInjector.enableClassInjection(inst);
injectDirectStore();
- String dispatchClass = DIRECT_DISPATCH;
+ Class> bridge = ClassInjector.injectBootClass(BRIDGE.replace('/', '.'), relocateBridge());
if (!variant.equals("direct")) {
- Class> bridge = ClassInjector.injectBootClass(BRIDGE.replace('/', '.'), relocateBridge());
Map targets = new HashMap<>();
MethodHandles.Lookup lookup = MethodHandles.lookup();
for (Method method : GlobalObjectStore.class.getDeclaredMethods()) {
@@ -69,13 +72,105 @@ static synchronized void install(String variant) throws Exception {
}
}
bridge.getMethod("initialize", Map.class).invoke(null, targets);
- dispatchClass = BOOT_PREFIX + "ObjectStoreDispatch_" + variant;
ClassInjector.injectBootClass(
dispatchClass.replace('/', '.'), dispatcher(variant, dispatchClass));
}
inst.addTransformer(new SelectDispatch(dispatchClass), true);
inst.retransformClasses(ObjectStore.class);
installed = variant;
+ return dispatchClass;
+ }
+
+ static int removeStaleEntries() throws Exception {
+ // Direct dispatch uses the relocated bootstrap store; other variants bind to the local store.
+ if (installed.equals("direct")) {
+ return (Integer)
+ Class.forName(BRIDGE.replace('/', '.')).getMethod("removeStaleEntries").invoke(null);
+ }
+ return ObjectStore.removeStaleEntries();
+ }
+
+ static void populateKeys(String storage, String dispatchClass, Object[]... groups)
+ throws Exception {
+ Constructor> constructor = null;
+ switch (storage) {
+ case "uninjected":
+ break;
+ case "injected":
+ case "weakFallback":
+ String name = BOOT_PREFIX + "DispatchBenchmarkKey_" + storage;
+ constructor =
+ ClassInjector.injectBootClass(
+ name.replace('/', '.'),
+ generateKey(name, storage.equals("injected"), dispatchClass))
+ .getConstructor();
+ break;
+ default:
+ throw new IllegalArgumentException(storage);
+ }
+ for (Object[] keys : groups) {
+ for (int i = 0; i < keys.length; i++) {
+ keys[i] = constructor == null ? new Object() : constructor.newInstance();
+ }
+ }
+ }
+
+ /** Models a field-injected key with either a field or a weak fallback for the requested store. */
+ private static byte[] generateKey(String name, boolean injected, String dispatchClass) {
+ ClassWriter cw = new ClassWriter(0);
+ cw.visit(
+ V1_8,
+ ACC_PUBLIC | ACC_FINAL,
+ name,
+ null,
+ "java/lang/Object",
+ new String[] {ObjectStoreGlue.KEY_ID.replace('.', '/')});
+ if (injected) {
+ cw.visitField(ACC_PRIVATE, "value", "Ljava/lang/Object;", null, null).visitEnd();
+ }
+ MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "", "()V", null, null);
+ mv.visitCode();
+ mv.visitVarInsn(ALOAD, 0);
+ mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "", "()V", false);
+ mv.visitInsn(RETURN);
+ mv.visitMaxs(1, 1);
+ mv.visitEnd();
+
+ mv = cw.visitMethod(ACC_PUBLIC, "$get$__dd_instrument$", "(I)Ljava/lang/Object;", null, null);
+ mv.visitCode();
+ mv.visitVarInsn(ALOAD, 0);
+ if (injected) {
+ mv.visitFieldInsn(GETFIELD, name, "value", "Ljava/lang/Object;");
+ } else {
+ mv.visitVarInsn(ILOAD, 1);
+ mv.visitMethodInsn(
+ INVOKESTATIC, dispatchClass, "weakGet", "(Ljava/lang/Object;I)Ljava/lang/Object;", false);
+ }
+ mv.visitInsn(ARETURN);
+ mv.visitMaxs(2, 2);
+ mv.visitEnd();
+
+ mv = cw.visitMethod(ACC_PUBLIC, "$put$__dd_instrument$", "(ILjava/lang/Object;)V", null, null);
+ mv.visitCode();
+ mv.visitVarInsn(ALOAD, 0);
+ if (injected) {
+ mv.visitVarInsn(ALOAD, 2);
+ mv.visitFieldInsn(PUTFIELD, name, "value", "Ljava/lang/Object;");
+ } else {
+ mv.visitVarInsn(ILOAD, 1);
+ mv.visitVarInsn(ALOAD, 2);
+ mv.visitMethodInsn(
+ INVOKESTATIC,
+ dispatchClass,
+ "weakPut",
+ "(Ljava/lang/Object;ILjava/lang/Object;)V",
+ false);
+ }
+ mv.visitInsn(RETURN);
+ mv.visitMaxs(3, 3);
+ mv.visitEnd();
+ cw.visitEnd();
+ return cw.toByteArray();
}
// Keep the measured baseline independent of the production bootstrap dispatcher.
@@ -104,16 +199,17 @@ private static void injectDirectStore() throws Exception {
private static byte[] relocateBridge() throws IOException {
ClassWriter writer = new ClassWriter(0);
+ Map renames = new HashMap<>();
+ renames.put(Type.getInternalName(DispatchBridge.class), BRIDGE);
+ renames.put(LOCAL_GLOBAL_STORE, BOOT_GLOBAL_STORE);
new ClassReader(DispatchBridge.class.getName())
- .accept(
- new ClassRemapper(
- writer,
- new SimpleRemapper(ASM9, Type.getInternalName(DispatchBridge.class), BRIDGE)),
- 0);
+ .accept(new ClassRemapper(writer, new SimpleRemapper(ASM9, renames)), 0);
return writer.toByteArray();
}
private static byte[] dispatcher(String variant, String dispatchClass) throws IOException {
+ boolean shared = variant.equals("indyShared");
+ boolean indy = variant.equals("indy") || shared;
ClassWriter writer = new ClassWriter(0);
Handle bootstrap =
new Handle(
@@ -138,6 +234,8 @@ public MethodVisitor visitMethod(
String descriptor,
String signature,
String[] exceptions) {
+ String weakFallback =
+ name.equals("get") ? "weakGet" : name.equals("put") ? "weakPut" : null;
return new MethodVisitor(
ASM9, super.visitMethod(access, name, descriptor, signature, exceptions)) {
@Override
@@ -148,7 +246,11 @@ public void visitMethodInsn(
String descriptor,
boolean isInterface) {
if (opcode == INVOKESTATIC && BOOT_GLOBAL_STORE.equals(owner)) {
- if (variant.equals("indy")) {
+ if (shared && weakFallback != null) {
+ // Keep indy only in weakGet/weakPut; normal accessors call them.
+ super.visitMethodInsn(
+ INVOKESTATIC, dispatchClass, weakFallback, descriptor, false);
+ } else if (indy) {
visitInvokeDynamicInsn(name, descriptor, bootstrap);
} else {
super.visitMethodInsn(
@@ -210,7 +312,7 @@ public void visitEnd() {}
},
remapper),
0);
- } else if (!variant.equals("indy")) {
+ } else if (!indy) {
throw new IllegalArgumentException(variant);
}
writer.visitEnd();
@@ -238,7 +340,27 @@ public byte[] transform(
ClassReader reader = new ClassReader(bytecode);
ClassWriter writer = new ClassWriter(reader, 0);
reader.accept(
- new ClassRemapper(writer, new SimpleRemapper(ASM9, LOCAL_GLOBAL_STORE, dispatchClass)),
+ new ClassVisitor(ASM9, writer) {
+ @Override
+ public MethodVisitor visitMethod(
+ int access, String name, String descriptor, String signature, String[] exceptions) {
+ MethodVisitor mv = super.visitMethod(access, name, descriptor, signature, exceptions);
+ // Only instance operations use dispatch; static cleanup stays on the global store.
+ if ((access & ACC_STATIC) != 0) {
+ return mv;
+ }
+ return new MethodVisitor(ASM9, mv) {
+ @Override
+ public void visitMethodInsn(
+ int opcode, String owner, String name, String descriptor, boolean isInterface) {
+ if (opcode == INVOKESTATIC && LOCAL_GLOBAL_STORE.equals(owner)) {
+ owner = dispatchClass;
+ }
+ super.visitMethodInsn(opcode, owner, name, descriptor, isInterface);
+ }
+ };
+ }
+ },
0);
return writer.toByteArray();
}
diff --git a/field-inject/src/jmh/java/datadog/instrument/fieldinject/DispatchBridge.java b/field-inject/src/jmh/java/datadog/instrument/fieldinject/DispatchBridge.java
index 89bee84..723ec76 100644
--- a/field-inject/src/jmh/java/datadog/instrument/fieldinject/DispatchBridge.java
+++ b/field-inject/src/jmh/java/datadog/instrument/fieldinject/DispatchBridge.java
@@ -14,12 +14,18 @@
import java.util.Collections;
import java.util.Map;
-/** Template copied to the bootstrap loader before either bridge is linked. */
+/** Bootstrap template for benchmark fallback linkage and direct-store cleanup. */
+@SuppressWarnings("unused") // Called reflectively or from generated benchmark bytecode.
public final class DispatchBridge {
private static Map targets = Collections.emptyMap();
private DispatchBridge() {}
+ /** Sweeps the relocated store used by the direct benchmark baseline. */
+ public static int removeStaleEntries() {
+ return GlobalObjectStore.removeStaleEntries();
+ }
+
public static void initialize(Map handles) {
targets = handles;
}
diff --git a/field-inject/src/jmh/java/datadog/instrument/fieldinject/FinalHandleFallback.java b/field-inject/src/jmh/java/datadog/instrument/fieldinject/FinalHandleFallback.java
index 1dc7823..68fdc92 100644
--- a/field-inject/src/jmh/java/datadog/instrument/fieldinject/FinalHandleFallback.java
+++ b/field-inject/src/jmh/java/datadog/instrument/fieldinject/FinalHandleFallback.java
@@ -10,13 +10,13 @@
import java.util.function.Function;
/** Its fields and methods are copied into the generated final-handle dispatcher. */
+@SuppressWarnings("unused") // Methods are copied into generated benchmark bytecode.
final class FinalHandleFallback {
private static final MethodHandle GET = DispatchBridge.target("get");
private static final MethodHandle PUT = DispatchBridge.target("put");
private static final MethodHandle GET_OR_PUT = DispatchBridge.target("getOrPut");
private static final MethodHandle GET_OR_COMPUTE = DispatchBridge.target("getOrCompute");
private static final MethodHandle REMOVE = DispatchBridge.target("remove");
- private static final MethodHandle CLEAN = DispatchBridge.target("removeStaleEntries");
private FinalHandleFallback() {}
@@ -40,8 +40,4 @@ public static Object getOrCompute(Object key, int storeId, Function