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 
  26 package com.sun.tools.javac.file;
  27 
  28 import java.io.IOException;
  29 import java.io.InputStream;
  30 import java.lang.ref.SoftReference;
  31 import java.lang.reflect.Constructor;
  32 import java.lang.reflect.Method;
  33 import java.net.URL;
  34 import java.net.URLClassLoader;
  35 import java.nio.ByteBuffer;
  36 import java.nio.CharBuffer;
  37 import java.nio.charset.Charset;
  38 import java.nio.charset.CharsetDecoder;
  39 import java.nio.charset.CoderResult;
  40 import java.nio.charset.CodingErrorAction;
  41 import java.nio.charset.IllegalCharsetNameException;
  42 import java.nio.charset.UnsupportedCharsetException;
  43 import java.nio.file.Path;
  44 import java.util.Collection;
  45 import java.util.HashMap;
  46 import java.util.Iterator;
  47 import java.util.Map;
  48 import java.util.Objects;
  49 import java.util.Set;
  50 
  51 import javax.tools.JavaFileManager;
  52 import javax.tools.JavaFileObject;
  53 import javax.tools.JavaFileObject.Kind;
  54 
  55 import com.sun.tools.javac.code.Lint;
  56 import com.sun.tools.javac.code.Source;
  57 import com.sun.tools.javac.main.Option;
  58 import com.sun.tools.javac.main.OptionHelper;
  59 import com.sun.tools.javac.main.OptionHelper.GrumpyHelper;
  60 import com.sun.tools.javac.resources.CompilerProperties.Errors;
  61 import com.sun.tools.javac.util.Abort;
  62 import com.sun.tools.javac.util.Context;
  63 import com.sun.tools.javac.util.DefinedBy;
  64 import com.sun.tools.javac.util.DefinedBy.Api;
  65 import com.sun.tools.javac.util.Log;
  66 import 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  */
  73 public 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                 return true;
 291 
 292             default:
 293                 return locations.handleOption(option, value);
 294         }
 295     }
 296 
 297     /**
 298      * Call handleOption for collection of options and corresponding values.
 299      * @param map a collection of options and corresponding values
 300      * @return true if all the calls are successful
 301      */
 302     public boolean handleOptions(Map<Option, String> map) {
 303         boolean ok = true;
 304         for (Map.Entry<Option, String> e: map.entrySet()) {
 305             try {
 306                 ok = ok & handleOption(e.getKey(), e.getValue());
 307             } catch (IllegalArgumentException ex) {
 308                 log.error(Errors.IllegalArgumentForOption(e.getKey().getPrimaryName(), ex.getMessage()));
 309                 ok = false;
 310             }
 311         }
 312         return ok;
 313     }
 314 
 315     // </editor-fold>
 316 
 317     // <editor-fold defaultstate="collapsed" desc="Encoding">
 318     private String encodingName;
 319     private String defaultEncodingName;
 320     private String getDefaultEncodingName() {
 321         if (defaultEncodingName == null) {
 322             defaultEncodingName = Charset.defaultCharset().name();
 323         }
 324         return defaultEncodingName;
 325     }
 326 
 327     public String getEncodingName() {
 328         return (encodingName != null) ? encodingName : getDefaultEncodingName();
 329     }
 330 
 331     @SuppressWarnings("cast")
 332     public CharBuffer decode(ByteBuffer inbuf, boolean ignoreEncodingErrors) {
 333         String encodingName = getEncodingName();
 334         CharsetDecoder decoder;
 335         try {
 336             decoder = getDecoder(encodingName, ignoreEncodingErrors);
 337         } catch (IllegalCharsetNameException | UnsupportedCharsetException e) {
 338             log.error("unsupported.encoding", encodingName);
 339             return (CharBuffer)CharBuffer.allocate(1).flip();
 340         }
 341 
 342         // slightly overestimate the buffer size to avoid reallocation.
 343         float factor =
 344             decoder.averageCharsPerByte() * 0.8f +
 345             decoder.maxCharsPerByte() * 0.2f;
 346         CharBuffer dest = CharBuffer.
 347             allocate(10 + (int)(inbuf.remaining()*factor));
 348 
 349         while (true) {
 350             CoderResult result = decoder.decode(inbuf, dest, true);
 351             dest.flip();
 352 
 353             if (result.isUnderflow()) { // done reading
 354                 // make sure there is at least one extra character
 355                 if (dest.limit() == dest.capacity()) {
 356                     dest = CharBuffer.allocate(dest.capacity()+1).put(dest);
 357                     dest.flip();
 358                 }
 359                 return dest;
 360             } else if (result.isOverflow()) { // buffer too small; expand
 361                 int newCapacity =
 362                     10 + dest.capacity() +
 363                     (int)(inbuf.remaining()*decoder.maxCharsPerByte());
 364                 dest = CharBuffer.allocate(newCapacity).put(dest);
 365             } else if (result.isMalformed() || result.isUnmappable()) {
 366                 // bad character in input
 367                 StringBuilder unmappable = new StringBuilder();
 368                 int len = result.length();
 369 
 370                 for (int i = 0; i < len; i++) {
 371                     unmappable.append(String.format("%02X", inbuf.get()));
 372                 }
 373 
 374                 String charsetName = charset == null ? encodingName : charset.name();
 375 
 376                 log.error(dest.limit(),
 377                           Errors.IllegalCharForEncoding(unmappable.toString(), charsetName));
 378 
 379                 // undo the flip() to prepare the output buffer
 380                 // for more translation
 381                 dest.position(dest.limit());
 382                 dest.limit(dest.capacity());
 383                 dest.put((char)0xfffd); // backward compatible
 384             } else {
 385                 throw new AssertionError(result);
 386             }
 387         }
 388         // unreached
 389     }
 390 
 391     public CharsetDecoder getDecoder(String encodingName, boolean ignoreEncodingErrors) {
 392         Charset cs = (this.charset == null)
 393             ? Charset.forName(encodingName)
 394             : this.charset;
 395         CharsetDecoder decoder = cs.newDecoder();
 396 
 397         CodingErrorAction action;
 398         if (ignoreEncodingErrors)
 399             action = CodingErrorAction.REPLACE;
 400         else
 401             action = CodingErrorAction.REPORT;
 402 
 403         return decoder
 404             .onMalformedInput(action)
 405             .onUnmappableCharacter(action);
 406     }
 407     // </editor-fold>
 408 
 409     // <editor-fold defaultstate="collapsed" desc="ByteBuffers">
 410     /**
 411      * Make a byte buffer from an input stream.
 412      * @param in the stream
 413      * @return a byte buffer containing the contents of the stream
 414      * @throws IOException if an error occurred while reading the stream
 415      */
 416     @SuppressWarnings("cast")
 417     public ByteBuffer makeByteBuffer(InputStream in)
 418         throws IOException {
 419         int limit = in.available();
 420         if (limit < 1024) limit = 1024;
 421         ByteBuffer result = byteBufferCache.get(limit);
 422         int position = 0;
 423         while (in.available() != 0) {
 424             if (position >= limit)
 425                 // expand buffer
 426                 result = ByteBuffer.
 427                     allocate(limit <<= 1).
 428                     put((ByteBuffer)result.flip());
 429             int count = in.read(result.array(),
 430                 position,
 431                 limit - position);
 432             if (count < 0) break;
 433             result.position(position += count);
 434         }
 435         return (ByteBuffer)result.flip();
 436     }
 437 
 438     public void recycleByteBuffer(ByteBuffer bb) {
 439         byteBufferCache.put(bb);
 440     }
 441 
 442     /**
 443      * A single-element cache of direct byte buffers.
 444      */
 445     @SuppressWarnings("cast")
 446     private static class ByteBufferCache {
 447         private ByteBuffer cached;
 448         ByteBuffer get(int capacity) {
 449             if (capacity < 20480) capacity = 20480;
 450             ByteBuffer result =
 451                 (cached != null && cached.capacity() >= capacity)
 452                 ? (ByteBuffer)cached.clear()
 453                 : ByteBuffer.allocate(capacity + capacity>>1);
 454             cached = null;
 455             return result;
 456         }
 457         void put(ByteBuffer x) {
 458             cached = x;
 459         }
 460     }
 461 
 462     private final ByteBufferCache byteBufferCache;
 463     // </editor-fold>
 464 
 465     // <editor-fold defaultstate="collapsed" desc="Content cache">
 466     public CharBuffer getCachedContent(JavaFileObject file) {
 467         ContentCacheEntry e = contentCache.get(file);
 468         if (e == null)
 469             return null;
 470 
 471         if (!e.isValid(file)) {
 472             contentCache.remove(file);
 473             return null;
 474         }
 475 
 476         return e.getValue();
 477     }
 478 
 479     public void cache(JavaFileObject file, CharBuffer cb) {
 480         contentCache.put(file, new ContentCacheEntry(file, cb));
 481     }
 482 
 483     public void flushCache(JavaFileObject file) {
 484         contentCache.remove(file);
 485     }
 486 
 487     protected final Map<JavaFileObject, ContentCacheEntry> contentCache = new HashMap<>();
 488 
 489     protected static class ContentCacheEntry {
 490         final long timestamp;
 491         final SoftReference<CharBuffer> ref;
 492 
 493         ContentCacheEntry(JavaFileObject file, CharBuffer cb) {
 494             this.timestamp = file.getLastModified();
 495             this.ref = new SoftReference<>(cb);
 496         }
 497 
 498         boolean isValid(JavaFileObject file) {
 499             return timestamp == file.getLastModified();
 500         }
 501 
 502         CharBuffer getValue() {
 503             return ref.get();
 504         }
 505     }
 506     // </editor-fold>
 507 
 508     public static Kind getKind(Path path) {
 509         return getKind(path.getFileName().toString());
 510     }
 511 
 512     public static Kind getKind(String name) {
 513         if (name.endsWith(Kind.CLASS.extension))
 514             return Kind.CLASS;
 515         else if (name.endsWith(Kind.SOURCE.extension))
 516             return Kind.SOURCE;
 517         else if (name.endsWith(Kind.HTML.extension))
 518             return Kind.HTML;
 519         else
 520             return Kind.OTHER;
 521     }
 522 
 523     protected static <T> T nullCheck(T o) {
 524         return Objects.requireNonNull(o);
 525     }
 526 
 527     protected static <T> Collection<T> nullCheck(Collection<T> it) {
 528         for (T t : it)
 529             Objects.requireNonNull(t);
 530         return it;
 531     }
 532 }