Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions internal-api/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,8 @@ dependencies {
// it contains annotations that are also present in the instrumented application classes
api("com.datadoghq:dd-javac-plugin-client:0.2.2")

implementation(libs.bytebuddy)

testImplementation("org.snakeyaml:snakeyaml-engine:2.9")
testImplementation(project(":utils:test-utils"))
testImplementation(libs.bundles.junit5)
Expand Down
52 changes: 50 additions & 2 deletions internal-api/src/main/java/datadog/trace/util/UnsafeUtils.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
package datadog.trace.util;

import static net.bytebuddy.matcher.ElementMatchers.isFinal;

import de.thetaphi.forbiddenapis.SuppressForbidden;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.asm.ModifierAdjustment;
import net.bytebuddy.description.modifier.FieldManifestation;
import net.bytebuddy.dynamic.DynamicType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.Unsafe;
Expand All @@ -13,6 +21,8 @@ public abstract class UnsafeUtils {

private static final Unsafe UNSAFE = getUnsafe();

private static final Map<String, Class<?>> CLASS_CACHE = new ConcurrentHashMap<>();

private static Unsafe getUnsafe() {
try {
Field f = Unsafe.class.getDeclaredField("theUnsafe");
Expand All @@ -37,7 +47,7 @@ private static Unsafe getUnsafe() {
* @param <T> Type of the object being cloned
*/
@SuppressWarnings("unchecked")
public static <T> T tryShallowClone(T original) {
public static <T> T originalTryShallowClone(T original) {
if (UNSAFE == null) {
log.debug("Unsafe is unavailable, {} will not be cloned", original);
return original;
Expand All @@ -58,7 +68,45 @@ public static <T> T tryShallowClone(T original) {
}
}

// TODO: JEP 500 - avoid mutating final fields
public static <T> T tryShallowClone(T original) {
if (UNSAFE == null) {
log.debug("Unsafe is unavailable, {} will not be cloned", original);
return original;
}
try {
Class<?> clazz = original.getClass();
if (!CLASS_CACHE.containsKey(clazz.getName())) {
CLASS_CACHE.put(clazz.getName(), createNonFinalSubclass(clazz));
}
Class<?> nonFinalSubclass = CLASS_CACHE.get(clazz.getName());

T clone = (T) UNSAFE.allocateInstance(nonFinalSubclass);

while (clazz != Object.class) {
cloneFields(clazz, original, clone);
clazz = clazz.getSuperclass();
}
return clone;

} catch (Throwable t) {
log.debug("Error while cloning {}: {}", original, t);
t.printStackTrace();
return original;
}
}

private static Class<?> createNonFinalSubclass(Class<?> clazz) throws Exception {
DynamicType.Unloaded<?> dynamicType =
new ByteBuddy()
.subclass(clazz)
.visit(new ModifierAdjustment().withFieldModifiers(isFinal(), FieldManifestation.PLAIN))
.make();
return dynamicType.load(clazz.getClassLoader()).getLoaded();
}

// Field::set() is forbidden because it may be used to mutate final fields, disallowed by
// https://openjdk.org/jeps/500.
// However, in this case we skip final fields, so it is safe.
@SuppressForbidden
private static void cloneFields(Class<?> clazz, Object original, Object clone) throws Exception {
for (Field field : clazz.getDeclaredFields()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import spock.lang.Specification

class UnsafeUtilsTest extends Specification {

def "test try shallow clone"() {
def "test try shallow clone does not clone final fields"() {
given:
def inner = new MyClass("a", false, [], "b", 2, null, null)
def instance = new MyClass("aaa", true, [ 4, 5, 6, ], "ddd", 1, new int[] {
Expand All @@ -16,13 +16,27 @@ class UnsafeUtilsTest extends Specification {

then:
clone !== instance
clone.a === instance.a
clone.b == instance.b
clone.c === instance.c
clone.d === instance.d
clone.e == instance.e
clone.f === instance.f
clone.g === instance.g
clone.a == null
clone.b == false
clone.c == null
clone.d == null
clone.e == 0
clone.f == null
clone.g == null
}

def "test try shallow clone clones non-final fields"() {
given:
def instance = new MyNonFinalClass("a", 1, [2, 3, 4])

when:
def clone = UnsafeUtils.tryShallowClone(instance)

then:
clone !== instance
clone.h == instance.h
clone.j == instance.j
clone.k === instance.k
}

private static class MyParentClass {
Expand Down Expand Up @@ -65,4 +79,16 @@ class UnsafeUtilsTest extends Specification {
this.g = g
}
}

private static class MyNonFinalClass {
private String h
private int j
private List<Integer> k

MyNonFinalClass(String h, int j, List<Integer> k) {
this.h = h
this.j = j
this.k = k
}
}
}
Loading