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