-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathClassLoader.java
More file actions
2645 lines (2470 loc) · 105 KB
/
ClassLoader.java
File metadata and controls
2645 lines (2470 loc) · 105 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
/*
* Copyright (c) 2013, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2019, Azul Systems, Inc. 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 java.lang;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
import java.io.InputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.security.cert.Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Set;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import jdk.internal.loader.BootLoader;
import jdk.internal.loader.BuiltinClassLoader;
import jdk.internal.loader.ClassLoaders;
import jdk.internal.loader.NativeLibrary;
import jdk.internal.loader.NativeLibraries;
import jdk.internal.perf.PerfCounter;
import jdk.internal.misc.Unsafe;
import jdk.internal.misc.VM;
import jdk.internal.reflect.CallerSensitive;
import jdk.internal.reflect.CallerSensitiveAdapter;
import jdk.internal.reflect.Reflection;
import jdk.internal.util.StaticProperty;
/**
* A class loader is an object that is responsible for loading classes. The
* class {@code ClassLoader} is an abstract class. Given the <a
* href="#binary-name">binary name</a> of a class, a class loader should attempt to
* locate or generate data that constitutes a definition for the class. A
* typical strategy is to transform the name into a file name and then read a
* "class file" of that name from a file system.
*
* <p> Every {@link java.lang.Class Class} object contains a {@link
* Class#getClassLoader() reference} to the {@code ClassLoader} that defined
* it.
*
* <p> {@code Class} objects for array classes are not created by class
* loaders, but are created automatically as required by the Java runtime.
* The class loader for an array class, as returned by {@link
* Class#getClassLoader()} is the same as the class loader for its element
* type; if the element type is a primitive type, then the array class has no
* class loader.
*
* <p> Applications implement subclasses of {@code ClassLoader} in order to
* extend the manner in which the Java virtual machine dynamically loads
* classes.
*
* <p> In addition to loading classes, a class loader is also responsible for
* locating resources. A resource is some data (a "{@code .class}" file,
* configuration data, or an image for example) that is identified with an
* abstract '/'-separated path name. Resources are typically packaged with an
* application or library so that they can be located by code in the
* application or library. In some cases, the resources are included so that
* they can be located by other libraries.
*
* <p> The {@code ClassLoader} class uses a delegation model to search for
* classes and resources. Each instance of {@code ClassLoader} has an
* associated parent class loader. When requested to find a class or
* resource, a {@code ClassLoader} instance will usually delegate the search
* for the class or resource to its parent class loader before attempting to
* find the class or resource itself.
*
* <p> Class loaders that support concurrent loading of classes are known as
* <em>{@linkplain #isRegisteredAsParallelCapable() parallel capable}</em> class
* loaders and are required to register themselves at their class initialization
* time by invoking the {@link
* #registerAsParallelCapable ClassLoader.registerAsParallelCapable}
* method. Note that the {@code ClassLoader} class is registered as parallel
* capable by default. However, its subclasses still need to register themselves
* if they are parallel capable.
* In environments in which the delegation model is not strictly
* hierarchical, class loaders need to be parallel capable, otherwise class
* loading can lead to deadlocks because the loader lock is held for the
* duration of the class loading process (see {@link #loadClass
* loadClass} methods).
*
* <h2> <a id="builtinLoaders">Run-time Built-in Class Loaders</a></h2>
*
* The Java run-time has the following built-in class loaders:
*
* <ul>
* <li><p>Bootstrap class loader.
* It is the virtual machine's built-in class loader, typically represented
* as {@code null}, and does not have a parent.</li>
* <li><p>{@linkplain #getPlatformClassLoader() Platform class loader}.
* The platform class loader is responsible for loading the
* <em>platform classes</em>. Platform classes include Java SE platform APIs,
* their implementation classes and JDK-specific run-time classes that are
* defined by the platform class loader or its ancestors.
* The platform class loader can be used as the parent of a {@code ClassLoader}
* instance.
* <p> To allow for upgrading/overriding of modules defined to the platform
* class loader, and where upgraded modules read modules defined to class
* loaders other than the platform class loader and its ancestors, then
* the platform class loader may have to delegate to other class loaders,
* the application class loader for example.
* In other words, classes in named modules defined to class loaders
* other than the platform class loader and its ancestors may be visible
* to the platform class loader. </li>
* <li><p>{@linkplain #getSystemClassLoader() System class loader}.
* It is also known as <em>application class loader</em> and is distinct
* from the platform class loader.
* The system class loader is typically used to define classes on the
* application class path, module path, and JDK-specific tools.
* The platform class loader is the parent or an ancestor of the system class
* loader, so the system class loader can load platform classes by delegating
* to its parent.</li>
* </ul>
*
* <p> Normally, the Java virtual machine loads classes from the local file
* system in a platform-dependent manner.
* However, some classes may not originate from a file; they may originate
* from other sources, such as the network, or they could be constructed by an
* application. The method {@link #defineClass(String, byte[], int, int)
* defineClass} converts an array of bytes into an instance of class
* {@code Class}. Instances of this newly defined class can be created using
* {@link Class#newInstance Class.newInstance}.
*
* <p> The methods and constructors of objects created by a class loader may
* reference other classes. To determine the class(es) referred to, the Java
* virtual machine invokes the {@link #loadClass loadClass} method of
* the class loader that originally created the class.
*
* <p> For example, an application could create a network class loader to
* download class files from a server. Sample code might look like:
*
* <blockquote><pre>
* ClassLoader loader = new NetworkClassLoader(host, port);
* Object main = loader.loadClass("Main", true).newInstance();
* . . .
* </pre></blockquote>
*
* <p> The network class loader subclass must define the methods {@link
* #findClass findClass} and {@code loadClassData} to load a class
* from the network. Once it has downloaded the bytes that make up the class,
* it should use the method {@link #defineClass defineClass} to
* create a class instance. A sample implementation is:
*
* <blockquote><pre>
* class NetworkClassLoader extends ClassLoader {
* String host;
* int port;
*
* public Class findClass(String name) {
* byte[] b = loadClassData(name);
* return defineClass(name, b, 0, b.length);
* }
*
* private byte[] loadClassData(String name) {
* // load the class data from the connection
* . . .
* }
* }
* </pre></blockquote>
*
* <h3> <a id="binary-name">Binary names</a> </h3>
*
* <p> Any class name provided as a {@code String} parameter to methods in
* {@code ClassLoader} must be a binary name as defined by
* <cite>The Java Language Specification</cite>.
*
* <p> Examples of valid class names include:
* <blockquote><pre>
* "java.lang.String"
* "javax.swing.JSpinner$DefaultEditor"
* "java.security.KeyStore$Builder$FileBuilder$1"
* "java.net.URLClassLoader$3$1"
* </pre></blockquote>
*
* <p> Any package name provided as a {@code String} parameter to methods in
* {@code ClassLoader} must be either the empty string (denoting an unnamed package)
* or a fully qualified name as defined by
* <cite>The Java Language Specification</cite>.
*
* @jls 6.7 Fully Qualified Names and Canonical Names
* @jls 13.1 The Form of a Binary
* @see #resolveClass(Class)
* @since 1.0
*/
@NullMarked
public abstract class ClassLoader {
private static native void registerNatives();
static {
registerNatives();
}
// The parent class loader for delegation
// Note: VM hardcoded the offset of this field, thus all new fields
// must be added *after* it.
private final @Nullable ClassLoader parent;
// class loader name
private final String name;
// the unnamed module for this ClassLoader
private final Module unnamedModule;
// a string for exception message printing
private final String nameAndId;
/**
* Encapsulates the set of parallel capable loader types.
*/
private static class ParallelLoaders {
private ParallelLoaders() {}
// the set of parallel capable loader types
private static final Set<Class<? extends ClassLoader>> loaderTypes =
Collections.newSetFromMap(new WeakHashMap<>());
static {
synchronized (loaderTypes) { loaderTypes.add(ClassLoader.class); }
}
/**
* Registers the given class loader type as parallel capable.
* Returns {@code true} is successfully registered; {@code false} if
* loader's super class is not registered.
*/
static boolean register(Class<? extends ClassLoader> c) {
synchronized (loaderTypes) {
if (loaderTypes.contains(c.getSuperclass())) {
// register the class loader as parallel capable
// if and only if all of its super classes are.
// Note: given current classloading sequence, if
// the immediate super class is parallel capable,
// all the super classes higher up must be too.
loaderTypes.add(c);
return true;
} else {
return false;
}
}
}
/**
* Returns {@code true} if the given class loader type is
* registered as parallel capable.
*/
static boolean isRegistered(Class<? extends ClassLoader> c) {
synchronized (loaderTypes) {
return loaderTypes.contains(c);
}
}
}
// Maps class name to the corresponding lock object when the current
// class loader is parallel capable.
// Note: VM also uses this field to decide if the current class loader
// is parallel capable and the appropriate lock object for class loading.
private final @Nullable ConcurrentHashMap<String, Object> parallelLockMap;
// Maps packages to certs
private final ConcurrentHashMap<String, Certificate[]> package2certs;
// Shared among all packages with unsigned classes
private static final Certificate[] nocerts = new Certificate[0];
// The classes loaded by this class loader. The only purpose of this table
// is to keep the classes from being GC'ed until the loader is GC'ed.
private final ArrayList<Class<?>> classes = new ArrayList<>();
// The "default" domain. Set as the default ProtectionDomain on newly
// created classes.
private final ProtectionDomain defaultDomain =
new ProtectionDomain(new CodeSource(null, (Certificate[]) null),
null, this, null);
// Invoked by the VM to record every loaded class with this loader.
void addClass(Class<?> c) {
synchronized (classes) {
classes.add(c);
}
}
// The packages defined in this class loader. Each package name is
// mapped to its corresponding NamedPackage object.
//
// The value is a Package object if ClassLoader::definePackage,
// Class::getPackage, ClassLoader::getDefinePackage(s) or
// Package::getPackage(s) method is called to define it.
// Otherwise, the value is a NamedPackage object.
private final ConcurrentHashMap<String, NamedPackage> packages
= new ConcurrentHashMap<>();
/*
* Returns a named package for the given module.
*/
private NamedPackage getNamedPackage(String pn, Module m) {
NamedPackage p = packages.get(pn);
if (p == null) {
p = new NamedPackage(pn, m);
NamedPackage value = packages.putIfAbsent(pn, p);
if (value != null) {
// Package object already be defined for the named package
p = value;
// if definePackage is called by this class loader to define
// a package in a named module, this will return Package
// object of the same name. Package object may contain
// unexpected information but it does not impact the runtime.
// this assertion may be helpful for troubleshooting
assert value.module() == m;
}
}
return p;
}
private static @Nullable Void checkCreateClassLoader() {
return checkCreateClassLoader(null);
}
private static Void checkCreateClassLoader(String name) {
if (name != null && name.isEmpty()) {
throw new IllegalArgumentException("name must be non-empty or null");
}
return null;
}
private ClassLoader(Void unused, String name, ClassLoader parent) {
this.name = name;
this.parent = parent;
this.unnamedModule = new Module(this);
if (ParallelLoaders.isRegistered(this.getClass())) {
parallelLockMap = new ConcurrentHashMap<>();
assertionLock = new Object();
} else {
// no finer-grained lock; lock on the classloader instance
parallelLockMap = null;
assertionLock = this;
}
this.package2certs = new ConcurrentHashMap<>();
this.nameAndId = nameAndId(this);
}
/**
* If the defining loader has a name explicitly set then
* '<loader-name>' @<id>
* If the defining loader has no name then
* <qualified-class-name> @<id>
* If it's built-in loader then omit `@<id>` as there is only one instance.
*/
private static String nameAndId(ClassLoader ld) {
String nid = ld.getName() != null ? "\'" + ld.getName() + "\'"
: ld.getClass().getName();
if (!(ld instanceof BuiltinClassLoader)) {
String id = Integer.toHexString(System.identityHashCode(ld));
nid = nid + " @" + id;
}
return nid;
}
// Returns nameAndId string for exception message printing
String nameAndId() {
return nameAndId;
}
/**
* Creates a new class loader of the specified name and using the
* specified parent class loader for delegation.
*
* @apiNote If the parent is specified as {@code null} (for the
* bootstrap class loader) then there is no guarantee that all platform
* classes are visible.
*
* @param name class loader name; or {@code null} if not named
* @param parent the parent class loader
*
* @throws IllegalArgumentException if the given name is empty.
*
* @since 9
*/
@SuppressWarnings("this-escape")
protected ClassLoader(@Nullable String name, @Nullable ClassLoader parent) {
this(checkCreateClassLoader(name), name, parent);
}
/**
* Creates a new class loader using the specified parent class loader for
* delegation.
*
* @apiNote If the parent is specified as {@code null} (for the
* bootstrap class loader) then there is no guarantee that all platform
* classes are visible.
*
* @param parent
* The parent class loader
*
* @since 1.2
*/
@SuppressWarnings("this-escape")
protected ClassLoader(@Nullable ClassLoader parent) {
this(checkCreateClassLoader(), null, parent);
}
/**
* Creates a new class loader using the {@code ClassLoader} returned by
* the method {@link #getSystemClassLoader()
* getSystemClassLoader()} as the parent class loader.
*/
@SuppressWarnings("this-escape")
protected ClassLoader() {
this(checkCreateClassLoader(), null, getSystemClassLoader());
}
/**
* Returns the name of this class loader or {@code null} if
* this class loader is not named.
*
* @apiNote This method is non-final for compatibility. If this
* method is overridden, this method must return the same name
* as specified when this class loader was instantiated.
*
* @return name of this class loader; or {@code null} if
* this class loader is not named.
*
* @since 9
*/
public @Nullable String getName() {
return name;
}
// package-private used by StackTraceElement to avoid
// calling the overridable getName method
final String name() {
return name;
}
// -- Class --
/**
* Loads the class with the specified <a href="#binary-name">binary name</a>.
* This method searches for classes in the same manner as the {@link
* #loadClass(String, boolean)} method. It is invoked by the Java virtual
* machine to resolve class references. Invoking this method is equivalent
* to invoking {@link #loadClass(String, boolean) loadClass(name,
* false)}.
*
* @param name
* The <a href="#binary-name">binary name</a> of the class
*
* @return The resulting {@code Class} object
*
* @throws ClassNotFoundException
* If the class was not found
*/
public Class<?> loadClass( String name) throws ClassNotFoundException {
return loadClass(name, false);
}
/**
* Loads the class with the specified <a href="#binary-name">binary name</a>. The
* default implementation of this method searches for classes in the
* following order:
*
* <ol>
*
* <li><p> Invoke {@link #findLoadedClass(String)} to check if the class
* has already been loaded. </p></li>
*
* <li><p> Invoke the {@link #loadClass(String) loadClass} method
* on the parent class loader. If the parent is {@code null} the class
* loader built into the virtual machine is used, instead. </p></li>
*
* <li><p> Invoke the {@link #findClass(String)} method to find the
* class. </p></li>
*
* </ol>
*
* <p> If the class was found using the above steps, and the
* {@code resolve} flag is true, this method will then invoke the {@link
* #resolveClass(Class)} method on the resulting {@code Class} object.
*
* <p> Subclasses of {@code ClassLoader} are encouraged to override {@link
* #findClass(String)}, rather than this method. </p>
*
* <p> Unless overridden, this method synchronizes on the result of
* {@link #getClassLoadingLock getClassLoadingLock} method
* during the entire class loading process.
*
* @param name
* The <a href="#binary-name">binary name</a> of the class
*
* @param resolve
* If {@code true} then resolve the class
*
* @return The resulting {@code Class} object
*
* @throws ClassNotFoundException
* If the class could not be found
*/
protected Class<?> loadClass( String name, boolean resolve)
throws ClassNotFoundException
{
synchronized (getClassLoadingLock(name)) {
// First, check if the class has already been loaded
Class<?> c = findLoadedClass(name);
if (c == null) {
long t0 = System.nanoTime();
try {
if (parent != null) {
c = parent.loadClass(name, false);
} else {
c = findBootstrapClassOrNull(name);
}
} catch (ClassNotFoundException e) {
// ClassNotFoundException thrown if class not found
// from the non-null parent class loader
}
if (c == null) {
// If still not found, then invoke findClass in order
// to find the class.
long t1 = System.nanoTime();
c = findClass(name);
// this is the defining class loader; record the stats
PerfCounter.getParentDelegationTime().addTime(t1 - t0);
PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
PerfCounter.getFindClasses().increment();
}
}
if (resolve) {
resolveClass(c);
}
return c;
}
}
/**
* Loads the class with the specified <a href="#binary-name">binary name</a>
* in a module defined to this class loader. This method returns {@code null}
* if the class could not be found.
*
* @apiNote This method does not delegate to the parent class loader.
*
* @implSpec The default implementation of this method searches for classes
* in the following order:
*
* <ol>
* <li>Invoke {@link #findLoadedClass(String)} to check if the class
* has already been loaded.</li>
* <li>Invoke the {@link #findClass(String, String)} method to find the
* class in the given module.</li>
* </ol>
*
* @param module
* The module
* @param name
* The <a href="#binary-name">binary name</a> of the class
*
* @return The resulting {@code Class} object in a module defined by
* this class loader, or {@code null} if the class could not be found.
*/
final Class<?> loadClass(Module module, String name) {
synchronized (getClassLoadingLock(name)) {
// First, check if the class has already been loaded
Class<?> c = findLoadedClass(name);
if (c == null) {
c = findClass(module.getName(), name);
}
if (c != null && c.getModule() == module) {
return c;
} else {
return null;
}
}
}
/**
* Returns the lock object for class loading operations.
*
* @implSpec
* If this {@code ClassLoader} object is registered as parallel capable,
* this method returns a dedicated object associated with the specified
* class name. Otherwise, this method returns this {@code ClassLoader} object.
*
* @apiNote
* This method allows parallel capable class loaders to implement
* finer-grained locking schemes such that multiple threads may load classes
* concurrently without deadlocks. For non-parallel-capable class loaders,
* the {@code ClassLoader} object is synchronized on during the class loading
* operations. Class loaders with non-hierarchical delegation should be
* {@linkplain #registerAsParallelCapable() registered as parallel capable}
* to prevent deadlocks.
*
* @param className
* The name of the to-be-loaded class
*
* @return the lock for class loading operations
*
* @throws NullPointerException
* If registered as parallel capable and {@code className} is {@code null}
*
* @see #loadClass(String, boolean)
*
* @since 1.7
*/
protected Object getClassLoadingLock(String className) {
Object lock = this;
if (parallelLockMap != null) {
Object newLock = new Object();
lock = parallelLockMap.putIfAbsent(className, newLock);
if (lock == null) {
lock = newLock;
}
}
return lock;
}
/**
* Finds the class with the specified <a href="#binary-name">binary name</a>.
* This method should be overridden by class loader implementations that
* follow the delegation model for loading classes, and will be invoked by
* the {@link #loadClass loadClass} method after checking the
* parent class loader for the requested class.
*
* @implSpec The default implementation throws {@code ClassNotFoundException}.
*
* @param name
* The <a href="#binary-name">binary name</a> of the class
*
* @return The resulting {@code Class} object
*
* @throws ClassNotFoundException
* If the class could not be found
*
* @since 1.2
*/
protected Class<?> findClass( String name) throws ClassNotFoundException {
throw new ClassNotFoundException(name);
}
/**
* Finds the class with the given <a href="#binary-name">binary name</a>
* in a module defined to this class loader.
* Class loader implementations that support loading from modules
* should override this method.
*
* @apiNote This method returns {@code null} rather than throwing
* {@code ClassNotFoundException} if the class could not be found.
*
* @implSpec The default implementation attempts to find the class by
* invoking {@link #findClass(String)} when the {@code moduleName} is
* {@code null}. It otherwise returns {@code null}.
*
* @param moduleName
* The module name; or {@code null} to find the class in the
* {@linkplain #getUnnamedModule() unnamed module} for this
* class loader
* @param name
* The <a href="#binary-name">binary name</a> of the class
*
* @return The resulting {@code Class} object, or {@code null}
* if the class could not be found.
*
* @since 9
*/
protected @Nullable Class<?> findClass(@Nullable String moduleName, String name) {
if (moduleName == null) {
try {
return findClass(name);
} catch (ClassNotFoundException ignore) { }
}
return null;
}
/**
* Converts an array of bytes into an instance of class {@code Class}.
* Before the {@code Class} can be used it must be resolved. This method
* is deprecated in favor of the version that takes a <a
* href="#binary-name">binary name</a> as its first argument, and is more secure.
*
* @param b
* The bytes that make up the class data. The bytes in positions
* {@code off} through {@code off+len-1} should have the format
* of a valid class file as defined by
* <cite>The Java Virtual Machine Specification</cite>.
*
* @param off
* The start offset in {@code b} of the class data
*
* @param len
* The length of the class data
*
* @return The {@code Class} object that was created from the specified
* class data
*
* @throws ClassFormatError
* If the data did not contain a valid class
*
* @throws IndexOutOfBoundsException
* If either {@code off} or {@code len} is negative, or if
* {@code off+len} is greater than {@code b.length}.
*
* @throws SecurityException
* If an attempt is made to add this class to a package that
* contains classes that were signed by a different set of
* certificates than this class, or if an attempt is made
* to define a class in a package with a fully-qualified name
* that starts with "{@code java.}".
*
* @see #loadClass(String, boolean)
* @see #resolveClass(Class)
*
* @deprecated Replaced by {@link #defineClass(String, byte[], int, int)
* defineClass(String, byte[], int, int)}
*/
@Deprecated(since="1.1")
@SuppressWarnings("signature")
protected final Class<?> defineClass(byte[] b, int off, int len)
throws ClassFormatError
{
return defineClass(null, b, off, len, null);
}
/**
* Converts an array of bytes into an instance of class {@code Class}.
* Before the {@code Class} can be used it must be resolved.
*
* <p> This method assigns a default {@link java.security.ProtectionDomain
* ProtectionDomain} to the newly defined class. The
* {@code getPermissions} method of the {@code ProtectionDomain} always
* returns {@code null}.
* The default protection domain is created on the first invocation
* of {@link #defineClass(String, byte[], int, int) defineClass},
* and re-used on subsequent invocations.
*
* <p> To assign a specific {@code ProtectionDomain} to the class, use
* the {@link #defineClass(String, byte[], int, int,
* java.security.ProtectionDomain) defineClass} method that takes a
* {@code ProtectionDomain} as one of its arguments. </p>
*
* <p>
* This method defines a package in this class loader corresponding to the
* package of the {@code Class} (if such a package has not already been defined
* in this class loader). The name of the defined package is derived from
* the <a href="#binary-name">binary name</a> of the class specified by
* the byte array {@code b}.
* Other properties of the defined package are as specified by {@link Package}.
*
* @param name
* The expected <a href="#binary-name">binary name</a> of the class, or
* {@code null} if not known
*
* @param b
* The bytes that make up the class data. The bytes in positions
* {@code off} through {@code off+len-1} should have the format
* of a valid class file as defined by
* <cite>The Java Virtual Machine Specification</cite>.
*
* @param off
* The start offset in {@code b} of the class data
*
* @param len
* The length of the class data
*
* @return The {@code Class} object that was created from the specified
* class data.
*
* @throws ClassFormatError
* If the data did not contain a valid class
*
* @throws IndexOutOfBoundsException
* If either {@code off} or {@code len} is negative, or if
* {@code off+len} is greater than {@code b.length}.
*
* @throws SecurityException
* If an attempt is made to add this class to a package that
* contains classes that were signed by a different set of
* certificates than this class (which is unsigned), or if
* {@code name} begins with "{@code java.}".
*
* @see #loadClass(String, boolean)
* @see #resolveClass(Class)
* @see java.security.CodeSource
* @see java.security.SecureClassLoader
*
* @since 1.1
*/
protected final Class<?> defineClass(@Nullable String name, byte[] b, int off, int len)
throws ClassFormatError
{
return defineClass(name, b, off, len, null);
}
/* Determine protection domain, and check that:
- not define java.* class,
- signer of this class matches signers for the rest of the classes in
package.
*/
private ProtectionDomain preDefineClass(@Nullable String name,
@Nullable ProtectionDomain pd)
{
if (!checkName(name))
throw new NoClassDefFoundError("IllegalName: " + name);
// Note: Checking logic in java.lang.invoke.MemberName.checkForTypeAlias
// relies on the fact that spoofing is impossible if a class has a name
// of the form "java.*"
if ((name != null) && name.startsWith("java.")
&& this != getBuiltinPlatformClassLoader()) {
throw new SecurityException
("Prohibited package name: " +
name.substring(0, name.lastIndexOf('.')));
}
if (pd == null) {
pd = defaultDomain;
}
if (name != null) {
checkCerts(name, pd.getCodeSource());
}
return pd;
}
private @Nullable String defineClassSourceLocation(ProtectionDomain pd) {
CodeSource cs = pd.getCodeSource();
String source = null;
if (cs != null && cs.getLocation() != null) {
source = cs.getLocation().toString();
}
return source;
}
private void postDefineClass(Class<?> c, ProtectionDomain pd) {
// define a named package, if not present
getNamedPackage(c.getPackageName(), c.getModule());
if (pd.getCodeSource() != null) {
Certificate certs[] = pd.getCodeSource().getCertificates();
if (certs != null)
setSigners(c, certs);
}
}
/**
* Converts an array of bytes into an instance of class {@code Class},
* with a given {@code ProtectionDomain}.
*
* <p> If the given {@code ProtectionDomain} is {@code null},
* then a default protection domain will be assigned to the class as specified
* in the documentation for {@link #defineClass(String, byte[], int, int)}.
* Before the class can be used it must be resolved.
*
* <p> The first class defined in a package determines the exact set of
* certificates that all subsequent classes defined in that package must
* contain. The set of certificates for a class is obtained from the
* {@link java.security.CodeSource CodeSource} within the
* {@code ProtectionDomain} of the class. Any classes added to that
* package must contain the same set of certificates or a
* {@code SecurityException} will be thrown. Note that if
* {@code name} is {@code null}, this check is not performed.
* You should always pass in the <a href="#binary-name">binary name</a> of the
* class you are defining as well as the bytes. This ensures that the
* class you are defining is indeed the class you think it is.
*
* <p> If the specified {@code name} begins with "{@code java.}", it can
* only be defined by the {@linkplain #getPlatformClassLoader()
* platform class loader} or its ancestors; otherwise {@code SecurityException}
* will be thrown. If {@code name} is not {@code null}, it must be equal to
* the <a href="#binary-name">binary name</a> of the class
* specified by the byte array {@code b}, otherwise a {@link
* NoClassDefFoundError NoClassDefFoundError} will be thrown.
*
* <p> This method defines a package in this class loader corresponding to the
* package of the {@code Class} (if such a package has not already been defined
* in this class loader). The name of the defined package is derived from
* the <a href="#binary-name">binary name</a> of the class specified by
* the byte array {@code b}.
* Other properties of the defined package are as specified by {@link Package}.
*
* @param name
* The expected <a href="#binary-name">binary name</a> of the class, or
* {@code null} if not known
*
* @param b
* The bytes that make up the class data. The bytes in positions
* {@code off} through {@code off+len-1} should have the format
* of a valid class file as defined by
* <cite>The Java Virtual Machine Specification</cite>.
*
* @param off
* The start offset in {@code b} of the class data
*
* @param len
* The length of the class data
*
* @param protectionDomain
* The {@code ProtectionDomain} of the class
*
* @return The {@code Class} object created from the data,
* and {@code ProtectionDomain}.
*
* @throws ClassFormatError
* If the data did not contain a valid class
*
* @throws NoClassDefFoundError
* If {@code name} is not {@code null} and not equal to the
* <a href="#binary-name">binary name</a> of the class specified by {@code b}
*
* @throws IndexOutOfBoundsException
* If either {@code off} or {@code len} is negative, or if
* {@code off+len} is greater than {@code b.length}.
*
* @throws SecurityException
* If an attempt is made to add this class to a package that
* contains classes that were signed by a different set of
* certificates than this class, or if {@code name} begins with
* "{@code java.}" and this class loader is not the platform
* class loader or its ancestor.
*/
protected final Class<?> defineClass(@Nullable String name, byte[] b, int off, int len,
@Nullable ProtectionDomain protectionDomain)
throws ClassFormatError
{
protectionDomain = preDefineClass(name, protectionDomain);
String source = defineClassSourceLocation(protectionDomain);
Class<?> c = defineClass1(this, name, b, off, len, protectionDomain, source);
postDefineClass(c, protectionDomain);
return c;
}
/**
* Converts a {@link java.nio.ByteBuffer ByteBuffer} into an instance
* of class {@code Class}, with the given {@code ProtectionDomain}.
* If the given {@code ProtectionDomain} is {@code null}, then a default
* protection domain will be assigned to the class as
* specified in the documentation for {@link #defineClass(String, byte[],
* int, int)}. Before the class can be used it must be resolved.
*
* <p>The rules about the first class defined in a package determining the
* set of certificates for the package, the restrictions on class names,
* and the defined package of the class
* are identical to those specified in the documentation for {@link
* #defineClass(String, byte[], int, int, ProtectionDomain)}.
*
* <p> An invocation of this method of the form
* <i>cl</i>{@code .defineClass(}<i>name</i>{@code ,}
* <i>bBuffer</i>{@code ,} <i>pd</i>{@code )} yields exactly the same
* result as the statements
*
*<p> <code>
* ...<br>
* byte[] temp = new byte[bBuffer.{@link
* java.nio.ByteBuffer#remaining remaining}()];<br>
* bBuffer.{@link java.nio.ByteBuffer#get(byte[])
* get}(temp);<br>
* return {@link #defineClass(String, byte[], int, int, ProtectionDomain)
* cl.defineClass}(name, temp, 0,
* temp.length, pd);<br>
* </code></p>