/
JmodTask.java
1626 lines (1430 loc) · 63.4 KB
/
JmodTask.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) 2015, 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 jdk.tools.jmod;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UncheckedIOException;
import java.lang.module.Configuration;
import java.lang.module.FindException;
import java.lang.module.ModuleDescriptor;
import java.lang.module.ModuleDescriptor.Exports;
import java.lang.module.ModuleDescriptor.Opens;
import java.lang.module.ModuleDescriptor.Provides;
import java.lang.module.ModuleDescriptor.Version;
import java.lang.module.ModuleFinder;
import java.lang.module.ModuleReader;
import java.lang.module.ModuleReference;
import java.lang.module.ResolutionException;
import java.lang.module.ResolvedModule;
import java.net.URI;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.MessageFormat;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import jdk.internal.jmod.JmodFile;
import jdk.internal.jmod.JmodFile.Section;
import jdk.internal.joptsimple.BuiltinHelpFormatter;
import jdk.internal.joptsimple.NonOptionArgumentSpec;
import jdk.internal.joptsimple.OptionDescriptor;
import jdk.internal.joptsimple.OptionException;
import jdk.internal.joptsimple.OptionParser;
import jdk.internal.joptsimple.OptionSet;
import jdk.internal.joptsimple.OptionSpec;
import jdk.internal.joptsimple.ValueConverter;
import jdk.internal.module.ModuleHashes;
import jdk.internal.module.ModuleHashesBuilder;
import jdk.internal.module.ModuleInfo;
import jdk.internal.module.ModuleInfoExtender;
import jdk.internal.module.ModulePath;
import jdk.internal.module.ModuleResolution;
import jdk.internal.module.ModuleTarget;
import jdk.internal.module.Resources;
import jdk.tools.jlink.internal.Utils;
import static java.util.stream.Collectors.joining;
/**
* Implementation for the jmod tool.
*/
public class JmodTask {
static class CommandException extends RuntimeException {
private static final long serialVersionUID = 0L;
boolean showUsage;
CommandException(String key, Object... args) {
super(getMessageOrKey(key, args));
}
CommandException showUsage(boolean b) {
showUsage = b;
return this;
}
private static String getMessageOrKey(String key, Object... args) {
try {
return MessageFormat.format(ResourceBundleHelper.bundle.getString(key), args);
} catch (MissingResourceException e) {
return key;
}
}
}
private static final String PROGNAME = "jmod";
private static final String MODULE_INFO = "module-info.class";
private static final Path CWD = Paths.get("");
private Options options;
private PrintWriter out = new PrintWriter(System.out, true);
void setLog(PrintWriter out, PrintWriter err) {
this.out = out;
}
/* Result codes. */
static final int EXIT_OK = 0, // Completed with no errors.
EXIT_ERROR = 1, // Completed but reported errors.
EXIT_CMDERR = 2, // Bad command-line arguments
EXIT_SYSERR = 3, // System error or resource exhaustion.
EXIT_ABNORMAL = 4;// terminated abnormally
enum Mode {
CREATE,
EXTRACT,
LIST,
DESCRIBE,
HASH
};
static class Options {
Mode mode;
Path jmodFile;
boolean help;
boolean helpExtra;
boolean version;
List<Path> classpath;
List<Path> cmds;
List<Path> configs;
List<Path> libs;
List<Path> headerFiles;
List<Path> manPages;
List<Path> legalNotices;;
ModuleFinder moduleFinder;
Version moduleVersion;
String mainClass;
String targetPlatform;
Pattern modulesToHash;
ModuleResolution moduleResolution;
boolean dryrun;
List<PathMatcher> excludes;
Path extractDir;
LocalDateTime date;
}
// Valid --date range
static final ZonedDateTime DATE_MIN = ZonedDateTime.parse("1980-01-01T00:00:02Z");
static final ZonedDateTime DATE_MAX = ZonedDateTime.parse("2099-12-31T23:59:59Z");
public int run(String[] args) {
try {
handleOptions(args);
if (options == null) {
showUsageSummary();
return EXIT_CMDERR;
}
if (options.help || options.helpExtra) {
showHelp();
return EXIT_OK;
}
if (options.version) {
showVersion();
return EXIT_OK;
}
boolean ok;
switch (options.mode) {
case CREATE:
ok = create();
break;
case EXTRACT:
ok = extract();
break;
case LIST:
ok = list();
break;
case DESCRIBE:
ok = describe();
break;
case HASH:
ok = hashModules();
break;
default:
throw new AssertionError("Unknown mode: " + options.mode.name());
}
return ok ? EXIT_OK : EXIT_ERROR;
} catch (CommandException e) {
reportError(e.getMessage());
if (e.showUsage)
showUsageSummary();
return EXIT_CMDERR;
} catch (Exception x) {
reportError(x.getMessage());
x.printStackTrace();
return EXIT_ABNORMAL;
} finally {
out.flush();
}
}
private boolean list() throws IOException {
ZipFile zip = null;
try {
try {
zip = new ZipFile(options.jmodFile.toFile());
} catch (IOException x) {
throw new IOException("error opening jmod file", x);
}
// Trivially print the archive entries for now, pending a more complete implementation
zip.stream().forEach(e -> out.println(e.getName()));
return true;
} finally {
if (zip != null)
zip.close();
}
}
private boolean extract() throws IOException {
Path dir = options.extractDir != null ? options.extractDir : CWD;
try (JmodFile jf = new JmodFile(options.jmodFile)) {
jf.stream().forEach(e -> {
try {
ZipEntry entry = e.zipEntry();
String name = entry.getName();
int index = name.lastIndexOf("/");
if (index != -1) {
Path p = dir.resolve(name.substring(0, index));
if (Files.notExists(p))
Files.createDirectories(p);
}
try (OutputStream os = Files.newOutputStream(dir.resolve(name))) {
jf.getInputStream(e).transferTo(os);
}
} catch (IOException x) {
throw new UncheckedIOException(x);
}
});
return true;
}
}
private boolean hashModules() throws IOException {
String moduleName = null;
if (options.jmodFile != null) {
try (JmodFile jf = new JmodFile(options.jmodFile)) {
try (InputStream in = jf.getInputStream(Section.CLASSES, MODULE_INFO)) {
ModuleInfo.Attributes attrs = ModuleInfo.read(in, null);
moduleName = attrs.descriptor().name();
} catch (IOException e) {
throw new CommandException("err.module.descriptor.not.found");
}
}
}
Hasher hasher = new Hasher(moduleName, options.moduleFinder);
if (options.dryrun) {
out.println("Dry run:");
}
Map<String, ModuleHashes> moduleHashes = hasher.computeHashes();
if (moduleHashes.isEmpty()) {
throw new CommandException("err.no.moduleToHash", "\"" + options.modulesToHash + "\"");
}
moduleHashes.forEach((mn, hashes) -> {
if (options.dryrun) {
out.format("%s%n", mn);
hashes.names().stream()
.sorted()
.forEach(name -> out.format(" hashes %s %s %s%n",
name, hashes.algorithm(), toHex(hashes.hashFor(name))));
} else {
try {
hasher.updateModuleInfo(mn, hashes);
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
});
return true;
}
private boolean describe() throws IOException {
try (JmodFile jf = new JmodFile(options.jmodFile)) {
try (InputStream in = jf.getInputStream(Section.CLASSES, MODULE_INFO)) {
ModuleInfo.Attributes attrs = ModuleInfo.read(in, null);
describeModule(attrs.descriptor(),
attrs.target(),
attrs.recordedHashes());
return true;
} catch (IOException e) {
throw new CommandException("err.module.descriptor.not.found");
}
}
}
static <T> String toLowerCaseString(Collection<T> c) {
if (c.isEmpty()) { return ""; }
return " " + c.stream().map(e -> e.toString().toLowerCase(Locale.ROOT))
.sorted().collect(joining(" "));
}
static <T> String toString(Collection<T> c) {
if (c.isEmpty()) { return ""; }
return " " + c.stream().map(e -> e.toString()).sorted().collect(joining(" "));
}
private void describeModule(ModuleDescriptor md,
ModuleTarget target,
ModuleHashes hashes)
throws IOException
{
StringBuilder sb = new StringBuilder();
sb.append(md.toNameAndVersion());
if (md.isOpen())
sb.append(" open");
if (md.isAutomatic())
sb.append(" automatic");
sb.append("\n");
// unqualified exports (sorted by package)
md.exports().stream()
.sorted(Comparator.comparing(Exports::source))
.filter(e -> !e.isQualified())
.forEach(e -> sb.append("exports ").append(e.source())
.append(toLowerCaseString(e.modifiers())).append("\n"));
// dependences
md.requires().stream().sorted()
.forEach(r -> sb.append("requires ").append(r.name())
.append(toLowerCaseString(r.modifiers())).append("\n"));
// service use and provides
md.uses().stream().sorted()
.forEach(s -> sb.append("uses ").append(s).append("\n"));
md.provides().stream()
.sorted(Comparator.comparing(Provides::service))
.forEach(p -> sb.append("provides ").append(p.service())
.append(" with")
.append(toString(p.providers()))
.append("\n"));
// qualified exports
md.exports().stream()
.sorted(Comparator.comparing(Exports::source))
.filter(Exports::isQualified)
.forEach(e -> sb.append("qualified exports ").append(e.source())
.append(" to").append(toLowerCaseString(e.targets()))
.append("\n"));
// open packages
md.opens().stream()
.sorted(Comparator.comparing(Opens::source))
.filter(o -> !o.isQualified())
.forEach(o -> sb.append("opens ").append(o.source())
.append(toLowerCaseString(o.modifiers()))
.append("\n"));
md.opens().stream()
.sorted(Comparator.comparing(Opens::source))
.filter(Opens::isQualified)
.forEach(o -> sb.append("qualified opens ").append(o.source())
.append(toLowerCaseString(o.modifiers()))
.append(" to").append(toLowerCaseString(o.targets()))
.append("\n"));
// non-exported/non-open packages
Set<String> concealed = new TreeSet<>(md.packages());
md.exports().stream().map(Exports::source).forEach(concealed::remove);
md.opens().stream().map(Opens::source).forEach(concealed::remove);
concealed.forEach(p -> sb.append("contains ").append(p).append("\n"));
md.mainClass().ifPresent(v -> sb.append("main-class ").append(v).append("\n"));
if (target != null) {
String targetPlatform = target.targetPlatform();
if (!targetPlatform.isEmpty())
sb.append("platform ").append(targetPlatform).append("\n");
}
if (hashes != null) {
hashes.names().stream().sorted().forEach(
mod -> sb.append("hashes ").append(mod).append(" ")
.append(hashes.algorithm()).append(" ")
.append(toHex(hashes.hashFor(mod)))
.append("\n"));
}
out.println(sb.toString());
}
private String toHex(byte[] ba) {
StringBuilder sb = new StringBuilder(ba.length);
for (byte b: ba) {
sb.append(String.format("%02x", b & 0xff));
}
return sb.toString();
}
private boolean create() throws IOException {
JmodFileWriter jmod = new JmodFileWriter();
// create jmod with temporary name to avoid it being examined
// when scanning the module path
Path target = options.jmodFile;
Path tempTarget = jmodTempFilePath(target);
try {
try (JmodOutputStream jos = JmodOutputStream.newOutputStream(tempTarget, options.date)) {
jmod.write(jos);
}
Files.move(tempTarget, target);
} catch (Exception e) {
try {
Files.deleteIfExists(tempTarget);
} catch (IOException ioe) {
e.addSuppressed(ioe);
}
throw e;
}
return true;
}
/*
* Create a JMOD .tmp file for the given target JMOD file
*/
private static Path jmodTempFilePath(Path target) throws IOException {
return target.resolveSibling("." + target.getFileName() + ".tmp");
}
private class JmodFileWriter {
final List<Path> cmds = options.cmds;
final List<Path> libs = options.libs;
final List<Path> configs = options.configs;
final List<Path> classpath = options.classpath;
final List<Path> headerFiles = options.headerFiles;
final List<Path> manPages = options.manPages;
final List<Path> legalNotices = options.legalNotices;
final Version moduleVersion = options.moduleVersion;
final String mainClass = options.mainClass;
final String targetPlatform = options.targetPlatform;
final List<PathMatcher> excludes = options.excludes;
final ModuleResolution moduleResolution = options.moduleResolution;
JmodFileWriter() { }
/**
* Writes the jmod to the given output stream.
*/
void write(JmodOutputStream out) throws IOException {
// module-info.class
writeModuleInfo(out, findPackages(classpath));
// classes
processClasses(out, classpath);
processSection(out, Section.CONFIG, configs);
processSection(out, Section.HEADER_FILES, headerFiles);
processSection(out, Section.LEGAL_NOTICES, legalNotices);
processSection(out, Section.MAN_PAGES, manPages);
processSection(out, Section.NATIVE_CMDS, cmds);
processSection(out, Section.NATIVE_LIBS, libs);
}
/**
* Returns a supplier of an input stream to the module-info.class
* on the class path of directories and JAR files.
*/
Supplier<InputStream> newModuleInfoSupplier() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (Path e: classpath) {
if (Files.isDirectory(e)) {
Path mi = e.resolve(MODULE_INFO);
if (Files.isRegularFile(mi)) {
Files.copy(mi, baos);
break;
}
} else if (Files.isRegularFile(e) && e.toString().endsWith(".jar")) {
try (JarFile jf = new JarFile(e.toFile())) {
ZipEntry entry = jf.getEntry(MODULE_INFO);
if (entry != null) {
jf.getInputStream(entry).transferTo(baos);
break;
}
} catch (ZipException x) {
// Skip. Do nothing. No packages will be added.
}
}
}
if (baos.size() == 0) {
return null;
} else {
byte[] bytes = baos.toByteArray();
return () -> new ByteArrayInputStream(bytes);
}
}
/**
* Writes the updated module-info.class to the ZIP output stream.
*
* The updated module-info.class will have a Packages attribute
* with the set of module-private/non-exported packages.
*
* If --module-version, --main-class, or other options were provided
* then the corresponding class file attributes are added to the
* module-info here.
*/
void writeModuleInfo(JmodOutputStream out, Set<String> packages)
throws IOException
{
Supplier<InputStream> miSupplier = newModuleInfoSupplier();
if (miSupplier == null) {
throw new IOException(MODULE_INFO + " not found");
}
ModuleDescriptor descriptor;
try (InputStream in = miSupplier.get()) {
descriptor = ModuleDescriptor.read(in);
}
// copy the module-info.class into the jmod with the additional
// attributes for the version, main class and other meta data
try (InputStream in = miSupplier.get()) {
ModuleInfoExtender extender = ModuleInfoExtender.newExtender(in);
// Add (or replace) the Packages attribute
if (packages != null) {
validatePackages(descriptor, packages);
extender.packages(packages);
}
// --main-class
if (mainClass != null)
extender.mainClass(mainClass);
// --target-platform
if (targetPlatform != null) {
extender.targetPlatform(targetPlatform);
}
// --module-version
if (moduleVersion != null)
extender.version(moduleVersion);
// --hash-modules
if (options.modulesToHash != null) {
// To compute hashes, it creates a Configuration to resolve
// a module graph. The post-resolution check requires
// the packages in ModuleDescriptor be available for validation.
ModuleDescriptor md;
try (InputStream is = miSupplier.get()) {
md = ModuleDescriptor.read(is, () -> packages);
}
ModuleHashes moduleHashes = computeHashes(md);
if (moduleHashes != null) {
extender.hashes(moduleHashes);
} else {
warning("warn.no.module.hashes", descriptor.name());
}
}
if (moduleResolution != null && moduleResolution.value() != 0) {
extender.moduleResolution(moduleResolution);
}
// write the (possibly extended or modified) module-info.class
out.writeEntry(extender.toByteArray(), Section.CLASSES, MODULE_INFO);
}
}
private void validatePackages(ModuleDescriptor descriptor, Set<String> packages) {
Set<String> nonExistPackages = new TreeSet<>();
descriptor.exports().stream()
.map(Exports::source)
.filter(pn -> !packages.contains(pn))
.forEach(nonExistPackages::add);
descriptor.opens().stream()
.map(Opens::source)
.filter(pn -> !packages.contains(pn))
.forEach(nonExistPackages::add);
if (!nonExistPackages.isEmpty()) {
throw new CommandException("err.missing.export.or.open.packages",
descriptor.name(), nonExistPackages);
}
}
/*
* Hasher resolves a module graph using the --hash-modules PATTERN
* as the roots.
*
* The jmod file is being created and does not exist in the
* given modulepath.
*/
private ModuleHashes computeHashes(ModuleDescriptor descriptor) {
String mn = descriptor.name();
URI uri = options.jmodFile.toUri();
ModuleReference mref = new ModuleReference(descriptor, uri) {
@Override
public ModuleReader open() {
throw new UnsupportedOperationException("opening " + mn);
}
};
// compose a module finder with the module path and also
// a module finder that can find the jmod file being created
ModuleFinder finder = ModuleFinder.compose(options.moduleFinder,
new ModuleFinder() {
@Override
public Optional<ModuleReference> find(String name) {
if (descriptor.name().equals(name))
return Optional.of(mref);
else return Optional.empty();
}
@Override
public Set<ModuleReference> findAll() {
return Collections.singleton(mref);
}
});
return new Hasher(mn, finder).computeHashes().get(mn);
}
/**
* Returns the set of all packages on the given class path.
*/
Set<String> findPackages(List<Path> classpath) {
Set<String> packages = new HashSet<>();
for (Path path : classpath) {
if (Files.isDirectory(path)) {
packages.addAll(findPackages(path));
} else if (Files.isRegularFile(path) && path.toString().endsWith(".jar")) {
try (JarFile jf = new JarFile(path.toString())) {
packages.addAll(findPackages(jf));
} catch (ZipException x) {
// Skip. Do nothing. No packages will be added.
} catch (IOException ioe) {
throw new UncheckedIOException(ioe);
}
}
}
return packages;
}
/**
* Returns the set of packages in the given directory tree.
*/
Set<String> findPackages(Path dir) {
try {
return Files.find(dir, Integer.MAX_VALUE,
((path, attrs) -> attrs.isRegularFile()),
FileVisitOption.FOLLOW_LINKS)
.map(dir::relativize)
.filter(path -> isResource(path.toString()))
.map(path -> toPackageName(path))
.filter(pkg -> pkg.length() > 0)
.distinct()
.collect(Collectors.toSet());
} catch (IOException ioe) {
throw new UncheckedIOException(ioe);
}
}
/**
* Returns the set of packages in the given JAR file.
*/
Set<String> findPackages(JarFile jf) {
return jf.stream()
.filter(e -> !e.isDirectory() && isResource(e.getName()))
.map(e -> toPackageName(e))
.filter(pkg -> pkg.length() > 0)
.distinct()
.collect(Collectors.toSet());
}
/**
* Returns true if it's a .class or a resource with an effective
* package name.
*/
boolean isResource(String name) {
name = name.replace(File.separatorChar, '/');
return name.endsWith(".class") || Resources.canEncapsulate(name);
}
String toPackageName(Path path) {
String name = path.toString();
int index = name.lastIndexOf(File.separatorChar);
if (index != -1)
return name.substring(0, index).replace(File.separatorChar, '.');
if (name.endsWith(".class") && !name.equals(MODULE_INFO)) {
IOException e = new IOException(name + " in the unnamed package");
throw new UncheckedIOException(e);
}
return "";
}
String toPackageName(ZipEntry entry) {
String name = entry.getName();
int index = name.lastIndexOf("/");
if (index != -1)
return name.substring(0, index).replace('/', '.');
if (name.endsWith(".class") && !name.equals(MODULE_INFO)) {
IOException e = new IOException(name + " in the unnamed package");
throw new UncheckedIOException(e);
}
return "";
}
void processClasses(JmodOutputStream out, List<Path> classpaths)
throws IOException
{
if (classpaths == null)
return;
for (Path p : classpaths) {
if (Files.isDirectory(p)) {
processSection(out, Section.CLASSES, p);
} else if (Files.isRegularFile(p) && p.toString().endsWith(".jar")) {
try (JarFile jf = new JarFile(p.toFile())) {
JarEntryConsumer jec = new JarEntryConsumer(out, jf);
jf.stream().filter(jec).forEach(jec);
}
}
}
}
void processSection(JmodOutputStream out, Section section, List<Path> paths)
throws IOException
{
if (paths == null)
return;
for (Path p : paths) {
processSection(out, section, p);
}
}
void processSection(JmodOutputStream out, Section section, Path path)
throws IOException
{
// Keep a sorted set of files to be processed, so that the jmod
// content is reproducible as Files.walkFileTree order is not defined
SortedMap<String, Path> filesToProcess = new TreeMap<String, Path>();
Files.walkFileTree(path, Set.of(FileVisitOption.FOLLOW_LINKS),
Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException
{
Path relPath = path.relativize(file);
String name = relPath.toString();
if (name.equals(MODULE_INFO)) {
if (!Section.CLASSES.equals(section))
warning("warn.ignore.entry", name, section);
} else if (!matches(relPath, excludes)) {
if (out.contains(section, name)) {
warning("warn.ignore.duplicate.entry", name, section);
} else {
filesToProcess.put(name, file);
}
}
return FileVisitResult.CONTINUE;
}
});
// Process files in sorted order for deterministic jmod content
for (Map.Entry<String, Path> entry : filesToProcess.entrySet()) {
String name = entry.getKey();
Path file = entry.getValue();
try (InputStream in = Files.newInputStream(file)) {
out.writeEntry(in, section, name);
}
}
}
boolean matches(Path path, List<PathMatcher> matchers) {
if (matchers != null) {
for (PathMatcher pm : matchers) {
if (pm.matches(path))
return true;
}
}
return false;
}
class JarEntryConsumer implements Consumer<JarEntry>, Predicate<JarEntry> {
final JmodOutputStream out;
final JarFile jarfile;
JarEntryConsumer(JmodOutputStream out, JarFile jarfile) {
this.out = out;
this.jarfile = jarfile;
}
@Override
public void accept(JarEntry je) {
try (InputStream in = jarfile.getInputStream(je)) {
out.writeEntry(in, Section.CLASSES, je.getName());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Override
public boolean test(JarEntry je) {
String name = je.getName();
// ## no support for excludes. Is it really needed?
if (name.endsWith(MODULE_INFO) || je.isDirectory()) {
return false;
}
if (out.contains(Section.CLASSES, name)) {
warning("warn.ignore.duplicate.entry", name, Section.CLASSES);
return false;
}
return true;
}
}
}
/**
* Compute and record hashes
*/
private class Hasher {
final Configuration configuration;
final ModuleHashesBuilder hashesBuilder;
final Set<String> modules;
final String moduleName; // a specific module to record hashes, if set
/**
* Constructs a Hasher to compute hashes.
*
* If a module name `M` is specified, it will compute the hashes of
* modules that depend upon M directly or indirectly matching the
* specified --hash-modules pattern and record in the ModuleHashes
* attribute in M's module-info.class.
*
* If name is null, this Hasher will determine which modules to
* record hashes, i.e. the module in a subgraph of modules to be
* hashed and that has no outgoing edges. It will record in each
* of these modules, say `M`, with the hashes of modules that
* depend upon M directly or indirectly matching the specified
* --hash-modules pattern.
*
* @param name name of the module to record hashes
* @param finder module finder for the specified --module-path
*/
Hasher(String name, ModuleFinder finder) {
// Determine the modules that matches the pattern {@code modulesToHash}
Set<String> roots = finder.findAll().stream()
.map(mref -> mref.descriptor().name())
.filter(mn -> options.modulesToHash.matcher(mn).find())
.collect(Collectors.toSet());
// use system module path unless it creates a JMOD file for
// a module that is present in the system image e.g. upgradeable
// module
ModuleFinder system;
if (name != null && ModuleFinder.ofSystem().find(name).isPresent()) {
system = ModuleFinder.of();
} else {
system = ModuleFinder.ofSystem();
}
// get a resolved module graph
Configuration config = null;
try {
config = Configuration.empty().resolve(system, finder, roots);
} catch (FindException | ResolutionException e) {
throw new CommandException("err.module.resolution.fail", e.getMessage());
}
this.moduleName = name;
this.configuration = config;
// filter modules resolved from the system module finder
this.modules = config.modules().stream()
.map(ResolvedModule::name)
.filter(mn -> roots.contains(mn) && system.find(mn).isEmpty())
.collect(Collectors.toSet());
this.hashesBuilder = new ModuleHashesBuilder(config, modules);
}
/**
* Returns a map of a module M to record hashes of the modules
* that depend upon M directly or indirectly.
*
* For jmod hash command, the returned map contains one entry
* for each module M that has no outgoing edges to any of the
* modules matching the specified --hash-modules pattern.
*
* Each entry represents a leaf node in a connected subgraph containing
* M and other candidate modules from the module graph where M's outgoing
* edges to any module other than the ones matching the specified
* --hash-modules pattern are excluded.
*/
Map<String, ModuleHashes> computeHashes() {
if (hashesBuilder == null)
return null;
if (moduleName != null) {
return hashesBuilder.computeHashes(Set.of(moduleName));
} else {
return hashesBuilder.computeHashes(modules);
}
}
/**
* Reads the given input stream of module-info.class and write
* the extended module-info.class with the given ModuleHashes
*
* @param in InputStream of module-info.class
* @param out OutputStream to write the extended module-info.class
* @param hashes ModuleHashes
*/
private void recordHashes(InputStream in, OutputStream out, ModuleHashes hashes)
throws IOException
{
ModuleInfoExtender extender = ModuleInfoExtender.newExtender(in);
extender.hashes(hashes);
extender.write(out);
}
void updateModuleInfo(String name, ModuleHashes moduleHashes)
throws IOException
{
Path target = moduleToPath(name);
Path tempTarget = jmodTempFilePath(target);
try {
if (target.getFileName().toString().endsWith(".jmod")) {
updateJmodFile(target, tempTarget, moduleHashes);
} else {
updateModularJar(target, tempTarget, moduleHashes);
}
} catch (IOException|RuntimeException e) {
try {
Files.deleteIfExists(tempTarget);
} catch (IOException ioe) {
e.addSuppressed(ioe);
}
throw e;
}
out.println(getMessage("module.hashes.recorded", name));
Files.move(tempTarget, target, StandardCopyOption.REPLACE_EXISTING);
}
private void updateModularJar(Path target, Path tempTarget,
ModuleHashes moduleHashes)
throws IOException
{
try (JarFile jf = new JarFile(target.toFile());
OutputStream out = Files.newOutputStream(tempTarget);
JarOutputStream jos = new JarOutputStream(out))
{
jf.stream().forEach(e -> {
try (InputStream in = jf.getInputStream(e)) {
if (e.getName().equals(MODULE_INFO)) {
// what about module-info.class in versioned entries?
ZipEntry ze = new ZipEntry(e.getName());
if (options.date != null) {
ze.setTimeLocal(options.date);
} else {
ze.setTime(System.currentTimeMillis());