From 05fbeb97a92608a9f66faa3f8d1c0fb67b0db62c Mon Sep 17 00:00:00 2001
From: Panu Matilainen <pmatilai@redhat.com>
Date: Wed, 7 Aug 2024 12:42:36 +0300
Subject: [PATCH] Fix crash on Lua file trigger exiting with return'ed data
 (#3029)

Conflict:modify the test code because b9b3f3515164 and 7f59c7dd2f4
         is not merged.
Reference:https://github.com/rpm-software-management/rpm/commit/05fbeb97a92608a9f66faa3f8d1c0fb67b0db62c

Reset the Lua stack on return from rpmluaRunScript() to discard any
unhandled returned data from the scriptlet. This may happen if there's
eg "return 0" from a non-macro scriptlet.

We could check for a numeric return value here and treat it as an exit
code, but then what to do with other kinds of returned data?
Our documentation states errors in Lua scriptlets should be signaled with
Lua error() function, it seems better to stick with that and avoid
introducing ambiguities and incompatibilities.

Update the existing file trigger tests to cover this case.

Fixes: #3029
---
 rpmio/rpmlua.c                     |  2 ++
 tests/data/SPECS/filetriggers.spec | 11 +++++++++++
 tests/rpmscript.at                 |  3 +++
 3 files changed, 16 insertions(+)

diff --git a/rpmio/rpmlua.c b/rpmio/rpmlua.c
index ecb21eb82..858be7739 100644
--- a/rpmio/rpmlua.c
+++ b/rpmio/rpmlua.c
@@ -303,6 +303,8 @@ int rpmluaRunScript(rpmlua lua, const char *script, const char *name,
 
 exit:
     free(buf);
+    /* discard any unhandled return data from the script */
+    lua_settop(L, otop);
     return ret;
 }
 
diff --git a/tests/data/SPECS/filetriggers.spec b/tests/data/SPECS/filetriggers.spec
index 3e2ee0034..e8d3bc7cd 100644
--- a/tests/data/SPECS/filetriggers.spec
+++ b/tests/data/SPECS/filetriggers.spec
@@ -52,6 +52,17 @@ end
 print("")
 io.flush()
 
+%filetriggerun -p <lua> -- /usr/bin
+print("filetriggerun(/usr/bin*)<lua>: "..arg[2].." "..arg[3])
+a = rpm.next_file()
+while a do
+    print(a)
+    a = rpm.next_file()
+end
+print("")
+io.flush()
+return 0
+
 %filetriggerin -- /foo
 echo "filetriggerin(/foo*):"
 cat
diff --git a/tests/rpmscript.at b/tests/rpmscript.at
index 8fc729a56..d47705008 100644
--- a/tests/rpmscript.at
+++ b/tests/rpmscript.at
@@ -461,6 +461,9 @@ filetriggerpostun(/foo*):
 filetriggerun(/usr/bin*): 0
 /usr/bin/hello
 
+filetriggerun(/usr/bin*)<lua>: 0
+/usr/bin/hello
+
 filetriggerpostun(/usr/bin*): 0
 /usr/bin/hello
 
-- 
2.33.0

