-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
Locations.java
2223 lines (1932 loc) · 79.5 KB
/
Locations.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.file;
import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.DirectoryIteratorException;
import java.nio.file.DirectoryStream;
import java.nio.file.FileSystem;
import java.nio.file.FileSystemNotFoundException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.ProviderNotFoundException;
import java.nio.file.spi.FileSystemProvider;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import javax.lang.model.SourceVersion;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileManager.Location;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardJavaFileManager.PathFactory;
import javax.tools.StandardLocation;
import jdk.internal.jmod.JmodFile;
import com.sun.tools.javac.code.Lint;
import com.sun.tools.javac.code.Lint.LintCategory;
import com.sun.tools.javac.main.Option;
import com.sun.tools.javac.resources.CompilerProperties.Errors;
import com.sun.tools.javac.resources.CompilerProperties.Warnings;
import com.sun.tools.javac.util.DefinedBy;
import com.sun.tools.javac.util.DefinedBy.Api;
import com.sun.tools.javac.util.JCDiagnostic.Warning;
import com.sun.tools.javac.util.ListBuffer;
import com.sun.tools.javac.util.Log;
import com.sun.tools.javac.jvm.ModuleNameReader;
import com.sun.tools.javac.util.Iterators;
import com.sun.tools.javac.util.Pair;
import com.sun.tools.javac.util.StringUtils;
import static javax.tools.StandardLocation.SYSTEM_MODULES;
import static javax.tools.StandardLocation.PLATFORM_CLASS_PATH;
import static com.sun.tools.javac.main.Option.BOOT_CLASS_PATH;
import static com.sun.tools.javac.main.Option.ENDORSEDDIRS;
import static com.sun.tools.javac.main.Option.EXTDIRS;
import static com.sun.tools.javac.main.Option.XBOOTCLASSPATH_APPEND;
import static com.sun.tools.javac.main.Option.XBOOTCLASSPATH_PREPEND;
/**
* This class converts command line arguments, environment variables and system properties (in
* File.pathSeparator-separated String form) into a boot class path, user class path, and source
* path (in {@code Collection<String>} form).
*
* <p>
* <b>This is NOT part of any supported API. If you write code that depends on this, you do so at
* your own risk. This code and its internal interfaces are subject to change or deletion without
* notice.</b>
*/
public class Locations {
/**
* The log to use for warning output
*/
private Log log;
/**
* Access to (possibly cached) file info
*/
private FSInfo fsInfo;
/**
* Whether to warn about non-existent path elements
*/
private boolean warn;
private ModuleNameReader moduleNameReader;
private PathFactory pathFactory = Paths::get;
static final Path javaHome = FileSystems.getDefault().getPath(System.getProperty("java.home"));
static final Path thisSystemModules = javaHome.resolve("lib").resolve("modules");
Map<Path, FileSystem> fileSystems = new LinkedHashMap<>();
List<Closeable> closeables = new ArrayList<>();
private Map<String,String> fsEnv = Collections.emptyMap();
Locations() {
initHandlers();
}
Path getPath(String first, String... more) {
try {
return pathFactory.getPath(first, more);
} catch (InvalidPathException ipe) {
throw new IllegalArgumentException(ipe);
}
}
public void close() throws IOException {
ListBuffer<IOException> list = new ListBuffer<>();
closeables.forEach(closeable -> {
try {
closeable.close();
} catch (IOException ex) {
list.add(ex);
}
});
if (list.nonEmpty()) {
IOException ex = new IOException();
for (IOException e: list)
ex.addSuppressed(e);
throw ex;
}
}
void update(Log log, boolean warn, FSInfo fsInfo) {
this.log = log;
this.warn = warn;
this.fsInfo = fsInfo;
}
void setPathFactory(PathFactory f) {
pathFactory = f;
}
boolean isDefaultBootClassPath() {
BootClassPathLocationHandler h
= (BootClassPathLocationHandler) getHandler(PLATFORM_CLASS_PATH);
return h.isDefault();
}
boolean isDefaultSystemModulesPath() {
SystemModulesLocationHandler h
= (SystemModulesLocationHandler) getHandler(SYSTEM_MODULES);
return !h.isExplicit();
}
/**
* Split a search path into its elements. Empty path elements will be ignored.
*
* @param searchPath The search path to be split
* @return The elements of the path
*/
private Iterable<Path> getPathEntries(String searchPath) {
return getPathEntries(searchPath, null);
}
/**
* Split a search path into its elements. If emptyPathDefault is not null, all empty elements in the
* path, including empty elements at either end of the path, will be replaced with the value of
* emptyPathDefault.
*
* @param searchPath The search path to be split
* @param emptyPathDefault The value to substitute for empty path elements, or null, to ignore
* empty path elements
* @return The elements of the path
*/
private Iterable<Path> getPathEntries(String searchPath, Path emptyPathDefault) {
ListBuffer<Path> entries = new ListBuffer<>();
for (String s: searchPath.split(Pattern.quote(File.pathSeparator), -1)) {
if (s.isEmpty()) {
if (emptyPathDefault != null) {
entries.add(emptyPathDefault);
}
} else {
try {
entries.add(getPath(s));
} catch (IllegalArgumentException e) {
if (warn) {
log.warning(LintCategory.PATH, Warnings.InvalidPath(s));
}
}
}
}
return entries;
}
public void setMultiReleaseValue(String multiReleaseValue) {
fsEnv = Collections.singletonMap("releaseVersion", multiReleaseValue);
}
private boolean contains(Collection<Path> searchPath, Path file) throws IOException {
if (searchPath == null) {
return false;
}
Path enclosingJar = null;
if (file.getFileSystem().provider() == fsInfo.getJarFSProvider()) {
URI uri = file.toUri();
if (uri.getScheme().equals("jar")) {
String ssp = uri.getSchemeSpecificPart();
int sep = ssp.lastIndexOf("!");
if (ssp.startsWith("file:") && sep > 0) {
enclosingJar = Paths.get(URI.create(ssp.substring(0, sep)));
}
}
}
Path nf = normalize(file);
for (Path p : searchPath) {
Path np = normalize(p);
if (np.getFileSystem() == nf.getFileSystem()
&& Files.isDirectory(np)
&& nf.startsWith(np)) {
return true;
}
if (enclosingJar != null
&& Files.isSameFile(enclosingJar, np)) {
return true;
}
}
return false;
}
/**
* Utility class to help evaluate a path option. Duplicate entries are ignored, jar class paths
* can be expanded.
*/
private class SearchPath extends LinkedHashSet<Path> {
private static final long serialVersionUID = 0;
private boolean expandJarClassPaths = false;
private final transient Set<Path> canonicalValues = new HashSet<>();
public SearchPath expandJarClassPaths(boolean x) {
expandJarClassPaths = x;
return this;
}
/**
* What to use when path element is the empty string
*/
private transient Path emptyPathDefault = null;
public SearchPath emptyPathDefault(Path x) {
emptyPathDefault = x;
return this;
}
public SearchPath addDirectories(String dirs, boolean warn) {
boolean prev = expandJarClassPaths;
expandJarClassPaths = true;
try {
if (dirs != null) {
for (Path dir : getPathEntries(dirs)) {
addDirectory(dir, warn);
}
}
return this;
} finally {
expandJarClassPaths = prev;
}
}
public SearchPath addDirectories(String dirs) {
return addDirectories(dirs, warn);
}
private void addDirectory(Path dir, boolean warn) {
if (!Files.isDirectory(dir)) {
if (warn) {
log.warning(Lint.LintCategory.PATH,
Warnings.DirPathElementNotFound(dir));
}
return;
}
try (Stream<Path> s = Files.list(dir)) {
s.filter(Locations.this::isArchive)
.forEach(dirEntry -> addFile(dirEntry, warn));
} catch (IOException ignore) {
}
}
public SearchPath addFiles(String files, boolean warn) {
if (files != null) {
addFiles(getPathEntries(files, emptyPathDefault), warn);
}
return this;
}
public SearchPath addFiles(String files) {
return addFiles(files, warn);
}
public SearchPath addFiles(Iterable<? extends Path> files, boolean warn) {
if (files != null) {
for (Path file : files) {
addFile(file, warn);
}
}
return this;
}
public SearchPath addFiles(Iterable<? extends Path> files) {
return addFiles(files, warn);
}
public void addFile(Path file, boolean warn) {
if (contains(file)) {
// discard duplicates
return;
}
if (!fsInfo.exists(file)) {
/* No such file or directory exists */
if (warn) {
log.warning(Lint.LintCategory.PATH,
Warnings.PathElementNotFound(file));
}
super.add(file);
return;
}
Path canonFile = fsInfo.getCanonicalFile(file);
if (canonicalValues.contains(canonFile)) {
/* Discard duplicates and avoid infinite recursion */
return;
}
if (fsInfo.isFile(file)) {
/* File is an ordinary file. */
if ( !file.getFileName().toString().endsWith(".jmod")
&& !file.endsWith("modules")) {
if (!isArchive(file)) {
/* Not a recognized extension; open it to see if
it looks like a valid zip file. */
try {
FileSystems.newFileSystem(file, (ClassLoader)null).close();
if (warn) {
log.warning(Lint.LintCategory.PATH,
Warnings.UnexpectedArchiveFile(file));
}
} catch (IOException | ProviderNotFoundException e) {
// FIXME: include e.getLocalizedMessage in warning
if (warn) {
log.warning(Lint.LintCategory.PATH,
Warnings.InvalidArchiveFile(file));
}
return;
}
} else {
if (fsInfo.getJarFSProvider() == null) {
log.error(Errors.NoZipfsForArchive(file));
return ;
}
}
}
}
/* Now what we have left is either a directory or a file name
conforming to archive naming convention */
super.add(file);
canonicalValues.add(canonFile);
if (expandJarClassPaths && fsInfo.isFile(file) && !file.endsWith("modules")) {
addJarClassPath(file, warn);
}
}
// Adds referenced classpath elements from a jar's Class-Path
// Manifest entry. In some future release, we may want to
// update this code to recognize URLs rather than simple
// filenames, but if we do, we should redo all path-related code.
private void addJarClassPath(Path jarFile, boolean warn) {
try {
for (Path f : fsInfo.getJarClassPath(jarFile)) {
addFile(f, warn);
}
} catch (IOException e) {
log.error(Errors.ErrorReadingFile(jarFile, JavacFileManager.getMessage(e)));
}
}
}
/**
* Base class for handling support for the representation of Locations.
*
* Locations are (by design) opaque handles that can easily be implemented
* by enums like StandardLocation. Within JavacFileManager, each Location
* has an associated LocationHandler, which provides much of the appropriate
* functionality for the corresponding Location.
*
* @see #initHandlers
* @see #getHandler
*/
protected abstract static class LocationHandler {
/**
* @see JavaFileManager#handleOption
*/
abstract boolean handleOption(Option option, String value);
/**
* @see StandardJavaFileManager#hasLocation
*/
boolean isSet() {
return (getPaths() != null);
}
abstract boolean isExplicit();
/**
* @see StandardJavaFileManager#getLocation
*/
abstract Collection<Path> getPaths();
/**
* @see StandardJavaFileManager#setLocation
*/
abstract void setPaths(Iterable<? extends Path> paths) throws IOException;
/**
* @see StandardJavaFileManager#setLocationForModule
*/
abstract void setPathsForModule(String moduleName, Iterable<? extends Path> paths)
throws IOException;
/**
* @see JavaFileManager#getLocationForModule(Location, String)
*/
Location getLocationForModule(String moduleName) throws IOException {
return null;
}
/**
* @see JavaFileManager#getLocationForModule(Location, JavaFileObject, String)
*/
Location getLocationForModule(Path file) throws IOException {
return null;
}
/**
* @see JavaFileManager#inferModuleName
*/
String inferModuleName() {
return null;
}
/**
* @see JavaFileManager#listLocationsForModules
*/
Iterable<Set<Location>> listLocationsForModules() throws IOException {
return null;
}
/**
* @see JavaFileManager#contains
*/
abstract boolean contains(Path file) throws IOException;
}
/**
* A LocationHandler for a given Location, and associated set of options.
*/
private abstract static class BasicLocationHandler extends LocationHandler {
final Location location;
final Set<Option> options;
boolean explicit;
/**
* Create a handler. The location and options provide a way to map from a location or an
* option to the corresponding handler.
*
* @param location the location for which this is the handler
* @param options the options affecting this location
* @see #initHandlers
*/
protected BasicLocationHandler(Location location, Option... options) {
this.location = location;
this.options = options.length == 0
? EnumSet.noneOf(Option.class)
: EnumSet.copyOf(Arrays.asList(options));
}
@Override
void setPathsForModule(String moduleName, Iterable<? extends Path> files) throws IOException {
// should not happen: protected by check in JavacFileManager
throw new UnsupportedOperationException("not supported for " + location);
}
protected Path checkSingletonDirectory(Iterable<? extends Path> paths) throws IOException {
Iterator<? extends Path> pathIter = paths.iterator();
if (!pathIter.hasNext()) {
throw new IllegalArgumentException("empty path for directory");
}
Path path = pathIter.next();
if (pathIter.hasNext()) {
throw new IllegalArgumentException("path too long for directory");
}
checkDirectory(path);
return path;
}
protected Path checkDirectory(Path path) throws IOException {
Objects.requireNonNull(path);
if (!Files.exists(path)) {
throw new FileNotFoundException(path + ": does not exist");
}
if (!Files.isDirectory(path)) {
throw new IOException(path + ": not a directory");
}
return path;
}
@Override
boolean isExplicit() {
return explicit;
}
}
/**
* General purpose implementation for output locations, such as -d/CLASS_OUTPUT and
* -s/SOURCE_OUTPUT. All options are treated as equivalent (i.e. aliases.)
* The value is a single file, possibly null.
*/
private class OutputLocationHandler extends BasicLocationHandler {
private Path outputDir;
private ModuleTable moduleTable;
OutputLocationHandler(Location location, Option... options) {
super(location, options);
}
@Override
boolean handleOption(Option option, String value) {
if (!options.contains(option)) {
return false;
}
explicit = true;
// TODO: could/should validate outputDir exists and is a directory
// need to decide how best to report issue for benefit of
// direct API call on JavaFileManager.handleOption(specifies IAE)
// vs. command line decoding.
outputDir = (value == null) ? null : getPath(value);
return true;
}
@Override
Collection<Path> getPaths() {
return (outputDir == null) ? null : Collections.singleton(outputDir);
}
@Override
void setPaths(Iterable<? extends Path> paths) throws IOException {
if (paths == null) {
outputDir = null;
} else {
explicit = true;
outputDir = checkSingletonDirectory(paths);
}
moduleTable = null;
listed = false;
}
@Override
Location getLocationForModule(String name) {
if (moduleTable == null) {
moduleTable = new ModuleTable();
}
ModuleLocationHandler l = moduleTable.get(name);
if (l == null) {
Path out = outputDir.resolve(name);
l = new ModuleLocationHandler(this, location.getName() + "[" + name + "]",
name, Collections.singletonList(out), true);
moduleTable.add(l);
}
return l;
}
@Override
void setPathsForModule(String name, Iterable<? extends Path> paths) throws IOException {
Path out = checkSingletonDirectory(paths);
if (moduleTable == null) {
moduleTable = new ModuleTable();
}
ModuleLocationHandler l = moduleTable.get(name);
if (l == null) {
l = new ModuleLocationHandler(this, location.getName() + "[" + name + "]",
name, Collections.singletonList(out), true);
moduleTable.add(l);
} else {
l.searchPath = Collections.singletonList(out);
moduleTable.updatePaths(l);
}
explicit = true;
}
@Override
Location getLocationForModule(Path file) {
return (moduleTable == null) ? null : moduleTable.get(file);
}
private boolean listed;
@Override
Iterable<Set<Location>> listLocationsForModules() throws IOException {
if (!listed && outputDir != null) {
try (DirectoryStream<Path> stream = Files.newDirectoryStream(outputDir)) {
for (Path p : stream) {
getLocationForModule(p.getFileName().toString());
}
}
listed = true;
}
if (moduleTable == null || moduleTable.isEmpty())
return Collections.emptySet();
return Collections.singleton(moduleTable.locations());
}
@Override
boolean contains(Path file) throws IOException {
if (moduleTable != null) {
return moduleTable.contains(file);
} else {
return (outputDir) != null && normalize(file).startsWith(normalize(outputDir));
}
}
}
/**
* General purpose implementation for search path locations,
* such as -sourcepath/SOURCE_PATH and -processorPath/ANNOTATION_PROCESSOR_PATH.
* All options are treated as equivalent (i.e. aliases.)
* The value is an ordered set of files and/or directories.
*/
private class SimpleLocationHandler extends BasicLocationHandler {
protected Collection<Path> searchPath;
SimpleLocationHandler(Location location, Option... options) {
super(location, options);
}
@Override
boolean handleOption(Option option, String value) {
if (!options.contains(option)) {
return false;
}
explicit = true;
searchPath = value == null ? null
: Collections.unmodifiableCollection(createPath().addFiles(value));
return true;
}
@Override
Collection<Path> getPaths() {
return searchPath;
}
@Override
void setPaths(Iterable<? extends Path> files) {
SearchPath p;
if (files == null) {
p = computePath(null);
} else {
explicit = true;
p = createPath().addFiles(files);
}
searchPath = Collections.unmodifiableCollection(p);
}
protected SearchPath computePath(String value) {
return createPath().addFiles(value);
}
protected SearchPath createPath() {
return new SearchPath();
}
@Override
boolean contains(Path file) throws IOException {
return Locations.this.contains(searchPath, file);
}
}
/**
* Subtype of SimpleLocationHandler for -classpath/CLASS_PATH.
* If no value is given, a default is provided, based on system properties and other values.
*/
private class ClassPathLocationHandler extends SimpleLocationHandler {
ClassPathLocationHandler() {
super(StandardLocation.CLASS_PATH, Option.CLASS_PATH);
}
@Override
Collection<Path> getPaths() {
lazy();
return searchPath;
}
@Override
protected SearchPath computePath(String value) {
String cp = value;
// CLASSPATH environment variable when run from `javac'.
if (cp == null) {
cp = System.getProperty("env.class.path");
}
// If invoked via a java VM (not the javac launcher), use the
// platform class path
if (cp == null && System.getProperty("application.home") == null) {
cp = System.getProperty("java.class.path");
}
// Default to current working directory.
if (cp == null) {
cp = ".";
}
return createPath().addFiles(cp);
}
@Override
protected SearchPath createPath() {
return new SearchPath()
.expandJarClassPaths(true) // Only search user jars for Class-Paths
.emptyPathDefault(getPath(".")); // Empty path elt ==> current directory
}
private void lazy() {
if (searchPath == null) {
setPaths(null);
}
}
}
/**
* Custom subtype of LocationHandler for PLATFORM_CLASS_PATH.
* Various options are supported for different components of the
* platform class path.
* Setting a value with setLocation overrides all existing option values.
* Setting any option overrides any value set with setLocation, and
* reverts to using default values for options that have not been set.
* Setting -bootclasspath or -Xbootclasspath overrides any existing
* value for -Xbootclasspath/p: and -Xbootclasspath/a:.
*/
private class BootClassPathLocationHandler extends BasicLocationHandler {
private Collection<Path> searchPath;
final Map<Option, String> optionValues = new EnumMap<>(Option.class);
/**
* Is the bootclasspath the default?
*/
private boolean isDefault;
BootClassPathLocationHandler() {
super(StandardLocation.PLATFORM_CLASS_PATH,
Option.BOOT_CLASS_PATH, Option.XBOOTCLASSPATH,
Option.XBOOTCLASSPATH_PREPEND,
Option.XBOOTCLASSPATH_APPEND,
Option.ENDORSEDDIRS, Option.DJAVA_ENDORSED_DIRS,
Option.EXTDIRS, Option.DJAVA_EXT_DIRS);
}
boolean isDefault() {
lazy();
return isDefault;
}
@Override
boolean handleOption(Option option, String value) {
if (!options.contains(option)) {
return false;
}
explicit = true;
option = canonicalize(option);
optionValues.put(option, value);
if (option == BOOT_CLASS_PATH) {
optionValues.remove(XBOOTCLASSPATH_PREPEND);
optionValues.remove(XBOOTCLASSPATH_APPEND);
}
searchPath = null; // reset to "uninitialized"
return true;
}
// where
// TODO: would be better if option aliasing was handled at a higher
// level
private Option canonicalize(Option option) {
switch (option) {
case XBOOTCLASSPATH:
return Option.BOOT_CLASS_PATH;
case DJAVA_ENDORSED_DIRS:
return Option.ENDORSEDDIRS;
case DJAVA_EXT_DIRS:
return Option.EXTDIRS;
default:
return option;
}
}
@Override
Collection<Path> getPaths() {
lazy();
return searchPath;
}
@Override
void setPaths(Iterable<? extends Path> files) {
if (files == null) {
searchPath = null; // reset to "uninitialized"
} else {
isDefault = false;
explicit = true;
SearchPath p = new SearchPath().addFiles(files, false);
searchPath = Collections.unmodifiableCollection(p);
optionValues.clear();
}
}
SearchPath computePath() throws IOException {
SearchPath path = new SearchPath();
String bootclasspathOpt = optionValues.get(BOOT_CLASS_PATH);
String endorseddirsOpt = optionValues.get(ENDORSEDDIRS);
String extdirsOpt = optionValues.get(EXTDIRS);
String xbootclasspathPrependOpt = optionValues.get(XBOOTCLASSPATH_PREPEND);
String xbootclasspathAppendOpt = optionValues.get(XBOOTCLASSPATH_APPEND);
path.addFiles(xbootclasspathPrependOpt);
if (endorseddirsOpt != null) {
path.addDirectories(endorseddirsOpt);
} else {
path.addDirectories(System.getProperty("java.endorsed.dirs"), false);
}
if (bootclasspathOpt != null) {
path.addFiles(bootclasspathOpt);
} else {
// Standard system classes for this compiler's release.
Collection<Path> systemClasses = systemClasses();
if (systemClasses != null) {
path.addFiles(systemClasses, false);
} else {
// fallback to the value of sun.boot.class.path
String files = System.getProperty("sun.boot.class.path");
path.addFiles(files, false);
}
}
path.addFiles(xbootclasspathAppendOpt);
// Strictly speaking, standard extensions are not bootstrap
// classes, but we treat them identically, so we'll pretend
// that they are.
if (extdirsOpt != null) {
path.addDirectories(extdirsOpt);
} else {
// Add lib/jfxrt.jar to the search path
Path jfxrt = javaHome.resolve("lib/jfxrt.jar");
if (Files.exists(jfxrt)) {
path.addFile(jfxrt, false);
}
path.addDirectories(System.getProperty("java.ext.dirs"), false);
}
isDefault =
(xbootclasspathPrependOpt == null)
&& (bootclasspathOpt == null)
&& (xbootclasspathAppendOpt == null);
return path;
}
/**
* Return a collection of files containing system classes.
* Returns {@code null} if not running on a modular image.
*
* @throws UncheckedIOException if an I/O errors occurs
*/
private Collection<Path> systemClasses() throws IOException {
// Return "modules" jimage file if available
if (Files.isRegularFile(thisSystemModules)) {
return Collections.singleton(thisSystemModules);
}
// Exploded module image
Path modules = javaHome.resolve("modules");
if (Files.isDirectory(modules.resolve("java.base"))) {
try (Stream<Path> listedModules = Files.list(modules)) {
return listedModules.toList();
}
}
// not a modular image that we know about
return null;
}
private void lazy() {
if (searchPath == null) {
try {
searchPath = Collections.unmodifiableCollection(computePath());
} catch (IOException e) {
// TODO: need better handling here, e.g. javac Abort?
throw new UncheckedIOException(e);
}
}
}
@Override
boolean contains(Path file) throws IOException {
return Locations.this.contains(searchPath, file);
}
}
/**
* A LocationHandler to represent modules found from a module-oriented
* location such as MODULE_SOURCE_PATH, UPGRADE_MODULE_PATH,
* SYSTEM_MODULES and MODULE_PATH.
*
* The Location can be specified to accept overriding classes from the
* {@code --patch-module <module>=<path> } parameter.
*/
private class ModuleLocationHandler extends LocationHandler implements Location {
private final LocationHandler parent;
private final String name;
private final String moduleName;
private final boolean output;
boolean explicit;
Collection<Path> searchPath;
ModuleLocationHandler(LocationHandler parent, String name, String moduleName,
Collection<Path> searchPath, boolean output) {
this.parent = parent;
this.name = name;