1 /*
2 * Copyright (c) 2005, 2025, 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.File;
29 import java.io.IOException;
30 import java.io.UncheckedIOException;
31 import java.lang.module.Configuration;
32 import java.lang.module.ModuleFinder;
33 import java.net.MalformedURLException;
34 import java.net.URI;
35 import java.net.URISyntaxException;
36 import java.net.URL;
37 import java.nio.CharBuffer;
38 import java.nio.charset.Charset;
39 import java.nio.file.FileSystem;
40 import java.nio.file.FileSystems;
41 import java.nio.file.FileVisitOption;
42 import java.nio.file.FileVisitResult;
43 import java.nio.file.Files;
44 import java.nio.file.InvalidPathException;
45 import java.nio.file.LinkOption;
46 import java.nio.file.Path;
47 import java.nio.file.Paths;
48 import java.nio.file.ProviderNotFoundException;
49 import java.nio.file.SimpleFileVisitor;
50 import java.nio.file.attribute.BasicFileAttributes;
51 import java.nio.file.spi.FileSystemProvider;
52 import java.util.ArrayList;
53 import java.util.Arrays;
54 import java.util.Collection;
55 import java.util.Collections;
56 import java.util.Comparator;
57 import java.util.HashMap;
58 import java.util.Iterator;
59 import java.util.Map;
60 import java.util.Objects;
61 import java.util.ServiceLoader;
62 import java.util.Set;
63 import java.util.stream.Stream;
64 import java.util.zip.ZipException;
65
66 import javax.lang.model.SourceVersion;
67 import javax.tools.FileObject;
68 import javax.tools.JavaFileManager;
69 import javax.tools.JavaFileObject;
70 import javax.tools.StandardJavaFileManager;
71
72 import com.sun.tools.javac.file.RelativePath.RelativeDirectory;
73 import com.sun.tools.javac.file.RelativePath.RelativeFile;
74 import com.sun.tools.javac.main.Option;
75 import com.sun.tools.javac.resources.CompilerProperties.Errors;
76 import com.sun.tools.javac.util.Assert;
77 import com.sun.tools.javac.util.Context;
78 import com.sun.tools.javac.util.Context.Factory;
79 import com.sun.tools.javac.util.DefinedBy;
80 import com.sun.tools.javac.util.DefinedBy.Api;
81 import com.sun.tools.javac.util.List;
82 import com.sun.tools.javac.util.ListBuffer;
83 import com.sun.tools.javac.util.Options;
84
85 import static java.nio.charset.StandardCharsets.US_ASCII;
86 import static java.nio.file.FileVisitOption.FOLLOW_LINKS;
87
88 import static javax.tools.StandardLocation.*;
89
90 /**
91 * This class provides access to the source, class and other files
92 * used by the compiler and related tools.
93 *
94 * <p><b>This is NOT part of any supported API.
95 * If you write code that depends on this, you do so at your own risk.
96 * This code and its internal interfaces are subject to change or
97 * deletion without notice.</b>
98 */
99 public class JavacFileManager extends BaseFileManager implements StandardJavaFileManager {
100
101 public static char[] toArray(CharBuffer buffer) {
102 if (buffer.hasArray())
103 return buffer.compact().flip().array();
104 else
105 return buffer.toString().toCharArray();
106 }
107
108 private FSInfo fsInfo;
109
110 private static final Set<JavaFileObject.Kind> SOURCE_OR_CLASS =
111 Set.of(JavaFileObject.Kind.SOURCE, JavaFileObject.Kind.CLASS);
112
113 protected boolean symbolFileEnabled = true;
114
115 private PathFactory pathFactory = Paths::get;
116
117 protected enum SortFiles implements Comparator<Path> {
118 FORWARD {
119 @Override
120 public int compare(Path f1, Path f2) {
121 return f1.getFileName().compareTo(f2.getFileName());
122 }
123 },
124 REVERSE {
125 @Override
126 public int compare(Path f1, Path f2) {
127 return f2.getFileName().compareTo(f1.getFileName());
128 }
129 }
130 }
131
132 protected SortFiles sortFiles;
133
134 /**
135 * We use a two-layered map instead of a map with a complex key because we don't want to reindex
136 * the values for every Location+RelativeDirectory pair. Once the PathsAndContainers are needed
137 * for a single Location, we should know all valid RelativeDirectory mappings. Because the
138 * indexing is costly for very large classpaths, this can result in a significant savings.
139 */
140 private Map<Location, Map<RelativeDirectory, java.util.List<PathAndContainer>>>
141 pathsAndContainersByLocationAndRelativeDirectory = new HashMap<>();
142
143 /** Containers that have no indexing by {@link RelativeDirectory}, keyed by {@link Location}. */
144 private Map<Location, java.util.List<PathAndContainer>> nonIndexingContainersByLocation =
145 new HashMap<>();
146
147 /**
148 * Register a Context.Factory to create a JavacFileManager.
149 */
150 public static void preRegister(Context context) {
151 context.put(JavaFileManager.class,
152 (Factory<JavaFileManager>)c -> new JavacFileManager(c, true, null));
153 }
154
155 /**
156 * Create a JavacFileManager using a given context, optionally registering
157 * it as the JavaFileManager for that context.
158 */
159 @SuppressWarnings("this-escape")
160 public JavacFileManager(Context context, boolean register, Charset charset) {
161 super(charset);
162 if (register)
163 context.put(JavaFileManager.class, this);
164 setContext(context);
165 }
166
167 /**
168 * Set the context for JavacFileManager.
169 */
170 @Override
171 public void setContext(Context context) {
172 super.setContext(context);
173 fsInfo = FSInfo.instance(context);
174 }
175
176 @Override
177 protected void applyOptions(Options options) {
178 super.applyOptions(options);
179
180 symbolFileEnabled = !options.isSet("ignore.symbol.file");
181
182 String sf = options.get("sortFiles");
183 if (sf != null) {
184 sortFiles = (sf.equals("reverse") ? SortFiles.REVERSE : SortFiles.FORWARD);
185 }
186 }
187
188 @Override @DefinedBy(DefinedBy.Api.COMPILER)
189 public void setPathFactory(PathFactory f) {
190 pathFactory = Objects.requireNonNull(f);
191 locations.setPathFactory(f);
192 }
193
194 private Path getPath(String first, String... more) {
195 return pathFactory.getPath(first, more);
196 }
197
198 /**
199 * Set whether or not to use ct.sym as an alternate to the current runtime.
200 */
201 public void setSymbolFileEnabled(boolean b) {
202 symbolFileEnabled = b;
203 }
204
205 public boolean isSymbolFileEnabled() {
206 return symbolFileEnabled;
207 }
208
209 // used by tests
210 public JavaFileObject getJavaFileObject(String name) {
211 return getJavaFileObjects(name).iterator().next();
212 }
213
214 // used by tests
215 public JavaFileObject getJavaFileObject(Path file) {
216 return getJavaFileObjects(file).iterator().next();
217 }
218
219 public JavaFileObject getFileForOutput(String classname,
220 JavaFileObject.Kind kind,
221 JavaFileObject sibling)
222 throws IOException
223 {
224 return getJavaFileForOutput(CLASS_OUTPUT, classname, kind, sibling);
225 }
226
227 @Override @DefinedBy(Api.COMPILER)
228 public Iterable<? extends JavaFileObject> getJavaFileObjectsFromStrings(Iterable<String> names) {
229 ListBuffer<Path> paths = new ListBuffer<>();
230 for (String name : names)
231 paths.append(getPath(nullCheck(name)));
232 return getJavaFileObjectsFromPaths(paths.toList());
233 }
234
235 @Override @DefinedBy(Api.COMPILER)
236 public Iterable<? extends JavaFileObject> getJavaFileObjects(String... names) {
237 return getJavaFileObjectsFromStrings(Arrays.asList(nullCheck(names)));
238 }
239
240 private static boolean isValidName(String name) {
241 // Arguably, isValidName should reject keywords (such as in SourceVersion.isName() ),
242 // but the set of keywords depends on the source level, and we don't want
243 // impls of JavaFileManager to have to be dependent on the source level.
244 // Therefore we simply check that the argument is a sequence of identifiers
245 // separated by ".".
246 for (String s : name.split("\\.", -1)) {
247 if (!SourceVersion.isIdentifier(s))
248 return false;
249 }
250 return true;
251 }
252
253 private static void validateClassName(String className) {
254 if (!isValidName(className))
255 throw new IllegalArgumentException("Invalid class name: " + className);
256 }
257
258 private static void validatePackageName(String packageName) {
259 if (packageName.length() > 0 && !isValidName(packageName))
260 throw new IllegalArgumentException("Invalid packageName name: " + packageName);
261 }
262
263 public static void testName(String name,
264 boolean isValidPackageName,
265 boolean isValidClassName)
266 {
267 try {
268 validatePackageName(name);
269 if (!isValidPackageName)
270 throw new AssertionError("Invalid package name accepted: " + name);
271 printAscii("Valid package name: \"%s\"", name);
272 } catch (IllegalArgumentException e) {
273 if (isValidPackageName)
274 throw new AssertionError("Valid package name rejected: " + name);
275 printAscii("Invalid package name: \"%s\"", name);
276 }
277 try {
278 validateClassName(name);
279 if (!isValidClassName)
280 throw new AssertionError("Invalid class name accepted: " + name);
281 printAscii("Valid class name: \"%s\"", name);
282 } catch (IllegalArgumentException e) {
283 if (isValidClassName)
284 throw new AssertionError("Valid class name rejected: " + name);
285 printAscii("Invalid class name: \"%s\"", name);
286 }
287 }
288
289 private static void printAscii(String format, Object... args) {
290 String message = new String(
291 String.format(null, format, args).getBytes(US_ASCII), US_ASCII);
292 System.out.println(message);
293 }
294
295 private final Map<Path, Container> containers = new HashMap<>();
296
297 synchronized Container getContainer(Path path) throws IOException {
298 Container fs = containers.get(path);
299
300 if (fs != null) {
301 return fs;
302 }
303
304 if (fsInfo.isFile(path) && path.equals(Locations.thisSystemModules)) {
305 containers.put(path, fs = new JRTImageContainer());
306 return fs;
307 }
308
309 Path realPath = fsInfo.getCanonicalFile(path);
310
311 fs = containers.get(realPath);
312
313 if (fs != null) {
314 containers.put(path, fs);
315 return fs;
316 }
317
318 BasicFileAttributes attr = null;
319
320 try {
321 attr = Files.readAttributes(realPath, BasicFileAttributes.class);
322 } catch (IOException ex) {
323 //non-existing
324 fs = MISSING_CONTAINER;
325 }
326
327 if (attr != null) {
328 if (attr.isDirectory()) {
329 fs = new DirectoryContainer(realPath);
330 } else {
331 try {
332 fs = new ArchiveContainer(path);
333 } catch (ProviderNotFoundException ex) {
334 throw new IOException(ex);
335 }
336 }
337 }
338
339 containers.put(realPath, fs);
340 containers.put(path, fs);
341
342 return fs;
343 }
344
345 private interface Container {
346 /**
347 * Insert all files in subdirectory subdirectory of container which
348 * match fileKinds into resultList
349 */
350 public abstract void list(Path userPath,
351 RelativeDirectory subdirectory,
352 Set<JavaFileObject.Kind> fileKinds,
353 boolean recurse,
354 ListBuffer<JavaFileObject> resultList) throws IOException;
355 public abstract JavaFileObject getFileObject(Path userPath, RelativeFile name) throws IOException;
356 public abstract void close() throws IOException;
357 public abstract boolean maintainsDirectoryIndex();
358
359 /**
360 * The directories this container indexes if {@link #maintainsDirectoryIndex()}, otherwise
361 * an empty iterable.
362 */
363 public abstract Iterable<RelativeDirectory> indexedDirectories();
364 }
365
366 private static final Container MISSING_CONTAINER = new Container() {
367 @Override
368 public void list(Path userPath,
369 RelativeDirectory subdirectory,
370 Set<JavaFileObject.Kind> fileKinds,
371 boolean recurse,
372 ListBuffer<JavaFileObject> resultList) throws IOException {
373 }
374 @Override
375 public JavaFileObject getFileObject(Path userPath, RelativeFile name) throws IOException {
376 return null;
377 }
378 @Override
379 public void close() throws IOException {}
380 @Override
381 public boolean maintainsDirectoryIndex() {
382 return false;
383 }
384 @Override
385 public Iterable<RelativeDirectory> indexedDirectories() {
386 return List.nil();
387 }
388 };
389
390 private final class JRTImageContainer implements Container {
391 // Monotonic, created on demand.
392 private JRTIndex jrtIndex = null;
393
394 private synchronized JRTIndex getJRTIndex() {
395 if (jrtIndex == null) {
396 jrtIndex = JRTIndex.instance(previewMode);
397 }
398 return jrtIndex;
399 }
400
401 /**
402 * Insert all files in a subdirectory of the platform image
403 * which match fileKinds into resultList.
404 */
405 @Override
406 public void list(Path userPath,
407 RelativeDirectory subdirectory,
408 Set<JavaFileObject.Kind> fileKinds,
409 boolean recurse,
410 ListBuffer<JavaFileObject> resultList) throws IOException {
411 try {
412 JRTIndex.Entry e = getJRTIndex().getEntry(subdirectory);
413 if (symbolFileEnabled && e.ctSym.hidden)
414 return;
415 for (Path file: e.files.values()) {
416 if (fileKinds.contains(getKind(file))) {
417 JavaFileObject fe
418 = PathFileObject.forJRTPath(JavacFileManager.this, file);
419 resultList.append(fe);
420 }
421 }
422
423 if (recurse) {
424 for (RelativeDirectory rd: e.subdirs) {
425 list(userPath, rd, fileKinds, recurse, resultList);
426 }
427 }
428 } catch (IOException ex) {
429 ex.printStackTrace(System.err);
430 log.error(Errors.ErrorReadingFile(userPath, getMessage(ex)));
431 }
432 }
433
434 @Override
435 public JavaFileObject getFileObject(Path userPath, RelativeFile name) throws IOException {
436 JRTIndex.Entry e = getJRTIndex().getEntry(name.dirname());
437 if (symbolFileEnabled && e.ctSym.hidden)
438 return null;
439 Path p = e.files.get(name.basename());
440 if (p != null) {
441 return PathFileObject.forJRTPath(JavacFileManager.this, p);
442 } else {
443 return null;
444 }
445 }
446
447 @Override
448 public void close() throws IOException {
449 if (jrtIndex != null) {
450 jrtIndex.close();
451 }
452 }
453
454 @Override
455 public boolean maintainsDirectoryIndex() {
456 return false;
457 }
458
459 @Override
460 public Iterable<RelativeDirectory> indexedDirectories() {
461 return List.nil();
462 }
463 }
464
465 private final class DirectoryContainer implements Container {
466 private final Path directory;
467
468 public DirectoryContainer(Path directory) {
469 this.directory = directory;
470 }
471
472 /**
473 * Insert all files in subdirectory subdirectory of directory userPath
474 * which match fileKinds into resultList
475 */
476 @Override
477 public void list(Path userPath,
478 RelativeDirectory subdirectory,
479 Set<JavaFileObject.Kind> fileKinds,
480 boolean recurse,
481 ListBuffer<JavaFileObject> resultList) throws IOException {
482 Path d;
483 try {
484 d = subdirectory.resolveAgainst(userPath);
485 } catch (InvalidPathException ignore) {
486 return ;
487 }
488
489 if (!Files.exists(d)) {
490 return;
491 }
492
493 if (!caseMapCheck(d, subdirectory)) {
494 return;
495 }
496
497 java.util.List<Path> files;
498 try (Stream<Path> s = Files.list(d)) {
499 files = (sortFiles == null ? s : s.sorted(sortFiles)).toList();
500 } catch (IOException ignore) {
501 return;
502 }
503
504 for (Path f: files) {
505 String fname = f.getFileName().toString();
506 if (fname.endsWith("/"))
507 fname = fname.substring(0, fname.length() - 1);
508 if (Files.isDirectory(f)) {
509 if (recurse && SourceVersion.isIdentifier(fname)) {
510 list(userPath,
511 new RelativeDirectory(subdirectory, fname),
512 fileKinds,
513 recurse,
514 resultList);
515 }
516 } else {
517 if (isValidFile(fname, fileKinds)) {
518 try {
519 RelativeFile file = new RelativeFile(subdirectory, fname);
520 JavaFileObject fe = PathFileObject.forDirectoryPath(JavacFileManager.this,
521 file.resolveAgainst(directory), userPath, file);
522 resultList.append(fe);
523 } catch (InvalidPathException e) {
524 throw new IOException("error accessing directory " + directory + e);
525 }
526 }
527 }
528 }
529 }
530
531 @Override
532 public JavaFileObject getFileObject(Path userPath, RelativeFile name) throws IOException {
533 try {
534 Path f = name.resolveAgainst(userPath);
535 if (Files.exists(f))
536 return PathFileObject.forSimplePath(JavacFileManager.this,
537 fsInfo.getCanonicalFile(f), f);
538 } catch (InvalidPathException ignore) {
539 }
540 return null;
541 }
542
543 @Override
544 public void close() throws IOException {
545 }
546
547 @Override
548 public boolean maintainsDirectoryIndex() {
549 return false;
550 }
551
552 @Override
553 public Iterable<RelativeDirectory> indexedDirectories() {
554 return List.nil();
555 }
556 }
557
558 private static final Set<FileVisitOption> NO_FILE_VISIT_OPTIONS = Set.of();
559 private static final Set<FileVisitOption> FOLLOW_LINKS_OPTIONS = Set.of(FOLLOW_LINKS);
560
561 private final class ArchiveContainer implements Container {
562 private final Path archivePath;
563 private final FileSystem fileSystem;
564 private final Map<RelativeDirectory, Path> packages;
565
566 public ArchiveContainer(Path archivePath) throws IOException, ProviderNotFoundException {
567 this.archivePath = archivePath;
568 if (multiReleaseValue != null && archivePath.toString().endsWith(".jar")) {
569 FileSystemProvider jarFSProvider = fsInfo.getJarFSProvider();
570 Assert.checkNonNull(jarFSProvider, "should have been caught before!");
571 Map<String, ?> env = fsInfo.readOnlyJarFSEnv(multiReleaseValue);
572 try {
573 this.fileSystem = jarFSProvider.newFileSystem(archivePath, env);
574 } catch (ZipException ze) {
575 throw new IOException("ZipException opening \"" + archivePath.getFileName() + "\": " + ze.getMessage(), ze);
576 }
577 } else {
578 // Less common case is possible if the file manager was not initialized in JavacTask,
579 // or if non "*.jar" files are on the classpath. If this is not a ZIP/JAR file then it
580 // will ignore ZIP specific parameters in env, and may not end up being read-only.
581 // However, Javac should never attempt to write back to archives either way.
582 Map<String, ?> env = fsInfo.readOnlyJarFSEnv(null);
583 this.fileSystem = FileSystems.newFileSystem(archivePath, env);
584 }
585 packages = new HashMap<>();
586 for (Path root : fileSystem.getRootDirectories()) {
587 Files.walkFileTree(root, NO_FILE_VISIT_OPTIONS, Integer.MAX_VALUE,
588 new SimpleFileVisitor<Path>() {
589 @Override
590 public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
591 if (isValid(dir.getFileName())) {
592 packages.put(new RelativeDirectory(root.relativize(dir).toString()), dir);
593 return FileVisitResult.CONTINUE;
594 } else {
595 return FileVisitResult.SKIP_SUBTREE;
596 }
597 }
598 });
599 }
600 }
601
602 /**
603 * Insert all files in subdirectory subdirectory of this archive
604 * which match fileKinds into resultList
605 */
606 @Override
607 public void list(Path userPath,
608 RelativeDirectory subdirectory,
609 Set<JavaFileObject.Kind> fileKinds,
610 boolean recurse,
611 ListBuffer<JavaFileObject> resultList) throws IOException {
612 Path resolvedSubdirectory = packages.get(subdirectory);
613
614 if (resolvedSubdirectory == null)
615 return ;
616
617 int maxDepth = (recurse ? Integer.MAX_VALUE : 1);
618 Files.walkFileTree(resolvedSubdirectory, FOLLOW_LINKS_OPTIONS, maxDepth,
619 new SimpleFileVisitor<Path>() {
620 @Override
621 public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
622 if (isValid(dir.getFileName())) {
623 return FileVisitResult.CONTINUE;
624 } else {
625 return FileVisitResult.SKIP_SUBTREE;
626 }
627 }
628
629 @Override
630 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
631 if (attrs.isRegularFile() && fileKinds.contains(getKind(file.getFileName().toString()))) {
632 JavaFileObject fe = PathFileObject.forJarPath(
633 JavacFileManager.this, file, archivePath);
634 resultList.append(fe);
635 }
636 return FileVisitResult.CONTINUE;
637 }
638 });
639
640 }
641
642 private boolean isValid(Path fileName) {
643 if (fileName == null) {
644 return true;
645 } else {
646 String name = fileName.toString();
647 if (name.endsWith("/")) {
648 name = name.substring(0, name.length() - 1);
649 }
650 return SourceVersion.isIdentifier(name);
651 }
652 }
653
654 @Override
655 public JavaFileObject getFileObject(Path userPath, RelativeFile name) throws IOException {
656 RelativeDirectory root = name.dirname();
657 Path packagepath = packages.get(root);
658 if (packagepath != null) {
659 Path relpath = packagepath.resolve(name.basename());
660 if (Files.exists(relpath)) {
661 return PathFileObject.forJarPath(JavacFileManager.this, relpath, userPath);
662 }
663 }
664 return null;
665 }
666
667 @Override
668 public void close() throws IOException {
669 fileSystem.close();
670 }
671
672 @Override
673 public boolean maintainsDirectoryIndex() {
674 return true;
675 }
676
677 @Override
678 public Iterable<RelativeDirectory> indexedDirectories() {
679 return packages.keySet();
680 }
681 }
682
683 /**
684 * container is a directory, a zip file, or a non-existent path.
685 */
686 private boolean isValidFile(String s, Set<JavaFileObject.Kind> fileKinds) {
687 JavaFileObject.Kind kind = getKind(s);
688 return fileKinds.contains(kind);
689 }
690
691 private static final boolean fileSystemIsCaseSensitive =
692 File.separatorChar == '/';
693
694 /** Hack to make Windows case sensitive. Test whether given path
695 * ends in a string of characters with the same case as given name.
696 * Ignore file separators in both path and name.
697 */
698 private boolean caseMapCheck(Path f, RelativePath name) {
699 if (fileSystemIsCaseSensitive) return true;
700 // Note that toRealPath() returns the case-sensitive
701 // spelled file name.
702 String path;
703 char sep;
704 try {
705 path = f.toRealPath(LinkOption.NOFOLLOW_LINKS).toString();
706 sep = f.getFileSystem().getSeparator().charAt(0);
707 } catch (IOException ex) {
708 return false;
709 }
710 char[] pcs = path.toCharArray();
711 char[] ncs = name.path.toCharArray();
712 int i = pcs.length - 1;
713 int j = ncs.length - 1;
714 while (i >= 0 && j >= 0) {
715 while (i >= 0 && pcs[i] == sep) i--;
716 while (j >= 0 && ncs[j] == '/') j--;
717 if (i >= 0 && j >= 0) {
718 if (pcs[i] != ncs[j]) return false;
719 i--;
720 j--;
721 }
722 }
723 return j < 0;
724 }
725
726 /** Flush any output resources.
727 */
728 @Override @DefinedBy(Api.COMPILER)
729 public void flush() {
730 contentCache.clear();
731 pathsAndContainersByLocationAndRelativeDirectory.clear();
732 nonIndexingContainersByLocation.clear();
733 }
734
735 /**
736 * Close the JavaFileManager, releasing resources.
737 */
738 @Override @DefinedBy(Api.COMPILER)
739 public void close() throws IOException {
740 if (deferredCloseTimeout > 0) {
741 deferredClose();
742 return;
743 }
744
745 locations.close();
746 for (Container container: containers.values()) {
747 container.close();
748 }
749 containers.clear();
750 pathsAndContainersByLocationAndRelativeDirectory.clear();
751 nonIndexingContainersByLocation.clear();
752 contentCache.clear();
753 resetOutputFilesWritten();
754 }
755
756 @Override @DefinedBy(Api.COMPILER)
757 public ClassLoader getClassLoader(Location location) {
758 checkNotModuleOrientedLocation(location);
759 Iterable<? extends File> path = getLocation(location);
760 if (path == null)
761 return null;
762 ListBuffer<URL> lb = new ListBuffer<>();
763 for (File f: path) {
764 try {
765 lb.append(f.toURI().toURL());
766 } catch (MalformedURLException e) {
767 throw new AssertionError(e);
768 }
769 }
770
771 return getClassLoader(lb.toArray(new URL[lb.size()]));
772 }
773
774 @Override @DefinedBy(Api.COMPILER)
775 public Iterable<JavaFileObject> list(Location location,
776 String packageName,
777 Set<JavaFileObject.Kind> kinds,
778 boolean recurse)
779 throws IOException
780 {
781 checkNotModuleOrientedLocation(location);
782 // validatePackageName(packageName);
783 nullCheck(packageName);
784 nullCheck(kinds);
785
786 RelativeDirectory subdirectory = RelativeDirectory.forPackage(packageName);
787 ListBuffer<JavaFileObject> results = new ListBuffer<>();
788
789 for (PathAndContainer pathAndContainer : pathsAndContainers(location, subdirectory)) {
790 Path directory = pathAndContainer.path;
791 Container container = pathAndContainer.container;
792 container.list(directory, subdirectory, kinds, recurse, results);
793 }
794
795 return results.toList();
796 }
797
798 @Override @DefinedBy(Api.COMPILER)
799 public String inferBinaryName(Location location, JavaFileObject file) {
800 checkNotModuleOrientedLocation(location);
801 Objects.requireNonNull(file);
802 // Need to match the path semantics of list(location, ...)
803 Iterable<? extends Path> path = getLocationAsPaths(location);
804 if (path == null) {
805 return null;
806 }
807
808 if (file instanceof PathFileObject pathFileObject) {
809 return pathFileObject.inferBinaryName(path);
810 } else
811 throw new IllegalArgumentException(file.getClass().getName());
812 }
813
814 @Override @DefinedBy(Api.COMPILER)
815 public boolean isSameFile(FileObject a, FileObject b) {
816 nullCheck(a);
817 nullCheck(b);
818 if (a instanceof PathFileObject pathFileObjectA && b instanceof PathFileObject pathFileObjectB)
819 return pathFileObjectA.isSameFile(pathFileObjectB);
820 return a.equals(b);
821 }
822
823 @Override @DefinedBy(Api.COMPILER)
824 public boolean hasLocation(Location location) {
825 nullCheck(location);
826 return locations.hasLocation(location);
827 }
828
829 protected boolean hasExplicitLocation(Location location) {
830 nullCheck(location);
831 return locations.hasExplicitLocation(location);
832 }
833
834 @Override @DefinedBy(Api.COMPILER)
835 public JavaFileObject getJavaFileForInput(Location location,
836 String className,
837 JavaFileObject.Kind kind)
838 throws IOException
839 {
840 checkNotModuleOrientedLocation(location);
841 // validateClassName(className);
842 nullCheck(className);
843 nullCheck(kind);
844 if (!SOURCE_OR_CLASS.contains(kind))
845 throw new IllegalArgumentException("Invalid kind: " + kind);
846 return getFileForInput(location, RelativeFile.forClass(className, kind));
847 }
848
849 @Override @DefinedBy(Api.COMPILER)
850 public FileObject getFileForInput(Location location,
851 String packageName,
852 String relativeName)
853 throws IOException
854 {
855 checkNotModuleOrientedLocation(location);
856 // validatePackageName(packageName);
857 nullCheck(packageName);
858 if (!isRelativeUri(relativeName))
859 throw new IllegalArgumentException("Invalid relative name: " + relativeName);
860 RelativeFile name = packageName.length() == 0
861 ? new RelativeFile(relativeName)
862 : new RelativeFile(RelativeDirectory.forPackage(packageName), relativeName);
863 return getFileForInput(location, name);
864 }
865
866 private JavaFileObject getFileForInput(Location location, RelativeFile name) throws IOException {
867 Iterable<? extends Path> path = getLocationAsPaths(location);
868 if (path == null)
869 return null;
870
871 for (Path file: path) {
872 JavaFileObject fo = getContainer(file).getFileObject(file, name);
873
874 if (fo != null) {
875 return fo;
876 }
877 }
878 return null;
879 }
880
881 @Override @DefinedBy(Api.COMPILER)
882 public JavaFileObject getJavaFileForOutput(Location location,
883 String className,
884 JavaFileObject.Kind kind,
885 FileObject sibling)
886 throws IOException
887 {
888 checkOutputLocation(location);
889 // validateClassName(className);
890 nullCheck(className);
891 nullCheck(kind);
892 if (!SOURCE_OR_CLASS.contains(kind))
893 throw new IllegalArgumentException("Invalid kind: " + kind);
894 return getFileForOutput(location, RelativeFile.forClass(className, kind), sibling);
895 }
896
897 @Override @DefinedBy(Api.COMPILER)
898 public FileObject getFileForOutput(Location location,
899 String packageName,
900 String relativeName,
901 FileObject sibling)
902 throws IOException
903 {
904 checkOutputLocation(location);
905 // validatePackageName(packageName);
906 nullCheck(packageName);
907 if (!isRelativeUri(relativeName))
908 throw new IllegalArgumentException("Invalid relative name: " + relativeName);
909 RelativeFile name = packageName.length() == 0
910 ? new RelativeFile(relativeName)
911 : new RelativeFile(RelativeDirectory.forPackage(packageName), relativeName);
912 return getFileForOutput(location, name, sibling);
913 }
914
915 private JavaFileObject getFileForOutput(Location location,
916 RelativeFile fileName,
917 FileObject sibling)
918 throws IOException
919 {
920 Path dir;
921 if (location == CLASS_OUTPUT) {
922 if (getClassOutDir() != null) {
923 dir = getClassOutDir();
924 } else {
925 // Sibling is the associated source of the class file (e.g. x/y/Foo.java).
926 // The base name for class output is the class file name (e.g. "Foo.class").
927 String baseName = fileName.basename();
928 // Use the sibling to determine the output location where possible, unless
929 // it is in a JAR/ZIP file (we don't attempt to write class files back into
930 // archives).
931 if (sibling instanceof PathFileObject pathFileObject && !pathFileObject.isJarFile()) {
932 return pathFileObject.getSibling(baseName);
933 } else {
934 // Without the sibling present, we just create an output path in the
935 // current working directory (this isn't great, but it is what older
936 // versions of the JDK did).
937 Path userPath = getPath(baseName);
938 Path realPath = fsInfo.getCanonicalFile(userPath);
939 return PathFileObject.forSimplePath(this, realPath, userPath);
940 }
941 }
942 } else if (location == SOURCE_OUTPUT) {
943 dir = (getSourceOutDir() != null ? getSourceOutDir() : getClassOutDir());
944 } else {
945 Iterable<? extends Path> path = locations.getLocation(location);
946 dir = null;
947 for (Path f: path) {
948 dir = f;
949 break;
950 }
951 }
952
953 try {
954 if (dir == null) {
955 dir = getPath(System.getProperty("user.dir"));
956 }
957 Path path = fileName.resolveAgainst(fsInfo.getCanonicalFile(dir));
958 return PathFileObject.forDirectoryPath(this, path, dir, fileName);
959 } catch (InvalidPathException e) {
960 throw new IOException("bad filename " + fileName, e);
961 }
962 }
963
964 @Override @DefinedBy(Api.COMPILER)
965 public Iterable<? extends JavaFileObject> getJavaFileObjectsFromFiles(
966 Iterable<? extends File> files)
967 {
968 ArrayList<PathFileObject> result;
969 if (files instanceof Collection<?> collection)
970 result = new ArrayList<>(collection.size());
971 else
972 result = new ArrayList<>();
973 for (File f: files) {
974 Objects.requireNonNull(f);
975 Path p = f.toPath();
976 result.add(PathFileObject.forSimplePath(this,
977 fsInfo.getCanonicalFile(p), p));
978 }
979 return result;
980 }
981
982 @Override @DefinedBy(Api.COMPILER)
983 public Iterable<? extends JavaFileObject> getJavaFileObjectsFromPaths(Collection<? extends Path> paths) {
984 ArrayList<PathFileObject> result;
985 if (paths != null) {
986 result = new ArrayList<>(paths.size());
987 for (Path p: paths)
988 result.add(PathFileObject.forSimplePath(this,
989 fsInfo.getCanonicalFile(p), p));
990 } else {
991 result = new ArrayList<>();
992 }
993 return result;
994 }
995
996 @Override @DefinedBy(Api.COMPILER)
997 public Iterable<? extends JavaFileObject> getJavaFileObjects(File... files) {
998 return getJavaFileObjectsFromFiles(Arrays.asList(nullCheck(files)));
999 }
1000
1001 @Override @DefinedBy(Api.COMPILER)
1002 public Iterable<? extends JavaFileObject> getJavaFileObjects(Path... paths) {
1003 return getJavaFileObjectsFromPaths(Arrays.asList(nullCheck(paths)));
1004 }
1005
1006 @Override @DefinedBy(Api.COMPILER)
1007 public void setLocation(Location location,
1008 Iterable<? extends File> searchpath)
1009 throws IOException
1010 {
1011 nullCheck(location);
1012 locations.setLocation(location, asPaths(searchpath));
1013 clearCachesForLocation(location);
1014 }
1015
1016 @Override @DefinedBy(Api.COMPILER)
1017 public void setLocationFromPaths(Location location,
1018 Collection<? extends Path> searchpath)
1019 throws IOException
1020 {
1021 nullCheck(location);
1022 locations.setLocation(location, nullCheck(searchpath));
1023 clearCachesForLocation(location);
1024 }
1025
1026 @Override @DefinedBy(Api.COMPILER)
1027 public Iterable<? extends File> getLocation(Location location) {
1028 nullCheck(location);
1029 return asFiles(locations.getLocation(location));
1030 }
1031
1032 @Override @DefinedBy(Api.COMPILER)
1033 public Collection<? extends Path> getLocationAsPaths(Location location) {
1034 nullCheck(location);
1035 return locations.getLocation(location);
1036 }
1037
1038 private java.util.List<PathAndContainer> pathsAndContainers(
1039 Location location, RelativeDirectory relativeDirectory) throws IOException {
1040 try {
1041 return pathsAndContainersByLocationAndRelativeDirectory.computeIfAbsent(
1042 location, this::indexPathsAndContainersByRelativeDirectory)
1043 .computeIfAbsent(
1044 relativeDirectory, d -> nonIndexingContainersByLocation.get(location));
1045 } catch (UncheckedIOException e) {
1046 throw e.getCause();
1047 }
1048 }
1049
1050 private Map<RelativeDirectory, java.util.List<PathAndContainer>> indexPathsAndContainersByRelativeDirectory(
1051 Location location) {
1052 Map<RelativeDirectory, java.util.List<PathAndContainer>> result = new HashMap<>();
1053 java.util.List<PathAndContainer> allPathsAndContainers = pathsAndContainers(location);
1054
1055 // First collect all of the containers that don't maintain their own index on
1056 // RelativeDirectory. These need to always be included for all mappings
1057 java.util.List<PathAndContainer> nonIndexingContainers = new ArrayList<>();
1058 for (PathAndContainer pathAndContainer : allPathsAndContainers) {
1059 if (!pathAndContainer.container.maintainsDirectoryIndex()) {
1060 nonIndexingContainers.add(pathAndContainer);
1061 }
1062 }
1063
1064 // Next, use the container that do maintain their own RelativeDirectory index to create a
1065 // single master index.
1066 for (PathAndContainer pathAndContainer : allPathsAndContainers) {
1067 Container container = pathAndContainer.container;
1068 if (container.maintainsDirectoryIndex()) {
1069 for (RelativeDirectory directory : container.indexedDirectories()) {
1070 result.computeIfAbsent(directory, d -> new ArrayList<>(nonIndexingContainers))
1071 .add(pathAndContainer);
1072 }
1073 }
1074 }
1075 nonIndexingContainersByLocation.put(location, nonIndexingContainers);
1076
1077 // Sorting preserves the search order used in the uncached Location path, which has
1078 // maintains consistency with the classpath order
1079 result.values().forEach(pathAndContainerList -> Collections.sort(pathAndContainerList));
1080
1081 return result;
1082 }
1083
1084 /**
1085 * For each {@linkplain #getLocationAsPaths(Location) path of the location}, compute the
1086 * corresponding {@link Container}.
1087 */
1088 private java.util.List<PathAndContainer> pathsAndContainers(Location location) {
1089 Collection<? extends Path> paths = getLocationAsPaths(location);
1090 if (paths == null) {
1091 return List.nil();
1092 }
1093 java.util.List<PathAndContainer> pathsAndContainers =
1094 new ArrayList<>(paths.size());
1095 for (Path path : paths) {
1096 Container container;
1097 try {
1098 container = getContainer(path);
1099 } catch (IOException e) {
1100 throw new UncheckedIOException(e);
1101 }
1102 pathsAndContainers.add(new PathAndContainer(path, container, pathsAndContainers.size()));
1103 }
1104 return pathsAndContainers;
1105 }
1106
1107 private static class PathAndContainer implements Comparable<PathAndContainer> {
1108 private final Path path;
1109 private final Container container;
1110 private final int index;
1111
1112 PathAndContainer(Path path, Container container, int index) {
1113 this.path = path;
1114 this.container = container;
1115 this.index = index;
1116 }
1117
1118 @Override
1119 public int compareTo(PathAndContainer other) {
1120 return index - other.index;
1121 }
1122
1123 @Override
1124 public boolean equals(Object o) {
1125 return (o instanceof PathAndContainer pathAndContainer)
1126 && path.equals(pathAndContainer.path)
1127 && container.equals(pathAndContainer.container)
1128 && index == pathAndContainer.index;
1129 }
1130
1131 @Override
1132 public int hashCode() {
1133 return Objects.hash(path, container, index);
1134 }
1135 }
1136
1137 @Override @DefinedBy(Api.COMPILER)
1138 public boolean contains(Location location, FileObject fo) throws IOException {
1139 nullCheck(location);
1140 nullCheck(fo);
1141 Path p = asPath(fo);
1142 return locations.contains(location, p);
1143 }
1144
1145 private Path getClassOutDir() {
1146 return locations.getOutputLocation(CLASS_OUTPUT);
1147 }
1148
1149 private Path getSourceOutDir() {
1150 return locations.getOutputLocation(SOURCE_OUTPUT);
1151 }
1152
1153 @Override @DefinedBy(Api.COMPILER)
1154 public Location getLocationForModule(Location location, String moduleName) throws IOException {
1155 checkModuleOrientedOrOutputLocation(location);
1156 nullCheck(moduleName);
1157 if (location == SOURCE_OUTPUT && getSourceOutDir() == null)
1158 location = CLASS_OUTPUT;
1159 return locations.getLocationForModule(location, moduleName);
1160 }
1161
1162 @Override @DefinedBy(Api.COMPILER)
1163 public <S> ServiceLoader<S> getServiceLoader(Location location, Class<S> service) throws IOException {
1164 nullCheck(location);
1165 nullCheck(service);
1166 getClass().getModule().addUses(service);
1167 if (location.isModuleOrientedLocation()) {
1168 Collection<Path> paths = locations.getLocation(location);
1169 ModuleFinder finder = ModuleFinder.of(paths.toArray(new Path[paths.size()]));
1170 ModuleLayer bootLayer = ModuleLayer.boot();
1171 Configuration cf = bootLayer.configuration().resolveAndBind(ModuleFinder.of(), finder, Collections.emptySet());
1172 ModuleLayer layer = bootLayer.defineModulesWithOneLoader(cf, ClassLoader.getSystemClassLoader());
1173 return ServiceLoader.load(layer, service);
1174 } else {
1175 return ServiceLoader.load(service, getClassLoader(location));
1176 }
1177 }
1178
1179 @Override @DefinedBy(Api.COMPILER)
1180 public Location getLocationForModule(Location location, JavaFileObject fo) throws IOException {
1181 checkModuleOrientedOrOutputLocation(location);
1182 if (!(fo instanceof PathFileObject pathFileObject))
1183 return null;
1184 Path p = Locations.normalize(pathFileObject.path);
1185 // need to find p in location
1186 return locations.getLocationForModule(location, p);
1187 }
1188
1189 @Override @DefinedBy(Api.COMPILER)
1190 public void setLocationForModule(Location location, String moduleName, Collection<? extends Path> paths)
1191 throws IOException {
1192 nullCheck(location);
1193 checkModuleOrientedOrOutputLocation(location);
1194 locations.setLocationForModule(location, nullCheck(moduleName), nullCheck(paths));
1195 clearCachesForLocation(location);
1196 }
1197
1198 @Override @DefinedBy(Api.COMPILER)
1199 public String inferModuleName(Location location) {
1200 checkNotModuleOrientedLocation(location);
1201 return locations.inferModuleName(location);
1202 }
1203
1204 @Override @DefinedBy(Api.COMPILER)
1205 public Iterable<Set<Location>> listLocationsForModules(Location location) throws IOException {
1206 checkModuleOrientedOrOutputLocation(location);
1207 return locations.listLocationsForModules(location);
1208 }
1209
1210 @Override @DefinedBy(Api.COMPILER)
1211 public Path asPath(FileObject file) {
1212 if (file instanceof PathFileObject pathFileObject) {
1213 return pathFileObject.path;
1214 } else
1215 throw new IllegalArgumentException(file.getName());
1216 }
1217
1218 /**
1219 * Enforces the specification of a "relative" name as used in
1220 * {@linkplain #getFileForInput(Location,String,String)
1221 * getFileForInput}. This method must follow the rules defined in
1222 * that method, do not make any changes without consulting the
1223 * specification.
1224 */
1225 protected static boolean isRelativeUri(URI uri) {
1226 if (uri.isAbsolute())
1227 return false;
1228 String path = uri.normalize().getPath();
1229 if (path.length() == 0 /* isEmpty() is mustang API */)
1230 return false;
1231 if (!path.equals(uri.getPath())) // implicitly checks for embedded . and ..
1232 return false;
1233 if (path.startsWith("/") || path.startsWith("./") || path.startsWith("../"))
1234 return false;
1235 return true;
1236 }
1237
1238 // Convenience method
1239 protected static boolean isRelativeUri(String u) {
1240 try {
1241 return isRelativeUri(new URI(u));
1242 } catch (URISyntaxException e) {
1243 return false;
1244 }
1245 }
1246
1247 /**
1248 * Converts a relative file name to a relative URI. This is
1249 * different from File.toURI as this method does not canonicalize
1250 * the file before creating the URI. Furthermore, no schema is
1251 * used.
1252 * @param file a relative file name
1253 * @return a relative URI
1254 * @throws IllegalArgumentException if the file name is not
1255 * relative according to the definition given in {@link
1256 * javax.tools.JavaFileManager#getFileForInput}
1257 */
1258 public static String getRelativeName(File file) {
1259 if (!file.isAbsolute()) {
1260 String result = file.getPath().replace(File.separatorChar, '/');
1261 if (isRelativeUri(result))
1262 return result;
1263 }
1264 throw new IllegalArgumentException("Invalid relative path: " + file);
1265 }
1266
1267 /**
1268 * Get a detail message from an IOException.
1269 * Most, but not all, instances of IOException provide a non-null result
1270 * for getLocalizedMessage(). But some instances return null: in these
1271 * cases, fall back to getMessage(), and if even that is null, return the
1272 * name of the exception itself.
1273 * @param e an IOException
1274 * @return a string to include in a compiler diagnostic
1275 */
1276 public static String getMessage(IOException e) {
1277 String s = e.getLocalizedMessage();
1278 if (s != null)
1279 return s;
1280 s = e.getMessage();
1281 if (s != null)
1282 return s;
1283 return e.toString();
1284 }
1285
1286 private void checkOutputLocation(Location location) {
1287 Objects.requireNonNull(location);
1288 if (!location.isOutputLocation())
1289 throw new IllegalArgumentException("location is not an output location: " + location.getName());
1290 }
1291
1292 private void checkModuleOrientedOrOutputLocation(Location location) {
1293 Objects.requireNonNull(location);
1294 if (!location.isModuleOrientedLocation() && !location.isOutputLocation())
1295 throw new IllegalArgumentException(
1296 "location is not an output location or a module-oriented location: "
1297 + location.getName());
1298 }
1299
1300 private void checkNotModuleOrientedLocation(Location location) {
1301 Objects.requireNonNull(location);
1302 if (location.isModuleOrientedLocation())
1303 throw new IllegalArgumentException("location is module-oriented: " + location.getName());
1304 }
1305
1306 /* Converters between files and paths.
1307 * These are temporary until we can update the StandardJavaFileManager API.
1308 */
1309
1310 private static Iterable<Path> asPaths(final Iterable<? extends File> files) {
1311 if (files == null)
1312 return null;
1313
1314 return () -> new Iterator<Path>() {
1315 Iterator<? extends File> iter = files.iterator();
1316
1317 @Override
1318 public boolean hasNext() {
1319 return iter.hasNext();
1320 }
1321
1322 @Override
1323 public Path next() {
1324 return iter.next().toPath();
1325 }
1326 };
1327 }
1328
1329 private static Iterable<File> asFiles(final Iterable<? extends Path> paths) {
1330 if (paths == null)
1331 return null;
1332
1333 return () -> new Iterator<File>() {
1334 Iterator<? extends Path> iter = paths.iterator();
1335
1336 @Override
1337 public boolean hasNext() {
1338 return iter.hasNext();
1339 }
1340
1341 @Override
1342 public File next() {
1343 try {
1344 return iter.next().toFile();
1345 } catch (UnsupportedOperationException e) {
1346 throw new IllegalStateException(e);
1347 }
1348 }
1349 };
1350 }
1351
1352 @Override
1353 public boolean handleOption(Option option, String value) {
1354 if (javacFileManagerOptions.contains(option)) {
1355 pathsAndContainersByLocationAndRelativeDirectory.clear();
1356 nonIndexingContainersByLocation.clear();
1357 }
1358 return super.handleOption(option, value);
1359 }
1360
1361 private void clearCachesForLocation(Location location) {
1362 nullCheck(location);
1363 pathsAndContainersByLocationAndRelativeDirectory.remove(location);
1364 nonIndexingContainersByLocation.remove(location);
1365 }
1366 }