1 /*
   2  * Copyright (c) 2015, 2019, 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.hotspot;
  26 
  27 import static org.graalvm.compiler.hotspot.HotSpotGraalOptionValues.GRAAL_OPTION_PROPERTY_PREFIX;
  28 import static org.graalvm.compiler.hotspot.HotSpotGraalOptionValues.defaultOptions;
  29 
  30 import java.io.FileNotFoundException;
  31 import java.io.FileOutputStream;
  32 import java.io.IOException;
  33 import java.io.OutputStream;
  34 import java.io.PrintStream;
  35 import java.util.List;
  36 
  37 import org.graalvm.compiler.core.common.SuppressFBWarnings;
  38 import org.graalvm.compiler.debug.TTYStreamProvider;
  39 import org.graalvm.compiler.options.Option;
  40 import org.graalvm.compiler.options.OptionKey;
  41 import org.graalvm.compiler.options.OptionType;
  42 import org.graalvm.compiler.serviceprovider.GraalServices;
  43 import org.graalvm.compiler.serviceprovider.ServiceProvider;
  44 
  45 import jdk.vm.ci.common.NativeImageReinitialize;
  46 import jdk.vm.ci.hotspot.HotSpotJVMCIRuntime;
  47 import jdk.vm.ci.services.Services;
  48 
  49 @ServiceProvider(TTYStreamProvider.class)
  50 public class HotSpotTTYStreamProvider implements TTYStreamProvider {
  51 
  52     public static class Options {
  53 
  54         // @formatter:off
  55         @Option(help = "File to which logging is sent.  A %p in the name will be replaced with a string identifying " +
  56                        "the process, usually the process id and %t will be replaced by System.currentTimeMillis().", type = OptionType.Expert)
  57         public static final LogStreamOptionKey LogFile = new LogStreamOptionKey();
  58         // @formatter:on
  59     }
  60 
  61     @Override
  62     public PrintStream getStream() {
  63         return Options.LogFile.getStream();
  64     }
  65 
  66     /**
  67      * An option for a configurable file name that can also open a {@link PrintStream} on the file.
  68      * If no value is given for the option, the stream will output to HotSpot's
  69      * {@link HotSpotJVMCIRuntime#getLogStream() log} stream
  70      */
  71     private static class LogStreamOptionKey extends OptionKey<String> {
  72 
  73         LogStreamOptionKey() {
  74             super(null);
  75         }
  76 
  77         /**
  78          * @return {@code nameTemplate} with all instances of %p replaced by
  79          *         {@link GraalServices#getExecutionID()} and %t by
  80          *         {@link System#currentTimeMillis()}
  81          */
  82         private static String makeFilename(String nameTemplate) {
  83             String name = nameTemplate;
  84             if (name.contains("%p")) {
  85                 name = name.replaceAll("%p", GraalServices.getExecutionID());
  86             }
  87             if (name.contains("%t")) {
  88                 name = name.replaceAll("%t", String.valueOf(System.currentTimeMillis()));
  89             }
  90             return name;
  91         }
  92 
  93         /**
  94          * An output stream that redirects to {@link HotSpotJVMCIRuntime#getLogStream()}. The
  95          * {@link HotSpotJVMCIRuntime#getLogStream()} value is only accessed the first time an IO
  96          * operation is performed on the stream. This is required to break a deadlock in early JVMCI
  97          * initialization.
  98          */
  99         class DelayedOutputStream extends OutputStream {
 100             @NativeImageReinitialize private volatile OutputStream lazy;
 101 
 102             private OutputStream lazy() {
 103                 if (lazy == null) {
 104                     synchronized (this) {
 105                         if (lazy == null) {
 106                             String nameTemplate = LogStreamOptionKey.this.getValue(defaultOptions());
 107                             if (nameTemplate != null) {
 108                                 String name = makeFilename(nameTemplate);
 109                                 try {
 110                                     final boolean enableAutoflush = true;
 111                                     FileOutputStream result = new FileOutputStream(name);
 112                                     if (!Services.IS_IN_NATIVE_IMAGE) {
 113                                         printVMConfig(enableAutoflush, result);
 114                                     } else {
 115                                         // There are no VM arguments for the libgraal library.
 116                                     }
 117                                     lazy = result;
 118                                     return lazy;
 119                                 } catch (FileNotFoundException e) {
 120                                     throw new RuntimeException("couldn't open file: " + name, e);
 121                                 }
 122                             }
 123 
 124                             lazy = HotSpotJVMCIRuntime.runtime().getLogStream();
 125                             PrintStream ps = new PrintStream(lazy);
 126                             ps.printf("[Use -D%sLogFile=<path> to redirect Graal log output to a file.]%n", GRAAL_OPTION_PROPERTY_PREFIX);
 127                             ps.flush();
 128                         }
 129                     }
 130                 }
 131                 return lazy;
 132             }
 133 
 134             @SuppressFBWarnings(value = "DLS_DEAD_LOCAL_STORE", justification = "false positive on dead store to `ps`")
 135             private void printVMConfig(final boolean enableAutoflush, FileOutputStream result) {
 136                 /*
 137                  * Add the JVM and Java arguments to the log file to help identity it.
 138                  */
 139                 PrintStream ps = new PrintStream(result, enableAutoflush);
 140                 List<String> inputArguments = GraalServices.getInputArguments();
 141                 if (inputArguments != null) {
 142                     ps.println("VM Arguments: " + String.join(" ", inputArguments));
 143                 }
 144                 String cmd = Services.getSavedProperties().get("sun.java.command");
 145                 if (cmd != null) {
 146                     ps.println("sun.java.command=" + cmd);
 147                 }
 148             }
 149 
 150             @Override
 151             public void write(byte[] b, int off, int len) throws IOException {
 152                 lazy().write(b, off, len);
 153             }
 154 
 155             @Override
 156             public void write(int b) throws IOException {
 157                 lazy().write(b);
 158             }
 159 
 160             @Override
 161             public void flush() throws IOException {
 162                 lazy().flush();
 163             }
 164 
 165             @Override
 166             public void close() throws IOException {
 167                 lazy().close();
 168             }
 169         }
 170 
 171         /**
 172          * Gets the print stream configured by this option. If no file is configured, the print
 173          * stream will output to HotSpot's {@link HotSpotJVMCIRuntime#getLogStream() log} stream.
 174          */
 175         public PrintStream getStream() {
 176             return new PrintStream(new DelayedOutputStream());
 177         }
 178     }
 179 
 180 }