From 5140dd0e21b9f776b7a1159188d3253c596d5bcc Mon Sep 17 00:00:00 2001 From: Nick Williams Date: Wed, 11 Nov 2026 05:33:26 +0000 Subject: [PATCH 1/3] Add the android.os.Parcel shim The repackaged Firebase classes implement Parcelable, so Timestamp, RemoteMessage, Trace and others expose writeToParcel(Parcel, int) and a CREATOR that reference android.os.Parcel, a class that was missing from the JVM classpath until now. Consumers compiling against those signatures, such as the Firebase Kotlin SDK's JVM artifacts, had to ship a placeholder of their own. The shim is a small in-memory implementation rather than a stub that throws: a parcel is a list of the values written to it, read back in the same order, so a Parcelable round-trips through writeParcelable and its CREATOR. It mirrors the Android signatures of obtain and recycle, the data position and size accessors, marshall and unmarshall, the typed write and read methods for primitives, strings, byte arrays, lists, maps, ArrayMaps, Bundles, Parcelables, Serializables and tagged values, and the exception transport. The hidden writeString8, readString8, writeArrayMap and readArrayMap are included because the ported Uri and ContentValues call them. Positions count values rather than bytes and marshall produces a Java-serialized form that only unmarshall understands, which is documented on the class; nothing crosses a process boundary on the JVM so there is no binary format to be compatible with. --- src/main/java/android/os/Parcel.java | 627 +++++++++++++++++++++++++++ src/test/kotlin/ParcelTest.kt | 140 ++++++ 2 files changed, 767 insertions(+) create mode 100644 src/main/java/android/os/Parcel.java create mode 100644 src/test/kotlin/ParcelTest.kt diff --git a/src/main/java/android/os/Parcel.java b/src/main/java/android/os/Parcel.java new file mode 100644 index 0000000..eb0cae8 --- /dev/null +++ b/src/main/java/android/os/Parcel.java @@ -0,0 +1,627 @@ +package android.os; + +import android.annotation.NonNull; +import android.annotation.Nullable; +import android.util.ArrayMap; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * A container for the values a {@link Parcelable} flattens itself into, with the Android class's API for the members + * the ported Firebase libraries and their consumers use. The repackaged Firebase classes (Timestamp, RemoteMessage, + * Trace and others) expose {@code writeToParcel(Parcel, int)} and a {@code CREATOR}, so this class exists mainly so + * that code compiled against them can reference it. + *

+ * Nothing is transported between processes on the JVM, so there is no binary format to be compatible with: the parcel + * is an in-memory list of the values written to it, read back in the same order. {@link #dataPosition()}, + * {@link #setDataPosition} and {@link #dataSize()} therefore count values, not bytes, and {@link #marshall()} is a + * Java-serialized copy of those values that only {@link #unmarshall} understands. Reading past the end or reading a + * value as another type throws an {@link IllegalStateException}. Instances are not pooled: {@link #obtain()} creates a + * fresh parcel and {@link #recycle()} empties it. + */ +public final class Parcel { + + private static final int VAL_NULL = -1; + private static final int VAL_STRING = 0; + private static final int VAL_INTEGER = 1; + private static final int VAL_MAP = 2; + private static final int VAL_BUNDLE = 3; + private static final int VAL_PARCELABLE = 4; + private static final int VAL_LONG = 6; + private static final int VAL_FLOAT = 7; + private static final int VAL_DOUBLE = 8; + private static final int VAL_BOOLEAN = 9; + private static final int VAL_LIST = 11; + private static final int VAL_BYTEARRAY = 13; + private static final int VAL_STRINGARRAY = 14; + private static final int VAL_BYTE = 20; + private static final int VAL_SERIALIZABLE = 21; + + private static final int EX_SECURITY = -1; + private static final int EX_ILLEGAL_ARGUMENT = -3; + private static final int EX_NULL_POINTER = -4; + private static final int EX_ILLEGAL_STATE = -5; + private static final int EX_UNSUPPORTED_OPERATION = -7; + + private final List values = new ArrayList<>(); + private int position; + + private Parcel() { + } + + /** A new, empty parcel. */ + @NonNull + public static Parcel obtain() { + return new Parcel(); + } + + /** Empties the parcel so that it can be written again. */ + public void recycle() { + values.clear(); + position = 0; + } + + /** The number of values written to the parcel. */ + public int dataSize() { + return values.size(); + } + + /** The number of values left to read from the current position. */ + public int dataAvail() { + return values.size() - position; + } + + /** The index of the next value to read or write. */ + public int dataPosition() { + return position; + } + + /** Moves to the value at {@code pos}, which is between 0 and {@link #dataSize()} inclusive. */ + public void setDataPosition(int pos) { + if (pos < 0 || pos > values.size()) { + throw new IllegalArgumentException("Position " + pos + " is outside the parcel of size " + values.size()); + } + position = pos; + } + + /** The values of the parcel as bytes that {@link #unmarshall} can read back into a parcel. */ + @NonNull + public byte[] marshall() { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (ObjectOutputStream out = new ObjectOutputStream(bytes)) { + out.writeObject(new ArrayList<>(values)); + } catch (IOException e) { + throw new IllegalStateException("Unable to marshall the parcel", e); + } + return bytes.toByteArray(); + } + + /** + * Replaces the contents of the parcel with the values {@link #marshall()} produced, leaving the position at the end + * like Android does: call {@link #setDataPosition setDataPosition(0)} before reading them. + */ + @SuppressWarnings("unchecked") + public void unmarshall(@NonNull byte[] data, int offset, int length) { + List unmarshalled; + try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data, offset, length))) { + unmarshalled = (List) in.readObject(); + } catch (IOException | ClassNotFoundException | ClassCastException e) { + throw new IllegalArgumentException("The data is not a marshalled parcel", e); + } + values.clear(); + values.addAll(unmarshalled); + position = values.size(); + } + + public void writeByte(byte val) { + writeInt(val); + } + + public void writeInt(int val) { + write(val); + } + + public void writeLong(long val) { + write(val); + } + + public void writeFloat(float val) { + write(val); + } + + public void writeDouble(double val) { + write(val); + } + + public void writeBoolean(boolean val) { + writeInt(val ? 1 : 0); + } + + public void writeString(@Nullable String val) { + write(val); + } + + /** The same as {@link #writeString}: there is no UTF-8 encoding to choose when nothing is encoded. */ + public void writeString8(@Nullable String val) { + write(val); + } + + /** Writes the array as a single value, or a null value for a null array. */ + public void writeByteArray(@Nullable byte[] b) { + write(b == null ? null : b.clone()); + } + + public void writeByteArray(@Nullable byte[] b, int offset, int len) { + if (b == null) { + write(null); + return; + } + byte[] copy = new byte[len]; + System.arraycopy(b, offset, copy, 0, len); + write(copy); + } + + /** Writes the size of the list, or -1 for a null list, followed by its strings. */ + public void writeStringList(@Nullable List val) { + if (val == null) { + writeInt(-1); + return; + } + writeInt(val.size()); + for (String s : val) { + writeString(s); + } + } + + /** Writes the size of the list, or -1 for a null list, followed by its elements with {@link #writeValue}. */ + public void writeList(@Nullable List val) { + if (val == null) { + writeInt(-1); + return; + } + writeInt(val.size()); + for (Object o : val) { + writeValue(o); + } + } + + /** Writes the size of the map, or -1 for a null map, followed by each key and value with {@link #writeValue}. */ + public void writeMap(@Nullable Map val) { + if (val == null) { + writeInt(-1); + return; + } + writeInt(val.size()); + for (Object entry : val.entrySet()) { + writeValue(((Map.Entry) entry).getKey()); + writeValue(((Map.Entry) entry).getValue()); + } + } + + /** Writes the size of the map, or -1 for a null map, followed by each key as a string and each value with {@link #writeValue}. */ + public void writeArrayMap(@Nullable ArrayMap val) { + if (val == null) { + writeInt(-1); + return; + } + writeInt(val.size()); + for (int i = 0; i < val.size(); i++) { + writeString(val.keyAt(i)); + writeValue(val.valueAt(i)); + } + } + + /** Writes the size of the bundle, or -1 for a null bundle, followed by each key as a string and each value with {@link #writeValue}. */ + public void writeBundle(@Nullable Bundle val) { + if (val == null) { + writeInt(-1); + return; + } + writeInt(val.size()); + for (String key : val.keySet()) { + writeString(key); + writeValue(val.get(key)); + } + } + + /** + * Writes the name of the Parcelable's class, or a null string for a null Parcelable, and then lets it write itself + * with {@link Parcelable#writeToParcel}. + */ + public void writeParcelable(@Nullable Parcelable p, int parcelableFlags) { + if (p == null) { + writeString(null); + return; + } + writeString(p.getClass().getName()); + p.writeToParcel(this, parcelableFlags); + } + + /** Writes the object itself, which must be Serializable for {@link #marshall()} to work. */ + public void writeSerializable(@Nullable Serializable s) { + write(s); + } + + /** + * Writes a value of one of the types the typed write methods take, with a tag for {@link #readValue} to know which, + * or any other Serializable value as is. + * + * @throws IllegalArgumentException for a value of any other type + */ + public void writeValue(@Nullable Object v) { + if (v == null) { + writeInt(VAL_NULL); + } else if (v instanceof String) { + writeInt(VAL_STRING); + writeString((String) v); + } else if (v instanceof Integer) { + writeInt(VAL_INTEGER); + writeInt((Integer) v); + } else if (v instanceof Map) { + writeInt(VAL_MAP); + writeMap((Map) v); + } else if (v instanceof Bundle) { + writeInt(VAL_BUNDLE); + writeBundle((Bundle) v); + } else if (v instanceof Parcelable) { + writeInt(VAL_PARCELABLE); + writeParcelable((Parcelable) v, 0); + } else if (v instanceof Long) { + writeInt(VAL_LONG); + writeLong((Long) v); + } else if (v instanceof Float) { + writeInt(VAL_FLOAT); + writeFloat((Float) v); + } else if (v instanceof Double) { + writeInt(VAL_DOUBLE); + writeDouble((Double) v); + } else if (v instanceof Boolean) { + writeInt(VAL_BOOLEAN); + writeBoolean((Boolean) v); + } else if (v instanceof List) { + writeInt(VAL_LIST); + writeList((List) v); + } else if (v instanceof byte[]) { + writeInt(VAL_BYTEARRAY); + writeByteArray((byte[]) v); + } else if (v instanceof String[]) { + writeInt(VAL_STRINGARRAY); + writeStringList(Arrays.asList((String[]) v)); + } else if (v instanceof Byte) { + writeInt(VAL_BYTE); + writeByte((Byte) v); + } else if (v instanceof Serializable) { + writeInt(VAL_SERIALIZABLE); + writeSerializable((Serializable) v); + } else { + throw new IllegalArgumentException("Parcel: unable to marshal value " + v); + } + } + + /** + * Writes an exception for {@link #readException()} to rethrow: a code for the exception types Android transports + * (SecurityException, IllegalArgumentException, NullPointerException, IllegalStateException and + * UnsupportedOperationException) followed by the message. Any other exception is thrown here instead, like Android + * does, wrapped in a RuntimeException unless it is one. + */ + public void writeException(@NonNull Exception e) { + int code = exceptionCode(e); + if (code == 0) { + if (e instanceof RuntimeException) { + throw (RuntimeException) e; + } + throw new RuntimeException(e); + } + writeInt(code); + writeString(e.getMessage()); + } + + /** Writes the code that tells {@link #readException()} that no exception occurred. */ + public void writeNoException() { + writeInt(0); + } + + /** Rethrows the exception {@link #writeException} wrote, if one was written at the current position. */ + public void readException() { + int code = readExceptionCode(); + if (code != 0) { + readException(code, readString()); + } + } + + /** The code of the exception written at the current position, or 0 when {@link #writeNoException()} was. */ + public int readExceptionCode() { + return readInt(); + } + + /** Throws the exception {@code code} stands for, with {@code msg}. */ + public void readException(int code, String msg) { + switch (code) { + case EX_SECURITY: + throw new SecurityException(msg); + case EX_ILLEGAL_ARGUMENT: + throw new IllegalArgumentException(msg); + case EX_NULL_POINTER: + throw new NullPointerException(msg); + case EX_ILLEGAL_STATE: + throw new IllegalStateException(msg); + case EX_UNSUPPORTED_OPERATION: + throw new UnsupportedOperationException(msg); + default: + throw new RuntimeException("Unknown exception code: " + code + " msg " + msg); + } + } + + public byte readByte() { + return (byte) readInt(); + } + + public int readInt() { + return read(Integer.class); + } + + public long readLong() { + return read(Long.class); + } + + public float readFloat() { + return read(Float.class); + } + + public double readDouble() { + return read(Double.class); + } + + public boolean readBoolean() { + return readInt() != 0; + } + + @Nullable + public String readString() { + return readNullable(String.class); + } + + /** The same as {@link #readString}, reading what either string method wrote. */ + @Nullable + public String readString8() { + return readNullable(String.class); + } + + @Nullable + public byte[] createByteArray() { + byte[] bytes = readNullable(byte[].class); + return bytes == null ? null : bytes.clone(); + } + + /** Reads an array of the same length as {@code val} into it. */ + public void readByteArray(@NonNull byte[] val) { + byte[] bytes = createByteArray(); + if (bytes == null || bytes.length != val.length) { + throw new IllegalStateException("bad array lengths"); + } + System.arraycopy(bytes, 0, val, 0, val.length); + } + + @Nullable + public ArrayList createStringArrayList() { + int n = readInt(); + if (n < 0) { + return null; + } + ArrayList list = new ArrayList<>(n); + for (int i = 0; i < n; i++) { + list.add(readString()); + } + return list; + } + + /** Replaces the contents of {@code list} with the strings {@link #writeStringList} wrote. */ + public void readStringList(@NonNull List list) { + list.clear(); + int n = readInt(); + for (int i = 0; i < n; i++) { + list.add(readString()); + } + } + + @Nullable + public ArrayList readArrayList(@Nullable ClassLoader loader) { + int n = readInt(); + if (n < 0) { + return null; + } + ArrayList list = new ArrayList<>(n); + readValues(n, list, loader); + return list; + } + + /** Adds the elements {@link #writeList} wrote to {@code outVal}. */ + @SuppressWarnings("unchecked") + public void readList(@NonNull List outVal, @Nullable ClassLoader loader) { + readValues(readInt(), outVal, loader); + } + + @Nullable + public HashMap readHashMap(@Nullable ClassLoader loader) { + int n = readInt(); + if (n < 0) { + return null; + } + HashMap map = new HashMap<>(n); + readEntries(n, map, loader); + return map; + } + + /** Adds the entries {@link #writeMap} wrote to {@code outVal}. */ + @SuppressWarnings("unchecked") + public void readMap(@NonNull Map outVal, @Nullable ClassLoader loader) { + readEntries(readInt(), outVal, loader); + } + + /** Adds the entries {@link #writeArrayMap} wrote to {@code outVal}. */ + public void readArrayMap(@NonNull ArrayMap outVal, @Nullable ClassLoader loader) { + int n = readInt(); + for (int i = 0; i < n; i++) { + outVal.put(readString(), readValue(loader)); + } + } + + @Nullable + public Bundle readBundle() { + return readBundle(null); + } + + @Nullable + public Bundle readBundle(@Nullable ClassLoader loader) { + int n = readInt(); + if (n < 0) { + return null; + } + Map map = new LinkedHashMap<>(); + for (int i = 0; i < n; i++) { + map.put(readString(), readValue(loader)); + } + return new Bundle(map); + } + + /** + * Creates the Parcelable {@link #writeParcelable} wrote with the {@code CREATOR} of its class, which is loaded + * through {@code loader} when one is given. + * + * @throws IllegalStateException when the class or its CREATOR cannot be found + */ + @Nullable + @SuppressWarnings("unchecked") + public T readParcelable(@Nullable ClassLoader loader) { + String name = readString(); + if (name == null) { + return null; + } + Parcelable.Creator creator; + try { + Class type = loader == null ? Class.forName(name) : Class.forName(name, true, loader); + creator = (Parcelable.Creator) type.getField("CREATOR").get(null); + } catch (ReflectiveOperationException | ClassCastException e) { + throw new IllegalStateException("Parcelable " + name + " has no public static CREATOR", e); + } + if (creator instanceof Parcelable.ClassLoaderCreator) { + return (T) ((Parcelable.ClassLoaderCreator) creator).createFromParcel(this, loader); + } + return (T) creator.createFromParcel(this); + } + + @Nullable + public Serializable readSerializable() { + return readNullable(Serializable.class); + } + + /** Reads a value {@link #writeValue} wrote, creating a Parcelable through {@code loader} when one is given. */ + @Nullable + public Object readValue(@Nullable ClassLoader loader) { + int type = readInt(); + switch (type) { + case VAL_NULL: + return null; + case VAL_STRING: + return readString(); + case VAL_INTEGER: + return readInt(); + case VAL_MAP: + return readHashMap(loader); + case VAL_BUNDLE: + return readBundle(loader); + case VAL_PARCELABLE: + return readParcelable(loader); + case VAL_LONG: + return readLong(); + case VAL_FLOAT: + return readFloat(); + case VAL_DOUBLE: + return readDouble(); + case VAL_BOOLEAN: + return readBoolean(); + case VAL_LIST: + return readArrayList(loader); + case VAL_BYTEARRAY: + return createByteArray(); + case VAL_STRINGARRAY: + ArrayList strings = createStringArrayList(); + return strings == null ? null : strings.toArray(new String[0]); + case VAL_BYTE: + return readByte(); + case VAL_SERIALIZABLE: + return readSerializable(); + default: + throw new IllegalStateException("Parcel: unknown type code " + type + " at position " + (position - 1)); + } + } + + private void write(@Nullable Object value) { + if (position == values.size()) { + values.add(value); + } else { + values.set(position, value); + } + position++; + } + + @NonNull + private T read(Class type) { + T value = readNullable(type); + if (value == null) { + throw new IllegalStateException("Parcel: expected a " + type.getSimpleName() + " at position " + (position - 1) + " but read null"); + } + return value; + } + + @Nullable + private T readNullable(Class type) { + if (position >= values.size()) { + throw new IllegalStateException("Parcel: no value left to read at position " + position); + } + Object value = values.get(position); + if (value != null && !type.isInstance(value)) { + throw new IllegalStateException("Parcel: expected a " + type.getSimpleName() + " at position " + position + " but found a " + value.getClass().getSimpleName()); + } + position++; + return type.cast(value); + } + + private void readValues(int n, List outVal, @Nullable ClassLoader loader) { + for (int i = 0; i < n; i++) { + outVal.add(readValue(loader)); + } + } + + private void readEntries(int n, Map outVal, @Nullable ClassLoader loader) { + for (int i = 0; i < n; i++) { + outVal.put(readValue(loader), readValue(loader)); + } + } + + private static int exceptionCode(Exception e) { + if (e instanceof SecurityException) { + return EX_SECURITY; + } else if (e instanceof IllegalArgumentException) { + return EX_ILLEGAL_ARGUMENT; + } else if (e instanceof NullPointerException) { + return EX_NULL_POINTER; + } else if (e instanceof IllegalStateException) { + return EX_ILLEGAL_STATE; + } else if (e instanceof UnsupportedOperationException) { + return EX_UNSUPPORTED_OPERATION; + } + return 0; + } +} diff --git a/src/test/kotlin/ParcelTest.kt b/src/test/kotlin/ParcelTest.kt new file mode 100644 index 0000000..071ed32 --- /dev/null +++ b/src/test/kotlin/ParcelTest.kt @@ -0,0 +1,140 @@ +/* + * Tests the android.os.Parcel shim: the repackaged Firebase classes expose writeToParcel(Parcel, int) and a CREATOR, + * and this checks that values written to a parcel read back the way they do on Android. + */ +import android.os.Bundle +import android.os.Parcel +import android.os.Parcelable +import android.util.ArrayMap +import com.google.firebase.Timestamp +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test + +class ParcelTest { + + @Test + fun `reads back primitives and strings in order`() { + val parcel = Parcel.obtain() + parcel.writeInt(42) + parcel.writeLong(1L shl 40) + parcel.writeDouble(42.5) + parcel.writeFloat(1.5f) + parcel.writeBoolean(true) + parcel.writeByte(7) + parcel.writeString("value") + parcel.writeString(null) + parcel.writeByteArray(byteArrayOf(1, 2, 3)) + parcel.writeByteArray(null) + assertEquals(10, parcel.dataSize()) + assertEquals(10, parcel.dataPosition()) + + parcel.setDataPosition(0) + assertEquals(42, parcel.readInt()) + assertEquals(1L shl 40, parcel.readLong()) + assertEquals(42.5, parcel.readDouble(), 0.0) + assertEquals(1.5f, parcel.readFloat(), 0.0f) + assertTrue(parcel.readBoolean()) + assertEquals(7.toByte(), parcel.readByte()) + assertEquals("value", parcel.readString()) + assertNull(parcel.readString()) + assertArrayEquals(byteArrayOf(1, 2, 3), parcel.createByteArray()) + assertNull(parcel.createByteArray()) + assertEquals(0, parcel.dataAvail()) + parcel.recycle() + assertEquals(0, parcel.dataSize()) + } + + @Test + fun `round trips a Firebase Parcelable through its CREATOR`() { + val parcel = Parcel.obtain() + parcel.writeParcelable(Timestamp(1_700_000_000L, 123_000), 0) + parcel.writeParcelable(null, 0) + parcel.setDataPosition(0) + + assertEquals(Timestamp(1_700_000_000L, 123_000), parcel.readParcelable(Timestamp::class.java.classLoader)) + assertNull(parcel.readParcelable(null)) + } + + @Test + fun `round trips collections, bundles and tagged values`() { + val parcel = Parcel.obtain() + parcel.writeStringList(listOf("a", "b")) + parcel.writeStringList(null) + parcel.writeList(listOf(1, "two", 3L, null)) + parcel.writeMap(mapOf("int" to 1, "list" to listOf(true))) + parcel.writeBundle(Bundle().apply { putString("key", "value"); putInt("int", 2) }) + parcel.writeBundle(null) + parcel.writeArrayMap(ArrayMap().apply { put("k", 1.5) }) + parcel.writeValue(Timestamp(1L, 2)) + parcel.writeValue(arrayOf("x", "y")) + parcel.writeValue(java.util.Date(5L)) + parcel.setDataPosition(0) + + assertEquals(listOf("a", "b"), parcel.createStringArrayList()) + assertNull(parcel.createStringArrayList()) + assertEquals(listOf(1, "two", 3L, null), parcel.readArrayList(null)) + assertEquals(mapOf("int" to 1, "list" to listOf(true)), parcel.readHashMap(null)) + val bundle = parcel.readBundle()!! + assertEquals("value", bundle.getString("key")) + assertEquals(2, bundle.getInt("int")) + assertNull(parcel.readBundle()) + val arrayMap = ArrayMap() + parcel.readArrayMap(arrayMap, null) + assertEquals(1.5, arrayMap["k"]) + assertEquals(Timestamp(1L, 2), parcel.readValue(null)) + assertArrayEquals(arrayOf("x", "y"), parcel.readValue(null) as Array<*>) + assertEquals(java.util.Date(5L), parcel.readValue(null)) + assertEquals(0, parcel.dataAvail()) + } + + @Test + fun `marshalls and unmarshalls`() { + val parcel = Parcel.obtain() + parcel.writeInt(1) + parcel.writeString("one") + parcel.writeParcelable(Timestamp(3L, 4), 0) + val bytes = parcel.marshall() + + val copy = Parcel.obtain() + copy.unmarshall(bytes, 0, bytes.size) + assertEquals(copy.dataSize(), copy.dataPosition()) + copy.setDataPosition(0) + assertEquals(1, copy.readInt()) + assertEquals("one", copy.readString()) + assertEquals(Timestamp(3L, 4), copy.readParcelable(null)) + } + + @Test + fun `transports exceptions`() { + val parcel = Parcel.obtain() + parcel.writeNoException() + parcel.writeException(IllegalArgumentException("bad")) + parcel.setDataPosition(0) + + parcel.readException() + val e = assertThrows(IllegalArgumentException::class.java) { parcel.readException() } + assertEquals("bad", e.message) + assertThrows(RuntimeException::class.java) { parcel.writeException(java.io.IOException("not transported")) } + } + + @Test + fun `fails clearly on misuse`() { + val parcel = Parcel.obtain() + parcel.writeString("text") + assertThrows(IllegalStateException::class.java) { parcel.readInt() } + parcel.setDataPosition(0) + assertThrows(IllegalStateException::class.java) { parcel.readInt() } + assertThrows(IllegalArgumentException::class.java) { parcel.setDataPosition(2) } + parcel.setDataPosition(0) + parcel.writeInt(5) // overwrites the string, like writing at a position does on Android + assertEquals(1, parcel.dataSize()) + parcel.setDataPosition(0) + assertEquals(5, parcel.readInt()) + assertFalse(parcel.dataAvail() > 0) + } +} From 33f945b551f8a048d9b44a9b58f7fa163318840c Mon Sep 17 00:00:00 2001 From: Nick Williams Date: Wed, 11 Nov 2026 05:39:27 +0000 Subject: [PATCH 2/3] Add the AuthKt facade of the Android firebase-auth library The Android SDK ships a file of Kotlin extensions with each library, and the ported libraries bring theirs along in their jars: FirebaseKt, FirestoreKt, DatabaseKt, StorageKt, FunctionsKt, RemoteConfigKt and InstallationsKt. Auth is implemented here rather than ported, so its facade, com.google.firebase.auth.AuthKt, was the one missing, and the Firebase Kotlin SDK has had to ship a copy of it in its JVM artifact. Auth.kt declares the same members with the Android signatures: the Firebase.auth property and Firebase.auth(app) function returning the FirebaseAuth of the default or a given app, and the actionCodeSettings, oAuthProvider (with and without a FirebaseAuth), oAuthCredential and userProfileChangeRequest builder functions, each applying its init block to a new builder of the corresponding class. --- .../java/com/google/firebase/auth/Auth.kt | 43 +++++++++++++ src/test/kotlin/FirebaseAuthKtTest.kt | 61 +++++++++++++++++++ 2 files changed, 104 insertions(+) create mode 100644 src/main/java/com/google/firebase/auth/Auth.kt create mode 100644 src/test/kotlin/FirebaseAuthKtTest.kt diff --git a/src/main/java/com/google/firebase/auth/Auth.kt b/src/main/java/com/google/firebase/auth/Auth.kt new file mode 100644 index 0000000..c70e9f1 --- /dev/null +++ b/src/main/java/com/google/firebase/auth/Auth.kt @@ -0,0 +1,43 @@ +/* + * The Kotlin extensions the Android SDK's firebase-auth ships as com.google.firebase.auth.AuthKt, so that code written + * against them compiles against this SDK like it does against the other ported libraries' facades (FirestoreKt, + * DatabaseKt and the rest, which come with their jars). + */ +package com.google.firebase.auth + +import com.google.firebase.Firebase +import com.google.firebase.FirebaseApp + +/** Returns the [FirebaseAuth] instance of the default [FirebaseApp]. */ +val Firebase.auth: FirebaseAuth + get() = FirebaseAuth.getInstance() + +/** Returns the [FirebaseAuth] instance of a given [FirebaseApp]. */ +fun Firebase.auth(app: FirebaseApp): FirebaseAuth = FirebaseAuth.getInstance(app) + +/** Returns a [ActionCodeSettings] instance initialized using the [init] function. */ +fun actionCodeSettings(init: ActionCodeSettings.Builder.() -> Unit): ActionCodeSettings = + ActionCodeSettings.newBuilder().apply(init).build() + +/** Returns a [OAuthProvider] instance initialized using the [init] function. */ +fun oAuthProvider( + providerId: String, + init: OAuthProvider.Builder.() -> Unit +): OAuthProvider = OAuthProvider.newBuilder(providerId).apply(init).build() + +/** Returns a [OAuthProvider] instance initialized using the [init] function. */ +fun oAuthProvider( + providerId: String, + firebaseAuth: FirebaseAuth, + init: OAuthProvider.Builder.() -> Unit +): OAuthProvider = OAuthProvider.newBuilder(providerId, firebaseAuth).apply(init).build() + +/** Returns a [AuthCredential] instance initialized using the [init] function. */ +fun oAuthCredential( + providerId: String, + init: OAuthProvider.CredentialBuilder.() -> Unit +): AuthCredential = OAuthProvider.newCredentialBuilder(providerId).apply(init).build() + +/** Returns a [UserProfileChangeRequest] instance initialized using the [init] function. */ +fun userProfileChangeRequest(init: UserProfileChangeRequest.Builder.() -> Unit): UserProfileChangeRequest = + UserProfileChangeRequest.Builder().apply(init).build() diff --git a/src/test/kotlin/FirebaseAuthKtTest.kt b/src/test/kotlin/FirebaseAuthKtTest.kt new file mode 100644 index 0000000..e36403c --- /dev/null +++ b/src/test/kotlin/FirebaseAuthKtTest.kt @@ -0,0 +1,61 @@ +/* + * Exercises the AuthKt facade, the Kotlin extensions the Android SDK's firebase-auth ships, against the builders and + * instances they stand for. None of it needs a server. + */ +import android.net.Uri +import com.google.firebase.Firebase +import com.google.firebase.auth.FirebaseAuth +import com.google.firebase.auth.OAuthCredential +import com.google.firebase.auth.actionCodeSettings +import com.google.firebase.auth.auth +import com.google.firebase.auth.oAuthCredential +import com.google.firebase.auth.oAuthProvider +import com.google.firebase.auth.userProfileChangeRequest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test + +class FirebaseAuthKtTest : FirebaseTest() { + + @Test + fun `auth extensions return the FirebaseAuth of the app`() { + assertSame(FirebaseAuth.getInstance(app), Firebase.auth(app)) + assertSame(FirebaseAuth.getInstance(), Firebase.auth) + } + + @Test + fun `builder functions apply their init to a new builder`() { + val auth = Firebase.auth(app) + + val settings = actionCodeSettings { + setUrl("https://example.com/finish") + setHandleCodeInApp(true) + } + assertEquals("https://example.com/finish", settings.url) + + val provider = oAuthProvider("apple.com") { setScopes(listOf("email")) } + assertEquals("apple.com", provider.providerId) + assertEquals(listOf("email"), provider.scopes) + + val providerWithAuth = oAuthProvider("github.com", auth) { addCustomParameter("locale", "fr") } + assertEquals("github.com", providerWithAuth.providerId) + assertEquals(mapOf("locale" to "fr"), providerWithAuth.customParameters) + + val credential = oAuthCredential("apple.com") { + setIdToken("id") + setAccessToken("access") + } + assertTrue(credential is OAuthCredential) + assertEquals("apple.com", credential.provider) + assertEquals("id", (credential as OAuthCredential).idToken) + assertEquals("access", credential.accessToken) + + val request = userProfileChangeRequest { + setDisplayName("Name") + setPhotoUri(Uri.parse("https://example.com/photo.png")) + } + assertEquals("Name", request.displayName) + assertEquals(Uri.parse("https://example.com/photo.png"), request.photoUri) + } +} From f75a2f79c6f8e1696fbf1de5a80f56f7ba1873b2 Mon Sep 17 00:00:00 2001 From: Nick Williams Date: Wed, 11 Nov 2026 06:16:08 +0000 Subject: [PATCH 3/3] Keep Parcel's serialized values as bytes and marshall a data-only stream Three fixes to the Parcel shim from review. writeSerializable stored the object itself, so a Serializable changed after it was written read back changed, and changing a read result changed later reads; the Serializable fallback of writeValue, which primitive arrays take, behaved the same. The parcel now keeps the bytes of the serialized form taken at write time, and readSerializable deserializes a fresh copy on every read. marshall used Java serialization for the whole value list and unmarshall read it back with ObjectInputStream.readObject, which runs deserialization callbacks before the result is checked to be a list, so bytes from an untrusted source could execute code through classpath types. The envelope is now a tagged byte stream written with DataOutputStream: the number of values, then each as a tag byte and its data, for the types a value in the list can have once the typed writes have flattened lists, maps, bundles and parcelables into them (null, String, int, long, float, double, byte arrays and serialized bytes). unmarshall deserializes nothing; a Serializable stays bytes until a caller asks for it with readSerializable, and malformed data is rejected with an IllegalArgumentException. marshall throws an IllegalStateException naming the type if a value it cannot carry ever reaches the list. Uri declared its CREATOR as a JvmStatic property, which the JVM sees as a getter, so writeParcelable accepted a Uri but readParcelable could not find the CREATOR field reflectively. It is a JvmField now, a public static field like Android's, and ParcelTest round-trips hierarchical and opaque Uris as well as snapshots of Serializables and the new stream. --- src/main/java/android/net/Uri.kt | 4 +- src/main/java/android/os/Parcel.java | 174 ++++++++++++++++++++++++--- src/test/kotlin/ParcelTest.kt | 56 +++++++++ 3 files changed, 216 insertions(+), 18 deletions(-) diff --git a/src/main/java/android/net/Uri.kt b/src/main/java/android/net/Uri.kt index 9ab18a8..c8622da 100644 --- a/src/main/java/android/net/Uri.kt +++ b/src/main/java/android/net/Uri.kt @@ -1835,8 +1835,8 @@ abstract class Uri private constructor() : Parcelable, Comparable { /** Identifies a null parcelled Uri. */ private const val NULL_TYPE_ID = 0 - /** Reads Uris from Parcels. */ - @JvmStatic + /** Reads Uris from Parcels. A field rather than a getter, like Android, so that Parcel finds it reflectively. */ + @JvmField val CREATOR: Parcelable.Creator = object : Parcelable.Creator { override fun createFromParcel(`in`: Parcel): Uri? { diff --git a/src/main/java/android/os/Parcel.java b/src/main/java/android/os/Parcel.java index eb0cae8..4225b1b 100644 --- a/src/main/java/android/os/Parcel.java +++ b/src/main/java/android/os/Parcel.java @@ -6,10 +6,13 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -26,9 +29,10 @@ * Nothing is transported between processes on the JVM, so there is no binary format to be compatible with: the parcel * is an in-memory list of the values written to it, read back in the same order. {@link #dataPosition()}, * {@link #setDataPosition} and {@link #dataSize()} therefore count values, not bytes, and {@link #marshall()} is a - * Java-serialized copy of those values that only {@link #unmarshall} understands. Reading past the end or reading a - * value as another type throws an {@link IllegalStateException}. Instances are not pooled: {@link #obtain()} creates a - * fresh parcel and {@link #recycle()} empties it. + * tagged byte stream of those values that only {@link #unmarshall} understands. A Serializable is kept as the bytes of + * its serialized form from the moment it is written, and only {@link #readSerializable()} deserializes it. Reading past + * the end or reading a value as another type throws an {@link IllegalStateException}. Instances are not pooled: + * {@link #obtain()} creates a fresh parcel and {@link #recycle()} empties it. */ public final class Parcel { @@ -48,6 +52,17 @@ public final class Parcel { private static final int VAL_BYTE = 20; private static final int VAL_SERIALIZABLE = 21; + // The tags of the marshalled stream, one for each type a value in the list can have once the typed writes have + // flattened lists, maps, bundles and parcelables into these. + private static final byte TAG_NULL = 0; + private static final byte TAG_STRING = 1; + private static final byte TAG_INT = 2; + private static final byte TAG_LONG = 3; + private static final byte TAG_FLOAT = 4; + private static final byte TAG_DOUBLE = 5; + private static final byte TAG_BYTES = 6; + private static final byte TAG_SERIALIZED = 7; + private static final int EX_SECURITY = -1; private static final int EX_ILLEGAL_ARGUMENT = -3; private static final int EX_NULL_POINTER = -4; @@ -95,12 +110,45 @@ public void setDataPosition(int pos) { position = pos; } - /** The values of the parcel as bytes that {@link #unmarshall} can read back into a parcel. */ + /** + * The values of the parcel as a tagged byte stream that {@link #unmarshall} reads back into a parcel: the number of + * values, then each as a tag byte and its data. Serializables stay the bytes of their serialized form. + * + * @throws IllegalStateException when a value is of a type the stream cannot carry, which the typed writes never store + */ @NonNull public byte[] marshall() { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - try (ObjectOutputStream out = new ObjectOutputStream(bytes)) { - out.writeObject(new ArrayList<>(values)); + try (DataOutputStream out = new DataOutputStream(bytes)) { + out.writeInt(values.size()); + for (Object value : values) { + if (value == null) { + out.writeByte(TAG_NULL); + } else if (value instanceof String) { + out.writeByte(TAG_STRING); + writeBytes(out, ((String) value).getBytes(StandardCharsets.UTF_8)); + } else if (value instanceof Integer) { + out.writeByte(TAG_INT); + out.writeInt((Integer) value); + } else if (value instanceof Long) { + out.writeByte(TAG_LONG); + out.writeLong((Long) value); + } else if (value instanceof Float) { + out.writeByte(TAG_FLOAT); + out.writeFloat((Float) value); + } else if (value instanceof Double) { + out.writeByte(TAG_DOUBLE); + out.writeDouble((Double) value); + } else if (value instanceof byte[]) { + out.writeByte(TAG_BYTES); + writeBytes(out, (byte[]) value); + } else if (value instanceof SerializedValue) { + out.writeByte(TAG_SERIALIZED); + writeBytes(out, ((SerializedValue) value).bytes); + } else { + throw new IllegalStateException("Parcel: cannot marshall a value of type " + value.getClass().getName()); + } + } } catch (IOException e) { throw new IllegalStateException("Unable to marshall the parcel", e); } @@ -109,14 +157,53 @@ public byte[] marshall() { /** * Replaces the contents of the parcel with the values {@link #marshall()} produced, leaving the position at the end - * like Android does: call {@link #setDataPosition setDataPosition(0)} before reading them. + * like Android does: call {@link #setDataPosition setDataPosition(0)} before reading them. Nothing is deserialized + * here: a Serializable in the data stays bytes until {@link #readSerializable()} asks for it. + * + * @throws IllegalArgumentException when the data is not a marshalled parcel */ - @SuppressWarnings("unchecked") public void unmarshall(@NonNull byte[] data, int offset, int length) { - List unmarshalled; - try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data, offset, length))) { - unmarshalled = (List) in.readObject(); - } catch (IOException | ClassNotFoundException | ClassCastException e) { + List unmarshalled = new ArrayList<>(); + try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(data, offset, length))) { + int count = in.readInt(); + if (count < 0) { + throw new IOException("Negative value count " + count); + } + for (int i = 0; i < count; i++) { + byte tag = in.readByte(); + switch (tag) { + case TAG_NULL: + unmarshalled.add(null); + break; + case TAG_STRING: + unmarshalled.add(new String(readBytes(in), StandardCharsets.UTF_8)); + break; + case TAG_INT: + unmarshalled.add(in.readInt()); + break; + case TAG_LONG: + unmarshalled.add(in.readLong()); + break; + case TAG_FLOAT: + unmarshalled.add(in.readFloat()); + break; + case TAG_DOUBLE: + unmarshalled.add(in.readDouble()); + break; + case TAG_BYTES: + unmarshalled.add(readBytes(in)); + break; + case TAG_SERIALIZED: + unmarshalled.add(new SerializedValue(readBytes(in))); + break; + default: + throw new IOException("Unknown value tag " + tag); + } + } + if (in.read() != -1) { + throw new IOException("Data after the last value"); + } + } catch (IOException e) { throw new IllegalArgumentException("The data is not a marshalled parcel", e); } values.clear(); @@ -124,6 +211,21 @@ public void unmarshall(@NonNull byte[] data, int offset, int length) { position = values.size(); } + private static void writeBytes(DataOutputStream out, byte[] bytes) throws IOException { + out.writeInt(bytes.length); + out.write(bytes); + } + + private static byte[] readBytes(DataInputStream in) throws IOException { + int length = in.readInt(); + if (length < 0 || length > in.available()) { + throw new IOException("Bad length " + length + " with " + in.available() + " bytes left"); + } + byte[] bytes = new byte[length]; + in.readFully(bytes); + return bytes; + } + public void writeByte(byte val) { writeInt(val); } @@ -248,14 +350,19 @@ public void writeParcelable(@Nullable Parcelable p, int parcelableFlags) { p.writeToParcel(this, parcelableFlags); } - /** Writes the object itself, which must be Serializable for {@link #marshall()} to work. */ + /** + * Writes a serialized snapshot of the object, so that changing it afterwards does not change the parcel and each + * {@link #readSerializable()} returns a fresh copy. + * + * @throws IllegalArgumentException when the object cannot be serialized + */ public void writeSerializable(@Nullable Serializable s) { - write(s); + write(s == null ? null : new SerializedValue(s)); } /** * Writes a value of one of the types the typed write methods take, with a tag for {@link #readValue} to know which, - * or any other Serializable value as is. + * or a serialized snapshot of any other Serializable value. * * @throws IllegalArgumentException for a value of any other type */ @@ -521,9 +628,16 @@ public T readParcelable(@Nullable ClassLoader loader) { return (T) creator.createFromParcel(this); } + /** + * Deserializes a fresh copy of the object {@link #writeSerializable} wrote. This is the only place the parcel + * deserializes anything: {@link #unmarshall} keeps serialized objects as bytes until a caller asks for them here. + * + * @throws IllegalStateException when the bytes cannot be deserialized + */ @Nullable public Serializable readSerializable() { - return readNullable(Serializable.class); + SerializedValue value = readNullable(SerializedValue.class); + return value == null ? null : value.read(); } /** Reads a value {@link #writeValue} wrote, creating a Parcelable through {@code loader} when one is given. */ @@ -610,6 +724,34 @@ private void readEntries(int n, Map outVal, @Nullable ClassLoade } } + /** The bytes of a Serializable's serialized form, taken when it is written and deserialized afresh on every read. */ + private static final class SerializedValue { + + final byte[] bytes; + + SerializedValue(Serializable value) { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (ObjectOutputStream out = new ObjectOutputStream(bytes)) { + out.writeObject(value); + } catch (IOException e) { + throw new IllegalArgumentException("Parcel: unable to marshal value " + value, e); + } + this.bytes = bytes.toByteArray(); + } + + SerializedValue(byte[] bytes) { + this.bytes = bytes; + } + + Serializable read() { + try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes))) { + return (Serializable) in.readObject(); + } catch (IOException | ClassNotFoundException | ClassCastException e) { + throw new IllegalStateException("Parcel: unable to read the serialized value", e); + } + } + } + private static int exceptionCode(Exception e) { if (e instanceof SecurityException) { return EX_SECURITY; diff --git a/src/test/kotlin/ParcelTest.kt b/src/test/kotlin/ParcelTest.kt index 071ed32..145f84b 100644 --- a/src/test/kotlin/ParcelTest.kt +++ b/src/test/kotlin/ParcelTest.kt @@ -2,6 +2,7 @@ * Tests the android.os.Parcel shim: the repackaged Firebase classes expose writeToParcel(Parcel, int) and a CREATOR, * and this checks that values written to a parcel read back the way they do on Android. */ +import android.net.Uri import android.os.Bundle import android.os.Parcel import android.os.Parcelable @@ -10,6 +11,7 @@ import com.google.firebase.Timestamp import org.junit.Assert.assertArrayEquals import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotSame import org.junit.Assert.assertNull import org.junit.Assert.assertThrows import org.junit.Assert.assertTrue @@ -60,6 +62,44 @@ class ParcelTest { assertNull(parcel.readParcelable(null)) } + @Test + fun `round trips a Uri through its CREATOR`() { + val hierarchical = Uri.parse("https://example.com/path/to?q=1&r=two#fragment") + val opaque = Uri.parse("mailto:someone@example.com") + val parcel = Parcel.obtain() + parcel.writeParcelable(hierarchical, 0) + parcel.writeValue(opaque) + parcel.setDataPosition(0) + + assertEquals(hierarchical, parcel.readParcelable(null)) + assertEquals(opaque, parcel.readValue(Uri::class.java.classLoader)) + } + + @Test + fun `serializables are snapshots, read as fresh copies`() { + val builder = StringBuilder("one") + val numbers = intArrayOf(1, 2) + val parcel = Parcel.obtain() + parcel.writeSerializable(builder) + parcel.writeValue(numbers) // falls back to the Serializable path + parcel.writeSerializable(null) + builder.append(" two") + numbers[0] = 99 + + parcel.setDataPosition(0) + val first = parcel.readSerializable() + assertEquals("one", first.toString()) + val read = parcel.readValue(null) as IntArray + assertArrayEquals(intArrayOf(1, 2), read) + assertNull(parcel.readSerializable()) + read[1] = 42 + parcel.setDataPosition(0) + val second = parcel.readSerializable() + assertEquals("one", second.toString()) + assertNotSame(first, second) + assertArrayEquals(intArrayOf(1, 2), parcel.readValue(null) as IntArray) + } + @Test fun `round trips collections, bundles and tagged values`() { val parcel = Parcel.obtain() @@ -98,6 +138,12 @@ class ParcelTest { parcel.writeInt(1) parcel.writeString("one") parcel.writeParcelable(Timestamp(3L, 4), 0) + parcel.writeString(null) + parcel.writeLong(1L shl 40) + parcel.writeFloat(1.5f) + parcel.writeDouble(2.5) + parcel.writeByteArray(byteArrayOf(9, 8)) + parcel.writeValue(java.util.Date(5L)) val bytes = parcel.marshall() val copy = Parcel.obtain() @@ -107,6 +153,16 @@ class ParcelTest { assertEquals(1, copy.readInt()) assertEquals("one", copy.readString()) assertEquals(Timestamp(3L, 4), copy.readParcelable(null)) + assertNull(copy.readString()) + assertEquals(1L shl 40, copy.readLong()) + assertEquals(1.5f, copy.readFloat(), 0.0f) + assertEquals(2.5, copy.readDouble(), 0.0) + assertArrayEquals(byteArrayOf(9, 8), copy.createByteArray()) + assertEquals(java.util.Date(5L), copy.readValue(null)) + assertEquals(0, copy.dataAvail()) + + assertThrows(IllegalArgumentException::class.java) { Parcel.obtain().unmarshall(byteArrayOf(0, 0, 0, 1, 42), 0, 5) } + assertThrows(IllegalArgumentException::class.java) { Parcel.obtain().unmarshall(bytes, 0, bytes.size - 1) } } @Test