Skip to content

Workarround to avoid the SEGFAULT case on libusb#12

Merged
antoniovazquezblanco merged 1 commit intousbbluetooth:mainfrom
sha0coder:main
Dec 16, 2025
Merged

Workarround to avoid the SEGFAULT case on libusb#12
antoniovazquezblanco merged 1 commit intousbbluetooth:mainfrom
sha0coder:main

Conversation

@sha0coder
Copy link
Contributor

@sha0coder sha0coder commented Dec 9, 2025

When the python program termiantes, it calls SuperSocket.__del__ and this triggers UsbBluetoothSocket.close() that closes the usbbluetooth controller.

The usbbluetooth controller shouldn't be closed from a __del__ because it calls is_kernel_driver_active
If pyusb's is_kernel_driver_active is called from a destructor will send a bad handle to libusb and will segfault always.

usbbluetooth cannot detect if it's being called from a destructor, and not calling is_kernel_driver_active will fix it but should be called in normal situations.
pyusb is a simply ctypes wrapper, it's like calling direclty the c libusb.

Having said that the best way is disabling SuperSocket.__del__ by overriding it on UsbBluetoothSocket.

These scripts triggers the segfault:

Trigger1.py:

import usbbluetooth

def get_controller():
    devices = usbbluetooth.list_controllers()
    return devices[0]

class Trigger:
    def __del__(self):
        c = get_controller()
        c.close() # segfault
        
t = Trigger()

Trigger2.py:

import usb

class Trigger:

    def __init__(self):
        devs = devs = usb.core.find(find_all=True)
        for dev in devs:
            self._dev = dev
            break

    def __del__(self):
        self._dev.is_kernel_driver_active(0) # segfault

t = Trigger()

@antoniovazquezblanco
Copy link
Member

Hey! Many thanks for looking into this @sha0coder!

It makes sense to me... It would be better if we could close the socket before the delete but there seems to be no intuitive way to do so...

Thanks for taking the time. Merging!

@antoniovazquezblanco antoniovazquezblanco merged commit 563a0f6 into usbbluetooth:main Dec 16, 2025
11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants