JavapTask.java 35.8 KB
Newer Older
1
/*
2
 * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
3 4 5 6
 * 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
7
 * published by the Free Software Foundation.  Oracle designates this
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
10 11 12 13 14 15 16 17 18
 *
 * 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,
19
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
24 25 26 27 28 29
 */

package com.sun.tools.javap;

import java.io.EOFException;
import java.io.FileNotFoundException;
30 31
import java.io.FilterInputStream;
import java.io.InputStream;
32 33 34
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
35
import java.io.Reader;
36 37
import java.io.StringWriter;
import java.io.Writer;
38
import java.net.URI;
39 40
import java.security.DigestInputStream;
import java.security.MessageDigest;
41
import java.security.NoSuchAlgorithmException;
42 43 44
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
45
import java.util.EnumSet;
46 47 48 49 50 51 52 53
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

54 55
import javax.lang.model.element.Modifier;
import javax.lang.model.element.NestingKind;
56 57 58 59 60 61 62 63
import javax.tools.Diagnostic;
import javax.tools.DiagnosticListener;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;

import com.sun.tools.classfile.*;
64 65 66
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
67 68 69 70 71

/**
 *  "Main" class for javap, normally accessed from the command line
 *  via Main, or from JSR199 via DisassemblerTool.
 *
72 73
 *  <p><b>This is NOT part of any supported API.
 *  If you write code that depends on this, you do so at your own risk.
74 75 76
 *  This code and its internal interfaces are subject to change or
 *  deletion without notice.</b>
 */
77
public class JavapTask implements DisassemblerTool.DisassemblerTask, Messages {
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
    public class BadArgs extends Exception {
        static final long serialVersionUID = 8765093759964640721L;
        BadArgs(String key, Object... args) {
            super(JavapTask.this.getMessage(key, args));
            this.key = key;
            this.args = args;
        }

        BadArgs showUsage(boolean b) {
            showUsage = b;
            return this;
        }

        final String key;
        final Object[] args;
        boolean showUsage;
    }

    static abstract class Option {
        Option(boolean hasArg, String... aliases) {
            this.hasArg = hasArg;
            this.aliases = aliases;
        }

        boolean matches(String opt) {
            for (String a: aliases) {
                if (a.equals(opt))
                    return true;
            }
            return false;
        }

        boolean ignoreRest() {
            return false;
        }

        abstract void process(JavapTask task, String opt, String arg) throws BadArgs;

        final boolean hasArg;
        final String[] aliases;
    }

120
    static final Option[] recognizedOptions = {
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142

        new Option(false, "-help", "--help", "-?") {
            void process(JavapTask task, String opt, String arg) {
                task.options.help = true;
            }
        },

        new Option(false, "-version") {
            void process(JavapTask task, String opt, String arg) {
                task.options.version = true;
            }
        },

        new Option(false, "-fullversion") {
            void process(JavapTask task, String opt, String arg) {
                task.options.fullVersion = true;
            }
        },

        new Option(false, "-v", "-verbose", "-all") {
            void process(JavapTask task, String opt, String arg) {
                task.options.verbose = true;
143
                task.options.showDescriptors = true;
144 145 146 147 148 149 150 151 152 153 154 155 156
                task.options.showFlags = true;
                task.options.showAllAttrs = true;
            }
        },

        new Option(false, "-l") {
            void process(JavapTask task, String opt, String arg) {
                task.options.showLineAndLocalVariableTables = true;
            }
        },

        new Option(false, "-public") {
            void process(JavapTask task, String opt, String arg) {
157
                task.options.accessOptions.add(opt);
158 159 160 161 162 163
                task.options.showAccess = AccessFlags.ACC_PUBLIC;
            }
        },

        new Option(false, "-protected") {
            void process(JavapTask task, String opt, String arg) {
164
                task.options.accessOptions.add(opt);
165 166 167 168 169 170
                task.options.showAccess = AccessFlags.ACC_PROTECTED;
            }
        },

        new Option(false, "-package") {
            void process(JavapTask task, String opt, String arg) {
171
                task.options.accessOptions.add(opt);
172 173 174 175 176 177
                task.options.showAccess = 0;
            }
        },

        new Option(false, "-p", "-private") {
            void process(JavapTask task, String opt, String arg) {
178 179 180 181
                if (!task.options.accessOptions.contains("-p") &&
                        !task.options.accessOptions.contains("-private")) {
                    task.options.accessOptions.add(opt);
                }
182 183 184 185 186 187 188 189 190 191 192 193
                task.options.showAccess = AccessFlags.ACC_PRIVATE;
            }
        },

        new Option(false, "-c") {
            void process(JavapTask task, String opt, String arg) {
                task.options.showDisassembled = true;
            }
        },

        new Option(false, "-s") {
            void process(JavapTask task, String opt, String arg) {
194
                task.options.showDescriptors = true;
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
            }
        },

//        new Option(false, "-all") {
//            void process(JavapTask task, String opt, String arg) {
//                task.options.showAllAttrs = true;
//            }
//        },

        new Option(false, "-h") {
            void process(JavapTask task, String opt, String arg) throws BadArgs {
                throw task.new BadArgs("err.h.not.supported");
            }
        },

        new Option(false, "-verify", "-verify-verbose") {
            void process(JavapTask task, String opt, String arg) throws BadArgs {
                throw task.new BadArgs("err.verify.not.supported");
            }
        },

216 217 218 219 220 221
        new Option(false, "-sysinfo") {
            void process(JavapTask task, String opt, String arg) {
                task.options.sysInfo = true;
            }
        },

222 223
        new Option(false, "-Xold") {
            void process(JavapTask task, String opt, String arg) throws BadArgs {
J
jjg 已提交
224
                task.log.println(task.getMessage("warn.Xold.not.supported"));
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
            }
        },

        new Option(false, "-Xnew") {
            void process(JavapTask task, String opt, String arg) throws BadArgs {
                // ignore: this _is_ the new version
            }
        },

        new Option(false, "-XDcompat") {
            void process(JavapTask task, String opt, String arg) {
                task.options.compat = true;
            }
        },

240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
        new Option(false, "-XDdetails") {
            void process(JavapTask task, String opt, String arg) {
                task.options.details = EnumSet.allOf(InstructionDetailWriter.Kind.class);
            }

        },

        new Option(false, "-XDdetails:") {
            @Override
            boolean matches(String opt) {
                int sep = opt.indexOf(":");
                return sep != -1 && super.matches(opt.substring(0, sep + 1));
            }

            void process(JavapTask task, String opt, String arg) throws BadArgs {
                int sep = opt.indexOf(":");
                for (String v: opt.substring(sep + 1).split("[,: ]+")) {
                    if (!handleArg(task, v))
                        throw task.new BadArgs("err.invalid.arg.for.option", v);
                }
            }

            boolean handleArg(JavapTask task, String arg) {
                if (arg.length() == 0)
                    return true;

                if (arg.equals("all")) {
                    task.options.details = EnumSet.allOf(InstructionDetailWriter.Kind.class);
                    return true;
                }

                boolean on = true;
                if (arg.startsWith("-")) {
                    on = false;
                    arg = arg.substring(1);
                }

                for (InstructionDetailWriter.Kind k: InstructionDetailWriter.Kind.values()) {
                    if (arg.equalsIgnoreCase(k.option)) {
                        if (on)
                            task.options.details.add(k);
                        else
                            task.options.details.remove(k);
                        return true;
                    }
                }
                return false;
            }
        },

290 291 292 293
        new Option(false, "-constants") {
            void process(JavapTask task, String opt, String arg) {
                task.options.showConstants = true;
            }
294 295 296 297 298 299
        },

        new Option(false, "-XDinner") {
            void process(JavapTask task, String opt, String arg) {
                task.options.showInnerClasses = true;
            }
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
        },

        new Option(false, "-XDindent:") {
            @Override
            boolean matches(String opt) {
                int sep = opt.indexOf(":");
                return sep != -1 && super.matches(opt.substring(0, sep + 1));
            }

            void process(JavapTask task, String opt, String arg) throws BadArgs {
                int sep = opt.indexOf(":");
                try {
                    task.options.indentWidth = Integer.valueOf(opt.substring(sep + 1));
                } catch (NumberFormatException e) {
                }
            }
        },

        new Option(false, "-XDtab:") {
            @Override
            boolean matches(String opt) {
                int sep = opt.indexOf(":");
                return sep != -1 && super.matches(opt.substring(0, sep + 1));
            }

            void process(JavapTask task, String opt, String arg) throws BadArgs {
                int sep = opt.indexOf(":");
                try {
                    task.options.tabColumn = Integer.valueOf(opt.substring(sep + 1));
                } catch (NumberFormatException e) {
                }
            }
332 333 334 335
        }

    };

336
    public JavapTask() {
337
        context = new Context();
338
        context.put(Messages.class, this);
339
        options = Options.instance(context);
340
        attributeFactory = new Attribute.Factory();
341 342
    }

343
    public JavapTask(Writer out,
344
            JavaFileManager fileManager,
345
            DiagnosticListener<? super JavaFileObject> diagnosticListener) {
346 347 348 349
        this();
        this.log = getPrintWriterForWriter(out);
        this.fileManager = fileManager;
        this.diagnosticListener = diagnosticListener;
350 351 352 353 354 355 356 357
    }

    public JavapTask(Writer out,
            JavaFileManager fileManager,
            DiagnosticListener<? super JavaFileObject> diagnosticListener,
            Iterable<String> options,
            Iterable<String> classes) {
        this(out, fileManager, diagnosticListener);
358 359 360 361 362 363

        this.classes = new ArrayList<String>();
        for (String classname: classes) {
            classname.getClass(); // null-check
            this.classes.add(classname);
        }
364 365

        try {
366 367
            if (options != null)
                handleOptions(options, false);
368 369 370
        } catch (BadArgs e) {
            throw new IllegalArgumentException(e.getMessage());
        }
371 372 373 374 375 376 377 378
    }

    public void setLocale(Locale locale) {
        if (locale == null)
            locale = Locale.getDefault();
        task_locale = locale;
    }

379 380
    public void setLog(Writer log) {
        this.log = getPrintWriterForWriter(log);
381 382 383 384 385 386 387
    }

    public void setLog(OutputStream s) {
        setLog(getPrintWriterForStream(s));
    }

    private static PrintWriter getPrintWriterForStream(OutputStream s) {
388
        return new PrintWriter(s == null ? System.err : s, true);
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
    }

    private static PrintWriter getPrintWriterForWriter(Writer w) {
        if (w == null)
            return getPrintWriterForStream(null);
        else if (w instanceof PrintWriter)
            return (PrintWriter) w;
        else
            return new PrintWriter(w, true);
    }

    public void setDiagnosticListener(DiagnosticListener<? super JavaFileObject> dl) {
        diagnosticListener = dl;
    }

    public void setDiagnosticListener(OutputStream s) {
        setDiagnosticListener(getDiagnosticListenerForStream(s));
    }

    private DiagnosticListener<JavaFileObject> getDiagnosticListenerForStream(OutputStream s) {
        return getDiagnosticListenerForWriter(getPrintWriterForStream(s));
    }

    private DiagnosticListener<JavaFileObject> getDiagnosticListenerForWriter(Writer w) {
        final PrintWriter pw = getPrintWriterForWriter(w);
        return new DiagnosticListener<JavaFileObject> () {
            public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
416 417
                switch (diagnostic.getKind()) {
                    case ERROR:
418
                        pw.print(getMessage("err.prefix"));
419 420 421 422 423 424 425
                        break;
                    case WARNING:
                        pw.print(getMessage("warn.prefix"));
                        break;
                    case NOTE:
                        pw.print(getMessage("note.prefix"));
                        break;
426
                }
427
                pw.print(" ");
428 429 430 431 432
                pw.println(diagnostic.getMessage(null));
            }
        };
    }

433 434 435 436 437 438 439 440 441
    /** Result codes.
     */
    static final int
        EXIT_OK = 0,        // Compilation completed with no errors.
        EXIT_ERROR = 1,     // Completed but reported errors.
        EXIT_CMDERR = 2,    // Bad command-line arguments
        EXIT_SYSERR = 3,    // System error or resource exhaustion.
        EXIT_ABNORMAL = 4;  // Compiler terminated abnormally

442 443 444
    int run(String[] args) {
        try {
            handleOptions(args);
445 446 447 448 449 450 451 452 453

            // the following gives consistent behavior with javac
            if (classes == null || classes.size() == 0) {
                if (options.help || options.version || options.fullVersion)
                    return EXIT_OK;
                else
                    return EXIT_CMDERR;
            }

454 455 456 457 458 459 460 461 462 463 464 465 466
            try {
                boolean ok = run();
                return ok ? EXIT_OK : EXIT_ERROR;
            } finally {
                if (defaultFileManager != null) {
                    try {
                        defaultFileManager.close();
                        defaultFileManager = null;
                    } catch (IOException e) {
                        throw new InternalError(e);
                    }
                }
            }
467
        } catch (BadArgs e) {
468
            reportError(e.key, e.args);
469 470 471
            if (e.showUsage) {
                log.println(getMessage("main.usage.summary", progname));
            }
472
            return EXIT_CMDERR;
473 474 475 476 477 478 479 480 481
        } catch (InternalError e) {
            Object[] e_args;
            if (e.getCause() == null)
                e_args = e.args;
            else {
                e_args = new Object[e.args.length + 1];
                e_args[0] = e.getCause();
                System.arraycopy(e.args, 0, e_args, 1, e.args.length);
            }
482
            reportError("err.internal.error", e_args);
483
            return EXIT_ABNORMAL;
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
        } finally {
            log.flush();
        }
    }

    public void handleOptions(String[] args) throws BadArgs {
        handleOptions(Arrays.asList(args), true);
    }

    private void handleOptions(Iterable<String> args, boolean allowClasses) throws BadArgs {
        if (log == null) {
            log = getPrintWriterForStream(System.out);
            if (diagnosticListener == null)
              diagnosticListener = getDiagnosticListenerForStream(System.err);
        } else {
            if (diagnosticListener == null)
              diagnosticListener = getDiagnosticListenerForWriter(log);
        }


        if (fileManager == null)
            fileManager = getDefaultFileManager(diagnosticListener, log);

        Iterator<String> iter = args.iterator();
508
        boolean noArgs = !iter.hasNext();
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523

        while (iter.hasNext()) {
            String arg = iter.next();
            if (arg.startsWith("-"))
                handleOption(arg, iter);
            else if (allowClasses) {
                if (classes == null)
                    classes = new ArrayList<String>();
                classes.add(arg);
                while (iter.hasNext())
                    classes.add(iter.next());
            } else
                throw new BadArgs("err.unknown.option", arg).showUsage(true);
        }

524 525 526 527 528 529 530 531 532 533
        if (!options.compat && options.accessOptions.size() > 1) {
            StringBuilder sb = new StringBuilder();
            for (String opt: options.accessOptions) {
                if (sb.length() > 0)
                    sb.append(" ");
                sb.append(opt);
            }
            throw new BadArgs("err.incompatible.options", sb);
        }

534
        if ((classes == null || classes.size() == 0) &&
535
                !(noArgs || options.help || options.version || options.fullVersion)) {
536 537
            throw new BadArgs("err.no.classes.specified");
        }
538 539 540 541 542 543

        if (noArgs || options.help)
            showHelp();

        if (options.version || options.fullVersion)
            showVersion(options.fullVersion);
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
    }

    private void handleOption(String name, Iterator<String> rest) throws BadArgs {
        for (Option o: recognizedOptions) {
            if (o.matches(name)) {
                if (o.hasArg) {
                    if (rest.hasNext())
                        o.process(this, name, rest.next());
                    else
                        throw new BadArgs("err.missing.arg", name).showUsage(true);
                } else
                    o.process(this, name, null);

                if (o.ignoreRest()) {
                    while (rest.hasNext())
                        rest.next();
                }
                return;
            }
        }

        if (fileManager.handleOption(name, rest))
            return;

        throw new BadArgs("err.unknown.option", name).showUsage(true);
    }

    public Boolean call() {
        return run();
    }

    public boolean run() {
        if (classes == null || classes.size() == 0)
577
            return false;
578 579 580

        context.put(PrintWriter.class, log);
        ClassWriter classWriter = ClassWriter.instance(context);
581 582
        SourceWriter sourceWriter = SourceWriter.instance(context);
        sourceWriter.setFileManager(fileManager);
583

584 585
        attributeFactory.setCompat(options.compat);

586 587 588 589 590
        boolean ok = true;

        for (String className: classes) {
            JavaFileObject fo;
            try {
591
                writeClass(classWriter, className);
592
            } catch (ConstantPoolException e) {
593
                reportError("err.bad.constant.pool", className, e.getLocalizedMessage());
594 595
                ok = false;
            } catch (EOFException e) {
596
                reportError("err.end.of.file", className);
597 598
                ok = false;
            } catch (FileNotFoundException e) {
599
                reportError("err.file.not.found", e.getLocalizedMessage());
600 601 602 603 604 605
                ok = false;
            } catch (IOException e) {
                //e.printStackTrace();
                Object msg = e.getLocalizedMessage();
                if (msg == null)
                    msg = e;
606
                reportError("err.ioerror", className, msg);
607 608 609 610 611 612
                ok = false;
            } catch (Throwable t) {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                t.printStackTrace(pw);
                pw.close();
613
                reportError("err.crash", t.toString(), sw.toString());
614
                ok = false;
615 616 617 618 619 620
            }
        }

        return ok;
    }

621 622
    protected boolean writeClass(ClassWriter classWriter, String className)
            throws IOException, ConstantPoolException {
623 624 625 626
        JavaFileObject fo = open(className);
        if (fo == null) {
            reportError("err.class.not.found", className);
            return false;
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
        }

        ClassFileInfo cfInfo = read(fo);
        if (!className.endsWith(".class")) {
            String cfName = cfInfo.cf.getName();
            if (!cfName.replaceAll("[/$]", ".").equals(className.replaceAll("[/$]", ".")))
                reportWarning("warn.unexpected.class", className, cfName.replace('/', '.'));
        }
        write(cfInfo);

        if (options.showInnerClasses) {
            ClassFile cf = cfInfo.cf;
            Attribute a = cf.getAttribute(Attribute.InnerClasses);
            if (a instanceof InnerClasses_attribute) {
                InnerClasses_attribute inners = (InnerClasses_attribute) a;
                try {
                    boolean ok = true;
                    for (int i = 0; i < inners.classes.length; i++) {
                        int outerIndex = inners.classes[i].outer_class_info_index;
                        ConstantPool.CONSTANT_Class_info outerClassInfo = cf.constant_pool.getClassInfo(outerIndex);
                        String outerClassName = outerClassInfo.getName();
                        if (outerClassName.equals(cf.getName())) {
                            int innerIndex = inners.classes[i].inner_class_info_index;
                            ConstantPool.CONSTANT_Class_info innerClassInfo = cf.constant_pool.getClassInfo(innerIndex);
                            String innerClassName = innerClassInfo.getName();
                            classWriter.println("// inner class " + innerClassName.replaceAll("[/$]", "."));
                            classWriter.println();
                            ok = ok & writeClass(classWriter, innerClassName);
                        }
                    }
                    return ok;
                } catch (ConstantPoolException e) {
                    reportError("err.bad.innerclasses.attribute", className);
                    return false;
                }
            } else if (a != null) {
                reportError("err.bad.innerclasses.attribute", className);
                return false;
            }
        }

        return true;
    }

671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
    protected JavaFileObject open(String className) throws IOException {
        // for compatibility, first see if it is a class name
        JavaFileObject fo = getClassFileObject(className);
        if (fo != null)
            return fo;

        // see if it is an inner class, by replacing dots to $, starting from the right
        String cn = className;
        int lastDot;
        while ((lastDot = cn.lastIndexOf(".")) != -1) {
            cn = cn.substring(0, lastDot) + "$" + cn.substring(lastDot + 1);
            fo = getClassFileObject(cn);
            if (fo != null)
                return fo;
        }

        if (!className.endsWith(".class"))
            return null;

        if (fileManager instanceof StandardJavaFileManager) {
            StandardJavaFileManager sfm = (StandardJavaFileManager) fileManager;
            fo = sfm.getJavaFileObjects(className).iterator().next();
            if (fo != null && fo.getLastModified() != 0) {
                return fo;
            }
        }

        // see if it is a URL, and if so, wrap it in just enough of a JavaFileObject
        // to suit javap's needs
        if (className.matches("^[A-Za-z]+:.*")) {
            try {
                final URI uri = new URI(className);
                final URL url = uri.toURL();
                final URLConnection conn = url.openConnection();
                return new JavaFileObject() {
                    public Kind getKind() {
                        return JavaFileObject.Kind.CLASS;
                    }

                    public boolean isNameCompatible(String simpleName, Kind kind) {
                        throw new UnsupportedOperationException();
                    }

                    public NestingKind getNestingKind() {
                        throw new UnsupportedOperationException();
                    }

                    public Modifier getAccessLevel() {
                        throw new UnsupportedOperationException();
                    }

                    public URI toUri() {
                        return uri;
                    }

                    public String getName() {
                        return url.toString();
                    }

                    public InputStream openInputStream() throws IOException {
                        return conn.getInputStream();
                    }

                    public OutputStream openOutputStream() throws IOException {
                        throw new UnsupportedOperationException();
                    }

                    public Reader openReader(boolean ignoreEncodingErrors) throws IOException {
                        throw new UnsupportedOperationException();
                    }

                    public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
                        throw new UnsupportedOperationException();
                    }

                    public Writer openWriter() throws IOException {
                        throw new UnsupportedOperationException();
                    }

                    public long getLastModified() {
                        return conn.getLastModified();
                    }

                    public boolean delete() {
                        throw new UnsupportedOperationException();
                    }

                };
            } catch (URISyntaxException ignore) {
            } catch (IOException ignore) {
            }
        }

        return null;
    }

767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
    public static class ClassFileInfo {
        ClassFileInfo(JavaFileObject fo, ClassFile cf, byte[] digest, int size) {
            this.fo = fo;
            this.cf = cf;
            this.digest = digest;
            this.size = size;
        }
        public final JavaFileObject fo;
        public final ClassFile cf;
        public final byte[] digest;
        public final int size;
    }

    public ClassFileInfo read(JavaFileObject fo) throws IOException, ConstantPoolException {
        InputStream in = fo.openInputStream();
        try {
            SizeInputStream sizeIn = null;
            MessageDigest md  = null;
            if (options.sysInfo || options.verbose) {
                try {
                    md = MessageDigest.getInstance("MD5");
                } catch (NoSuchAlgorithmException ignore) {
                }
                in = new DigestInputStream(in, md);
                in = sizeIn = new SizeInputStream(in);
            }

            ClassFile cf = ClassFile.read(in, attributeFactory);
            byte[] digest = (md == null) ? null : md.digest();
            int size = (sizeIn == null) ? -1 : sizeIn.size();
            return new ClassFileInfo(fo, cf, digest, size);
        } finally {
            in.close();
        }
    }

    public void write(ClassFileInfo info) {
        ClassWriter classWriter = ClassWriter.instance(context);
        if (options.sysInfo || options.verbose) {
            classWriter.setFile(info.fo.toUri());
            classWriter.setLastModified(info.fo.getLastModified());
            classWriter.setDigest("MD5", info.digest);
            classWriter.setFileSize(info.size);
        }

        classWriter.write(info.cf);
    }

    protected void setClassFile(ClassFile classFile) {
        ClassWriter classWriter = ClassWriter.instance(context);
        classWriter.setClassFile(classFile);
    }

    protected void setMethod(Method enclosingMethod) {
        ClassWriter classWriter = ClassWriter.instance(context);
        classWriter.setMethod(enclosingMethod);
    }

    protected void write(Attribute value) {
        AttributeWriter attrWriter = AttributeWriter.instance(context);
        ClassWriter classWriter = ClassWriter.instance(context);
        ClassFile cf = classWriter.getClassFile();
        attrWriter.write(cf, value, cf.constant_pool);
    }

    protected void write(Attributes attrs) {
        AttributeWriter attrWriter = AttributeWriter.instance(context);
        ClassWriter classWriter = ClassWriter.instance(context);
        ClassFile cf = classWriter.getClassFile();
        attrWriter.write(cf, attrs, cf.constant_pool);
    }

    protected void write(ConstantPool constant_pool) {
        ConstantWriter constantWriter = ConstantWriter.instance(context);
        constantWriter.writeConstantPool(constant_pool);
    }

    protected void write(ConstantPool constant_pool, int value) {
        ConstantWriter constantWriter = ConstantWriter.instance(context);
        constantWriter.write(value);
    }

    protected void write(ConstantPool.CPInfo value) {
        ConstantWriter constantWriter = ConstantWriter.instance(context);
        constantWriter.println(value);
    }

    protected void write(Field value) {
        ClassWriter classWriter = ClassWriter.instance(context);
        classWriter.writeField(value);
    }

    protected void write(Method value) {
        ClassWriter classWriter = ClassWriter.instance(context);
        classWriter.writeMethod(value);
    }

864
    private JavaFileManager getDefaultFileManager(final DiagnosticListener<? super JavaFileObject> dl, PrintWriter log) {
865 866 867
        if (defaultFileManager == null)
            defaultFileManager = JavapFileManager.create(dl, log);
        return defaultFileManager;
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
    }

    private JavaFileObject getClassFileObject(String className) throws IOException {
        JavaFileObject fo;
        fo = fileManager.getJavaFileForInput(StandardLocation.PLATFORM_CLASS_PATH, className, JavaFileObject.Kind.CLASS);
        if (fo == null)
            fo = fileManager.getJavaFileForInput(StandardLocation.CLASS_PATH, className, JavaFileObject.Kind.CLASS);
        return fo;
    }

    private void showHelp() {
        log.println(getMessage("main.usage", progname));
        for (Option o: recognizedOptions) {
            String name = o.aliases[0].substring(1); // there must always be at least one name
            if (name.startsWith("X") || name.equals("fullversion") || name.equals("h") || name.equals("verify"))
                continue;
            log.println(getMessage("main.opt." + name));
        }
        String[] fmOptions = { "-classpath", "-bootclasspath" };
        for (String o: fmOptions) {
            if (fileManager.isSupportedOption(o) == -1)
                continue;
            String name = o.substring(1);
            log.println(getMessage("main.opt." + name));
        }

    }

    private void showVersion(boolean full) {
        log.println(version(full ? "full" : "release"));
    }

    private static final String versionRBName = "com.sun.tools.javap.resources.version";
    private static ResourceBundle versionRB;

    private String version(String key) {
        // key=version:  mm.nn.oo[-milestone]
        // key=full:     mm.mm.oo[-milestone]-build
        if (versionRB == null) {
            try {
                versionRB = ResourceBundle.getBundle(versionRBName);
            } catch (MissingResourceException e) {
                return getMessage("version.resource.missing", System.getProperty("java.version"));
            }
        }
        try {
            return versionRB.getString(key);
        }
        catch (MissingResourceException e) {
            return getMessage("version.unknown", System.getProperty("java.version"));
        }
    }

921 922 923 924 925 926 927 928 929 930 931 932 933 934
    private void reportError(String key, Object... args) {
        diagnosticListener.report(createDiagnostic(Diagnostic.Kind.ERROR, key, args));
    }

    private void reportNote(String key, Object... args) {
        diagnosticListener.report(createDiagnostic(Diagnostic.Kind.NOTE, key, args));
    }

    private void reportWarning(String key, Object... args) {
        diagnosticListener.report(createDiagnostic(Diagnostic.Kind.WARNING, key, args));
    }

    private Diagnostic<JavaFileObject> createDiagnostic(
            final Diagnostic.Kind kind, final String key, final Object... args) {
935 936
        return new Diagnostic<JavaFileObject>() {
            public Kind getKind() {
937
                return kind;
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971
            }

            public JavaFileObject getSource() {
                return null;
            }

            public long getPosition() {
                return Diagnostic.NOPOS;
            }

            public long getStartPosition() {
                return Diagnostic.NOPOS;
            }

            public long getEndPosition() {
                return Diagnostic.NOPOS;
            }

            public long getLineNumber() {
                return Diagnostic.NOPOS;
            }

            public long getColumnNumber() {
                return Diagnostic.NOPOS;
            }

            public String getCode() {
                return key;
            }

            public String getMessage(Locale locale) {
                return JavapTask.this.getMessage(locale, key, args);
            }

972
            @Override
973 974 975 976
            public String toString() {
                return getClass().getName() + "[key=" + key + ",args=" + Arrays.asList(args) + "]";
            }

977 978 979 980
        };

    }

981
    public String getMessage(String key, Object... args) {
982 983 984
        return getMessage(task_locale, key, args);
    }

985
    public String getMessage(Locale locale, String key, Object... args) {
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
        if (bundles == null) {
            // could make this a HashMap<Locale,SoftReference<ResourceBundle>>
            // and for efficiency, keep a hard reference to the bundle for the task
            // locale
            bundles = new HashMap<Locale, ResourceBundle>();
        }

        if (locale == null)
            locale = Locale.getDefault();

        ResourceBundle b = bundles.get(locale);
        if (b == null) {
            try {
                b = ResourceBundle.getBundle("com.sun.tools.javap.resources.javap", locale);
                bundles.put(locale, b);
            } catch (MissingResourceException e) {
                throw new InternalError("Cannot find javap resource bundle for locale " + locale);
            }
        }

        try {
            return MessageFormat.format(b.getString(key), args);
        } catch (MissingResourceException e) {
            throw new InternalError(e, key);
        }
    }

1013
    protected Context context;
1014
    JavaFileManager fileManager;
1015
    JavaFileManager defaultFileManager;
1016 1017 1018 1019 1020 1021 1022
    PrintWriter log;
    DiagnosticListener<? super JavaFileObject> diagnosticListener;
    List<String> classes;
    Options options;
    //ResourceBundle bundle;
    Locale task_locale;
    Map<Locale, ResourceBundle> bundles;
1023
    protected Attribute.Factory attributeFactory;
1024 1025

    private static final String progname = "javap";
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052

    private static class SizeInputStream extends FilterInputStream {
        SizeInputStream(InputStream in) {
            super(in);
        }

        int size() {
            return size;
        }

        @Override
        public int read(byte[] buf, int offset, int length) throws IOException {
            int n = super.read(buf, offset, length);
            if (n > 0)
                size += n;
            return n;
        }

        @Override
        public int read() throws IOException {
            int b = super.read();
            size += 1;
            return b;
        }

        private int size;
    }
1053
}