Repository navigation
Closed
Labels
Description
libusb_unref_device() is not supposed to be called after the context (for that device) has been destroyed with libsub_exit().
However, with
# file: repro.py
import usb
devices = list(usb.core.find(find_all=True))
print(f"Found {len(devices)} USB devices")
del(devices)and current PyUSB HEAD:
$ 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
Related: libusb/libusb#1058
Activity
benzea commentedon Feb 8, 2022
Wait, no. This is completely fine. I added a
printafter thedeland added some debugging into context finalizer. What you are seeing here seems to belibusb_unref_devicedone internally bylibusb_exitas it is caching the discovered devices.i.e.:
and
benzea commentedon Feb 8, 2022
Said differently, with f644ea7 the situation should be fine:
i.e. we have the following references:
Deviceinstance ->_ResourceManager_ResourceManager->_Deviceand_LibUSBinstanceSo, we have a reference cycle containing the modules and
_LibUSBinstance. However, we do not have a reference cycle for theDeviceinstance and the associated_ResourceManagerand_Deviceinstances. As such, the garbage collection of_Deviceshould be guaranteed to be before_LibUSB.It is all a little bit indirect. I suppose, one could make this explicit by changing the
_ResourceManagerfinalizer to ensure that the underlying_Devicereference is dropped before the backend reference is.jonasmalacofilho commentedon Feb 8, 2022
Oh, you're right. And the backtrace from those last
libusb_unref_device()calls is:And by adding a trace to
_Device._finalize_object:we can also see that we are indeed calling the finalizers (i.e. we're not leaving LibUSB to clean up for ourselves):
I'll check if there's anything else that could use a trace as well, add them all, and close this.
I'll take a look at this, thanks.
jonasmalacofilho commentedon Feb 8, 2022
Yes, I see that both
libusb1andcoremodules reference themselves. But I just realized I don't see the reference cycle with_LibUSByou mentioned. Can you explain?It's indeed a bit indirect, but that's necessary because of the various backends, and PyUSB even supports user-provided ones.
What change to
_ResourceManagerwould you suggest to ensure thatdevis dropped beforebackend?benzea commentedon Feb 8, 2022
Sure, the way I see it, we have:
_LibUSBinstance ->_LibUSBclass_LibUSBclass -> libusb1 backend module_lib_objectvariable ->_LibUSBinstancebenzea commentedon Feb 8, 2022
Hmm, I thought that adding the following should be enough:
benzea commentedon Feb 8, 2022
Hrm, to be honest, not sure. In cpython this works, but I suppose that e.g. pypy may not behave in the same way. And, I suspect we may not be able to just call
self.dev.finalizebecause there may be further references.jonasmalacofilho commentedon Feb 8, 2022
I don't think that counts, as the class doesn't reference the module itself, other things living in it (alongside the class itself).
While that initially looked good to me, it doesn't seem to actually do much.
If we remove the
del(devices)from our repros and also add a trace to this new_ResourceManager.__del__(), we see that it can sometimes be executed after bothdevandbackendhave been finalized.Therefore the order in which the reference counts to
devandbackendis decremented doesn't really matter.(I suspected that could happen because the collection will be done some unknown time after the reference counts are decremented. And AFAIK it's the garbage collector that calls
__del__()).[-]Rework finalization of LibUSB (1.x) devices and context[/-][+]Review finalization of LibUSB (1.x) devices and context[/+]libusb1: add trace to _Device finalizer
jonasmalacofilho commentedon Feb 8, 2022
Well, the_LibUSBrefers to the module though its__module__field, so you're correct.But if that's the only reason that_LibUSBis dropped after_Device, thenlibusb_exit()might not be called at all in interpreters that are less tolerant to cycles than CPython.Nevermind,
__module__is a string, obviously... btw, I was looking at the output fromgc.get_referrents(_LibUSB).benzea commentedon Feb 8, 2022
Hah, I fell for exactly that myself!
I fear I am a bit out of knowledge about python garbage collection and object destruction at this point :-/
My naive approach would be to create a chain like
Device -> _ResourceManager -> _Device -> _LibUSB, and then hopefully python cannot release the objects in the wrong order. So, maybe it is enough to attach a reference to_LibUSBto the_Deviceinstance?jonasmalacofilho commentedon Feb 9, 2022
Good to know I'm not the only one : )
I think what allows the code to work currently (under both CPython and PyPy, as I've just confirmed) is:
_Deviceinstances can't outlive the_Deviceclass;_Deviceclass can't outlive thelibusb1module;_LibUSBsingleton instance lives as long as thelibusbmodule.I also think that if
_Device._finalize_objectgets to run (finalizers aren't guaranteed to run, especially in some cases when the interpreter is exiting), then that counts to the_Deviceclass still being there, and thus the_LibUSBinstance as well.So I'm going to close this as it seems everything is working properly, both practically and in theory.
Thanks for all the help!