forked from kangjianwei/LearningJDK
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJarFile.java
1445 lines (1253 loc) · 56.1 KB
/
JarFile.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) 1997, 2018, 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 java.util.jar;
import java.io.ByteArrayInputStream;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.URL;
import java.security.CodeSigner;
import java.security.CodeSource;
import java.security.cert.Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import jdk.internal.misc.JavaUtilZipFileAccess;
import jdk.internal.misc.SharedSecrets;
import sun.security.action.GetPropertyAction;
import sun.security.util.ManifestEntryVerifier;
import sun.security.util.SignatureFileVerifier;
/**
* The {@code JarFile} class is used to read the contents of a jar file
* from any file that can be opened with {@code java.io.RandomAccessFile}.
* It extends the class {@code java.util.zip.ZipFile} with support
* for reading an optional {@code Manifest} entry, and support for
* processing multi-release jar files. The {@code Manifest} can be used
* to specify meta-information about the jar file and its entries.
*
* <p><a id="multirelease">A multi-release jar file</a> is a jar file that
* contains a manifest with a main attribute named "Multi-Release",
* a set of "base" entries, some of which are public classes with public
* or protected methods that comprise the public interface of the jar file,
* and a set of "versioned" entries contained in subdirectories of the
* "META-INF/versions" directory. The versioned entries are partitioned by the
* major version of the Java platform. A versioned entry, with a version
* {@code n}, {@code 8 < n}, in the "META-INF/versions/{n}" directory overrides
* the base entry as well as any entry with a version number {@code i} where
* {@code 8 < i < n}.
*
* <p>By default, a {@code JarFile} for a multi-release jar file is configured
* to process the multi-release jar file as if it were a plain (unversioned) jar
* file, and as such an entry name is associated with at most one base entry.
* The {@code JarFile} may be configured to process a multi-release jar file by
* creating the {@code JarFile} with the
* {@link JarFile#JarFile(File, boolean, int, Runtime.Version)} constructor. The
* {@code Runtime.Version} object sets a maximum version used when searching for
* versioned entries. When so configured, an entry name
* can correspond with at most one base entry and zero or more versioned
* entries. A search is required to associate the entry name with the latest
* versioned entry whose version is less than or equal to the maximum version
* (see {@link #getEntry(String)}).
*
* <p>Class loaders that utilize {@code JarFile} to load classes from the
* contents of {@code JarFile} entries should construct the {@code JarFile}
* by invoking the {@link JarFile#JarFile(File, boolean, int, Runtime.Version)}
* constructor with the value {@code Runtime.version()} assigned to the last
* argument. This assures that classes compatible with the major
* version of the running JVM are loaded from multi-release jar files.
*
* <p> If the {@code verify} flag is on when opening a signed jar file, the content
* of the jar entry is verified against the signature embedded inside the manifest
* that is associated with its {@link JarEntry#getRealName() path name}. For a
* multi-release jar file, the content of a versioned entry is verfieid against
* its own signature and {@link JarEntry#getCodeSigners()} returns its own signers.
*
* Please note that the verification process does not include validating the
* signer's certificate. A caller should inspect the return value of
* {@link JarEntry#getCodeSigners()} to further determine if the signature
* can be trusted.
*
* <p> Unless otherwise noted, passing a {@code null} argument to a constructor
* or method in this class will cause a {@link NullPointerException} to be
* thrown.
*
* @author David Connelly
* @implNote <div class="block">
* If the API can not be used to configure a {@code JarFile} (e.g. to override
* the configuration of a compiled application or library), two {@code System}
* properties are available.
* <ul>
* <li>
* {@code jdk.util.jar.version} can be assigned a value that is the
* {@code String} representation of a non-negative integer
* {@code <= Runtime.version().feature()}. The value is used to set the effective
* runtime version to something other than the default value obtained by
* evaluating {@code Runtime.version().feature()}. The effective runtime version
* is the version that the {@link JarFile#JarFile(File, boolean, int, Runtime.Version)}
* constructor uses when the value of the last argument is
* {@code JarFile.runtimeVersion()}.
* </li>
* <li>
* {@code jdk.util.jar.enableMultiRelease} can be assigned one of the three
* {@code String} values <em>true</em>, <em>false</em>, or <em>force</em>. The
* value <em>true</em>, the default value, enables multi-release jar file
* processing. The value <em>false</em> disables multi-release jar processing,
* ignoring the "Multi-Release" manifest attribute, and the versioned
* directories in a multi-release jar file if they exist. Furthermore,
* the method {@link JarFile#isMultiRelease()} returns <em>false</em>. The value
* <em>force</em> causes the {@code JarFile} to be initialized to runtime
* versioning after construction. It effectively does the same as this code:
* {@code (new JarFile(File, boolean, int, JarFile.runtimeVersion())}.
* </li>
* </ul>
* </div>
* @see Manifest
* @see java.util.zip.ZipFile
* @see java.util.jar.JarEntry
* @since 1.2
*/
// jar文件,适用于读取具有规范jar结构的压缩文件
public class JarFile extends ZipFile {
private static final String META_INF = "META-INF/";
/**
* The JAR manifest file name.
*/
public static final String MANIFEST_NAME = META_INF + "MANIFEST.MF";
private static final String META_INF_VERSIONS = META_INF + "versions/";
/** Statics for hand-coded Boyer-Moore search */
// "class-path: "
private static final byte[] CLASSPATH_CHARS = {'C', 'L', 'A', 'S', 'S', '-', 'P', 'A', 'T', 'H', ':', ' '};
/** The bad character shift for "class-path: " */
private static final byte[] CLASSPATH_LASTOCC;
/** The good suffix shift for "class-path: " */
private static final byte[] CLASSPATH_OPTOSFT;
// "multi-release: true"
private static final byte[] MULTIRELEASE_CHARS = {'M', 'U', 'L', 'T', 'I', '-', 'R', 'E', 'L', 'E', 'A', 'S', 'E', ':', ' ', 'T', 'R', 'U', 'E'};
/** The bad character shift for "multi-release: true" */
private static final byte[] MULTIRELEASE_LASTOCC;
/** The good suffix shift for "multi-release: true" */
private static final byte[] MULTIRELEASE_OPTOSFT;
private final static Runtime.Version BASE_VERSION; // 基础版本(最低兼容版本)
private final static int BASE_VERSION_FEATURE; // 基础版本(最低兼容版本)的主版本号
private final static Runtime.Version RUNTIME_VERSION; // 当前运行(兼容)的JDK版本,介于基础版本和当前JDK版本(默认)之间
private final static boolean MULTI_RELEASE_ENABLED; // 是否允许支持multi-release jar
private final static boolean MULTI_RELEASE_FORCED; // 是否需要强制支持multi-release jar
// current version
private final Runtime.Version version; // 当前使用的发行版本
// version.feature()
private final int versionFeature; // 当前使用的发行版本号
// true if manifest checked for special attributes
private volatile boolean hasCheckedSpecialAttributes; // 是否已对Class-Path和Multi-Release属性进行了检查
private JarEntry manEntry; // "META-INF/MANIFEST.MF"实体
private SoftReference<Manifest> manRef; // jar中的"META-INF/MANIFEST.MF"文件(对象)
// is jar multi-release?
private boolean isMultiRelease; // 当前jar是否为multi-release
// indicates if Class-Path attribute present
private boolean hasClassPathAttribute; // 是否包含"class-path: "属性
private boolean verify; // 是否需要校验jar
private JarVerifier jv;
private boolean jvInitialized;
private static final JavaUtilZipFileAccess JUZFA;
static {
// Set up JavaUtilJarAccess in SharedSecrets
SharedSecrets.setJavaUtilJarAccess(new JavaUtilJarAccessImpl());
// Get JavaUtilZipFileAccess from SharedSecrets
JUZFA = jdk.internal.misc.SharedSecrets.getJavaUtilZipFileAccess();
// multi-release jar file versions >= 9
BASE_VERSION = Runtime.Version.parse(Integer.toString(8)); // 基础版本(最低兼容版本)
BASE_VERSION_FEATURE = BASE_VERSION.feature(); // 基础版本(最低兼容版本)的主版本号
int runtimeVersion = Runtime.version().feature(); // 当前运行的JDK版本
// 从运行参数中解析出期望版本
String jarVersion = GetPropertyAction.privilegedGetProperty("jdk.util.jar.version");
if(jarVersion != null) {
// 期望版本的主版本号
int jarVer = Integer.parseInt(jarVersion);
runtimeVersion = (jarVer>runtimeVersion)
? runtimeVersion // 期望版本大于实际运行的JDK版本,则取实际版本
: Math.max(jarVer, BASE_VERSION_FEATURE); // 期望版本小于实际运行的版本,则取期望版本与基础版本的最大值
}
// 记录当前运行(兼容)的JDK版本,介于基础版本和当前JDK版本之间
RUNTIME_VERSION = Runtime.Version.parse(Integer.toString(runtimeVersion));
// 是否允许支持multi-release jar
String enableMultiRelease = GetPropertyAction.privilegedGetProperty("jdk.util.jar.enableMultiRelease", "true");
switch(enableMultiRelease) {
case "true":
default:
MULTI_RELEASE_ENABLED = true;
MULTI_RELEASE_FORCED = false;
break;
case "false":
MULTI_RELEASE_ENABLED = false;
MULTI_RELEASE_FORCED = false;
break;
case "force":
MULTI_RELEASE_ENABLED = true;
MULTI_RELEASE_FORCED = true;
break;
}
}
static {
CLASSPATH_LASTOCC = new byte[65];
CLASSPATH_OPTOSFT = new byte[12];
CLASSPATH_LASTOCC[(int) 'C' - 32] = 1;
CLASSPATH_LASTOCC[(int) 'L' - 32] = 2;
CLASSPATH_LASTOCC[(int) 'S' - 32] = 5;
CLASSPATH_LASTOCC[(int) '-' - 32] = 6;
CLASSPATH_LASTOCC[(int) 'P' - 32] = 7;
CLASSPATH_LASTOCC[(int) 'A' - 32] = 8;
CLASSPATH_LASTOCC[(int) 'T' - 32] = 9;
CLASSPATH_LASTOCC[(int) 'H' - 32] = 10;
CLASSPATH_LASTOCC[(int) ':' - 32] = 11;
CLASSPATH_LASTOCC[(int) ' ' - 32] = 12;
for(int i = 0; i<11; i++) {
CLASSPATH_OPTOSFT[i] = 12;
}
CLASSPATH_OPTOSFT[11] = 1;
MULTIRELEASE_LASTOCC = new byte[65];
MULTIRELEASE_OPTOSFT = new byte[19];
MULTIRELEASE_LASTOCC[(int) 'M' - 32] = 1;
MULTIRELEASE_LASTOCC[(int) 'I' - 32] = 5;
MULTIRELEASE_LASTOCC[(int) '-' - 32] = 6;
MULTIRELEASE_LASTOCC[(int) 'L' - 32] = 9;
MULTIRELEASE_LASTOCC[(int) 'A' - 32] = 11;
MULTIRELEASE_LASTOCC[(int) 'S' - 32] = 12;
MULTIRELEASE_LASTOCC[(int) ':' - 32] = 14;
MULTIRELEASE_LASTOCC[(int) ' ' - 32] = 15;
MULTIRELEASE_LASTOCC[(int) 'T' - 32] = 16;
MULTIRELEASE_LASTOCC[(int) 'R' - 32] = 17;
MULTIRELEASE_LASTOCC[(int) 'U' - 32] = 18;
MULTIRELEASE_LASTOCC[(int) 'E' - 32] = 19;
for(int i = 0; i<17; i++) {
MULTIRELEASE_OPTOSFT[i] = 19;
}
MULTIRELEASE_OPTOSFT[17] = 6;
MULTIRELEASE_OPTOSFT[18] = 1;
}
/*▼ 构造器 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Creates a new {@code JarFile} to read from the specified
* file {@code name}. The {@code JarFile} will be verified if
* it is signed.
*
* @param name the name of the jar file to be opened for reading
*
* @throws IOException if an I/O error has occurred
* @throws SecurityException if access to the file is denied
* by the SecurityManager
*/
// 打开指定名称的JarFile,需要验证
public JarFile(String name) throws IOException {
this(new File(name), true, ZipFile.OPEN_READ);
}
/**
* Creates a new {@code JarFile} to read from the specified
* file {@code name}.
*
* @param name the name of the jar file to be opened for reading
* @param verify whether or not to verify the jar file if it is signed.
*
* @throws IOException if an I/O error has occurred
* @throws SecurityException if access to the file is denied
* by the SecurityManager
*/
// 打开指定名称的JarFile,verify指示是否需要验证
public JarFile(String name, boolean verify) throws IOException {
this(new File(name), verify, ZipFile.OPEN_READ);
}
/**
* Creates a new {@code JarFile} to read from the specified
* {@code File} object. The {@code JarFile} will be verified if
* it is signed.
*
* @param file the jar file to be opened for reading
*
* @throws IOException if an I/O error has occurred
* @throws SecurityException if access to the file is denied
* by the SecurityManager
*/
// 打开指定的JarFile,需要验证
public JarFile(File file) throws IOException {
this(file, true, ZipFile.OPEN_READ);
}
/**
* Creates a new {@code JarFile} to read from the specified
* {@code File} object.
*
* @param file the jar file to be opened for reading
* @param verify whether or not to verify the jar file if
* it is signed.
*
* @throws IOException if an I/O error has occurred
* @throws SecurityException if access to the file is denied
* by the SecurityManager.
*/
// 打开指定的JarFile,verify指示是否需要验证
public JarFile(File file, boolean verify) throws IOException {
this(file, verify, ZipFile.OPEN_READ);
}
/**
* Creates a new {@code JarFile} to read from the specified
* {@code File} object in the specified mode. The mode argument
* must be either {@code OPEN_READ} or {@code OPEN_READ | OPEN_DELETE}.
*
* @param file the jar file to be opened for reading
* @param verify whether or not to verify the jar file if
* it is signed.
* @param mode the mode in which the file is to be opened
*
* @throws IOException if an I/O error has occurred
* @throws IllegalArgumentException if the {@code mode} argument is invalid
* @throws SecurityException if access to the file is denied
* by the SecurityManager
* @since 1.3
*/
public JarFile(File file, boolean verify, int mode) throws IOException {
this(file, verify, mode, BASE_VERSION);
}
/**
* Creates a new {@code JarFile} to read from the specified
* {@code File} object in the specified mode. The mode argument
* must be either {@code OPEN_READ} or {@code OPEN_READ | OPEN_DELETE}.
* The version argument, after being converted to a canonical form, is
* used to configure the {@code JarFile} for processing
* multi-release jar files.
* <p>
* The canonical form derived from the version parameter is
* {@code Runtime.Version.parse(Integer.toString(n))} where {@code n} is
* {@code Math.max(version.feature(), JarFile.baseVersion().feature())}.
*
* @param file the jar file to be opened for reading
* @param verify whether or not to verify the jar file if
* it is signed.
* @param mode the mode in which the file is to be opened
* @param version specifies the release version for a multi-release jar file
*
* @throws IOException if an I/O error has occurred
* @throws IllegalArgumentException if the {@code mode} argument is invalid
* @throws SecurityException if access to the file is denied by the SecurityManager
* @throws NullPointerException if {@code version} is {@code null}
* @since 9
*/
/*
* 打开指定的JarFile,使用UTF8编码作为解压字符集。
*
* verify - 是否需要校验jar。
* mode - 打开模式,一般为OPEN_READ或OPEN_READ|OPEN_DELETE。
* version - 指定jar的发行版本
*/
public JarFile(File file, boolean verify, int mode, Runtime.Version version) throws IOException {
super(file, mode);
Objects.requireNonNull(version);
this.verify = verify;
/* BASE_VERSION -- RUNTIME_VERSION -- JDK_VERSION */
if(MULTI_RELEASE_FORCED || version.feature() == RUNTIME_VERSION.feature()) {
// This deals with the common case where the value from JarFile.runtimeVersion() is passed
this.version = RUNTIME_VERSION;
} else if(version.feature()<=BASE_VERSION_FEATURE) {
// This also deals with the common case where the value from JarFile.baseVersion() is passed
this.version = BASE_VERSION;
} else {
// Canonicalize
this.version = Runtime.Version.parse(Integer.toString(version.feature()));
}
this.versionFeature = this.version.feature();
}
/*▲ 构造器 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ get ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns the version that represents the unversioned configuration of a
* multi-release jar file.
*
* @return the version that represents the unversioned configuration
*
* @since 9
*/
// 返回基础版本(最低兼容版本)
public static Runtime.Version baseVersion() {
return BASE_VERSION;
}
/**
* Returns the version that represents the effective runtime versioned
* configuration of a multi-release jar file.
* <p>
* By default the feature version number of the returned {@code Version} will
* be equal to the feature version number of {@code Runtime.version()}.
* However, if the {@code jdk.util.jar.version} property is set, the
* returned {@code Version} is derived from that property and feature version
* numbers may not be equal.
*
* @return the version that represents the runtime versioned configuration
*
* @since 9
*/
// 返回当前运行(兼容)的JDK版本,介于基础版本和当前JDK版本(默认)之间
public static Runtime.Version runtimeVersion() {
return RUNTIME_VERSION;
}
/**
* Returns the maximum version used when searching for versioned entries.
* <p>
* If this {@code JarFile} is not a multi-release jar file or is not
* configured to be processed as such, then the version returned will be the
* same as that returned from {@link #baseVersion()}.
*
* @return the maximum version
*
* @since 9
*/
// 如果当前jar为multi-release,返回当前使用的发行版本,否则,返回基础版本(最低兼容版本)
public final Runtime.Version getVersion() {
return isMultiRelease() ? this.version : BASE_VERSION;
}
/**
* Returns the jar file manifest, or {@code null} if none.
*
* @return the jar file manifest, or {@code null} if none
*
* @throws IllegalStateException may be thrown if the jar file has been closed
* @throws IOException if an I/O error has occurred
*/
// 返回jar中的"META-INF/MANIFEST.MF"文件(对象)
public Manifest getManifest() throws IOException {
return getManifestFromReference();
}
/**
* Returns the {@code JarEntry} for the given base entry name or
* {@code null} if not found.
*
* <p>If this {@code JarFile} is a multi-release jar file and is configured
* to be processed as such, then a search is performed to find and return
* a {@code JarEntry} that is the latest versioned entry associated with the
* given entry name. The returned {@code JarEntry} is the versioned entry
* corresponding to the given base entry name prefixed with the string
* {@code "META-INF/versions/{n}/"}, for the largest value of {@code n} for
* which an entry exists. If such a versioned entry does not exist, then
* the {@code JarEntry} for the base entry is returned, otherwise
* {@code null} is returned if no entries are found. The initial value for
* the version {@code n} is the maximum version as returned by the method
* {@link JarFile#getVersion()}.
*
* @param name the jar file entry name
*
* @return the {@code JarEntry} for the given entry name, or
* the versioned entry name, or {@code null} if not found
*
* @throws IllegalStateException may be thrown if the jar file has been closed
* @implSpec <div class="block">
* This implementation invokes {@link JarFile#getEntry(String)}.
* </div>
* @see java.util.jar.JarEntry
*/
// 返回指定名称的jar实体(在multi-release jar下,会结合发行版本信息)
public JarEntry getJarEntry(String name) {
return (JarEntry) getEntry(name);
}
/**
* Returns the {@code ZipEntry} for the given base entry name or
* {@code null} if not found.
*
* <p>If this {@code JarFile} is a multi-release jar file and is configured
* to be processed as such, then a search is performed to find and return
* a {@code ZipEntry} that is the latest versioned entry associated with the
* given entry name. The returned {@code ZipEntry} is the versioned entry
* corresponding to the given base entry name prefixed with the string
* {@code "META-INF/versions/{n}/"}, for the largest value of {@code n} for
* which an entry exists. If such a versioned entry does not exist, then
* the {@code ZipEntry} for the base entry is returned, otherwise
* {@code null} is returned if no entries are found. The initial value for
* the version {@code n} is the maximum version as returned by the method
* {@link JarFile#getVersion()}.
*
* @param name the jar file entry name
*
* @return the {@code ZipEntry} for the given entry name or
* the versioned entry name or {@code null} if not found
*
* @throws IllegalStateException may be thrown if the jar file has been closed
* @implSpec <div class="block">
* This implementation may return a versioned entry for the requested name
* even if there is not a corresponding base entry. This can occur
* if there is a private or package-private versioned entry that matches.
* If a subclass overrides this method, assure that the override method
* invokes {@code super.getEntry(name)} to obtain all versioned entries.
* </div>
* @see java.util.zip.ZipEntry
*/
// 返回指定名称的jar实体(在multi-release jar下,会结合发行版本信息)
public ZipEntry getEntry(String name) {
// 返回给定名称的实体
JarFileEntry je = getEntry0(name);
// 如果当前jar为multi-release
if(isMultiRelease()) {
// 返回当前发行版本下的指定名称的实体
return getVersionedEntry(name, je);
}
return je;
}
/**
* Returns an input stream for reading the contents of the specified
* zip file entry.
*
* @param ze the zip file entry
*
* @return an input stream for reading the contents of the specified
* zip file entry
*
* @throws ZipException if a zip file format error has occurred
* @throws IOException if an I/O error has occurred
* @throws SecurityException if any of the jar file entries
* are incorrectly signed.
* @throws IllegalStateException may be thrown if the jar file has been closed
*/
// 返回指定jar实体的输入流,以便后续对该jar进行解压(读取)
public synchronized InputStream getInputStream(ZipEntry entry) throws IOException {
maybeInstantiateVerifier();
if(jv == null) {
return super.getInputStream(entry);
}
if(!jvInitialized) {
initializeVerifier();
jvInitialized = true;
// could be set to null after a call to initializeVerifier if we have nothing to verify
if(jv == null) {
return super.getInputStream(entry);
}
}
// 获取jar中的"META-INF/MANIFEST.MF"文件(对象)
Manifest manifest = getManifestFromReference();
// 返回指定的jar实体
JarEntry jarEntry = verifiableEntry(entry);
// 返回针对指定ZipEntry条目的(解压)输入流,可从中读取解压后的数据
InputStream inputStream = super.getInputStream(entry);
/* wrap a verifier stream around the real stream */
return new JarVerifier.VerifierStream(manifest, jarEntry, inputStream, jv);
}
/*▲ get ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 集合 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns an enumeration of the jar file entries.
*
* @return an enumeration of the jar file entries
*
* @throws IllegalStateException may be thrown if the jar file has been closed
*/
// 返回一个JarEntry实体迭代器
public Enumeration<JarEntry> entries() {
return JUZFA.entries(this, JarFileEntry::new);
}
/**
* Returns an ordered {@code Stream} over the jar file entries.
* Entries appear in the {@code Stream} in the order they appear in
* the central directory of the jar file.
*
* @return an ordered {@code Stream} of entries in this jar file
*
* @throws IllegalStateException if the jar file has been closed
* @since 1.8
*/
// 返回JarEntry实体流
public Stream<JarEntry> stream() {
return JUZFA.stream(this, JarFileEntry::new);
}
/**
* Returns a {@code Stream} of the versioned jar file entries.
*
* <p>If this {@code JarFile} is a multi-release jar file and is configured to
* be processed as such, then an entry in the stream is the latest versioned entry
* associated with the corresponding base entry name. The maximum version of the
* latest versioned entry is the version returned by {@link #getVersion()}.
* The returned stream may include an entry that only exists as a versioned entry.
*
* If the jar file is not a multi-release jar file or the {@code JarFile} is not
* configured for processing a multi-release jar file, this method returns the
* same stream that {@link #stream()} returns.
*
* @return stream of versioned entries
*
* @since 10
*/
// 返回JarEntry实体流(在multi-release jar下,会结合发行版本信息)
public Stream<JarEntry> versionedStream() {
// 如果当前jar为multi-release
if(isMultiRelease()) {
return JUZFA.entryNameStream(this) // 实体名称流
.map(this::getBasename) // 获取jar实体的基础名称(去掉前面的目录)
.filter(Objects::nonNull) // 只保留非空的数据
.distinct() // 去重
.map(this::getJarEntry); // 构造指定名称的jar(在multi-release jar下,会结合发行版本信息)
}
return stream();
}
/*▲ 集合 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Indicates whether or not this jar file is a multi-release jar file.
*
* @return true if this JarFile is a multi-release jar file
*
* @since 9
*/
// 判断当前jar是否为multi-release
public final boolean isMultiRelease() {
if(isMultiRelease) {
return true;
}
// 是否允许支持multi-release jar,在JDK9之后默认是支持的
if(MULTI_RELEASE_ENABLED) {
try {
// 检验Class-Path属性和Multi-Release属性
checkForSpecialAttributes();
} catch(IOException io) {
isMultiRelease = false;
}
}
return isMultiRelease;
}
/*▲ ████████████████████████████████████████████████████████████████████████████████┛ */
/** placeholder for now */
// 返回指定的实体的名称
String getRealName(JarEntry entry) {
return entry.getRealName();
}
/**
* Returns {@code true} iff this JAR file has a manifest with the Class-Path attribute
*/
// 判断是否包含"class-path: "属性
boolean hasClassPathAttribute() throws IOException {
// 检验Class-Path属性和Multi-Release属性
checkForSpecialAttributes();
return hasClassPathAttribute;
}
/**
* Returns a versioned {@code JarFileEntry} for the given entry,
* if there is one. Otherwise returns the original entry.
* This is invoked by the {@code entries2} for verifier.
*/
// 返回指定的jar实体(在multi-release jar下,会结合发行版本信息)
JarEntry newEntry(JarEntry je) {
// 判断当前jar是否为multi-release
if(isMultiRelease()) {
String name = je.getName();
// 返回当前发行版本下的指定名称的实体
return getVersionedEntry(name, je);
}
return je;
}
/**
* Returns a versioned {@code JarFileEntry} for the given entry name,
* if there is one. Otherwise returns a {@code JarFileEntry} with the given name.
* It is invoked from JarVerifier's entries2 for {@code singers}.
*/
// 返回指定名称的jar实体(在multi-release jar下,会结合发行版本信息)
JarEntry newEntry(String name) {
// 判断当前jar是否为multi-release
if(isMultiRelease()) {
// 返回当前发行版本下的指定名称的实体
JarEntry vje = getVersionedEntry(name, null);
if(vje != null) {
return vje;
}
}
return new JarFileEntry(name);
}
/**
* Returns an enumeration of the zip file entries
* excluding internal JAR mechanism entries and including
* signed entries missing from the ZIP directory.
*/
// 返回JarEntry实体枚举器(在multi-release jar下,会结合发行版本信息)
Enumeration<JarEntry> entries2() {
ensureInitialization();
if(jv != null) {
return jv.entries2(this, JUZFA.entries(JarFile.this, JarFileEntry::new));
}
/* screen out entries which are never signed */
// 返回一个JarEntry实体迭代器
final var unfilteredEntries = JUZFA.entries(JarFile.this, JarFileEntry::new);
return new Enumeration<>() {
JarEntry entry;
// 是否包含更多未访问的jar实体
public boolean hasMoreElements() {
if(entry != null) {
return true;
}
while(unfilteredEntries.hasMoreElements()) {
JarEntry je = unfilteredEntries.nextElement();
if(JarVerifier.isSigningRelated(je.getName())) {
continue;
}
entry = je;
return true;
}
return false;
}
// 获取下一个jar实体(在multi-release jar下,会结合发行版本信息)
public JarEntry nextElement() {
if(hasMoreElements()) {
JarEntry je = entry;
entry = null;
// 返回指定的jar实体(在multi-release jar下,会结合发行版本信息)
return newEntry(je);
}
throw new NoSuchElementException();
}
};
}
Enumeration<String> entryNames(CodeSource[] cs) {
ensureInitialization();
if(jv != null) {
return jv.entryNames(this, cs);
}
/*
* JAR file has no signed content. Is there a non-signing
* code source?
*/
boolean includeUnsigned = false;
for(CodeSource c : cs) {
if(c.getCodeSigners() == null) {
includeUnsigned = true;
break;
}
}
if(includeUnsigned) {
return unsignedEntryNames();
} else {
return Collections.emptyEnumeration();
}
}
CodeSource[] getCodeSources(URL url) {
ensureInitialization();
if(jv != null) {
return jv.getCodeSources(this, url);
}
/*
* JAR file has no signed content. Is there a non-signing
* code source?
*/
Enumeration<String> unsigned = unsignedEntryNames();
if(unsigned.hasMoreElements()) {
return new CodeSource[]{JarVerifier.getUnsignedCS(url)};
} else {
return null;
}
}
CodeSource getCodeSource(URL url, String name) {
ensureInitialization();
if(jv != null) {
if(jv.eagerValidation) {
CodeSource cs = null;
JarEntry je = getJarEntry(name);
if(je != null) {
cs = jv.getCodeSource(url, this, je);
} else {
cs = jv.getCodeSource(url, name);
}
return cs;
} else {
return jv.getCodeSource(url, name);
}
}
return JarVerifier.getUnsignedCS(url);
}
void setEagerValidation(boolean eager) {
try {
maybeInstantiateVerifier();
} catch(IOException e) {
throw new RuntimeException(e);
}
if(jv != null) {
jv.setEagerValidation(eager);
}
}
List<Object> getManifestDigests() {
ensureInitialization();
if(jv != null) {
return jv.getManifestDigests();
}
return new ArrayList<>();
}
// 返回jar中的"META-INF/MANIFEST.MF"文件(对象)
private Manifest getManifestFromReference() throws IOException {
Manifest man = manRef != null ? manRef.get() : null;
if(man == null) {
// 获取"META-INF/MANIFEST.MF"实体
JarEntry manEntry = getManEntry();
/* If found then load the manifest */
if(manEntry != null) {
if(verify) {
// 将指定的ZipEntry实体解压后存入byte[]中返回
byte[] b = getBytes(manEntry);
man = new Manifest(new ByteArrayInputStream(b));
if(!jvInitialized) {
jv = new JarVerifier(b);
}
} else {
man = new Manifest(super.getInputStream(manEntry));
}
manRef = new SoftReference<>(man);
}
}
return man;
}
// 返回元数据名称(路径)列表(即META-INF(子)目录内的文件名称)
private String[] getMetaInfEntryNames() {
return JUZFA.getMetaInfEntryNames(this);
}
/**
* Invokes {@ZipFile}'s getEntry to Return a {@code JarFileEntry} for the given entry name or {@code null} if not found.
*/
// 返回给定名称的实体
private JarFileEntry getEntry0(String name) {
// Not using a lambda/method reference here to optimize startup time
Function<String, JarEntry> newJarFileEntryFn = new Function<>() {
@Override
public JarEntry apply(String name) {
return new JarFileEntry(name);
}
};
return (JarFileEntry) JUZFA.getEntry(this, name, newJarFileEntryFn);
}
// 获取jar实体的基础名称(去掉前面的目录)
private String getBasename(String name) {
// 如果name以"META-INF/versions/"开头
if(name.startsWith(META_INF_VERSIONS)) {
int off = META_INF_VERSIONS.length();
int index = name.indexOf('/', off);
try {
// filter out dir META-INF/versions/ and META-INF/versions/*/ and any entry with version > 'version'
if(index == -1 || index == (name.length() - 1) || Integer.parseInt(name, off, index, 10)>versionFeature) {
return null;
}
} catch(NumberFormatException x) {
return null; // remove malformed entries silently
}
// map to its base name
return name.substring(index + 1);
}
return name;
}
/*
* 返回当前发行版本下的指定名称的实体
*
* 比如查找com/example/A.class,但是当前使用的发行版本为9,
* 那么则需要去查找META-INF/versions/9/com/example/A.class
*