1 /* 2 * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23 24 25 package org.graalvm.compiler.core.test; 26 27 import static org.graalvm.compiler.debug.DebugContext.BASIC_LEVEL; 28 29 import java.util.ArrayList; 30 import java.util.Arrays; 31 import java.util.HashSet; 32 import java.util.List; 33 import java.util.Set; 34 35 import org.graalvm.compiler.core.common.type.ObjectStamp; 36 import org.graalvm.compiler.debug.DebugContext; 37 import org.graalvm.compiler.debug.GraalError; 38 import org.graalvm.compiler.graph.Graph; 39 import org.graalvm.compiler.graph.Node; 40 import org.graalvm.compiler.graph.NodeInputList; 41 import org.graalvm.compiler.nodes.CallTargetNode; 42 import org.graalvm.compiler.nodes.Invoke; 43 import org.graalvm.compiler.nodes.NodeView; 44 import org.graalvm.compiler.nodes.StructuredGraph; 45 import org.graalvm.compiler.nodes.ValueNode; 46 import org.graalvm.compiler.nodes.java.MethodCallTargetNode; 47 import org.graalvm.compiler.nodes.java.NewArrayNode; 48 import org.graalvm.compiler.nodes.java.StoreIndexedNode; 49 import org.graalvm.compiler.phases.VerifyPhase; 50 import org.graalvm.compiler.phases.tiers.PhaseContext; 51 52 import jdk.vm.ci.meta.Constant; 53 import jdk.vm.ci.meta.MetaAccessProvider; 54 import jdk.vm.ci.meta.PrimitiveConstant; 55 import jdk.vm.ci.meta.ResolvedJavaMethod; 56 import jdk.vm.ci.meta.ResolvedJavaType; 57 58 /** 59 * Verifies that call sites calling one of the methods in {@link DebugContext} use them correctly. 60 * Correct usage of the methods in {@link DebugContext} requires call sites to not eagerly evaluate 61 * their arguments. Additionally this phase verifies that no argument is the result of a call to 62 * {@link StringBuilder#toString()} or {@link StringBuffer#toString()}. Ideally the parameters at 63 * call sites of {@link DebugContext} are eliminated, and do not produce additional allocations, if 64 * {@link DebugContext#isDumpEnabled(int)} (or {@link DebugContext#isLogEnabled(int)}, ...) is 65 * {@code false}. 66 * 67 * Methods in {@link DebugContext} checked by this phase are various different versions of 68 * {@link DebugContext#log(String)} , {@link DebugContext#dump(int, Object, String)}, 69 * {@link DebugContext#logAndIndent(String)} and {@link DebugContext#verify(Object, String)}. 70 */ 71 public class VerifyDebugUsage extends VerifyPhase<PhaseContext> { 72 73 @Override 74 public boolean checkContract() { 75 return false; 76 } 77 78 MetaAccessProvider metaAccess; 79 80 @Override 81 protected boolean verify(StructuredGraph graph, PhaseContext context) { 82 metaAccess = context.getMetaAccess(); 83 ResolvedJavaType debugType = metaAccess.lookupJavaType(DebugContext.class); 84 ResolvedJavaType nodeType = metaAccess.lookupJavaType(Node.class); 85 ResolvedJavaType stringType = metaAccess.lookupJavaType(String.class); 86 ResolvedJavaType graalErrorType = metaAccess.lookupJavaType(GraalError.class); 87 88 for (MethodCallTargetNode t : graph.getNodes(MethodCallTargetNode.TYPE)) { 89 ResolvedJavaMethod callee = t.targetMethod(); 90 String calleeName = callee.getName(); 91 if (callee.getDeclaringClass().equals(debugType)) { 92 boolean isDump = calleeName.equals("dump"); 93 if (calleeName.equals("log") || calleeName.equals("logAndIndent") || calleeName.equals("verify") || isDump) { 94 verifyParameters(t, graph, t.arguments(), stringType, isDump ? 2 : 1); 95 } 96 } 97 if (callee.getDeclaringClass().isAssignableFrom(nodeType)) { 98 if (calleeName.equals("assertTrue") || calleeName.equals("assertFalse")) { 99 verifyParameters(t, graph, t.arguments(), stringType, 1); 100 } 101 } 102 if (callee.getDeclaringClass().isAssignableFrom(graalErrorType) && !graph.method().getDeclaringClass().isAssignableFrom(graalErrorType)) { 103 if (calleeName.equals("guarantee")) { 104 verifyParameters(t, graph, t.arguments(), stringType, 0); 105 } 106 if (calleeName.equals("<init>") && callee.getSignature().getParameterCount(false) == 2) { 107 verifyParameters(t, graph, t.arguments(), stringType, 1); 108 } 109 } 110 } 111 return true; 112 } 113 114 private void verifyParameters(MethodCallTargetNode callTarget, StructuredGraph callerGraph, NodeInputList<? extends ValueNode> args, ResolvedJavaType stringType, int startArgIdx) { 115 if (callTarget.targetMethod().isVarArgs() && args.get(args.count() - 1) instanceof NewArrayNode) { 116 // unpack the arguments to the var args 117 List<ValueNode> unpacked = new ArrayList<>(args.snapshot()); 118 NewArrayNode varArgParameter = (NewArrayNode) unpacked.remove(unpacked.size() - 1); 119 int firstVarArg = unpacked.size(); 120 for (Node usage : varArgParameter.usages()) { 121 if (usage instanceof StoreIndexedNode) { 122 StoreIndexedNode si = (StoreIndexedNode) usage; 123 unpacked.add(si.value()); 124 } 125 } 126 verifyParameters(callerGraph, callTarget, unpacked, stringType, startArgIdx, firstVarArg); 127 } else { 128 verifyParameters(callerGraph, callTarget, args, stringType, startArgIdx, -1); 129 } 130 } 131 132 private static final Set<Integer> DebugLevels = new HashSet<>( 133 Arrays.asList(DebugContext.ENABLED_LEVEL, BASIC_LEVEL, DebugContext.INFO_LEVEL, DebugContext.VERBOSE_LEVEL, DebugContext.DETAILED_LEVEL, DebugContext.VERY_DETAILED_LEVEL)); 134 135 /** 136 * The set of methods allowed to call a {@code Debug.dump(...)} method with the {@code level} 137 * parameter bound to {@link DebugContext#BASIC_LEVEL} and the {@code object} parameter bound to 138 * a {@link StructuredGraph} value. 139 * 140 * This whitelist exists to ensure any increase in graph dumps is in line with the policy 141 * outlined by {@link DebugContext#BASIC_LEVEL}. If you add a *justified* graph dump at this 142 * level, then update the whitelist. 143 */ 144 private static final Set<String> BasicLevelStructuredGraphDumpWhitelist = new HashSet<>(Arrays.asList( 145 "org.graalvm.compiler.phases.BasePhase.dumpAfter", 146 "org.graalvm.compiler.phases.BasePhase.dumpBefore", 147 "org.graalvm.compiler.core.GraalCompiler.emitFrontEnd", 148 "org.graalvm.compiler.truffle.compiler.PartialEvaluator.fastPartialEvaluation", 149 "org.graalvm.compiler.truffle.compiler.PartialEvaluator$PerformanceInformationHandler.reportPerformanceWarnings", 150 "org.graalvm.compiler.truffle.compiler.TruffleCompilerImpl.compilePEGraph", 151 "org.graalvm.compiler.core.test.VerifyDebugUsageTest$ValidDumpUsagePhase.run", 152 "org.graalvm.compiler.core.test.VerifyDebugUsageTest$InvalidConcatDumpUsagePhase.run", 153 "org.graalvm.compiler.core.test.VerifyDebugUsageTest$InvalidDumpUsagePhase.run")); 154 155 /** 156 * The set of methods allowed to call a {@code Debug.dump(...)} method with the {@code level} 157 * parameter bound to {@link DebugContext#INFO_LEVEL} and the {@code object} parameter bound to 158 * a {@link StructuredGraph} value. 159 * 160 * This whitelist exists to ensure any increase in graph dumps is in line with the policy 161 * outlined by {@link DebugContext#INFO_LEVEL}. If you add a *justified* graph dump at this 162 * level, then update the whitelist. 163 */ 164 private static final Set<String> InfoLevelStructuredGraphDumpWhitelist = new HashSet<>(Arrays.asList( 165 "org.graalvm.compiler.core.GraalCompiler.emitFrontEnd", 166 "org.graalvm.compiler.phases.BasePhase.dumpAfter", 167 "org.graalvm.compiler.replacements.ReplacementsImpl$GraphMaker.makeGraph", 168 "org.graalvm.compiler.replacements.SnippetTemplate.instantiate")); 169 170 private void verifyParameters(StructuredGraph callerGraph, MethodCallTargetNode debugCallTarget, List<? extends ValueNode> args, ResolvedJavaType stringType, int startArgIdx, 171 int varArgsIndex) { 172 ResolvedJavaMethod verifiedCallee = debugCallTarget.targetMethod(); 173 Integer dumpLevel = null; 174 int argIdx = startArgIdx; 175 int varArgsElementIndex = 0; 176 boolean reportVarArgs = false; 177 for (int i = 0; i < args.size(); i++) { 178 ValueNode arg = args.get(i); 179 if (arg instanceof Invoke) { 180 reportVarArgs = varArgsIndex >= 0 && argIdx >= varArgsIndex; 181 Invoke invoke = (Invoke) arg; 182 CallTargetNode callTarget = invoke.callTarget(); 183 if (callTarget instanceof MethodCallTargetNode) { 184 ResolvedJavaMethod m = ((MethodCallTargetNode) callTarget).targetMethod(); 185 if (m.getName().equals("toString")) { 186 int bci = invoke.bci(); 187 int nonVarArgIdx = reportVarArgs ? argIdx - varArgsElementIndex : argIdx; 188 verifyStringConcat(callerGraph, verifiedCallee, bci, nonVarArgIdx, reportVarArgs ? varArgsElementIndex : -1, m); 189 verifyToStringCall(callerGraph, verifiedCallee, stringType, m, bci, nonVarArgIdx, reportVarArgs ? varArgsElementIndex : -1); 190 } else if (m.getName().equals("format")) { 191 int bci = invoke.bci(); 192 int nonVarArgIdx = reportVarArgs ? argIdx - varArgsElementIndex : argIdx; 193 verifyFormatCall(callerGraph, verifiedCallee, stringType, m, bci, nonVarArgIdx, reportVarArgs ? varArgsElementIndex : -1); 194 195 } 196 } 197 } 198 if (i == 1) { 199 if (verifiedCallee.getName().equals("dump")) { 200 dumpLevel = verifyDumpLevelParameter(callerGraph, debugCallTarget, verifiedCallee, arg); 201 } 202 } else if (i == 2) { 203 if (dumpLevel != null) { 204 verifyDumpObjectParameter(callerGraph, debugCallTarget, arg, verifiedCallee, dumpLevel); 205 } 206 } 207 if (varArgsIndex >= 0 && i >= varArgsIndex) { 208 varArgsElementIndex++; 209 } 210 argIdx++; 211 } 212 } 213 214 /** 215 * The {@code level} arg for the {@code Debug.dump(...)} methods must be a reference to one of 216 * the {@code Debug.*_LEVEL} constants. 217 */ 218 protected Integer verifyDumpLevelParameter(StructuredGraph callerGraph, MethodCallTargetNode debugCallTarget, ResolvedJavaMethod verifiedCallee, ValueNode arg) 219 throws org.graalvm.compiler.phases.VerifyPhase.VerificationError { 220 // The 'level' arg for the Debug.dump(...) methods must be a reference to one of 221 // the Debug.*_LEVEL constants. 222 223 Constant c = arg.asConstant(); 224 if (c != null) { 225 Integer dumpLevel = ((PrimitiveConstant) c).asInt(); 226 if (!DebugLevels.contains(dumpLevel)) { 227 StackTraceElement e = callerGraph.method().asStackTraceElement(debugCallTarget.invoke().bci()); 228 throw new VerificationError( 229 "In %s: parameter 0 of call to %s does not match a Debug.*_LEVEL constant: %s.%n", e, verifiedCallee.format("%H.%n(%p)"), dumpLevel); 230 } 231 return dumpLevel; 232 } 233 StackTraceElement e = callerGraph.method().asStackTraceElement(debugCallTarget.invoke().bci()); 234 throw new VerificationError( 235 "In %s: parameter 0 of call to %s must be a constant, not %s.%n", e, verifiedCallee.format("%H.%n(%p)"), arg); 236 } 237 238 protected void verifyDumpObjectParameter(StructuredGraph callerGraph, MethodCallTargetNode debugCallTarget, ValueNode arg, ResolvedJavaMethod verifiedCallee, Integer dumpLevel) 239 throws org.graalvm.compiler.phases.VerifyPhase.VerificationError { 240 ResolvedJavaType argType = ((ObjectStamp) arg.stamp(NodeView.DEFAULT)).type(); 241 if (metaAccess.lookupJavaType(Graph.class).isAssignableFrom(argType)) { 242 verifyStructuredGraphDumping(callerGraph, debugCallTarget, verifiedCallee, dumpLevel); 243 } 244 } 245 246 /** 247 * Verifies that dumping a {@link StructuredGraph} at level {@link DebugContext#BASIC_LEVEL} or 248 * {@link DebugContext#INFO_LEVEL} only occurs in white-listed methods. 249 */ 250 protected void verifyStructuredGraphDumping(StructuredGraph callerGraph, MethodCallTargetNode debugCallTarget, ResolvedJavaMethod verifiedCallee, Integer dumpLevel) 251 throws org.graalvm.compiler.phases.VerifyPhase.VerificationError { 252 if (dumpLevel == DebugContext.BASIC_LEVEL) { 253 StackTraceElement e = callerGraph.method().asStackTraceElement(debugCallTarget.invoke().bci()); 254 String qualifiedMethod = e.getClassName() + "." + e.getMethodName(); 255 if (!BasicLevelStructuredGraphDumpWhitelist.contains(qualifiedMethod)) { 256 throw new VerificationError( 257 "In %s: call to %s with level == DebugContext.BASIC_LEVEL not in %s.BasicLevelDumpWhitelist.%n", e, verifiedCallee.format("%H.%n(%p)"), 258 getClass().getName()); 259 } 260 } else if (dumpLevel == DebugContext.INFO_LEVEL) { 261 StackTraceElement e = callerGraph.method().asStackTraceElement(debugCallTarget.invoke().bci()); 262 String qualifiedMethod = e.getClassName() + "." + e.getMethodName(); 263 if (!InfoLevelStructuredGraphDumpWhitelist.contains(qualifiedMethod)) { 264 throw new VerificationError( 265 "In %s: call to %s with level == Debug.INFO_LEVEL not in %s.InfoLevelDumpWhitelist.%n", e, verifiedCallee.format("%H.%n(%p)"), 266 getClass().getName()); 267 } 268 } 269 } 270 271 /** 272 * Checks that a given call is not to {@link StringBuffer#toString()} or 273 * {@link StringBuilder#toString()}. 274 */ 275 private static void verifyStringConcat(StructuredGraph callerGraph, ResolvedJavaMethod verifiedCallee, int bci, int argIdx, int varArgsElementIndex, ResolvedJavaMethod callee) { 276 if (callee.getDeclaringClass().getName().equals("Ljava/lang/StringBuilder;") || callee.getDeclaringClass().getName().equals("Ljava/lang/StringBuffer;")) { 277 StackTraceElement e = callerGraph.method().asStackTraceElement(bci); 278 if (varArgsElementIndex >= 0) { 279 throw new VerificationError( 280 "In %s: element %d of parameter %d of call to %s appears to be a String concatenation expression.%n", e, varArgsElementIndex, argIdx, 281 verifiedCallee.format("%H.%n(%p)")); 282 } else { 283 throw new VerificationError( 284 "In %s: parameter %d of call to %s appears to be a String concatenation expression.", e, argIdx, verifiedCallee.format("%H.%n(%p)")); 285 } 286 } 287 } 288 289 /** 290 * Checks that a given call is not to {@link Object#toString()}. 291 */ 292 private static void verifyToStringCall(StructuredGraph callerGraph, ResolvedJavaMethod verifiedCallee, ResolvedJavaType stringType, ResolvedJavaMethod callee, int bci, int argIdx, 293 int varArgsElementIndex) { 294 if (callee.getSignature().getParameterCount(false) == 0 && callee.getSignature().getReturnType(callee.getDeclaringClass()).equals(stringType)) { 295 StackTraceElement e = callerGraph.method().asStackTraceElement(bci); 296 if (varArgsElementIndex >= 0) { 297 throw new VerificationError( 298 "In %s: element %d of parameter %d of call to %s is a call to toString() which is redundant (the callee will do it) and forces unnecessary eager evaluation.", 299 e, varArgsElementIndex, argIdx, verifiedCallee.format("%H.%n(%p)")); 300 } else { 301 throw new VerificationError("In %s: parameter %d of call to %s is a call to toString() which is redundant (the callee will do it) and forces unnecessary eager evaluation.", e, argIdx, 302 verifiedCallee.format("%H.%n(%p)")); 303 } 304 } 305 } 306 307 /** 308 * Checks that a given call is not to {@link String#format(String, Object...)} or 309 * {@link String#format(java.util.Locale, String, Object...)}. 310 */ 311 private static void verifyFormatCall(StructuredGraph callerGraph, ResolvedJavaMethod verifiedCallee, ResolvedJavaType stringType, ResolvedJavaMethod callee, int bci, int argIdx, 312 int varArgsElementIndex) { 313 if (callee.getDeclaringClass().equals(stringType) && callee.getSignature().getReturnType(callee.getDeclaringClass()).equals(stringType)) { 314 StackTraceElement e = callerGraph.method().asStackTraceElement(bci); 315 if (varArgsElementIndex >= 0) { 316 throw new VerificationError( 317 "In %s: element %d of parameter %d of call to %s is a call to String.format() which is redundant (%s does formatting) and forces unnecessary eager evaluation.", 318 e, varArgsElementIndex, argIdx, verifiedCallee.format("%H.%n(%p)"), verifiedCallee.format("%h.%n")); 319 } else { 320 throw new VerificationError("In %s: parameter %d of call to %s is a call to String.format() which is redundant (%s does formatting) and forces unnecessary eager evaluation.", e, 321 argIdx, 322 verifiedCallee.format("%H.%n(%p)"), verifiedCallee.format("%h.%n")); 323 } 324 } 325 } 326 }