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                     "org.graalvm.compiler.hotspot.SymbolicSnippetEncoder.verifySnippetEncodeDecode"));
 155 
 156     /**
 157      * The set of methods allowed to call a {@code Debug.dump(...)} method with the {@code level}
 158      * parameter bound to {@link DebugContext#INFO_LEVEL} and the {@code object} parameter bound to
 159      * a {@link StructuredGraph} value.
 160      *
 161      * This whitelist exists to ensure any increase in graph dumps is in line with the policy
 162      * outlined by {@link DebugContext#INFO_LEVEL}. If you add a *justified* graph dump at this
 163      * level, then update the whitelist.
 164      */
 165     private static final Set<String> InfoLevelStructuredGraphDumpWhitelist = new HashSet<>(Arrays.asList(
 166                     "org.graalvm.compiler.core.GraalCompiler.emitFrontEnd",
 167                     "org.graalvm.compiler.phases.BasePhase.dumpAfter",
 168                     "org.graalvm.compiler.replacements.ReplacementsImpl$GraphMaker.makeGraph",
 169                     "org.graalvm.compiler.replacements.SnippetTemplate.instantiate",
 170                     "org.graalvm.compiler.hotspot.SymbolicSnippetEncoder.verifySnippetEncodeDecode"));
 171 
 172     private void verifyParameters(StructuredGraph callerGraph, MethodCallTargetNode debugCallTarget, List<? extends ValueNode> args, ResolvedJavaType stringType, int startArgIdx,
 173                     int varArgsIndex) {
 174         ResolvedJavaMethod verifiedCallee = debugCallTarget.targetMethod();
 175         Integer dumpLevel = null;
 176         int argIdx = startArgIdx;
 177         int varArgsElementIndex = 0;
 178         boolean reportVarArgs = false;
 179         for (int i = 0; i < args.size(); i++) {
 180             ValueNode arg = args.get(i);
 181             if (arg instanceof Invoke) {
 182                 reportVarArgs = varArgsIndex >= 0 && argIdx >= varArgsIndex;
 183                 Invoke invoke = (Invoke) arg;
 184                 CallTargetNode callTarget = invoke.callTarget();
 185                 if (callTarget instanceof MethodCallTargetNode) {
 186                     ResolvedJavaMethod m = ((MethodCallTargetNode) callTarget).targetMethod();
 187                     if (m.getName().equals("toString")) {
 188                         int bci = invoke.bci();
 189                         int nonVarArgIdx = reportVarArgs ? argIdx - varArgsElementIndex : argIdx;
 190                         verifyStringConcat(callerGraph, verifiedCallee, bci, nonVarArgIdx, reportVarArgs ? varArgsElementIndex : -1, m);
 191                         verifyToStringCall(callerGraph, verifiedCallee, stringType, m, bci, nonVarArgIdx, reportVarArgs ? varArgsElementIndex : -1);
 192                     } else if (m.getName().equals("format")) {
 193                         int bci = invoke.bci();
 194                         int nonVarArgIdx = reportVarArgs ? argIdx - varArgsElementIndex : argIdx;
 195                         verifyFormatCall(callerGraph, verifiedCallee, stringType, m, bci, nonVarArgIdx, reportVarArgs ? varArgsElementIndex : -1);
 196 
 197                     }
 198                 }
 199             }
 200             if (i == 1) {
 201                 if (verifiedCallee.getName().equals("dump")) {
 202                     dumpLevel = verifyDumpLevelParameter(callerGraph, debugCallTarget, verifiedCallee, arg);
 203                 }
 204             } else if (i == 2) {
 205                 if (dumpLevel != null) {
 206                     verifyDumpObjectParameter(callerGraph, debugCallTarget, arg, verifiedCallee, dumpLevel);
 207                 }
 208             }
 209             if (varArgsIndex >= 0 && i >= varArgsIndex) {
 210                 varArgsElementIndex++;
 211             }
 212             argIdx++;
 213         }
 214     }
 215 
 216     /**
 217      * The {@code level} arg for the {@code Debug.dump(...)} methods must be a reference to one of
 218      * the {@code Debug.*_LEVEL} constants.
 219      */
 220     protected Integer verifyDumpLevelParameter(StructuredGraph callerGraph, MethodCallTargetNode debugCallTarget, ResolvedJavaMethod verifiedCallee, ValueNode arg)
 221                     throws org.graalvm.compiler.phases.VerifyPhase.VerificationError {
 222         // The 'level' arg for the Debug.dump(...) methods must be a reference to one of
 223         // the Debug.*_LEVEL constants.
 224 
 225         Constant c = arg.asConstant();
 226         if (c != null) {
 227             Integer dumpLevel = ((PrimitiveConstant) c).asInt();
 228             if (!DebugLevels.contains(dumpLevel)) {
 229                 StackTraceElement e = callerGraph.method().asStackTraceElement(debugCallTarget.invoke().bci());
 230                 throw new VerificationError(
 231                                 "In %s: parameter 0 of call to %s does not match a Debug.*_LEVEL constant: %s.%n", e, verifiedCallee.format("%H.%n(%p)"), dumpLevel);
 232             }
 233             return dumpLevel;
 234         }
 235         StackTraceElement e = callerGraph.method().asStackTraceElement(debugCallTarget.invoke().bci());
 236         throw new VerificationError(
 237                         "In %s: parameter 0 of call to %s must be a constant, not %s.%n", e, verifiedCallee.format("%H.%n(%p)"), arg);
 238     }
 239 
 240     protected void verifyDumpObjectParameter(StructuredGraph callerGraph, MethodCallTargetNode debugCallTarget, ValueNode arg, ResolvedJavaMethod verifiedCallee, Integer dumpLevel)
 241                     throws org.graalvm.compiler.phases.VerifyPhase.VerificationError {
 242         ResolvedJavaType argType = ((ObjectStamp) arg.stamp(NodeView.DEFAULT)).type();
 243         if (metaAccess.lookupJavaType(Graph.class).isAssignableFrom(argType)) {
 244             verifyStructuredGraphDumping(callerGraph, debugCallTarget, verifiedCallee, dumpLevel);
 245         }
 246     }
 247 
 248     /**
 249      * Verifies that dumping a {@link StructuredGraph} at level {@link DebugContext#BASIC_LEVEL} or
 250      * {@link DebugContext#INFO_LEVEL} only occurs in white-listed methods.
 251      */
 252     protected void verifyStructuredGraphDumping(StructuredGraph callerGraph, MethodCallTargetNode debugCallTarget, ResolvedJavaMethod verifiedCallee, Integer dumpLevel)
 253                     throws org.graalvm.compiler.phases.VerifyPhase.VerificationError {
 254         if (dumpLevel == DebugContext.BASIC_LEVEL) {
 255             StackTraceElement e = callerGraph.method().asStackTraceElement(debugCallTarget.invoke().bci());
 256             String qualifiedMethod = e.getClassName() + "." + e.getMethodName();
 257             if (!BasicLevelStructuredGraphDumpWhitelist.contains(qualifiedMethod)) {
 258                 throw new VerificationError(
 259                                 "In %s: call to %s with level == DebugContext.BASIC_LEVEL not in %s.BasicLevelDumpWhitelist.%n", e, verifiedCallee.format("%H.%n(%p)"),
 260                                 getClass().getName());
 261             }
 262         } else if (dumpLevel == DebugContext.INFO_LEVEL) {
 263             StackTraceElement e = callerGraph.method().asStackTraceElement(debugCallTarget.invoke().bci());
 264             String qualifiedMethod = e.getClassName() + "." + e.getMethodName();
 265             if (!InfoLevelStructuredGraphDumpWhitelist.contains(qualifiedMethod)) {
 266                 throw new VerificationError(
 267                                 "In %s: call to %s with level == Debug.INFO_LEVEL not in %s.InfoLevelDumpWhitelist.%n", e, verifiedCallee.format("%H.%n(%p)"),
 268                                 getClass().getName());
 269             }
 270         }
 271     }
 272 
 273     /**
 274      * Checks that a given call is not to {@link StringBuffer#toString()} or
 275      * {@link StringBuilder#toString()}.
 276      */
 277     private static void verifyStringConcat(StructuredGraph callerGraph, ResolvedJavaMethod verifiedCallee, int bci, int argIdx, int varArgsElementIndex, ResolvedJavaMethod callee) {
 278         if (callee.getDeclaringClass().getName().equals("Ljava/lang/StringBuilder;") || callee.getDeclaringClass().getName().equals("Ljava/lang/StringBuffer;")) {
 279             StackTraceElement e = callerGraph.method().asStackTraceElement(bci);
 280             if (varArgsElementIndex >= 0) {
 281                 throw new VerificationError(
 282                                 "In %s: element %d of parameter %d of call to %s appears to be a String concatenation expression.%n", e, varArgsElementIndex, argIdx,
 283                                 verifiedCallee.format("%H.%n(%p)"));
 284             } else {
 285                 throw new VerificationError(
 286                                 "In %s: parameter %d of call to %s appears to be a String concatenation expression.", e, argIdx, verifiedCallee.format("%H.%n(%p)"));
 287             }
 288         }
 289     }
 290 
 291     /**
 292      * Checks that a given call is not to {@link Object#toString()}.
 293      */
 294     private static void verifyToStringCall(StructuredGraph callerGraph, ResolvedJavaMethod verifiedCallee, ResolvedJavaType stringType, ResolvedJavaMethod callee, int bci, int argIdx,
 295                     int varArgsElementIndex) {
 296         if (callee.getSignature().getParameterCount(false) == 0 && callee.getSignature().getReturnType(callee.getDeclaringClass()).equals(stringType)) {
 297             StackTraceElement e = callerGraph.method().asStackTraceElement(bci);
 298             if (varArgsElementIndex >= 0) {
 299                 throw new VerificationError(
 300                                 "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.",
 301                                 e, varArgsElementIndex, argIdx, verifiedCallee.format("%H.%n(%p)"));
 302             } else {
 303                 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,
 304                                 verifiedCallee.format("%H.%n(%p)"));
 305             }
 306         }
 307     }
 308 
 309     /**
 310      * Checks that a given call is not to {@link String#format(String, Object...)} or
 311      * {@link String#format(java.util.Locale, String, Object...)}.
 312      */
 313     private static void verifyFormatCall(StructuredGraph callerGraph, ResolvedJavaMethod verifiedCallee, ResolvedJavaType stringType, ResolvedJavaMethod callee, int bci, int argIdx,
 314                     int varArgsElementIndex) {
 315         if (callee.getDeclaringClass().equals(stringType) && callee.getSignature().getReturnType(callee.getDeclaringClass()).equals(stringType)) {
 316             StackTraceElement e = callerGraph.method().asStackTraceElement(bci);
 317             if (varArgsElementIndex >= 0) {
 318                 throw new VerificationError(
 319                                 "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.",
 320                                 e, varArgsElementIndex, argIdx, verifiedCallee.format("%H.%n(%p)"), verifiedCallee.format("%h.%n"));
 321             } else {
 322                 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,
 323                                 argIdx,
 324                                 verifiedCallee.format("%H.%n(%p)"), verifiedCallee.format("%h.%n"));
 325             }
 326         }
 327     }
 328 }