Wed, 16 Oct 2013 16:33:04 -0400
8026286: Improper locking of annotation queues causes assertion failures.
8026063: Calls to annotate.flush() cause incorrect type annotations to be generated.
Summary: Fix locking in ClassReader.java
Reviewed-by: jfranck
1 /*
2 * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * 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 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 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 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
26 package com.sun.tools.javac.util;
28 import java.io.*;
29 import java.util.Arrays;
30 import java.util.EnumSet;
31 import java.util.HashSet;
32 import java.util.Queue;
33 import java.util.Set;
34 import javax.tools.DiagnosticListener;
35 import javax.tools.JavaFileObject;
37 import com.sun.tools.javac.api.DiagnosticFormatter;
38 import com.sun.tools.javac.main.Main;
39 import com.sun.tools.javac.main.Option;
40 import com.sun.tools.javac.tree.EndPosTable;
41 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
42 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType;
44 import static com.sun.tools.javac.main.Option.*;
46 /** A class for error logs. Reports errors and warnings, and
47 * keeps track of error numbers and positions.
48 *
49 * <p><b>This is NOT part of any supported API.
50 * If you write code that depends on this, you do so at your own risk.
51 * This code and its internal interfaces are subject to change or
52 * deletion without notice.</b>
53 */
54 public class Log extends AbstractLog {
55 /** The context key for the log. */
56 public static final Context.Key<Log> logKey
57 = new Context.Key<Log>();
59 /** The context key for the output PrintWriter. */
60 public static final Context.Key<PrintWriter> outKey =
61 new Context.Key<PrintWriter>();
63 /* TODO: Should unify this with prefix handling in JCDiagnostic.Factory. */
64 public enum PrefixKind {
65 JAVAC("javac."),
66 COMPILER_MISC("compiler.misc.");
67 PrefixKind(String v) {
68 value = v;
69 }
70 public String key(String k) {
71 return value + k;
72 }
73 final String value;
74 }
76 /**
77 * DiagnosticHandler's provide the initial handling for diagnostics.
78 * When a diagnostic handler is created and has been initialized, it
79 * should install itself as the current diagnostic handler. When a
80 * client has finished using a handler, the client should call
81 * {@code log.removeDiagnosticHandler();}
82 *
83 * Note that javax.tools.DiagnosticListener (if set) is called later in the
84 * diagnostic pipeline.
85 */
86 public static abstract class DiagnosticHandler {
87 /**
88 * The previously installed diagnostic handler.
89 */
90 protected DiagnosticHandler prev;
92 /**
93 * Install this diagnostic handler as the current one,
94 * recording the previous one.
95 */
96 protected void install(Log log) {
97 prev = log.diagnosticHandler;
98 log.diagnosticHandler = this;
99 }
101 /**
102 * Handle a diagnostic.
103 */
104 public abstract void report(JCDiagnostic diag);
105 }
107 /**
108 * A DiagnosticHandler that discards all diagnostics.
109 */
110 public static class DiscardDiagnosticHandler extends DiagnosticHandler {
111 public DiscardDiagnosticHandler(Log log) {
112 install(log);
113 }
115 public void report(JCDiagnostic diag) { }
116 }
118 /**
119 * A DiagnosticHandler that can defer some or all diagnostics,
120 * by buffering them for later examination and/or reporting.
121 * If a diagnostic is not deferred, or is subsequently reported
122 * with reportAllDiagnostics(), it will be reported to the previously
123 * active diagnostic handler.
124 */
125 public static class DeferredDiagnosticHandler extends DiagnosticHandler {
126 private Queue<JCDiagnostic> deferred = new ListBuffer<>();
127 private final Filter<JCDiagnostic> filter;
129 public DeferredDiagnosticHandler(Log log) {
130 this(log, null);
131 }
133 public DeferredDiagnosticHandler(Log log, Filter<JCDiagnostic> filter) {
134 this.filter = filter;
135 install(log);
136 }
138 public void report(JCDiagnostic diag) {
139 if (!diag.isFlagSet(JCDiagnostic.DiagnosticFlag.NON_DEFERRABLE) &&
140 (filter == null || filter.accepts(diag))) {
141 deferred.add(diag);
142 } else {
143 prev.report(diag);
144 }
145 }
147 public Queue<JCDiagnostic> getDiagnostics() {
148 return deferred;
149 }
151 /** Report all deferred diagnostics. */
152 public void reportDeferredDiagnostics() {
153 reportDeferredDiagnostics(EnumSet.allOf(JCDiagnostic.Kind.class));
154 }
156 /** Report selected deferred diagnostics. */
157 public void reportDeferredDiagnostics(Set<JCDiagnostic.Kind> kinds) {
158 JCDiagnostic d;
159 while ((d = deferred.poll()) != null) {
160 if (kinds.contains(d.getKind()))
161 prev.report(d);
162 }
163 deferred = null; // prevent accidental ongoing use
164 }
165 }
167 public enum WriterKind { NOTICE, WARNING, ERROR };
169 protected PrintWriter errWriter;
171 protected PrintWriter warnWriter;
173 protected PrintWriter noticeWriter;
175 /** The maximum number of errors/warnings that are reported.
176 */
177 protected int MaxErrors;
178 protected int MaxWarnings;
180 /** Switch: prompt user on each error.
181 */
182 public boolean promptOnError;
184 /** Switch: emit warning messages.
185 */
186 public boolean emitWarnings;
188 /** Switch: suppress note messages.
189 */
190 public boolean suppressNotes;
192 /** Print stack trace on errors?
193 */
194 public boolean dumpOnError;
196 /** Print multiple errors for same source locations.
197 */
198 public boolean multipleErrors;
200 /**
201 * Diagnostic listener, if provided through programmatic
202 * interface to javac (JSR 199).
203 */
204 protected DiagnosticListener<? super JavaFileObject> diagListener;
206 /**
207 * Formatter for diagnostics.
208 */
209 private DiagnosticFormatter<JCDiagnostic> diagFormatter;
211 /**
212 * Keys for expected diagnostics.
213 */
214 public Set<String> expectDiagKeys;
216 /**
217 * Set to true if a compressed diagnostic is reported
218 */
219 public boolean compressedOutput;
221 /**
222 * JavacMessages object used for localization.
223 */
224 private JavacMessages messages;
226 /**
227 * Handler for initial dispatch of diagnostics.
228 */
229 private DiagnosticHandler diagnosticHandler;
231 /** Construct a log with given I/O redirections.
232 */
233 protected Log(Context context, PrintWriter errWriter, PrintWriter warnWriter, PrintWriter noticeWriter) {
234 super(JCDiagnostic.Factory.instance(context));
235 context.put(logKey, this);
236 this.errWriter = errWriter;
237 this.warnWriter = warnWriter;
238 this.noticeWriter = noticeWriter;
240 @SuppressWarnings("unchecked") // FIXME
241 DiagnosticListener<? super JavaFileObject> dl =
242 context.get(DiagnosticListener.class);
243 this.diagListener = dl;
245 diagnosticHandler = new DefaultDiagnosticHandler();
247 messages = JavacMessages.instance(context);
248 messages.add(Main.javacBundleName);
250 final Options options = Options.instance(context);
251 initOptions(options);
252 options.addListener(new Runnable() {
253 public void run() {
254 initOptions(options);
255 }
256 });
257 }
258 // where
259 private void initOptions(Options options) {
260 this.dumpOnError = options.isSet(DOE);
261 this.promptOnError = options.isSet(PROMPT);
262 this.emitWarnings = options.isUnset(XLINT_CUSTOM, "none");
263 this.suppressNotes = options.isSet("suppressNotes");
264 this.MaxErrors = getIntOption(options, XMAXERRS, getDefaultMaxErrors());
265 this.MaxWarnings = getIntOption(options, XMAXWARNS, getDefaultMaxWarnings());
267 boolean rawDiagnostics = options.isSet("rawDiagnostics");
268 this.diagFormatter = rawDiagnostics ? new RawDiagnosticFormatter(options) :
269 new BasicDiagnosticFormatter(options, messages);
271 String ek = options.get("expectKeys");
272 if (ek != null)
273 expectDiagKeys = new HashSet<String>(Arrays.asList(ek.split(", *")));
274 }
276 private int getIntOption(Options options, Option option, int defaultValue) {
277 String s = options.get(option);
278 try {
279 if (s != null) {
280 int n = Integer.parseInt(s);
281 return (n <= 0 ? Integer.MAX_VALUE : n);
282 }
283 } catch (NumberFormatException e) {
284 // silently ignore ill-formed numbers
285 }
286 return defaultValue;
287 }
289 /** Default value for -Xmaxerrs.
290 */
291 protected int getDefaultMaxErrors() {
292 return 100;
293 }
295 /** Default value for -Xmaxwarns.
296 */
297 protected int getDefaultMaxWarnings() {
298 return 100;
299 }
301 /** The default writer for diagnostics
302 */
303 static PrintWriter defaultWriter(Context context) {
304 PrintWriter result = context.get(outKey);
305 if (result == null)
306 context.put(outKey, result = new PrintWriter(System.err));
307 return result;
308 }
310 /** Construct a log with default settings.
311 */
312 protected Log(Context context) {
313 this(context, defaultWriter(context));
314 }
316 /** Construct a log with all output redirected.
317 */
318 protected Log(Context context, PrintWriter defaultWriter) {
319 this(context, defaultWriter, defaultWriter, defaultWriter);
320 }
322 /** Get the Log instance for this context. */
323 public static Log instance(Context context) {
324 Log instance = context.get(logKey);
325 if (instance == null)
326 instance = new Log(context);
327 return instance;
328 }
330 /** The number of errors encountered so far.
331 */
332 public int nerrors = 0;
334 /** The number of warnings encountered so far.
335 */
336 public int nwarnings = 0;
338 /** A set of all errors generated so far. This is used to avoid printing an
339 * error message more than once. For each error, a pair consisting of the
340 * source file name and source code position of the error is added to the set.
341 */
342 private Set<Pair<JavaFileObject, Integer>> recorded = new HashSet<Pair<JavaFileObject,Integer>>();
344 public boolean hasDiagnosticListener() {
345 return diagListener != null;
346 }
348 public void setEndPosTable(JavaFileObject name, EndPosTable endPosTable) {
349 name.getClass(); // null check
350 getSource(name).setEndPosTable(endPosTable);
351 }
353 /** Return current sourcefile.
354 */
355 public JavaFileObject currentSourceFile() {
356 return source == null ? null : source.getFile();
357 }
359 /** Get the current diagnostic formatter.
360 */
361 public DiagnosticFormatter<JCDiagnostic> getDiagnosticFormatter() {
362 return diagFormatter;
363 }
365 /** Set the current diagnostic formatter.
366 */
367 public void setDiagnosticFormatter(DiagnosticFormatter<JCDiagnostic> diagFormatter) {
368 this.diagFormatter = diagFormatter;
369 }
371 public PrintWriter getWriter(WriterKind kind) {
372 switch (kind) {
373 case NOTICE: return noticeWriter;
374 case WARNING: return warnWriter;
375 case ERROR: return errWriter;
376 default: throw new IllegalArgumentException();
377 }
378 }
380 public void setWriter(WriterKind kind, PrintWriter pw) {
381 pw.getClass();
382 switch (kind) {
383 case NOTICE: noticeWriter = pw; break;
384 case WARNING: warnWriter = pw; break;
385 case ERROR: errWriter = pw; break;
386 default: throw new IllegalArgumentException();
387 }
388 }
390 public void setWriters(PrintWriter pw) {
391 pw.getClass();
392 noticeWriter = warnWriter = errWriter = pw;
393 }
395 /**
396 * Propagate the previous log's information.
397 */
398 public void initRound(Log other) {
399 this.noticeWriter = other.noticeWriter;
400 this.warnWriter = other.warnWriter;
401 this.errWriter = other.errWriter;
402 this.sourceMap = other.sourceMap;
403 this.recorded = other.recorded;
404 this.nerrors = other.nerrors;
405 this.nwarnings = other.nwarnings;
406 }
408 /**
409 * Replace the specified diagnostic handler with the
410 * handler that was current at the time this handler was created.
411 * The given handler must be the currently installed handler;
412 * it must be specified explicitly for clarity and consistency checking.
413 */
414 public void popDiagnosticHandler(DiagnosticHandler h) {
415 Assert.check(diagnosticHandler == h);
416 diagnosticHandler = h.prev;
417 }
419 /** Flush the logs
420 */
421 public void flush() {
422 errWriter.flush();
423 warnWriter.flush();
424 noticeWriter.flush();
425 }
427 public void flush(WriterKind kind) {
428 getWriter(kind).flush();
429 }
431 /** Returns true if an error needs to be reported for a given
432 * source name and pos.
433 */
434 protected boolean shouldReport(JavaFileObject file, int pos) {
435 if (multipleErrors || file == null)
436 return true;
438 Pair<JavaFileObject,Integer> coords = new Pair<JavaFileObject,Integer>(file, pos);
439 boolean shouldReport = !recorded.contains(coords);
440 if (shouldReport)
441 recorded.add(coords);
442 return shouldReport;
443 }
445 /** Prompt user after an error.
446 */
447 public void prompt() {
448 if (promptOnError) {
449 System.err.println(localize("resume.abort"));
450 try {
451 while (true) {
452 switch (System.in.read()) {
453 case 'a': case 'A':
454 System.exit(-1);
455 return;
456 case 'r': case 'R':
457 return;
458 case 'x': case 'X':
459 throw new AssertionError("user abort");
460 default:
461 }
462 }
463 } catch (IOException e) {}
464 }
465 }
467 /** Print the faulty source code line and point to the error.
468 * @param pos Buffer index of the error position, must be on current line
469 */
470 private void printErrLine(int pos, PrintWriter writer) {
471 String line = (source == null ? null : source.getLine(pos));
472 if (line == null)
473 return;
474 int col = source.getColumnNumber(pos, false);
476 printRawLines(writer, line);
477 for (int i = 0; i < col - 1; i++) {
478 writer.print((line.charAt(i) == '\t') ? "\t" : " ");
479 }
480 writer.println("^");
481 writer.flush();
482 }
484 public void printNewline() {
485 noticeWriter.println();
486 }
488 public void printNewline(WriterKind wk) {
489 getWriter(wk).println();
490 }
492 public void printLines(String key, Object... args) {
493 printRawLines(noticeWriter, localize(key, args));
494 }
496 public void printLines(PrefixKind pk, String key, Object... args) {
497 printRawLines(noticeWriter, localize(pk, key, args));
498 }
500 public void printLines(WriterKind wk, String key, Object... args) {
501 printRawLines(getWriter(wk), localize(key, args));
502 }
504 public void printLines(WriterKind wk, PrefixKind pk, String key, Object... args) {
505 printRawLines(getWriter(wk), localize(pk, key, args));
506 }
508 /** Print the text of a message, translating newlines appropriately
509 * for the platform.
510 */
511 public void printRawLines(String msg) {
512 printRawLines(noticeWriter, msg);
513 }
515 /** Print the text of a message, translating newlines appropriately
516 * for the platform.
517 */
518 public void printRawLines(WriterKind kind, String msg) {
519 printRawLines(getWriter(kind), msg);
520 }
522 /** Print the text of a message, translating newlines appropriately
523 * for the platform.
524 */
525 public static void printRawLines(PrintWriter writer, String msg) {
526 int nl;
527 while ((nl = msg.indexOf('\n')) != -1) {
528 writer.println(msg.substring(0, nl));
529 msg = msg.substring(nl+1);
530 }
531 if (msg.length() != 0) writer.println(msg);
532 }
534 /**
535 * Print the localized text of a "verbose" message to the
536 * noticeWriter stream.
537 */
538 public void printVerbose(String key, Object... args) {
539 printRawLines(noticeWriter, localize("verbose." + key, args));
540 }
542 protected void directError(String key, Object... args) {
543 printRawLines(errWriter, localize(key, args));
544 errWriter.flush();
545 }
547 /** Report a warning that cannot be suppressed.
548 * @param pos The source position at which to report the warning.
549 * @param key The key for the localized warning message.
550 * @param args Fields of the warning message.
551 */
552 public void strictWarning(DiagnosticPosition pos, String key, Object ... args) {
553 writeDiagnostic(diags.warning(source, pos, key, args));
554 nwarnings++;
555 }
557 /**
558 * Primary method to report a diagnostic.
559 * @param diagnostic
560 */
561 public void report(JCDiagnostic diagnostic) {
562 diagnosticHandler.report(diagnostic);
563 }
565 /**
566 * Common diagnostic handling.
567 * The diagnostic is counted, and depending on the options and how many diagnostics have been
568 * reported so far, the diagnostic may be handed off to writeDiagnostic.
569 */
570 private class DefaultDiagnosticHandler extends DiagnosticHandler {
571 public void report(JCDiagnostic diagnostic) {
572 if (expectDiagKeys != null)
573 expectDiagKeys.remove(diagnostic.getCode());
575 switch (diagnostic.getType()) {
576 case FRAGMENT:
577 throw new IllegalArgumentException();
579 case NOTE:
580 // Print out notes only when we are permitted to report warnings
581 // Notes are only generated at the end of a compilation, so should be small
582 // in number.
583 if ((emitWarnings || diagnostic.isMandatory()) && !suppressNotes) {
584 writeDiagnostic(diagnostic);
585 }
586 break;
588 case WARNING:
589 if (emitWarnings || diagnostic.isMandatory()) {
590 if (nwarnings < MaxWarnings) {
591 writeDiagnostic(diagnostic);
592 nwarnings++;
593 }
594 }
595 break;
597 case ERROR:
598 if (nerrors < MaxErrors
599 && shouldReport(diagnostic.getSource(), diagnostic.getIntPosition())) {
600 writeDiagnostic(diagnostic);
601 nerrors++;
602 }
603 break;
604 }
605 if (diagnostic.isFlagSet(JCDiagnostic.DiagnosticFlag.COMPRESSED)) {
606 compressedOutput = true;
607 }
608 }
609 }
611 /**
612 * Write out a diagnostic.
613 */
614 protected void writeDiagnostic(JCDiagnostic diag) {
615 if (diagListener != null) {
616 diagListener.report(diag);
617 return;
618 }
620 PrintWriter writer = getWriterForDiagnosticType(diag.getType());
622 printRawLines(writer, diagFormatter.format(diag, messages.getCurrentLocale()));
624 if (promptOnError) {
625 switch (diag.getType()) {
626 case ERROR:
627 case WARNING:
628 prompt();
629 }
630 }
632 if (dumpOnError)
633 new RuntimeException().printStackTrace(writer);
635 writer.flush();
636 }
638 @Deprecated
639 protected PrintWriter getWriterForDiagnosticType(DiagnosticType dt) {
640 switch (dt) {
641 case FRAGMENT:
642 throw new IllegalArgumentException();
644 case NOTE:
645 return noticeWriter;
647 case WARNING:
648 return warnWriter;
650 case ERROR:
651 return errWriter;
653 default:
654 throw new Error();
655 }
656 }
658 /** Find a localized string in the resource bundle.
659 * Because this method is static, it ignores the locale.
660 * Use localize(key, args) when possible.
661 * @param key The key for the localized string.
662 * @param args Fields to substitute into the string.
663 */
664 public static String getLocalizedString(String key, Object ... args) {
665 return JavacMessages.getDefaultLocalizedString(PrefixKind.COMPILER_MISC.key(key), args);
666 }
668 /** Find a localized string in the resource bundle.
669 * @param key The key for the localized string.
670 * @param args Fields to substitute into the string.
671 */
672 public String localize(String key, Object... args) {
673 return localize(PrefixKind.COMPILER_MISC, key, args);
674 }
676 /** Find a localized string in the resource bundle.
677 * @param key The key for the localized string.
678 * @param args Fields to substitute into the string.
679 */
680 public String localize(PrefixKind pk, String key, Object... args) {
681 if (useRawMessages)
682 return pk.key(key);
683 else
684 return messages.getLocalizedString(pk.key(key), args);
685 }
686 // where
687 // backdoor hook for testing, should transition to use -XDrawDiagnostics
688 private static boolean useRawMessages = false;
690 /***************************************************************************
691 * raw error messages without internationalization; used for experimentation
692 * and quick prototyping
693 ***************************************************************************/
695 /** print an error or warning message:
696 */
697 private void printRawError(int pos, String msg) {
698 if (source == null || pos == Position.NOPOS) {
699 printRawLines(errWriter, "error: " + msg);
700 } else {
701 int line = source.getLineNumber(pos);
702 JavaFileObject file = source.getFile();
703 if (file != null)
704 printRawLines(errWriter,
705 file.getName() + ":" +
706 line + ": " + msg);
707 printErrLine(pos, errWriter);
708 }
709 errWriter.flush();
710 }
712 /** report an error:
713 */
714 public void rawError(int pos, String msg) {
715 if (nerrors < MaxErrors && shouldReport(currentSourceFile(), pos)) {
716 printRawError(pos, msg);
717 prompt();
718 nerrors++;
719 }
720 errWriter.flush();
721 }
723 /** report a warning:
724 */
725 public void rawWarning(int pos, String msg) {
726 if (nwarnings < MaxWarnings && emitWarnings) {
727 printRawError(pos, "warning: " + msg);
728 }
729 prompt();
730 nwarnings++;
731 errWriter.flush();
732 }
734 public static String format(String fmt, Object... args) {
735 return String.format((java.util.Locale)null, fmt, args);
736 }
738 }