fix(darwin): copy screen id/name C strings and snapshot screen count atomically
Description
Fixes a hard crash (SIGSEGV in C.GoString) that occurs during display-reconfiguration event storms β typically when a Mac wakes from sleep, connects/disconnects a monitor, or changes resolution while a v3 app is running.
Crash observed (v3.0.0-alpha.97, macOS 26.5, arm64)
fatal error: fault
[signal SIGSEGV: segmentation violation code=0x2 addr=0x100000000 pc=...]
runtime.gostring(0x10000001b)
github.com/wailsapp/wails/v3/pkg/application._Cfunc_GoString
github.com/wailsapp/wails/v3/pkg/application.cScreenToScreen screen_darwin.go:185
github.com/wailsapp/wails/v3/pkg/application.(*macosApp).processAndCacheScreens
github.com/wailsapp/wails/v3/pkg/application.(*macosApp).run.func3
github.com/wailsapp/wails/v3/pkg/application.(*EventManager).handleApplicationEvent.func1
The app had been running ~12.5h and crashed on wake.
Root causes (two memory-safety issues in screen_darwin.go)
-
Dangling C strings.
processScreenstores the raw result of-[NSString UTF8String]into theScreenstruct:returnScreen.id = [[NSString stringWithFormat:@"%d", displayID] UTF8String]; returnScreen.name = [screen.localizedName UTF8String];That pointer is owned by the (autoreleased)
NSString. Go reads it later viaC.GoStringβ once the string is deallocated, the pointer dangles.0x10000001babove is exactly such a garbage pointer. -
Count/allocation race.
getAllScreens()mallocs the array from one[NSScreen screens]snapshot, whileprocessAndCacheScreensfetches the element count via a separateGetNumScreens()call. If the display configuration changes between the two calls (precisely when these code paths run), the loop over-reads the allocation.
Fix
copyCStringhelper:strdupthe UTF-8 bytes; the Go side frees them after conversion incScreenToScreen, keeping everyprocessScreencaller leak-free.getAllScreens(int* outCount): return the count from the same snapshot as the allocation.- Zero-initialize the
Screenstruct and guaranteeid/nameare always owned, non-NULL pointers (empty string whenlocalizedNameis unavailable or theNSScreenis nil) β this also removes a latentC.GoString(NULL)hazard via thegetScreenForWindow/getScreenForSystemTraypaths (e.g. window not currently on any screen).
No public API changes; getAllScreens is internal to the file.
Testing
go build ./pkg/applicationon macOS 26.5 / arm64 / go1.25.- Downstream app (x-haose/tg-checkin, long-running menubar-resident app) now runs with this patch via
go.mod replace; previously crashed on wake, will report back after soak.
Type of change
- [x] Bug fix (non-breaking change which fixes an issue)
Summary by CodeRabbit
-
Bug Fixes
- Improved screen detection reliability by preventing race conditions during display reconfiguration.
-
Refactor
- Enhanced memory safety and management of internal screen data structures.
No actionable comments were generated in the recent review. π
βΉοΈ Recent review info
βοΈ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 35225834-8313-4d05-a7c3-7920377200d3
π₯ Commits
Reviewing files that changed from the base of the PR and between 2633f8124ea742b43f1da82ec166179828c57e38 and 43569fe6bbfef76ad390d02cf28d0421658c808d.
π Files selected for processing (1)
v3/pkg/application/screen_darwin.go
Walkthrough
Screen enumeration on macOS now uses explicit C heap ownership for string fields and atomic screen-count acquisition. A new copyCString helper duplicates NSString UTF-8 bytes onto the C heap for Screen.id and Screen.name. The getAllScreens function captures screen count atomically within a single snapshot. Go-side cleanup adds deferred free calls to release the heap allocations after converting to Go strings.
Changes
Darwin Screen Enumeration Memory Safety
| Layer / File(s) | Summary |
|---|---|
Heap-allocated string fields in processScreen v3/pkg/application/screen_darwin.go |
Introduces copyCString C helper to duplicate NSString UTF-8 data onto the C heap. Updates processScreen to allocate Screen.id and Screen.name via copyCString, replacing unsafe direct UTF8String pointers with owned heap allocations. |
Atomic screen count and Go-side memory management v3/pkg/application/screen_darwin.go |
Refactors getAllScreens to snapshot NSScreen screens once and capture count atomically. Adds deferred free calls in cScreenToScreen to release heap-allocated strings after Go conversion. Updates processAndCacheScreens to obtain screen count from the same snapshot used to allocate the array, eliminating a separate count fetch. |
Estimated code review effort
π― 3 (Moderate) | β±οΈ ~20 minutes
Possibly related issues
- wailsapp/wails#5556: Directly addressed by these changes, which implement heap-allocated UTF-8 string duplication and atomic screen-count acquisition from a single NSScreen snapshot.
Suggested labels
Bug, go, MacOS, size:M, awaiting review π
Suggested reviewers
- leaanthony
- atterpac
- flofreud
Poem
π° A rabbit hops through Darwin's screens, With strings that now know what they meanβ No dangling pointers left behind, Just heap-owned data, safely signed! One snapshot counts them all at once, No races nowβour memory won't.
π₯ Pre-merge checks | β 3 | β 2
β Failed checks (1 warning, 1 inconclusive)
| Check name | Status | Explanation | Resolution |
|---|---|---|---|
| Docstring Coverage | β οΈ Warning | Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. | Write docstrings for the functions missing them to satisfy the coverage threshold. |
| Description check | β Inconclusive | The description covers the crash context, root causes, fixes, and testing. However, it does not reference an issue number using 'Fixes #' format and some template sections are incomplete or unchecked. | Add 'Fixes # |
β Passed checks (3 passed)
| Check name | Status | Explanation |
|---|---|---|
| Title check | β Passed | The title accurately summarizes the two main fixes: copying C strings for screen id/name and atomically snapshotting screen count. |
| Linked Issues check | β Passed | Check skipped because no linked issues were found for this pull request. |
| Out of Scope Changes check | β Passed | Check skipped because no linked issues were found for this pull request. |
βοΈ Tip: You can configure your own custom pre-merge checks in the settings.
β¨ Finishing Touches
π§ͺ Generate unit tests (beta)
- [ ] Create PR with unit tests
[!WARNING] There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.
π§ golangci-lint (2.12.2)
level=error msg="[linters_context] typechecking error: pattern ./...: directory prefix . does not contain main module or its selected dependencies"
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment @coderabbitai help to get the list of available commands and usage tips.
Thanks for this, @x-haose β you correctly spotted that macOS screen enumeration could hand back pointers into Objective-C strings that get freed, and reading the screen count separately from the list was a real race. Solid catch.
The same fix landed just ahead of this via #5565, which added strdupOrNull for the id/name and a single getAllScreens(int* outCount) that returns the list and count together β the same approach as yours. So I'm closing this as already-resolved, purely on timing. You'll be credited in the release notes for independently finding and fixing it. π
(Note for posterity: #5516 tackles the same area from a different angle β marshalling enumeration onto the main thread β so that protection is being tracked separately.)