package jdk.nashorn.internal.runtime.linker;
import static jdk.nashorn.internal.lookup.Lookup.MH;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAdder;
import jdk.dynalink.DynamicLinker;
import jdk.dynalink.linker.GuardedInvocation;
import jdk.dynalink.support.ChainedCallSite;
import jdk.nashorn.internal.runtime.Context;
import jdk.nashorn.internal.runtime.Debug;
import jdk.nashorn.internal.runtime.ScriptObject;
import jdk.nashorn.internal.runtime.ScriptRuntime;
import jdk.nashorn.internal.runtime.options.Options;
public class LinkerCallSite extends ChainedCallSite {
public static final int ARGLIMIT = 250;
private static final String PROFILEFILE = Options.getStringProperty("nashorn.profilefile", "NashornProfile.txt");
private static final MethodHandle INCREASE_MISS_COUNTER = MH.findStatic(MethodHandles.lookup(), LinkerCallSite.class, "increaseMissCount", MH.type(Object.class, String.class, Object.class));
LinkerCallSite(final NashornCallSiteDescriptor descriptor) {
super(descriptor);
if (Context.DEBUG) {
LinkerCallSite.count.increment();
}
}
static LinkerCallSite newLinkerCallSite(final MethodHandles.Lookup lookup, final String name, final MethodType type, final int flags) {
final NashornCallSiteDescriptor desc = NashornCallSiteDescriptor.get(lookup, name, type, flags);
if (desc.isProfile()) {
return ProfilingLinkerCallSite.newProfilingLinkerCallSite(desc);
}
if (desc.isTrace()) {
return new TracingLinkerCallSite(desc);
}
return new LinkerCallSite(desc);
}
@Override
public String toString() {
return getDescriptor().toString();
}
public NashornCallSiteDescriptor getNashornDescriptor() {
return (NashornCallSiteDescriptor)getDescriptor();
}
@Override
public void relink(final GuardedInvocation invocation, final MethodHandle relink) {
super.relink(invocation, getDebuggingRelink(relink));
}
@Override
public void resetAndRelink(final GuardedInvocation invocation, final MethodHandle relink) {
super.resetAndRelink(invocation, getDebuggingRelink(relink));
}
private MethodHandle getDebuggingRelink(final MethodHandle relink) {
if (Context.DEBUG) {
return MH.filterArguments(relink, 0, getIncreaseMissCounter(relink.type().parameterType(0)));
}
return relink;
}
private MethodHandle getIncreaseMissCounter(final Class<?> type) {
final MethodHandle missCounterWithDesc = MH.bindTo(INCREASE_MISS_COUNTER, getDescriptor().getOperation() + " @ " + getScriptLocation());
if (type == Object.class) {
return missCounterWithDesc;
}
return MH.asType(missCounterWithDesc, missCounterWithDesc.type().changeParameterType(0, type).changeReturnType(type));
}
private static String getScriptLocation() {
final StackTraceElement caller = DynamicLinker.getLinkedCallSiteLocation();
return caller == null ? "unknown location" : (caller.getFileName() + ":" + caller.getLineNumber());
}
public static Object increaseMissCount(final String desc, final Object self) {
missCount.increment();
if (r.nextInt(100) < missSamplingPercentage) {
final AtomicInteger i = missCounts.get(desc);
if (i == null) {
missCounts.put(desc, new AtomicInteger(1));
} else {
i.incrementAndGet();
}
}
return self;
}
private static class ProfilingLinkerCallSite extends LinkerCallSite {
private static LinkedList<ProfilingLinkerCallSite> profileCallSites = null;
private long startTime;
private int depth;
private long totalTime;
private long hitCount;
private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
private static final MethodHandle PROFILEENTRY = MH.findVirtual(LOOKUP, ProfilingLinkerCallSite.class, "profileEntry", MH.type(Object.class, Object.class));
private static final MethodHandle PROFILEEXIT = MH.findVirtual(LOOKUP, ProfilingLinkerCallSite.class, "profileExit", MH.type(Object.class, Object.class));
private static final MethodHandle PROFILEVOIDEXIT = MH.findVirtual(LOOKUP, ProfilingLinkerCallSite.class, "profileVoidExit", MH.type(void.class));
ProfilingLinkerCallSite(final NashornCallSiteDescriptor desc) {
super(desc);
}
public static ProfilingLinkerCallSite newProfilingLinkerCallSite(final NashornCallSiteDescriptor desc) {
if (profileCallSites == null) {
profileCallSites = new LinkedList<>();
final Thread profileDumperThread = new Thread(new ProfileDumper());
Runtime.getRuntime().addShutdownHook(profileDumperThread);
}
final ProfilingLinkerCallSite callSite = new ProfilingLinkerCallSite(desc);
profileCallSites.add(callSite);
return callSite;
}
@Override
public void setTarget(final MethodHandle newTarget) {
final MethodType type = type();
final boolean isVoid = type.returnType() == void.class;
final Class<?> newSelfType = newTarget.type().parameterType(0);
MethodHandle selfFilter = MH.bindTo(PROFILEENTRY, this);
if (newSelfType != Object.class) {
final MethodType selfFilterType = MethodType.methodType(newSelfType, newSelfType);
selfFilter = selfFilter.asType(selfFilterType);
}
MethodHandle methodHandle = MH.filterArguments(newTarget, 0, selfFilter);
if (isVoid) {
methodHandle = MH.filterReturnValue(methodHandle, MH.bindTo(PROFILEVOIDEXIT, this));
} else {
final MethodType filter = MH.type(type.returnType(), type.returnType());
methodHandle = MH.filterReturnValue(methodHandle, MH.asType(MH.bindTo(PROFILEEXIT, this), filter));
}
super.setTarget(methodHandle);
}
@SuppressWarnings("unused")
public Object profileEntry(final Object self) {
if (depth == 0) {
startTime = System.nanoTime();
}
depth++;
hitCount++;
return self;
}
@SuppressWarnings("unused")
public Object profileExit(final Object result) {
depth--;
if (depth == 0) {
totalTime += System.nanoTime() - startTime;
}
return result;
}
@SuppressWarnings("unused")
public void profileVoidExit() {
depth--;
if (depth == 0) {
totalTime += System.nanoTime() - startTime;
}
}
static class ProfileDumper implements Runnable {
@Override
public void run() {
PrintWriter out = null;
boolean fileOutput = false;
try {
try {
out = new PrintWriter(new FileOutputStream(PROFILEFILE));
fileOutput = true;
} catch (final FileNotFoundException e) {
out = Context.getCurrentErr();
}
dump(out);
} finally {
if (out != null && fileOutput) {
out.close();
}
}
}
private static void dump(final PrintWriter out) {
int index = 0;
for (final ProfilingLinkerCallSite callSite : profileCallSites) {
out.println("" + (index++) + '\t' +
callSite.getDescriptor().getOperation() + '\t' +
callSite.totalTime + '\t' +
callSite.hitCount);
}
}
}
}
private static class TracingLinkerCallSite extends LinkerCallSite {
private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
private static final MethodHandle TRACEOBJECT = MH.findVirtual(LOOKUP, TracingLinkerCallSite.class, "traceObject", MH.type(Object.class, MethodHandle.class, Object[].class));
private static final MethodHandle TRACEVOID = MH.findVirtual(LOOKUP, TracingLinkerCallSite.class, "traceVoid", MH.type(void.class, MethodHandle.class, Object[].class));
private static final MethodHandle TRACEMISS = MH.findVirtual(LOOKUP, TracingLinkerCallSite.class, "traceMiss", MH.type(void.class, String.class, Object[].class));
TracingLinkerCallSite(final NashornCallSiteDescriptor desc) {
super(desc);
}
@Override
public void setTarget(final MethodHandle newTarget) {
if (!getNashornDescriptor().isTraceEnterExit()) {
super.setTarget(newTarget);
return;
}
final MethodType type = type();
final boolean isVoid = type.returnType() == void.class;
MethodHandle traceMethodHandle = isVoid ? TRACEVOID : TRACEOBJECT;
traceMethodHandle = MH.bindTo(traceMethodHandle, this);
traceMethodHandle = MH.bindTo(traceMethodHandle, newTarget);
traceMethodHandle = MH.asCollector(traceMethodHandle, Object[].class, type.parameterCount());
traceMethodHandle = MH.asType(traceMethodHandle, type);
super.setTarget(traceMethodHandle);
}
@Override
public void initialize(final MethodHandle relinkAndInvoke) {
super.initialize(getFallbackLoggingRelink(relinkAndInvoke));
}
@Override
public void relink(final GuardedInvocation invocation, final MethodHandle relink) {
super.relink(invocation, getFallbackLoggingRelink(relink));
}
@Override
public void resetAndRelink(final GuardedInvocation invocation, final MethodHandle relink) {
super.resetAndRelink(invocation, getFallbackLoggingRelink(relink));
}
private MethodHandle getFallbackLoggingRelink(final MethodHandle relink) {
if (!getNashornDescriptor().isTraceMisses()) {
return relink;
}
final MethodType type = relink.type();
return MH.foldArguments(relink, MH.asType(MH.asCollector(MH.insertArguments(TRACEMISS, 0, this, "MISS " + getScriptLocation() + " "), Object[].class, type.parameterCount()), type.changeReturnType(void.class)));
}
private void printObject(final PrintWriter out, final Object arg) {
if (!getNashornDescriptor().isTraceObjects()) {
out.print((arg instanceof ScriptObject) ? "ScriptObject" : arg);
return;
}
if (arg instanceof ScriptObject) {
final ScriptObject object = (ScriptObject)arg;
boolean isFirst = true;
final Set<Object> keySet = object.keySet();
if (keySet.isEmpty()) {
out.print(ScriptRuntime.safeToString(arg));
} else {
out.print("{ ");
for (final Object key : keySet) {
if (!isFirst) {
out.print(", ");
}
out.print(key);
out.print(":");
final Object value = object.get(key);
if (value instanceof ScriptObject) {
out.print("...");
} else {
printObject(out, value);
}
isFirst = false;
}
out.print(" }");
}
} else {
out.print(ScriptRuntime.safeToString(arg));
}
}
private void tracePrint(final PrintWriter out, final String tag, final Object[] args, final Object result) {
out.print(Debug.id(this) + " TAG " + tag);
out.print(getDescriptor().getOperation() + "(");
if (args.length > 0) {
printObject(out, args[0]);
for (int i = 1; i < args.length; i++) {
final Object arg = args[i];
out.print(", ");
if (!(arg instanceof ScriptObject && ((ScriptObject)arg).isScope())) {
printObject(out, arg);
} else {
out.print("SCOPE");
}
}
}
out.print(")");
if (tag.equals("EXIT ")) {
out.print(" --> ");
printObject(out, result);
}
out.println();
}
@SuppressWarnings("unused")
public Object traceObject(final MethodHandle mh, final Object... args) throws Throwable {
final PrintWriter out = Context.getCurrentErr();
tracePrint(out, "ENTER ", args, null);
final Object result = mh.invokeWithArguments(args);
tracePrint(out, "EXIT ", args, result);
return result;
}
@SuppressWarnings("unused")
public void traceVoid(final MethodHandle mh, final Object... args) throws Throwable {
final PrintWriter out = Context.getCurrentErr();
tracePrint(out, "ENTER ", args, null);
mh.invokeWithArguments(args);
tracePrint(out, "EXIT ", args, null);
}
@SuppressWarnings("unused")
public void traceMiss(final String desc, final Object... args) throws Throwable {
tracePrint(Context.getCurrentErr(), desc, args, null);
}
}
private static LongAdder count;
private static final HashMap<String, AtomicInteger> missCounts = new HashMap<>();
private static LongAdder missCount;
private static final Random r = new Random();
private static final int missSamplingPercentage = Options.getIntProperty("nashorn.tcs.miss.samplePercent", 1);
static {
if (Context.DEBUG) {
count = new LongAdder();
missCount = new LongAdder();
}
}
@Override
protected int getMaxChainLength() {
return 8;
}
public static long getCount() {
return count.longValue();
}
public static long getMissCount() {
return missCount.longValue();
}
public static int getMissSamplingPercentage() {
return missSamplingPercentage;
}
public static void getMissCounts(final PrintWriter out) {
final ArrayList<Entry<String, AtomicInteger>> entries = new ArrayList<>(missCounts.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<String, AtomicInteger>>() {
@Override
public int compare(final Entry<String, AtomicInteger> o1, final Entry<String, AtomicInteger> o2) {
return o2.getValue().get() - o1.getValue().get();
}
});
for (final Entry<String, AtomicInteger> entry : entries) {
out.println(" " + entry.getKey() + "\t" + entry.getValue().get());
}
}
}