1 /* 2 * Copyright (c) 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 import static java.io.File.createTempFile; 25 import static java.lang.Long.parseLong; 26 import static java.lang.System.getProperty; 27 import static java.nio.file.Files.readAllBytes; 28 import static java.util.Arrays.stream; 29 import static java.util.Collections.emptyList; 30 import static java.util.stream.Collectors.joining; 31 import static java.util.stream.Collectors.toList; 32 import static jdk.test.lib.process.ProcessTools.createJavaProcessBuilder; 33 34 import java.io.BufferedReader; 35 import java.io.File; 36 import java.io.FileNotFoundException; 37 import java.io.FileOutputStream; 38 import java.io.IOException; 39 import java.io.InputStreamReader; 40 import java.util.Collection; 41 import java.util.Optional; 42 import java.util.stream.Stream; 43 44 /* 45 * @test TestInheritFD 46 * @bug 8176717 8176809 47 * @summary a new process should not inherit open file descriptors 48 * @library /test/lib 49 * @modules java.base/jdk.internal.misc 50 * java.management 51 */ 52 53 /** 54 * Test that HotSpot does not leak logging file descriptors. 55 * 56 * This test is performed in three steps. The first VM starts a second VM with 57 * gc logging enabled. The second VM starts a third VM and redirects the third 58 * VMs output to the first VM, it then exits and hopefully closes its log file. 59 * 60 * The third VM waits for the second to exit and close its log file. After that, 61 * the third VM tries to rename the log file of the second VM. If it succeeds in 62 * doing so it means that the third VM did not inherit the open log file 63 * (windows can not rename opened files easily) 64 * 65 * The third VM communicates the success to rename the file by printing "CLOSED 66 * FD". The first VM checks that the string was printed by the third VM. 67 * 68 * On unix like systems "lsof" or "pfiles" is used. 69 */ 70 71 public class TestInheritFD { 72 73 public static final String LEAKS_FD = "VM RESULT => LEAKS FD"; 74 public static final String RETAINS_FD = "VM RESULT => RETAINS FD"; 75 public static final String EXIT = "VM RESULT => VM EXIT"; 76 public static final String LOG_SUFFIX = ".strangelogsuffixthatcanbecheckedfor"; 77 78 // first VM 79 public static void main(String[] args) throws Exception { 80 String logPath = createTempFile("logging", LOG_SUFFIX).getName(); 81 File commFile = createTempFile("communication", ".txt"); 82 83 ProcessBuilder pb = createJavaProcessBuilder( 84 "-Xlog:gc:\"" + logPath + "\"", 85 "-Dtest.jdk=" + getProperty("test.jdk"), 86 VMStartedWithLogging.class.getName(), 87 logPath); 88 89 pb.redirectOutput(commFile); // use temp file to communicate between processes 90 pb.start(); 91 92 String out = ""; 93 do { 94 out = new String(readAllBytes(commFile.toPath())); 95 Thread.sleep(100); 96 System.out.println("SLEEP 100 millis"); 97 } while (!out.contains(EXIT)); 98 99 System.out.println(out); 100 if (out.contains(RETAINS_FD)) { 101 System.out.println("Log file was not inherited by third VM"); 102 } else { 103 throw new RuntimeException("could not match: " + RETAINS_FD); 104 } 105 } 106 107 static class VMStartedWithLogging { 108 // second VM 109 public static void main(String[] args) throws IOException, InterruptedException { 110 ProcessBuilder pb = createJavaProcessBuilder( 111 "-Dtest.jdk=" + getProperty("test.jdk"), 112 VMShouldNotInheritFileDescriptors.class.getName(), 113 args[0], 114 "" + ProcessHandle.current().pid()); 115 pb.inheritIO(); // in future, redirect information from third VM to first VM 116 pb.start(); 117 118 if (getProperty("os.name").toLowerCase().contains("win") == false) { 119 System.out.println("(Second VM) Open file descriptors:\n" + outputContainingFilenames().stream().collect(joining("\n"))); 120 } 121 } 122 } 123 124 static class VMShouldNotInheritFileDescriptors { 125 // third VM 126 public static void main(String[] args) throws InterruptedException { 127 try { 128 File logFile = new File(args[0]); 129 long parentPid = parseLong(args[1]); 130 fakeLeakyJVM(false); // for debugging of test case 131 132 if (getProperty("os.name").toLowerCase().contains("win")) { 133 windows(logFile, parentPid); 134 } else { 135 Collection<String> output = outputContainingFilenames(); 136 System.out.println("(Third VM) Open file descriptors:\n" + output.stream().collect(joining("\n"))); 137 System.out.println(findOpenLogFile(output) ? LEAKS_FD : RETAINS_FD); 138 } 139 } catch (Exception e) { 140 System.out.println(e.toString()); 141 } finally { 142 System.out.println(EXIT); 143 } 144 } 145 } 146 147 // for debugging of test case 148 @SuppressWarnings("resource") 149 static void fakeLeakyJVM(boolean fake) { 150 if (fake) { 151 try { 152 new FileOutputStream("fakeLeakyJVM" + LOG_SUFFIX, false); 153 } catch (FileNotFoundException e) { 154 } 155 } 156 } 157 158 static Stream<String> run(String... args){ 159 try { 160 return new BufferedReader(new InputStreamReader(new ProcessBuilder(args).start().getInputStream())).lines(); 161 } catch (IOException e) { 162 throw new RuntimeException(e); 163 } 164 } 165 166 static Collection<String> outputContainingFilenames() { 167 long pid = ProcessHandle.current().pid(); 168 Optional<String[]> command = stream(new String[][]{ 169 {"/usr/bin/lsof", "-p"}, 170 {"/usr/sbin/lsof", "-p"}, 171 {"/bin/lsof", "-p"}, 172 {"/sbin/lsof", "-p"}, 173 {"/usr/local/bin/lsof", "-p"}, 174 {"/usr/bin/pfiles", "-F"}}) // Solaris 175 .filter(args -> new File(args[0]).exists()) 176 .findFirst(); 177 178 System.out.println("using command: " + command.map((c) -> c[0] + " " + c[1]).orElse("<not found>")); 179 // if command can not be found return list without log file (some machines does not have "lsof" in the expected place) 180 return command.map(c -> run(c[0], c[1], "" + pid).collect(toList())).orElse(emptyList()); 181 } 182 183 static boolean findOpenLogFile(Collection<String> fileNames) { 184 return fileNames.stream() 185 .filter(fileName -> fileName.contains(LOG_SUFFIX)) 186 .findAny() 187 .isPresent(); 188 } 189 190 static void windows(File f, long parentPid) throws InterruptedException { 191 System.out.println("waiting for pid: " + parentPid); 192 ProcessHandle.of(parentPid).ifPresent(handle -> handle.onExit().join()); 193 System.out.println("trying to rename file to the same name: " + f); 194 System.out.println(f.renameTo(f) ? RETAINS_FD : LEAKS_FD); // this parts communicates a closed file descriptor by printing "VM RESULT => RETAINS FD" 195 }