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