From sanghyun.park.cnu at gmail.com  Tue Jun 16 03:19:27 2026
From: sanghyun.park.cnu at gmail.com (Sanghyun Park)
Date: Tue, 16 Jun 2026 12:19:27 +0900
Subject: [PATCH] ash: fix stack overflow in evalfun()
Message-ID: <20260616031928.1182292-1-sanghyun.park.cnu@gmail.com>

Recursive shell functions can repeatedly enter evalfun() until the
process stack is exhausted. Track active shell function calls and raise a
normal shell error when the recursion limit is reached.

The counter is decremented through the existing funcdone cleanup path so
errors raised from inside the function body unwind it correctly.

Signed-off-by: Sanghyun Park <sanghyun.park.cnu at gmail.com>
---
 shell/ash.c | 8 ++++++++
 1 file changed, 8 insertions(+)

diff --git a/shell/ash.c b/shell/ash.c
--- a/shell/ash.c
+++ b/shell/ash.c
@@ -414,6 +414,7 @@ struct globals_misc {
 	int shlvl;
 #define rootshell (!shlvl)
 	int errlinno;
+	unsigned func_depth;
 
 	char *minusc;  /* argument to -c option */
 
@@ -506,6 +507,7 @@ extern struct globals_misc *BB_GLOBAL_CO
 #define rootpid     (G_misc.rootpid    )
 #define shlvl       (G_misc.shlvl      )
 #define errlinno    (G_misc.errlinno   )
+#define func_depth  (G_misc.func_depth )
 #define minusc      (G_misc.minusc     )
 #define curdir      (G_misc.curdir     )
 #define physdir     (G_misc.physdir    )
@@ -9928,6 +9930,10 @@ evalfun(struct funcnode *func, int argc,
 	int savefuncline;
 	char *savefuncname;
 	char *savetrap = NULL;
+	enum { MAX_ASH_FUNC_DEPTH = 1000 };
+
+	if (func_depth >= MAX_ASH_FUNC_DEPTH)
+		ash_msg_and_raise_error("function recursion limit exceeded");
 
 	if (!Eflag) {
 		savetrap = trap[NTRAP_ERR];
@@ -9946,6 +9952,7 @@ evalfun(struct funcnode *func, int argc,
 	exception_handler = &jmploc;
 	shellparam.malloced = 0;
 	func->count++;
+	func_depth++;
 	funcname = func->n.ndefun.text;
 	funcline = func->n.ndefun.linno;
 	INT_ON;
@@ -9967,6 +9974,7 @@ evalfun(struct funcnode *func, int argc,
 	}
 	funcline = savefuncline;
 	lineno = savelineno;
+	func_depth--;
 	freefunc(func);
 	freeparam(&shellparam);
 	shellparam = saveparam;
