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 dispatch = newBootstrapDispatch(); + RecordingStore.entries.clear(); + RecordingStore.computeCalls.set(0); + + initialize(dispatch, MethodHandles.lookup().in(RecordingStore.class)); + + assertThat(RecordingStore.computeCalls).hasValue(1); + assertThat(RecordingStore.entries).isEmpty(); + } + + @Test + void partialLinkageFailurePersists() throws Exception { + Class dispatch = newBootstrapDispatch(); + + assertThatThrownBy(() -> initialize(dispatch, MethodHandles.lookup().in(PartialStore.class))) + .isInstanceOf(InvocationTargetException.class) + .hasCauseInstanceOf(BootstrapMethodError.class) + .cause() + .cause() + .isInstanceOf(NoSuchMethodException.class) + .hasMessageContaining("getOrCompute"); + Method get = dispatch.getMethod("get", Object.class, int.class); + Object key = new Object(); + assertThat(get.invoke(null, key, 0)).isEqualTo("other store"); + + assertThatThrownBy(() -> initialize(dispatch)) + .isInstanceOf(InvocationTargetException.class) + .hasCauseInstanceOf(BootstrapMethodError.class); + assertThat(get.invoke(null, key, 0)).isEqualTo("other store"); + } + @Test void firstLookupWins() throws Exception { Class dispatch = newBootstrapDispatch(); @@ -78,7 +114,7 @@ void callingGlueBeforeInitializationFails() throws Exception { } @Test - void incorrectFirstLookupCannotBeReplaced() throws Exception { + void incorrectFirstLookupCannotBeReplaced() { Class dispatch = newBootstrapDispatch(); // The lookup must be scoped to GlobalObjectStore, not merely originate in its package. assertThatThrownBy(() -> initialize(dispatch, MethodHandles.lookup())) @@ -92,16 +128,17 @@ void incorrectFirstLookupCannotBeReplaced() throws Exception { .hasCauseInstanceOf(BootstrapMethodError.class); } - @Test - void cleanupReturnsBoundStoreResult() throws Exception { - Class dispatch = newBootstrapDispatch(); - initialize(dispatch, MethodHandles.lookup().in(OtherStore.class)); - - assertThat(dispatch.getMethod("removeStaleEntries").invoke(null)).isEqualTo(42); + /** A valid alternate target that makes an unintended rebind observable. */ + @SuppressWarnings("unused") // Linked by generated bootstrap dispatch. + public static class OtherStore extends PartialStore { + public static Object getOrCompute(Object key, int storeId, Function function) { + return "other store"; + } } - /** A valid alternate target that makes an unintended rebind observable. */ - public static class OtherStore { + /** Links every fallback except getOrCompute, so initialization fails after partial success. */ + @SuppressWarnings("unused") // Linked by generated bootstrap dispatch. + public static class PartialStore { public static Object get(Object key, int storeId) { return "other store"; } @@ -112,16 +149,47 @@ public static Object getOrPut(Object key, int storeId, Object value) { return "other store"; } - public static Object getOrCompute(Object key, int storeId, Function function) { + public static Object remove(Object key, int storeId) { return "other store"; } + } - public static Object remove(Object key, int storeId) { - return "other store"; + /** Retains computed entries until remove is called, making initialization cleanup observable. */ + @SuppressWarnings("unused") // Linked by generated bootstrap dispatch. + public static class RecordingStore { + static final Map entries = new IdentityHashMap<>(); + static final AtomicInteger computeCalls = new AtomicInteger(); + + public static Object get(Object key, int storeId) { + return entries.get(key); + } + + public static void put(Object key, int storeId, Object value) { + if (value == null) { + entries.remove(key); + } else { + entries.put(key, value); + } } - public static int removeStaleEntries() { - return 42; + public static Object getOrPut(Object key, int storeId, Object value) { + Object existing = entries.get(key); + if (existing != null) { + return existing; + } + put(key, storeId, value); + return value; + } + + public static Object getOrCompute(Object key, int storeId, Function function) { + computeCalls.incrementAndGet(); + Object value = function.apply(key); + entries.put(key, value); + return value; + } + + public static Object remove(Object key, int storeId) { + return entries.remove(key); } } } diff --git a/field-inject/src/test/java/datadog/instrument/fieldinject/LocalDispatchTest.java b/field-inject/src/test/java/datadog/instrument/fieldinject/LocalDispatchTest.java index 06d9f43..29b7d2a 100644 --- a/field-inject/src/test/java/datadog/instrument/fieldinject/LocalDispatchTest.java +++ b/field-inject/src/test/java/datadog/instrument/fieldinject/LocalDispatchTest.java @@ -1,6 +1,7 @@ package datadog.instrument.fieldinject; import static datadog.instrument.fieldinject.ObjectStoreIds.objectStoreId; +import static datadog.instrument.fieldinject.ObjectStoreTestKeys.fastPathKey; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assumptions.assumeTrue; @@ -46,7 +47,6 @@ class LocalDispatchTest { private Method removeMethod; private Method weakGetMethod; private Method weakPutMethod; - private Method removeStaleEntriesMethod; @BeforeEach void loadGeneratedClasses() throws Exception { @@ -66,14 +66,13 @@ final void loadGeneratedClasses(Class keyClass, Class dispatchClass) throw removeMethod = dispatchClass.getMethod("remove", Object.class, int.class); weakGetMethod = dispatchClass.getMethod("weakGet", Object.class, int.class); weakPutMethod = dispatchClass.getMethod("weakPut", Object.class, int.class, Object.class); - removeStaleEntriesMethod = dispatchClass.getMethod("removeStaleEntries"); } @Test void fastPathRoundTripsThroughAccessorAndBypassesGlobalStore() throws Exception { int storeId = objectStoreId("test.Dispatch.FastPath.Key", "test.Dispatch.FastPath.Value"); Map backing = Collections.synchronizedMap(new HashMap<>()); - Object key = fastPathKey(backing); + Object key = fastPathKey(keyWithValueClass, backing); // seed the global store, so we can tell if the fast path ever reads from or writes to it GlobalObjectStore.put(key, storeId, "global"); @@ -128,7 +127,7 @@ void uninjectedKeysUseGlobalStore() throws Exception { void getOrPutOnlySetsAccessorWhenAbsent() throws Exception { int storeId = objectStoreId("test.Dispatch.GetOrPut.Key", "test.Dispatch.GetOrPut.Value"); Map backing = Collections.synchronizedMap(new HashMap<>()); - Object key = fastPathKey(backing); + Object key = fastPathKey(keyWithValueClass, backing); assertThat(getOrPutMethod.invoke(null, key, storeId, "first")).isEqualTo("first"); assertThat(backing.get(storeId)).isEqualTo("first"); @@ -144,7 +143,7 @@ void getOrComputeInvokesFunctionWithOriginalKeyOnlyWhenAbsent() throws Exception int storeId = objectStoreId("test.Dispatch.GetOrCompute.Key", "test.Dispatch.GetOrCompute.Value"); Map backing = Collections.synchronizedMap(new HashMap<>()); - Object key = fastPathKey(backing); + Object key = fastPathKey(keyWithValueClass, backing); AtomicReference receivedKey = new AtomicReference<>(); Function computeOnce = @@ -172,7 +171,7 @@ void getOrComputeInvokesFunctionWithOriginalKeyOnlyWhenAbsent() throws Exception void removeReturnsPreviousValueAndClearsAccessor() throws Exception { int storeId = objectStoreId("test.Dispatch.Remove.Key", "test.Dispatch.Remove.Value"); Map backing = Collections.synchronizedMap(new HashMap<>()); - Object key = fastPathKey(backing); + Object key = fastPathKey(keyWithValueClass, backing); backing.put(storeId, "existing"); assertThat(removeMethod.invoke(null, key, storeId)).isEqualTo("existing"); @@ -303,6 +302,61 @@ void concurrentInsertionOnSameKeyConvergesToASingleWinner(String operation) thro .allMatch(winner::equals); } + @Test + void concurrentRemovalHasSingleWinner() throws Exception { + int storeId = + objectStoreId("test.Dispatch.ConcurrentRemove.Key", "test.Dispatch.ConcurrentRemove.Value"); + Map backing = Collections.synchronizedMap(new HashMap<>()); + backing.put(storeId, "existing"); + CountDownLatch initialReads = new CountDownLatch(2); + AtomicInteger getterCalls = new AtomicInteger(); + AtomicInteger setterCalls = new AtomicInteger(); + Object key = + Proxy.newProxyInstance( + keyWithValueClass.getClassLoader(), + new Class[] {keyWithValueClass}, + (proxy, method, args) -> { + if (args.length == 1) { + if (getterCalls.incrementAndGet() <= 2) { + initialReads.countDown(); + if (!initialReads.await(10, TimeUnit.SECONDS)) { + throw new AssertionError("both removers must reach the initial accessor read"); + } + // Both callers must observe the value before either can remove it. + return "existing"; + } + return backing.get((Integer) args[0]); + } + setterCalls.incrementAndGet(); + backing.put((Integer) args[0], args[1]); + return null; + }); + + ExecutorService executor = + Executors.newFixedThreadPool( + 2, + r -> { + Thread thread = new Thread(r, "dispatch-remove"); + thread.setDaemon(true); + return thread; + }); + List results = new ArrayList<>(); + try { + java.util.concurrent.Future first = + executor.submit(() -> removeMethod.invoke(null, key, storeId)); + java.util.concurrent.Future second = + executor.submit(() -> removeMethod.invoke(null, key, storeId)); + results.add(first.get(10, TimeUnit.SECONDS)); + results.add(second.get(10, TimeUnit.SECONDS)); + } finally { + executor.shutdownNow(); + } + + assertThat(results).containsExactlyInAnyOrder("existing", null); + assertThat(setterCalls).hasValue(1); + assertThat(backing.get(storeId)).isNull(); + } + @TableTest({ "failurePoint", "'compute' ", @@ -369,7 +423,7 @@ void failureInsideMonitorReleasesLockAndAllowsRetry(String failurePoint) throws void nullComputedValueIsNotCachedAndCanBeRetried() throws Exception { int storeId = objectStoreId("test.Dispatch.NullCompute.Key", "test.Dispatch.NullCompute.Value"); Map backing = Collections.synchronizedMap(new HashMap<>()); - Object key = fastPathKey(backing); + Object key = fastPathKey(keyWithValueClass, backing); AtomicInteger calls = new AtomicInteger(); Function compute = k -> calls.incrementAndGet() <= 2 ? null : "computed"; @@ -394,7 +448,7 @@ void removeStaleEntriesReportsSizeAndReleasesValuesForCollectedKeys() throws Exc int remaining; WeakReference gcProbe; do { - remaining = (Integer) removeStaleEntriesMethod.invoke(null); + remaining = ObjectStore.removeStaleEntries(); // An independent probe distinguishes unavailable GC from a value retained by broken cleanup. gcProbe = new WeakReference<>(new Object()); System.gc(); @@ -420,22 +474,6 @@ private WeakReference putWithEphemeralKey(int storeId) throws Exception return new WeakReference<>(value); } - /** - * Creates a {@code KeyWithValue} proxy backed by a plain map, simulating a field-injected key. - */ - private Object fastPathKey(Map backing) { - InvocationHandler handler = - (proxy, method, args) -> { - if (args.length == 1) { - return backing.get((Integer) args[0]); - } - backing.put((Integer) args[0], args[1]); - return null; - }; - return Proxy.newProxyInstance( - keyWithValueClass.getClassLoader(), new Class[] {keyWithValueClass}, handler); - } - /** * Mimics a field-injected key: stores it has fields for use the backing map, anything else falls * back via {@code ObjectStoreDispatch.weakGet/weakPut} (injected code can't assume it has access diff --git a/field-inject/src/test/java/datadog/instrument/fieldinject/ObjectStoreDispatchTestSupport.java b/field-inject/src/test/java/datadog/instrument/fieldinject/ObjectStoreDispatchTestSupport.java index 6a6582c..ed45832 100644 --- a/field-inject/src/test/java/datadog/instrument/fieldinject/ObjectStoreDispatchTestSupport.java +++ b/field-inject/src/test/java/datadog/instrument/fieldinject/ObjectStoreDispatchTestSupport.java @@ -6,6 +6,8 @@ import datadog.instrument.testing.TestAgent; import java.lang.invoke.MethodHandles; import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.UnaryOperator; +import javax.annotation.Nullable; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; @@ -26,8 +28,7 @@ final class ObjectStoreDispatchTestSupport { BOOT_KEY_WITH_VALUE = ClassInjector.injectBootClass( ObjectStoreGlue.KEY_ID, Glue.unpackBytecode(ObjectStoreGlue.KEY)); - BOOT_DISPATCH = - ClassInjector.injectBootClass(DISPATCH_NAME, Glue.unpackBytecode(ObjectStoreGlue.DISPATCH)); + BOOT_DISPATCH = newBootstrapDispatch(); } private ObjectStoreDispatchTestSupport() {} @@ -43,24 +44,39 @@ static void initialize(Class dispatch, MethodHandles.Lookup lookup) throws Ex /** Isolates first-binding and failed-linkage state without relying on test execution order. */ static Class newBootstrapDispatch() { String name = DISPATCH_NAME + "$Test" + NEXT_ID.incrementAndGet(); + return injectCopy( + new ClassReader(Glue.unpackBytecode(ObjectStoreGlue.DISPATCH)), + name, + null, + visitor -> + new ClassVisitor(Opcodes.ASM9, visitor) { + @Override + public FieldVisitor visitField( + int access, String field, String descriptor, String signature, Object value) { + // Let tests invalidate bootstrap without affecting already linked call sites. + if (field.equals("globalLookup")) { + access = (access & ~Opcodes.ACC_PRIVATE) | Opcodes.ACC_PUBLIC; + } + return super.visitField(access, field, descriptor, signature, value); + } + }); + } + + /** Copies a class under a new binary name; a null loader selects the bootstrap loader. */ + static Class injectCopy( + ClassReader original, + String newName, + @Nullable ClassLoader loader, + UnaryOperator transform) { ClassWriter cw = new ClassWriter(0); - new ClassReader(Glue.unpackBytecode(ObjectStoreGlue.DISPATCH)) - .accept( - new ClassRemapper( - new ClassVisitor(Opcodes.ASM9, cw) { - @Override - public FieldVisitor visitField( - int access, String field, String descriptor, String signature, Object value) { - // Let tests invalidate bootstrap without affecting already linked call sites. - if (field.equals("globalLookup")) { - access = (access & ~Opcodes.ACC_PRIVATE) | Opcodes.ACC_PUBLIC; - } - return super.visitField(access, field, descriptor, signature, value); - } - }, - new SimpleRemapper( - Opcodes.ASM9, DISPATCH_NAME.replace('.', '/'), name.replace('.', '/'))), - 0); - return ClassInjector.injectBootClass(name, cw.toByteArray()); + original.accept( + new ClassRemapper( + transform.apply(cw), + new SimpleRemapper(Opcodes.ASM9, original.getClassName(), newName.replace('.', '/'))), + 0); + byte[] bytecode = cw.toByteArray(); + return loader == null + ? ClassInjector.injectBootClass(newName, bytecode) + : ClassInjector.injectClass(newName, bytecode, loader); } } diff --git a/field-inject/src/test/java/datadog/instrument/fieldinject/ObjectStoreDispatchTransformationTest.java b/field-inject/src/test/java/datadog/instrument/fieldinject/ObjectStoreDispatchTransformationTest.java new file mode 100644 index 0000000..5410d19 --- /dev/null +++ b/field-inject/src/test/java/datadog/instrument/fieldinject/ObjectStoreDispatchTransformationTest.java @@ -0,0 +1,125 @@ +package datadog.instrument.fieldinject; + +import static datadog.instrument.fieldinject.ObjectStoreDispatchTestSupport.BOOT_DISPATCH; +import static datadog.instrument.fieldinject.ObjectStoreDispatchTestSupport.BOOT_KEY_WITH_VALUE; +import static datadog.instrument.fieldinject.ObjectStoreDispatchTestSupport.injectCopy; +import static datadog.instrument.fieldinject.ObjectStoreIds.objectStoreId; +import static datadog.instrument.fieldinject.ObjectStoreTestKeys.fastPathKey; +import static org.assertj.core.api.Assertions.assertThat; +import static org.objectweb.asm.Opcodes.ACC_STATIC; +import static org.objectweb.asm.Opcodes.ASM9; +import static org.objectweb.asm.Opcodes.INVOKESTATIC; + +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; +import org.junit.jupiter.api.BeforeAll; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassVisitor; +import org.objectweb.asm.MethodVisitor; +import org.tabletest.junit.TableTest; + +class ObjectStoreDispatchTransformationTest { + @BeforeAll + static void initializeBootstrapDispatch() throws Exception { + ObjectStoreDispatchTestSupport.initialize(BOOT_DISPATCH); + } + + @TableTest({ + "boot ", + "false", + "true " + }) + void transformSelectsAccessorMethods(boolean boot) throws Exception { + Class keyType = + boot ? BOOT_KEY_WITH_VALUE : Class.forName("datadog.instrument.fieldinject.KeyWithValue"); + Class storeType = transformedStore(boot); + Object store = + storeType + .getMethod("of", String.class, String.class) + .invoke(null, "test.Transformed.Key." + boot, "test.Transformed.Value"); + Method get = storeType.getMethod("get", Object.class); + Method put = storeType.getMethod("put", Object.class, Object.class); + Method getOrPut = storeType.getMethod("getOrPut", Object.class, Object.class); + Method compute = storeType.getMethod("getOrCompute", Object.class, Function.class); + Method remove = storeType.getMethod("remove", Object.class); + Map fields = new HashMap<>(); + Object injectedKey = fastPathKey(keyType, fields); + + Object fallbackKey = new Object(); + for (Object key : new Object[] {fallbackKey, injectedKey}) { + assertThat(get.invoke(store, key)).isNull(); + put.invoke(store, key, "value"); + if (key == injectedKey) { + assertThat(fields).containsValue("value"); + } + assertThat(getOrPut.invoke(store, key, "ignored")).isEqualTo("value"); + assertThat(remove.invoke(store, key)).isEqualTo("value"); + assertThat(compute.invoke(store, key, (Function) k -> "computed")) + .isEqualTo("computed"); + assertThat(get.invoke(store, key)).isEqualTo("computed"); + assertThat(remove.invoke(store, key)).isEqualTo("computed"); + assertThat(getOrPut.invoke(store, key, "new")).isEqualTo("new"); + } + int storeId = objectStoreId("test.Transformed.Key." + boot, "test.Transformed.Value"); + assertThat(GlobalObjectStore.get(fallbackKey, storeId)).isEqualTo("new"); + // Static cleanup remains callable and preserves this test's live global and injected values. + storeType.getMethod("removeStaleEntries").invoke(null); + assertThat(GlobalObjectStore.get(fallbackKey, storeId)).isEqualTo("new"); + assertThat(get.invoke(store, fallbackKey)).isEqualTo("new"); + assertThat(get.invoke(store, injectedKey)).isEqualTo("new"); + remove.invoke(store, fallbackKey); + remove.invoke(store, injectedKey); + } + + /** Transforms an isolated copy so other suites keep using the original ObjectStore. */ + private static Class transformedStore(boolean boot) throws Exception { + String original = "datadog.instrument.fieldinject.ObjectStore"; + String name = original + (boot ? "$BootDispatchTest" : "$LocalDispatchTest"); + String dispatchClass = + boot + ? BOOT_DISPATCH.getName().replace('.', '/') + : "datadog/instrument/fieldinject/ObjectStoreDispatch"; + return injectCopy( + new ClassReader(original), + name, + ObjectStore.class.getClassLoader(), + visitor -> + new ClassVisitor(ASM9, visitor) { + @Override + public MethodVisitor visitMethod( + int access, + String name, + String descriptor, + String signature, + String[] exceptions) { + MethodVisitor mv = + super.visitMethod(access, name, descriptor, signature, exceptions); + if ((access & ACC_STATIC) != 0) { + return mv; + } + return new RedirectToDispatch(mv, dispatchClass); + } + }); + } + + private static final class RedirectToDispatch extends MethodVisitor { + private final String dispatchClass; + + RedirectToDispatch(MethodVisitor mv, String dispatchClass) { + super(ASM9, mv); + this.dispatchClass = dispatchClass; + } + + @Override + public void visitMethodInsn( + int opcode, String owner, String name, String descriptor, boolean isInterface) { + if (opcode == INVOKESTATIC + && owner.equals("datadog/instrument/fieldinject/GlobalObjectStore")) { + owner = dispatchClass; + } + super.visitMethodInsn(opcode, owner, name, descriptor, isInterface); + } + } +} diff --git a/field-inject/src/test/java/datadog/instrument/fieldinject/ObjectStoreTest.java b/field-inject/src/test/java/datadog/instrument/fieldinject/ObjectStoreTest.java index 8e405e1..5abe3e8 100644 --- a/field-inject/src/test/java/datadog/instrument/fieldinject/ObjectStoreTest.java +++ b/field-inject/src/test/java/datadog/instrument/fieldinject/ObjectStoreTest.java @@ -509,7 +509,7 @@ void oneShardsSustainedLoadDoesNotAgeOrEvictAnotherShard() { // Pick two key types landing on different shards, matching ObjectStoreShardingTest's approach. String loadedKeyType = "test.ShardIsolation.LoadedKey"; int loadedStoreId = objectStoreId(loadedKeyType, "test.ShardIsolation.Value"); - String quietKeyType = null; + String quietKeyType; int suffix = 0; while (true) { String candidate = "test.ShardIsolation.QuietKey" + suffix; diff --git a/field-inject/src/test/java/datadog/instrument/fieldinject/ObjectStoreTestKeys.java b/field-inject/src/test/java/datadog/instrument/fieldinject/ObjectStoreTestKeys.java new file mode 100644 index 0000000..ff48910 --- /dev/null +++ b/field-inject/src/test/java/datadog/instrument/fieldinject/ObjectStoreTestKeys.java @@ -0,0 +1,28 @@ +package datadog.instrument.fieldinject; + +import java.lang.reflect.Proxy; +import java.util.Map; + +/** Key fixtures that do not require bootstrap class injection. */ +final class ObjectStoreTestKeys { + private ObjectStoreTestKeys() {} + + /** Creates a map-backed accessor, simulating a field-injected key. */ + static Object fastPathKey(Class keyType, Map backing) { + return Proxy.newProxyInstance( + keyType.getClassLoader(), + new Class[] {keyType}, + (proxy, method, args) -> { + int id = (Integer) args[0]; + if (args.length == 1) { + return backing.get(id); + } + if (args[1] == null) { + backing.remove(id); + } else { + backing.put(id, args[1]); + } + return null; + }); + } +} diff --git a/field-inject/src/test/java/datadog/instrument/glue/ObjectStoreGlueGeneratorTest.java b/field-inject/src/test/java/datadog/instrument/glue/ObjectStoreGlueGeneratorTest.java index 0fb5614..4bd6b68 100644 --- a/field-inject/src/test/java/datadog/instrument/glue/ObjectStoreGlueGeneratorTest.java +++ b/field-inject/src/test/java/datadog/instrument/glue/ObjectStoreGlueGeneratorTest.java @@ -8,6 +8,7 @@ import java.io.StringWriter; import java.lang.reflect.Method; import java.lang.reflect.Modifier; +import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.TreeSet; @@ -28,7 +29,7 @@ class ObjectStoreGlueGeneratorTest { @Test void keyBytecodeVerifies() { - verifyAll(ObjectStoreGlueGenerator.generateKey()); + verifyAll(ObjectStoreGlueGenerator.generateLocalKey()); } @Test @@ -48,6 +49,8 @@ void fallbacksMatchStoreSignatures(boolean bootstrap) throws Exception { // collect every static call the generated dispatch makes to GlobalObjectStore String globalObjectStoreClass = Type.getInternalName(globalObjectStore); Set fallbackCalls = new TreeSet<>(); + Set dispatchMethods = new TreeSet<>(); + List dynamicDispatchMethods = new ArrayList<>(); new ClassReader( bootstrap ? Glue.unpackBytecode(ObjectStoreGlue.DISPATCH) @@ -61,6 +64,11 @@ public MethodVisitor visitMethod( String descriptor, String signature, String[] exceptions) { + if ((access & (Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC)) + == (Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC)) { + dispatchMethods.add(name + descriptor); + } + String dispatchMethod = name; return new MethodVisitor(ASM9) { @Override public void visitMethodInsn( @@ -82,6 +90,7 @@ public void visitInvokeDynamicInsn( assertThat(target.getOwner()) .isEqualTo(ObjectStoreGlue.DISPATCH_ID.replace('.', '/')); assertThat(target.getName()).isEqualTo("bootstrap"); + dynamicDispatchMethods.add(dispatchMethod); fallbackCalls.add(name + descriptor); } }; @@ -98,10 +107,31 @@ public void visitInvokeDynamicInsn( } } - assertThat(fallbackCalls).isNotEmpty(); + Set expectedFallbackCalls = + new TreeSet<>( + asList( + "get(Ljava/lang/Object;I)Ljava/lang/Object;", + "put(Ljava/lang/Object;ILjava/lang/Object;)V", + "getOrPut(Ljava/lang/Object;ILjava/lang/Object;)Ljava/lang/Object;", + "getOrCompute(Ljava/lang/Object;ILjava/util/function/Function;)Ljava/lang/Object;", + "remove(Ljava/lang/Object;I)Ljava/lang/Object;")); + Set expectedDispatchMethods = new TreeSet<>(expectedFallbackCalls); + expectedDispatchMethods.add("weakGet(Ljava/lang/Object;I)Ljava/lang/Object;"); + expectedDispatchMethods.add("weakPut(Ljava/lang/Object;ILjava/lang/Object;)V"); + if (bootstrap) { + expectedDispatchMethods.add("initialize(Ljava/lang/invoke/MethodHandles$Lookup;)V"); + } + + assertThat(dispatchMethods).containsExactlyInAnyOrderElementsOf(expectedDispatchMethods); + assertThat(fallbackCalls).containsExactlyInAnyOrderElementsOf(expectedFallbackCalls); assertThat(accessibleStaticMethods) .as("generated fallbacks must match non-private static methods on GlobalObjectStore") .containsAll(fallbackCalls); + if (bootstrap) { + assertThat(dynamicDispatchMethods) + .as("get/put share the five indy instructions through weakGet/weakPut") + .containsExactlyInAnyOrder("weakGet", "weakPut", "getOrPut", "getOrCompute", "remove"); + } } /** Perform strict class verification, like -Xverify:all */