• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.hardware.usb;
18 
19 import android.annotation.Nullable;
20 import android.compat.annotation.UnsupportedAppUsage;
21 import android.os.Build;
22 import android.util.Log;
23 
24 import com.android.internal.util.Preconditions;
25 
26 import dalvik.system.CloseGuard;
27 
28 import java.nio.BufferOverflowException;
29 import java.nio.ByteBuffer;
30 import java.util.Objects;
31 
32 /**
33  * A class representing USB request packet.
34  * This can be used for both reading and writing data to or from a
35  * {@link android.hardware.usb.UsbDeviceConnection}.
36  * UsbRequests can be used to transfer data on bulk and interrupt endpoints.
37  * Requests on bulk endpoints can be sent synchronously via {@link UsbDeviceConnection#bulkTransfer}
38  * or asynchronously via {@link #queue} and {@link UsbDeviceConnection#requestWait}.
39  * Requests on interrupt endpoints are only send and received asynchronously.
40  *
41  * <p>Requests on endpoint zero are not supported by this class;
42  * use {@link UsbDeviceConnection#controlTransfer} for endpoint zero requests instead.
43  */
44 public class UsbRequest {
45 
46     private static final String TAG = "UsbRequest";
47 
48     // From drivers/usb/core/devio.c
49     static final int MAX_USBFS_BUFFER_SIZE = 16384;
50 
51     // used by the JNI code
52     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
53     private long mNativeContext;
54 
55     private UsbEndpoint mEndpoint;
56 
57     /** The buffer that is currently being read / written */
58     @UnsupportedAppUsage
59     private ByteBuffer mBuffer;
60 
61     /** The amount of data to read / write when using {@link #queue} */
62     @UnsupportedAppUsage
63     private int mLength;
64 
65     // for client use
66     private Object mClientData;
67 
68     // Prevent the connection from being finalized
69     private UsbDeviceConnection mConnection;
70 
71     /**
72      * Whether this buffer was {@link #queue(ByteBuffer) queued using the new behavior} or
73      * {@link #queue(ByteBuffer, int) queued using the deprecated behavior}.
74      */
75     private boolean mIsUsingNewQueue;
76 
77     /** Temporary buffer than might be used while buffer is enqueued */
78     private ByteBuffer mTempBuffer;
79 
80     private final CloseGuard mCloseGuard = CloseGuard.get();
81 
82     /**
83      * Lock for queue, enqueue and dequeue, so a queue operation can be finished by a dequeue
84      * operation on a different thread.
85      */
86     private final Object mLock = new Object();
87 
UsbRequest()88     public UsbRequest() {
89     }
90 
91     /**
92      * Initializes the request so it can read or write data on the given endpoint.
93      * Whether the request allows reading or writing depends on the direction of the endpoint.
94      *
95      * @param endpoint the endpoint to be used for this request.
96      * @return true if the request was successfully opened.
97      */
initialize(UsbDeviceConnection connection, UsbEndpoint endpoint)98     public boolean initialize(UsbDeviceConnection connection, UsbEndpoint endpoint) {
99         mEndpoint = endpoint;
100         mConnection = Objects.requireNonNull(connection, "connection");
101 
102         boolean wasInitialized = native_init(connection, endpoint.getAddress(),
103                 endpoint.getAttributes(), endpoint.getMaxPacketSize(), endpoint.getInterval());
104 
105         if (wasInitialized) {
106             mCloseGuard.open("close");
107         }
108 
109         return wasInitialized;
110     }
111 
112     /**
113      * Releases all resources related to this request.
114      */
close()115     public void close() {
116         if (mNativeContext != 0) {
117             mEndpoint = null;
118             mConnection = null;
119             native_close();
120             mCloseGuard.close();
121         }
122     }
123 
124     @Override
finalize()125     protected void finalize() throws Throwable {
126         try {
127             if (mCloseGuard != null) {
128                 mCloseGuard.warnIfOpen();
129             }
130 
131             close();
132         } finally {
133             super.finalize();
134         }
135     }
136 
137     /**
138      * Returns the endpoint for the request, or null if the request is not opened.
139      *
140      * @return the request's endpoint
141      */
getEndpoint()142     public UsbEndpoint getEndpoint() {
143         return mEndpoint;
144     }
145 
146     /**
147      * Returns the client data for the request.
148      * This can be used in conjunction with {@link #setClientData}
149      * to associate another object with this request, which can be useful for
150      * maintaining state between calls to {@link #queue} and
151      * {@link android.hardware.usb.UsbDeviceConnection#requestWait}
152      *
153      * @return the client data for the request
154      */
getClientData()155     public Object getClientData() {
156         return mClientData;
157     }
158 
159     /**
160      * Sets the client data for the request.
161      * This can be used in conjunction with {@link #getClientData}
162      * to associate another object with this request, which can be useful for
163      * maintaining state between calls to {@link #queue} and
164      * {@link android.hardware.usb.UsbDeviceConnection#requestWait}
165      *
166      * @param data the client data for the request
167      */
setClientData(Object data)168     public void setClientData(Object data) {
169         mClientData = data;
170     }
171 
172     /**
173      * Queues the request to send or receive data on its endpoint.
174      * <p>For OUT endpoints, the given buffer data will be sent on the endpoint. For IN endpoints,
175      * the endpoint will attempt to read the given number of bytes into the specified buffer. If the
176      * queueing operation is successful, return true. The result will be returned via
177      * {@link UsbDeviceConnection#requestWait}</p>
178      *
179      * @param buffer the buffer containing the bytes to write, or location to store the results of a
180      *               read. Position and array offset will be ignored and assumed to be 0. Limit and
181      *               capacity will be ignored. Once the request
182      *               {@link UsbDeviceConnection#requestWait() is processed} the position will be set
183      *               to the number of bytes read/written.
184      * @param length number of bytes to read or write. Before {@value Build.VERSION_CODES#P}, a
185      *               value larger than 16384 bytes would be truncated down to 16384. In API
186      *               {@value Build.VERSION_CODES#P} and after, any value of length is valid.
187      *
188      * @return true if the queueing operation succeeded
189      *
190      * @deprecated Use {@link #queue(ByteBuffer)} instead.
191      */
192     @Deprecated
queue(ByteBuffer buffer, int length)193     public boolean queue(ByteBuffer buffer, int length) {
194         boolean out = (mEndpoint.getDirection() == UsbConstants.USB_DIR_OUT);
195         boolean result;
196 
197         if (mConnection.getContext().getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.P
198                 && length > MAX_USBFS_BUFFER_SIZE) {
199             length = MAX_USBFS_BUFFER_SIZE;
200         }
201 
202         synchronized (mLock) {
203             // save our buffer for when the request has completed
204             mBuffer = buffer;
205             mLength = length;
206 
207             // Note: On a buffer slice we lost the capacity information about the underlying buffer,
208             // hence we cannot check if the access would be a data leak/memory corruption.
209 
210             if (buffer.isDirect()) {
211                 result = native_queue_direct(buffer, length, out);
212             } else if (buffer.hasArray()) {
213                 result = native_queue_array(buffer.array(), length, out);
214             } else {
215                 throw new IllegalArgumentException("buffer is not direct and has no array");
216             }
217             if (!result) {
218                 mBuffer = null;
219                 mLength = 0;
220             }
221         }
222 
223         return result;
224     }
225 
226     /**
227      * Queues the request to send or receive data on its endpoint.
228      *
229      * <p>For OUT endpoints, the remaining bytes of the buffer will be sent on the endpoint. For IN
230      * endpoints, the endpoint will attempt to fill the remaining bytes of the buffer. If the
231      * queueing operation is successful, return true. The result will be returned via
232      * {@link UsbDeviceConnection#requestWait}</p>
233      *
234      * @param buffer the buffer containing the bytes to send, or the buffer to fill. The state
235      *               of the buffer is undefined until the request is returned by
236      *               {@link UsbDeviceConnection#requestWait}. If the request failed the buffer
237      *               will be unchanged; if the request succeeded the position of the buffer is
238      *               incremented by the number of bytes sent/received. Before
239      *               {@value Build.VERSION_CODES#P}, a buffer of length larger than 16384 bytes
240      *               would throw IllegalArgumentException. In API {@value Build.VERSION_CODES#P}
241      *               and after, any size buffer is valid.
242      *
243      * @return true if the queueing operation succeeded
244      */
queue(@ullable ByteBuffer buffer)245     public boolean queue(@Nullable ByteBuffer buffer) {
246         // Request need to be initialized
247         Preconditions.checkState(mNativeContext != 0, "request is not initialized");
248 
249         // Request can not be currently queued
250         Preconditions.checkState(!mIsUsingNewQueue, "this request is currently queued");
251 
252         boolean isSend = (mEndpoint.getDirection() == UsbConstants.USB_DIR_OUT);
253         boolean wasQueued;
254 
255         synchronized (mLock) {
256             mBuffer = buffer;
257 
258             if (buffer == null) {
259                 // Null buffers enqueue empty USB requests which is supported
260                 mIsUsingNewQueue = true;
261                 wasQueued = native_queue(null, 0, 0);
262             } else {
263                 if (mConnection.getContext().getApplicationInfo().targetSdkVersion
264                         < Build.VERSION_CODES.P) {
265                     // Can only send/receive MAX_USBFS_BUFFER_SIZE bytes at once
266                     Preconditions.checkArgumentInRange(buffer.remaining(), 0, MAX_USBFS_BUFFER_SIZE,
267                             "number of remaining bytes");
268                 }
269 
270                 // Can not receive into read-only buffers.
271                 Preconditions.checkArgument(!(buffer.isReadOnly() && !isSend), "buffer can not be "
272                         + "read-only when receiving data");
273 
274                 if (!buffer.isDirect()) {
275                     mTempBuffer = ByteBuffer.allocateDirect(mBuffer.remaining());
276 
277                     if (isSend) {
278                         // Copy buffer into temporary buffer
279                         mBuffer.mark();
280                         mTempBuffer.put(mBuffer);
281                         mTempBuffer.flip();
282                         mBuffer.reset();
283                     }
284 
285                     // Send/Receive into the temp buffer instead
286                     buffer = mTempBuffer;
287                 }
288 
289                 mIsUsingNewQueue = true;
290                 wasQueued = native_queue(buffer, buffer.position(), buffer.remaining());
291             }
292         }
293 
294         if (!wasQueued) {
295             mIsUsingNewQueue = false;
296             mTempBuffer = null;
297             mBuffer = null;
298         }
299 
300         return wasQueued;
301     }
302 
dequeue(boolean useBufferOverflowInsteadOfIllegalArg)303     /* package */ void dequeue(boolean useBufferOverflowInsteadOfIllegalArg) {
304         boolean isSend = (mEndpoint.getDirection() == UsbConstants.USB_DIR_OUT);
305         int bytesTransferred;
306 
307         synchronized (mLock) {
308             if (mIsUsingNewQueue) {
309                 bytesTransferred = native_dequeue_direct();
310                 mIsUsingNewQueue = false;
311 
312                 if (mBuffer == null) {
313                     // Nothing to do
314                 } else if (mTempBuffer == null) {
315                     mBuffer.position(mBuffer.position() + bytesTransferred);
316                 } else {
317                     mTempBuffer.limit(bytesTransferred);
318 
319                     // The user might have modified mBuffer which might make put/position fail.
320                     // Changing the buffer while a request is in flight is not supported. Still,
321                     // make sure to free mTempBuffer correctly.
322                     try {
323                         if (isSend) {
324                             mBuffer.position(mBuffer.position() + bytesTransferred);
325                         } else {
326                             // Copy temp buffer back into original buffer
327                             mBuffer.put(mTempBuffer);
328                         }
329                     } finally {
330                         mTempBuffer = null;
331                     }
332                 }
333             } else {
334                 if (mBuffer.isDirect()) {
335                     bytesTransferred = native_dequeue_direct();
336                 } else {
337                     bytesTransferred = native_dequeue_array(mBuffer.array(), mLength, isSend);
338                 }
339                 if (bytesTransferred >= 0) {
340                     int bytesToStore = Math.min(bytesTransferred, mLength);
341                     try {
342                         mBuffer.position(bytesToStore);
343                     } catch (IllegalArgumentException e) {
344                         if (useBufferOverflowInsteadOfIllegalArg) {
345                             Log.e(TAG, "Buffer " + mBuffer + " does not have enough space to read "
346                                     + bytesToStore + " bytes", e);
347                             throw new BufferOverflowException();
348                         } else {
349                             throw e;
350                         }
351                     }
352                 }
353             }
354 
355             mBuffer = null;
356             mLength = 0;
357         }
358     }
359 
360     /**
361      * Cancels a pending queue operation.
362      *
363      * @return true if cancelling succeeded
364      */
cancel()365     public boolean cancel() {
366         if (mConnection == null) {
367             return false;
368         }
369 
370         return mConnection.cancelRequest(this);
371     }
372 
373     /**
374      * Cancels a pending queue operation (for use when the UsbDeviceConnection associated
375      * with this request is synchronized). This ensures we don't have a race where the
376      * device is closed and then the request is canceled which would lead to a
377      * use-after-free because the cancel operation uses the device connection
378      * information freed in the when UsbDeviceConnection is closed.<br/>
379      *
380      * This method assumes the connected is not closed while this method is executed.
381      *
382      * @return true if cancelling succeeded.
383      */
cancelIfOpen()384     /* package */ boolean cancelIfOpen() {
385         if (mNativeContext == 0 || (mConnection != null && !mConnection.isOpen())) {
386             Log.w(TAG,
387                     "Detected attempt to cancel a request on a connection which isn't open");
388             return false;
389         }
390         return native_cancel();
391     }
392 
native_init(UsbDeviceConnection connection, int ep_address, int ep_attributes, int ep_max_packet_size, int ep_interval)393     private native boolean native_init(UsbDeviceConnection connection, int ep_address,
394             int ep_attributes, int ep_max_packet_size, int ep_interval);
native_close()395     private native void native_close();
native_queue(ByteBuffer buffer, int offset, int length)396     private native boolean native_queue(ByteBuffer buffer, int offset, int length);
native_queue_array(byte[] buffer, int length, boolean out)397     private native boolean native_queue_array(byte[] buffer, int length, boolean out);
native_dequeue_array(byte[] buffer, int length, boolean out)398     private native int native_dequeue_array(byte[] buffer, int length, boolean out);
native_queue_direct(ByteBuffer buffer, int length, boolean out)399     private native boolean native_queue_direct(ByteBuffer buffer, int length, boolean out);
native_dequeue_direct()400     private native int native_dequeue_direct();
native_cancel()401     private native boolean native_cancel();
402 }
403