Subject: bug#40023: 26.3; Emacs crashes when creating process if many file handles are in use (e.g., when using ccls)

From: Robert Pluim <[email-masked]>
Date: Thu, 12 Mar 2020 17:46:58 +0100

>>>>> On Thu, 12 Mar 2020 17:50:14 +0200, Eli Zaretskii <[email-masked]> said:

    >> From: Robert Pluim <[email-masked]>
    >> Cc: [email-masked],  [email-masked]
    >> Date: Thu, 12 Mar 2020 16:24:44 +0100
    >> 
    >> >> You mean Bug#39164? I donʼt think there was a commit for that.
    >> 
    Eli> That's too bad.  I think we should revive that bug and fix it in Emacs
    Eli> 27, since I understand the recent versions of macOS will have that
    Eli> effect more and more frequently.
    >> 
    >> If someone has an 'emacs -Q' testcase I can look at it. Soon we will
    >> all be spending lots of time at home here :-(

    Eli> We could simply install the proposed workaround on the emacs-27 branch
    Eli> for now, I think.

Holger, is it possible for you to rebuild emacs with the following
patch and see if Emacs still crashes? If it fixes things Iʼll install
to emacs-27

diff --git a/src/nsterm.m b/src/nsterm.m
index aefbb2721e..90f63bc182 100644
--- a/src/nsterm.m
+++ b/src/nsterm.m
@@ -5805,6 +5805,22 @@ - (void)applicationDidFinishLaunching: (NSNotification *)notification
 #endif
 
 #ifdef NS_IMPL_COCOA
+  /* Some functions/methods in CoreFoundation/Foundation increase the
+     maximum number of open files for the process in their first call.
+     We make dummy calls to them and then reduce the resource limit
+     here, since pselect cannot handle file descriptors that are
+     greater than or equal to FD_SETSIZE.  */
+  CFSocketGetTypeID ();
+  CFFileDescriptorGetTypeID ();
+  [[NSFileHandle alloc] init];
+  struct rlimit rlim;
+  if (getrlimit (RLIMIT_NOFILE, &rlim) == 0
+      && rlim.rlim_cur > FD_SETSIZE)
+    {
+      rlim.rlim_cur = FD_SETSIZE;
+      setrlimit (RLIMIT_NOFILE, &rlim);
+    }
+
   if ([NSApp activationPolicy] == NSApplicationActivationPolicyProhibited) {
     /* Set the app's activation policy to regular when we run outside
        of a bundle.  This is already done for us by Info.plist when we