001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *   https://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.apache.bcel.util;
020
021import java.io.File;
022import java.io.FileNotFoundException;
023import java.io.IOException;
024import java.io.PrintWriter;
025import java.io.UnsupportedEncodingException;
026import java.nio.charset.Charset;
027import java.nio.charset.StandardCharsets;
028import java.util.HashSet;
029import java.util.Set;
030
031import org.apache.bcel.Const;
032import org.apache.bcel.Constants;
033import org.apache.bcel.classfile.Attribute;
034import org.apache.bcel.classfile.ClassParser;
035import org.apache.bcel.classfile.ConstantPool;
036import org.apache.bcel.classfile.JavaClass;
037import org.apache.bcel.classfile.Method;
038import org.apache.bcel.classfile.Utility;
039
040/**
041 * Read class file(s) and convert them into HTML files.
042 *
043 * Given a JavaClass object "class" that is in package "package" five files will be created in the specified directory.
044 *
045 * <OL>
046 * <LI>"package"."class".html as the main file which defines the frames for the following subfiles.
047 * <LI>"package"."class"_attributes.html contains all (known) attributes found in the file
048 * <LI>"package"."class"_cp.html contains the constant pool
049 * <LI>"package"."class"_code.html contains the byte code
050 * <LI>"package"."class"_methods.html contains references to all methods and fields of the class
051 * </OL>
052 *
053 * All subfiles reference each other appropriately, for example clicking on a method in the Method's frame will jump to the
054 * appropriate method in the Code frame.
055 */
056public class Class2HTML implements Constants {
057
058    private static String classPackage; // name of package, unclean to make it static, but ...
059    private static String className; // name of current class, dito
060    private static ConstantPool constantPool;
061    private static final Set<String> basicTypes = new HashSet<>();
062    static {
063        basicTypes.add("int");
064        basicTypes.add("short");
065        basicTypes.add("boolean");
066        basicTypes.add("void");
067        basicTypes.add("char");
068        basicTypes.add("byte");
069        basicTypes.add("long");
070        basicTypes.add("double");
071        basicTypes.add("float");
072    }
073
074    /**
075     * The class name comes from the attacker-controlled this_class constant of the parsed class file and is
076     * concatenated into the five output file paths ("dir + className + suffix"). Class file parsing only folds
077     * '/' into '.', so Windows separators ('\\'), drive designators (':') and ".." segments survive and would
078     * let a crafted class file write its HTML output outside the target directory (CWE-22).
079     *
080     * @param name the class name about to be used as part of a file name.
081     * @throws IOException Thrown if the name contains a path separator, a Windows-reserved file name character, a
082     *         control character, or a ".." sequence.
083     */
084    private static void checkFileNameSafe(final String name) throws IOException {
085        for (int i = 0; i < name.length(); i++) {
086            final char c = name.charAt(i);
087            if (c < ' ' || "\\/:*?\"<>|".indexOf(c) >= 0) {
088                throw new IOException("Refusing to write HTML for a class whose name contains the unsafe character (0x"
089                    + Integer.toHexString(c) + "): " + name);
090            }
091        }
092        if (name.contains("..")) {
093            throw new IOException("Refusing to write HTML for a class whose name contains \"..\": " + name);
094        }
095    }
096
097    /**
098     * Main program to convert class files to HTML.
099     *
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}