From 5b0eac6254c988dfd6e1ed4c8cd2f89f26db735e Mon Sep 17 00:00:00 2001 From: Stuart McCulloch Date: Wed, 2 Dec 2026 22:53:13 +0000 Subject: [PATCH 1/2] Generate bootstrap dispatch backed by the original global store Link fallback calls through generated constant call sites and keep GlobalObjectStore and its nested classes out of bootstrap glue. Derive fallback argument loads from descriptors and verify local and bootstrap dispatch signatures. --- .../main/kotlin/instrument-glue.gradle.kts | 1 - field-inject/build.gradle.kts | 8 +- .../glue/ObjectStoreGlueGenerator.java | 451 +++++++++--------- .../BootstrapDispatchInitializationTest.java | 127 +++++ .../fieldinject/BootstrapDispatchTest.java | 23 + ...tionalTest.java => LocalDispatchTest.java} | 94 +++- .../ObjectStoreDispatchTestSupport.java | 66 +++ .../fieldinject/ObjectStoreTest.java | 2 +- .../glue/ObjectStoreGlueGeneratorTest.java | 58 ++- 9 files changed, 556 insertions(+), 274 deletions(-) create mode 100644 field-inject/src/test/java/datadog/instrument/fieldinject/BootstrapDispatchInitializationTest.java create mode 100644 field-inject/src/test/java/datadog/instrument/fieldinject/BootstrapDispatchTest.java rename field-inject/src/test/java/datadog/instrument/fieldinject/{ObjectStoreDispatchFunctionalTest.java => LocalDispatchTest.java} (84%) create mode 100644 field-inject/src/test/java/datadog/instrument/fieldinject/ObjectStoreDispatchTestSupport.java diff --git a/buildSrc/src/main/kotlin/instrument-glue.gradle.kts b/buildSrc/src/main/kotlin/instrument-glue.gradle.kts index 8ed87e5d..e43e3626 100644 --- a/buildSrc/src/main/kotlin/instrument-glue.gradle.kts +++ b/buildSrc/src/main/kotlin/instrument-glue.gradle.kts @@ -22,7 +22,6 @@ val glueImplementation = configurations.getByName("glueImplementation") dependencies { glueImplementation(libs.asm) glueImplementation(libs.asm.commons) - glueImplementation(libs.spotbugs.annotations) glueImplementation(project(":utils")) } diff --git a/field-inject/build.gradle.kts b/field-inject/build.gradle.kts index d0d3ce14..2a836e29 100644 --- a/field-inject/build.gradle.kts +++ b/field-inject/build.gradle.kts @@ -1,24 +1,20 @@ plugins { id("java-common") id("instrument-glue") + id("instrument-testing") } dependencies { testImplementation(sourceSets["glue"].output) testImplementation(project(":utils")) + testImplementation(project(":class-inject")) testImplementation(libs.asm.commons) testImplementation(libs.asm.util) jmh("com.blogspot.mydailyjava:weak-lock-free:0.18") } -// include GlobalObjectStore in glue generation, so we can repackage it for injection -sourceSets["glue"].java { - srcDir("src/main/java") - include("**/GlobalObjectStore.java") -} - // field-inject generates dispatch + access glue for injection into the bootstrap classpath extra["glue"] = listOf("ObjectStoreGlue") 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 115c1747..75eda108 100644 --- a/field-inject/src/glue/java/datadog/instrument/glue/ObjectStoreGlueGenerator.java +++ b/field-inject/src/glue/java/datadog/instrument/glue/ObjectStoreGlueGenerator.java @@ -11,9 +11,7 @@ import static org.objectweb.asm.ClassWriter.COMPUTE_FRAMES; import static org.objectweb.asm.Opcodes.*; -import datadog.instrument.utils.JVM; import java.io.IOException; -import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -22,47 +20,39 @@ import java.util.List; import java.util.Map; import java.util.function.Consumer; -import org.objectweb.asm.AnnotationVisitor; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.FieldVisitor; +import org.objectweb.asm.Handle; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Type; -import org.objectweb.asm.TypePath; import org.objectweb.asm.commons.ClassRemapper; import org.objectweb.asm.commons.Remapper; import org.objectweb.asm.commons.SimpleRemapper; -/** - * Generates {@code KeyWithValue}/{@code ObjectStoreDispatch} bytecode, plus java.lang-relocated - * copies of them and {@code GlobalObjectStore} packed as glue for the bootstrap classpath. - */ +/** Generates local and bootstrap object-store dispatch. */ final class ObjectStoreGlueGenerator { - // generated dispatch glue - private static final String KEYWITHVALUE_CLASS = "datadog/instrument/fieldinject/KeyWithValue"; - private static final String OBJECTSTOREDISPATCH_CLASS = - "datadog/instrument/fieldinject/ObjectStoreDispatch"; + private static final String KEY_CLASS = "datadog/instrument/fieldinject/KeyWithValue"; + private static final String DISPATCH_CLASS = "datadog/instrument/fieldinject/ObjectStoreDispatch"; + + // bootstrap glue must be located inside the java.lang namespace for accessibility reasons + private static final String BOOT_KEY_CLASS = "java/lang/$Datadog$KeyWithValue"; + private static final String BOOT_DISPATCH_CLASS = "java/lang/$Datadog$ObjectStoreDispatch"; - // repackaged support glue + // fallback dispatch target private static final String GLOBALOBJECTSTORE_CLASS = "datadog/instrument/fieldinject/GlobalObjectStore"; - private static final String GLOBALOBJECTSTORE_STOREKEY_CLASS = - GLOBALOBJECTSTORE_CLASS + "$StoreKey"; - private static final String GLOBALOBJECTSTORE_LOOKUPKEY_CLASS = - GLOBALOBJECTSTORE_CLASS + "$LookupKey"; - private static final String GLOBALOBJECTSTORE_LOOKUPKEYCACHE_CLASS = - GLOBALOBJECTSTORE_CLASS + "$LookupKeyCache"; - private static final String GLOBALOBJECTSTORE_VALUECOMPUTER_CLASS = - GLOBALOBJECTSTORE_CLASS + "$ValueComputer"; private static final String OBJECT_CLASS = "java/lang/Object"; private static final String FUNCTION_CLASS = "java/util/function/Function"; - - // bootstrap glue must be located inside the java.lang namespace for accessibility reasons - private static final String JAVA_LANG_PREFIX = "java/lang/$Datadog$"; + private static final String LOOKUP_CLASS = "java/lang/invoke/MethodHandles$Lookup"; + 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 String INJECTED_STORE_MARKER = "__dd_instrument$"; @@ -93,90 +83,43 @@ private ObjectStoreGlueGenerator() {} * @see GlueGenerator#main */ public static void generateGlue(Path resourcePath, Path javaPath) throws IOException { - byte[] keyWithValueBytecode = generateKeyWithValueBytecode(); - byte[] objectStoreDispatchBytecode = generateObjectStoreDispatchBytecode(); + byte[] keyWithValueBytecode = generateKey(); + byte[] objectStoreDispatchBytecode = generateLocalDispatch(); // first generate dispatch glue for the field-inject package Path fieldInjectPackagePath = resourcePath.resolveSibling("fieldinject"); Files.createDirectories(fieldInjectPackagePath); - writeClassResource(fieldInjectPackagePath, KEYWITHVALUE_CLASS, keyWithValueBytecode); - writeClassResource( - fieldInjectPackagePath, OBJECTSTOREDISPATCH_CLASS, objectStoreDispatchBytecode); - - // next collect all the glue we need to repackage for the bootstrap. - List relocatedClasses = new ArrayList<>(); - relocatedClasses.add( - new RelocatedClass("KEYWITHVALUE", KEYWITHVALUE_CLASS, keyWithValueBytecode)); - relocatedClasses.add( - new RelocatedClass( - "OBJECTSTOREDISPATCH", OBJECTSTOREDISPATCH_CLASS, objectStoreDispatchBytecode)); - relocatedClasses.add( - new RelocatedClass( - "GLOBALOBJECTSTORE", - GLOBALOBJECTSTORE_CLASS, - readClassResource(GLOBALOBJECTSTORE_CLASS))); - relocatedClasses.add( - new RelocatedClass( - "GLOBALOBJECTSTORE_STOREKEY", - GLOBALOBJECTSTORE_STOREKEY_CLASS, - readClassResource(GLOBALOBJECTSTORE_STOREKEY_CLASS))); - relocatedClasses.add( - new RelocatedClass( - "GLOBALOBJECTSTORE_LOOKUPKEY", - GLOBALOBJECTSTORE_LOOKUPKEY_CLASS, - readClassResource(GLOBALOBJECTSTORE_LOOKUPKEY_CLASS))); - relocatedClasses.add( - new RelocatedClass( - "GLOBALOBJECTSTORE_LOOKUPKEYCACHE", - GLOBALOBJECTSTORE_LOOKUPKEYCACHE_CLASS, - readClassResource(GLOBALOBJECTSTORE_LOOKUPKEYCACHE_CLASS))); - relocatedClasses.add( - new RelocatedClass( - "GLOBALOBJECTSTORE_VALUECOMPUTER", - GLOBALOBJECTSTORE_VALUECOMPUTER_CLASS, - readClassResource(GLOBALOBJECTSTORE_VALUECOMPUTER_CLASS))); + writeClassResource(fieldInjectPackagePath, KEY_CLASS, keyWithValueBytecode); + writeClassResource(fieldInjectPackagePath, DISPATCH_CLASS, objectStoreDispatchBytecode); - Map renames = new HashMap<>(); - for (RelocatedClass relocated : relocatedClasses) { - renames.put(relocated.originalClass, relocated.relocatedClass); - } - Remapper remapper = new SimpleRemapper(ASM9, renames); - - // make the bootstrap glue available for class injection + // generate bootstrap dispatch glue that binds fallback calls via invokedynamic + Remapper remapper = bootRemapper(); List lines = new ArrayList<>(); classHeader(lines, "ObjectStoreGlue"); - lines.add(" /** Shared prefix of bootstrap glue */"); - lines.add(" String PREFIX = \"" + JAVA_LANG_PREFIX.replace('/', '.') + "\";"); - for (RelocatedClass relocated : relocatedClasses) { - packRelocatedClass(lines, remapper, relocated); - } + packGlue(lines, "KEY", BOOT_KEY_CLASS, relocate(remapper, keyWithValueBytecode)); + packGlue( + lines, + "DISPATCH", + BOOT_DISPATCH_CLASS, + generateBootDispatch(objectStoreDispatchBytecode, remapper)); lines.add("}"); Files.write(javaPath.resolve("ObjectStoreGlue.java"), lines, StandardCharsets.UTF_8); } - /** A class to be relocated into the {@code java.lang} namespace and packed into the glue. */ - private static final class RelocatedClass { - final String constantName; - final String originalClass; - final String relocatedClass; - final byte[] originalBytecode; - - RelocatedClass(String constantName, String originalClass, byte[] originalBytecode) { - String simpleName = originalClass.substring(originalClass.lastIndexOf('/') + 1); - this.constantName = constantName; - this.originalClass = originalClass; - this.relocatedClass = JAVA_LANG_PREFIX + simpleName; - this.originalBytecode = originalBytecode; - } + private static Remapper bootRemapper() { + Map renames = new HashMap<>(); + renames.put(KEY_CLASS, BOOT_KEY_CLASS); + renames.put(DISPATCH_CLASS, BOOT_DISPATCH_CLASS); + return new SimpleRemapper(ASM9, renames); } /** Generates bytecode for the {@code KeyWithValue} marker interface. */ - static byte[] generateKeyWithValueBytecode() { + static byte[] generateKey() { ClassWriter cw = new ClassWriter(0); cw.visit( V1_8, ACC_PUBLIC | ACC_INTERFACE | ACC_ABSTRACT | ACC_SYNTHETIC, - KEYWITHVALUE_CLASS, + KEY_CLASS, null, OBJECT_CLASS, null); @@ -189,15 +132,10 @@ static byte[] generateKeyWithValueBytecode() { } /** Generates bytecode for {@code ObjectStoreDispatch}. */ - static byte[] generateObjectStoreDispatchBytecode() { + static byte[] generateLocalDispatch() { ClassWriter cw = new ClassWriter(COMPUTE_FRAMES); cw.visit( - V1_8, - ACC_PUBLIC | ACC_FINAL | ACC_SYNTHETIC, - OBJECTSTOREDISPATCH_CLASS, - null, - OBJECT_CLASS, - null); + 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 @@ -220,6 +158,9 @@ static byte[] generateObjectStoreDispatchBytecode() { }); generateDoubleCheckedDispatch(cw, "remove", REMOVE_DESCRIPTOR, 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); @@ -228,7 +169,162 @@ static byte[] generateObjectStoreDispatchBytecode() { return cw.toByteArray(); } - /** Whether the descriptor's 3rd argument is the value to store, by convention. */ + /** 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(); + } + + /** + * Generates 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. + */ + private static void generateBootstrap(ClassWriter cw) { + cw.visitField( + ACC_PRIVATE | ACC_STATIC | ACC_VOLATILE, "globalLookup", LOOKUP_DESCRIPTOR, null, null) + .visitEnd(); + cw.visitField(ACC_PRIVATE | ACC_STATIC, "linked", "Z", null, null).visitEnd(); + + // keep the first binding so later initialization cannot split the call sites across stores + MethodVisitor mv = + cw.visitMethod( + ACC_PUBLIC | ACC_STATIC | ACC_SYNCHRONIZED, + "initialize", + "(" + LOOKUP_DESCRIPTOR + ")V", + null, + null); + 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 + 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); + + // 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.visitInsn(RETURN); + mv.visitMaxs(3, 2); + mv.visitEnd(); + + // 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"); + mv.visitInsn(DUP); + mv.visitFieldInsn(GETSTATIC, BOOT_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.visitMethodInsn( + INVOKEVIRTUAL, + LOOKUP_CLASS, + "findStatic", + "(Ljava/lang/Class;Ljava/lang/String;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/MethodHandle;", + false); + mv.visitMethodInsn( + INVOKESPECIAL, + "java/lang/invoke/ConstantCallSite", + "", + "(Ljava/lang/invoke/MethodHandle;)V", + false); + mv.visitInsn(ARETURN); + mv.visitMaxs(6, 3); + 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) { + 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.visitMethodInsn(INVOKESTATIC, BOOT_DISPATCH_CLASS, method, descriptor, false); + if (Type.getReturnType(descriptor).getSort() != Type.VOID) { + mv.visitInsn(POP); + } + } + + /** Whether the descriptor takes a value or a mapping function after the key and store ID. */ private static boolean hasValueArg(String descriptor) { return Type.getArgumentTypes(descriptor).length > 2; } @@ -236,15 +332,11 @@ private static boolean hasValueArg(String descriptor) { /** Generates a method that unconditionally delegates to {@code GlobalObjectStore}. */ private static void generateForwardDispatch( ClassWriter cw, String method, String forwardMethod, String descriptor) { - final boolean hasValueArg = hasValueArg(descriptor); - final int returnOpcode = Type.getReturnType(descriptor).getOpcode(IRETURN); - final MethodVisitor mv = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, method, descriptor, null, null); mv.visitCode(); - mv.visitVarInsn(ALOAD, 0); - emitFallback(mv, forwardMethod, descriptor, hasValueArg, returnOpcode); + emitFallback(mv, forwardMethod, descriptor, 0); mv.visitMaxs(-1, -1); mv.visitEnd(); } @@ -266,17 +358,16 @@ private static void generateCheckedDispatch(ClassWriter cw, String method, Strin emitInstanceOfCheck(mv, fallback); // fast path: ((KeyWithValue) key).accessorMethod(storeId[, value]) - mv.visitTypeInsn(CHECKCAST, KEYWITHVALUE_CLASS); + mv.visitTypeInsn(CHECKCAST, KEY_CLASS); mv.visitVarInsn(ILOAD, 1); if (hasValueArg) { mv.visitVarInsn(ALOAD, 2); } - mv.visitMethodInsn( - INVOKEINTERFACE, KEYWITHVALUE_CLASS, accessorMethod, accessorDescriptor, true); + mv.visitMethodInsn(INVOKEINTERFACE, KEY_CLASS, accessorMethod, accessorDescriptor, true); mv.visitInsn(returnOpcode); mv.visitLabel(fallback); - emitFallback(mv, method, descriptor, hasValueArg, returnOpcode); + emitFallback(mv, method, descriptor, 1); mv.visitMaxs(-1, -1); mv.visitEnd(); @@ -292,6 +383,8 @@ private static void generateDoubleCheckedDispatch( 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; @@ -311,10 +404,10 @@ private static void generateDoubleCheckedDispatch( emitInstanceOfCheck(mv, fallback); // KeyWithValue accessor = (KeyWithValue) key; - mv.visitTypeInsn(CHECKCAST, KEYWITHVALUE_CLASS); + mv.visitTypeInsn(CHECKCAST, KEY_CLASS); mv.visitVarInsn(ASTORE, accessorLocal); - // Object existing = accessor.$dd_instrument_$get$(storeId); + // Object existing = accessor.$get$__dd_instrument$(storeId); emitAccessorGet(mv, accessorLocal, existingLocal); // if (existing [is/isn't] null) return existing; @@ -326,20 +419,19 @@ private static void generateDoubleCheckedDispatch( mv.visitInsn(MONITORENTER); mv.visitLabel(monitorEntered); - // existing = accessor.$dd_instrument_$get$(storeId); (re-check now we hold the lock) + // existing = accessor.$get$__dd_instrument$(storeId); (recheck under the lock) emitAccessorGet(mv, accessorLocal, existingLocal); mv.visitVarInsn(ALOAD, existingLocal); mv.visitJumpInsn(skipToReturnOpcode, skipPut); - // stored = ; accessor.$dd_instrument_$put$(storeId, stored); + // 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.visitMethodInsn( - INVOKEINTERFACE, KEYWITHVALUE_CLASS, PUT_ACCESSOR, PUT_ACCESSOR_DESCRIPTOR, true); + mv.visitMethodInsn(INVOKEINTERFACE, KEY_CLASS, PUT_ACCESSOR, PUT_ACCESSOR_DESCRIPTOR, true); mv.visitLabel(skipPut); mv.visitVarInsn(ALOAD, accessorLocal); @@ -358,24 +450,26 @@ private static void generateDoubleCheckedDispatch( mv.visitInsn(ARETURN); mv.visitLabel(fallback); - emitFallback(mv, method, descriptor, hasValueArg, ARETURN); + emitFallback(mv, method, descriptor, 1); mv.visitMaxs(-1, -1); mv.visitEnd(); } - /** - * Emits {@code return GlobalObjectStore.method(key, storeId[, value]);} reusing the key reference - * already left on the stack by {@link #emitInstanceOfCheck}. - */ + /** Loads the remaining arguments, then calls the global store. */ private static void emitFallback( - MethodVisitor mv, String method, String descriptor, boolean hasValueArg, int returnOpcode) { - mv.visitVarInsn(ILOAD, 1); - if (hasValueArg) { - mv.visitVarInsn(ALOAD, 2); + MethodVisitor mv, String method, String descriptor, int loadedArguments) { + Type[] arguments = Type.getArgumentTypes(descriptor); + int local = 0; + for (int i = 0; i < arguments.length; i++) { + Type argument = arguments[i]; + if (i >= loadedArguments) { + mv.visitVarInsn(argument.getOpcode(ILOAD), local); + } + local += argument.getSize(); } mv.visitMethodInsn(INVOKESTATIC, GLOBALOBJECTSTORE_CLASS, method, descriptor, false); - mv.visitInsn(returnOpcode); + mv.visitInsn(Type.getReturnType(descriptor).getOpcode(IRETURN)); } /** @@ -385,122 +479,35 @@ private static void emitFallback( private static void emitInstanceOfCheck(MethodVisitor mv, Label notInjected) { mv.visitVarInsn(ALOAD, 0); mv.visitInsn(DUP); - mv.visitTypeInsn(INSTANCEOF, KEYWITHVALUE_CLASS); + mv.visitTypeInsn(INSTANCEOF, KEY_CLASS); mv.visitJumpInsn(IFEQ, notInjected); } - /** Emits {@code existing = accessor.$dd_instrument_$get$(storeId);} */ + /** 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); - mv.visitMethodInsn( - INVOKEINTERFACE, KEYWITHVALUE_CLASS, GET_ACCESSOR, GET_ACCESSOR_DESCRIPTOR, true); + mv.visitMethodInsn(INVOKEINTERFACE, KEY_CLASS, GET_ACCESSOR, GET_ACCESSOR_DESCRIPTOR, true); mv.visitVarInsn(ASTORE, existingLocal); } - /** Packs a relocated class as a string constant into the generated Java source lines. */ - private static void packRelocatedClass( - List lines, Remapper remapper, RelocatedClass relocated) { - String constantName = relocated.constantName; - lines.add(" /** Packed bytecode for relocated " + constantName + " */"); + private static void packGlue( + List lines, String constantName, String internalName, byte[] bytecode) { + lines.add(" /** Glue Id for " + constantName + " */"); + lines.add(" String " + constantName + "_ID = \"" + internalName.replace('/', '.') + "\";"); + lines.add(" /** Packed bytecode for " + constantName + " */"); lines.add(" String " + constantName + " ="); - packBytecode(lines, relocate(remapper, relocated.originalBytecode)); + packBytecode(lines, bytecode); } - /** Relocates the given bytecode with the given remapper, dropping non-essential metadata. */ + /** 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 MetadataPruner(new ClassRemapper(cw, remapper)), ClassReader.SKIP_DEBUG); + cr.accept(new ClassRemapper(cw, remapper), 0); return cw.toByteArray(); } - /** Drops annotations and generic signatures, which are unused by the relocated glue. */ - private static final class MetadataPruner extends ClassVisitor { - MetadataPruner(ClassVisitor cv) { - super(ASM9, cv); - } - - @Override - public void visit( - int version, - int access, - String name, - String signature, - String superName, - String[] interfaces) { - super.visit(version, access, name, null, superName, interfaces); - } - - @Override - public AnnotationVisitor visitAnnotation(String descriptor, boolean visible) { - return null; - } - - @Override - public AnnotationVisitor visitTypeAnnotation( - int typeRef, TypePath typePath, String descriptor, boolean visible) { - return null; - } - - @Override - public FieldVisitor visitField( - int access, String name, String descriptor, String signature, Object value) { - return new FieldVisitor(ASM9, super.visitField(access, name, descriptor, null, value)) { - @Override - public AnnotationVisitor visitAnnotation(String descriptor, boolean visible) { - return null; - } - - @Override - public AnnotationVisitor visitTypeAnnotation( - int typeRef, TypePath typePath, String descriptor, boolean visible) { - return null; - } - }; - } - - @Override - public MethodVisitor visitMethod( - int access, String name, String descriptor, String signature, String[] exceptions) { - return new MethodVisitor( - ASM9, super.visitMethod(access, name, descriptor, null, exceptions)) { - @Override - public AnnotationVisitor visitAnnotation(String descriptor, boolean visible) { - return null; - } - - @Override - public AnnotationVisitor visitTypeAnnotation( - int typeRef, TypePath typePath, String descriptor, boolean visible) { - return null; - } - - @Override - public void visitAnnotableParameterCount(int parameterCount, boolean visible) {} - - @Override - public AnnotationVisitor visitParameterAnnotation( - int parameter, String descriptor, boolean visible) { - return null; - } - }; - } - } - - /** Reads the bytecode of an already-compiled class off the classpath. */ - private static byte[] readClassResource(String internalName) throws IOException { - try (InputStream in = - ObjectStoreGlueGenerator.class - .getClassLoader() - .getResourceAsStream(internalName + ".class")) { - if (in == null) { - throw new IOException("Could not find class on classpath: " + internalName); - } - return JVM.readAllBytes(in); - } - } - /** 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/test/java/datadog/instrument/fieldinject/BootstrapDispatchInitializationTest.java b/field-inject/src/test/java/datadog/instrument/fieldinject/BootstrapDispatchInitializationTest.java new file mode 100644 index 00000000..3ffa1637 --- /dev/null +++ b/field-inject/src/test/java/datadog/instrument/fieldinject/BootstrapDispatchInitializationTest.java @@ -0,0 +1,127 @@ +package datadog.instrument.fieldinject; + +import static datadog.instrument.fieldinject.ObjectStoreDispatchTestSupport.initialize; +import static datadog.instrument.fieldinject.ObjectStoreDispatchTestSupport.newBootstrapDispatch; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.lang.invoke.MethodHandles; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.function.Function; +import org.junit.jupiter.api.Test; + +/** + * Exercises bootstrap glue initialization directly. + * + *

The expected initialization sequence is to initialize dispatch with a lookup scoped to the + * {@code GlobalObjectStore} before making fallback calls. The failure tests deliberately bypass + * this sequence to document the consequences of incomplete or incorrect setup. This makes the + * ordering and lookup requirements explicit for code that integrates the glue. + */ +class BootstrapDispatchInitializationTest { + @Test + void initializeLinksEveryFallbackBeforeReturning() throws Exception { + Class dispatch = newBootstrapDispatch(); + initialize(dispatch); + // Any fallback that still needs bootstrap will now fail, rather than silently linking lazily. + dispatch.getField("globalLookup").set(null, null); + + Object key = new Object(); + for (Method method : dispatch.getDeclaredMethods()) { + if (!Modifier.isPublic(method.getModifiers()) || method.getName().equals("initialize")) { + continue; + } + Class[] types = method.getParameterTypes(); + Object[] args = new Object[types.length]; + if (args.length > 0) { + args[0] = key; + args[1] = 0; + if (args.length > 2 && types[2] == Function.class) { + args[2] = (Function) k -> null; + } + } + method.invoke(null, args); + } + } + + @Test + void firstLookupWins() throws Exception { + Class dispatch = newBootstrapDispatch(); + Method get = dispatch.getMethod("get", Object.class, int.class); + Method put = dispatch.getMethod("put", Object.class, int.class, Object.class); + Object key = new Object(); + int storeId = 123; + GlobalObjectStore.put(key, storeId, "original"); + + initialize(dispatch); + initialize(dispatch, MethodHandles.lookup().in(OtherStore.class)); + + assertThat(get.invoke(null, key, storeId)).isEqualTo("original"); + put.invoke(null, key, storeId, "updated"); + assertThat(GlobalObjectStore.get(key, storeId)).isEqualTo("updated"); + assertThat(get.invoke(null, key, storeId)).isEqualTo("updated"); + } + + @Test + void callingGlueBeforeInitializationFails() throws Exception { + Class dispatch = newBootstrapDispatch(); + Method get = dispatch.getMethod("get", Object.class, int.class); + Object key = new Object(); + int storeId = 124; + + assertThatThrownBy(() -> get.invoke(null, key, storeId)) + .isInstanceOf(InvocationTargetException.class) + .hasCauseInstanceOf(BootstrapMethodError.class) + .hasRootCauseInstanceOf(NullPointerException.class); + } + + @Test + void incorrectFirstLookupCannotBeReplaced() throws Exception { + Class dispatch = newBootstrapDispatch(); + // The lookup must be scoped to GlobalObjectStore, not merely originate in its package. + assertThatThrownBy(() -> initialize(dispatch, MethodHandles.lookup())) + .isInstanceOf(InvocationTargetException.class) + .hasCauseInstanceOf(BootstrapMethodError.class) + .cause() + .cause() + .isInstanceOf(NoSuchMethodException.class); + assertThatThrownBy(() -> initialize(dispatch)) + .isInstanceOf(InvocationTargetException.class) + .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. */ + public static class OtherStore { + public static Object get(Object key, int storeId) { + return "other store"; + } + + public static void put(Object key, int storeId, Object value) {} + + public static Object getOrPut(Object key, int storeId, Object value) { + return "other store"; + } + + public static Object getOrCompute(Object key, int storeId, Function function) { + return "other store"; + } + + public static Object remove(Object key, int storeId) { + return "other store"; + } + + public static int removeStaleEntries() { + return 42; + } + } +} diff --git a/field-inject/src/test/java/datadog/instrument/fieldinject/BootstrapDispatchTest.java b/field-inject/src/test/java/datadog/instrument/fieldinject/BootstrapDispatchTest.java new file mode 100644 index 00000000..eb3f081d --- /dev/null +++ b/field-inject/src/test/java/datadog/instrument/fieldinject/BootstrapDispatchTest.java @@ -0,0 +1,23 @@ +package datadog.instrument.fieldinject; + +import static datadog.instrument.fieldinject.ObjectStoreDispatchTestSupport.BOOT_DISPATCH; +import static datadog.instrument.fieldinject.ObjectStoreDispatchTestSupport.BOOT_KEY_WITH_VALUE; +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; + +class BootstrapDispatchTest extends LocalDispatchTest { + @BeforeAll + static void initializeBootstrapDispatch() throws Exception { + assertThat(BOOT_KEY_WITH_VALUE.getClassLoader()).isNull(); + assertThat(BOOT_DISPATCH.getClassLoader()).isNull(); + ObjectStoreDispatchTestSupport.initialize(BOOT_DISPATCH); + } + + @Override + @BeforeEach + void loadGeneratedClasses() throws Exception { + loadGeneratedClasses(BOOT_KEY_WITH_VALUE, BOOT_DISPATCH); + } +} diff --git a/field-inject/src/test/java/datadog/instrument/fieldinject/ObjectStoreDispatchFunctionalTest.java b/field-inject/src/test/java/datadog/instrument/fieldinject/LocalDispatchTest.java similarity index 84% rename from field-inject/src/test/java/datadog/instrument/fieldinject/ObjectStoreDispatchFunctionalTest.java rename to field-inject/src/test/java/datadog/instrument/fieldinject/LocalDispatchTest.java index 92681903..06d9f433 100644 --- a/field-inject/src/test/java/datadog/instrument/fieldinject/ObjectStoreDispatchFunctionalTest.java +++ b/field-inject/src/test/java/datadog/instrument/fieldinject/LocalDispatchTest.java @@ -3,7 +3,9 @@ import static datadog.instrument.fieldinject.ObjectStoreIds.objectStoreId; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assumptions.assumeTrue; +import java.lang.ref.WeakReference; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -22,7 +24,7 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; -import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.tabletest.junit.TableTest; @@ -31,24 +33,30 @@ * fast-path/fallback dispatch and double-checked locking behave correctly - not just that the * bytecode passes structural verification (see {@code ObjectStoreGlueGeneratorTest}). * - *

The generated classes are loaded from the build-time glue on the test classpath, so they share - * the same class loader (and runtime package) as the package-private {@link GlobalObjectStore}. + *

This suite uses local dispatch. {@link BootstrapDispatchTest} repeats it with the bootstrap + * glue linked to the same {@link GlobalObjectStore}. */ -class ObjectStoreDispatchFunctionalTest { - - private static Class keyWithValueClass; - private static Method getMethod; - private static Method putMethod; - private static Method getOrPutMethod; - private static Method getOrComputeMethod; - private static Method removeMethod; - private static Method weakGetMethod; - private static Method weakPutMethod; - - @BeforeAll - static void loadGeneratedClasses() throws Exception { - keyWithValueClass = Class.forName("datadog.instrument.fieldinject.KeyWithValue"); - Class dispatchClass = Class.forName("datadog.instrument.fieldinject.ObjectStoreDispatch"); +class LocalDispatchTest { + + private Class keyWithValueClass; + private Method getMethod; + private Method putMethod; + private Method getOrPutMethod; + private Method getOrComputeMethod; + private Method removeMethod; + private Method weakGetMethod; + private Method weakPutMethod; + private Method removeStaleEntriesMethod; + + @BeforeEach + void loadGeneratedClasses() throws Exception { + loadGeneratedClasses( + Class.forName("datadog.instrument.fieldinject.KeyWithValue"), + Class.forName("datadog.instrument.fieldinject.ObjectStoreDispatch")); + } + + final void loadGeneratedClasses(Class keyClass, Class dispatchClass) throws Exception { + keyWithValueClass = keyClass; getMethod = dispatchClass.getMethod("get", Object.class, int.class); putMethod = dispatchClass.getMethod("put", Object.class, int.class, Object.class); @@ -58,6 +66,7 @@ static void loadGeneratedClasses() throws Exception { 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 @@ -83,7 +92,7 @@ void fastPathRoundTripsThroughAccessorAndBypassesGlobalStore() throws Exception } @Test - void fallbackPathDelegatesAllOperationsToGlobalObjectStoreForNonInjectedKey() throws Exception { + void uninjectedKeysUseGlobalStore() throws Exception { int storeId = objectStoreId("test.Dispatch.Fallback.Key", "test.Dispatch.Fallback.Value"); Object key = new Object(); @@ -91,6 +100,9 @@ void fallbackPathDelegatesAllOperationsToGlobalObjectStoreForNonInjectedKey() th assertThat(GlobalObjectStore.get(key, storeId)).isEqualTo("value"); assertThat(getMethod.invoke(null, key, storeId)).isEqualTo("value"); + GlobalObjectStore.put(key, storeId, "updated globally"); + assertThat(getMethod.invoke(null, key, storeId)).isEqualTo("updated globally"); + putMethod.invoke(null, key, storeId, "value"); assertThat(getOrPutMethod.invoke(null, key, storeId, "ignored")).isEqualTo("value"); assertThat(removeMethod.invoke(null, key, storeId)).isEqualTo("value"); assertThat(GlobalObjectStore.get(key, storeId)).isNull(); @@ -189,7 +201,7 @@ void removeDoesNotWriteToAccessorWhenValueIsAbsent() throws Exception { } @Test - void injectedAccessorFallsBackViaWeakGetPutForStoresItDoesNotHave() throws Exception { + void missingInjectedStoreUsesWeakFallback() throws Exception { int injectedId = objectStoreId("test.Dispatch.Weak.Key", "test.Dispatch.Weak.Injected"); int fallbackId = objectStoreId("test.Dispatch.Weak.Key", "test.Dispatch.Weak.Fallback"); Map backing = Collections.synchronizedMap(new HashMap<>()); @@ -370,10 +382,48 @@ void nullComputedValueIsNotCachedAndCanBeRetried() throws Exception { assertThat(backing.get(storeId)).isEqualTo("computed"); } + @Test + void removeStaleEntriesReportsSizeAndReleasesValuesForCollectedKeys() throws Exception { + int storeId = objectStoreId("test.Dispatch.Cleanup.Key", "test.Dispatch.Cleanup.Value"); + Object liveKey = new Object(); + putMethod.invoke(null, liveKey, storeId, "alive"); + WeakReference staleValue = putWithEphemeralKey(storeId); + assertThat(staleValue.get()).isNotNull(); + + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + int remaining; + WeakReference gcProbe; + do { + remaining = (Integer) removeStaleEntriesMethod.invoke(null); + // An independent probe distinguishes unavailable GC from a value retained by broken cleanup. + gcProbe = new WeakReference<>(new Object()); + System.gc(); + if (staleValue.get() == null) { + break; + } + Thread.sleep(10); + } while (System.nanoTime() < deadline); + + assertThat(remaining).as("the live entry must be included in the size").isPositive(); + assertThat(getMethod.invoke(null, liveKey, storeId)).isEqualTo("alive"); + removeMethod.invoke(null, liveKey, storeId); + assumeTrue( + staleValue.get() == null || gcProbe.get() == null, + "GC did not collect the independent probe within the timeout"); + assertThat(staleValue.get()).as("cleanup must release the stale entry's value").isNull(); + } + + private WeakReference putWithEphemeralKey(int storeId) throws Exception { + Object key = new Object(); + Object value = new Object(); + putMethod.invoke(null, key, storeId, value); + return new WeakReference<>(value); + } + /** * Creates a {@code KeyWithValue} proxy backed by a plain map, simulating a field-injected key. */ - private static Object fastPathKey(Map backing) { + private Object fastPathKey(Map backing) { InvocationHandler handler = (proxy, method, args) -> { if (args.length == 1) { @@ -392,7 +442,7 @@ private static Object fastPathKey(Map backing) { * to {@code GlobalObjectStore}). Fails fast if the accessor is re-entered by a recursive * fallback. */ - private static Object injectedKey(Map backing, Set injectedIds) { + private Object injectedKey(Map backing, Set injectedIds) { AtomicInteger depth = new AtomicInteger(); InvocationHandler handler = (proxy, method, args) -> { diff --git a/field-inject/src/test/java/datadog/instrument/fieldinject/ObjectStoreDispatchTestSupport.java b/field-inject/src/test/java/datadog/instrument/fieldinject/ObjectStoreDispatchTestSupport.java new file mode 100644 index 00000000..6a6582c0 --- /dev/null +++ b/field-inject/src/test/java/datadog/instrument/fieldinject/ObjectStoreDispatchTestSupport.java @@ -0,0 +1,66 @@ +package datadog.instrument.fieldinject; + +import datadog.instrument.classinject.ClassInjector; +import datadog.instrument.glue.Glue; +import datadog.instrument.glue.ObjectStoreGlue; +import datadog.instrument.testing.TestAgent; +import java.lang.invoke.MethodHandles; +import java.util.concurrent.atomic.AtomicInteger; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassVisitor; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.FieldVisitor; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.commons.ClassRemapper; +import org.objectweb.asm.commons.SimpleRemapper; + +final class ObjectStoreDispatchTestSupport { + private static final String DISPATCH_NAME = ObjectStoreGlue.DISPATCH_ID; + private static final AtomicInteger NEXT_ID = new AtomicInteger(); + + static final Class BOOT_KEY_WITH_VALUE; + static final Class BOOT_DISPATCH; + + static { + ClassInjector.enableClassInjection(TestAgent.getInstrumentation()); + BOOT_KEY_WITH_VALUE = + ClassInjector.injectBootClass( + ObjectStoreGlue.KEY_ID, Glue.unpackBytecode(ObjectStoreGlue.KEY)); + BOOT_DISPATCH = + ClassInjector.injectBootClass(DISPATCH_NAME, Glue.unpackBytecode(ObjectStoreGlue.DISPATCH)); + } + + private ObjectStoreDispatchTestSupport() {} + + static void initialize(Class dispatch) throws Exception { + initialize(dispatch, MethodHandles.lookup().in(GlobalObjectStore.class)); + } + + static void initialize(Class dispatch, MethodHandles.Lookup lookup) throws Exception { + dispatch.getMethod("initialize", MethodHandles.Lookup.class).invoke(null, lookup); + } + + /** Isolates first-binding and failed-linkage state without relying on test execution order. */ + static Class newBootstrapDispatch() { + String name = DISPATCH_NAME + "$Test" + NEXT_ID.incrementAndGet(); + 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()); + } +} 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 216aedad..8e405e15 100644 --- a/field-inject/src/test/java/datadog/instrument/fieldinject/ObjectStoreTest.java +++ b/field-inject/src/test/java/datadog/instrument/fieldinject/ObjectStoreTest.java @@ -358,7 +358,7 @@ void liveEntriesArePreservedByRemoveStaleEntries() { } @Test - void removeStaleEntriesIsIdempotent() { + void repeatedCleanupPreservesLiveEntries() { Object key = new Object(); store.put(key, "stable"); 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 aef388ab..0fb5614f 100644 --- a/field-inject/src/test/java/datadog/instrument/glue/ObjectStoreGlueGeneratorTest.java +++ b/field-inject/src/test/java/datadog/instrument/glue/ObjectStoreGlueGeneratorTest.java @@ -1,14 +1,13 @@ package datadog.instrument.glue; +import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.objectweb.asm.Opcodes.ASM9; import java.io.PrintWriter; import java.io.StringWriter; -import java.lang.reflect.Field; 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; @@ -16,34 +15,43 @@ import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.Handle; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.commons.ClassRemapper; import org.objectweb.asm.commons.Remapper; import org.objectweb.asm.util.CheckClassAdapter; +import org.tabletest.junit.TableTest; class ObjectStoreGlueGeneratorTest { @Test - void keyWithValueBytecodePassesVerification() { - verifyAll(ObjectStoreGlueGenerator.generateKeyWithValueBytecode()); + void keyBytecodeVerifies() { + verifyAll(ObjectStoreGlueGenerator.generateKey()); } @Test - void objectStoreDispatchBytecodePassesVerification() { - verifyAll(ObjectStoreGlueGenerator.generateObjectStoreDispatchBytecode()); + void localDispatchVerifies() { + verifyAll(ObjectStoreGlueGenerator.generateLocalDispatch()); } - @Test - void objectStoreDispatchFallbacksMatchGlobalObjectStoreSignatures() throws Exception { + @TableTest({ + "bootstrap", + "false ", + "true " + }) + void fallbacksMatchStoreSignatures(boolean bootstrap) throws Exception { // GlobalObjectStore is package-private, so look it up by name Class globalObjectStore = Class.forName("datadog.instrument.fieldinject.GlobalObjectStore"); // collect every static call the generated dispatch makes to GlobalObjectStore String globalObjectStoreClass = Type.getInternalName(globalObjectStore); Set fallbackCalls = new TreeSet<>(); - new ClassReader(ObjectStoreGlueGenerator.generateObjectStoreDispatchBytecode()) + new ClassReader( + bootstrap + ? Glue.unpackBytecode(ObjectStoreGlue.DISPATCH) + : ObjectStoreGlueGenerator.generateLocalDispatch()) .accept( new ClassVisitor(ASM9) { @Override @@ -62,9 +70,20 @@ public void visitMethodInsn( String descriptor, boolean isInterface) { if (opcode == Opcodes.INVOKESTATIC && owner.equals(globalObjectStoreClass)) { + assertThat(bootstrap).isFalse(); fallbackCalls.add(name + descriptor); } } + + @Override + public void visitInvokeDynamicInsn( + String name, String descriptor, Handle target, Object... arguments) { + assertThat(bootstrap).isTrue(); + assertThat(target.getOwner()) + .isEqualTo(ObjectStoreGlue.DISPATCH_ID.replace('.', '/')); + assertThat(target.getName()).isEqualTo("bootstrap"); + fallbackCalls.add(name + descriptor); + } }; } }, @@ -93,11 +112,12 @@ private static void verifyAll(byte[] bytecode) { } @Test - void relocatedGlueClassesPassVerification() throws Exception { + void bootstrapGlueVerifies() { List relocatedBytecode = relocatedBytecode(); - // KeyWithValue, ObjectStoreDispatch, GlobalObjectStore + $StoreKey + $LookupKey - assertThat(relocatedBytecode).hasSize(7); + assertThat(relocatedBytecode) + .extracting(bytecode -> new ClassReader(bytecode).getClassName().replace('/', '.')) + .containsExactly(ObjectStoreGlue.KEY_ID, ObjectStoreGlue.DISPATCH_ID); // the relocated classes reference each other by their new java.lang names, which can't be // loaded via a normal class loader (the JVM forbids defining classes into java.* packages @@ -111,7 +131,7 @@ void relocatedGlueClassesPassVerification() throws Exception { } @Test - void relocatedGlueClassesOnlyReferenceRelocatedTypes() throws Exception { + void bootstrapGlueHasNoLocalTypeReferences() { // catches nested/helper classes missing from the relocation list, which would otherwise // only fail at runtime with NoClassDefFoundError when loaded from the bootstrap classpath Set unrelocatedTypes = new TreeSet<>(); @@ -132,15 +152,9 @@ public String map(String internalName) { } /** Unpacks the relocated bytecode from the build-time generated {@code ObjectStoreGlue}. */ - private static List relocatedBytecode() throws IllegalAccessException { - // ObjectStoreGlue is generated at build-time and already compiled onto the test classpath - List relocatedBytecode = new ArrayList<>(); - for (Field field : ObjectStoreGlue.class.getFields()) { - if (field.getType() == String.class && !field.getName().equals("PREFIX")) { - relocatedBytecode.add(Glue.unpackBytecode((String) field.get(null))); - } - } - return relocatedBytecode; + private static List relocatedBytecode() { + return asList( + Glue.unpackBytecode(ObjectStoreGlue.KEY), Glue.unpackBytecode(ObjectStoreGlue.DISPATCH)); } /** Performs structural checks without resolving referenced types */ From 53162f168aecd8c1b695413d3b3d02d1deca2e1f Mon Sep 17 00:00:00 2001 From: Stuart McCulloch Date: Thu, 3 Dec 2026 13:16:12 +0000 Subject: [PATCH 2/2] Benchmark global fallback dispatch alternatives --- field-inject/build.gradle.kts | 9 + .../fieldinject/DispatchBenchmarkSupport.java | 246 ++++++++++++++++++ .../fieldinject/DispatchBridge.java | 38 +++ .../fieldinject/FinalHandleFallback.java | 47 ++++ .../ObjectStoreDispatchBenchmark.java | 104 ++++++++ 5 files changed, 444 insertions(+) create mode 100644 field-inject/src/jmh/java/datadog/instrument/fieldinject/DispatchBenchmarkSupport.java create mode 100644 field-inject/src/jmh/java/datadog/instrument/fieldinject/DispatchBridge.java create mode 100644 field-inject/src/jmh/java/datadog/instrument/fieldinject/FinalHandleFallback.java create mode 100644 field-inject/src/jmh/java/datadog/instrument/fieldinject/ObjectStoreDispatchBenchmark.java diff --git a/field-inject/build.gradle.kts b/field-inject/build.gradle.kts index 2a836e29..9ebd98fe 100644 --- a/field-inject/build.gradle.kts +++ b/field-inject/build.gradle.kts @@ -13,6 +13,15 @@ dependencies { testImplementation(libs.asm.util) jmh("com.blogspot.mydailyjava:weak-lock-free:0.18") + jmh(project(":testing")) + jmh(project(":class-inject")) + jmh(libs.asm.commons) +} + +val benchmarkAgent = configurations["testAgent"] +tasks.jmh { + dependsOn(benchmarkAgent) + jvmArgsPrepend.add(benchmarkAgent.elements.map { "-javaagent:${it.single().asFile.absolutePath}" }) } // field-inject generates dispatch + access glue for injection into the bootstrap classpath diff --git a/field-inject/src/jmh/java/datadog/instrument/fieldinject/DispatchBenchmarkSupport.java b/field-inject/src/jmh/java/datadog/instrument/fieldinject/DispatchBenchmarkSupport.java new file mode 100644 index 00000000..b9dbbf3a --- /dev/null +++ b/field-inject/src/jmh/java/datadog/instrument/fieldinject/DispatchBenchmarkSupport.java @@ -0,0 +1,246 @@ +/* + * Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License. + * This product includes software developed at Datadog (https://www.datadoghq.com/). + * Copyright 2026-Present Datadog, Inc. + */ + +package datadog.instrument.fieldinject; + +import static org.objectweb.asm.Opcodes.*; + +import datadog.instrument.classinject.ClassInjector; +import datadog.instrument.testing.TestAgent; +import java.io.IOException; +import java.lang.instrument.ClassFileTransformer; +import java.lang.instrument.Instrumentation; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.security.ProtectionDomain; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import javax.annotation.Nullable; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassVisitor; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.Handle; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Type; +import org.objectweb.asm.commons.ClassRemapper; +import org.objectweb.asm.commons.Remapper; +import org.objectweb.asm.commons.SimpleRemapper; + +final class DispatchBenchmarkSupport { + private static final String BOOT_PREFIX = "java/lang/$Datadog$"; + private static final String DIRECT_DISPATCH = BOOT_PREFIX + "ObjectStoreDispatch"; + private static final String BOOT_GLOBAL_STORE = BOOT_PREFIX + "GlobalObjectStore"; + private static final String BRIDGE = BOOT_PREFIX + "DispatchBenchmarkBridge"; + private static final String LOCAL_GLOBAL_STORE = + "datadog/instrument/fieldinject/GlobalObjectStore"; + private static byte[] directDispatcher; + private static String installed; + + private DispatchBenchmarkSupport() {} + + static synchronized void install(String variant) throws Exception { + if (installed != null) { + if (!installed.equals(variant)) { + throw new IllegalStateException("Use a separate JMH fork for each variant"); + } + return; + } + Instrumentation inst = TestAgent.getInstrumentation(); + ClassInjector.enableClassInjection(inst); + injectDirectStore(); + String dispatchClass = DIRECT_DISPATCH; + 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()) { + if (Modifier.isPublic(method.getModifiers()) && Modifier.isStatic(method.getModifiers())) { + targets.put(method.getName(), lookup.unreflect(method)); + } + } + 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; + } + + // Keep the measured baseline independent of the production bootstrap dispatcher. + private static void injectDirectStore() throws Exception { + List> classes = + new ArrayList<>(Arrays.asList(GlobalObjectStore.class.getDeclaredClasses())); + classes.add(GlobalObjectStore.class); + classes.add(Class.forName("datadog.instrument.fieldinject.KeyWithValue")); + classes.add(Class.forName("datadog.instrument.fieldinject.ObjectStoreDispatch")); + Map renames = new HashMap<>(); + for (Class type : classes) { + String name = Type.getInternalName(type); + renames.put(name, BOOT_PREFIX + name.substring(name.lastIndexOf('/') + 1)); + } + Remapper remapper = new SimpleRemapper(ASM9, renames); + Map bytecode = new LinkedHashMap<>(); + for (Class type : classes) { + ClassWriter writer = new ClassWriter(0); + new ClassReader(type.getName()) + .accept(new ClassRemapper(writer, remapper), ClassReader.SKIP_DEBUG); + bytecode.put(renames.get(Type.getInternalName(type)).replace('/', '.'), writer.toByteArray()); + } + directDispatcher = bytecode.get(DIRECT_DISPATCH.replace('/', '.')); + ClassInjector.injectBootClasses(bytecode); + } + + private static byte[] relocateBridge() throws IOException { + ClassWriter writer = new ClassWriter(0); + new ClassReader(DispatchBridge.class.getName()) + .accept( + new ClassRemapper( + writer, + new SimpleRemapper(ASM9, Type.getInternalName(DispatchBridge.class), BRIDGE)), + 0); + return writer.toByteArray(); + } + + private static byte[] dispatcher(String variant, String dispatchClass) throws IOException { + ClassWriter writer = new ClassWriter(0); + Handle bootstrap = + new Handle( + H_INVOKESTATIC, + BRIDGE, + "bootstrap", + MethodType.methodType( + java.lang.invoke.CallSite.class, + MethodHandles.Lookup.class, + String.class, + MethodType.class) + .toMethodDescriptorString(), + false); + new ClassReader(directDispatcher) + .accept( + new ClassRemapper( + new ClassVisitor(ASM9, writer) { + @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 && BOOT_GLOBAL_STORE.equals(owner)) { + if (variant.equals("indy")) { + visitInvokeDynamicInsn(name, descriptor, bootstrap); + } else { + super.visitMethodInsn( + INVOKESTATIC, dispatchClass, "fallback$" + name, descriptor, false); + } + } else { + super.visitMethodInsn(opcode, owner, name, descriptor, isInterface); + } + } + }; + } + + @Override + public void visitEnd() {} + }, + new SimpleRemapper(ASM9, DIRECT_DISPATCH, dispatchClass)), + 0); + if (variant.equals("finalHandle")) { + String template = Type.getInternalName(FinalHandleFallback.class); + Map renames = new HashMap<>(); + renames.put(template, dispatchClass); + renames.put(Type.getInternalName(DispatchBridge.class), BRIDGE); + Remapper remapper = + new SimpleRemapper(ASM9, renames) { + @Override + public String mapMethodName(String owner, String name, String descriptor) { + return owner.equals(template) && !name.startsWith("<") + ? "fallback$" + name + : super.mapMethodName(owner, name, descriptor); + } + }; + new ClassReader(FinalHandleFallback.class.getName()) + .accept( + new ClassRemapper( + new ClassVisitor(ASM9, writer) { + @Override + public void visit( + int version, + int access, + String name, + String signature, + String superName, + String[] interfaces) {} + + @Override + public MethodVisitor visitMethod( + int access, + String name, + String descriptor, + String signature, + String[] exceptions) { + return name.equals("") + ? null + : super.visitMethod(access, name, descriptor, signature, exceptions); + } + + @Override + public void visitEnd() {} + }, + remapper), + 0); + } else if (!variant.equals("indy")) { + throw new IllegalArgumentException(variant); + } + writer.visitEnd(); + return writer.toByteArray(); + } + + private static final class SelectDispatch implements ClassFileTransformer { + private final String dispatchClass; + + SelectDispatch(String dispatchClass) { + this.dispatchClass = dispatchClass; + } + + @Override + @Nullable + public byte[] transform( + @Nullable ClassLoader loader, + @Nullable String className, + @Nullable Class redefined, + @Nullable ProtectionDomain domain, + byte[] bytecode) { + if (redefined == null || !"datadog/instrument/fieldinject/ObjectStore".equals(className)) { + return null; + } + ClassReader reader = new ClassReader(bytecode); + ClassWriter writer = new ClassWriter(reader, 0); + reader.accept( + new ClassRemapper(writer, new SimpleRemapper(ASM9, LOCAL_GLOBAL_STORE, dispatchClass)), + 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 new file mode 100644 index 00000000..89bee84d --- /dev/null +++ b/field-inject/src/jmh/java/datadog/instrument/fieldinject/DispatchBridge.java @@ -0,0 +1,38 @@ +/* + * Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License. + * This product includes software developed at Datadog (https://www.datadoghq.com/). + * Copyright 2026-Present Datadog, Inc. + */ + +package datadog.instrument.fieldinject; + +import java.lang.invoke.CallSite; +import java.lang.invoke.ConstantCallSite; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.util.Collections; +import java.util.Map; + +/** Template copied to the bootstrap loader before either bridge is linked. */ +public final class DispatchBridge { + private static Map targets = Collections.emptyMap(); + + private DispatchBridge() {} + + public static void initialize(Map handles) { + targets = handles; + } + + public static MethodHandle target(String name) { + MethodHandle target = targets.get(name); + if (target == null) { + throw new IllegalArgumentException(name); + } + return target; + } + + public static CallSite bootstrap(MethodHandles.Lookup caller, String name, MethodType type) { + return new ConstantCallSite(target(name).asType(type)); + } +} diff --git a/field-inject/src/jmh/java/datadog/instrument/fieldinject/FinalHandleFallback.java b/field-inject/src/jmh/java/datadog/instrument/fieldinject/FinalHandleFallback.java new file mode 100644 index 00000000..1dc78238 --- /dev/null +++ b/field-inject/src/jmh/java/datadog/instrument/fieldinject/FinalHandleFallback.java @@ -0,0 +1,47 @@ +/* + * Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License. + * This product includes software developed at Datadog (https://www.datadoghq.com/). + * Copyright 2026-Present Datadog, Inc. + */ + +package datadog.instrument.fieldinject; + +import java.lang.invoke.MethodHandle; +import java.util.function.Function; + +/** Its fields and methods are copied into the generated final-handle dispatcher. */ +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() {} + + public static Object get(Object key, int storeId) throws Throwable { + return (Object) GET.invokeExact(key, storeId); + } + + public static void put(Object key, int storeId, Object value) throws Throwable { + PUT.invokeExact(key, storeId, value); + } + + public static Object getOrPut(Object key, int storeId, Object value) throws Throwable { + return (Object) GET_OR_PUT.invokeExact(key, storeId, value); + } + + public static Object getOrCompute(Object key, int storeId, Function factory) + throws Throwable { + return (Object) GET_OR_COMPUTE.invokeExact(key, storeId, factory); + } + + public static Object remove(Object key, int storeId) throws Throwable { + return (Object) REMOVE.invokeExact(key, storeId); + } + + public static int removeStaleEntries() throws Throwable { + return (int) CLEAN.invokeExact(); + } +} diff --git a/field-inject/src/jmh/java/datadog/instrument/fieldinject/ObjectStoreDispatchBenchmark.java b/field-inject/src/jmh/java/datadog/instrument/fieldinject/ObjectStoreDispatchBenchmark.java new file mode 100644 index 00000000..81463c09 --- /dev/null +++ b/field-inject/src/jmh/java/datadog/instrument/fieldinject/ObjectStoreDispatchBenchmark.java @@ -0,0 +1,104 @@ +/* + * Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License. + * This product includes software developed at Datadog (https://www.datadoghq.com/). + * Copyright 2026-Present Datadog, Inc. + */ + +package datadog.instrument.fieldinject; + +import static java.util.concurrent.TimeUnit.NANOSECONDS; + +import java.util.function.Function; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Param; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Threads; +import org.openjdk.jmh.annotations.Warmup; + +/** Runs with the testing jar supplied through -javaagent, including in each JMH fork. */ +@State(Scope.Thread) +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(NANOSECONDS) +@Warmup(iterations = 5, time = 1) +@Measurement(iterations = 5, time = 1) +@Fork( + value = 3, + jvmArgsAppend = {"-Xms512m", "-Xmx512m"}) +@Threads(1) +public class ObjectStoreDispatchBenchmark { + private static final int KEY_COUNT = 1024; + private static final int KEY_MASK = KEY_COUNT - 1; + private static final String KEY_TYPE = "benchmark.Dispatch.Key"; + private static final String VALUE_TYPE = "benchmark.Dispatch.Value"; + + @Param({"direct", "finalHandle", "indy"}) + public String dispatch; + + private final Object[] keys = new Object[KEY_COUNT]; + private final Object[] absentKeys = new Object[KEY_COUNT]; + private final Object value = new Object(); + private final Function factory = key -> value; + private ObjectStore store; + private int cursor; + + @Setup + public void setup() throws Exception { + DispatchBenchmarkSupport.install(dispatch); + store = ObjectStore.of(KEY_TYPE, VALUE_TYPE); + for (int i = 0; i < KEY_COUNT; i++) { + keys[i] = new Object(); + absentKeys[i] = new Object(); + store.put(keys[i], value); + } + verifyFallback(); + } + + private void verifyFallback() { + Object key = new Object(); + if (store.get(key) != null + || store.getOrPut(key, value) != value + || store.getOrCompute(key, factory) != value + || store.remove(key) != value + || store.getOrCompute(key, factory) != value + || store.remove(key) != value) { + throw new AssertionError("Global fallback failed: " + dispatch); + } + ObjectStore.removeStaleEntries(); + int storeId = ObjectStoreIds.objectStoreId(KEY_TYPE, VALUE_TYPE); + if (!dispatch.equals("direct") && GlobalObjectStore.get(keys[0], storeId) != value) { + throw new AssertionError("Bridge did not use the original global store"); + } + if (dispatch.equals("direct") && GlobalObjectStore.get(keys[0], storeId) != null) { + throw new AssertionError("Direct baseline did not use the bootstrap global store"); + } + } + + @Benchmark + public Object getHit() { + return store.get(keys[cursor++ & KEY_MASK]); + } + + @Benchmark + public Object getMiss() { + return store.get(absentKeys[cursor++ & KEY_MASK]); + } + + @Benchmark + public void putExisting() { + store.put(keys[cursor++ & KEY_MASK], value); + } + + @Benchmark + public Object putAndRemove() { + Object key = absentKeys[cursor++ & KEY_MASK]; + store.put(key, value); + return store.remove(key); + } +}