Skip to content

darwin: initialise the bluetooth managers in Enable instead of package init - #530

Draft
jbanyer wants to merge 1 commit into
tinygo-org:devfrom
jbanyer:darwin-lazy-managers
Draft

jbanyer wants to merge 1 commit into
tinygo-org:devfrom
jbanyer:darwin-lazy-managers

Conversation

@jbanyer

@jbanyer jbanyer commented Nov 17, 2026

Copy link
Copy Markdown

darwin: create CoreBluetooth managers in Enable, not at package init

DefaultAdapter on darwin creates its CBCentralManager and
CBPeripheralManager in a package-level initialiser, so any program that
imports tinygo.org/x/bluetooth starts CoreBluetooth before main runs,
whether or not it ever calls Enable().

Creating a manager triggers macOS's Bluetooth privacy check, which for a
command-line program applies to the terminal app that launched it. On macOS
27.2, run from a terminal without Bluetooth permission, the process is killed
with SIGABRT a moment after it starts. There's no Go panic or stack trace, and
the program can't detect or handle it. (On macOS 26.6 the same program gets a
permission prompt instead, and keeps running if access is denied.) We hit this
with a large program that uses BLE in one optional feature: it crashed on
startup on a developer's Mac even though that feature was turned off. It didn't
crash under lldb, where a different process is responsible for it.

This PR moves creating the managers into Enable(), so only programs that
actually use Bluetooth start CoreBluetooth. Reset() now clears the managers
instead of creating new ones; its doc already says that the following
Enable() creates fresh managers.

This matches the other backends, whose DefaultAdapter holds only Go state
and leaves all platform setup to Enable(): D-Bus on Linux, RoInitialize on
Windows, the SoftDevice on nRF, and so on.

Behaviour changes:

  • Programs that import the package but never call Enable() no longer touch
    CoreBluetooth.
  • Programs that call Enable() behave as before. The managers are created just
    before the delegate is set, and the existing comment about setting the
    delegate before checking the state still applies.
  • Calling other Adapter methods before Enable() was already documented as
    unsupported. Those methods now message a nil manager, which Objective-C
    treats as a no-op.

Tested:

  • go vet . on darwin and linux.
  • [TODO, confirm before submitting] On macOS: a program that imports the package without calling Enable() now
    starts from a terminal without Bluetooth permission, where it used to abort.

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.

1 participant