summaryrefslogtreecommitdiff
path: root/core/tests/coretests/src/android/os/BundleTest.java
blob: 0fa5ec33749f330a898549c52bbbdbe074ff7f75 (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
/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.os;

import static com.google.common.truth.Truth.assertThat;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;

import android.platform.test.annotations.Presubmit;
import android.util.Log;

import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;

import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.util.Objects;

/**
 * Unit tests for bundle that requires accessing hidden APS.  Tests that can be written only with
 * public APIs should go in the CTS counterpart.
 *
 * Run with: atest FrameworksCoreTests:android.os.BundleTest
 */
@SmallTest
@Presubmit
@RunWith(AndroidJUnit4.class)
public class BundleTest {
    private Log.TerribleFailureHandler mWtfHandler;

    @After
    public void tearDown() throws Exception {
        BaseBundle.setShouldDefuse(false);
        if (mWtfHandler != null) {
            Log.setWtfHandler(mWtfHandler);
        }
    }

    /**
     * Take a bundle, write it to a parcel and return the parcel.
     */
    private Parcel getParcelledBundle(Bundle bundle) {
        final Parcel p = Parcel.obtain();
        // Don't use p.writeParcelabe(), which would write the creator, which we don't need.
        bundle.writeToParcel(p, 0);
        p.setDataPosition(0);
        return p;
    }

    /**
     * Create a test bundle, parcel it and return the parcel.
     */
    private Parcel createBundleParcel(boolean withFd) throws Exception {
        final Bundle source = new Bundle();
        source.putString("string", "abc");
        source.putInt("int", 1);
        if (withFd) {
            ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe();
            pipe[1].close();
            source.putParcelable("fd", pipe[0]);
        }
        return getParcelledBundle(source);
    }

    /**
     * Verify a bundle generated by {@link #createBundleParcel(boolean)}.
     */
    private void checkBundle(Bundle b, boolean withFd) {
        // First, do the checks without actually unparceling the bundle.
        // (Note looking into the contents will unparcel a bundle, so we'll do it later.)
        assertTrue("mParcelledData shouldn't be null here.", b.isParcelled());

        // Make sure FLAG_HAS_FDS and FLAG_HAS_FDS_KNOWN are set/cleared properly.
        if (withFd) {
            // FLAG_HAS_FDS and FLAG_HAS_FDS_KNOWN should both be set.
            assertEquals(Bundle.FLAG_HAS_FDS | Bundle.FLAG_HAS_FDS_KNOWN,
                    b.mFlags & (Bundle.FLAG_HAS_FDS | Bundle.FLAG_HAS_FDS_KNOWN));
        } else {
            // FLAG_HAS_FDS_KNOWN should be set, bot not FLAG_HAS_FDS.
            assertEquals(Bundle.FLAG_HAS_FDS_KNOWN,
                    b.mFlags & (Bundle.FLAG_HAS_FDS | Bundle.FLAG_HAS_FDS_KNOWN));
        }

        // Then, check the contents.
        assertEquals("abc", b.getString("string"));
        assertEquals(1, b.getInt("int"));

        // Make sure FLAG_HAS_FDS and FLAG_HAS_FDS_KNOWN are set/cleared properly.
        if (withFd) {
            assertEquals(ParcelFileDescriptor.class, b.getParcelable("fd").getClass());
            assertEquals(3, b.keySet().size());
        } else {
            assertEquals(2, b.keySet().size());
        }
        assertFalse(b.isParcelled());
    }

    @Test
    public void testCreateFromParcel() throws Exception {
        boolean withFd;
        Parcel p;
        Bundle b;
        int length;

        withFd = false;

        // new Bundle with p
        p = createBundleParcel(withFd);
        checkBundle(new Bundle(p), withFd);
        p.recycle();

        // new Bundle with p and length
        p = createBundleParcel(withFd);
        length = p.readInt();
        checkBundle(new Bundle(p, length), withFd);
        p.recycle();

        // readFromParcel()
        p = createBundleParcel(withFd);
        b = new Bundle();
        b.readFromParcel(p);
        checkBundle(b, withFd);
        p.recycle();

        // Same test with FDs.
        withFd = true;

        // new Bundle with p
        p = createBundleParcel(withFd);
        checkBundle(new Bundle(p), withFd);
        p.recycle();

        // new Bundle with p and length
        p = createBundleParcel(withFd);
        length = p.readInt();
        checkBundle(new Bundle(p, length), withFd);
        p.recycle();

        // readFromParcel()
        p = createBundleParcel(withFd);
        b = new Bundle();
        b.readFromParcel(p);
        checkBundle(b, withFd);
        p.recycle();
    }

    @Test
    public void kindofEquals_bothUnparcelled_same() {
        Bundle bundle1 = new Bundle();
        bundle1.putString("StringKey", "S");
        bundle1.putInt("IntKey", 2);

        Bundle bundle2 = new Bundle();
        bundle2.putString("StringKey", "S");
        bundle2.putInt("IntKey", 2);

        assertTrue(BaseBundle.kindofEquals(bundle1, bundle2));
    }

    @Test
    public void kindofEquals_bothUnparcelled_different() {
        Bundle bundle1 = new Bundle();
        bundle1.putString("StringKey", "S");
        bundle1.putInt("IntKey", 2);

        Bundle bundle2 = new Bundle();
        bundle2.putString("StringKey", "T");
        bundle2.putLong("LongKey", 30L);

        assertFalse(BaseBundle.kindofEquals(bundle1, bundle2));
    }

    @Test
    public void kindofEquals_bothParcelled_same() {
        Bundle bundle1 = new Bundle();
        bundle1.putString("StringKey", "S");
        bundle1.putInt("IntKey", 2);
        bundle1.readFromParcel(getParcelledBundle(bundle1));

        Bundle bundle2 = new Bundle();
        bundle2.putString("StringKey", "S");
        bundle2.putInt("IntKey", 2);
        bundle2.readFromParcel(getParcelledBundle(bundle2));

        assertTrue(bundle1.isParcelled());
        assertTrue(bundle2.isParcelled());
        assertTrue(BaseBundle.kindofEquals(bundle1, bundle2));
    }

    @Test
    public void kindofEquals_bothParcelled_different() {
        Bundle bundle1 = new Bundle();
        bundle1.putString("StringKey", "S");
        bundle1.putInt("IntKey", 2);
        bundle1.readFromParcel(getParcelledBundle(bundle1));

        Bundle bundle2 = new Bundle();
        bundle2.putString("StringKey", "T");
        bundle2.putLong("LongKey", 5);
        bundle2.readFromParcel(getParcelledBundle(bundle2));

        assertTrue(bundle1.isParcelled());
        assertTrue(bundle2.isParcelled());
        assertFalse(BaseBundle.kindofEquals(bundle1, bundle2));
    }

    @Test
    public void kindofEquals_ParcelledUnparcelled_empty() {
        Bundle bundle1 = new Bundle();
        bundle1.readFromParcel(getParcelledBundle(bundle1));

        Bundle bundle2 = new Bundle();

        assertTrue(bundle1.isParcelled());
        assertFalse(bundle2.isParcelled());
        // Even though one is parcelled and the other is not, both are empty, so it should
        // return true
        assertTrue(BaseBundle.kindofEquals(bundle1, bundle2));
    }

    @Test
    public void kindofEquals_lazyValues() {
        Parcelable p1 = new CustomParcelable(13, "Tiramisu");
        Parcelable p2 = new CustomParcelable(13, "Tiramisu");

        // 2 maps with live objects
        Bundle a = new Bundle();
        a.putParcelable("key1", p1);
        Bundle b = new Bundle();
        b.putParcelable("key1", p2);
        assertTrue(Bundle.kindofEquals(a, b));

        // 2 identical parcels
        a.readFromParcel(getParcelledBundle(a));
        a.setClassLoader(getClass().getClassLoader());
        b.readFromParcel(getParcelledBundle(b));
        b.setClassLoader(getClass().getClassLoader());
        assertTrue(Bundle.kindofEquals(a, b));

        // 2 lazy values with identical parcels inside
        a.isEmpty();
        b.isEmpty();
        assertTrue(Bundle.kindofEquals(a, b));

        // 1 lazy value vs 1 live object
        a.getParcelable("key1");
        assertFalse(Bundle.kindofEquals(a, b));

        // 2 live objects
        b.getParcelable("key1");
        assertTrue(Bundle.kindofEquals(a, b));
    }

    @Test
    public void kindofEquals_lazyValuesWithIdenticalParcels_returnsTrue() {
        Parcelable p1 = new CustomParcelable(13, "Tiramisu");
        Parcelable p2 = new CustomParcelable(13, "Tiramisu");
        Bundle a = new Bundle();
        a.putParcelable("key1", p1);
        a.readFromParcel(getParcelledBundle(a));
        a.setClassLoader(getClass().getClassLoader());
        Bundle b = new Bundle();
        // Adding extra element so that the position of the elements of interest in their respective
        // source parcels are different so we can cover that case of Parcel.compareData(). We'll
        // remove the element later so the map is equal.
        b.putString("key0", "string");
        b.putParcelable("key1", p2);
        b.readFromParcel(getParcelledBundle(b));
        b.setClassLoader(getClass().getClassLoader());
        a.isEmpty();
        b.isEmpty();
        b.remove("key0");
        // 2 lazy values with identical parcels inside

        assertTrue(Bundle.kindofEquals(a, b));
    }

    @Test
    public void kindofEquals_lazyValuesAndDifferentClassLoaders_returnsFalse() {
        Parcelable p1 = new CustomParcelable(13, "Tiramisu");
        Parcelable p2 = new CustomParcelable(13, "Tiramisu");
        Bundle a = new Bundle();
        a.putParcelable("key", p1);
        a.readFromParcel(getParcelledBundle(a));
        a.setClassLoader(getClass().getClassLoader());
        Bundle b = new Bundle();
        b.putParcelable("key", p2);
        b.readFromParcel(getParcelledBundle(b));
        b.setClassLoader(Bundle.class.getClassLoader()); // BCP
        // 2 lazy values with identical parcels inside
        a.isEmpty();
        b.isEmpty();

        assertFalse(Bundle.kindofEquals(a, b));
    }

    @Test
    public void kindofEquals_lazyValuesOfDifferentTypes_returnsFalse() {
        Parcelable p = new CustomParcelable(13, "Tiramisu");
        Parcelable[] ps = {p};
        Bundle a = new Bundle();
        a.putParcelable("key", p);
        a.readFromParcel(getParcelledBundle(a));
        a.setClassLoader(getClass().getClassLoader());
        Bundle b = new Bundle();
        b.putParcelableArray("key", ps);
        b.readFromParcel(getParcelledBundle(b));
        b.setClassLoader(getClass().getClassLoader());
        a.isEmpty();
        b.isEmpty();

        assertFalse(Bundle.kindofEquals(a, b));
    }

    @Test
    public void kindofEquals_lazyValuesWithDifferentLengths_returnsFalse() {
        Parcelable p1 = new CustomParcelable(13, "Tiramisu");
        Parcelable p2 = new CustomParcelable(13, "Tiramisuuuuuuuu");
        Bundle a = new Bundle();
        a.putParcelable("key", p1);
        a.readFromParcel(getParcelledBundle(a));
        a.setClassLoader(getClass().getClassLoader());
        Bundle b = new Bundle();
        b.putParcelable("key", p2);
        b.readFromParcel(getParcelledBundle(b));
        b.setClassLoader(getClass().getClassLoader());
        a.isEmpty();
        b.isEmpty();

        assertFalse(Bundle.kindofEquals(a, b));
    }

    @Test
    public void readWriteLengthMismatch_logsWtf() throws Exception {
        mWtfHandler = Log.setWtfHandler((tag, e, system) -> {
            throw new RuntimeException(e);
        });
        Parcelable parcelable = new CustomParcelable(13, "Tiramisu").setHasLengthMismatch(true);
        Bundle bundle = new Bundle();
        bundle.putParcelable("p", parcelable);
        bundle.readFromParcel(getParcelledBundle(bundle));
        bundle.setClassLoader(getClass().getClassLoader());
        RuntimeException e = assertThrows(RuntimeException.class, () -> bundle.getParcelable("p"));
        assertThat(e.getCause()).isInstanceOf(Log.TerribleFailure.class);
    }

    @Test
    public void getParcelable_whenThrowingAndNotDefusing_throws() throws Exception {
        Bundle.setShouldDefuse(false);
        Bundle bundle = new Bundle();
        bundle.putParcelable("key", new CustomParcelable(13, "Tiramisu"));
        bundle.readFromParcel(getParcelledBundle(bundle));

        // Default class-loader is the bootpath class-loader, which doesn't contain
        // CustomParcelable, so trying to read it will throw BadParcelableException.
        assertThrows(BadParcelableException.class, () -> bundle.getParcelable("key"));
    }

    @Test
    public void getParcelable_whenThrowingAndDefusing_returnsNull() throws Exception {
        Bundle.setShouldDefuse(true);
        Bundle bundle = new Bundle();
        bundle.putParcelable("key", new CustomParcelable(13, "Tiramisu"));
        bundle.putString("string", "value");
        bundle.readFromParcel(getParcelledBundle(bundle));

        // Default class-loader is the bootpath class-loader, which doesn't contain
        // CustomParcelable, so trying to read it will throw BadParcelableException.
        assertThat(bundle.<Parcelable>getParcelable("key")).isNull();
        // Doesn't affect other items
        assertThat(bundle.getString("string")).isEqualTo("value");
    }

    @Test
    public void getParcelable_whenThrowingAndDefusing_leavesElement() throws Exception {
        Bundle.setShouldDefuse(true);
        Bundle bundle = new Bundle();
        Parcelable parcelable = new CustomParcelable(13, "Tiramisu");
        bundle.putParcelable("key", parcelable);
        bundle.putString("string", "value");
        bundle.readFromParcel(getParcelledBundle(bundle));
        assertThat(bundle.<Parcelable>getParcelable("key")).isNull();

        // Now, we simulate reserializing and assign the proper class loader to not throw anymore
        bundle.readFromParcel(getParcelledBundle(bundle));
        bundle.setClassLoader(getClass().getClassLoader());

        // We're able to retrieve it even though we failed before
        assertThat(bundle.<Parcelable>getParcelable("key")).isEqualTo(parcelable);
    }

    @Test
    public void readFromParcel_withLazyValues_copiesUnderlyingParcel() {
        Bundle bundle = new Bundle();
        Parcelable parcelable = new CustomParcelable(13, "Tiramisu");
        bundle.putParcelable("key", parcelable);
        bundle.putString("string", "value");
        Parcel parcelledBundle = getParcelledBundle(bundle);

        Bundle testBundle = new Bundle();
        testBundle.setClassLoader(getClass().getClassLoader());
        testBundle.readFromParcel(parcelledBundle);
        // Recycle the parcel as it should have been copied
        parcelledBundle.recycle();
        assertThat(testBundle.getString("string")).isEqualTo("value");
        assertThat(testBundle.<Parcelable>getParcelable("key")).isEqualTo(parcelable);
    }

    @Test
    public void readFromParcelWithRwHelper_whenThrowingAndNotDefusing_throws() {
        Bundle bundle = new Bundle();
        Parcelable parcelable = new CustomParcelable(13, "Tiramisu");
        bundle.putParcelable("key", parcelable);
        bundle.putString("string", "value");
        Parcel parcelledBundle = getParcelledBundle(bundle);
        parcelledBundle.setReadWriteHelper(new Parcel.ReadWriteHelper());

        Bundle testBundle = new Bundle();
        assertThrows(BadParcelableException.class,
                () -> testBundle.readFromParcel(parcelledBundle));
    }

    @Test
    public void readFromParcelWithRwHelper_whenThrowingAndDefusing_returnsNull() {
        Bundle bundle = new Bundle();
        Parcelable parcelable = new CustomParcelable(13, "Tiramisu");
        bundle.putParcelable("key", parcelable);
        bundle.putString("string", "value");
        Parcel parcelledBundle = getParcelledBundle(bundle);
        parcelledBundle.setReadWriteHelper(new Parcel.ReadWriteHelper());

        Bundle.setShouldDefuse(true);
        Bundle testBundle = new Bundle();
        testBundle.readFromParcel(parcelledBundle);
        // Recycle the parcel as it should not be referenced
        parcelledBundle.recycle();
        assertThat(testBundle.getString("string")).isNull();
        assertThat(testBundle.<Parcelable>getParcelable("key")).isNull();
    }

    @Test
    public void readFromParcelWithRwHelper_withoutLazyObject_returnsValue() {
        Bundle bundle = new Bundle();
        bundle.putString("string", "value");
        Parcel parcelledBundle = getParcelledBundle(bundle);
        parcelledBundle.setReadWriteHelper(new Parcel.ReadWriteHelper());

        Bundle testBundle = new Bundle();
        testBundle.readFromParcel(parcelledBundle);
        // Recycle the parcel as it should not be referenced
        parcelledBundle.recycle();
        assertThat(testBundle.getString("string")).isEqualTo("value");
    }

    @Test
    public void partialDeserialization_whenNotDefusing_throws() throws Exception {
        Bundle.setShouldDefuse(false);
        Bundle bundle = getMalformedBundle();
        assertThrows(BadParcelableException.class, bundle::isEmpty);
    }

    @Test
    public void partialDeserialization_whenDefusing_emptiesMap() throws Exception {
        Bundle.setShouldDefuse(true);
        Bundle bundle = getMalformedBundle();
        bundle.isEmpty();
        // Nothing thrown
        assertThat(bundle.size()).isEqualTo(0);
    }

    private Bundle getMalformedBundle() {
        Parcel p = Parcel.obtain();
        p.writeInt(BaseBundle.BUNDLE_MAGIC);
        int start = p.dataPosition();
        p.writeInt(1); // Number of items
        p.writeString("key");
        p.writeInt(131313); // Invalid type
        p.writeInt(0); // Anything, really
        int end = p.dataPosition();
        p.setDataPosition(0);
        return new Bundle(p, end - start);
    }


    private static class CustomParcelable implements Parcelable {
        public final int integer;
        public final String string;
        public boolean hasLengthMismatch;

        CustomParcelable(int integer, String string) {
            this.integer = integer;
            this.string = string;
        }

        protected CustomParcelable(Parcel in) {
            integer = in.readInt();
            string = in.readString();
            hasLengthMismatch = in.readBoolean();
        }

        public CustomParcelable setHasLengthMismatch(boolean hasLengthMismatch) {
            this.hasLengthMismatch = hasLengthMismatch;
            return this;
        }

        @Override
        public int describeContents() {
            return 0;
        }

        @Override
        public void writeToParcel(Parcel out, int flags) {
            out.writeInt(integer);
            out.writeString(string);
            out.writeBoolean(hasLengthMismatch);
            if (hasLengthMismatch) {
                out.writeString("extra-write");
            }
        }

        @Override
        public boolean equals(Object other) {
            if (this == other) {
                return true;
            }
            if (!(other instanceof CustomParcelable)) {
                return false;
            }
            CustomParcelable
                    that = (CustomParcelable) other;
            return integer == that.integer
                    && hasLengthMismatch == that.hasLengthMismatch
                    && string.equals(that.string);
        }

        @Override
        public int hashCode() {
            return Objects.hash(integer, string, hasLengthMismatch);
        }

        public static final Creator<CustomParcelable> CREATOR = new Creator<CustomParcelable>() {
            @Override
            public CustomParcelable createFromParcel(Parcel in) {
                return new CustomParcelable(in);
            }
            @Override
            public CustomParcelable[] newArray(int size) {
                return new CustomParcelable[size];
            }
        };
    }
}