Skip to content

Review finalization of LibUSB (1.x) devices and context #409

Closed

Description

@jonasmalacofilho

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

  1. benzea commented on Feb 8, 2022

    @benzea

    Wait, no. This is completely fine. I added a print after the del and added some debugging into context finalizer. What you are seeing here seems to be libusb_unref_device done internally by libusb_exit as it is caching the discovered devices.

    [benjamin@ben-x1c7 pyusb]$ LIBUSB_DEBUG=4 python3 ./test.py 
    [timestamp] [threadID] facility level [function call] <message>
    --------------------------------------------------------------------------------
    [ 0.000009] [00003cc2] libusb: debug [libusb_init] libusb v1.0.25.11692
    ...
    Found 15 USB devices
    devices deleted
    finalize backend: c_void_p(94152616332288)
    [ 0.004286] [00003cc2] libusb: debug [libusb_exit]  
    [ 0.004300] [00003cc4] libusb: debug [linux_udev_event_thread_main] udev event thread exiting
    [ 0.004353] [00003cc2] libusb: debug [libusb_unref_device] destroy device 4.1
    [ 0.004357] [00003cc2] libusb: debug [libusb_unref_device] destroy device 3.1
    [ 0.004359] [00003cc2] libusb: debug [libusb_unref_device] destroy device 2.3
    [ 0.004361] [00003cc2] libusb: debug [libusb_unref_device] destroy device 2.2
    [ 0.004363] [00003cc2] libusb: debug [libusb_unref_device] destroy device 2.1
    [ 0.004365] [00003cc2] libusb: debug [libusb_unref_device] destroy device 1.7
    [ 0.004368] [00003cc2] libusb: debug [libusb_unref_device] destroy device 1.5
    [ 0.004370] [00003cc2] libusb: debug [libusb_unref_device] destroy device 1.3
    [ 0.004372] [00003cc2] libusb: debug [libusb_unref_device] destroy device 1.10
    [ 0.004374] [00003cc2] libusb: debug [libusb_unref_device] destroy device 1.8
    [ 0.004376] [00003cc2] libusb: debug [libusb_unref_device] destroy device 1.6
    [ 0.004378] [00003cc2] libusb: debug [libusb_unref_device] destroy device 1.4
    [ 0.004380] [00003cc2] libusb: debug [libusb_unref_device] destroy device 1.2
    [ 0.004382] [00003cc2] libusb: debug [libusb_unref_device] destroy device 1.9
    [ 0.004384] [00003cc2] libusb: debug [libusb_unref_device] destroy device 1.1
    [ 0.004386] [00003cc2] libusb: debug [usbi_remove_event_source] remove fd 4
    [ 0.004390] [00003cc2] libusb: debug [usbi_remove_event_source] remove fd 3
    libusb_exit done: c_void_p(94152616332288)
    

    i.e.:

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

    and

    diff --git a/usb/backend/libusb1.py b/usb/backend/libusb1.py
    index 6615d68..39c6c13 100644
    --- a/usb/backend/libusb1.py
    +++ b/usb/backend/libusb1.py
    @@ -718,8 +718,10 @@ class _LibUSB(usb.backend.IBackend):
     
         @methodtrace(_logger)
         def _finalize_object(self):
    +        print("finalize backend:", self.ctx)
             if self.ctx:
                 self.lib.libusb_exit(self.ctx)
    +        print("libusb_exit done:", self.ctx)
     
     
         @methodtrace(_logger)
    
  2. benzea commented on Feb 8, 2022

    @benzea

    Said differently, with f644ea7 the situation should be fine:

    i.e. we have the following references:

    • Device instance -> _ResourceManager
    • _ResourceManager -> _Device and _LibUSB instance
    • All of these keep the modules alive (via their classes)

    So, we have a reference cycle containing the modules and _LibUSB instance. However, we do not have a reference cycle for the Device instance and the associated _ResourceManager and _Device instances. As such, the garbage collection of _Device should be guaranteed to be before _LibUSB.

    It is all a little bit indirect. I suppose, one could make this explicit by changing the _ResourceManager finalizer to ensure that the underlying _Device reference is dropped before the backend reference is.

  3. jonasmalacofilho commented on Feb 8, 2022

    @jonasmalacofilho
    MemberAuthor

    Wait, no. This is completely fine. I added a print after the del and added some debugging into context finalizer. What you are seeing here seems to be libusb_unref_device done internally by libusb_exit as it is caching the discovered devices.

    Oh, you're right. And the backtrace from those last libusb_unref_device() calls is:

    #0  libusb_unref_device (dev=0x5555556d4ce0) at /build/libusb/src/libusb-1.0.25/libusb/core.c:1180
    #1  0x00007ffff704d1d6 in usbi_hotplug_exit (ctx=ctx@entry=0x5555556cfba0) at /build/libusb/src/libusb-1.0.25/libusb/hotplug.c:208
    #2  0x00007ffff704f2b0 in usbi_hotplug_exit (ctx=0x5555556cfba0) at /build/libusb/src/libusb-1.0.25/libusb/hotplug.c:171
    #3  libusb_exit (ctx=0x5555556cfba0) at /build/libusb/src/libusb-1.0.25/libusb/core.c:2438
    [...]
    

    And by adding a trace to _Device._finalize_object:

     usb/backend/libusb1.py | 2 ++
     1 file changed, 2 insertions(+)
    
    diff --git a/usb/backend/libusb1.py b/usb/backend/libusb1.py
    index 6615d68b7800..c7306ada1227 100644
    --- a/usb/backend/libusb1.py
    +++ b/usb/backend/libusb1.py
    @@ -609,6 +609,8 @@ def _check(ret):
     class _Device(_objfinalizer.AutoFinalizedObject):
         def __init__(self, devid):
             self.devid = _lib.libusb_ref_device(devid)
    +
    +    @methodtrace(_logger)
         def _finalize_object(self):
             _lib.libusb_unref_device(self.devid)

    we can also see that we are indeed calling the finalizers (i.e. we're not leaving LibUSB to clean up for ourselves):

    PYUSB_DEBUG=debug vlocal/bin/python repro.py
    Using PyUSB v1.2.1.post18+g629943a1d73a.d20220208-editable
    2022-02-08 08:04:26,036 DEBUG:usb.backend.libusb1:_LibUSB.__init__(<CDLL 'libusb-1.0.so.0', handle 55e45e142e30 at 0x7fa8223ebbe0>)
    2022-02-08 08:04:26,040 INFO:usb.core:find(): using backend "usb.backend.libusb1"
    2022-02-08 08:04:26,040 DEBUG:usb.backend.libusb1:_LibUSB.enumerate_devices()
    2022-02-08 08:04:26,040 DEBUG:usb.backend.libusb1:_LibUSB.get_device_descriptor(<usb.backend.libusb1._Device object at 0x7fa8222e6110>)
    2022-02-08 08:04:26,040 DEBUG:usb.backend.libusb1:_LibUSB.get_device_descriptor(<usb.backend.libusb1._Device object at 0x7fa8222e6290>)
    2022-02-08 08:04:26,040 DEBUG:usb.backend.libusb1:_LibUSB.get_device_descriptor(<usb.backend.libusb1._Device object at 0x7fa8222e63b0>)
    2022-02-08 08:04:26,040 DEBUG:usb.backend.libusb1:_LibUSB.get_device_descriptor(<usb.backend.libusb1._Device object at 0x7fa8222e6500>)
    2022-02-08 08:04:26,040 DEBUG:usb.backend.libusb1:_LibUSB.get_device_descriptor(<usb.backend.libusb1._Device object at 0x7fa8222e6620>)
    2022-02-08 08:04:26,040 DEBUG:usb.backend.libusb1:_LibUSB.get_device_descriptor(<usb.backend.libusb1._Device object at 0x7fa8222e6770>)
    2022-02-08 08:04:26,040 DEBUG:usb.backend.libusb1:_LibUSB.get_device_descriptor(<usb.backend.libusb1._Device object at 0x7fa8222e68c0>)
    2022-02-08 08:04:26,040 DEBUG:usb.backend.libusb1:_LibUSB.get_device_descriptor(<usb.backend.libusb1._Device object at 0x7fa8222e69e0>)
    2022-02-08 08:04:26,040 DEBUG:usb.backend.libusb1:_LibUSB.get_device_descriptor(<usb.backend.libusb1._Device object at 0x7fa8222e6b00>)
    2022-02-08 08:04:26,040 DEBUG:usb.backend.libusb1:_LibUSB.get_device_descriptor(<usb.backend.libusb1._Device object at 0x7fa8222e6c20>)
    2022-02-08 08:04:26,040 DEBUG:usb.backend.libusb1:_LibUSB.get_device_descriptor(<usb.backend.libusb1._Device object at 0x7fa8222e6d70>)
    2022-02-08 08:04:26,040 DEBUG:usb.backend.libusb1:_LibUSB.get_device_descriptor(<usb.backend.libusb1._Device object at 0x7fa8222e6ec0>)
    2022-02-08 08:04:26,040 DEBUG:usb.backend.libusb1:_LibUSB.get_device_descriptor(<usb.backend.libusb1._Device object at 0x7fa8222e7010>)
    2022-02-08 08:04:26,040 DEBUG:usb.backend.libusb1:_LibUSB.get_device_descriptor(<usb.backend.libusb1._Device object at 0x7fa8222e7160>)
    Found 14 USB devices
    2022-02-08 08:04:26,040 DEBUG:usb.backend.libusb1:_Device._finalize_object()
    2022-02-08 08:04:26,040 DEBUG:usb.backend.libusb1:_Device._finalize_object()
    2022-02-08 08:04:26,040 DEBUG:usb.backend.libusb1:_Device._finalize_object()
    2022-02-08 08:04:26,041 DEBUG:usb.backend.libusb1:_Device._finalize_object()
    2022-02-08 08:04:26,041 DEBUG:usb.backend.libusb1:_Device._finalize_object()
    2022-02-08 08:04:26,041 DEBUG:usb.backend.libusb1:_Device._finalize_object()
    2022-02-08 08:04:26,041 DEBUG:usb.backend.libusb1:_Device._finalize_object()
    2022-02-08 08:04:26,041 DEBUG:usb.backend.libusb1:_Device._finalize_object()
    2022-02-08 08:04:26,041 DEBUG:usb.backend.libusb1:_Device._finalize_object()
    2022-02-08 08:04:26,041 DEBUG:usb.backend.libusb1:_Device._finalize_object()
    2022-02-08 08:04:26,041 DEBUG:usb.backend.libusb1:_Device._finalize_object()
    2022-02-08 08:04:26,041 DEBUG:usb.backend.libusb1:_Device._finalize_object()
    2022-02-08 08:04:26,041 DEBUG:usb.backend.libusb1:_Device._finalize_object()
    2022-02-08 08:04:26,041 DEBUG:usb.backend.libusb1:_Device._finalize_object()
    2022-02-08 08:04:26,041 DEBUG:usb.backend.libusb1:_LibUSB._finalize_object()
    

    I'll check if there's anything else that could use a trace as well, add them all, and close this.


    It is all a little bit indirect. I suppose, one could make this explicit by changing the _ResourceManager finalizer to ensure that the underlying _Device reference is dropped before the backend reference is.

    I'll take a look at this, thanks.

  4. jonasmalacofilho commented on Feb 8, 2022

    @jonasmalacofilho
    MemberAuthor

    So, we have a reference cycle containing the modules and _LibUSB instance

    Yes, I see that both libusb1 and core modules reference themselves. But I just realized I don't see the reference cycle with _LibUSB you mentioned. Can you explain?


    It is all a little bit indirect. I suppose, one could make this explicit by changing the _ResourceManager finalizer to ensure that the underlying _Device reference is dropped before the backend reference is.

    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 _ResourceManager would you suggest to ensure that dev is dropped before backend?

  5. benzea commented on Feb 8, 2022

    @benzea

    Yes, I see that both libusb1 and core modules reference themselves. But I just realized I don't see the reference cycle with _LibUSB you mentioned. Can you explain?

    Sure, the way I see it, we have:

    • _LibUSB instance -> _LibUSB class
    • _LibUSB class -> libusb1 backend module
    • libusb1 backend module _lib_object variable -> _LibUSB instance
  6. benzea commented on Feb 8, 2022

    @benzea

    What change to _ResourceManager would you suggest to ensure that dev is dropped before backend?

    Hmm, I thought that adding the following should be enough:

        def __del__(self):
            del self.dev
            del self.backend
    
  7. benzea commented on Feb 8, 2022

    @benzea

    What change to _ResourceManager would you suggest to ensure that dev is dropped before backend?

    Hmm, I thought that adding the following should be enough:

        def __del__(self):
            del self.dev
            del self.backend
    

    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.finalize because there may be further references.

  8. jonasmalacofilho commented on Feb 8, 2022

    @jonasmalacofilho
    MemberAuthor
    • _LibUSB class -> libusb1 backend module

    I don't think that counts, as the class doesn't reference the module itself, other things living in it (alongside the class itself).


    Hmm, I thought that adding the following should be enough: [...]

    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 both dev and backend have been finalized.

    $ PYUSB_DEBUG=debug vlocal/bin/python repro.py
    Using PyUSB v1.2.1.post18+g629943a1d73a.d20220208-editable
    [ ... ]
    Found 14 USB devices
    2022-02-08 13:00:47,829 DEBUG:usb.backend.libusb1:_Device._finalize_object()
    2022-02-08 13:00:47,829 DEBUG:usb.backend.libusb1:_Device._finalize_object()
    2022-02-08 13:00:47,829 DEBUG:usb.backend.libusb1:_Device._finalize_object()
    2022-02-08 13:00:47,829 DEBUG:usb.backend.libusb1:_Device._finalize_object()
    2022-02-08 13:00:47,830 DEBUG:usb.backend.libusb1:_Device._finalize_object()
    2022-02-08 13:00:47,830 DEBUG:usb.backend.libusb1:_Device._finalize_object()
    2022-02-08 13:00:47,830 DEBUG:usb.backend.libusb1:_Device._finalize_object()
    2022-02-08 13:00:47,830 DEBUG:usb.backend.libusb1:_Device._finalize_object()
    2022-02-08 13:00:47,830 DEBUG:usb.backend.libusb1:_Device._finalize_object()
    2022-02-08 13:00:47,830 DEBUG:usb.backend.libusb1:_Device._finalize_object()
    2022-02-08 13:00:47,830 DEBUG:usb.backend.libusb1:_Device._finalize_object()
    2022-02-08 13:00:47,830 DEBUG:usb.backend.libusb1:_Device._finalize_object()
    2022-02-08 13:00:47,830 DEBUG:usb.backend.libusb1:_Device._finalize_object()
    2022-02-08 13:00:47,830 DEBUG:usb.backend.libusb1:_Device._finalize_object()
    2022-02-08 13:00:47,830 DEBUG:usb.backend.libusb1:_LibUSB._finalize_object()
    2022-02-08 13:00:47,831 DEBUG:usb.core:running _ResourceManager.__del__()
    2022-02-08 13:00:47,831 DEBUG:usb.core:running _ResourceManager.__del__()
    2022-02-08 13:00:47,831 DEBUG:usb.core:running _ResourceManager.__del__()
    2022-02-08 13:00:47,831 DEBUG:usb.core:running _ResourceManager.__del__()
    2022-02-08 13:00:47,831 DEBUG:usb.core:running _ResourceManager.__del__()
    2022-02-08 13:00:47,831 DEBUG:usb.core:running _ResourceManager.__del__()
    2022-02-08 13:00:47,831 DEBUG:usb.core:running _ResourceManager.__del__()
    2022-02-08 13:00:47,831 DEBUG:usb.core:running _ResourceManager.__del__()
    2022-02-08 13:00:47,831 DEBUG:usb.core:running _ResourceManager.__del__()
    2022-02-08 13:00:47,831 DEBUG:usb.core:running _ResourceManager.__del__()
    2022-02-08 13:00:47,831 DEBUG:usb.core:running _ResourceManager.__del__()
    2022-02-08 13:00:47,831 DEBUG:usb.core:running _ResourceManager.__del__()
    2022-02-08 13:00:47,831 DEBUG:usb.core:running _ResourceManager.__del__()
    2022-02-08 13:00:47,831 DEBUG:usb.core:running _ResourceManager.__del__()
    

    Therefore the order in which the reference counts to dev and backend is 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__()).

  9. changed the title [-]Rework finalization of LibUSB (1.x) devices and context[/-] [+]Review finalization of LibUSB (1.x) devices and context[/+] on Feb 8, 2022
  10. jonasmalacofilho commented on Feb 8, 2022

    @jonasmalacofilho
    MemberAuthor
    • _LibUSB class -> libusb1 backend module

    I don't think that counts, as the class doesn't reference the module itself, other things living in it (alongside the class itself).

    Well, the _LibUSB refers to the module though its __module__ field, so you're correct.

    But if that's the only reason that _LibUSB is dropped after _Device, then libusb_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 from gc.get_referrents(_LibUSB).

  11. benzea commented on Feb 8, 2022

    @benzea

    Nevermind, module is a string, obviously...

    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 _LibUSB to the _Device instance?

  12. jonasmalacofilho commented on Feb 9, 2022

    @jonasmalacofilho
    MemberAuthor

    Hah, I fell for exactly that myself!

    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:

    • _Device instances can't outlive the _Device class;
    • the _Device class can't outlive the libusb1 module;
    • and the _LibUSB singleton instance lives as long as the libusb module.

    I also think that if _Device._finalize_object gets to run (finalizers aren't guaranteed to run, especially in some cases when the interpreter is exiting), then that counts to the _Device class still being there, and thus the _LibUSB instance 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!

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions