1 /*
   2  * Copyright (c) 2011, 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.printer;
  24 
  25 import static org.graalvm.compiler.debug.DebugConfig.asJavaMethod;
  26 
  27 import java.io.IOException;
  28 import java.nio.channels.ClosedByInterruptException;
  29 import java.util.ArrayList;
  30 import java.util.Arrays;
  31 import java.util.Collections;
  32 import java.util.Date;
  33 import java.util.HashMap;
  34 import java.util.List;
  35 import java.util.Map;
  36 import java.util.WeakHashMap;
  37 
  38 import org.graalvm.compiler.debug.DebugContext;
  39 import org.graalvm.compiler.debug.DebugDumpHandler;
  40 import org.graalvm.compiler.debug.DebugDumpScope;
  41 import org.graalvm.compiler.debug.DebugOptions;
  42 import org.graalvm.compiler.debug.GraalError;
  43 import org.graalvm.compiler.debug.TTY;
  44 import org.graalvm.compiler.graph.Graph;
  45 import org.graalvm.compiler.nodes.StructuredGraph;
  46 import org.graalvm.compiler.options.OptionValues;
  47 import org.graalvm.compiler.phases.contract.NodeCostUtil;
  48 
  49 import jdk.vm.ci.meta.JavaMethod;
  50 import jdk.vm.ci.meta.ResolvedJavaMethod;
  51 
  52 //JaCoCo Exclude
  53 
  54 /**
  55  * Observes compilation events and uses {@link BinaryGraphPrinter} to generate a graph
  56  * representation that can be inspected with the Graph Visualizer.
  57  */
  58 public class GraphPrinterDumpHandler implements DebugDumpHandler {
  59 
  60     private static final int FAILURE_LIMIT = 8;
  61     private final GraphPrinterSupplier printerSupplier;
  62     protected GraphPrinter printer;
  63     private List<String> previousInlineContext;
  64     private int[] dumpIds = {};
  65     private int failuresCount;
  66     private Map<Graph, List<String>> inlineContextMap;
  67     private final String jvmArguments;
  68     private final String sunJavaCommand;
  69 
  70     @FunctionalInterface
  71     public interface GraphPrinterSupplier {
  72         GraphPrinter get(DebugContext ctx, Graph graph) throws IOException;
  73     }
  74 
  75     /**
  76      * Creates a new {@link GraphPrinterDumpHandler}.
  77      *
  78      * @param printerSupplier Supplier used to create the GraphPrinter. Should supply an optional or
  79      *            null in case of failure.
  80      */
  81     public GraphPrinterDumpHandler(GraphPrinterSupplier printerSupplier) {
  82         this.printerSupplier = printerSupplier;
  83         /* Add the JVM and Java arguments to the graph properties to help identify it. */
  84         this.jvmArguments = jvmArguments();
  85         this.sunJavaCommand = System.getProperty("sun.java.command");
  86     }
  87 
  88     private static String jvmArguments() {
  89         try {
  90             return String.join(" ", java.lang.management.ManagementFactory.getRuntimeMXBean().getInputArguments());
  91         } catch (LinkageError err) {
  92             return "unknown";
  93         }
  94     }
  95 
  96     private void ensureInitialized(DebugContext ctx, Graph graph) {
  97         if (printer == null) {
  98             if (failuresCount >= FAILURE_LIMIT) {
  99                 return;
 100             }
 101             previousInlineContext = new ArrayList<>();
 102             inlineContextMap = new WeakHashMap<>();
 103             DebugContext debug = graph.getDebug();
 104             try {
 105                 printer = printerSupplier.get(ctx, graph);
 106             } catch (IOException e) {
 107                 handleException(debug, e);
 108             }
 109         }
 110     }
 111 
 112     private int nextDumpId() {
 113         int depth = previousInlineContext.size();
 114         if (dumpIds.length < depth) {
 115             dumpIds = Arrays.copyOf(dumpIds, depth);
 116         }
 117         return dumpIds[depth - 1]++;
 118     }
 119 
 120     @Override
 121     @SuppressWarnings("try")
 122     public void dump(DebugContext debug, Object object, final String format, Object... arguments) {
 123         OptionValues options = debug.getOptions();
 124         if (object instanceof Graph && DebugOptions.PrintGraph.getValue(options)) {
 125             final Graph graph = (Graph) object;
 126             ensureInitialized(debug, graph);
 127             if (printer == null) {
 128                 return;
 129             }
 130 
 131             // Get all current JavaMethod instances in the context.
 132             List<String> inlineContext = getInlineContext(graph);
 133 
 134             if (inlineContext != previousInlineContext) {
 135                 Map<Object, Object> properties = new HashMap<>();
 136                 properties.put("graph", graph.toString());
 137                 addCompilationId(properties, graph);
 138                 if (inlineContext.equals(previousInlineContext)) {
 139                     /*
 140                      * two different graphs have the same inline context, so make sure they appear
 141                      * in different folders by closing and reopening the top scope.
 142                      */
 143                     int inlineDepth = previousInlineContext.size() - 1;
 144                     closeScope(debug, inlineDepth);
 145                     openScope(debug, inlineContext.get(inlineDepth), inlineDepth, properties);
 146                 } else {
 147                     // Check for method scopes that must be closed since the previous dump.
 148                     for (int i = 0; i < previousInlineContext.size(); ++i) {
 149                         if (i >= inlineContext.size() || !inlineContext.get(i).equals(previousInlineContext.get(i))) {
 150                             for (int inlineDepth = previousInlineContext.size() - 1; inlineDepth >= i; --inlineDepth) {
 151                                 closeScope(debug, inlineDepth);
 152                             }
 153                             break;
 154                         }
 155                     }
 156                     // Check for method scopes that must be opened since the previous dump.
 157                     for (int i = 0; i < inlineContext.size(); ++i) {
 158                         if (i >= previousInlineContext.size() || !inlineContext.get(i).equals(previousInlineContext.get(i))) {
 159                             for (int inlineDepth = i; inlineDepth < inlineContext.size(); ++inlineDepth) {
 160                                 openScope(debug, inlineContext.get(inlineDepth), inlineDepth, inlineDepth == inlineContext.size() - 1 ? properties : null);
 161                             }
 162                             break;
 163                         }
 164                     }
 165                 }
 166             }
 167 
 168             // Save inline context for next dump.
 169             previousInlineContext = inlineContext;
 170 
 171             // Capture before creating the sandbox
 172             String currentScopeName = debug.getCurrentScopeName();
 173             try (DebugContext.Scope s = debug.sandbox("PrintingGraph", null)) {
 174                 // Finally, output the graph.
 175                 Map<Object, Object> properties = new HashMap<>();
 176                 properties.put("graph", graph.toString());
 177                 properties.put("scope", currentScopeName);
 178                 if (graph instanceof StructuredGraph) {
 179                     properties.put("compilationIdentifier", ((StructuredGraph) graph).compilationId());
 180                     try {
 181                         int size = NodeCostUtil.computeGraphSize((StructuredGraph) graph);
 182                         properties.put("node-cost graph size", size);
 183                     } catch (Throwable t) {
 184                         properties.put("node-cost-exception", t.getMessage());
 185                     }
 186                 }
 187                 printer.print(debug, graph, properties, nextDumpId(), format, arguments);
 188             } catch (IOException e) {
 189                 handleException(debug, e);
 190             } catch (Throwable e) {
 191                 throw debug.handle(e);
 192             }
 193         }
 194     }
 195 
 196     void handleException(DebugContext debug, IOException e) {
 197         if (debug != null && DebugOptions.DumpingErrorsAreFatal.getValue(debug.getOptions())) {
 198             throw new GraalError(e);
 199         }
 200         if (e instanceof ClosedByInterruptException) {
 201             /*
 202              * The current dumping was aborted by an interrupt so treat this as a transient failure.
 203              */
 204             failuresCount = 0;
 205         } else {
 206             failuresCount++;
 207         }
 208         printer = null;
 209         e.printStackTrace(TTY.out);
 210         if (failuresCount > FAILURE_LIMIT) {
 211             TTY.println("Too many failures with dumping. Disabling dump in thread " + Thread.currentThread());
 212         }
 213     }
 214 
 215     private static void addCompilationId(Map<Object, Object> properties, final Graph graph) {
 216         if (graph instanceof StructuredGraph) {
 217             properties.put("compilationId", ((StructuredGraph) graph).compilationId());
 218         }
 219     }
 220 
 221     private List<String> getInlineContext(Graph graph) {
 222         List<String> result = inlineContextMap.get(graph);
 223         if (result == null) {
 224             result = new ArrayList<>();
 225             Object lastMethodOrGraph = null;
 226             boolean graphSeen = false;
 227             DebugContext debug = graph.getDebug();
 228             for (Object o : debug.context()) {
 229                 if (o == graph) {
 230                     graphSeen = true;
 231                 }
 232 
 233                 if (o instanceof DebugDumpScope) {
 234                     DebugDumpScope debugDumpScope = (DebugDumpScope) o;
 235                     if (debugDumpScope.decorator && !result.isEmpty()) {
 236                         result.set(result.size() - 1, debugDumpScope.name + ":" + result.get(result.size() - 1));
 237                     } else {
 238                         result.add(debugDumpScope.name);
 239                     }
 240                 } else {
 241                     addMethodContext(result, o, lastMethodOrGraph);
 242                 }
 243                 if (o instanceof JavaMethod || o instanceof Graph) {
 244                     lastMethodOrGraph = o;
 245                 }
 246             }
 247 
 248             if (result.isEmpty()) {
 249                 result.add(graph.toString());
 250                 graphSeen = true;
 251             }
 252             // Reverse list such that inner method comes after outer method.
 253             Collections.reverse(result);
 254             if (!graphSeen) {
 255                 /*
 256                  * The graph isn't in any context but is being processed within another graph so add
 257                  * it to the end of the scopes.
 258                  */
 259                 if (asJavaMethod(graph) != null) {
 260                     addMethodContext(result, graph, lastMethodOrGraph);
 261                 } else {
 262                     result.add(graph.toString());
 263                 }
 264             }
 265             inlineContextMap.put(graph, result);
 266         }
 267         return result;
 268     }
 269 
 270     private static void addMethodContext(List<String> result, Object o, Object lastMethodOrGraph) {
 271         JavaMethod method = asJavaMethod(o);
 272         if (method != null) {
 273             /*
 274              * Include the current method in the context if there was no previous JavaMethod or
 275              * JavaMethodContext or if the method is different or if the method is the same but it
 276              * comes from two different graphs. This ensures that recursive call patterns are
 277              * handled properly.
 278              */
 279             if (lastMethodOrGraph == null || asJavaMethod(lastMethodOrGraph) == null || !asJavaMethod(lastMethodOrGraph).equals(method) ||
 280                             (lastMethodOrGraph != o && lastMethodOrGraph instanceof Graph && o instanceof Graph)) {
 281                 result.add(method.format("%H.%n(%p)"));
 282             } else {
 283                 /*
 284                  * This prevents multiple adjacent method context objects for the same method from
 285                  * resulting in multiple IGV tree levels. This works on the assumption that real
 286                  * inlining debug scopes will have a graph context object between the inliner and
 287                  * inlinee context objects.
 288                  */
 289             }
 290         }
 291     }
 292 
 293     private void openScope(DebugContext debug, String name, int inlineDepth, Map<Object, Object> properties) {
 294         try {
 295             Map<Object, Object> props = properties;
 296             if (inlineDepth == 0) {
 297                 /* Include some VM specific properties at the root. */
 298                 if (props == null) {
 299                     props = new HashMap<>();
 300                 }
 301                 props.put("jvmArguments", jvmArguments);
 302                 if (sunJavaCommand != null) {
 303                     props.put("sun.java.command", sunJavaCommand);
 304                 }
 305                 props.put("date", new Date().toString());
 306             }
 307             printer.beginGroup(debug, name, name, debug.contextLookup(ResolvedJavaMethod.class), -1, props);
 308         } catch (IOException e) {
 309             handleException(debug, e);
 310         }
 311     }
 312 
 313     private void closeScope(DebugContext debug, int inlineDepth) {
 314         dumpIds[inlineDepth] = 0;
 315         try {
 316             if (printer != null) {
 317                 printer.endGroup();
 318             }
 319         } catch (IOException e) {
 320             handleException(debug, e);
 321         }
 322     }
 323 
 324     @Override
 325     public void close() {
 326         if (previousInlineContext != null) {
 327             for (int inlineDepth = 0; inlineDepth < previousInlineContext.size(); inlineDepth++) {
 328                 closeScope(null, inlineDepth);
 329             }
 330         }
 331         if (printer != null) {
 332             printer.close();
 333             printer = null;
 334         }
 335     }
 336 }