Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 887aa66d authored by Ytai Ben-tsvi's avatar Ytai Ben-tsvi Committed by Gerrit Code Review
Browse files

Merge changes from topic "hidl-memory-java"

* changes:
  Add HidlMemoryUtil
  Add parceling support for HIDL memory in Java
parents afb2c9e9 a736d1c1
Loading
Loading
Loading
Loading
+4 −0
Original line number Diff line number Diff line
@@ -816,11 +816,13 @@ java_library {
    srcs: [
        "core/java/android/os/HidlSupport.java",
        "core/java/android/annotation/IntDef.java",
        "core/java/android/annotation/IntRange.java",
        "core/java/android/annotation/NonNull.java",
        "core/java/android/annotation/Nullable.java",
        "core/java/android/annotation/SystemApi.java",
        "core/java/android/annotation/TestApi.java",
        "core/java/android/annotation/UnsupportedAppUsage.java",
        "core/java/android/os/HidlMemory.java",
        "core/java/android/os/HwBinder.java",
        "core/java/android/os/HwBlob.java",
        "core/java/android/os/HwParcel.java",
@@ -1358,8 +1360,10 @@ droidstubs {
    srcs: [
        "core/java/android/os/HidlSupport.java",
        "core/java/android/annotation/IntDef.java",
        "core/java/android/annotation/IntRange.java",
        "core/java/android/annotation/NonNull.java",
        "core/java/android/annotation/SystemApi.java",
        "core/java/android/os/HidlMemory.java",
        "core/java/android/os/HwBinder.java",
        "core/java/android/os/HwBlob.java",
        "core/java/android/os/HwParcel.java",
+16 −0
Original line number Diff line number Diff line
@@ -5246,6 +5246,17 @@ package android.os {
    method @NonNull public static java.io.File getVendorDirectory();
  }
  public class HidlMemory implements java.io.Closeable {
    ctor public HidlMemory(@NonNull String, @IntRange(from=0) long, @Nullable android.os.NativeHandle);
    method public void close() throws java.io.IOException;
    method @NonNull public android.os.HidlMemory dup() throws java.io.IOException;
    method protected void finalize();
    method @Nullable public android.os.NativeHandle getHandle();
    method @NonNull public String getName();
    method public long getSize();
    method @NonNull public android.os.NativeHandle releaseHandle();
  }
  public class HidlSupport {
    method public static boolean deepEquals(Object, Object);
    method public static int deepHashCode(Object);
@@ -5276,6 +5287,7 @@ package android.os {
    method public final void copyToInt8Array(long, byte[], int);
    method public final boolean getBool(long);
    method public final double getDouble(long);
    method public final long getFieldHandle(long);
    method public final float getFloat(long);
    method public final short getInt16(long);
    method public final int getInt32(long);
@@ -5290,6 +5302,7 @@ package android.os {
    method public final void putDoubleArray(long, double[]);
    method public final void putFloat(long, float);
    method public final void putFloatArray(long, float[]);
    method public final void putHidlMemory(long, @NonNull android.os.HidlMemory);
    method public final void putInt16(long, short);
    method public final void putInt16Array(long, short[]);
    method public final void putInt32(long, int);
@@ -5318,9 +5331,11 @@ package android.os {
    method public final double readDouble();
    method public final java.util.ArrayList<java.lang.Double> readDoubleVector();
    method public final android.os.HwBlob readEmbeddedBuffer(long, long, long, boolean);
    method @NonNull @Nullable public final android.os.HidlMemory readEmbeddedHidlMemory(long, long, long);
    method @Nullable public final android.os.NativeHandle readEmbeddedNativeHandle(long, long);
    method public final float readFloat();
    method public final java.util.ArrayList<java.lang.Float> readFloatVector();
    method @NonNull public final android.os.HidlMemory readHidlMemory();
    method public final short readInt16();
    method public final java.util.ArrayList<java.lang.Short> readInt16Vector();
    method public final int readInt32();
@@ -5345,6 +5360,7 @@ package android.os {
    method public final void writeDoubleVector(java.util.ArrayList<java.lang.Double>);
    method public final void writeFloat(float);
    method public final void writeFloatVector(java.util.ArrayList<java.lang.Float>);
    method public final void writeHidlMemory(@NonNull android.os.HidlMemory);
    method public final void writeInt16(short);
    method public final void writeInt16Vector(java.util.ArrayList<java.lang.Short>);
    method public final void writeInt32(int);
+16 −0
Original line number Diff line number Diff line
@@ -1724,6 +1724,17 @@ package android.os {
    method public static boolean contains(java.io.File, java.io.File);
  }

  public class HidlMemory implements java.io.Closeable {
    ctor public HidlMemory(@NonNull String, @IntRange(from=0) long, @Nullable android.os.NativeHandle);
    method public void close() throws java.io.IOException;
    method @NonNull public android.os.HidlMemory dup() throws java.io.IOException;
    method protected void finalize();
    method @Nullable public android.os.NativeHandle getHandle();
    method @NonNull public String getName();
    method public long getSize();
    method @NonNull public android.os.NativeHandle releaseHandle();
  }

  public abstract class HwBinder implements android.os.IHwBinder {
    ctor public HwBinder();
    method public static final void configureRpcThreadpool(long, boolean);
@@ -1747,6 +1758,7 @@ package android.os {
    method public final void copyToInt8Array(long, byte[], int);
    method public final boolean getBool(long);
    method public final double getDouble(long);
    method public final long getFieldHandle(long);
    method public final float getFloat(long);
    method public final short getInt16(long);
    method public final int getInt32(long);
@@ -1761,6 +1773,7 @@ package android.os {
    method public final void putDoubleArray(long, double[]);
    method public final void putFloat(long, float);
    method public final void putFloatArray(long, float[]);
    method public final void putHidlMemory(long, @NonNull android.os.HidlMemory);
    method public final void putInt16(long, short);
    method public final void putInt16Array(long, short[]);
    method public final void putInt32(long, int);
@@ -1789,9 +1802,11 @@ package android.os {
    method public final double readDouble();
    method public final java.util.ArrayList<java.lang.Double> readDoubleVector();
    method public final android.os.HwBlob readEmbeddedBuffer(long, long, long, boolean);
    method @NonNull @Nullable public final android.os.HidlMemory readEmbeddedHidlMemory(long, long, long);
    method @Nullable public final android.os.NativeHandle readEmbeddedNativeHandle(long, long);
    method public final float readFloat();
    method public final java.util.ArrayList<java.lang.Float> readFloatVector();
    method @NonNull public final android.os.HidlMemory readHidlMemory();
    method public final short readInt16();
    method public final java.util.ArrayList<java.lang.Short> readInt16Vector();
    method public final int readInt32();
@@ -1816,6 +1831,7 @@ package android.os {
    method public final void writeDoubleVector(java.util.ArrayList<java.lang.Double>);
    method public final void writeFloat(float);
    method public final void writeFloatVector(java.util.ArrayList<java.lang.Float>);
    method public final void writeHidlMemory(@NonNull android.os.HidlMemory);
    method public final void writeInt16(short);
    method public final void writeInt16Vector(java.util.ArrayList<java.lang.Short>);
    method public final void writeInt32(int);
+141 −0
Original line number Diff line number Diff line
/*
 * Copyright (C) 2019 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 android.annotation.IntRange;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemApi;
import android.annotation.TestApi;

import java.io.Closeable;
import java.io.IOException;

/**
 * An abstract representation of a memory block, as representing by the HIDL system.
 *
 * The block is defined by a {name, size, handle} tuple, where the name is used to determine how to
 * interpret the handle. The underlying handle is assumed to be owned by this instance and will be
 * closed as soon as {@link #close()} is called on this instance, or this instance has been
 * finalized (the latter supports using it in a shared manner without having to worry about who owns
 * this instance, the former is more efficient resource-wise and is recommended for most use-cases).
 * Note, however, that ownership of the handle does not necessarily imply ownership of the
 * underlying file descriptors - the underlying handle may or may not own them. If you want the
 * underlying handle to outlive this instance, call {@link #releaseHandle()} to obtain the handle
 * and detach the ownership relationship.
 *
 * @hide
 */
@SystemApi
@TestApi
public class HidlMemory implements Closeable {
    private final @NonNull String mName;
    private final long mSize;
    private @Nullable NativeHandle mHandle;
    private long mNativeContext;  // For use of native code.

    /**
     * Constructor.
     *
     * @param name      The name of the IMapper service used to resolve the handle (e.g. "ashmem").
     * @param size      The (non-negative) size in bytes of the memory block.
     * @param handle    The handle. May be null. This instance will own the handle and will close it
     *                  as soon as {@link #close()} is called or the object is destroyed. This, this
     *                  handle instance should generally not be shared with other clients.
     */
    public HidlMemory(@NonNull String name, @IntRange(from = 0) long size,
            @Nullable NativeHandle handle) {
        mName = name;
        mSize = size;
        mHandle = handle;
    }

    /**
     * Create a copy of this instance, where the underlying handle (and its file descriptors) have
     * been duplicated.
     */
    @NonNull
    public HidlMemory dup() throws IOException {
        return new HidlMemory(mName, mSize, mHandle != null ? mHandle.dup() : null);
    }

    /**
     * Close the underlying native handle. No-op if handle is null or has been released using {@link
     * #releaseHandle()}.
     */
    @Override
    public void close() throws IOException {
        if (mHandle != null) {
            mHandle.close();
        }
    }

    /**
     * Disowns the underlying handle and returns it. This object becomes invalid.
     *
     * @return The underlying handle.
     */
    @NonNull
    public NativeHandle releaseHandle() {
        NativeHandle handle = mHandle;
        mHandle = null;
        return handle;
    }

    /**
     * Gets the name, which represents how the handle is to be interpreted.
     *
     * @return The name.
     */
    @NonNull
    public String getName() {
        return mName;
    }

    /**
     * Gets the size of the block, in bytes.
     *
     * @return The size.
     */
    public long getSize() {
        return mSize;
    }

    /**
     * Gets a native handle. The actual interpretation depends on the name and is implementation
     * defined.
     *
     * @return The native handle.
     */
    @Nullable
    public NativeHandle getHandle() {
        return mHandle;
    }

    @Override
    protected void finalize() {
        try {
            close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            nativeFinalize();
        }
    }

    private native void nativeFinalize();
}
+215 −0
Original line number Diff line number Diff line
/*
 * Copyright (C) 2019 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 android.system.OsConstants.MAP_SHARED;
import static android.system.OsConstants.PROT_READ;

import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SuppressLint;
import android.annotation.SystemApi;
import android.annotation.TestApi;
import android.system.ErrnoException;
import android.system.Os;
import android.util.Log;

import com.android.internal.util.Preconditions;

import java.nio.ByteBuffer;
import java.nio.DirectByteBuffer;
import java.util.ArrayList;
import java.util.List;

/**
 * Provides utilities for dealing with HidlMemory.
 *
 * @hide
 */
public final class HidlMemoryUtil {
    static private final String TAG = "HidlMemoryUtil";

    private HidlMemoryUtil() {
    }

    /**
     * Copies a byte-array into a new Ashmem region and return it as HidlMemory.
     * The returned instance owns the underlying file descriptors, and the client should generally
     * call close on it when no longer in use (or otherwise, when the object gets destroyed it will
     * be closed).
     *
     * @param input The input byte array.
     * @return A HidlMemory instance, containing a copy of the input.
     */
    public static @NonNull
    HidlMemory byteArrayToHidlMemory(@NonNull byte[] input) {
        return byteArrayToHidlMemory(input, null);
    }

    /**
     * Copies a byte-array into a new Ashmem region and return it as HidlMemory.
     * The returned instance owns the underlying file descriptors, and the client should generally
     * call close on it when no longer in use (or otherwise, when the object gets destroyed it will
     * be closed).
     *
     * @param input The input byte array.
     * @param name  An optional name for the ashmem region.
     * @return A HidlMemory instance, containing a copy of the input.
     */
    public static @NonNull
    HidlMemory byteArrayToHidlMemory(@NonNull byte[] input, @Nullable String name) {
        Preconditions.checkNotNull(input);

        if (input.length == 0) {
            return new HidlMemory("ashmem", 0, null);
        }

        try {
            SharedMemory shmem = SharedMemory.create(name != null ? name : "", input.length);
            ByteBuffer buffer = shmem.mapReadWrite();
            buffer.put(input);
            shmem.unmap(buffer);
            NativeHandle handle = new NativeHandle(shmem.getFileDescriptor(), true);
            return new HidlMemory("ashmem", input.length, handle);
        } catch (ErrnoException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Copies a byte list into a new Ashmem region and return it as HidlMemory.
     * The returned instance owns the underlying file descriptors, and the client should generally
     * call close on it when no longer in use (or otherwise, when the object gets destroyed it will
     * be closed).
     *
     * @param input The input byte list.
     * @return A HidlMemory instance, containing a copy of the input.
     */
    public static @NonNull
    HidlMemory byteListToHidlMemory(@NonNull List<Byte> input) {
        return byteListToHidlMemory(input, null);
    }

    /**
     * Copies a byte list into a new Ashmem region and return it as HidlMemory.
     * The returned instance owns the underlying file descriptors, and the client should generally
     * call close on it when no longer in use (or otherwise, when the object gets destroyed it will
     * be closed).
     *
     * @param input The input byte list.
     * @param name  An optional name for the ashmem region.
     * @return A HidlMemory instance, containing a copy of the input.
     */
    public static @NonNull
    HidlMemory byteListToHidlMemory(@NonNull List<Byte> input, @Nullable String name) {
        Preconditions.checkNotNull(input);

        if (input.isEmpty()) {
            return new HidlMemory("ashmem", 0, null);
        }

        try {
            SharedMemory shmem = SharedMemory.create(name != null ? name : "", input.size());
            ByteBuffer buffer = shmem.mapReadWrite();
            for (Byte b : input) {
                buffer.put(b);
            }
            shmem.unmap(buffer);
            NativeHandle handle = new NativeHandle(shmem.getFileDescriptor(), true);
            return new HidlMemory("ashmem", input.size(), handle);
        } catch (ErrnoException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Copies all data from a HidlMemory instance into a byte array.
     *
     * @param mem The HidlMemory instance. Must be of name "ashmem" and of size that doesn't exceed
     *            {@link Integer#MAX_VALUE}.
     * @return A byte array, containing a copy of the input.
     */
    public static @NonNull
    byte[] hidlMemoryToByteArray(@NonNull HidlMemory mem) {
        Preconditions.checkNotNull(mem);
        Preconditions.checkArgumentInRange(mem.getSize(), 0L, (long) Integer.MAX_VALUE,
                "Memory size");
        Preconditions.checkArgument(mem.getSize() == 0 || mem.getName().equals("ashmem"),
                "Unsupported memory type: %s", mem.getName());

        if (mem.getSize() == 0) {
            return new byte[0];
        }

        ByteBuffer buffer = getBuffer(mem);
        byte[] result = new byte[buffer.remaining()];
        buffer.get(result);
        return result;
    }

    /**
     * Copies all data from a HidlMemory instance into a byte list.
     *
     * @param mem The HidlMemory instance. Must be of name "ashmem" and of size that doesn't exceed
     *            {@link Integer#MAX_VALUE}.
     * @return A byte list, containing a copy of the input.
     */
    @SuppressLint("ConcreteCollection")
    public static @NonNull
    ArrayList<Byte> hidlMemoryToByteList(@NonNull HidlMemory mem) {
        Preconditions.checkNotNull(mem);
        Preconditions.checkArgumentInRange(mem.getSize(), 0L, (long) Integer.MAX_VALUE,
                "Memory size");
        Preconditions.checkArgument(mem.getSize() == 0 || mem.getName().equals("ashmem"),
                "Unsupported memory type: %s", mem.getName());

        if (mem.getSize() == 0) {
            return new ArrayList<>();
        }

        ByteBuffer buffer = getBuffer(mem);

        ArrayList<Byte> result = new ArrayList<>(buffer.remaining());
        while (buffer.hasRemaining()) {
            result.add(buffer.get());
        }
        return result;
    }

    private static ByteBuffer getBuffer(@NonNull HidlMemory mem) {
        try {
            final int size = (int) mem.getSize();

            if (size == 0) {
                return ByteBuffer.wrap(new byte[0]);
            }

            NativeHandle handle = mem.getHandle();

            final long address = Os.mmap(0, size, PROT_READ, MAP_SHARED, handle.getFileDescriptor(),
                    0);
            return new DirectByteBuffer(size, address, handle.getFileDescriptor(), () -> {
                try {
                    Os.munmap(address, size);
                } catch (ErrnoException e) {
                    Log.wtf(TAG, e);
                }
            }, true);
        } catch (ErrnoException e) {
            throw new RuntimeException(e);
        }
    }
}
Loading