Cocoa crash from event handlers accessing freed memory
Original Reporter info from Mantis: zpeterson @boramis
-
Reporter name: Zoë Peterson
Original Reporter info from Mantis: zpeterson @boramis
- Reporter name: Zoë Peterson
Description:
I don't have a patch for this yet, because I believe a proper fix will require extensive changes and wanted to discuss it before making them.
Currently TLCLCommonCallback objects are freed in the widgetset DestroyHandle functions, immediately before the NS object is released. If a control is destroyed in response to an event where it's the target, the calling functions may access the callback object after it's been freed.
I think that the proper fix for this would be to free the callback in the NS object's dealloc, rather than DestroyHandle. Cocoa retains the NS object until the event is done being processed. DestroyHandle might need to still set the callback's Target to nil to terminate further processing, and if so, we would probably need to add additional checks of Assigned(Target).
We saw the issue because we're using FastMM4's full debug mode, which catches use of freed objects/interfaces and faults. An easier way to expose it is by applying the attached patch, which triggers a fault if the callback is freed in the middle of KeyEvBefore. Once you do, run the sample project, click on an item in the treeview a couple of times to make it enter rename mode, then press [Enter] or [Esc] to exit it.
I've verified that the issue was not caused by my key event patches. It affects mouse down events too, though that's been harder to trigger since they don't access the callback object as much as the key events do. In the case where we were seeing it, we were moving a TFrame between two forms and freeing one of the forms.
Mantis conversion info:
- Mantis ID: 35706
- Version: 2.0.3 (SVN)
- Monitored by: » @neurolabusc1 (Chris Rorden)