getrlimit-based stack limits
authorAndy Wingo <wingo@pobox.com>
Fri, 27 Mar 2009 22:44:17 +0000 (15:44 -0700)
committerAndy Wingo <wingo@pobox.com>
Fri, 27 Mar 2009 22:44:17 +0000 (15:44 -0700)
* libguile/debug.c (init_stack_limit): Initialize the stack limit based
  on operating system limits (via getrlimit(2)), or 1 MB -- whichever is
  smaller.

libguile/debug.c

index 5d0e208..ec37d3a 100644 (file)
 # include <config.h>
 #endif
 
+#ifdef HAVE_GETRLIMIT
+#include <sys/time.h>
+#include <sys/resource.h>
+#endif
+
 #include "libguile/_scm.h"
 #include "libguile/async.h"
 #include "libguile/eval.h"
@@ -513,11 +518,42 @@ SCM_DEFINE (scm_debug_hang, "debug-hang", 0, 1, 0,
 #undef FUNC_NAME
 #endif
 
+static void
+init_stack_limit (void)
+{
+#ifdef HAVE_GETRLIMIT
+  struct rlimit lim;
+  if (getrlimit (RLIMIT_STACK, &lim) == 0)
+      {
+        int bytes = lim.rlim_cur, words;
+
+        /* set our internal stack limit to 1 MB or 80% of the rlimit, whichever
+           is lower. */
+        if (bytes == RLIM_INFINITY)
+          bytes = lim.rlim_max;
+
+        if (bytes == RLIM_INFINITY)
+          words = 1024 * 1024 / sizeof (scm_t_bits);
+        else
+          {
+            bytes = bytes * 8 / 10;
+            if (bytes > 1024 * 1024)
+              bytes = 1024 * 1024;
+            words = bytes / sizeof (scm_t_bits);
+          }
+
+        SCM_STACK_LIMIT = words;
+      }
+  errno = 0;
+#endif
+}
+
 \f
 
 void
 scm_init_debug ()
 {
+  init_stack_limit ();
   scm_init_opts (scm_debug_options, scm_debug_opts);
 
   scm_tc16_memoized = scm_make_smob_type ("memoized", 0);