Sitelet https://github.com/lua/lua/commit/1ecfbfa1a1debd2258decdf7c1954ac6f9761699
Skip to content

Commit 1ecfbfa

Browse files
committed
Fixed bug: invalid mode can crash 'io.popen'
1 parent e1d8770 commit 1ecfbfa

2 files changed

Lines changed: 22 additions & 0 deletions

File tree

‎liolib.c‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,12 @@ static int l_checkmode (const char *mode) {
5252
** =======================================================
5353
*/
5454

55+
#if !defined(l_checkmodep)
56+
/* By default, Lua accepts only "r" or "w" as mode */
57+
#define l_checkmodep(m) ((m[0] == 'r' || m[0] == 'w') && m[1] == '\0')
58+
#endif
59+
60+
5561
#if !defined(l_popen) /* { */
5662

5763
#if defined(LUA_USE_POSIX) /* { */
@@ -279,6 +285,7 @@ static int io_popen (lua_State *L) {
279285
const char *filename = luaL_checkstring(L, 1);
280286
const char *mode = luaL_optstring(L, 2, "r");
281287
LStream *p = newprefile(L);
288+
luaL_argcheck(L, l_checkmodep(mode), 2, "invalid mode");
282289
p->f = l_popen(L, filename, mode);
283290
p->closef = &io_pclose;
284291
return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;

‎testes/files.lua‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -721,6 +721,21 @@ if not _port then
721721
progname = '"' .. arg[i + 1] .. '"'
722722
end
723723
print("testing popen/pclose and execute")
724+
-- invalid mode for popen
725+
checkerr("invalid mode", io.popen, "cat", "")
726+
checkerr("invalid mode", io.popen, "cat", "r+")
727+
checkerr("invalid mode", io.popen, "cat", "rw")
728+
do -- basic tests for popen
729+
local file = os.tmpname()
730+
local f = assert(io.popen("cat - > " .. file, "w"))
731+
f:write("a line")
732+
assert(f:close())
733+
local f = assert(io.popen("cat - < " .. file, "r"))
734+
assert(f:read("a") == "a line")
735+
assert(f:close())
736+
assert(os.remove(file))
737+
end
738+
724739
local tests = {
725740
-- command, what, code
726741
{"ls > /dev/null", "ok"},

0 commit comments

Comments
 (0)