summaryrefslogtreecommitdiff
path: root/external/ikvm/openjdk/java/io/InteropObjectOutputStream.java
blob: f32c98b19c7e45d0075cecf3cd14260e4a4d9fec (plain)
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
/*
 * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
 * Copyright 2009 Jeroen Frijters
 * 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 cli.System.Runtime.Serialization.IObjectReference;
import cli.System.Runtime.Serialization.SerializationException;
import cli.System.Runtime.Serialization.SerializationInfo;
import cli.System.Runtime.Serialization.StreamingContext;
import cli.System.SerializableAttribute;
import java.util.ArrayList;

@ikvm.lang.Internal
public final class InteropObjectOutputStream extends ObjectOutputStream
{
    private final ObjectDataOutputStream dos;
    private Object curObj;
    private ObjectStreamClass curDesc;
    private PutFieldImpl curPut;
    
    @SerializableAttribute.Annotation
    private static final class ReplaceProxy implements IObjectReference
    {
        private Object obj;

        @cli.System.Security.SecurityCriticalAttribute.Annotation
        public Object GetRealObject(StreamingContext context)
        {
            return obj;
        }
    }
    
    static final class DynamicProxy implements Serializable
    {
        Object obj;

        private Object readResolve()
        {
            return obj;
        }
    }
    
    public static void writeObject(Object obj, SerializationInfo info)
    {
        try
        {
            boolean replaced = false;
            Class cl = obj.getClass();
            ObjectStreamClass desc;
            for (;;)
            {
                Class repCl;
                desc = ObjectStreamClass.lookup(cl, true);
                if (!desc.hasWriteReplaceMethod() ||
                    (obj = desc.invokeWriteReplace(obj)) == null ||
                    (repCl = obj.getClass()) == cl)
                {
                    break;
                }
                cl = repCl;
                replaced = true;
            }
            if (replaced)
            {
                info.AddValue("obj", obj);
                info.SetType(ikvm.runtime.Util.getInstanceTypeFromClass(ReplaceProxy.class));
            }
            else
            {
                new InteropObjectOutputStream(info, obj, cl, desc);
            }
        }
        catch (IOException x)
        {
            ikvm.runtime.Util.throwException(new SerializationException(x.getMessage(), x));
        }
    }
    
    private InteropObjectOutputStream(SerializationInfo info, Object obj, Class cl, ObjectStreamClass desc) throws IOException
    {
        dos = new ObjectDataOutputStream(info);
        if (obj instanceof ObjectStreamClass)
        {
            ObjectStreamClass osc = (ObjectStreamClass)obj;
            if (osc.isProxy())
            {
                writeProxyDesc(osc);
            }
            else
            {
                writeNonProxyDesc(osc);
            }
        }
        else if (obj instanceof Serializable)
        {
            if (desc.isDynamicClass())
            {
                info.SetType(ikvm.runtime.Util.getInstanceTypeFromClass(DynamicProxy.class));
            }
            writeOrdinaryObject(obj, desc);
        }
        else
        {
            throw new NotSerializableException(cl.getName());
        }
        dos.close();
    }
    
    private void writeProxyDesc(ObjectStreamClass desc) throws IOException
    {
        writeByte(TC_PROXYCLASSDESC);
        Class cl = desc.forClass();
        Class[] ifaces = cl.getInterfaces();
        writeInt(ifaces.length);
        for (int i = 0; i < ifaces.length; i++)
        {
            writeObject(ifaces[i]);
        }
        writeObject(desc.getSuperDesc());
    }
    
    private void writeNonProxyDesc(ObjectStreamClass desc) throws IOException
    {
        writeByte(TC_CLASSDESC);
        writeObject(desc.forClass());
        desc.writeNonProxy(this);
        writeObject(desc.getSuperDesc());
    }
    
    private void writeOrdinaryObject(Object obj, ObjectStreamClass desc) throws IOException
    {
        desc.checkSerialize();
        writeObject(desc);
        if (desc.isExternalizable() && !desc.isProxy())
        {
            writeExternalData((Externalizable)obj);
        }
        else
        {
            writeSerialData(obj, desc);
        }
    }
    
    private void writeExternalData(Externalizable obj) throws IOException
    {
        Object oldObj = curObj;
        ObjectStreamClass oldDesc = curDesc;
        PutFieldImpl oldPut = curPut;
        curObj = obj;
        curDesc = null;
        curPut = null;

        obj.writeExternal(this);
        dos.writeMarker();

        curObj = oldObj;
        curDesc = oldDesc;
        curPut = oldPut;
    }
    
    private void writeSerialData(Object obj, ObjectStreamClass desc) throws IOException
    {
        ObjectStreamClass.ClassDataSlot[] slots = desc.getClassDataLayout();
        for (int i = 0; i < slots.length; i++)
        {
            ObjectStreamClass slotDesc = slots[i].desc;
            if (slotDesc.hasWriteObjectMethod())
            {
                Object oldObj = curObj;
                ObjectStreamClass oldDesc = curDesc;
                PutFieldImpl oldPut = curPut;
                curObj = obj;
                curDesc = slotDesc;
                curPut = null;
                slotDesc.invokeWriteObject(obj, this);
                dos.writeMarker();
                curObj = oldObj;
                curDesc = oldDesc;
                curPut = oldPut;
            }
            else
            {
                defaultWriteFields(obj, slotDesc);
            }
        }
    }

    private void defaultWriteFields(Object obj, ObjectStreamClass desc) throws IOException
    {
        desc.checkDefaultSerialize();

        byte[] primVals = new byte[desc.getPrimDataSize()];
        desc.getPrimFieldValues(obj, primVals);
        write(primVals);

        Object[] objVals = new Object[desc.getNumObjFields()];
        desc.getObjFieldValues(obj, objVals);
        for (int i = 0; i < objVals.length; i++)
        {
            writeObject(objVals[i]);
        }
    }

    @Override    
    public void defaultWriteObject() throws IOException
    {
        defaultWriteFields(curObj, curDesc);
    }

    @Override    
    public void close()
    {
        throw new UnsupportedOperationException();
    }

    @Override    
    public void flush()
    {
    }

    @Override    
    public ObjectOutputStream.PutField putFields() throws IOException
    {
        if (curPut == null)
        {
            if (curObj == null || curDesc == null)
            {
                throw new NotActiveException("not in call to writeObject");
            }
            curPut = new PutFieldImpl(curDesc);
        }
        return curPut;
    }

    @Override    
    public void reset() throws IOException
    {
        throw new IOException("stream active");
    }

    @Override    
    protected void writeObjectOverride(Object obj)
    {
        // TODO consider tagging ghost arrays
        dos.writeObject(obj);
    }

    @Override    
    public void writeFields() throws IOException
    {
        if (curPut == null)
        {
            throw new NotActiveException("no current PutField object");
        }
        curPut.writeFields();
    }

    @Override    
    public void writeUnshared(Object obj)
    {
        throw new UnsupportedOperationException();
    }

    @Override    
    public void useProtocolVersion(int version)
    {
        throw new IllegalStateException("stream non-empty");
    }

    @Override    
    public void write(byte[] buf) throws IOException
    {
        write(buf, 0, buf.length);
    }

    @Override    
    public void write(int val) throws IOException
    {
        dos.write(val);
    }

    @Override    
    public void write(byte[] buf, int off, int len) throws IOException
    {
        dos.write(buf, off, len);
    }

    @Override    
    public void writeBoolean(boolean val) throws IOException
    {
        dos.writeBoolean(val);
    }

    @Override    
    public void writeByte(int val) throws IOException
    {
        dos.writeByte(val);
    }

    @Override    
    public void writeBytes(String str) throws IOException
    {
        dos.writeBytes(str);
    }

    @Override    
    public void writeChar(int val) throws IOException
    {
        dos.writeChar(val);
    }

    @Override    
    public void writeChars(String str) throws IOException
    {
        dos.writeChars(str);
    }

    @Override    
    public void writeDouble(double val) throws IOException
    {
        dos.writeDouble(val);
    }

    @Override    
    public void writeFloat(float val) throws IOException
    {
        dos.writeFloat(val);
    }

    @Override    
    public void writeInt(int val) throws IOException
    {
        dos.writeInt(val);
    }

    @Override    
    public void writeLong(long val) throws IOException
    {
        dos.writeLong(val);
    }

    @Override    
    public void writeShort(int val) throws IOException
    {
        dos.writeShort(val);
    }

    @Override    
    public void writeUTF(String str) throws IOException
    {
        dos.writeUTF(str);
    }
    
    // private API used by ObjectStreamClass
    @Override    
    void writeTypeString(String str) throws IOException
    {
        writeObject(str);
    }

    private final class PutFieldImpl extends PutField {

        /** class descriptor describing serializable fields */
        private final ObjectStreamClass desc;
        /** primitive field values */
        private final byte[] primVals;
        /** object field values */
        private final Object[] objVals;

        /**
         * Creates PutFieldImpl object for writing fields defined in given
         * class descriptor.
         */
        PutFieldImpl(ObjectStreamClass desc) {
            this.desc = desc;
            primVals = new byte[desc.getPrimDataSize()];
            objVals = new Object[desc.getNumObjFields()];
        }

        public void put(String name, boolean val) {
            Bits.putBoolean(primVals, getFieldOffset(name, Boolean.TYPE), val);
        }

        public void put(String name, byte val) {
            primVals[getFieldOffset(name, Byte.TYPE)] = val;
        }

        public void put(String name, char val) {
            Bits.putChar(primVals, getFieldOffset(name, Character.TYPE), val);
        }

        public void put(String name, short val) {
            Bits.putShort(primVals, getFieldOffset(name, Short.TYPE), val);
        }

        public void put(String name, int val) {
            Bits.putInt(primVals, getFieldOffset(name, Integer.TYPE), val);
        }

        public void put(String name, float val) {
            Bits.putFloat(primVals, getFieldOffset(name, Float.TYPE), val);
        }

        public void put(String name, long val) {
            Bits.putLong(primVals, getFieldOffset(name, Long.TYPE), val);
        }

        public void put(String name, double val) {
            Bits.putDouble(primVals, getFieldOffset(name, Double.TYPE), val);
        }

        public void put(String name, Object val) {
            objVals[getFieldOffset(name, Object.class)] = val;
        }

        // deprecated in ObjectOutputStream.PutField
        public void write(ObjectOutput out) throws IOException {
            /*
             * Applications should *not* use this method to write PutField
             * data, as it will lead to stream corruption if the PutField
             * object writes any primitive data (since block data mode is not
             * unset/set properly, as is done in OOS.writeFields()).  This
             * broken implementation is being retained solely for behavioral
             * compatibility, in order to support applications which use
             * OOS.PutField.write() for writing only non-primitive data.
             *
             * Serialization of unshared objects is not implemented here since
             * it is not necessary for backwards compatibility; also, unshared
             * semantics may not be supported by the given ObjectOutput
             * instance.  Applications which write unshared objects using the
             * PutField API must use OOS.writeFields().
             */
            if (InteropObjectOutputStream.this != out) {
                throw new IllegalArgumentException("wrong stream");
            }
            out.write(primVals, 0, primVals.length);

            ObjectStreamField[] fields = desc.getFields(false);
            int numPrimFields = fields.length - objVals.length;
            // REMIND: warn if numPrimFields > 0?
            for (int i = 0; i < objVals.length; i++) {
                if (fields[numPrimFields + i].isUnshared()) {
                    throw new IOException("cannot write unshared object");
                }
                out.writeObject(objVals[i]);
            }
        }

        /**
         * Writes buffered primitive data and object fields to stream.
         */
        void writeFields() throws IOException {
            InteropObjectOutputStream.this.write(primVals, 0, primVals.length);

            ObjectStreamField[] fields = desc.getFields(false);
            int numPrimFields = fields.length - objVals.length;
            for (int i = 0; i < objVals.length; i++) {
                writeObject(objVals[i]);
            }
        }

        /**
         * Returns offset of field with given name and type.  A specified type
         * of null matches all types, Object.class matches all non-primitive
         * types, and any other non-null type matches assignable types only.
         * Throws IllegalArgumentException if no matching field found.
         */
        private int getFieldOffset(String name, Class type) {
            ObjectStreamField field = desc.getField(name, type);
            if (field == null) {
                throw new IllegalArgumentException("no such field " + name +
                                                   " with type " + type);
            }
            return field.getOffset();
        }
    }

    private static final class ObjectDataOutputStream extends DataOutputStream
    {
        /*
         * States:
         *  blockStart   objCount
         *          -1          0       Previous byte was a marker (or we're at the start of the stream), next byte will be MARKER, OBJECTS or BYTES
         *         >=0          0       We're currently writing a byte stream (that starts at blockStart + 1)
         *          -1         >0       We're currently writing objects (just a count of objects really)
         *
         */
        private static final byte MARKER = 0;
        private static final byte OBJECTS = 10;
        private static final byte BYTES = 20;
        private final SerializationInfo info;
        private byte[] buf = new byte[16];
        private int pos;
        private int blockStart = -1;
        private int objCount;
        private int objId;

        ObjectDataOutputStream(SerializationInfo info)
        {
            super(null);
            out = this;
            this.info = info;
        }
        
        private void grow(int minGrow)
        {
            int newSize = buf.length + Math.max(buf.length, minGrow);
            byte[] newBuf = new byte[newSize];
            System.arraycopy(buf, 0, newBuf, 0, pos);
            buf = newBuf;
        }
        
        private void switchToData()
        {
            if (objCount == 0)
            {
                if (pos == buf.length)
                {
                    grow(1);
                }
                buf[pos++] = BYTES;
            }
            else
            {
                int len = packedLength(objCount);
                if (pos + len >= buf.length)
                {
                    grow(len);
                }
                writePacked(pos, objCount);
                objCount = 0;
                pos += len;
            }
            blockStart = pos;
            // reserve space for the number of bytes
            // (we assume that one byte will suffice, but if it won't the endData code will copy the data to make room)
            if (pos == buf.length)
            {
                grow(1);
            }
            pos++;
        }
        
        private void endData()
        {
            if (blockStart == -1)
            {
                if (pos == buf.length)
                {
                    grow(1);
                }
                buf[pos++] = OBJECTS;
            }
            else
            {
                int len = (pos - blockStart) - 1;
                int lenlen = packedLength(len);
                if (lenlen > 1)
                {
                    lenlen--;
                    if (buf.length - pos <= lenlen)
                    {
                        grow(lenlen);
                    }
                    System.arraycopy(buf, blockStart + 1, buf, blockStart + 1 + lenlen, pos - (blockStart + 1));
                    pos += lenlen;
                }
                writePacked(blockStart, len);
                blockStart = -1;
            }
        }
        
        private int packedLength(int val)
        {
            if (val < 0)
            {
                // we only use packed integers for lengths or counts, so they can never be negative
                throw new Error();
            }
            else if (val < 128)
            {
                return 1;
            }
            else if (val < 16129)
            {
                return 2;
            }
            else
            {
                return 5;
            }
        }
        
        private void writePacked(int pos, int v)
        {
            if (v < 128)
            {
                buf[pos] = (byte)v;
            }
            else if (v < 16129)
            {
                buf[pos + 0] = (byte)(128 | (v >> 7));
                buf[pos + 1] = (byte)(v & 127);
            }
            else
            {
                buf[pos + 0] = (byte)128;
                buf[pos + 1] = (byte)(v >>> 24);
                buf[pos + 2] = (byte)(v >>> 16);
                buf[pos + 3] = (byte)(v >>>  8);
                buf[pos + 4] = (byte)(v >>>  0);
            }
        }
        
        @Override
        public void write(int b)
        {
            if (blockStart == -1)
            {
                switchToData();
            }
            if (pos == buf.length)
            {
                grow(1);
            }
            buf[pos++] = (byte)b;
        }
        
        @Override
        public void write(byte[] b, int off, int len)
        {
            if (len == 0)
            {
                return;
            }
            if (blockStart == -1)
            {
                switchToData();
            }
            if (pos + len >= buf.length)
            {
                grow(len);
            }
            System.arraycopy(b, off, buf, pos, len);
            pos += len;
        }
        
        public void writeObject(Object obj)
        {
            if (objCount == 0)
            {
                endData();
            }
            objCount++;
            info.AddValue("$" + (objId++), obj);
        }
        
        @Override
        public void close()
        {
            if (objCount == 0)
            {
                if (blockStart == -1)
                {
                    // we've just written a marker, so we don't need to do anything else
                }
                else
                {
                    endData();
                }
            }
            else
            {
                switchToData();
            }
            trim();
            info.AddValue("$data", buf);
        }
        
        private void trim()
        {
            if (buf.length != pos)
            {
                byte[] newBuf = new byte[pos];
                System.arraycopy(buf, 0, newBuf, 0, pos);
                buf = newBuf;
            }
        }
        
        @Override
        public void flush()
        {
        }
        
        public void writeMarker()
        {
            if (objCount == 0)
            {
                if (blockStart != -1)
                {
                    endData();
                }
                if (pos == buf.length)
                {
                    grow(1);
                }
                buf[pos++] = MARKER;
            }
            else
            {
                switchToData();
            }
            blockStart = -1;
        }
    }
}