Skip to content

Latest commit

Β 

History

History
381 lines (344 loc) Β· 26 KB

objc-ffi.md

File metadata and controls

381 lines (344 loc) Β· 26 KB
paths
crates/openlogi-desktop/src/platform/**
crates/openlogi-overlay/src/platform.rs
crates/openlogi-permissions/**
crates/openlogi-camera/**
crates/openlogi-agent/src/activity_macos.rs
crates/openlogi-agent/src/tray.rs
crates/openlogi-agent/src/status_item.rs
crates/openlogi-agent/src/lifecycle/armed_session.rs
crates/openlogi-agent-core/src/watchers/camera.rs
crates/openlogi-hook/src/macos.rs
crates/openlogi-hook/src/macos/**
crates/openlogi-inject/src/inject/macos.rs
crates/openlogi-inject/src/inject/macos/**
crates/openlogi-hid/src/permissions.rs

macOS native FFI

OpenLogi's Objective-C FFI runs on objc2 (0.6 / framework crates 0.3): Retained<T> smart pointers, typed framework objects, define_class! for subclasses. It is spread across crates rather than one directory β€” the GUI owns almost none of it. The whole workspace's native macOS surface is exactly these files; keep this table in sync when you add or move one:

File What it carries
openlogi-agent/src/activity_macos.rs the device-I/O gate's levels: the IOPMConnection powerd subscription (hand-declared SPI, see below) and the CGSessionCopyCurrentDictionary console read
openlogi-agent/src/status_item.rs safe objc2 wrappers over NSStatusItem / NSMenu / NSMenuItem
openlogi-agent/src/tray.rs the menu-bar semantics, MenuTarget + SessionTarget (define_class!), the Accessory NSApplication loop, the NSWorkspace session (fast-user-switch) notifications
openlogi-agent-core/src/watchers/camera.rs the CoreMediaIO "camera is running" property read
openlogi-camera/src/capture_macos.rs AVCaptureSession capture + the define_class! frame delegate, and the Camera TCC prompt
openlogi-camera/src/macos.rs AVCaptureDevice enumeration (class! + msg_send!)
openlogi-camera/src/uvc_macos.rs, .../uvc_macos/iokit.rs IOKit USB / UVC control transfers; every unsafe in the macOS UVC backend lives in iokit.rs
openlogi-desktop/src/platform/registration/macos.rs SMAppService registration of the agent's launchd service (the login-item side of the agent lifecycle; the GUI must own it β€” the API resolves the plist against the calling app's bundle)
openlogi-desktop/src/platform/os.rs NSProcessInfo OS version + the NSAppearance titlebar sync
openlogi-hid/src/permissions.rs IOHIDCheckAccess / IOHIDRequestAccess (the prompting half of Input Monitoring)
openlogi-hook/src/macos.rs the CGEventTap (on core-graphics, see below), the Accessibility-trust check/prompt, the off-tap NSWorkspace frontmost-app read, and the CGGetEventTapList enumeration
openlogi-hook/src/macos/foreground.rs the NSWorkspace activation observer, the NSRunningApplication conversion behind every frontmost-app read, and the Safari PID snapshot
openlogi-hook/src/macos/probe.rs Flow's pointer probe: the modifier read (CGEventSourceFlagsState), CGGetActiveDisplayList / CGDisplayBounds, and the CGWarpMouseCursorPosition warp
openlogi-hook/src/macos/secure_input.rs the Secure Event Input read: IsSecureEventInputEnabled (hand-declared, see below) and the kCGSSessionSecureInputPID entry of CGSessionCopyCurrentDictionary, named through foreground.rs's NSRunningApplication conversion
openlogi-hook/src/macos/sender.rs the HID sender-id lookup and the IOKit registry walk that resolves it to a device
openlogi-inject/src/inject/macos.rs CGEvent key and click synthesis, media-key NSEvents
openlogi-inject/src/inject/macos/scroll.rs CGEvent scroll synthesis, including the continuous-scroll phase fields, and the zoom retyping of wheel events while Accessibility Zoom's scroll modifiers are held (+[NSEvent modifierFlags] and the com.apple.universalaccess defaults)
openlogi-inject/src/inject/macos/ax.rs the shared AXUIElement attribute reads (CFRetained adoption of the Copy-rule out-pointer) and AXChildren iteration
openlogi-inject/src/inject/macos/browser.rs Safari's toolbar-button navigation over ax.rs, and the off-thread NSWorkspace Safari validation
openlogi-inject/src/inject/macos/menu_shortcut.rs the hidden probe NSMenu AppKit remaps for the keyboard layout, and pressing the frontmost app's matching menu item through AX
openlogi-inject/src/inject/macos/{app_services,dock,symbolic_hotkey}.rs the dlopen'd private SPIs: CoreDockSendNotification and the CGS symbolic-hotkey trio
openlogi-inject/src/inject/macos/keyboard_layout.rs the active keyboard layout's uchr data (Text Input Source Services, read on the main thread) and UCKeyTranslate over it
openlogi-inject/src/inject/macos/main_thread.rs the bounded hand-off of main-thread work from the action worker to the main queue (dispatch2)
openlogi-inject/src/inject/macos/virtual_keyboard/device.rs the IOHIDUserDevice virtual keyboard that key synthesis types through: its creation (which needs the com.apple.developer.hid.virtual.device entitlement) and its timestamped input reports. The report state in virtual_keyboard.rs above it is safe code
openlogi-overlay/src/platform.rs the Actions Ring helper's window policy: accessory activation, a non-activating panel that a click does not make key, the NSEvent global click-away monitor (block2), and CGGetActiveDisplayList / CGDisplayBounds
openlogi-permissions/src/macos.rs non-prompting permission reads + System-Settings deep links; +[CBManager authorization] via an AnyClass lookup

Every rule below binds all of them, whichever crate they live in.

Spawning the agent under its own macOS TCC identity (so its Accessibility / Input-Monitoring grants aren't attributed to the GUI, issue #214) lives in the external disclaim crate β€” posix_spawn + the private responsibility_spawnattrs_setdisclaim, not ObjC. openlogi-desktop/src/services/ipc/launch.rs's spawn_agent uses it; there is no in-tree FFI for it. Likewise, installed-application discovery and icon rendering for per-app profiles live in the external appcatalog crate (NSWorkspace + NSBitmapImageRep there, not here); openlogi-desktop/src/platform/app_icon.rs only wraps its PNG bytes into a gpui::Image. The privacy-grant change notifications β€” the com.apple.accessibility.api distributed notification and tccd's com.apple.tcc.access.changed Darwin notification β€” are observed by the external axwatch crate (CFNotificationCenter there, not here); openlogi-hook's grant::ProbeCue and openlogi-agent-core's grant watchers only consume its wakes. The System Settings drag guide for the agent's Accessibility and Input Monitoring grants lives in the external gpui-tcc crate (the NSWorkspace icon and frontmost-app reads, the CGWindowListCopyWindowInfo lookup of the System Settings window, and the overlay NSWindow level and NSVisualEffectView material are there, not here); openlogi-desktop/src/platform/permission_guide.rs only decides when to present it and which agent bundle it holds.

The rest of openlogi-desktop/src/platform/ (updater.rs, on gpui_updater, and permission_guide.rs, on gpui_tcc) carries no ObjC FFI β€” don't add any. Neither do openlogi-core's single_instance.rs (fs4 lock) or openlogi-agent's autostart/macos.rs (legacy-plist cleanup via std::fs).

Ownership: Retained<T>, never raw id

objc2 makes ownership a value: a Retained<T> releases exactly once on Drop. That is why this code can't reproduce issue #99 (a +1 NSString leaked on every 2 s tray refresh under the old cocoa/objc 0.x path).

  • Every string is NSString::from_str(s) β†’ a Retained<NSString> used as a borrowed temporary; it releases at the end of the statement. There is no nsstring() helper and no autorelease pool in the tray path β€” don't reintroduce either.
  • alloc/init/new/copy and the framework getters return Retained<T> / Option<Retained<T>>; you keep what you need and let Drop free it.
  • IOKit handles get the same treatment by hand in camera/src/uvc_macos/iokit.rs: IoObject, UsbInterface and SeizedDevice release on drop, and CoreFoundation values arrive as CFRetained. Never hand-balance a release.
  • Never call manual retain/release/autorelease, add raw cocoa/objc 0.x, or build a bespoke retain/release helper layer β€” that re-derives Retained<T>, worse. AX navigation adopts Copy-rule outputs as CFRetained and downcasts their runtime types before use.

Thread affinity is in the type system

  • NSMenu and NSMenuItem are #[thread_kind = MainThreadOnly] β†’ their Retained is !Send. NSStatusItem, NSImage, NSWorkspace are AnyThread (their Retained is still !Send, because a bare ObjC object is !Sync).
  • Constructing a MainThreadOnly object needs a MainThreadMarker (NSMenu::new(mtm), NSMenuItem::alloc(mtm), status_item.button(mtm)). Mutating an already-held Retained<NSMenuItem> (setTitle/setHidden) does not β€” possessing the !Send handle already proves you're on the main thread.
  • The mtm is obtained with MainThreadMarker::new() at each process's entry into AppKit β€” tray::run_app_loop in the agent, configure_application in the overlay, set_app_appearance in the GUI β€” and threaded down from there. Do not copy gpui's own NSThread.isMainThread + dispatch2 runtime-check idiom; we use the compile-time MainThreadMarker guarantee.
  • The tray needs no static and no thread_local: run_app_loop is -> !, so the status item, its MenuTarget, the SessionTarget and the powerd PowerConnection are bound as locals that outlive NSApplication::run(). They must stay bound β€” menu items reference their target weakly, the notification center does the same, and the power callback's param points into the connection's own Arc.
  • openlogi-camera's frame delegate is deliberately the opposite: an NSObject subclass with no thread_kind, because AVFoundation drives it on a background dispatch queue. Its one ivar is the owning session's Arc<FrameSink> (Send + Sync), so which session a frame belongs to is carried by ownership instead of process-global statics.

Privacy permissions (TCC): typed framework crates, never a hand-rolled extern

There is no general TCC API: Apple ships no public way to enumerate or request TCC state generically, and TCC.db is SIP-protected (reading it needs Full Disk Access). Crates that paper over this exist β€” permission-flow covers many services β€” but none fit here, for the reason in the rules below. Every permission is its own framework call, so "the TCC layer" is just this table:

Permission Crate Symbol Read / prompt
Accessibility objc2-application-services (HIServices + AXUIElement) AXIsProcessTrusted / AXIsProcessTrustedWithOptions both in openlogi-hook
Input Monitoring / Post Event objc2-io-kit (hidsystem) IOHIDCheckAccess / IOHIDRequestAccess read in openlogi-permissions, prompt in openlogi-hid
Bluetooth objc2 class lookup (see below) +[CBManager authorization] openlogi-permissions
Camera / microphone openlogi-camera (capture_macos.rs) +[AVCaptureDevice authorizationStatusForMediaType:] / requestAccessForMediaType: openlogi-camera
Screen Recording (unused) objc2-core-graphics CGPreflightScreenCaptureAccess β€”
Full Disk Access (unused) β€” no API; only a probe of a protected path β€”

Rules:

  • Never re-declare a permission API in a #[link(name = "…", kind = "framework")] extern "C" block and never hardcode its discriminants. The generated bindings are typed (IOHIDRequestType::ListenEvent, IOHIDAccessType::Granted), which is the workspace rule about wire values in another guise β€” a bare IOHIDCheckAccess(1) == 0 says nothing. IOHIDCheckAccess is a safe fn in objc2-io-kit; the AX pair is unsafe only because the options dictionary is untyped.
  • Add these crates with cargo add … --no-default-features --features <modules> (they are huge and gated per C header), then declare the version once in the workspace table with default-features = false and pick features per crate. Umbrella-feature trap: a leaf feature is not enough β€” AXUIElement also needs HIServices, or the symbols silently don't exist.
  • Checking never prompts; prompting belongs to whoever owns the resource. The agent raises the Accessibility prompt (it owns the tap) and calls IOHIDRequestAccess before opening HID; the GUI only reads status and deep-links to System Settings (open_pane, or the gpui-tcc drag guide, which opens the same pane and prompts nothing). Never call the prompting half from the GUI β€” the grant would land on the wrong code-signing identity (issue #214, see disclaim). This split is also why the ready-made permission crates don't fit: they model one app asking for itself. permission-flow additionally brings its own onboarding UI and links the Swift runtime into every downstream binary; macos-accessibility-client is a raw-extern wrapper where this file requires typed bindings.
  • TCC matches the full Designated Requirement, not the bundle ID (TN3127). Re-signing one bundle ID with a different kind of certificate leaves a record that can never match again, and toggling the checkbox does not rewrite the stored csreq. Not hypothetical: 0.6.24–0.6.26 shipped .dev bundle IDs signed with Developer ID (a344e22f), so a dev build of the same ID signed Apple Development meets a stale Developer ID requirement and tccd logs Failed to match existing code requirement. Suspect this first when a grant silently does nothing; tccutil reset <service> <bundle-id> clears the record, and a never-used bundle ID (or a fresh user/VM) is the only clean re-test.
  • Accessibility does not use tccd's generic consent sheet, so its logs read oddly: a request answers "Service kTCCServiceAccessibility does not allow prompting; returning Unknown" with DB Action:None. That describes the tccd preflight only β€” the flow continues into universalAccessAuthWarn, which makes its own TCCAccessCopyInformation call and pre-creates an unchecked row when no matching record exists. Reading DB Action:None as "nothing is ever written" is wrong, and it points debugging away from the stale-requirement case above.
  • CBCentralManager.authorization deliberately stays an AnyClass::get + msg_send! lookup rather than objc2-core-bluetooth: a missing class must degrade to Unknown, not panic.

Availability: the bindings do not know the deployment floor

The bundles declare macOS 13.0 (MACOSX_DEPLOYMENT_TARGET in the release workflows, LSMinimumSystemVersion in the Info.plist templates under crates/openlogi-desktop/bundle/), but objc2 generates every symbol a header declares regardless of its API_AVAILABLE(macos(N)), and Rust has no @available check. A function newer than the floor merely crashes when called on an older macOS; an extern static β€” SMAppServiceErrorDomain is macos(15.0) while the rest of SMAppService is 13.0 β€” is bound by dyld at load, so the whole binary is refused before main (#1279; 0.8.2 and 0.8.3 would not launch on 13 or 14). CI never runs on the floor release, so nothing catches it after the fact.

Before using a generated symbol, read its API_AVAILABLE in the SDK header (xcrun --show-sdk-path). If it is newer than the floor: for a string constant, spell the documented value out (the error domain above is the literal "SMAppServiceErrorDomain" on every release since 13); for a function, gate the call on the OS version and resolve it with dlsym β€” never import it strongly.

Raw extern blocks: only where no bindings exist

Typed framework crates are the default; a hand-written unsafe extern "C" block is allowed only for symbols objc2 has no bindings for, and it stays next to its single user. The current set, all deliberate:

  • openlogi-hook: CGEventCopyIOHIDEvent / IOHIDEventGetSenderID β€” undocumented, no bindings anywhere.
  • openlogi-hook/src/macos/secure_input.rs: IsSecureEventInputEnabled β€” Carbon HIToolbox, which objc2-carbon skips. It takes no arguments and has no precondition, so the block declares it safe fn.
  • openlogi-agent/src/activity_macos.rs: the IOPMConnection SPI (IOPMConnectionCreate / SetNotification / SetDispatchQueue / AcknowledgeEvent / Release / GetSystemCapabilities) β€” exported by IOKit since 10.6 and what pmset is built on, but declared only in Apple's open-source IOKitUser/pwr_mgt.subproj/IOPMLibPrivate.h, so objc2-io-kit cannot generate it. It is the only API that reports a DarkWake β†’ FullWake transition, which is why the gate needs it (see docs/DECISIONS.md).
  • openlogi-camera: the AVFoundation / CoreMedia / CoreVideo / CoreFoundation statics and functions its capture and enumeration paths need (AVMediaTypeVideo, CMSampleBufferGetImageBuffer, the CVPixelBuffer accessors, CFRunLoopRunInMode, dispatch_queue_create) β€” AVFoundation has no typed framework crate in the tree.
  • openlogi-agent-core/src/watchers/camera.rs: the CoreMediaIO property API β€” same reason.
  • openlogi-inject: the dlopen/dlsym-resolved private SPIs (CoreDockSendNotification, the CGS symbolic-hotkey trio), and in keyboard_layout.rs Text Input Source Services, LMGetKbdType, and UCKeyTranslate β€” objc2-carbon skips HIToolbox and objc2-core-services skips CarbonCore. UCKeyTranslate's lengths are UniCharCount, an unsigned long: usize, not u32.
  • the disclaim crate: responsibility_spawnattrs_setdisclaim (private SPI).

openlogi-camera's AVAuthorizationStatus integers remain on the migrate-when-touched list: they belong in objc2-av-foundation. Don't copy that pattern into new code.

The unsafe that remains (and the SAFETY rule)

unsafe_code is deny workspace-wide; every file that needs it opts in with a scoped #[expect(unsafe_code, reason = "…")], and every block does one operation under a SAFETY comment. Where it currently lives on macOS:

  • agent/status_item.rs β€” NSMenuItem::initWithTitle_action_keyEquivalent + setTarget: (raw selector; the target is a weak reference, which is why the tray keeps MenuTarget alive for the app's lifetime).
  • agent/activity_macos.rs β€” the IOPMConnection calls, its C callback (the param is the gate the PowerConnection keeps alive, and Drop drains the delivery queue before that Arc goes), and the CGSession dictionary cast.
  • agent/tray.rs β€” msg_send![super(this), init], the notification-center addObserver:selector:name:object:, and the NSWorkspaceSession*Notification name statics.
  • agent/lifecycle/armed_session.rs β€” SessionGetInfo (objc2-security, AuthSession) and sysctlbyname("kern.bootsessionuuid"): two out-pointer reads that identify the login session, so the dormancy gate can re-arm a crash respawn.
  • hook/macos.rs β€” the whole tap (Core Graphics / Core Foundation C APIs), AXIsProcessTrusted[WithOptions] with the two extern statics they need (kAXTrustedCheckOptionPrompt, kCFBooleanTrue), and the kern.sleeptime / kern.waketime sysctlbyname reads the lifecycle watchdog gates its gap discount on. Its module-wide #![expect(unsafe_code)] covers the three files below as well.
  • hook/macos/foreground.rs β€” the NSWorkspace activation-observer registration and typed notification payload, and NSString::to_str(pool) (the borrow is tied to the pool).
  • hook/macos/secure_input.rs β€” the CGSession dictionary cast.
  • hook/macos/sender.rs β€” the sender-id extern calls and the IOKit registry walk, including the Create-rule CFString / CFNumber wraps.
  • hook/macos/probe.rs β€” the CGGetActiveDisplayList out-pointers; the rest of Flow's pointer probe is safe objc2-core-graphics.
  • inject/macos/ax.rs β€” AX attribute-copy out-pointers and the unchecked AXChildren element type; each child is downcast before use.
  • inject/macos/browser.rs β€” typed AX creation, AXPress, and NSString::to_str(pool) for Safari validation.
  • inject/macos/menu_shortcut.rs β€” AX application creation and AXPress on the frontmost app's menu item. The probe menu itself is safe objc2-app-kit on the main thread: AppKit remaps an item for the keyboard layout only once the run loop has turned with it in the main menu, so the agent installs the probes before NSApplication::run, and workers read them through main_thread.rs.
  • inject/macos/keyboard_layout.rs β€” the input-source copy and property read, LMGetKbdType, and UCKeyTranslate over the copied uchr bytes. Text Input Source Services must run on the main thread (HIToolbox crashes when another thread reads the layout), so a worker hands the read to the main queue and waits a bounded time; only UCKeyTranslate, a pure function of the copied data, runs on the worker.
  • inject/macos/virtual_keyboard/device.rs β€” IOHIDUserDevice::with_properties, handle_report_with_time_stamp over the eight-byte report, mach2's mach_absolute_time for its timestamp, and the Send impl that lets the process-wide slot hold the device. The device is never scheduled on a dispatch queue, so it needs no Activate / Cancel pair: releasing it removes it.
  • permissions/macos.rs β€” the CoreBluetooth force-link and the CBManager class-method send. IOHIDCheckAccess needs none: objc2-io-kit exposes it as a safe fn, in openlogi-permissions and openlogi-hid alike.
  • overlay/platform.rs β€” NSEvent::removeMonitor and the CGGetActiveDisplayList / CGDisplayBounds pair.
  • desktop/platform/os.rs β€” reading AppKit's NSAppearanceName statics to set NSApp.appearance.
  • desktop/platform/registration/macos.rs β€” the SMAppService calls (all generated bindings are unsafe fns). Together with os.rs, the GUI's entire unsafe surface.
  • camera/{capture_macos,uvc_macos/iokit}.rs β€” the AVFoundation capture FFI and the IOKit USB plug-in; uvc_macos/iokit.rs deliberately concentrates every unsafe of the macOS UVC backend so the descriptor parser above it is ordinary safe code.

CGEventTap stays on core-graphics β€” on purpose

The event tap in openlogi-hook/src/macos.rs is not migrated. objc2-core-graphics 0.3 does expose CGEvent::tap_create/tap_enable (it's not an availability gap), but the tap's Accessibility-revoke freeze-hazard state machine (the 500 ms run-loop slice + self-disable on its own thread) is load-bearing and must stay byte-for-byte. Only the NSWorkspace frontmost-app read moved to objc2. Don't "modernize" the tap casually.

Off-main autorelease pools

Code on the main run loop needs no pool (Retained frees deterministically); code on a bare thread does, because the framework still autoreleases internal temporaries. The call sites that keep an explicit objc2::rc::autoreleasepool, and the only ones that should:

  • openlogi-hook's frontmost-application reads and activation observer β€” the watcher and notification callback may run on threads with no run loop, and to_str borrows its UTF-8 view from the pool (both the bundle id and the localized name). Registration and removal use the same boundary so AppKit's internal autoreleased temporaries are drained as well. The Secure Event Input app read names its app through the same conversion, on the secure-input watcher thread, under its own pool.
  • openlogi-inject's post_media_key β€” the hook/gesture dispatch threads, where both the NSEvent creation and the CGEvent getter autorelease temporaries.
  • openlogi-inject's ax_browser_navigate β€” the action worker, where to_str borrows the current frontmost app's bundle id while validating the captured Safari process.
  • openlogi-inject's menu-shortcut press β€” the action worker, where the NSWorkspace frontmost-app reads autorelease temporaries.
  • openlogi-inject's wheel-event zoom check β€” the scroll worker and hook threads, where the NSUserDefaults suite read autoreleases temporaries.
  • openlogi-camera's device enumeration β€” every AVCaptureDevice string is copied out before the pool drains, so no Retained<T> escapes it.

Dependencies

cocoa / objc 0.x are gone from every crate's direct deps (they remain in Cargo.lock only transitively via gpui β€” expected). Use cargo add for objc2 framework crates, then verify that Cargo.lock still carries one version-aligned gpui-pre stack and the workspace's pinned Kit release.

Every ObjC / Core-framework crate is declared once in the workspace table β€” objc2, objc2-app-kit, objc2-foundation, objc2-core-foundation, objc2-core-graphics, objc2-application-services, objc2-io-kit, objc2-service-management, objc2-security, block2, core-graphics, core-foundation. The header-gated ones carry default-features = false there, and each member inherits with workspace = true and adds only the feature modules it uses. A new one belongs in that table too, never inline in a member manifest: the unified version is what keeps the native framework types compatible across the app and GPUI. Trim a member's feature list when the code that needed it moves out.

Build & verify

The GUI crates need the real Xcode toolchain for gpui's Metal shader compile: DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer, SDKROOT=$(xcrun --show-sdk-path), xcbuild stripped from PATH. Behavioural checks (tray icon shows, Open/Quit fire, device rows update, the ring follows the cursor's display) need the running app. Confirm an FFI memory fix with leaks over a multi-minute session: the CFString/NSString count must stay flat (the empirical inverse of #99).