forked from kangjianwei/LearningJDK
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ObjectInputStream.java
4346 lines (3816 loc) · 173 KB
/
ObjectInputStream.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) 1996, 2017, 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.io;
import java.io.ObjectStreamClass.WeakClassKey;
import java.lang.System.Logger;
import java.lang.ref.ReferenceQueue;
import java.lang.reflect.Array;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import jdk.internal.misc.SharedSecrets;
import jdk.internal.misc.Unsafe;
import jdk.internal.misc.VM;
import sun.reflect.misc.ReflectUtil;
/**
* An ObjectInputStream deserializes primitive data and objects previously
* written using an ObjectOutputStream.
*
* <p><strong>Warning: Deserialization of untrusted data is inherently dangerous
* and should be avoided. Untrusted data should be carefully validated according to the
* "Serialization and Deserialization" section of the
* {@extLink secure_coding_guidelines_javase Secure Coding Guidelines for Java SE}.
* {@extLink serialization_filter_guide Serialization Filtering} describes best
* practices for defensive use of serial filters.
* </strong></p>
*
* <p>ObjectOutputStream and ObjectInputStream can provide an application with
* persistent storage for graphs of objects when used with a FileOutputStream
* and FileInputStream respectively. ObjectInputStream is used to recover
* those objects previously serialized. Other uses include passing objects
* between hosts using a socket stream or for marshaling and unmarshaling
* arguments and parameters in a remote communication system.
*
* <p>ObjectInputStream ensures that the types of all objects in the graph
* created from the stream match the classes present in the Java Virtual
* Machine. Classes are loaded as required using the standard mechanisms.
*
* <p>Only objects that support the java.io.Serializable or
* java.io.Externalizable interface can be read from streams.
*
* <p>The method <code>readObject</code> is used to read an object from the
* stream. Java's safe casting should be used to get the desired type. In
* Java, strings and arrays are objects and are treated as objects during
* serialization. When read they need to be cast to the expected type.
*
* <p>Primitive data types can be read from the stream using the appropriate
* method on DataInput.
*
* <p>The default deserialization mechanism for objects restores the contents
* of each field to the value and type it had when it was written. Fields
* declared as transient or static are ignored by the deserialization process.
* References to other objects cause those objects to be read from the stream
* as necessary. Graphs of objects are restored correctly using a reference
* sharing mechanism. New objects are always allocated when deserializing,
* which prevents existing objects from being overwritten.
*
* <p>Reading an object is analogous to running the constructors of a new
* object. Memory is allocated for the object and initialized to zero (NULL).
* No-arg constructors are invoked for the non-serializable classes and then
* the fields of the serializable classes are restored from the stream starting
* with the serializable class closest to java.lang.object and finishing with
* the object's most specific class.
*
* <p>For example to read from a stream as written by the example in
* ObjectOutputStream:
* <br>
* <pre>
* FileInputStream fis = new FileInputStream("t.tmp");
* ObjectInputStream ois = new ObjectInputStream(fis);
*
* int i = ois.readInt();
* String today = (String) ois.readObject();
* Date date = (Date) ois.readObject();
*
* ois.close();
* </pre>
*
* <p>Classes control how they are serialized by implementing either the
* java.io.Serializable or java.io.Externalizable interfaces.
*
* <p>Implementing the Serializable interface allows object serialization to
* save and restore the entire state of the object and it allows classes to
* evolve between the time the stream is written and the time it is read. It
* automatically traverses references between objects, saving and restoring
* entire graphs.
*
* <p>Serializable classes that require special handling during the
* serialization and deserialization process should implement the following
* methods:
*
* <pre>
* private void writeObject(java.io.ObjectOutputStream stream)
* throws IOException;
* private void readObject(java.io.ObjectInputStream stream)
* throws IOException, ClassNotFoundException;
* private void readObjectNoData()
* throws ObjectStreamException;
* </pre>
*
* <p>The readObject method is responsible for reading and restoring the state
* of the object for its particular class using data written to the stream by
* the corresponding writeObject method. The method does not need to concern
* itself with the state belonging to its superclasses or subclasses. State is
* restored by reading data from the ObjectInputStream for the individual
* fields and making assignments to the appropriate fields of the object.
* Reading primitive data types is supported by DataInput.
*
* <p>Any attempt to read object data which exceeds the boundaries of the
* custom data written by the corresponding writeObject method will cause an
* OptionalDataException to be thrown with an eof field value of true.
* Non-object reads which exceed the end of the allotted data will reflect the
* end of data in the same way that they would indicate the end of the stream:
* bytewise reads will return -1 as the byte read or number of bytes read, and
* primitive reads will throw EOFExceptions. If there is no corresponding
* writeObject method, then the end of default serialized data marks the end of
* the allotted data.
*
* <p>Primitive and object read calls issued from within a readExternal method
* behave in the same manner--if the stream is already positioned at the end of
* data written by the corresponding writeExternal method, object reads will
* throw OptionalDataExceptions with eof set to true, bytewise reads will
* return -1, and primitive reads will throw EOFExceptions. Note that this
* behavior does not hold for streams written with the old
* <code>ObjectStreamConstants.PROTOCOL_VERSION_1</code> protocol, in which the
* end of data written by writeExternal methods is not demarcated, and hence
* cannot be detected.
*
* <p>The readObjectNoData method is responsible for initializing the state of
* the object for its particular class in the event that the serialization
* stream does not list the given class as a superclass of the object being
* deserialized. This may occur in cases where the receiving party uses a
* different version of the deserialized instance's class than the sending
* party, and the receiver's version extends classes that are not extended by
* the sender's version. This may also occur if the serialization stream has
* been tampered; hence, readObjectNoData is useful for initializing
* deserialized objects properly despite a "hostile" or incomplete source
* stream.
*
* <p>Serialization does not read or assign values to the fields of any object
* that does not implement the java.io.Serializable interface. Subclasses of
* Objects that are not serializable can be serializable. In this case the
* non-serializable class must have a no-arg constructor to allow its fields to
* be initialized. In this case it is the responsibility of the subclass to
* save and restore the state of the non-serializable class. It is frequently
* the case that the fields of that class are accessible (public, package, or
* protected) or that there are get and set methods that can be used to restore
* the state.
*
* <p>The contents of the stream can be filtered during deserialization.
* If a {@linkplain #setObjectInputFilter(ObjectInputFilter) filter is set}
* on an ObjectInputStream, the {@link ObjectInputFilter} can check that
* the classes, array lengths, number of references in the stream, depth, and
* number of bytes consumed from the input stream are allowed and
* if not, can terminate deserialization.
* A {@linkplain ObjectInputFilter.Config#setSerialFilter(ObjectInputFilter) process-wide filter}
* can be configured that is applied to each {@code ObjectInputStream} unless replaced
* using {@link #setObjectInputFilter(ObjectInputFilter) setObjectInputFilter}.
*
* <p>Any exception that occurs while deserializing an object will be caught by
* the ObjectInputStream and abort the reading process.
*
* <p>Implementing the Externalizable interface allows the object to assume
* complete control over the contents and format of the object's serialized
* form. The methods of the Externalizable interface, writeExternal and
* readExternal, are called to save and restore the objects state. When
* implemented by a class they can write and read their own state using all of
* the methods of ObjectOutput and ObjectInput. It is the responsibility of
* the objects to handle any versioning that occurs.
*
* <p>Enum constants are deserialized differently than ordinary serializable or
* externalizable objects. The serialized form of an enum constant consists
* solely of its name; field values of the constant are not transmitted. To
* deserialize an enum constant, ObjectInputStream reads the constant name from
* the stream; the deserialized constant is then obtained by calling the static
* method <code>Enum.valueOf(Class, String)</code> with the enum constant's
* base type and the received constant name as arguments. Like other
* serializable or externalizable objects, enum constants can function as the
* targets of back references appearing subsequently in the serialization
* stream. The process by which enum constants are deserialized cannot be
* customized: any class-specific readObject, readObjectNoData, and readResolve
* methods defined by enum types are ignored during deserialization.
* Similarly, any serialPersistentFields or serialVersionUID field declarations
* are also ignored--all enum types have a fixed serialVersionUID of 0L.
*
* @author Mike Warres
* @author Roger Riggs
* @see java.io.DataInput
* @see java.io.ObjectOutputStream
* @see java.io.Serializable
* @see <a href="{@docRoot}/../specs/serialization/input.html">
* Object Serialization Specification, Section 3, Object Input Classes</a>
* @since 1.1
*/
/*
* 对象输入流,参与反序列化过程
*
* 对于实现了Externalizable接口的类,需要自行实现反序列化逻辑
*/
public class ObjectInputStream extends InputStream implements ObjectInput, ObjectStreamConstants {
/** handle value representing null */
private static final int NULL_HANDLE = -1;
private static final Unsafe UNSAFE = Unsafe.getUnsafe();
/** marker for unshared objects in internal handle table */
private static final Object unsharedMarker = new Object();
/**
* immutable table mapping primitive type names to corresponding
* class objects
*/
private static final Map<String, Class<?>> primClasses = Map.of(
"boolean", boolean.class,
"byte", byte.class,
"char", char.class,
"short", short.class,
"int", int.class,
"long", long.class,
"float", float.class,
"double", double.class,
"void", void.class
);
/** recursion depth */
private long depth; // 序列化嵌套深度
/** filter stream for handling block data conversion */
private final BlockDataInputStream bin; // 块数据输入流
/** wire handle -> obj/exception map */
private final HandleTable handles; // 共享对象哈希表
/** validation callback list */
private final ValidationList vlist; // 验证回调列表
/** Total number of references to any type of object, class, enum, proxy, etc. */
private long totalObjectRefs; // 总计反序列化的对象数量
/** whether stream is closed */
private boolean closed;
/** scratch field for passing handle values up/down call stack */
private int passHandle = NULL_HANDLE;
/** flag set when at end of field value block with no TC_ENDBLOCKDATA */
private boolean defaultDataEnd = false;
/** if true, invoke readObjectOverride() instead of readObject() */
private final boolean enableOverride; // 是否使用子类实现的readObjectOverride()方法,而不是使用默认的反序列化逻辑
/** if true, invoke resolveObject() */
private boolean enableResolve; // 是否需要调用resolveObject()方法,默认为false
/**
* Context during upcalls to class-defined readObject methods; holds
* object currently being deserialized and descriptor for current class.
* Null when not during readObject upcall.
*/
private SerialCallbackContext curContext; // 序列化上下文
/**
* Filter of class descriptors and classes read from the stream;
* may be null.
*/
private ObjectInputFilter serialFilter; // 反序列化过滤器
static {
SharedSecrets.setJavaObjectInputStreamAccess(ObjectInputStream::checkArray);
}
/*▼ 构造器 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Creates an ObjectInputStream that reads from the specified InputStream.
* A serialization stream header is read from the stream and verified.
* This constructor will block until the corresponding ObjectOutputStream
* has written and flushed the header.
*
* <p>The serialization filter is initialized to the value of
* {@linkplain ObjectInputFilter.Config#getSerialFilter() the process-wide filter}.
*
* <p>If a security manager is installed, this constructor will check for
* the "enableSubclassImplementation" SerializablePermission when invoked
* directly or indirectly by the constructor of a subclass which overrides
* the ObjectInputStream.readFields or ObjectInputStream.readUnshared
* methods.
*
* @param in input stream to read from
*
* @throws StreamCorruptedException if the stream header is incorrect
* @throws IOException if an I/O error occurs while reading stream header
* @throws SecurityException if untrusted subclass illegally overrides
* security-sensitive methods
* @throws NullPointerException if <code>in</code> is <code>null</code>
* @see ObjectInputStream#ObjectInputStream()
* @see ObjectInputStream#readFields()
* @see ObjectOutputStream#ObjectOutputStream(OutputStream)
*/
public ObjectInputStream(InputStream in) throws IOException {
verifySubclass();
bin = new BlockDataInputStream(in);
handles = new HandleTable(10);
vlist = new ValidationList();
enableOverride = false;
serialFilter = ObjectInputFilter.Config.getSerialFilter();
// 读取序列化头(包含一个魔数和一个版本号)
readStreamHeader();
// 设置待写数据处于块模式下
bin.setBlockDataMode(true);
}
/**
* Provide a way for subclasses that are completely reimplementing
* ObjectInputStream to not have to allocate private data just used by this
* implementation of ObjectInputStream.
*
* <p>The serialization filter is initialized to the value of
* {@linkplain ObjectInputFilter.Config#getSerialFilter() the process-wide filter}.
*
* <p>If there is a security manager installed, this method first calls the
* security manager's <code>checkPermission</code> method with the
* <code>SerializablePermission("enableSubclassImplementation")</code>
* permission to ensure it's ok to enable subclassing.
*
* @throws SecurityException if a security manager exists and its
* <code>checkPermission</code> method denies enabling
* subclassing.
* @throws IOException if an I/O error occurs while creating this stream
* @see SecurityManager#checkPermission
* @see java.io.SerializablePermission
*/
protected ObjectInputStream() throws IOException, SecurityException {
SecurityManager sm = System.getSecurityManager();
if(sm != null) {
sm.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
}
bin = null;
handles = null;
vlist = null;
serialFilter = ObjectInputFilter.Config.getSerialFilter();
enableOverride = true;
}
/*▲ 构造器 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 读 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Reads in a boolean.
*
* @return the boolean read.
*
* @throws EOFException If end of file is reached.
* @throws IOException If other I/O error has occurred.
*/
// 从块数据输入流读取boolean值
public boolean readBoolean() throws IOException {
return bin.readBoolean();
}
/**
* Reads a 16 bit char.
*
* @return the 16 bit char read.
*
* @throws EOFException If end of file is reached.
* @throws IOException If other I/O error has occurred.
*/
// 从块数据输入流读取char值
public char readChar() throws IOException {
return bin.readChar();
}
/**
* Reads an 8 bit byte.
*
* @return the 8 bit byte read.
*
* @throws EOFException If end of file is reached.
* @throws IOException If other I/O error has occurred.
*/
// 从块数据输入流读取byte值
public byte readByte() throws IOException {
return bin.readByte();
}
/**
* Reads an unsigned 8 bit byte.
*
* @return the 8 bit byte read.
*
* @throws EOFException If end of file is reached.
* @throws IOException If other I/O error has occurred.
*/
// 从块数据输入流读取byte值
public int readUnsignedByte() throws IOException {
return bin.readUnsignedByte();
}
/**
* Reads a 16 bit short.
*
* @return the 16 bit short read.
*
* @throws EOFException If end of file is reached.
* @throws IOException If other I/O error has occurred.
*/
// 从块数据输入流读取short值
public short readShort() throws IOException {
return bin.readShort();
}
/**
* Reads an unsigned 16 bit short.
*
* @return the 16 bit short read.
*
* @throws EOFException If end of file is reached.
* @throws IOException If other I/O error has occurred.
*/
// 从块数据输入流读取无符号short值
public int readUnsignedShort() throws IOException {
return bin.readUnsignedShort();
}
/**
* Reads a 32 bit int.
*
* @return the 32 bit integer read.
*
* @throws EOFException If end of file is reached.
* @throws IOException If other I/O error has occurred.
*/
// 从块数据输入流读取int值
public int readInt() throws IOException {
return bin.readInt();
}
/**
* Reads a 64 bit long.
*
* @return the read 64 bit long.
*
* @throws EOFException If end of file is reached.
* @throws IOException If other I/O error has occurred.
*/
// 从块数据输入流读取long值
public long readLong() throws IOException {
return bin.readLong();
}
/**
* Reads a 32 bit float.
*
* @return the 32 bit float read.
*
* @throws EOFException If end of file is reached.
* @throws IOException If other I/O error has occurred.
*/
// 从块数据输入流读取float值
public float readFloat() throws IOException {
return bin.readFloat();
}
/**
* Reads a 64 bit double.
*
* @return the 64 bit double read.
*
* @throws EOFException If end of file is reached.
* @throws IOException If other I/O error has occurred.
*/
// 从块数据输入流读取double值
public double readDouble() throws IOException {
return bin.readDouble();
}
/**
* Reads a byte of data. This method will block if no input is available.
*
* @return the byte read, or -1 if the end of the stream is reached.
*
* @throws IOException If an I/O error has occurred.
*/
// 从块数据输入流读取一个字节,返回-1表示读取结束
public int read() throws IOException {
return bin.read();
}
/**
* Reads into an array of bytes. This method will block until some input
* is available. Consider using java.io.DataInputStream.readFully to read
* exactly 'length' bytes.
*
* @param buf the buffer into which the data is read
* @param off the start offset in the destination array {@code buf}
* @param len the maximum number of bytes read
*
* @return the actual number of bytes read, -1 is returned when the end of
* the stream is reached.
*
* @throws NullPointerException if {@code buf} is {@code null}.
* @throws IndexOutOfBoundsException if {@code off} is negative,
* {@code len} is negative, or {@code len} is greater than
* {@code buf.length - off}.
* @throws IOException If an I/O error has occurred.
* @see java.io.DataInputStream#readFully(byte[], int, int)
*/
// 从块数据输入流读取len个字节,并将读到的内容插入到字节数组b的off索引处
public int read(byte[] buf, int off, int len) throws IOException {
if(buf == null) {
throw new NullPointerException();
}
int endoff = off + len;
if(off<0 || len<0 || endoff>buf.length || endoff<0) {
throw new IndexOutOfBoundsException();
}
return bin.read(buf, off, len, false);
}
/**
* Reads bytes, blocking until all bytes are read.
*
* @param buf the buffer into which the data is read
*
* @throws NullPointerException If {@code buf} is {@code null}.
* @throws EOFException If end of file is reached.
* @throws IOException If other I/O error has occurred.
*/
// 从块数据输入流读取足够字节填满buf
public void readFully(byte[] buf) throws IOException {
bin.readFully(buf, 0, buf.length, false);
}
/**
* Reads bytes, blocking until all bytes are read.
*
* @param buf the buffer into which the data is read
* @param off the start offset into the data array {@code buf}
* @param len the maximum number of bytes to read
*
* @throws NullPointerException If {@code buf} is {@code null}.
* @throws IndexOutOfBoundsException If {@code off} is negative,
* {@code len} is negative, or {@code len} is greater than
* {@code buf.length - off}.
* @throws EOFException If end of file is reached.
* @throws IOException If other I/O error has occurred.
*/
// 从块数据输入流读取len个字节写入buf的off处
public void readFully(byte[] buf, int off, int len) throws IOException {
int endoff = off + len;
if(off<0 || len<0 || endoff>buf.length || endoff<0) {
throw new IndexOutOfBoundsException();
}
bin.readFully(buf, off, len, false);
}
/**
* Reads a String in <a href="DataInput.html#modified-utf-8">modified UTF-8</a> format.
*
* @return the String.
*
* @throws IOException if there are I/O errors while reading from the
* underlying <code>InputStream</code>
* @throws UTFDataFormatException if read bytes do not represent a valid
* modified UTF-8 encoding of a string
*/
// 读取一个UTF8编码格式的小字符串
public String readUTF() throws IOException {
return bin.readUTF();
}
/**
* Reads in a line that has been terminated by a \n, \r, \r\n or EOF.
*
* @return a String copy of the line.
*
* @throws IOException if there are I/O errors while reading from the
* underlying <code>InputStream</code>
* @deprecated This method does not properly convert bytes to characters.
* see DataInputStream for the details and alternatives.
*/
// 读取一行数据:已过时
@Deprecated
public String readLine() throws IOException {
return bin.readLine();
}
/*▲ 读 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 反序列化 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Read an object from the ObjectInputStream. The class of the object, the
* signature of the class, and the values of the non-transient and
* non-static fields of the class and all of its supertypes are read.
* Default deserializing for a class can be overridden using the writeObject
* and readObject methods. Objects referenced by this object are read
* transitively so that a complete equivalent graph of objects is
* reconstructed by readObject.
*
* <p>The root object is completely restored when all of its fields and the
* objects it references are completely restored. At this point the object
* validation callbacks are executed in order based on their registered
* priorities. The callbacks are registered by objects (in the readObject
* special methods) as they are individually restored.
*
* <p>The serialization filter, when not {@code null}, is invoked for
* each object (regular or class) read to reconstruct the root object.
* See {@link #setObjectInputFilter(ObjectInputFilter) setObjectInputFilter} for details.
*
* <p>Exceptions are thrown for problems with the InputStream and for
* classes that should not be deserialized. All exceptions are fatal to
* the InputStream and leave it in an indeterminate state; it is up to the
* caller to ignore or recover the stream state.
*
* @throws ClassNotFoundException Class of a serialized object cannot be
* found.
* @throws InvalidClassException Something is wrong with a class used by
* serialization.
* @throws StreamCorruptedException Control information in the
* stream is inconsistent.
* @throws OptionalDataException Primitive data was found in the
* stream instead of objects.
* @throws IOException Any of the usual Input/Output related exceptions.
*/
// 从输入流读取共享对象
public final Object readObject() throws IOException, ClassNotFoundException {
if(enableOverride) {
// 使用子类实现的反序列化逻辑
return readObjectOverride();
}
// if nested read, passHandle contains handle of enclosing object
int outerHandle = passHandle;
try {
// 使用默认的反序列化逻辑,读取共享对象obj
Object obj = readObject0(false);
handles.markDependency(outerHandle, passHandle);
ClassNotFoundException ex = handles.lookupException(passHandle);
if(ex != null) {
throw ex;
}
// 反序列化完成后,对反序列化的对象执行验证
if(depth == 0) {
// 从前往后,按优先级从高到低执行回调逻辑
vlist.doCallbacks();
freeze();
}
return obj;
} finally {
passHandle = outerHandle;
if(closed && depth == 0) {
clear();
}
}
}
/**
* Reads an "unshared" object from the ObjectInputStream. This method is
* identical to readObject, except that it prevents subsequent calls to
* readObject and readUnshared from returning additional references to the
* deserialized instance obtained via this call. Specifically:
* <ul>
* <li>If readUnshared is called to deserialize a back-reference (the
* stream representation of an object which has been written
* previously to the stream), an ObjectStreamException will be
* thrown.
*
* <li>If readUnshared returns successfully, then any subsequent attempts
* to deserialize back-references to the stream handle deserialized
* by readUnshared will cause an ObjectStreamException to be thrown.
* </ul>
* Deserializing an object via readUnshared invalidates the stream handle
* associated with the returned object. Note that this in itself does not
* always guarantee that the reference returned by readUnshared is unique;
* the deserialized object may define a readResolve method which returns an
* object visible to other parties, or readUnshared may return a Class
* object or enum constant obtainable elsewhere in the stream or through
* external means. If the deserialized object defines a readResolve method
* and the invocation of that method returns an array, then readUnshared
* returns a shallow clone of that array; this guarantees that the returned
* array object is unique and cannot be obtained a second time from an
* invocation of readObject or readUnshared on the ObjectInputStream,
* even if the underlying data stream has been manipulated.
*
* <p>The serialization filter, when not {@code null}, is invoked for
* each object (regular or class) read to reconstruct the root object.
* See {@link #setObjectInputFilter(ObjectInputFilter) setObjectInputFilter} for details.
*
* <p>ObjectInputStream subclasses which override this method can only be
* constructed in security contexts possessing the
* "enableSubclassImplementation" SerializablePermission; any attempt to
* instantiate such a subclass without this permission will cause a
* SecurityException to be thrown.
*
* @return reference to deserialized object
*
* @throws ClassNotFoundException if class of an object to deserialize
* cannot be found
* @throws StreamCorruptedException if control information in the stream
* is inconsistent
* @throws ObjectStreamException if object to deserialize has already
* appeared in stream
* @throws OptionalDataException if primitive data is next in stream
* @throws IOException if an I/O error occurs during deserialization
* @since 1.4
*/
// 从输入流读取非共享对象
public Object readUnshared() throws IOException, ClassNotFoundException {
// if nested read, passHandle contains handle of enclosing object
int outerHandle = passHandle;
try {
Object obj = readObject0(true);
handles.markDependency(outerHandle, passHandle);
ClassNotFoundException ex = handles.lookupException(passHandle);
if(ex != null) {
throw ex;
}
// 反序列化完成后,对反序列化的对象执行验证
if(depth == 0) {
// 从前往后,按优先级从高到低执行回调逻辑
vlist.doCallbacks();
freeze();
}
return obj;
} finally {
passHandle = outerHandle;
if(closed && depth == 0) {
clear();
}
}
}
/**
* Read the non-static and non-transient fields of the current class from
* this stream. This may only be called from the readObject method of the
* class being deserialized. It will throw the NotActiveException if it is
* called otherwise.
*
* @throws ClassNotFoundException if the class of a serialized object
* could not be found.
* @throws IOException if an I/O error occurs.
* @throws NotActiveException if the stream is not currently reading
* objects.
*/
/*
* 默认反序列化
*
* 读取目标类的非static和非transient字段
* 只能从readObject()中调用此方法,否则会抛异常
*/
public void defaultReadObject() throws IOException, ClassNotFoundException {
SerialCallbackContext ctx = curContext;
if(ctx == null) {
throw new NotActiveException("not in call to readObject");
}
Object curObj = ctx.getObj();
ObjectStreamClass curDesc = ctx.getDesc();
bin.setBlockDataMode(false);
FieldValues vals = defaultReadFields(curObj, curDesc);
if(curObj != null) {
defaultCheckFieldValues(curObj, curDesc, vals);
defaultSetFieldValues(curObj, curDesc, vals);
}
bin.setBlockDataMode(true);
if(!curDesc.hasWriteObjectData()) {
/*
* Fix for 4360508: since stream does not contain terminating TC_ENDBLOCKDATA tag,
* set flag so that reading code elsewhere knows to simulate end-of-custom-data behavior.
*/
defaultDataEnd = true;
}
ClassNotFoundException ex = handles.lookupException(passHandle);
if(ex != null) {
throw ex;
}
}
/**
* This method is called by trusted subclasses of ObjectOutputStream that
* constructed ObjectOutputStream using the protected no-arg constructor.
* The subclass is expected to provide an override method with the modifier
* "final".
*
* @return the Object read from the stream.
*
* @throws ClassNotFoundException Class definition of a serialized object
* cannot be found.
* @throws OptionalDataException Primitive data was found in the stream
* instead of objects.
* @throws IOException if I/O errors occurred while reading from the
* underlying stream
* @see #ObjectInputStream()
* @see #readObject()
* @since 1.2
*/
// [子类覆盖]如果开启了enableOverride,则会调用该方法来替代默认的反序列化逻辑
protected Object readObjectOverride() throws IOException, ClassNotFoundException {
return null;
}
/**
* Load the local class equivalent of the specified stream class
* description. Subclasses may implement this method to allow classes to
* be fetched from an alternate source.
*
* <p>The corresponding method in <code>ObjectOutputStream</code> is
* <code>annotateClass</code>. This method will be invoked only once for
* each unique class in the stream. This method can be implemented by
* subclasses to use an alternate loading mechanism but must return a
* <code>Class</code> object. Once returned, if the class is not an array
* class, its serialVersionUID is compared to the serialVersionUID of the
* serialized class, and if there is a mismatch, the deserialization fails
* and an {@link InvalidClassException} is thrown.
*
* <p>The default implementation of this method in
* <code>ObjectInputStream</code> returns the result of calling
* <pre>
* Class.forName(desc.getName(), false, loader)
* </pre>
* where <code>loader</code> is the first class loader on the current
* thread's stack (starting from the currently executing method) that is
* neither the {@linkplain ClassLoader#getPlatformClassLoader() platform
* class loader} nor its ancestor; otherwise, <code>loader</code> is the
* <em>platform class loader</em>. If this call results in a
* <code>ClassNotFoundException</code> and the name of the passed
* <code>ObjectStreamClass</code> instance is the Java language keyword
* for a primitive type or void, then the <code>Class</code> object
* representing that primitive type or void will be returned
* (e.g., an <code>ObjectStreamClass</code> with the name
* <code>"int"</code> will be resolved to <code>Integer.TYPE</code>).
* Otherwise, the <code>ClassNotFoundException</code> will be thrown to
* the caller of this method.
*
* @param desc an instance of class <code>ObjectStreamClass</code>
*
* @return a <code>Class</code> object corresponding to <code>desc</code>
*
* @throws IOException any of the usual Input/Output exceptions.
* @throws ClassNotFoundException if class of a serialized object cannot
* be found.
*/
// 解析非代理类对象的序列化描述符
protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
String name = desc.getName();
try {
return Class.forName(name, false, latestUserDefinedLoader());
} catch(ClassNotFoundException ex) {
Class<?> cl = primClasses.get(name);
if(cl != null) {
return cl;
} else {
throw ex;
}
}
}
/**
* Returns a proxy class that implements the interfaces named in a proxy
* class descriptor; subclasses may implement this method to read custom
* data from the stream along with the descriptors for dynamic proxy
* classes, allowing them to use an alternate loading mechanism for the
* interfaces and the proxy class.
*
* <p>This method is called exactly once for each unique proxy class
* descriptor in the stream.
*
* <p>The corresponding method in <code>ObjectOutputStream</code> is
* <code>annotateProxyClass</code>. For a given subclass of
* <code>ObjectInputStream</code> that overrides this method, the
* <code>annotateProxyClass</code> method in the corresponding subclass of
* <code>ObjectOutputStream</code> must write any data or objects read by
* this method.
*
* <p>The default implementation of this method in
* <code>ObjectInputStream</code> returns the result of calling
* <code>Proxy.getProxyClass</code> with the list of <code>Class</code>
* objects for the interfaces that are named in the <code>interfaces</code>
* parameter. The <code>Class</code> object for each interface name
* <code>i</code> is the value returned by calling
* <pre>
* Class.forName(i, false, loader)
* </pre>
* where <code>loader</code> is the first class loader on the current
* thread's stack (starting from the currently executing method) that is
* neither the {@linkplain ClassLoader#getPlatformClassLoader() platform
* class loader} nor its ancestor; otherwise, <code>loader</code> is the
* <em>platform class loader</em>.
* Unless any of the resolved interfaces are non-public, this same value
* of <code>loader</code> is also the class loader passed to
* <code>Proxy.getProxyClass</code>; if non-public interfaces are present,
* their class loader is passed instead (if more than one non-public
* interface class loader is encountered, an
* <code>IllegalAccessError</code> is thrown).
* If <code>Proxy.getProxyClass</code> throws an
* <code>IllegalArgumentException</code>, <code>resolveProxyClass</code>
* will throw a <code>ClassNotFoundException</code> containing the
* <code>IllegalArgumentException</code>.
*
* @param interfaces the list of interface names that were
* deserialized in the proxy class descriptor
*
* @return a proxy class for the specified interfaces
*
* @throws IOException any exception thrown by the underlying
* <code>InputStream</code>
* @throws ClassNotFoundException if the proxy class or any of the
* named interfaces could not be found
* @see ObjectOutputStream#annotateProxyClass(Class)
* @since 1.3
*/
// 解析代理类的类对象,interfaces是代理接口
protected Class<?> resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException {
ClassLoader latestLoader = latestUserDefinedLoader();
ClassLoader nonPublicLoader = null;
boolean hasNonPublicInterface = false;
// define proxy in class loader of non-public interface(s), if any
Class<?>[] classObjs = new Class<?>[interfaces.length];
for(int i = 0; i<interfaces.length; i++) {
Class<?> cl = Class.forName(interfaces[i], false, latestLoader);
if((cl.getModifiers() & Modifier.PUBLIC) == 0) {
if(hasNonPublicInterface) {
if(nonPublicLoader != cl.getClassLoader()) {
throw new IllegalAccessError("conflicting non-public interface class loaders");
}