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  package org.apache.bcel.util;
20  
21  import java.io.File;
22  import java.io.FileNotFoundException;
23  import java.io.IOException;
24  import java.io.PrintWriter;
25  import java.io.UnsupportedEncodingException;
26  import java.nio.charset.Charset;
27  import java.nio.charset.StandardCharsets;
28  import java.util.HashSet;
29  import java.util.Set;
30  
31  import org.apache.bcel.Const;
32  import org.apache.bcel.Constants;
33  import org.apache.bcel.classfile.Attribute;
34  import org.apache.bcel.classfile.ClassParser;
35  import org.apache.bcel.classfile.ConstantPool;
36  import org.apache.bcel.classfile.JavaClass;
37  import org.apache.bcel.classfile.Method;
38  import org.apache.bcel.classfile.Utility;
39  
40  /**
41   * Read class file(s) and convert them into HTML files.
42   *
43   * Given a JavaClass object "class" that is in package "package" five files will be created in the specified directory.
44   *
45   * <OL>
46   * <LI>"package"."class".html as the main file which defines the frames for the following subfiles.
47   * <LI>"package"."class"_attributes.html contains all (known) attributes found in the file
48   * <LI>"package"."class"_cp.html contains the constant pool
49   * <LI>"package"."class"_code.html contains the byte code
50   * <LI>"package"."class"_methods.html contains references to all methods and fields of the class
51   * </OL>
52   *
53   * All subfiles reference each other appropriately, for example clicking on a method in the Method's frame will jump to the
54   * appropriate method in the Code frame.
55   */
56  public class Class2HTML implements Constants {
57  
58      private static String classPackage; // name of package, unclean to make it static, but ...
59      private static String className; // name of current class, dito
60      private static ConstantPool constantPool;
61      private static final Set<String> basicTypes = new HashSet<>();
62      static {
63          basicTypes.add("int");
64          basicTypes.add("short");
65          basicTypes.add("boolean");
66          basicTypes.add("void");
67          basicTypes.add("char");
68          basicTypes.add("byte");
69          basicTypes.add("long");
70          basicTypes.add("double");
71          basicTypes.add("float");
72      }
73  
74      /**
75       * The class name comes from the attacker-controlled this_class constant of the parsed class file and is
76       * concatenated into the five output file paths ("dir + className + suffix"). Class file parsing only folds
77       * '/' into '.', so Windows separators ('\\'), drive designators (':') and ".." segments survive and would
78       * let a crafted class file write its HTML output outside the target directory (CWE-22).
79       *
80       * @param name the class name about to be used as part of a file name.
81       * @throws IOException Thrown if the name contains a path separator, a Windows-reserved file name character, a
82       *         control character, or a ".." sequence.
83       */
84      private static void checkFileNameSafe(final String name) throws IOException {
85          for (int i = 0; i < name.length(); i++) {
86              final char c = name.charAt(i);
87              if (c < ' ' || "\\/:*?\"<>|".indexOf(c) >= 0) {
88                  throw new IOException("Refusing to write HTML for a class whose name contains the unsafe character (0x"
89                      + Integer.toHexString(c) + "): " + name);
90              }
91          }
92          if (name.contains("..")) {
93              throw new IOException("Refusing to write HTML for a class whose name contains \"..\": " + name);
94          }
95      }
96  
97      /**
98       * Main program to convert class files to HTML.
99       *
100      * @param argv command line arguments.
101      * @throws IOException Thrown if an I/O error occurs.
102      */
103     public static void main(final String[] argv) throws IOException {
104         final String[] fileName = new String[argv.length];
105         int files = 0;
106         ClassParser parser = null;
107         JavaClass javaClass = null;
108         String zipFile = null;
109         final char sep = File.separatorChar;
110         String dir = "." + sep; // Where to store HTML files
111         /*
112          * Parse command line arguments.
113          */
114         for (int i = 0; i < argv.length; i++) {
115             if (argv[i].charAt(0) == '-') { // command line switch
116                 if (argv[i].equals("-d")) { // Specify target directory, default '.'
117                     dir = argv[++i];
118                     if (!dir.endsWith("" + sep)) {
119                         dir += sep;
120                     }
121                     final File store = new File(dir);
122                     if (!store.isDirectory()) {
123                         final boolean created = store.mkdirs(); // Create target directory if necessary
124                         if (!created && !store.isDirectory()) {
125                             System.out.println("Tried to create the directory " + dir + " but failed");
126                         }
127                     }
128                 } else if (argv[i].equals("-zip")) {
129                     zipFile = argv[++i];
130                 } else {
131                     System.out.println("Unknown option " + argv[i]);
132                 }
133             } else {
134                 fileName[files++] = argv[i];
135             }
136         }
137         if (files == 0) {
138             System.err.println("Class2HTML: No input files specified.");
139         } else { // Loop through files ...
140             for (int i = 0; i < files; i++) {
141                 System.out.print("Processing " + fileName[i] + "...");
142                 if (zipFile == null) {
143                     parser = new ClassParser(fileName[i]); // Create parser object from file
144                 } else {
145                     parser = new ClassParser(zipFile, fileName[i]); // Create parser object from ZIP file
146                 }
147                 javaClass = parser.parse();
148                 new Class2HTML(javaClass, dir);
149                 System.out.println("Done.");
150             }
151         }
152     }
153 
154     /**
155      * Utility method that converts a class reference in the constant pool, that is, an index to a string.
156      */
157     static String referenceClass(final int index) {
158         String str = constantPool.getConstantString(index, Const.CONSTANT_Class);
159         str = Utility.compactClassName(str);
160         str = Utility.compactClassName(str, classPackage + ".", true);
161         return "<A HREF=\"" + className + "_cp.html#cp" + index + "\" TARGET=ConstantPool>" + toHTML(str) + "</A>";
162     }
163 
164     static String referenceType(final String type) {
165         String shortType = Utility.compactClassName(type);
166         shortType = Utility.compactClassName(shortType, classPackage + ".", true);
167         final int index = type.indexOf('['); // Type is an array?
168         String baseType = type;
169         if (index > -1) {
170             baseType = type.substring(0, index); // Tack of the '['
171         }
172         // test for basic type
173         if (basicTypes.contains(baseType)) {
174             return "<FONT COLOR=\"#00FF00\">" + type + "</FONT>";
175         }
176         return "<A HREF=\"" + toHTMLRef(baseType) + ".html\" TARGET=_top>" + toHTML(shortType) + "</A>";
177     }
178 
179     static String toHTML(final String str) {
180         final StringBuilder buf = new StringBuilder();
181         for (int i = 0; i < str.length(); i++) {
182             final char ch;
183             switch (ch = str.charAt(i)) {
184             case '&':
185                 buf.append("&amp;");
186                 break;
187             case '<':
188                 buf.append("&lt;");
189                 break;
190             case '>':
191                 buf.append("&gt;");
192                 break;
193             case '"':
194                 buf.append("&quot;");
195                 break;
196             case '\'':
197                 buf.append("&#39;");
198                 break;
199             case '\n':
200                 buf.append("\\n");
201                 break;
202             case '\r':
203                 buf.append("\\r");
204                 break;
205             default:
206                 buf.append(ch);
207             }
208         }
209         return buf.toString();
210     }
211 
212     /**
213      * Escapes a class or type name taken from the constant pool for use as a relative link target inside an HREF
214      * attribute value. On top of the text escaping done by {@code toHTML(String)}, any ':' is replaced so an
215      * attacker-chosen name cannot smuggle a URL scheme such as "javascript:" into the generated link.
216      */
217     static String toHTMLRef(final String str) {
218         return toHTML(str.replace(':', '_'));
219     }
220 
221     private final JavaClass javaClass; // current class object
222 
223     private final String dir;
224 
225     /**
226      * Writes contents of the given JavaClass into HTML files.
227      *
228      * @param javaClass The class to write.
229      * @param dir The directory to put the files in.
230      * @throws IOException Thrown when an I/O exception of some sort has occurred.
231      */
232     public Class2HTML(final JavaClass javaClass, final String dir) throws IOException {
233         this(javaClass, dir, StandardCharsets.UTF_8);
234     }
235 
236     private Class2HTML(final JavaClass javaClass, final String dir, final Charset charset) throws IOException {
237         final Method[] methods = javaClass.getMethods();
238         this.javaClass = javaClass;
239         this.dir = dir;
240         className = javaClass.getClassName(); // Remember full name
241         checkFileNameSafe(className);
242         constantPool = javaClass.getConstantPool();
243         // Get package name by tacking off everything after the last '.'
244         final int index = className.lastIndexOf('.');
245         if (index > -1) {
246             classPackage = className.substring(0, index);
247         } else {
248             classPackage = ""; // default package
249         }
250         final ConstantHTML constantHtml = new ConstantHTML(dir, className, classPackage, methods, constantPool, charset);
251         /*
252          * Attributes can't be written in one step, so we just open a file which will be written consequently.
253          */
254         try (AttributeHTML attributeHtml = new AttributeHTML(dir, className, constantPool, constantHtml, charset)) {
255             new MethodHTML(dir, className, methods, javaClass.getFields(), constantHtml, attributeHtml, charset);
256             // Write main file (with frames, yuk)
257             writeMainHTML(attributeHtml, charset);
258             new CodeHTML(dir, className, methods, constantPool, constantHtml, charset);
259         }
260     }
261 
262     private void writeMainHTML(final AttributeHTML attributeHtml, final Charset charset) throws FileNotFoundException, UnsupportedEncodingException {
263         try (PrintWriter file = new PrintWriter(dir + className + ".html", charset.name())) {
264             // @formatter:off
265             file.println("<HTML>\n"
266                 + "<HEAD><TITLE>Documentation for " + toHTML(className) + "</TITLE></HEAD>\n"
267                 + "<FRAMESET BORDER=1 cols=\"30%,*\">\n"
268                 + "<FRAMESET BORDER=1 rows=\"80%,*\">\n"
269                 + "<FRAME NAME=\"ConstantPool\" SRC=\"" + className + "_cp.html" + "\"\n"
270                 + "MARGINWIDTH=\"0\" "
271                 + "MARGINHEIGHT=\"0\" FRAMEBORDER=\"1\" SCROLLING=\"AUTO\">\n"
272                 + "<FRAME NAME=\"Attributes\" SRC=\"" + className + "_attributes.html\"\n"
273                 + " MARGINWIDTH=\"0\" MARGINHEIGHT=\"0\" FRAMEBORDER=\"1\" SCROLLING=\"AUTO\">\n"
274                 + "</FRAMESET>\n"
275                 + "<FRAMESET BORDER=1 rows=\"80%,*\">\n"
276                 + "<FRAME NAME=\"Code\" SRC=\"" + className + "_code.html\"\n"
277                 + " MARGINWIDTH=0 "
278                 + "MARGINHEIGHT=0 FRAMEBORDER=1 SCROLLING=\"AUTO\">\n"
279                 + "<FRAME NAME=\"Methods\" SRC=\"" + className + "_methods.html\"\n"
280                 + " MARGINWIDTH=0 "
281                 + "MARGINHEIGHT=0 FRAMEBORDER=1 SCROLLING=\"AUTO\">\n"
282                 + "</FRAMESET></FRAMESET></HTML>");
283             // @formatter:on
284         }
285         final Attribute[] attributes = javaClass.getAttributes();
286         for (int i = 0; i < attributes.length; i++) {
287             attributeHtml.writeAttribute(attributes[i], "class" + i);
288         }
289     }
290 }