ClassWriter.java 20.4 KB
Newer Older
1
/*
X
xdono 已提交
2
 * Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Sun designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Sun in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
 * CA 95054 USA or visit www.sun.com if you need additional information or
 * have any questions.
 */

package com.sun.tools.javap;

28
import java.net.URI;
29
import java.text.DateFormat;
30
import java.util.Collection;
31
import java.util.Date;
32 33 34 35 36 37 38 39 40
import java.util.List;

import com.sun.tools.classfile.AccessFlags;
import com.sun.tools.classfile.Attribute;
import com.sun.tools.classfile.Attributes;
import com.sun.tools.classfile.ClassFile;
import com.sun.tools.classfile.Code_attribute;
import com.sun.tools.classfile.ConstantPool;
import com.sun.tools.classfile.ConstantPoolException;
41
import com.sun.tools.classfile.ConstantValue_attribute;
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
import com.sun.tools.classfile.Descriptor;
import com.sun.tools.classfile.DescriptorException;
import com.sun.tools.classfile.Exceptions_attribute;
import com.sun.tools.classfile.Field;
import com.sun.tools.classfile.Method;
import com.sun.tools.classfile.Signature;
import com.sun.tools.classfile.Signature_attribute;
import com.sun.tools.classfile.SourceFile_attribute;
import com.sun.tools.classfile.Type;

import static com.sun.tools.classfile.AccessFlags.*;

/*
 *  The main javap class to write the contents of a class file as text.
 *
 *  <p><b>This is NOT part of any API supported by Sun Microsystems.  If
 *  you write code that depends on this, you do so at your own risk.
 *  This code and its internal interfaces are subject to change or
 *  deletion without notice.</b>
 */
public class ClassWriter extends BasicWriter {
    static ClassWriter instance(Context context) {
        ClassWriter instance = context.get(ClassWriter.class);
        if (instance == null)
            instance = new ClassWriter(context);
        return instance;
    }

    protected ClassWriter(Context context) {
        super(context);
        context.put(ClassWriter.class, this);
        options = Options.instance(context);
        attrWriter = AttributeWriter.instance(context);
        codeWriter = CodeWriter.instance(context);
        constantWriter = ConstantWriter.instance(context);
    }

79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
    void setDigest(String name, byte[] digest) {
        this.digestName = name;
        this.digest = digest;
    }

    void setFile(URI uri) {
        this.uri = uri;
    }

    void setFileSize(int size) {
        this.size = size;
    }

    void setLastModified(long lastModified) {
        this.lastModified = lastModified;
    }

96
    protected ClassFile getClassFile() {
97 98 99
        return classFile;
    }

100 101 102 103 104 105
    protected void setClassFile(ClassFile cf) {
        classFile = cf;
        constant_pool = classFile.constant_pool;
    }

    protected Method getMethod() {
106 107 108
        return method;
    }

109 110 111 112
    protected void setMethod(Method m) {
        method = m;
    }

113
    public void write(ClassFile cf) {
114
        setClassFile(cf);
115

116 117 118 119 120 121 122
        if ((options.sysInfo || options.verbose) && !options.compat) {
            if (uri != null) {
                if (uri.getScheme().equals("file"))
                    println("Classfile " + uri.getPath());
                else
                    println("Classfile " + uri);
            }
123
            indent(+1);
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
            if (lastModified != -1) {
                Date lm = new Date(lastModified);
                DateFormat df = DateFormat.getDateInstance();
                if (size > 0) {
                    println("Last modified " + df.format(lm) + "; size " + size + " bytes");
                } else {
                    println("Last modified " + df.format(lm));
                }
            } else if (size > 0) {
                println("Size " + size + " bytes");
            }
            if (digestName != null && digest != null) {
                StringBuilder sb = new StringBuilder();
                for (byte b: digest)
                    sb.append(String.format("%02x", b));
                println(digestName + " checksum " + sb);
            }
        }

143 144 145 146 147
        Attribute sfa = cf.getAttribute(Attribute.SourceFile);
        if (sfa instanceof SourceFile_attribute) {
            println("Compiled from \"" + getSourceFile((SourceFile_attribute) sfa) + "\"");
        }

148 149 150 151
        if ((options.sysInfo || options.verbose) && !options.compat) {
            indent(-1);
        }

152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
        String name = getJavaName(classFile);
        AccessFlags flags = cf.access_flags;

        writeModifiers(flags.getClassModifiers());

        if (classFile.isClass())
            print("class ");
        else if (classFile.isInterface())
            print("interface ");

        print(name);

        Signature_attribute sigAttr = getSignature(cf.attributes);
        if (sigAttr == null) {
            // use info from class file header
167 168 169 170
            if (classFile.isClass() && classFile.super_class != 0 ) {
                String sn = getJavaSuperclassName(cf);
                print(" extends ");
                print(sn);
171 172 173 174 175 176 177 178 179 180 181
            }
            for (int i = 0; i < classFile.interfaces.length; i++) {
                print(i == 0 ? (classFile.isClass() ? " implements " : " extends ") : ",");
                print(getJavaInterfaceName(classFile, i));
            }
        } else {
            try {
                Type t = sigAttr.getParsedSignature().getType(constant_pool);
                // The signature parser cannot disambiguate between a
                // FieldType and a ClassSignatureType that only contains a superclass type.
                if (t instanceof Type.ClassSigType)
182
                    print(getJavaName(t.toString()));
183
                else {
184
                    print(" extends ");
185
                    print(getJavaName(t.toString()));
186 187 188 189 190 191 192 193
                }
            } catch (ConstantPoolException e) {
                print(report(e));
            }
        }

        if (options.verbose) {
            println();
194
            indent(+1);
195
            attrWriter.write(cf, cf.attributes, constant_pool);
196 197
            println("minor version: " + cf.minor_version);
            println("major version: " + cf.major_version);
198
            if (!options.compat)
199 200
              writeList("flags: ", flags.getClassFlags(), NEWLINE);
            indent(-1);
201 202
            constantWriter.writeConstantPool();
        } else {
203
            print(" ");
204 205 206
        }

        println("{");
207
        indent(+1);
208 209
        writeFields();
        writeMethods();
210
        indent(-1);
211 212 213
        println("}");
    }

214
    protected void writeFields() {
215 216 217 218 219
        for (Field f: classFile.fields) {
            writeField(f);
        }
    }

220
    protected void writeField(Field f) {
221 222 223 224 225 226 227
        if (!options.checkAccess(f.access_flags))
            return;

        AccessFlags flags = f.access_flags;
        writeModifiers(flags.getFieldModifiers());
        Signature_attribute sigAttr = getSignature(f.attributes);
        if (sigAttr == null)
228
            print(getJavaFieldType(f.descriptor));
229 230 231
        else {
            try {
                Type t = sigAttr.getParsedSignature().getType(constant_pool);
232
                print(getJavaName(t.toString()));
233 234 235
            } catch (ConstantPoolException e) {
                // report error?
                // fall back on non-generic descriptor
236
                print(getJavaFieldType(f.descriptor));
237 238 239 240
            }
        }
        print(" ");
        print(getFieldName(f));
241 242 243 244 245 246 247 248
        if (options.showConstants && !options.compat) { // BUG 4111861 print static final field contents
            Attribute a = f.attributes.get(Attribute.ConstantValue);
            if (a instanceof ConstantValue_attribute) {
                print(" = ");
                ConstantValue_attribute cv = (ConstantValue_attribute) a;
                print(getConstantValue(f.descriptor, cv.constantvalue_index));
            }
        }
249 250 251
        print(";");
        println();

252 253
        indent(+1);

254
        if (options.showInternalSignatures)
255
            println("Signature: " + getValue(f.descriptor));
256 257

        if (options.verbose && !options.compat)
258
            writeList("flags: ", flags.getFieldFlags(), NEWLINE);
259 260 261 262 263 264 265

        if (options.showAllAttrs) {
            for (Attribute attr: f.attributes)
                attrWriter.write(f, attr, constant_pool);
            println();
        }

266 267
        indent(-1);

268 269 270 271
        if (options.showDisassembled || options.showLineAndLocalVariableTables)
            println();
    }

272
    protected void writeMethods() {
273 274
        for (Method m: classFile.methods)
            writeMethod(m);
275
        setPendingNewline(false);
276 277
    }

278
    protected void writeMethod(Method m) {
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
        if (!options.checkAccess(m.access_flags))
            return;

        method = m;

        AccessFlags flags = m.access_flags;

        Descriptor d;
        Type.MethodType methodType;
        List<? extends Type> methodExceptions;

        Signature_attribute sigAttr = getSignature(m.attributes);
        if (sigAttr == null) {
            d = m.descriptor;
            methodType = null;
            methodExceptions = null;
        } else {
            Signature methodSig = sigAttr.getParsedSignature();
            d = methodSig;
            try {
                methodType = (Type.MethodType) methodSig.getType(constant_pool);
                methodExceptions = methodType.throwsTypes;
                if (methodExceptions != null && methodExceptions.size() == 0)
                    methodExceptions = null;
            } catch (ConstantPoolException e) {
                // report error?
                // fall back on standard descriptor
                methodType = null;
                methodExceptions = null;
            }
        }

        writeModifiers(flags.getMethodModifiers());
        if (methodType != null) {
313
            writeListIfNotEmpty("<", methodType.typeParamTypes, "> ");
314 315 316
        }
        if (getName(m).equals("<init>")) {
            print(getJavaName(classFile));
317
            print(getJavaParameterTypes(d, flags));
318 319 320
        } else if (getName(m).equals("<clinit>")) {
            print("{}");
        } else {
321
            print(getJavaReturnType(d));
322 323
            print(" ");
            print(getName(m));
324
            print(getJavaParameterTypes(d, flags));
325 326 327 328 329 330 331 332 333 334 335 336 337
        }

        Attribute e_attr = m.attributes.get(Attribute.Exceptions);
        if (e_attr != null) { // if there are generic exceptions, there must be erased exceptions
            if (e_attr instanceof Exceptions_attribute) {
                Exceptions_attribute exceptions = (Exceptions_attribute) e_attr;
                print(" throws ");
                if (methodExceptions != null) { // use generic list if available
                    writeList("", methodExceptions, "");
                } else {
                    for (int i = 0; i < exceptions.number_of_exceptions; i++) {
                        if (i > 0)
                            print(", ");
338
                        print(getJavaException(exceptions, i));
339 340 341 342 343 344 345
                    }
                }
            } else {
                report("Unexpected or invalid value for Exceptions attribute");
            }
        }

346
        println(";");
347

348
        indent(+1);
349

350 351 352 353 354 355 356
        if (options.showInternalSignatures) {
            println("Signature: " + getValue(m.descriptor));
        }

        if (options.verbose && !options.compat) {
            writeList("flags: ", flags.getMethodFlags(), NEWLINE);
        }
357 358 359 360 361 362 363 364 365 366 367 368

        Code_attribute code = null;
        Attribute c_attr = m.attributes.get(Attribute.Code);
        if (c_attr != null) {
            if (c_attr instanceof Code_attribute)
                code = (Code_attribute) c_attr;
            else
                report("Unexpected or invalid value for Code attribute");
        }

        if (options.showDisassembled && !options.showAllAttrs) {
            if (code != null) {
369
                println("Code:");
370 371 372 373 374 375
                codeWriter.writeInstrs(code);
                codeWriter.writeExceptionTable(code);
            }
        }

        if (options.showLineAndLocalVariableTables) {
376
            if (code != null) {
377 378
                attrWriter.write(code, code.attributes.get(Attribute.LineNumberTable), constant_pool);
                attrWriter.write(code, code.attributes.get(Attribute.LocalVariableTable), constant_pool);
379
            }
380 381 382 383 384 385 386
        }

        if (options.showAllAttrs) {
            Attribute[] attrs = m.attributes.attrs;
            for (Attribute attr: attrs)
                attrWriter.write(m, attr, constant_pool);
        }
387 388 389 390 391 392 393 394 395 396 397

        indent(-1);

        // set pendingNewline to write a newline before the next method (if any)
        // if a separator is desired
        setPendingNewline(
                options.showDisassembled ||
                options.showAllAttrs ||
                options.showInternalSignatures ||
                options.showLineAndLocalVariableTables ||
                options.verbose);
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
    }

    void writeModifiers(Collection<String> items) {
        for (Object item: items) {
            print(item);
            print(" ");
        }
    }

    void writeList(String prefix, Collection<?> items, String suffix) {
        print(prefix);
        String sep = "";
        for (Object item: items) {
            print(sep);
            print(item);
            sep = ", ";
        }
        print(suffix);
    }

    void writeListIfNotEmpty(String prefix, List<?> items, String suffix) {
        if (items != null && items.size() > 0)
            writeList(prefix, items, suffix);
    }

    Signature_attribute getSignature(Attributes attributes) {
        if (options.compat) // javap does not recognize recent attributes
            return null;
        return (Signature_attribute) attributes.get(Attribute.Signature);
    }

    String adjustVarargs(AccessFlags flags, String params) {
        if (flags.is(ACC_VARARGS) && !options.compat) {
            int i = params.lastIndexOf("[]");
            if (i > 0)
                return params.substring(0, i) + "..." + params.substring(i+2);
        }

        return params;
    }

    String getJavaName(ClassFile cf) {
        try {
            return getJavaName(cf.getName());
        } catch (ConstantPoolException e) {
            return report(e);
        }
    }

    String getJavaSuperclassName(ClassFile cf) {
        try {
            return getJavaName(cf.getSuperclassName());
        } catch (ConstantPoolException e) {
            return report(e);
        }
    }

    String getJavaInterfaceName(ClassFile cf, int index) {
        try {
            return getJavaName(cf.getInterfaceName(index));
        } catch (ConstantPoolException e) {
            return report(e);
        }
    }

463
    String getJavaFieldType(Descriptor d) {
464
        try {
465
            return getJavaName(d.getFieldType(constant_pool));
466 467 468 469 470 471 472
        } catch (ConstantPoolException e) {
            return report(e);
        } catch (DescriptorException e) {
            return report(e);
        }
    }

473
    String getJavaReturnType(Descriptor d) {
474
        try {
475
            return getJavaName(d.getReturnType(constant_pool));
476 477 478 479 480 481 482
        } catch (ConstantPoolException e) {
            return report(e);
        } catch (DescriptorException e) {
            return report(e);
        }
    }

483
    String getJavaParameterTypes(Descriptor d, AccessFlags flags) {
484
        try {
485
            return getJavaName(adjustVarargs(flags, d.getParameterTypes(constant_pool)));
486 487 488 489 490 491 492
        } catch (ConstantPoolException e) {
            return report(e);
        } catch (DescriptorException e) {
            return report(e);
        }
    }

493 494 495 496 497 498 499 500
    String getJavaException(Exceptions_attribute attr, int index) {
        try {
            return getJavaName(attr.getException(index, constant_pool));
        } catch (ConstantPoolException e) {
            return report(e);
        }
    }

501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
    String getValue(Descriptor d) {
        try {
            return d.getValue(constant_pool);
        } catch (ConstantPoolException e) {
            return report(e);
        }
    }

    String getFieldName(Field f) {
        try {
            return f.getName(constant_pool);
        } catch (ConstantPoolException e) {
            return report(e);
        }
    }

    String getName(Method m) {
        try {
            return m.getName(constant_pool);
        } catch (ConstantPoolException e) {
            return report(e);
        }
    }

    static String getJavaName(String name) {
        return name.replace('/', '.');
    }

    String getSourceFile(SourceFile_attribute attr) {
        try {
            return attr.getSourceFile(constant_pool);
        } catch (ConstantPoolException e) {
            return report(e);
        }
    }

537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
    /**
     * Get the value of an entry in the constant pool as a Java constant.
     * Characters and booleans are represented by CONSTANT_Intgere entries.
     * Character and string values are processed to escape characters outside
     * the basic printable ASCII set.
     * @param d the descriptor, giving the expected type of the constant
     * @param index the index of the value in the constant pool
     * @return a printable string containing the value of the constant.
     */
    String getConstantValue(Descriptor d, int index) {
        try {
            ConstantPool.CPInfo cpInfo = constant_pool.get(index);

            switch (cpInfo.getTag()) {
                case ConstantPool.CONSTANT_Integer: {
                    ConstantPool.CONSTANT_Integer_info info =
                            (ConstantPool.CONSTANT_Integer_info) cpInfo;
                    String t = d.getValue(constant_pool);
                    if (t.equals("C")) { // character
                        return getConstantCharValue((char) info.value);
                    } else if (t.equals("Z")) { // boolean
                        return String.valueOf(info.value == 1);
                    } else { // other: assume integer
                        return String.valueOf(info.value);
                    }
                }

                case ConstantPool.CONSTANT_String: {
                    ConstantPool.CONSTANT_String_info info =
                            (ConstantPool.CONSTANT_String_info) cpInfo;
                    return getConstantStringValue(info.getString());
                }

                default:
                    return constantWriter.stringValue(cpInfo);
            }
        } catch (ConstantPoolException e) {
            return "#" + index;
        }
    }

    private String getConstantCharValue(char c) {
        StringBuilder sb = new StringBuilder();
        sb.append('\'');
        sb.append(esc(c, '\''));
        sb.append('\'');
        return sb.toString();
    }

    private String getConstantStringValue(String s) {
        StringBuilder sb = new StringBuilder();
        sb.append("\"");
        for (int i = 0; i < s.length(); i++) {
            sb.append(esc(s.charAt(i), '"'));
        }
        sb.append("\"");
        return sb.toString();
    }

    private String esc(char c, char quote) {
        if (32 <= c && c <= 126 && c != quote)
            return String.valueOf(c);
        else switch (c) {
            case '\b': return "\\b";
            case '\n': return "\\n";
            case '\t': return "\\t";
            case '\f': return "\\f";
            case '\r': return "\\r";
            case '\\': return "\\\\";
            case '\'': return "\\'";
            case '\"': return "\\\"";
            default:   return String.format("\\u%04x", (int) c);
        }
    }

612 613 614 615 616
    private Options options;
    private AttributeWriter attrWriter;
    private CodeWriter codeWriter;
    private ConstantWriter constantWriter;
    private ClassFile classFile;
617 618 619 620 621
    private URI uri;
    private long lastModified;
    private String digestName;
    private byte[] digest;
    private int size;
622 623 624 625
    private ConstantPool constant_pool;
    private Method method;
    private static final String NEWLINE = System.getProperty("line.separator", "\n");
}