Subject: bug#34762: Acknowledgement (26.1.92; objc[27300]: Invalid or prematurely-freed autorelease pool 0x1040021e0.)

From: Win Treese <[email-masked]>
Date: Thu, 3 Sep 2020 21:44:57 -0400

[This is the first time I have submitted a patch, so please let me know if I should do something differently.]

This message includes a patch for bug#34762. I think that this is also the problem for bug#26982, previously marked wontfix.

The problem seems to be with the memory management for the EmacsMenu object. Here's what I think is going on with memory management in ns_update_panel:

1. The code sets up an autorelease pool at line 125
2. The only NS object allocated is an EmacsMenu at line 136
3. If that allocation happens, the new object is set as the application main menu at line 455

So the allocated menu object lasts beyond the life of the pool.

The pool seems to be pretty much irrelevant in this particular case. Since the menu is given to the app, and might be deallocated under some circumstances if it's passed back to ns_update_menu, it seems like simply removing the pool code is sufficient without causing a memory leak.

I have attached a patch against Emacs head for it, although the same patch applies to the Emacs 26 code in Aquamacs.

An Aquamacs user provided a test case, with some help from the team that does the poly-R package. I reduced the test case to a standalone piece of elisp that can be loaded. It installs packages for demonstrating the bug, but it does in /tmp so it doesn't interfere with actual configuration.

;; Set up to reproduce a crash in the Mac menu code
;; Load/evaluate this file in Emacs started with -q, then click on the menu bar.
;; This code installs some packages in a temporary user-package-dir.

(if (boundp 'aquamacs-version)
    (setq package-user-dir "/tmp/emacs-bug-test-packages-aquamacs")
  (setq package-user-dir "/tmp/emacs-bug-test-packages"))

(make-directory package-user-dir t)

(setq package-archives '(("melpa-stable" . "https://stable.melpa.org/packages/")
                         ("gnu" . "https://elpa.gnu.org/packages/")))
(package-initialize)
(package-refresh-contents)

(dolist (pkg '(ess poly-R))
  (unless (package-installed-p pkg)
    (package-install pkg)))

(require 'poly-R)
(message "Run 'M-x R', then try clicking on the menu bar")
;; End test code

The crash is immediate when you click on the menu bar, and does not happen with the patch applied. There is some chance of a memory leak if I didn't fully understand the object lifecycles.

This is also tracked as Aquamacs bug #180 on github: https://github.com/aquamacs-emacs/aquamacs-emacs/issues/180

- Win