UsbDeviceConnection requestWait() native crash

北慕城南 提交于 2019-12-03 22:30:50

This is a bug in the Android Platform and has given me headaches for the past 2 weeks. In the end the only solution for my project to work was to create a patch.

First the root of the problem: in class UsbRequest.java : http://androidxref.com/4.4.4_r1/xref/frameworks/base/core/java/android/hardware/usb/UsbRequest.java

in line 136 they are determining the direction of the endpoint:

boolean out = (mEndpoint.getDirection() == UsbConstants.USB_DIR_OUT);

and the out boolean is send as a parameter to the native functions in lines 139 and 141. if we follow the native_queue_direct method in the native counterpart UsbRequest.cpp : http://androidxref.com/4.4.4_r1/xref/frameworks/base/core/jni/android_hardware_UsbRequest.cpp

we can see that the out boolean once received by the function is not used !

The out boolean must be used because only the read (IN) endpoint (the one that we will do requestWait() on it) should allocate memory - request->client_data = (void *)env->NewGlobalRef(thiz); - that will be returned by the requestWait() method. By not using it the out boolean when we queue data on the OUT (write) endpoint it will also allocate memory and replace the memory allocated by the IN endpoint. Then when requestWait() returnes it will try to return the memory block allocated by the IN endpoint which is now different and it crashes with : JNI ERROR (app bug): accessed stale global reference 0x7ad003fa (index 254 in a table of size 254).

The fix:

android.hardware.usb.UsbDeviceConnection udc = usbManager.openDevice(device);
com.fixed.usb.UsbDeviceConnection usbDeviceConnection = new com.fixed.usb.UsbDeviceConnection(device, udc.getFileDescriptor());

After we open the device, we use the returned UsbDeviceConnection to get the device's file descriptor and we'll construct a new (fixed) UsbDeviceConnection. Then we use this as the regular UsbDeviceConnection.

You can download the patch from the issue's page.

This issue can happen when you try to open device and connection again (when everything of that was already done)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!