Notes from building Lunille

HIServices read my AXObserver's context pointer as a notification name

On 18 November a test build of Lunille 1.3.0 died after 26 minutes, on an unrecognized selector: -[AXListener length].

AXListener is my class. It's the object I pass as the context pointer, the refcon, when I call AXObserverAddNotification, so my callback knows whom to tell. length is a message you send to a CFString. Somewhere inside HIServices, the framework behind the Accessibility API, my context had ended up where a notification name should be.

Why the observer had its own thread

macOS shows Live Activities as small ovals in the menu bar, and Lunille reads where they are so the notch can make room for them. To know where they are, it follows MenuBarAgent, the process that draws the right side of the menu bar on macOS 27, with an AXObserver for four notifications: kAXCreatedNotification, kAXUIElementDestroyedNotification, kAXLayoutChangedNotification and kAXWindowCreatedNotification.

MenuBarAgent also passes on notifications about other apps' status items. A browser's menus coming and going make about one a second while the browser is in front. I didn't want those to wake the main thread, so the observer's run loop source lived on a thread of its own, Lunille.MenuBarOvals, where the callback drops anything that isn't from MenuBarAgent's pid.

This was the setup before the fix, trimmed:

// ...
let listener = AXListener(pid: pid, owner: self)
let context = Unmanaged.passRetained(listener).toOpaque()
let added = Self.notifications.filter {
    AXObserverAddNotification(observer, element, $0 as CFString, context) == .success
}
// ...
AXListenerThread.shared.add(observer)

add runs CFRunLoopAddSource on the listener thread through CFRunLoopPerformBlock and wakes it, so the source joined that run loop right away. Tearing down took the source off the thread and released the context there. It never called AXObserverRemoveNotification.

What HIServices does with a registration

This section is my reading of a closed framework on macOS 27.2, worked out in lldb.

When you add a notification on an application element, HIServices finishes the job in a block on the main queue. That block notes the name and the context in the observer, and registers them with every other process whose views the application shows. MenuBarAgent shows a lot of them: other apps' status items and the Live Activities' renderers.

MenuBarAgent answers each registration by telling the observer about those processes. HIServices handles that answer on the thread the observer's run loop source is on, and it reads the same notes the main queue is writing, without a lock. It counts them, then copies them into arrays of that size, the contexts' array just below the names'. If the main queue adds a note between the count and the copy, the extra context spills into the names.

With the source on another thread, the main queue's writes and the listener thread's reads meet in the milliseconds after each registration. My code also opened that window far more often than it needed to. Lunille took MenuBarAgent for restarted whenever the list of running apps came back without it, and while another app quits, that list can miss MenuBarAgent for a moment. So Lunille dropped its observer at nearly every app quit and built a new one at the next launch, four fresh registrations each time. On 18 November the read that lost the race came from an app launching.

One crash in about 36,000 cycles

To reproduce it, I wrote a command-line tool that compiles the app's real observer file next to a small driver. It never launches Lunille. Given MenuBarAgent's pid, it drops an observer and makes a new one every 50 ms for 180 seconds (both defaults), first the old way and then through the fixed class, each in its own process. The old way is the setup above, line for line. The callback context is a plain Swift class, as in the app, so a failure looks the same. An optional second process shows and hides a status item every 200 ms. Each time, MenuBarAgent tells every observer about the processes it shows views for, as it does when an app launches.

Over 18 and 19 November, the old way crashed once in about 36,000 cycles. The tool's only crash report still on disk came 29 seconds into a run. Its crashing thread, without the abort frames above and the dispatch frames below, has no frame of mine:

libswiftCore    -[_TtCs12_SwiftObject doesNotRecognizeSelector:]
CoreFoundation  ___forwarding___
CoreFoundation  _CF_forwarding_prep_0
HIServices      _AXObserverAddNotification
HIServices      __processObserverForRemoteProcessNotifications_block_invoke
libdispatch     _dispatch_call_block_and_release

The selector still sitting in x23 is length. That thread is a dispatch worker, while the listener thread sits idle in mach_msg. I think the copy happens on the listener thread and this block later registers the copied names with another process, but I haven't traced that link. When the process died, 100 of its 102 threads were inside that same HIServices block, 80 of them waiting on the lock CoreFoundation takes to log the error. I don't know why there were so many.

At those odds a run that survives proves very little, so the stress tool can't be the proof.

The order, in lldb

A second script attaches lldb to the tool. These are its breakpoints, minus one that marks each step and the Python callbacks that log the thread and the time:

breakpoint set -n _XXMIGPostNotification
breakpoint set -r "AXObserverAddNotificationAndCheckRemote_block_invoke$"
breakpoint set -r "AXObserverRemoveNotificationAndCheckRemote_block_invoke$"
breakpoint set -n CFRunLoopRemoveSource

The two block invocations are the main queue writing and removing notes. _XXMIGPostNotification is HIServices reading them on the observer's thread. To tell which observer a block belongs to, the callback starts from x0, the block itself. On macOS 27.2 the observer is at +0x20 in the block, and the observer's run loop source at +0x18 in the observer.

The tool makes three observers each way, 1.5 seconds apart. The old way gets a read between the main-queue adds, which is the crash's window. The fixed class only gets reads once every note is written, and it takes the source off its thread before removing anything. The script also checks an observer that is made and dropped in the same main-queue turn: its registrations should be noted and removed, and never read.

The fix

The fix changes the order of the calls. Notifications are added and removed on the main thread. The run loop source joins the listener thread only after the main queue has run what HIServices queued for the registrations, and leaves it before any notification is removed. The observer, element, names and context are kept 10 more seconds, past HIServices' default 6 second messaging timeout.

The first part is one block on the main queue, queued after the AXObserverAddNotification calls, so it runs behind HIServices' own blocks. listen() is what adds the source on the listener thread:

// Behind what HIServices has just queued on the main queue for these registrations.
DispatchQueue.main.async {
    MainActor.assumeIsolated { self.listen() }
}

Teardown goes the other way round. thread.perform is CFRunLoopPerformBlock on the listener thread, so it runs in turn with the callbacks:

// ...
thread.perform {
    if listening { CFRunLoopRemoveSource(CFRunLoopGetCurrent(), source, .defaultMode) }
    DispatchQueue.main.async {
        for name in names { AXObserverRemoveNotification(observer, element, name) }
        DispatchQueue.main.asyncAfter(deadline: .now() + Self.grace) {
            withExtendedLifetime((observer, element, names)) {}
            if let context = UnsafeMutableRawPointer(bitPattern: context) {
                Unmanaged<AnyObject>.fromOpaque(context).release()
            }
        }
    }
}

I also cut the churn. Before believing the app list, Lunille now checks kill(pid, 0) on the MenuBarAgent it follows, and Accessibility has to read as off for 3 seconds before the observer is dropped.

If your AXObserver listens off the main thread

Add the notifications on the main thread. Add the run loop source to your own thread from a block you queue on the main queue after those calls, not straight away. To stop, take the source off that thread first, on that thread. Then remove the notifications on the main thread, and keep the observer, the element and your context alive for a while after that. I use 10 seconds.

Moving the AXObserverAddNotification calls to your own thread doesn't help, because HIServices' half of the work still runs on the main queue. Make observers as rarely as you can, too: every new one is a fresh set of registrations.

I think the simplest way out is to keep the source on the main run loop, where HIServices' writes and reads run on the same thread. I moved mine off to keep other apps' traffic away from the main thread.

What I haven't checked

I've only looked at this on macOS 27.2, and the offsets in the lldb script are for that version. The fix doesn't depend on them. If you've run into this, I'd like to hear about it.


I ran into this while building Lunille, a notch app for macOS.