BaseFileManager.java revision 3656:238ab021ff4d
1/*
2 * Copyright (c) 2009, 2016, 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 */
25
26package com.sun.tools.javac.file;
27
28import java.io.IOException;
29import java.io.InputStream;
30import java.lang.ref.SoftReference;
31import java.lang.reflect.Constructor;
32import java.lang.reflect.Method;
33import java.net.URL;
34import java.net.URLClassLoader;
35import java.nio.ByteBuffer;
36import java.nio.CharBuffer;
37import java.nio.charset.Charset;
38import java.nio.charset.CharsetDecoder;
39import java.nio.charset.CoderResult;
40import java.nio.charset.CodingErrorAction;
41import java.nio.charset.IllegalCharsetNameException;
42import java.nio.charset.UnsupportedCharsetException;
43import java.nio.file.Path;
44import java.util.Collection;
45import java.util.HashMap;
46import java.util.Iterator;
47import java.util.Map;
48import java.util.Objects;
49import java.util.Set;
50
51import javax.tools.JavaFileManager;
52import javax.tools.JavaFileObject;
53import javax.tools.JavaFileObject.Kind;
54
55import com.sun.tools.javac.code.Lint;
56import com.sun.tools.javac.code.Source;
57import com.sun.tools.javac.main.Option;
58import com.sun.tools.javac.main.OptionHelper;
59import com.sun.tools.javac.main.OptionHelper.GrumpyHelper;
60import com.sun.tools.javac.resources.CompilerProperties.Errors;
61import com.sun.tools.javac.util.Abort;
62import com.sun.tools.javac.util.Context;
63import com.sun.tools.javac.util.DefinedBy;
64import com.sun.tools.javac.util.DefinedBy.Api;
65import com.sun.tools.javac.util.Log;
66import com.sun.tools.javac.util.Options;
67
68/**
69 * Utility methods for building a filemanager.
70 * There are no references here to file-system specific objects such as
71 * java.io.File or java.nio.file.Path.
72 */
73public abstract class BaseFileManager implements JavaFileManager {
74    protected BaseFileManager(Charset charset) {
75        this.charset = charset;
76        byteBufferCache = new ByteBufferCache();
77        locations = createLocations();
78    }
79
80    /**
81     * Set the context for JavacPathFileManager.
82     * @param context the context containing items to be associated with the file manager
83     */
84    public void setContext(Context context) {
85        log = Log.instance(context);
86        options = Options.instance(context);
87        classLoaderClass = options.get("procloader");
88        locations.update(log, Lint.instance(context), FSInfo.instance(context));
89
90        // Setting this option is an indication that close() should defer actually closing
91        // the file manager until after a specified period of inactivity.
92        // This is to accomodate clients which save references to Symbols created for use
93        // within doclets or annotation processors, and which then attempt to use those
94        // references after the tool exits, having closed any internally managed file manager.
95        // Ideally, such clients should run the tool via the javax.tools API, providing their
96        // own file manager, which can be closed by the client when all use of that file
97        // manager is complete.
98        // If the option has a numeric value, it will be interpreted as the duration,
99        // in seconds, of the period of inactivity to wait for, before the file manager
100        // is actually closed.
101        // See also deferredClose().
102        String s = options.get("fileManager.deferClose");
103        if (s != null) {
104            try {
105                deferredCloseTimeout = (int) (Float.parseFloat(s) * 1000);
106            } catch (NumberFormatException e) {
107                deferredCloseTimeout = 60 * 1000;  // default: one minute, in millis
108            }
109        }
110    }
111
112    protected Locations createLocations() {
113        return new Locations();
114    }
115
116    /**
117     * The log to be used for error reporting.
118     */
119    public Log log;
120
121    /**
122     * User provided charset (through javax.tools).
123     */
124    protected Charset charset;
125
126    protected Options options;
127
128    protected String classLoaderClass;
129
130    protected Locations locations;
131
132    /**
133     * A flag for clients to use to indicate that this file manager should
134     * be closed when it is no longer required.
135     */
136    public boolean autoClose;
137
138    /**
139     * Wait for a period of inactivity before calling close().
140     * The length of the period of inactivity is given by {@code deferredCloseTimeout}
141     */
142    protected void deferredClose() {
143        Thread t = new Thread(getClass().getName() + " DeferredClose") {
144            @Override
145            public void run() {
146                try {
147                    synchronized (BaseFileManager.this) {
148                        long now = System.currentTimeMillis();
149                        while (now < lastUsedTime + deferredCloseTimeout) {
150                            BaseFileManager.this.wait(lastUsedTime + deferredCloseTimeout - now);
151                            now = System.currentTimeMillis();
152                        }
153                        deferredCloseTimeout = 0;
154                        close();
155                    }
156                } catch (InterruptedException e) {
157                } catch (IOException e) {
158                }
159            }
160        };
161        t.setDaemon(true);
162        t.start();
163    }
164
165    synchronized void updateLastUsedTime() {
166        if (deferredCloseTimeout > 0) { // avoid updating the time unnecessarily
167            lastUsedTime = System.currentTimeMillis();
168        }
169    }
170
171    private long lastUsedTime = System.currentTimeMillis();
172    protected long deferredCloseTimeout = 0;
173
174    protected Source getSource() {
175        String sourceName = options.get(Option.SOURCE);
176        Source source = null;
177        if (sourceName != null)
178            source = Source.lookup(sourceName);
179        return (source != null ? source : Source.DEFAULT);
180    }
181
182    protected ClassLoader getClassLoader(URL[] urls) {
183        ClassLoader thisClassLoader = getClass().getClassLoader();
184
185        // Allow the following to specify a closeable classloader
186        // other than URLClassLoader.
187
188        // 1: Allow client to specify the class to use via hidden option
189        if (classLoaderClass != null) {
190            try {
191                Class<? extends ClassLoader> loader =
192                        Class.forName(classLoaderClass).asSubclass(ClassLoader.class);
193                Class<?>[] constrArgTypes = { URL[].class, ClassLoader.class };
194                Constructor<? extends ClassLoader> constr = loader.getConstructor(constrArgTypes);
195                return ensureReadable(constr.newInstance(urls, thisClassLoader));
196            } catch (ReflectiveOperationException t) {
197                // ignore errors loading user-provided class loader, fall through
198            }
199        }
200        return ensureReadable(new URLClassLoader(urls, thisClassLoader));
201    }
202
203    /**
204     * Ensures that the unnamed module of the given classloader is readable to this
205     * module.
206     */
207    private ClassLoader ensureReadable(ClassLoader targetLoader) {
208        try {
209            Method getModuleMethod = Class.class.getMethod("getModule");
210            Object thisModule = getModuleMethod.invoke(this.getClass());
211            Method getUnnamedModuleMethod = ClassLoader.class.getMethod("getUnnamedModule");
212            Object targetModule = getUnnamedModuleMethod.invoke(targetLoader);
213
214            Class<?> moduleClass = getModuleMethod.getReturnType();
215            Method addReadsMethod = moduleClass.getMethod("addReads", moduleClass);
216            addReadsMethod.invoke(thisModule, targetModule);
217        } catch (NoSuchMethodException e) {
218            // ignore
219        } catch (Exception e) {
220            throw new Abort(e);
221        }
222        return targetLoader;
223    }
224
225    public boolean isDefaultBootClassPath() {
226        return locations.isDefaultBootClassPath();
227    }
228
229    // <editor-fold defaultstate="collapsed" desc="Option handling">
230    @Override @DefinedBy(Api.COMPILER)
231    public boolean handleOption(String current, Iterator<String> remaining) {
232        OptionHelper helper = new GrumpyHelper(log) {
233            @Override
234            public String get(Option option) {
235                return options.get(option);
236            }
237
238            @Override
239            public void put(String name, String value) {
240                options.put(name, value);
241            }
242
243            @Override
244            public void remove(String name) {
245                options.remove(name);
246            }
247
248            @Override
249            public boolean handleFileManagerOption(Option option, String value) {
250                return handleOption(option, value);
251            }
252        };
253
254        Option o = Option.lookup(current, javacFileManagerOptions);
255        if (o == null) {
256            return false;
257        }
258
259        if (!o.handleOption(helper, current, remaining))
260            throw new IllegalArgumentException(current);
261
262        return true;
263    }
264    // where
265        private static final Set<Option> javacFileManagerOptions =
266            Option.getJavacFileManagerOptions();
267
268    @Override @DefinedBy(Api.COMPILER)
269    public int isSupportedOption(String option) {
270        Option o = Option.lookup(option, javacFileManagerOptions);
271        return (o == null) ? -1 : o.hasArg() ? 1 : 0;
272    }
273
274    protected String multiReleaseValue;
275
276    /**
277     * Common back end for OptionHelper handleFileManagerOption.
278     * @param option the option whose value to be set
279     * @param value the value for the option
280     * @return true if successful, and false otherwise
281     */
282    public boolean handleOption(Option option, String value) {
283        switch (option) {
284            case ENCODING:
285                encodingName = value;
286                return true;
287
288            case MULTIRELEASE:
289                multiReleaseValue = value;
290                locations.setMultiReleaseValue(value);
291                return true;
292
293            default:
294                return locations.handleOption(option, value);
295        }
296    }
297
298    /**
299     * Call handleOption for collection of options and corresponding values.
300     * @param map a collection of options and corresponding values
301     * @return true if all the calls are successful
302     */
303    public boolean handleOptions(Map<Option, String> map) {
304        boolean ok = true;
305        for (Map.Entry<Option, String> e: map.entrySet()) {
306            try {
307                ok = ok & handleOption(e.getKey(), e.getValue());
308            } catch (IllegalArgumentException ex) {
309                log.error(Errors.IllegalArgumentForOption(e.getKey().getPrimaryName(), ex.getMessage()));
310                ok = false;
311            }
312        }
313        return ok;
314    }
315
316    // </editor-fold>
317
318    // <editor-fold defaultstate="collapsed" desc="Encoding">
319    private String encodingName;
320    private String defaultEncodingName;
321    private String getDefaultEncodingName() {
322        if (defaultEncodingName == null) {
323            defaultEncodingName = Charset.defaultCharset().name();
324        }
325        return defaultEncodingName;
326    }
327
328    public String getEncodingName() {
329        return (encodingName != null) ? encodingName : getDefaultEncodingName();
330    }
331
332    @SuppressWarnings("cast")
333    public CharBuffer decode(ByteBuffer inbuf, boolean ignoreEncodingErrors) {
334        String encodingName = getEncodingName();
335        CharsetDecoder decoder;
336        try {
337            decoder = getDecoder(encodingName, ignoreEncodingErrors);
338        } catch (IllegalCharsetNameException | UnsupportedCharsetException e) {
339            log.error("unsupported.encoding", encodingName);
340            return (CharBuffer)CharBuffer.allocate(1).flip();
341        }
342
343        // slightly overestimate the buffer size to avoid reallocation.
344        float factor =
345            decoder.averageCharsPerByte() * 0.8f +
346            decoder.maxCharsPerByte() * 0.2f;
347        CharBuffer dest = CharBuffer.
348            allocate(10 + (int)(inbuf.remaining()*factor));
349
350        while (true) {
351            CoderResult result = decoder.decode(inbuf, dest, true);
352            dest.flip();
353
354            if (result.isUnderflow()) { // done reading
355                // make sure there is at least one extra character
356                if (dest.limit() == dest.capacity()) {
357                    dest = CharBuffer.allocate(dest.capacity()+1).put(dest);
358                    dest.flip();
359                }
360                return dest;
361            } else if (result.isOverflow()) { // buffer too small; expand
362                int newCapacity =
363                    10 + dest.capacity() +
364                    (int)(inbuf.remaining()*decoder.maxCharsPerByte());
365                dest = CharBuffer.allocate(newCapacity).put(dest);
366            } else if (result.isMalformed() || result.isUnmappable()) {
367                // bad character in input
368                StringBuilder unmappable = new StringBuilder();
369                int len = result.length();
370
371                for (int i = 0; i < len; i++) {
372                    unmappable.append(String.format("%02X", inbuf.get()));
373                }
374
375                String charsetName = charset == null ? encodingName : charset.name();
376
377                log.error(dest.limit(),
378                          Errors.IllegalCharForEncoding(unmappable.toString(), charsetName));
379
380                // undo the flip() to prepare the output buffer
381                // for more translation
382                dest.position(dest.limit());
383                dest.limit(dest.capacity());
384                dest.put((char)0xfffd); // backward compatible
385            } else {
386                throw new AssertionError(result);
387            }
388        }
389        // unreached
390    }
391
392    public CharsetDecoder getDecoder(String encodingName, boolean ignoreEncodingErrors) {
393        Charset cs = (this.charset == null)
394            ? Charset.forName(encodingName)
395            : this.charset;
396        CharsetDecoder decoder = cs.newDecoder();
397
398        CodingErrorAction action;
399        if (ignoreEncodingErrors)
400            action = CodingErrorAction.REPLACE;
401        else
402            action = CodingErrorAction.REPORT;
403
404        return decoder
405            .onMalformedInput(action)
406            .onUnmappableCharacter(action);
407    }
408    // </editor-fold>
409
410    // <editor-fold defaultstate="collapsed" desc="ByteBuffers">
411    /**
412     * Make a byte buffer from an input stream.
413     * @param in the stream
414     * @return a byte buffer containing the contents of the stream
415     * @throws IOException if an error occurred while reading the stream
416     */
417    @SuppressWarnings("cast")
418    public ByteBuffer makeByteBuffer(InputStream in)
419        throws IOException {
420        int limit = in.available();
421        if (limit < 1024) limit = 1024;
422        ByteBuffer result = byteBufferCache.get(limit);
423        int position = 0;
424        while (in.available() != 0) {
425            if (position >= limit)
426                // expand buffer
427                result = ByteBuffer.
428                    allocate(limit <<= 1).
429                    put((ByteBuffer)result.flip());
430            int count = in.read(result.array(),
431                position,
432                limit - position);
433            if (count < 0) break;
434            result.position(position += count);
435        }
436        return (ByteBuffer)result.flip();
437    }
438
439    public void recycleByteBuffer(ByteBuffer bb) {
440        byteBufferCache.put(bb);
441    }
442
443    /**
444     * A single-element cache of direct byte buffers.
445     */
446    @SuppressWarnings("cast")
447    private static class ByteBufferCache {
448        private ByteBuffer cached;
449        ByteBuffer get(int capacity) {
450            if (capacity < 20480) capacity = 20480;
451            ByteBuffer result =
452                (cached != null && cached.capacity() >= capacity)
453                ? (ByteBuffer)cached.clear()
454                : ByteBuffer.allocate(capacity + capacity>>1);
455            cached = null;
456            return result;
457        }
458        void put(ByteBuffer x) {
459            cached = x;
460        }
461    }
462
463    private final ByteBufferCache byteBufferCache;
464    // </editor-fold>
465
466    // <editor-fold defaultstate="collapsed" desc="Content cache">
467    public CharBuffer getCachedContent(JavaFileObject file) {
468        ContentCacheEntry e = contentCache.get(file);
469        if (e == null)
470            return null;
471
472        if (!e.isValid(file)) {
473            contentCache.remove(file);
474            return null;
475        }
476
477        return e.getValue();
478    }
479
480    public void cache(JavaFileObject file, CharBuffer cb) {
481        contentCache.put(file, new ContentCacheEntry(file, cb));
482    }
483
484    public void flushCache(JavaFileObject file) {
485        contentCache.remove(file);
486    }
487
488    protected final Map<JavaFileObject, ContentCacheEntry> contentCache = new HashMap<>();
489
490    protected static class ContentCacheEntry {
491        final long timestamp;
492        final SoftReference<CharBuffer> ref;
493
494        ContentCacheEntry(JavaFileObject file, CharBuffer cb) {
495            this.timestamp = file.getLastModified();
496            this.ref = new SoftReference<>(cb);
497        }
498
499        boolean isValid(JavaFileObject file) {
500            return timestamp == file.getLastModified();
501        }
502
503        CharBuffer getValue() {
504            return ref.get();
505        }
506    }
507    // </editor-fold>
508
509    public static Kind getKind(Path path) {
510        return getKind(path.getFileName().toString());
511    }
512
513    public static Kind getKind(String name) {
514        if (name.endsWith(Kind.CLASS.extension))
515            return Kind.CLASS;
516        else if (name.endsWith(Kind.SOURCE.extension))
517            return Kind.SOURCE;
518        else if (name.endsWith(Kind.HTML.extension))
519            return Kind.HTML;
520        else
521            return Kind.OTHER;
522    }
523
524    protected static <T> T nullCheck(T o) {
525        return Objects.requireNonNull(o);
526    }
527
528    protected static <T> Collection<T> nullCheck(Collection<T> it) {
529        for (T t : it)
530            Objects.requireNonNull(t);
531        return it;
532    }
533}
534