001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.tools.bugreport;
003
004import java.io.PrintWriter;
005import java.io.Serializable;
006import java.lang.reflect.InvocationTargetException;
007import java.nio.file.InvalidPathException;
008import java.util.ArrayList;
009import java.util.Arrays;
010import java.util.Collection;
011import java.util.Collections;
012import java.util.ConcurrentModificationException;
013import java.util.HashMap;
014import java.util.IdentityHashMap;
015import java.util.Iterator;
016import java.util.LinkedList;
017import java.util.Map;
018import java.util.Map.Entry;
019import java.util.NoSuchElementException;
020import java.util.Set;
021import java.util.function.Supplier;
022
023import org.openstreetmap.josm.tools.Logging;
024import org.openstreetmap.josm.tools.StreamUtils;
025import org.openstreetmap.josm.tools.Utils;
026
027/**
028 * This is a special exception that cannot be directly thrown.
029 * <p>
030 * It is used to capture more information about an exception that was already thrown.
031 *
032 * @author Michael Zangl
033 * @see BugReport
034 * @since 10285
035 */
036public class ReportedException extends RuntimeException {
037    /**
038     * How many entries of a collection to include in the bug report.
039     */
040    private static final int MAX_COLLECTION_ENTRIES = 30;
041
042    private static final long serialVersionUID = 737333873766201033L;
043
044    /**
045     * We capture all stack traces on exception creation. This allows us to trace synchronization problems better.
046     * We cannot be really sure what happened but we at least see which threads
047     */
048    private final transient Map<Thread, StackTraceElement[]> allStackTraces = new HashMap<>();
049    private final LinkedList<Section> sections = new LinkedList<>();
050    private final transient Thread caughtOnThread;
051    private String methodWarningFrom;
052
053    /**
054     * Constructs a new {@code ReportedException}.
055     * @param exception the cause (which is saved for later retrieval by the {@link #getCause()} method)
056     * @since 14380
057     */
058    public ReportedException(Throwable exception) {
059        this(exception, Thread.currentThread());
060    }
061
062    /**
063     * Constructs a new {@code ReportedException}.
064     * @param exception the cause (which is saved for later retrieval by the {@link #getCause()} method)
065     * @param caughtOnThread thread where the exception was caught
066     * @since 14380
067     */
068    public ReportedException(Throwable exception, Thread caughtOnThread) {
069        super(exception);
070
071        try {
072            allStackTraces.putAll(Thread.getAllStackTraces());
073        } catch (SecurityException e) {
074            Logging.log(Logging.LEVEL_ERROR, "Unable to get thread stack traces", e);
075        }
076        this.caughtOnThread = caughtOnThread;
077    }
078
079    /**
080     * Displays a warning for this exception. The program can then continue normally. Does not block.
081     */
082    public void warn() {
083        methodWarningFrom = BugReport.getCallingMethod(2);
084        try {
085            BugReportQueue.getInstance().submit(this);
086        } catch (RuntimeException e) {
087            Logging.error(e);
088        }
089    }
090
091    /**
092     * Starts a new debug data section. This normally does not need to be called manually.
093     *
094     * @param sectionName
095     *            The section name.
096     */
097    public void startSection(String sectionName) {
098        sections.add(new Section(sectionName));
099    }
100
101    /**
102     * Prints the captured data of this report to a {@link PrintWriter}.
103     *
104     * @param out
105     *            The writer to print to.
106     */
107    public void printReportDataTo(PrintWriter out) {
108        out.println("=== REPORTED CRASH DATA ===");
109        for (Section s : sections) {
110            s.printSection(out);
111            out.println();
112        }
113
114        if (methodWarningFrom != null) {
115            out.println("Warning issued by: " + methodWarningFrom);
116            out.println();
117        }
118    }
119
120    /**
121     * Prints the stack trace of this report to a {@link PrintWriter}.
122     *
123     * @param out
124     *            The writer to print to.
125     */
126    public void printReportStackTo(PrintWriter out) {
127        out.println("=== STACK TRACE ===");
128        out.println(niceThreadName(caughtOnThread));
129        getCause().printStackTrace(out);
130        out.println();
131    }
132
133    /**
134     * Prints the stack traces for other threads of this report to a {@link PrintWriter}.
135     *
136     * @param out
137     *            The writer to print to.
138     */
139    public void printReportThreadsTo(PrintWriter out) {
140        out.println("=== RUNNING THREADS ===");
141        for (Entry<Thread, StackTraceElement[]> thread : allStackTraces.entrySet()) {
142            out.println(niceThreadName(thread.getKey()));
143            if (caughtOnThread.equals(thread.getKey())) {
144                out.println("Stacktrace see above.");
145            } else {
146                for (StackTraceElement e : thread.getValue()) {
147                    out.println(e);
148                }
149            }
150            out.println();
151        }
152    }
153
154    private static String niceThreadName(Thread thread) {
155        StringBuilder name = new StringBuilder("Thread: ").append(thread.getName()).append(" (").append(thread.getId()).append(')');
156        ThreadGroup threadGroup = thread.getThreadGroup();
157        if (threadGroup != null) {
158            name.append(" of ").append(threadGroup.getName());
159        }
160        return name.toString();
161    }
162
163    /**
164     * Checks if this exception is considered the same as an other exception. This is the case if both have the same cause and message.
165     *
166     * @param e
167     *            The exception to check against.
168     * @return <code>true</code> if they are considered the same.
169     */
170    public boolean isSame(ReportedException e) {
171        return getMessage().equals(e.getMessage()) && hasSameStackTrace(new CauseTraceIterator(), e.getCause());
172    }
173
174    private static boolean hasSameStackTrace(CauseTraceIterator causeTraceIterator, Throwable e2) {
175        if (!causeTraceIterator.hasNext()) {
176            // all done.
177            return true;
178        }
179        Throwable e1 = causeTraceIterator.next();
180        StackTraceElement[] t1 = e1.getStackTrace();
181        StackTraceElement[] t2 = e2.getStackTrace();
182
183        if (!Arrays.equals(t1, t2)) {
184            return false;
185        }
186
187        Throwable c1 = e1.getCause();
188        Throwable c2 = e2.getCause();
189        if ((c1 == null) != (c2 == null)) {
190            return false;
191        }
192        return c1 == null || hasSameStackTrace(causeTraceIterator, c2);
193    }
194
195    /**
196     * Adds some debug values to this exception. The value is converted to a string. Errors during conversion are handled.
197     *
198     * @param key
199     *            The key to add this for. Does not need to be unique but it would be nice.
200     * @param value
201     *            The value.
202     * @return This exception for easy chaining.
203     */
204    public ReportedException put(String key, Object value) {
205        return put(key, () -> value);
206    }
207
208    /**
209    * Adds some debug values to this exception. This method automatically catches errors that occur during the production of the value.
210    *
211    * @param key
212    *            The key to add this for. Does not need to be unique but it would be nice.
213    * @param valueSupplier
214    *            A supplier that is called once to get the value.
215    * @return This exception for easy chaining.
216    * @since 10586
217    */
218    public ReportedException put(String key, Supplier<Object> valueSupplier) {
219        String string;
220        try {
221            Object value = valueSupplier.get();
222            if (value == null) {
223                string = "null";
224            } else if (value instanceof Collection) {
225                string = makeCollectionNice((Collection<?>) value);
226            } else if (value.getClass().isArray()) {
227                string = makeCollectionNice(Collections.singleton(value));
228            } else {
229                string = value.toString();
230            }
231        } catch (RuntimeException t) {
232            Logging.warn(t);
233            string = "<Error calling toString()>";
234        }
235        sections.getLast().put(key, string);
236        return this;
237    }
238
239    private static String makeCollectionNice(Collection<?> value) {
240        int lines = 0;
241        StringBuilder str = new StringBuilder(32);
242        for (Object e : value) {
243            str.append("\n    - ");
244            if (lines <= MAX_COLLECTION_ENTRIES) {
245                ++lines;
246                str.append(e);
247            } else {
248                str.append("\n    ... (")
249                   .append(value.size())
250                   .append(" entries)");
251                break;
252            }
253        }
254        return str.toString();
255    }
256
257    @Override
258    public String toString() {
259        return "ReportedException [thread=" + caughtOnThread + ", exception=" + getCause()
260                + ", methodWarningFrom=" + methodWarningFrom + ']';
261    }
262
263    /**
264     * Check if this exception may be caused by a threading issue.
265     * @return <code>true</code> if it is.
266     * @since 10585
267     */
268    public boolean mayHaveConcurrentSource() {
269        return StreamUtils.toStream(CauseTraceIterator::new)
270                .anyMatch(t -> t instanceof ConcurrentModificationException || t instanceof InvocationTargetException);
271    }
272
273    /**
274     * Check if this is caused by an out of memory situation
275     * @return <code>true</code> if it is.
276     * @since 10819
277     */
278    public boolean isOutOfMemory() {
279        return StreamUtils.toStream(CauseTraceIterator::new).anyMatch(OutOfMemoryError.class::isInstance);
280    }
281
282    /**
283     * Check if this is caused by the name of a file which cannot be represented in the character set Java uses for
284     * file names. Java takes that character set from the locale, so this happens when JOSM runs in the C/POSIX locale,
285     * or with a locale which is not installed: file names are then ASCII only, and opening a folder which holds a
286     * non-ASCII name fails. See #14596.
287     * @return <code>true</code> if it is.
288     * @since 19637
289     */
290    public boolean isUnmappableFileName() {
291        return !"UTF-8".equalsIgnoreCase(Utils.getSystemProperty("sun.jnu.encoding"))
292                && StreamUtils.toStream(CauseTraceIterator::new).anyMatch(t -> t instanceof InvalidPathException
293                        && String.valueOf(((InvalidPathException) t).getReason()).contains("unmappable characters"));
294    }
295
296    /**
297     * Iterates over the causes for this exception. Ignores cycles and aborts iteration then.
298     * @author Michal Zangl
299     * @since 10585
300     */
301    private final class CauseTraceIterator implements Iterator<Throwable> {
302        private Throwable current = getCause();
303        private final Set<Throwable> dejaVu = Collections.newSetFromMap(new IdentityHashMap<>());
304
305        @Override
306        public boolean hasNext() {
307            return current != null;
308        }
309
310        @Override
311        public Throwable next() {
312            if (!hasNext()) {
313                throw new NoSuchElementException();
314            }
315            Throwable toReturn = current;
316            advance();
317            return toReturn;
318        }
319
320        private void advance() {
321            dejaVu.add(current);
322            current = current.getCause();
323            if (current != null && dejaVu.contains(current)) {
324                current = null;
325            }
326        }
327    }
328
329    private static class SectionEntry implements Serializable {
330
331        private static final long serialVersionUID = 1L;
332
333        private final String key;
334        private final String value;
335
336        SectionEntry(String key, String value) {
337            this.key = key;
338            this.value = value;
339        }
340
341        /**
342         * Prints this entry to the output stream in a line.
343         * @param out The stream to print to.
344         */
345        public void print(PrintWriter out) {
346            out.print(" - ");
347            out.print(key);
348            out.print(": ");
349            out.println(value);
350        }
351    }
352
353    private static class Section implements Serializable {
354
355        private static final long serialVersionUID = 1L;
356
357        private final String sectionName;
358        private final ArrayList<SectionEntry> entries = new ArrayList<>();
359
360        Section(String sectionName) {
361            this.sectionName = sectionName;
362        }
363
364        /**
365         * Add a key/value entry to this section.
366         * @param key The key. Need not be unique.
367         * @param value The value.
368         */
369        public void put(String key, String value) {
370            entries.add(new SectionEntry(key, value));
371        }
372
373        /**
374         * Prints this section to the output stream.
375         * @param out The stream to print to.
376         */
377        public void printSection(PrintWriter out) {
378            out.println(sectionName + ':');
379            if (entries.isEmpty()) {
380                out.println("No data collected.");
381            } else {
382                for (SectionEntry e : entries) {
383                    e.print(out);
384                }
385            }
386        }
387    }
388}