1 /*
  2  * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved.
  3  * Copyright (c) 2022, 2024 SAP SE. All rights reserved.
  4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  5  *
  6  * This code is free software; you can redistribute it and/or modify it
  7  * under the terms of the GNU General Public License version 2 only, as
  8  * published by the Free Software Foundation.
  9  *
 10  * This code is distributed in the hope that it will be useful, but WITHOUT
 11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 13  * version 2 for more details (a copy is included in the LICENSE file that
 14  * accompanied this code).
 15  *
 16  * You should have received a copy of the GNU General Public License version
 17  * 2 along with this work; if not, write to the Free Software Foundation,
 18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 19  *
 20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 21  * or visit www.oracle.com if you need additional information or have any
 22  * questions.
 23  */
 24 
 25 import jdk.test.lib.process.OutputAnalyzer;
 26 
 27 import java.io.*;
 28 import java.util.*;
 29 import java.util.regex.Pattern;
 30 
 31 public class HsErrFileUtils {
 32 
 33     /**
 34      * Given the output of a java VM that crashed, extract the name of the hs-err file from the output
 35      */
 36     public static String extractHsErrFileNameFromOutput(OutputAnalyzer output) {
 37         output.shouldMatch("# A fatal error has been detected.*");
 38 
 39         // extract hs-err file
 40         String hs_err_file = output.firstMatch("# *(\\S*hs_err_pid\\d+\\.log)", 1);
 41         if (hs_err_file == null) {
 42             throw new RuntimeException("Did not find hs-err file in output.\n");
 43         }
 44 
 45         return hs_err_file;
 46     }
 47 
 48     /**
 49      * Given the output of a java VM that crashed, extract the name of the hs-err file from the output,
 50      * open that file and return its File.
 51      */
 52     public static File openHsErrFileFromOutput(OutputAnalyzer output) {
 53         String name = extractHsErrFileNameFromOutput(output);
 54         File f = new File(name);
 55         if (!f.exists()) {
 56             throw new RuntimeException("Cannot find hs-err file at " + f.getAbsolutePath());
 57         }
 58         return f;
 59     }
 60 
 61     /**
 62      * Given an open hs-err file, read it line by line and check for existence of a set of patterns. Will fail
 63      * if patterns are missing, or if the END marker is missing.
 64      * @param f Input file
 65      * @param patterns An array of patterns that need to match, in that order
 66      * @param verbose If true, the content of the hs-err file is printed while matching. If false, only the matched patterns
 67      *                are printed.
 68      * @throws RuntimeException, {@link IOException}
 69      */
 70     public static void checkHsErrFileContent(File f, Pattern[] patterns, boolean verbose) throws IOException {
 71         checkHsErrFileContent(f, patterns, null, true, verbose, false);
 72     }
 73 
 74     /**
 75      * Given an open hs-err file, read it line by line and check for various conditions.
 76      * @param f input file
 77      * @param positivePatterns Optional array of patterns that need to appear, in given order, in the file. Missing
 78      *                        patterns cause the test to fail.
 79      * @param negativePatterns Optional array of patterns that must not appear in the file; test fails if they do.
 80      *                        Order is irrelevant.
 81      * @param checkEndMarker If true, we check for the final "END" in an hs-err file; if it is missing it indicates
 82      *                        that hs-err file printing did not complete successfully.
 83      * @param verbose If true, the content of the hs-err file is printed while matching. If false, only the matched patterns
 84      *                are printed.
 85      * @throws RuntimeException, {@link IOException}
 86      */
 87     public static void checkHsErrFileContent(File f, Pattern[] positivePatterns, Pattern[] negativePatterns, boolean checkEndMarker, boolean verbose) throws IOException {
 88         checkHsErrFileContent(f, positivePatterns, negativePatterns, checkEndMarker, verbose, false);
 89     }
 90 
 91     /**
 92      * Given an open hs-err file, read it line by line and check for existence of a set of patterns. Will fail
 93      * if patterns are missing, or if the END marker is missing.
 94      * @param f Input file
 95      * @param patterns An array of patterns that need to match, in that order
 96      * @param verbose If true, the content of the hs-err file is printed while matching. If false, only the matched patterns
 97      *                are printed.
 98      * @param printHserrOnError If true, the content of the hs-err file is printed in case of a failing check
 99      * @throws RuntimeException, {@link IOException}
100      */
101     public static void checkHsErrFileContent(File f, Pattern[] patterns, boolean verbose, boolean printHserrOnError) throws IOException {
102         checkHsErrFileContent(f, patterns, null, true, verbose, printHserrOnError);
103     }
104 
105     /**
106      * Given an open hs-err file, read it line by line and check for various conditions.
107      * @param f input file
108      * @param positivePatterns Optional array of patterns that need to appear, in given order, in the file. Missing
109      *                        patterns cause the test to fail.
110      * @param negativePatterns Optional array of patterns that must not appear in the file; test fails if they do.
111      *                        Order is irrelevant.
112      * @param checkEndMarker If true, we check for the final "END" in an hs-err file; if it is missing it indicates
113      *                        that hs-err file printing did not complete successfully.
114      * @param verbose If true, the content of the hs-err file is printed while matching. If false, only the matched patterns
115      *                are printed.
116      * @param printHserrOnError If true, the content of the hs-err file is printed in case of a failing check
117      * @throws RuntimeException, {@link IOException}
118      */
119     public static void checkHsErrFileContent(File f, Pattern[] positivePatterns, Pattern[] negativePatterns, boolean checkEndMarker, boolean verbose, boolean printHserrOnError) throws IOException {
120         try (
121                 FileInputStream fis = new FileInputStream(f);
122                 BufferedReader br = new BufferedReader(new InputStreamReader(fis));
123         ) {
124             String line = null;
125             String lastLine = null;
126             int lineNo = 0;
127 
128             Deque<Pattern> positivePatternStack = new ArrayDeque<Pattern>();
129             if (positivePatterns != null) {
130                 Collections.addAll(positivePatternStack, positivePatterns);
131             }
132             Pattern currentPositivePattern = positivePatternStack.pollFirst();
133 
134             while ((line = br.readLine()) != null) {
135                 if (verbose) {
136                     System.out.println(line);
137                 }
138                 if (currentPositivePattern != null) {
139                     if (currentPositivePattern.matcher(line).matches()) {
140                         if (!verbose) {
141                             System.out.println(line);
142                         }
143                         System.out.println("^^^ Matches " + currentPositivePattern + " at line " + lineNo + "^^^");
144                         currentPositivePattern = positivePatternStack.pollFirst();
145                         if (currentPositivePattern == null && negativePatterns == null && checkEndMarker == false) {
146                             System.out.println("Lazily skipping the rest of the hs-err file...");
147                             break; // Shortcut. Nothing to do.
148                         }
149                     }
150                 }
151                 if (negativePatterns != null) {
152                     for (Pattern negativePattern : negativePatterns) {
153                         if (negativePattern.matcher(line).matches()) {
154                             if (!verbose) {
155                                 System.out.println(line);
156                             }
157                             System.out.println("^^^ Forbidden pattern found at line " + lineNo + ": " + negativePattern + "^^^");
158                             if (printHserrOnError) {
159                                 printHsErrFile(f);
160                             }
161                             throw new RuntimeException("Forbidden pattern found at line " + lineNo + ": " + negativePattern);
162                         }
163                     }
164                 }
165                 lastLine = line;
166                 lineNo++;
167             }
168             // If the current pattern is not null then it didn't match
169             if (currentPositivePattern != null) {
170                 if (printHserrOnError) {
171                     printHsErrFile(f);
172                 }
173                 throw new RuntimeException("hs-err file incomplete (first missing pattern: " + currentPositivePattern.pattern() + ")");
174             }
175             if (checkEndMarker && !lastLine.equals("END.")) {
176                 if (printHserrOnError) {
177                     printHsErrFile(f);
178                 }
179                 throw new RuntimeException("hs-err file incomplete (missing END marker.)");
180             }
181             System.out.println("hs-err file " + f.getAbsolutePath() + " scanned successfully.");
182         }
183     }
184 
185     private static void printHsErrFile(File f) throws IOException {
186         try (
187                 FileInputStream fis = new FileInputStream(f);
188                 BufferedReader br = new BufferedReader(new InputStreamReader(fis));
189         ) {
190             String line;
191             System.out.println("------------------------ hs-err file ------------------------");
192             while ((line = br.readLine()) != null) {
193                 System.out.println(line);
194             }
195             System.out.println("-------------------------------------------------------------");
196         }
197     }
198 
199 }