View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   https://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  
20  package org.apache.bcel.verifier;
21  
22  import static org.junit.jupiter.api.Assertions.assertTrue;
23  import static org.junit.jupiter.api.Assertions.fail;
24  
25  import java.io.ByteArrayOutputStream;
26  import java.io.File;
27  import java.io.IOException;
28  import java.util.ArrayList;
29  import java.util.Arrays;
30  import java.util.List;
31  
32  import org.apache.bcel.classfile.JavaClass;
33  import org.apache.commons.exec.CommandLine;
34  import org.apache.commons.exec.DefaultExecuteResultHandler;
35  import org.apache.commons.exec.DefaultExecutor;
36  import org.apache.commons.exec.ExecuteException;
37  import org.apache.commons.exec.ExecuteWatchdog;
38  import org.apache.commons.exec.PumpStreamHandler;
39  import org.apache.commons.lang3.ArrayUtils;
40  import org.apache.commons.lang3.SystemProperties;
41  import org.junit.jupiter.api.Test;
42  
43  /**
44   * Test a number of BCEL issues related to running the Verifier on a bad or malformed .class file and having it die with
45   * an exception rather than report a verification failure.
46   */
47  class VerifyBadClassesTest {
48  
49      private List<String> buildVerifyCommand(final String className, final String testDir) {
50          final List<String> command = new ArrayList<>();
51          command.add("java");
52          command.add("-ea");
53  
54          command.add("-classpath");
55          command.add(SystemProperties.getJavaClassPath() + ":" + testDir);
56  
57          command.add("org.apache.bcel.verifier.Verifier");
58          command.add(className);
59  
60          return command;
61      }
62  
63      /**
64       * Runs the given command synchronously in the given directory. If the command completes normally, returns a
65       * {@link Status} object capturing the command, exit status, and output from the process.
66       *
67       * @param command The command to be run in the process.
68       * @return A String capturing the error output of executing the command.
69       * @throws ExecuteException Thrown if executor fails
70       * @throws IOException Thrown if executor fails
71       */
72      private String run(final List<String> command) throws ExecuteException, IOException {
73  
74          /** The process timeout in milliseconds. Defaults to 30 seconds. */
75          final long timeout = 30 * 1000;
76  
77          final String[] args = command.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
78          final CommandLine cmdLine = new CommandLine(args[0]); // constructor requires executable name
79          cmdLine.addArguments(Arrays.copyOfRange(args, 1, args.length));
80  
81          final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
82          final DefaultExecutor executor = new DefaultExecutor();
83  
84          final ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
85          executor.setWatchdog(watchdog);
86  
87          final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
88          final ByteArrayOutputStream errStream = new ByteArrayOutputStream();
89          final PumpStreamHandler streamHandler = new PumpStreamHandler(outStream, errStream);
90          executor.setStreamHandler(streamHandler);
91          executor.execute(cmdLine, resultHandler);
92  
93          int exitValue = -1;
94          try {
95              resultHandler.waitFor();
96              exitValue = resultHandler.getExitValue();
97          } catch (final InterruptedException e) {
98              // Ignore exception, but watchdog.killedProcess() records that the process timed out.
99              Thread.currentThread().interrupt();
100         }
101         final boolean timedOut = executor.isFailure(exitValue) && watchdog.killedProcess();
102         if (timedOut) {
103             return "Command timed out.";
104         }
105 
106         // return "stdout: " + outStream.toString() + "\nstderr: " + errStream.toString();
107         return errStream.toString();
108     }
109 
110     /**
111      * BCEL-303: AssertionViolatedException in Pass 3A Verification of invoke instructions
112      */
113     @Test
114     void testB303() {
115         testVerify("issue303/example", "A");
116     }
117 
118     /**
119      * BCEL-307: ClassFormatException thrown in Pass 3A verification
120      */
121     @Test
122     void testB307() {
123         testVerify("issue307/example", "A");
124     }
125 
126     /**
127      * BCEL-308: NullPointerException in Verifier Pass 3A
128      */
129     @Test
130     void testB308() {
131         testVerify("issue308", "Hello");
132     }
133 
134     /**
135      * BCEL-309: NegativeArraySizeException when Code attribute length is negative
136      */
137     @Test
138     void testB309() {
139         testVerify("issue309", "Hello");
140     }
141 
142     /**
143      * BCEL-310: ArrayIndexOutOfBounds in Verifier Pass 3A
144      */
145     @Test
146     void testB310() {
147         testVerify("issue310", "Hello");
148     }
149 
150     /**
151      * BCEL-311: ClassCastException in Verifier Pass 2
152      */
153     @Test
154     void testB311() {
155         testVerify("issue311", "Hello");
156     }
157 
158     /**
159      * BCEL-312: AssertionViolation: INTERNAL ERROR Please adapt StringRepresentation to deal with ConstantPackage in
160      * Verifier Pass 2
161      */
162     @Test
163     void testB312() {
164         testVerify("issue312", "Hello");
165     }
166 
167     /**
168      * BCEL-313: ClassFormatException: Invalid signature: Ljava/lang/String)V in Verifier Pass 3A
169      */
170     @Test
171     void testB313() {
172         testVerify("issue313", "Hello");
173     }
174 
175     /**
176      * BCEL-337: StringIndexOutOfBounds in Pass 2 Verification of empty method names in the constant pool
177      */
178     @Test
179     void testB337() {
180         testVerify("issue337/example", "A");
181     }
182 
183     /**
184      * Note that the test classes are bad or malformed and this causes the animal-sniffer-maven-plugin to fail during the
185      * build/verification process. I was not able to figure out the right incantations to get it to ignore these files.
186      * Hence, their file extension is '.classx' to avoid this problem. As part of the test process we rename them to
187      * '.class' and then back to '.classx' after the test. If we can get animal-sniffer to ignore the files, these steps
188      * could be omitted.
189      */
190     private void testVerify(final String directory, final String className) {
191         final String baseDir = "target/test-classes";
192         final String testDir = baseDir + (directory.isEmpty() ? "" : File.separator + directory);
193 
194         final File origFile = new File(testDir, className + ".classx");
195         final File testFile = new File(testDir, className + JavaClass.EXTENSION);
196 
197         if (!origFile.renameTo(testFile)) {
198             fail("Failed to rename original file");
199         }
200 
201         String result;
202         try {
203             result = run(buildVerifyCommand(className, testDir));
204         } catch (final Exception e) {
205             result = e.getMessage();
206         }
207 
208         if (!testFile.renameTo(origFile)) {
209             fail("Failed to rename test file");
210         }
211 
212         assertTrue(result.isEmpty(), result);
213     }
214 }