Skip to content

core: Unset device ctx if it has been destroyed - #1058

Closed
benzea wants to merge 1 commit into
libusb:masterfrom
benzea:benzea/fix-device-outliving-ctx
Closed

benzea wants to merge 1 commit into
libusb:masterfrom
benzea:benzea/fix-device-outliving-ctx

Conversation

@benzea

@benzea benzea commented Feb 4, 2022

Copy link
Copy Markdown

Devices can outlive their context in some cases (in particular with
python garbage collection). Guard against this happening by clearing the
ctx pointer so that it is not pointing to uninitialized memory.

See: https://bugzilla.redhat.com/show_bug.cgi?id=2050638

This is now happening because the debug output in libusb_unref_device was changed to use the device ctx.

Devices can outlive their context in some cases (in particular with
python garbage collection). Guard against this happening by clearing the
ctx pointer so that it is not pointing to uninitialized memory.
@mcuee mcuee added the core Related to common codes label Feb 5, 2022
@mcuee

mcuee commented Feb 5, 2022 •

Copy link
Copy Markdown
Member

I think the fix itself seems to be a quick fix to address the paticular issue, which may or may not be the right fix. Let's check with pyusb side.

@jonasmalacofilho
Please review the comments here in the original ticket here. Thanks.
https://bugzilla.redhat.com/show_bug.cgi?id=2050638

However, that said. I am thinking that the python USB wrapper might be a bit stupid. i.e. it should probably keep the USB context open while if one is still referencing a device.

Or libusb1 should be doing that, but I don't think it has refcounting for the USB context.

@hjelmn

hjelmn commented Feb 5, 2022

Copy link
Copy Markdown
Member

This usage seems wrong to me. The context should not be destroyed with outstanding devices. I mean we should be better but i think the Python library is doing it wrong. Thoughts?

@jonasmalacofilho

jonasmalacofilho commented Feb 5, 2022 •

Copy link
Copy Markdown
Contributor

I can only reproduce it with PyUSB 1.0.2, which is considerably outdated by now (released in 2017). In particular, it lacks pyusb/pyusb@f644ea7a6b7e, which fixed an issue around cleanup.

# file: repro.py

import usb

devices = list(usb.core.find(find_all=True))
print(f"Found {len(devices)} USB devices")

# make the failure more obvious and reliable
del(devices)
$ python -m venv v102
$ v102/bin/pip install pyusb==1.0.2
$ v102/bin/python repro.py
Found 14 USB devices
libusb: debug [libusb_unref_device] destroy device 4.1
[2]    21475 segmentation fault (core dumped)  v102/bin/python repro.py

(It would have helped if the Fedora bug report mentioned the PyUSB version and showed the contents of playground.py).

PyUSB 1.1.0 (from 2020) and later already don't result in a segfault:

$ python -m venv v110
$ v110/bin/pip install pyusb==1.1.0
$ v110/bin/python repro.py
Found 14 USB devices
$ python -m venv vmaster
$ vmaster/bin/pip install git+https://github.com/pyusb/pyusb@master
$ vmaster/bin/python repro.py
Found 14 USB devices

That said, the debug output from LibUSB still shows the call to libusb_exit() being before calls to libusb_unref_devive():

$ LIBUSB_DEBUG=4 vmaster/bin/python repro.py
[timestamp] [threadID] facility level [function call] <message>
--------------------------------------------------------------------------------
[ 0.000008] [0000554e] libusb: debug [libusb_init] libusb v1.0.25.11692
[ 0.000015] [0000554e] libusb: debug [usbi_add_event_source] add fd 3 events 1
[ 0.000017] [0000554e] libusb: debug [usbi_io_init] using timer for timeouts
[ 0.000018] [0000554e] libusb: debug [usbi_add_event_source] add fd 4 events 1
[ 0.000021] [0000554e] libusb: debug [get_kernel_version] reported kernel version is 5.16.5-arch1-1
[ 0.000028] [0000554e] libusb: debug [op_init] found usbfs at /dev/bus/usb
[ 0.000029] [0000554e] libusb: debug [op_init] max iso packet length is (likely) 98304 bytes
[ 0.000032] [0000554e] libusb: debug [op_init] sysfs is available
[ 0.000229] [00005551] libusb: debug [linux_udev_event_thread_main] udev event thread entering
[ 0.002767] [0000554e] libusb: debug [linux_get_device_address] getting address for device: usb1 detached: 0
[ 0.002771] [0000554e] libusb: debug [linux_get_device_address] scan usb1
[ 0.002782] [0000554e] libusb: debug [linux_get_device_address] bus=1 dev=1
[ 0.002783] [0000554e] libusb: debug [linux_enumerate_device] busnum 1 devaddr 1 session_id 257
[ 0.002785] [0000554e] libusb: debug [linux_enumerate_device] allocating new device for 1/1 (session 257)
[... corresponding calls to 12 other devices ...]
[ 0.003536] [0000554e] libusb: debug [linux_get_device_address] getting address for device: usb4 detached: 0
[ 0.003537] [0000554e] libusb: debug [linux_get_device_address] scan usb4
[ 0.003547] [0000554e] libusb: debug [linux_get_device_address] bus=4 dev=1
[ 0.003549] [0000554e] libusb: debug [linux_enumerate_device] busnum 4 devaddr 1 session_id 1025
[ 0.003550] [0000554e] libusb: debug [linux_enumerate_device] allocating new device for 4/1 (session 1025)
[ 0.003624] [0000554e] libusb: debug [libusb_get_device_list]  
[ 0.003649] [0000554e] libusb: debug [libusb_get_device_descriptor]  
[... 12 other calls to libusb_get_device_descriptor ...]
[ 0.003939] [0000554e] libusb: debug [libusb_get_device_descriptor]  
Found 14 USB devices
[ 0.004073] [0000554e] libusb: debug [libusb_exit]  
[ 0.004104] [00005551] libusb: debug [linux_udev_event_thread_main] udev event thread exiting
[ 0.004127] [0000554e] libusb: debug [libusb_unref_device] destroy device 4.1
[... 12 other calls to libusb_unref_device ...]
[ 0.004144] [0000554e] libusb: debug [libusb_unref_device] destroy device 1.1
[ 0.004146] [0000554e] libusb: debug [usbi_remove_event_source] remove fd 4
[ 0.004149] [0000554e] libusb: debug [usbi_remove_event_source] remove fd 3

So while the documentation of libusb_exit() only states that previously opened devices must be closed (but not necessarily all device reference counts must be zero),1 it seems there's still something to be fixed in PyUSB, even though it doesn't cause obvious errors right now. What do you all think?

Finally, note that unlike with PyUSB 1.0.2, more recent versions don't result in warnings like:

[ 0.004335] [000053b2] libusb: warning [libusb_exit] device 4.1 still referenced

P.S. I also tested (and am the maintainer of) liquidctl: no issues with LibUSB 1.0.25 and latest PyUSB.

Footnotes

  1. https://libusb.sourceforge.io/api-1.0/group__libusb__lib.html#gadc174de608932caeb2fc15d94fa0844d ↩

@diabolo38

Copy link
Copy Markdown

also feel like context should not be e destroyed with outstanding devices.
In such case who is to blaim ? i feel it's the application trying to close/Exit lib while it as still active device
to me the proposed fix is not so bad all at least it try to make a bad situation goes even worst but it can hide a bad usage to user

@mcuee

mcuee commented Feb 5, 2022

Copy link
Copy Markdown
Member

@benzea What is the version of pyusb you are using? Please also post the contents of "playground.py". Thanks.

@mcuee

mcuee commented Feb 5, 2022

Copy link
Copy Markdown
Member

@tormodvolden

tormodvolden commented Feb 5, 2022 •

Copy link
Copy Markdown
Contributor

The Fedora bug was reported on FC36 and they have only pyusb 1.0.2. https://src.fedoraproject.org/rpms/pyusb

EDIT: I read the version wrongly at first.

@benzea

benzea commented Feb 5, 2022

Copy link
Copy Markdown
Author

Well, it happens on F35 too, which is why I cancelled the F35/F34 updates. I reproduced this with python3-pyusb-1.0.2-13.fc35.noarch.

Reproduction is trivial, I just do:

#! /usr/bin/env python3
import usb
dev = usb.core.find()
del dev

Interestingly, the del is important, but I have no idea how that triggers the issue. Maybe some reference cycle is cleaned up in the wrong order or so, it is kind of odd.

Either way, while I think that pyusb is doing something wrong (as mentioned in the downstream bug), there is also a libusb bug that is fixed by this patch.

@benzea

benzea commented Feb 5, 2022 •

Copy link
Copy Markdown
Author

Right, I should have read the other comments properly first. So pyusb is already fixed then, and Fedora should really update it.

Filed: https://bugzilla.redhat.com/show_bug.cgi?id=2051231

@mcuee

mcuee commented Feb 6, 2022

Copy link
Copy Markdown
Member

Great, thanks to the clear analysis from Jonas, the issue is clear now. Fedora is using pyusb 1.0.2 and they should upgrade pyusb version in this case.

@hjelmn @tormodvolden
Now the question is that if we should take this pull request or not. I tend to think it is fine to accept the patch.

@benzea

benzea commented Feb 6, 2022

Copy link
Copy Markdown
Author

@hjelmn @tormodvolden Now the question is that if we should take this pull request or not. I tend to think it is fine to accept the patch.

I know I am repeating myself. But I really think this patch is necessary. Without it, libusb will correctly warn about the misuse of the API, and then continues to crash anyway.

@hjelmn

hjelmn commented Feb 6, 2022 •

Copy link
Copy Markdown
Member

I kind of like how the change exposed these usage issues. I would even support an explicit abort() if using the interface wrong. That said, since this is a behavior change I had no real issue with adding this.

@jonasmalacofilho

Copy link
Copy Markdown
Contributor

@hjelmn

I kind of like how the change exposed these usage issues.

I think @benzea is correct that what exposed the issue in 1.0.25 was libusb_unref_device() starting to use the device ctx when logging that a device is being destroyed.

Specifically, the global context was used before 6cae9c6 ("core: update usbi_dbg to take the context as an argument").


Can you please confirm whether the restriction on libusb_unref_device() being called before libusb_exit() (on the same context) is indeed intended?

I ask because it isn't documented in either function, and getting Python finalizers to execute in a particular order is tricky. So part of me doesn't want to open that particular can of worms... at the same time, I think this restriction makes sense, since one cannot try to open a libsub_device() once its context is gone.

Anyway, if this restriction is intended, then PyUSB is still not behaving correctly, even if we haven't been able to reproduce the segfault with its latest versions.

@hjelmn

hjelmn commented Feb 6, 2022

Copy link
Copy Markdown
Member

In my understanding libusb_unref_device should not be called after the context is destroyed. The warning in libusb_exit is intended to aid in debugging an erroneous program. From what I can tell this was never properly documented so I consider it a documentation bug.

The fact that it worked before 1.0.25 is more dumb luck than anything. It could have been broken at any time (or could have never broken for that matter) so pyusb is in error here. They should always destroy all libusb objects before the context is destroyed. This usage only became apparent due to some work to rethink the global context. In this particular case wanted to ensure that usbi_dbg honors the debug level of the context the device belonged to (which it was not).

@hjelmn

hjelmn commented Feb 6, 2022 •

Copy link
Copy Markdown
Member

All that said. I am leaning toward taking this because accessing the destroyed context is not great. pyusb went a long time without the usage bug being flagged so i may want to make the warning unconditional to avoid future issues if we take this.

@benzea

benzea commented Feb 7, 2022

Copy link
Copy Markdown
Author

I ask because it isn't documented in either function, and getting Python finalizers to execute in a particular order is tricky.

Yeah, the main thing pointing to this is the usbi_warn call. Though, I guess it is also kind of implied by the context not being reference counted.

On the pyusb side, couldn't the device object just store a reference to the context? My thinking is that this should enforce destruction in the correct order (assuming there is no circular reference pointing from the context to the device).

@hjelmn

hjelmn commented Feb 8, 2022

Copy link
Copy Markdown
Member

Yeah. I will work on the changes to the warning tomorrow. Once that is done I will merge this.

@jonasmalacofilho

Copy link
Copy Markdown
Contributor

@benzea,

Yeah, the main thing pointing to this is the usbi_warn call. Though, I guess it is also kind of implied by the context not being reference counted.

Note that the device %d.%d still referenced warning is only issued for the PyUSB version that segfaults, so it doesn't catch all cases where the unref_device()/exit() order is incorrect.

On the pyusb side, couldn't the device object just store a reference to the context? My thinking is that this should enforce destruction in the correct order (assuming there is no circular reference pointing from the context to the device).

We already do that, don't we? Besides that, what we could try to do is not have a persistent reference to the context in the module, but that would mean using a different context for every PyUSB find() call, which I don't think is a good idea. And even then, we would still need finalizers to issue the calls to libusb_unref_device()/libusb_exit(), which could reintroduce ordering issues anyway.

I opened pyusb/pyusb#409 for this, and we should continue this part of the discussion there. I'll look into it when I have some time...

P.S. I had to resolve similar problem in cython-hidapi a couple of months ago... the end result looks surprisingly simple (since we don't see all the failed attempts that preceded it).

@mcuee

mcuee commented Feb 18, 2022 •

Copy link
Copy Markdown
Member

@soerengrunewald
Please help to elaborate why #1058 breaks mtp. Thanks.

@tormodvolden

Copy link
Copy Markdown
Contributor

Yeah. I will work on the changes to the warning tomorrow. Once that is done I will merge this.

@hjelmn Is this still valid?

tormodvolden pushed a commit to tormodvolden/libusb that referenced this pull request Mar 15, 2022
Devices can outlive their context in some cases (in particular with
python garbage collection). Guard against this happening by clearing the
ctx pointer so that it is not pointing to uninitialized memory.

Closes libusb#1058
@tormodvolden

Copy link
Copy Markdown
Contributor

I would like to merge this and #1073 (and prepare 1.0.26-RC1 soon) so that it gets more testing. We still have to rework the warning in libusb_exit.

@mcuee

mcuee commented Mar 15, 2022

Copy link
Copy Markdown
Member

I would like to merge this and #1073 (and prepare 1.0.26-RC1 soon) so that it gets more testing. We still have to rework the warning in libusb_exit.

That will be great.

@benzea

benzea commented Mar 15, 2022

Copy link
Copy Markdown
Author

I would like to merge this and #1073 (and prepare 1.0.26-RC1 soon) so that it gets more testing.

Great!

Please tell me if I should reshuffle the various MRs. Maybe overkill, but I also quickly opened #1090 so that all functional changes in #1078 have their own separate MR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core Related to common codes Documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants