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