1 /*
   2  * Copyright (c) 2009, 2012, 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.util;
  27 
  28 import java.io.ByteArrayOutputStream;
  29 import java.io.Closeable;
  30 import java.io.IOException;
  31 import java.io.InputStream;
  32 import java.io.OutputStreamWriter;
  33 import java.lang.ref.SoftReference;
  34 import java.lang.reflect.Constructor;
  35 import java.net.URL;
  36 import java.net.URLClassLoader;
  37 import java.nio.ByteBuffer;
  38 import java.nio.CharBuffer;
  39 import java.nio.charset.Charset;
  40 import java.nio.charset.CharsetDecoder;
  41 import java.nio.charset.CoderResult;
  42 import java.nio.charset.CodingErrorAction;
  43 import java.nio.charset.IllegalCharsetNameException;
  44 import java.nio.charset.UnsupportedCharsetException;
  45 import java.util.Collection;
  46 import java.util.HashMap;
  47 import java.util.Iterator;
  48 import java.util.Map;
  49 import java.util.Set;
  50 import javax.tools.JavaFileObject;
  51 import javax.tools.JavaFileObject.Kind;
  52 
  53 import com.sun.tools.javac.code.Lint;
  54 import com.sun.tools.javac.code.Source;
  55 import com.sun.tools.javac.file.FSInfo;
  56 import com.sun.tools.javac.file.Locations;
  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.util.JCDiagnostic.SimpleDiagnosticPosition;
  61 
  62 /**
  63  * Utility methods for building a filemanager.
  64  * There are no references here to file-system specific objects such as
  65  * java.io.File or java.nio.file.Path.
  66  */
  67 public abstract class BaseFileManager {
  68     protected BaseFileManager(Charset charset) {
  69         this.charset = charset;
  70         byteBufferCache = new ByteBufferCache();
  71         locations = createLocations();
  72     }
  73 
  74     /**
  75      * Set the context for JavacPathFileManager.
  76      */
  77     public void setContext(Context context) {
  78         log = Log.instance(context);
  79         options = Options.instance(context);
  80         classLoaderClass = options.get("procloader");
  81         locations.update(log, options, Lint.instance(context), FSInfo.instance(context));
  82     }
  83 
  84     protected Locations createLocations() {
  85         return new Locations();
  86     }
  87 
  88     /**
  89      * The log to be used for error reporting.
  90      */
  91     public Log log;
  92 
  93     /**
  94      * User provided charset (through javax.tools).
  95      */
  96     protected Charset charset;
  97 
  98     protected Options options;
  99 
 100     protected String classLoaderClass;
 101 
 102     protected Locations locations;
 103 
 104     protected Source getSource() {
 105         String sourceName = options.get(Option.SOURCE);
 106         Source source = null;
 107         if (sourceName != null)
 108             source = Source.lookup(sourceName);
 109         return (source != null ? source : Source.DEFAULT);
 110     }
 111 
 112     protected ClassLoader getClassLoader(URL[] urls) {
 113         ClassLoader thisClassLoader = getClass().getClassLoader();
 114 
 115         // Bug: 6558476
 116         // Ideally, ClassLoader should be Closeable, but before JDK7 it is not.
 117         // On older versions, try the following, to get a closeable classloader.
 118 
 119         // 1: Allow client to specify the class to use via hidden option
 120         if (classLoaderClass != null) {
 121             try {
 122                 Class<? extends ClassLoader> loader =
 123                         Class.forName(classLoaderClass).asSubclass(ClassLoader.class);
 124                 Class<?>[] constrArgTypes = { URL[].class, ClassLoader.class };
 125                 Constructor<? extends ClassLoader> constr = loader.getConstructor(constrArgTypes);
 126                 return constr.newInstance(new Object[] { urls, thisClassLoader });
 127             } catch (Throwable t) {
 128                 // ignore errors loading user-provided class loader, fall through
 129             }
 130         }
 131 
 132         // 2: If URLClassLoader implements Closeable, use that.
 133         if (Closeable.class.isAssignableFrom(URLClassLoader.class))
 134             return new URLClassLoader(urls, thisClassLoader);
 135 
 136         // 3: Try using private reflection-based CloseableURLClassLoader
 137         try {
 138             return new CloseableURLClassLoader(urls, thisClassLoader);
 139         } catch (Throwable t) {
 140             // ignore errors loading workaround class loader, fall through
 141         }
 142 
 143         // 4: If all else fails, use plain old standard URLClassLoader
 144         return new URLClassLoader(urls, thisClassLoader);
 145     }
 146 
 147     // <editor-fold defaultstate="collapsed" desc="Option handling">
 148     public boolean handleOption(String current, Iterator<String> remaining) {
 149         OptionHelper helper = new GrumpyHelper(log) {
 150             @Override
 151             public String get(Option option) {
 152                 return options.get(option.getText());
 153             }
 154 
 155             @Override
 156             public void put(String name, String value) {
 157                 options.put(name, value);
 158             }
 159 
 160             @Override
 161             public void remove(String name) {
 162                 options.remove(name);
 163             }
 164         };
 165         for (Option o: javacFileManagerOptions) {
 166             if (o.matches(current))  {
 167                 if (o.hasArg()) {
 168                     if (remaining.hasNext()) {
 169                         if (!o.process(helper, current, remaining.next()))
 170                             return true;
 171                     }
 172                 } else {
 173                     if (!o.process(helper, current))
 174                         return true;
 175                 }
 176                 // operand missing, or process returned false
 177                 throw new IllegalArgumentException(current);
 178             }
 179         }
 180 
 181         return false;
 182     }
 183     // where
 184         private static final Set<Option> javacFileManagerOptions =
 185             Option.getJavacFileManagerOptions();
 186 
 187     public int isSupportedOption(String option) {
 188         for (Option o : javacFileManagerOptions) {
 189             if (o.matches(option))
 190                 return o.hasArg() ? 1 : 0;
 191         }
 192         return -1;
 193     }
 194 
 195     public abstract boolean isDefaultBootClassPath();
 196 
 197     // </editor-fold>
 198 
 199     // <editor-fold defaultstate="collapsed" desc="Encoding">
 200     private String defaultEncodingName;
 201     private String getDefaultEncodingName() {
 202         if (defaultEncodingName == null) {
 203             defaultEncodingName =
 204                 new OutputStreamWriter(new ByteArrayOutputStream()).getEncoding();
 205         }
 206         return defaultEncodingName;
 207     }
 208 
 209     public String getEncodingName() {
 210         String encName = options.get(Option.ENCODING);
 211         if (encName == null)
 212             return getDefaultEncodingName();
 213         else
 214             return encName;
 215     }
 216 
 217     public CharBuffer decode(ByteBuffer inbuf, boolean ignoreEncodingErrors) {
 218         String encodingName = getEncodingName();
 219         CharsetDecoder decoder;
 220         try {
 221             decoder = getDecoder(encodingName, ignoreEncodingErrors);
 222         } catch (IllegalCharsetNameException e) {
 223             log.error("unsupported.encoding", encodingName);
 224             return (CharBuffer)CharBuffer.allocate(1).flip();
 225         } catch (UnsupportedCharsetException e) {
 226             log.error("unsupported.encoding", encodingName);
 227             return (CharBuffer)CharBuffer.allocate(1).flip();
 228         }
 229 
 230         // slightly overestimate the buffer size to avoid reallocation.
 231         float factor =
 232             decoder.averageCharsPerByte() * 0.8f +
 233             decoder.maxCharsPerByte() * 0.2f;
 234         CharBuffer dest = CharBuffer.
 235             allocate(10 + (int)(inbuf.remaining()*factor));
 236 
 237         while (true) {
 238             CoderResult result = decoder.decode(inbuf, dest, true);
 239             dest.flip();
 240 
 241             if (result.isUnderflow()) { // done reading
 242                 // make sure there is at least one extra character
 243                 if (dest.limit() == dest.capacity()) {
 244                     dest = CharBuffer.allocate(dest.capacity()+1).put(dest);
 245                     dest.flip();
 246                 }
 247                 return dest;
 248             } else if (result.isOverflow()) { // buffer too small; expand
 249                 int newCapacity =
 250                     10 + dest.capacity() +
 251                     (int)(inbuf.remaining()*decoder.maxCharsPerByte());
 252                 dest = CharBuffer.allocate(newCapacity).put(dest);
 253             } else if (result.isMalformed() || result.isUnmappable()) {
 254                 // bad character in input
 255 
 256                 // report coding error (warn only pre 1.5)
 257                 if (!getSource().allowEncodingErrors()) {
 258                     log.error(new SimpleDiagnosticPosition(dest.limit()),
 259                               "illegal.char.for.encoding",
 260                               charset == null ? encodingName : charset.name());
 261                 } else {
 262                     log.warning(new SimpleDiagnosticPosition(dest.limit()),
 263                                 "illegal.char.for.encoding",
 264                                 charset == null ? encodingName : charset.name());
 265                 }
 266 
 267                 // skip past the coding error
 268                 inbuf.position(inbuf.position() + result.length());
 269 
 270                 // undo the flip() to prepare the output buffer
 271                 // for more translation
 272                 dest.position(dest.limit());
 273                 dest.limit(dest.capacity());
 274                 dest.put((char)0xfffd); // backward compatible
 275             } else {
 276                 throw new AssertionError(result);
 277             }
 278         }
 279         // unreached
 280     }
 281 
 282     public CharsetDecoder getDecoder(String encodingName, boolean ignoreEncodingErrors) {
 283         Charset cs = (this.charset == null)
 284             ? Charset.forName(encodingName)
 285             : this.charset;
 286         CharsetDecoder decoder = cs.newDecoder();
 287 
 288         CodingErrorAction action;
 289         if (ignoreEncodingErrors)
 290             action = CodingErrorAction.REPLACE;
 291         else
 292             action = CodingErrorAction.REPORT;
 293 
 294         return decoder
 295             .onMalformedInput(action)
 296             .onUnmappableCharacter(action);
 297     }
 298     // </editor-fold>
 299 
 300     // <editor-fold defaultstate="collapsed" desc="ByteBuffers">
 301     /**
 302      * Make a byte buffer from an input stream.
 303      */
 304     public ByteBuffer makeByteBuffer(InputStream in)
 305         throws IOException {
 306         int limit = in.available();
 307         if (limit < 1024) limit = 1024;
 308         ByteBuffer result = byteBufferCache.get(limit);
 309         int position = 0;
 310         while (in.available() != 0) {
 311             if (position >= limit)
 312                 // expand buffer
 313                 result = ByteBuffer.
 314                     allocate(limit <<= 1).
 315                     put((ByteBuffer)result.flip());
 316             int count = in.read(result.array(),
 317                 position,
 318                 limit - position);
 319             if (count < 0) break;
 320             result.position(position += count);
 321         }
 322         return (ByteBuffer)result.flip();
 323     }
 324 
 325     public void recycleByteBuffer(ByteBuffer bb) {
 326         byteBufferCache.put(bb);
 327     }
 328 
 329     /**
 330      * A single-element cache of direct byte buffers.
 331      */
 332     private static class ByteBufferCache {
 333         private ByteBuffer cached;
 334         ByteBuffer get(int capacity) {
 335             if (capacity < 20480) capacity = 20480;
 336             ByteBuffer result =
 337                 (cached != null && cached.capacity() >= capacity)
 338                 ? (ByteBuffer)cached.clear()
 339                 : ByteBuffer.allocate(capacity + capacity>>1);
 340             cached = null;
 341             return result;
 342         }
 343         void put(ByteBuffer x) {
 344             cached = x;
 345         }
 346     }
 347 
 348     private final ByteBufferCache byteBufferCache;
 349     // </editor-fold>
 350 
 351     // <editor-fold defaultstate="collapsed" desc="Content cache">
 352     public CharBuffer getCachedContent(JavaFileObject file) {
 353         ContentCacheEntry e = contentCache.get(file);
 354         if (e == null)
 355             return null;
 356 
 357         if (!e.isValid(file)) {
 358             contentCache.remove(file);
 359             return null;
 360         }
 361 
 362         return e.getValue();
 363     }
 364 
 365     public void cache(JavaFileObject file, CharBuffer cb) {
 366         contentCache.put(file, new ContentCacheEntry(file, cb));
 367     }
 368 
 369     public void flushCache(JavaFileObject file) {
 370         contentCache.remove(file);
 371     }
 372 
 373     protected final Map<JavaFileObject, ContentCacheEntry> contentCache
 374             = new HashMap<JavaFileObject, ContentCacheEntry>();
 375 
 376     protected static class ContentCacheEntry {
 377         final long timestamp;
 378         final SoftReference<CharBuffer> ref;
 379 
 380         ContentCacheEntry(JavaFileObject file, CharBuffer cb) {
 381             this.timestamp = file.getLastModified();
 382             this.ref = new SoftReference<CharBuffer>(cb);
 383         }
 384 
 385         boolean isValid(JavaFileObject file) {
 386             return timestamp == file.getLastModified();
 387         }
 388 
 389         CharBuffer getValue() {
 390             return ref.get();
 391         }
 392     }
 393     // </editor-fold>
 394 
 395     public static Kind getKind(String name) {
 396         if (name.endsWith(Kind.CLASS.extension))
 397             return Kind.CLASS;
 398         else if (name.endsWith(Kind.SOURCE.extension))
 399             return Kind.SOURCE;
 400         else if (name.endsWith(Kind.HTML.extension))
 401             return Kind.HTML;
 402         else
 403             return Kind.OTHER;
 404     }
 405 
 406     protected static <T> T nullCheck(T o) {
 407         o.getClass(); // null check
 408         return o;
 409     }
 410 
 411     protected static <T> Collection<T> nullCheck(Collection<T> it) {
 412         for (T t : it)
 413             t.getClass(); // null check
 414         return it;
 415     }
 416 }