Repository navigation
Expand file tree
/
Copy pathModuleClassLoader.java
More file actions
1423 lines (1327 loc) · 53.5 KB
/
Copy pathModuleClassLoader.java
File metadata and controls
1423 lines (1327 loc) · 53.5 KB
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
package io.smallrye.modules;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.lang.module.Configuration;
import java.lang.module.ModuleFinder;
import java.lang.module.ModuleReader;
import java.lang.module.ModuleReference;
import java.net.URI;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystems;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.jboss.logging.Logger;
import io.smallrye.classfile.ClassFile;
import io.smallrye.classfile.attribute.ModuleAttribute;
import io.smallrye.classfile.attribute.ModulePackagesAttribute;
import io.smallrye.classfile.extras.constant.ConstantUtils;
import io.smallrye.classfile.extras.constant.ModuleDesc;
import io.smallrye.classfile.extras.constant.PackageDesc;
import io.smallrye.classfile.extras.reflect.AccessFlag;
import io.smallrye.common.cpu.CPU;
import io.smallrye.common.os.OS;
import io.smallrye.common.resource.MemoryResource;
import io.smallrye.common.resource.PathResource;
import io.smallrye.common.resource.Resource;
import io.smallrye.common.resource.ResourceLoader;
import io.smallrye.common.resource.ResourceUtils;
import io.smallrye.modules.desc.Dependency;
import io.smallrye.modules.desc.ModuleDescriptor;
import io.smallrye.modules.desc.PackageAccess;
import io.smallrye.modules.desc.PackageInfo;
import io.smallrye.modules.impl.Access;
import io.smallrye.modules.impl.Util;
import io.smallrye.modules.jfr.DefineDuplicateEvent;
import io.smallrye.modules.jfr.DefineFailedEvent;
import io.smallrye.modules.jfr.JfrSupport;
import io.smallrye.modules.jfr.LinkEvent;
/**
* A class loader for a module.
*/
public class ModuleClassLoader extends ClassLoader {
static {
if (!ClassLoader.registerAsParallelCapable()) {
throw new InternalError("Class loader cannot be made parallel-capable");
}
}
private static final Map<String, Module> bootModuleIndex;
static {
HashMap<String, Module> map = new HashMap<>(1000);
populateIndex(map, Util.myLayer);
bootModuleIndex = Map.copyOf(map);
}
private static void populateIndex(Map<String, Module> map, ModuleLayer layer) {
for (Module module : layer.modules()) {
for (String pn : module.getPackages()) {
map.put(pn, module);
}
}
for (ModuleLayer parent : layer.parents()) {
populateIndex(map, parent);
}
}
private final String moduleName;
private final String moduleVersion;
private final ModuleLoader moduleLoader;
private final String mainClassName;
private final Set<ModuleLayer> registeredLayers = ConcurrentHashMap.newKeySet();
/**
* The lock used for certain linking operations.
* No other lock should ever be acquired while holding this lock,
* including the lock(s) of other instances of this class.
*/
private final ReentrantLock linkLock = new ReentrantLock();
private volatile LinkState linkState;
/**
* Construct a new instance.
*
* @param config the configuration (must not be {@code null})
* @param name the non-empty class loader name, or {@code null} for no name
*/
public ModuleClassLoader(ClassLoaderConfiguration config, String name) {
super(name, null);
config.checkAndClear();
if (!isRegisteredAsParallelCapable()) {
throw new IllegalStateException("Class loader is not registered as parallel-capable");
}
this.moduleLoader = config.moduleLoader();
ModuleDescriptor descriptor = config.descriptor();
this.moduleName = descriptor.name();
this.moduleVersion = descriptor.version().orElse(null);
this.mainClassName = descriptor.mainClass().orElse(null);
this.linkState = new LinkState.New(
moduleName,
mainClassName,
descriptor.dependencies(),
config.resourceLoaders(),
descriptor.packages(),
descriptor.modifiers(),
descriptor.uses(),
descriptor.provides(),
descriptor.location().orElse(null));
}
/**
* {@return the name of this class loader}
*/
public final String getName() {
return super.getName();
}
/**
* {@return the defining module loader of this module (not {@code null})}
*/
public final ModuleLoader moduleLoader() {
return moduleLoader;
}
/**
* {@return the name of this class loader's module (not {@code null})}
*/
public String moduleName() {
return moduleName;
}
/**
* {@return the module loaded by this class loader (not {@code null})}
*/
public final Module module() {
return linkDefined().module();
}
/**
* {@return the optional main class of this module (not {@code null})}
*/
public final Optional<Class<?>> mainClass() {
String mainClassName = this.mainClassName;
if (mainClassName == null) {
return Optional.empty();
}
Class<?> mainClass;
try {
mainClass = loadClassDirect(mainClassName);
} catch (ClassNotFoundException e) {
return Optional.empty();
}
return Optional.of(mainClass);
}
private static final String archName = OS.current().name().toLowerCase(Locale.ROOT) + "-" + CPU.host().name();
/**
* {@inheritDoc}
* Searches the module's resource loaders for a native library with the given name.
*/
protected String findLibrary(String libName) {
for (ResourceLoader loader : linkDefined().resourceLoaders()) {
Resource resource;
try {
resource = loader.findResource(archName + "/" + libName);
} catch (IOException e) {
// not found
continue;
}
// todo: replace with pr.hasFile()
if (resource instanceof PathResource pr && pr.path().getFileSystem() == FileSystems.getDefault()) {
// todo: replace with pr.file()
return pr.path().toFile().getAbsolutePath();
}
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
public final Class<?> loadClass(final String name) throws ClassNotFoundException {
return loadClass(name, false);
}
/**
* {@inheritDoc}
*/
@Override
protected final Class<?> loadClass(final String name, final boolean resolve) throws ClassNotFoundException {
if (name.startsWith("[")) {
return loadClassFromDescriptor(name, 0);
}
String binaryName = name.replace('/', '.');
String packageName = Util.packageName(binaryName);
if (packageName.isEmpty() || linkNew().packages().containsKey(packageName)) {
// force full linkage
linkPackages();
return loadClassDirect(name);
}
if (bootModuleIndex.containsKey(packageName)) {
if (binaryName.equals("java.util.ServiceLoader")) {
// loading services! extra linking required
linkUses();
}
// -> BootLoader.loadClass(...)
Module module = bootModuleIndex.get(packageName);
if (!module.isExported(packageName, module())) {
throw new ClassNotFoundException("Cannot load " + name + ": package " + packageName + " not exported from "
+ module + " to " + module());
}
Class<?> result = Class.forName(module, binaryName);
if (result != null) {
return result;
}
throw new ClassNotFoundException("Cannot find " + name + " from " + this);
}
LoadedModule lm = linkPackages().modulesByPackage().get(packageName);
if (lm == null) {
throw new ClassNotFoundException(
"Class loader for " + this + " does not link against package `" + packageName + "`");
}
Class<?> loaded;
ClassLoader cl = lm.classLoader();
if (cl == this) {
loaded = loadClassDirect(binaryName);
} else {
Module module = module();
if (lm.module().isExported(packageName, module)) {
if (cl instanceof ModuleClassLoader mcl) {
loaded = mcl.loadClassDirect(binaryName);
} else {
loaded = Class.forName(binaryName, false, cl);
}
} else {
throw new ClassNotFoundException(lm.name().map(n -> "Module " + n).orElse("Unnamed module")
+ " does not export package " + packageName + " to " + module().getName());
}
}
if (resolve) {
// note: this is a no-op in OpenJDK
resolveClass(loaded);
}
return loaded;
}
/**
* Get a resource from this module that is exported to the caller.
*
* @param name the resource name (must not be {@code null})
* @return the resource, or {@code null} if not found or not accessible
*/
public final Resource getExportedResource(final String name) {
try {
return getExportedResource(name, stackWalker.walk(callerFinder));
} catch (IOException e) {
return null;
}
}
/**
* {@inheritDoc}
*/
public final URL getResource(final String name) {
Resource resource;
try {
resource = getExportedResource(name, stackWalker.walk(callerFinder));
} catch (IOException e) {
return null;
}
return resource == null ? null : resource.url();
}
/**
* {@inheritDoc}
*/
@Override
public final InputStream getResourceAsStream(final String name) {
Resource resource;
try {
resource = getExportedResource(name, stackWalker.walk(callerFinder));
return resource == null ? null : resource.openStream();
} catch (IOException e) {
return null;
}
}
/**
* Get all resources with the given name from this module that are exported to the caller.
*
* @param name the resource name (must not be {@code null})
* @return the list of accessible resources (not {@code null})
* @throws IOException if an I/O error occurs
*/
public final List<Resource> getExportedResources(final String name) throws IOException {
return getExportedResources(name, stackWalker.walk(callerFinder));
}
/**
* {@inheritDoc}
*/
@Override
public final Enumeration<URL> getResources(final String name) throws IOException {
// todo: filter to exportable resources?
List<Resource> resources = loadResourcesDirect(name);
Iterator<Resource> iterator = resources.iterator();
return new Enumeration<URL>() {
public boolean hasMoreElements() {
return iterator.hasNext();
}
public URL nextElement() {
return iterator.next().url();
}
};
}
/**
* {@inheritDoc}
*/
@Override
public final Stream<URL> resources(final String name) {
// todo: filter to exportable resources?
try {
return loadResourcesDirect(name).stream().map(Resource::url);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
/**
* {@return the set of exported package names for this module (not {@code null})}
*/
public final Set<String> exportedPackages() {
throw new UnsupportedOperationException("Not supported yet.");
}
/**
* {@return the module class loader of the calling class, or {@code null} if the calling class does not have one}
*/
public static ModuleClassLoader current() {
return stackWalker.getCallerClass().getClassLoader() instanceof ModuleClassLoader mcl ? mcl : null;
}
/**
* {@return the module class loader of the given module, or {@code null} if it does not have one}
*
* @param module the module to examine (must not be {@code null})
*/
public static ModuleClassLoader ofModule(Module module) {
return module.getClassLoader() instanceof ModuleClassLoader mcl ? mcl : null;
}
/**
* {@return the module class loader of the given thread, or {@code null} if it does not have one}
*
* @param thread the thread to examine (must not be {@code null})
*/
public static ModuleClassLoader ofThread(Thread thread) {
return thread.getContextClassLoader() instanceof ModuleClassLoader mcl ? mcl : null;
}
/**
* {@inheritDoc}
*/
public String toString() {
return "ModuleClassLoader[" + moduleName + "]";
}
// private
/**
* Get a resource from an exported and open package.
*
* @param name the resource name (must not be {@code null})
* @param caller the caller's class (must not be {@code null})
* @return the resource or {@code null} if it is not available to {@code caller}
* @throws IOException if an error occurs while getting the resource
*/
private Resource getExportedResource(final String name, Class<?> caller) throws IOException {
// loading the resource will canonicalize its path for us
Resource resource = loadResourceDirect(name);
if (resource == null) {
return null;
}
return getExportedResource0(caller, resource.pathName(), resource, null);
}
private List<Resource> getExportedResources(final String name, final Class<?> caller) throws IOException {
List<Resource> resources = loadResourcesDirect(name);
if (resources.isEmpty()) {
return List.of();
}
return getExportedResource0(caller, resources.get(0).pathName(), resources, List.of());
}
private <R> R getExportedResource0(Class<?> caller, String pathName, R resource, R defaultVal) {
if (pathName.endsWith(".class")) {
return resource;
}
if (caller == null || caller.getModule().getClassLoader() == this) {
return resource;
}
String pkgName = Util.resourcePackageName(pathName);
if (pkgName.isEmpty() || !linkDefined().packages().containsKey(pkgName)) {
return resource;
}
if (linkDefined().packages().getOrDefault(pkgName, PackageInfo.PRIVATE).packageAccess()
.isAtLeast(PackageAccess.EXPORTED)) {
return resource;
}
if (module().isOpen(pkgName, caller.getModule())) {
return resource;
}
// no access
return defaultVal;
}
// direct loaders
/**
* Load a class directly from this class loader.
*
* @param name the dot-separated ("binary") name of the class to load (must not be {@code null})
* @return the loaded class (not {@code null})
* @throws ClassNotFoundException if the class is not found in this class loader
*/
final Class<?> loadClassDirect(String name) throws ClassNotFoundException {
String binaryName = name.replace('/', '.');
Class<?> loaded = findLoadedClass(binaryName);
if (loaded != null) {
return loaded;
}
LinkState.Defined linked = linkDefined();
String packageName = Util.packageName(binaryName);
if (!packageName.isEmpty() && !linked.packages().containsKey(packageName)) {
throw new ClassNotFoundException("Class `" + name + "` is not in a package that is reachable from " + moduleName);
}
String fullPath = name.replace('.', '/') + ".class";
try {
Resource resource = loadResourceDirect(fullPath);
if (resource != null) {
// found it!
ProtectionDomain pd = linked.cachedProtectionDomain(resource);
return defineOrGetClass(binaryName, resource, pd);
}
} catch (IOException e) {
throw new ClassNotFoundException("Failed to load " + binaryName, e);
}
throw new ClassNotFoundException("Class `" + name + "` is not found in " + moduleName);
}
final Resource loadResourceDirect(String rawName) throws IOException {
String name = ResourceUtils.canonicalizeRelativePath(rawName);
if (name.equals("module-info.class")) {
// this is always loaded as a resource
return loadModuleInfo();
}
if (isServiceFileName(name)) {
if (linkNew().modifiers().contains(ModuleDescriptor.Modifier.UNNAMED)) {
return loadServicesFileDirect(name);
} else {
return null;
}
}
for (ResourceLoader loader : linkNew().resourceLoaders()) {
Resource resource = loader.findResource(name);
if (resource != null) {
return resource;
}
}
return null;
}
final List<Resource> loadResourcesDirect(final String rawName) throws IOException {
String name = ResourceUtils.canonicalizeRelativePath(rawName);
if (name.equals("module-info.class")) {
// this is always loaded as a resource
Resource moduleInfo = loadModuleInfo();
return moduleInfo == null ? List.of() : List.of(moduleInfo);
}
if (isServiceFileName(name)) {
if (linkNew().modifiers().contains(ModuleDescriptor.Modifier.UNNAMED)) {
Resource resource = loadServicesFileDirect(name);
return resource == null ? List.of() : List.of(resource);
} else {
return List.of();
}
}
try {
return linkNew().resourceLoaders().stream().map(l -> {
try {
return l.findResource(name);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}).filter(Objects::nonNull).collect(Util.toList());
} catch (UncheckedIOException e) {
throw e.getCause();
}
}
private Resource loadServicesFileDirect(final String name) {
List<String> services = linkDependencies().provides().getOrDefault(name.substring(18), List.of());
if (services.isEmpty()) {
return null;
}
String result = services.stream().collect(Collectors.joining("\n", "", "\n"));
return new MemoryResource(name, result.getBytes(StandardCharsets.UTF_8));
}
private static String getAttribute(Attributes.Name name, Attributes packageAttribute, Attributes mainAttribute,
String defVal) {
String value = null;
if (packageAttribute != null) {
value = packageAttribute.getValue(name);
}
if (value == null && mainAttribute != null) {
value = mainAttribute.getValue(name);
}
if (value == null) {
value = defVal;
}
return value;
}
final Package loadPackageDirect(final String name) {
Package pkg = getDefinedPackage(name);
if (pkg != null) {
return pkg;
}
Manifest manifest = null;
ResourceLoader loader = null;
List<ResourceLoader> list = linkDefined().resourceLoaders();
for (ResourceLoader rl : list) {
try {
manifest = rl.manifest();
} catch (IOException e) {
throw new IllegalStateException("Failed to load manifest for package " + name, e);
}
if (manifest != null) {
loader = rl;
break;
}
}
String specTitle;
String specVersion;
String specVendor;
String implTitle;
String implVersion;
String implVendor;
boolean sealed;
if (manifest == null) {
specTitle = null;
specVersion = null;
specVendor = null;
implTitle = moduleName;
implVersion = moduleVersion;
implVendor = null;
sealed = false;
} else {
Attributes ma = manifest.getMainAttributes();
String path = name.replace('.', '/') + '/';
Attributes pa = manifest.getAttributes(path);
specTitle = getAttribute(Attributes.Name.SPECIFICATION_TITLE, pa, ma, null);
specVersion = getAttribute(Attributes.Name.SPECIFICATION_VERSION, pa, ma, null);
specVendor = getAttribute(Attributes.Name.SPECIFICATION_VENDOR, pa, ma, null);
implTitle = getAttribute(Attributes.Name.IMPLEMENTATION_TITLE, pa, ma, moduleName);
implVersion = getAttribute(Attributes.Name.IMPLEMENTATION_VERSION, pa, ma, moduleVersion);
implVendor = getAttribute(Attributes.Name.IMPLEMENTATION_VENDOR, pa, ma, null);
sealed = Boolean.parseBoolean(getAttribute(Attributes.Name.SEALED, pa, ma, "false"));
}
try {
return definePackage(
name,
specTitle,
specVersion,
specVendor,
implTitle,
implVersion,
implVendor,
sealed ? loader.baseUrl() : null);
} catch (IllegalArgumentException e) {
// double check
pkg = getDefinedPackage(name);
if (pkg != null) {
return pkg;
}
throw e;
}
}
// linking
private boolean locked() {
return linkLock.isHeldByCurrentThread();
}
private <O> O doLocked(Function<ModuleClassLoader, O> operation) {
assert !locked();
ReentrantLock lock = linkLock;
lock.lock();
try {
return operation.apply(this);
} finally {
lock.unlock();
}
}
private <I, O> O doLocked(BiFunction<ModuleClassLoader, I, O> operation, I input) {
assert !locked();
ReentrantLock lock = linkLock;
lock.lock();
try {
return operation.apply(this, input);
} finally {
lock.unlock();
}
}
LinkState.New linkNew() {
LinkState linkState = this.linkState;
if (linkState instanceof LinkState.New state) {
return state;
}
assert linkState == LinkState.Closed.INSTANCE;
throw new IllegalStateException("Module " + moduleName + " has been unloaded");
}
LinkState.Dependencies linkDependencies() {
// fast path
if (linkState instanceof LinkState.Dependencies dependencies) {
return dependencies;
}
LinkState.New linkState = linkNew();
if (linkState instanceof LinkState.Dependencies dependencies) {
return dependencies;
}
LinkEvent event;
if (JfrSupport.ENABLED) {
event = new LinkEvent();
event.moduleName = moduleName;
event.moduleVersion = moduleVersion;
event.linkStage = "dependencies";
event.begin();
} else {
event = null;
}
try {
List<Dependency> lsDeps = linkState.dependencies();
ArrayList<LoadedDependency> loadedDependencies = new ArrayList<>(lsDeps.size());
for (Dependency dep : lsDeps) {
ModuleLoader ml = dep.moduleLoader().orElse(moduleLoader);
LoadedModule lm;
if (dep.modifiers().contains(Dependency.Modifier.OPTIONAL)) {
lm = ml.loadModule(dep.moduleName());
} else {
try {
lm = ml.requireModule(dep.moduleName());
} catch (ModuleLoadException e) {
throw e.withMessage(e.getMessage() + " (required by " + moduleName + ")");
}
}
if (lm != null) {
if (lm.classLoader() == this && lm.name().isPresent()) {
throw new ModuleLoadException("Module " + moduleName() + " depends on itself");
}
loadedDependencies.add(new LoadedDependency(dep, lm));
}
}
return doLocked(ModuleClassLoader::linkDependenciesLocked, loadedDependencies);
} finally {
if (event != null) {
event.commit();
}
}
}
private LinkState.Dependencies linkDependenciesLocked(List<LoadedDependency> loadedDependencies) {
LinkState.New linkState = linkNew();
if (linkState instanceof LinkState.Dependencies deps) {
return deps;
}
LinkState.Dependencies newState = new LinkState.Dependencies(linkState, loadedDependencies);
this.linkState = newState;
return newState;
}
private static Set<java.lang.module.ModuleDescriptor.Modifier> toJlmModifiers(
ModuleDescriptor.Modifier.Set modifiers) {
if (modifiers.contains(ModuleDescriptor.Modifier.AUTOMATIC)) {
return Set.of(java.lang.module.ModuleDescriptor.Modifier.AUTOMATIC);
} else if (modifiers.contains(ModuleDescriptor.Modifier.OPEN)) {
return Set.of(java.lang.module.ModuleDescriptor.Modifier.OPEN);
} else {
return Set.of();
}
}
private static final Set<java.lang.module.ModuleDescriptor.Requires.Modifier> justStatic = Set.of(
java.lang.module.ModuleDescriptor.Requires.Modifier.STATIC);
LinkState.Defined linkDefined() {
// fast path
if (linkState instanceof LinkState.Defined defined) {
return defined;
}
LinkState.New linkState = linkDependencies();
if (linkState instanceof LinkState.Defined defined) {
return defined;
}
LinkEvent event;
if (JfrSupport.ENABLED) {
event = new LinkEvent();
event.moduleName = moduleName;
event.moduleVersion = moduleVersion;
event.linkStage = "defined";
event.begin();
} else {
event = null;
}
try {
java.lang.module.ModuleDescriptor descriptor;
if (linkState.modifiers().contains(ModuleDescriptor.Modifier.UNNAMED)) {
descriptor = null;
} else {
java.lang.module.ModuleDescriptor.Builder builder = java.lang.module.ModuleDescriptor.newModule(
moduleName,
toJlmModifiers(linkState.modifiers()));
try {
java.lang.module.ModuleDescriptor.Version v = java.lang.module.ModuleDescriptor.Version
.parse(moduleVersion);
builder.version(v);
} catch (IllegalArgumentException ignored) {
}
builder.packages(linkState.packages().keySet());
if (mainClassName != null) {
// not actually used, but for completeness...
builder.mainClass(mainClassName);
}
if (!linkState.modifiers().contains(ModuleDescriptor.Modifier.AUTOMATIC)) {
linkState.packages().forEach((name, pkg) -> {
switch (pkg.packageAccess()) {
case EXPORTED -> builder.exports(name);
case OPEN -> builder.opens(name);
}
});
linkState.dependencies().forEach(d -> builder.requires(justStatic, d.moduleName()));
}
descriptor = builder.build();
}
return doLocked(ModuleClassLoader::linkDefinedLocked, descriptor);
} finally {
if (event != null) {
event.commit();
}
}
}
private static final List<Configuration> PARENT_CONFIGS = List.of(Util.myLayer.configuration());
private static final List<ModuleLayer> BOOT_LAYER_ONLY = List.of(Util.myLayer);
private LinkState.Defined linkDefinedLocked(java.lang.module.ModuleDescriptor descriptor) {
LinkState.Dependencies linkState = linkDependencies();
if (linkState instanceof LinkState.Defined defined) {
return defined;
}
LinkState.Defined defined;
if (linkState.modifiers().contains(ModuleDescriptor.Modifier.UNNAMED)) {
// nothing needed
defined = new LinkState.Defined(linkState, getUnnamedModule(), null);
} else {
// all the stuff that the JDK needs to have a module
URI uri = linkState.location();
ModuleReference modRef = new ModuleReference(descriptor, uri) {
public ModuleReader open() {
throw new UnsupportedOperationException();
}
};
final Configuration cf = Configuration.resolve(
new SingleModuleFinder(modRef),
PARENT_CONFIGS,
Util.EMPTY_MF,
List.of(moduleName));
ModuleLayer.Controller ctl = ModuleLayer.defineModules(cf, BOOT_LAYER_ONLY, ignored -> this);
ModuleLayer moduleLayer = ctl.layer();
Module module = moduleLayer.findModule(moduleName).orElseThrow(IllegalStateException::new);
if (linkState.modifiers().contains(ModuleDescriptor.Modifier.NATIVE_ACCESS)) {
Access.enableNativeAccess(module);
}
defined = new LinkState.Defined(
linkState,
module,
ctl);
defined.addReads(Util.myModule);
Util.myModule.addReads(module);
}
this.linkState = defined;
return defined;
}
LinkState.Packages linkPackages() {
// fast path
if (linkState instanceof LinkState.Packages packages) {
return packages;
}
LinkState.Defined linkState = linkDefined();
if (linkState instanceof LinkState.Packages packages) {
return packages;
}
LinkEvent event;
if (JfrSupport.ENABLED) {
event = new LinkEvent();
event.moduleName = moduleName;
event.moduleVersion = moduleVersion;
event.linkStage = "packages";
event.begin();
} else {
event = null;
}
try {
LoadedModule self = LoadedModule.forModule(linkState.module());
HashSet<LoadedModule> visited = new HashSet<>();
visited.add(self);
// link immediate dependency packages
HashMap<String, LoadedModule> modulesByPackage = new HashMap<>();
for (LoadedDependency ld : linkState.loadedDependencies()) {
Dependency dependency = ld.dependency();
LoadedModule lm = ld.loadedModule();
Module depModule = lm.module();
if (dependency.isRead()) {
linkState.addReads(depModule);
}
if (dependency.isServices()) {
// link up service loaders early; needed in case someone uses ServiceLoader.load(svc, myMCL)
// TODO in this case providers are still not registered
ModuleLayer layer = depModule.getLayer();
if (layer != ModuleLayer.boot()) {
registerLayer(layer);
}
}
boolean linked = dependency.isLinked();
linkTransitive(linkState, dependency.isRead(), linked, lm, modulesByPackage, visited);
// link up special package accesses of dependency (only for immediate dependencies)
Module myModule = module();
for (Map.Entry<String, PackageAccess> entry : dependency.packageAccesses().entrySet()) {
String pn = entry.getKey();
if (depModule.getPackages().contains(pn)) {
switch (entry.getValue()) {
case EXPORTED -> Access.addExports(depModule, pn, myModule);
case OPEN -> Access.addOpens(depModule, pn, myModule);
case PRIVATE -> {
continue;
}
}
} else {
log.warnf(
"Module %s requested access to package %s in %s, but the package is not present in that module",
moduleName(), pn, dependency.moduleName());
}
if (linked) {
modulesByPackage.putIfAbsent(pn, lm);
}
}
}
// and don't forget our own packages
for (String pkg : linkState.packages().keySet()) {
modulesByPackage.put(pkg, self);
}
// link up directed exports and opens (TODO: do this later when target module is loaded)
for (Map.Entry<String, PackageInfo> entry : linkState.packages().entrySet()) {
for (String target : entry.getValue().exportTargets()) {
LoadedModule resolved = moduleLoader().loadModule(target);
if (resolved != null) {
linkState.addExports(entry.getKey(), resolved.module());
}
}
for (String target : entry.getValue().openTargets()) {
LoadedModule resolved = moduleLoader().loadModule(target);
if (resolved != null) {
linkState.addOpens(entry.getKey(), resolved.module());
}
}
}
return doLocked(ModuleClassLoader::linkPackagesLocked, modulesByPackage);
} finally {
if (event != null) {
event.commit();
}
}
}
private LinkState.Packages linkPackagesLocked(final Map<String, LoadedModule> modulesByPackage) {
// double-check it inside the lock
LinkState.Defined defined = linkDefined();
if (defined instanceof LinkState.Packages packages) {
return packages;
}
LinkState.Packages linked = new LinkState.Packages(
defined,
Map.copyOf(modulesByPackage));
linkState = linked;
return linked;
}
/**
* Link the packages of the dependency, and then recurse to the transitive dependencies of the dependency.
*
* @param linkState this module's link state (must not be {@code null})
* @param read {@code true} to register the dependency as readable, otherwise {@code false}
* @param linked {@code true} to register the dependency as linked, otherwise {@code false}
* @param loadedModule the loaded dependency module (must not be {@code null})
* @param modulesByPackage the map being populated (must not be {@code null})
* @param visited the visited module set (must not be {@code null})
*/
private void linkTransitive(LinkState.Defined linkState, boolean read, boolean linked, LoadedModule loadedModule,
Map<String, LoadedModule> modulesByPackage, Set<LoadedModule> visited) {
if (visited.add(loadedModule)) {
if (loadedModule.classLoader() instanceof ModuleClassLoader mcl) {
if (linked) {
loadedModule.forEachExportedPackage(linkState.module(), pn -> {
modulesByPackage.putIfAbsent(pn, loadedModule);
});
}
for (LoadedDependency ld : mcl.linkDependencies().loadedDependencies()) {
Dependency dependency = ld.dependency();
boolean subLinked = linked && dependency.isLinked();
boolean subRead = read && dependency.isRead();
if (subRead) {
linkState.addReads(loadedModule.module());
}
if (dependency.isTransitive()) {
linkTransitive(linkState, subRead, subLinked, ld.loadedModule(), modulesByPackage, visited);
}
}
} else {
Module module = loadedModule.module();
java.lang.module.ModuleDescriptor descriptor = module.getDescriptor();
if (descriptor != null) {
if (linked && !ModuleLayer.boot().modules().contains(module)) {
loadedModule.forEachExportedPackage(linkState.module(), pn -> {
modulesByPackage.putIfAbsent(pn, loadedModule);
});
}
for (java.lang.module.ModuleDescriptor.Requires require : descriptor.requires()) {
if (require.modifiers().contains(java.lang.module.ModuleDescriptor.Requires.Modifier.TRANSITIVE)) {
Optional<Module> optDep = module.getLayer().findModule(require.name());
if (optDep.isEmpty()) {
if (require.modifiers().contains(java.lang.module.ModuleDescriptor.Requires.Modifier.STATIC)) {
continue;
}
throw new ModuleLoadException(
"Failed to link " + moduleName + ": dependency from " + module.getName()
+ " to " + require.name() + " is missing");
}
Module subModule = optDep.get();
LoadedModule subLm = LoadedModule.forModule(subModule);
if (read) {
linkState.addReads(loadedModule.module());
}
linkTransitive(linkState, read, linked, subLm, modulesByPackage, visited);
}
}
}
}
}
}
LinkState.Provides linkProvides() {
// fast path
if (linkState instanceof LinkState.Provides provides) {