Bug in string.match/gmatch/gsub handling of 0x00

  • From: Bruce Hill <bruce@xxxxxxxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Fri, 31 Aug 2018 17:20:57 -0700

I found this bug in string.match/gmatch/gsub handling of NUL bytes (0x00) in 
the pattern string. The behavior is the same on LuaJIT 2.0.5 and 2.1.0-beta3:

LuaJIT 2.1.0-beta3 -- Copyright (C) 2005-2017 Mike Pall. http://luajit.org/
JIT: ON SSE2 SSE3 SSE4.1 BMI2 fold cse dce fwd dse narrow loop abc sink fuse

print(string.match("xxx", "xxx\0"))
xxx
print(string.gsub("xxx\0xxx", "\0", "<NUL>"))
<NUL>x<NUL>x<NUL>x<NUL><NUL>x<NUL>x<NUL>x<NUL>  8
print(string.match("xxx", "[^\0]*"))
stdin:1: malformed pattern (missing ']')
stack traceback:
        [C]: in function 'match'
        stdin:1: in main chunk
        [C]: at 0x0100001220

Lua 5.2+ displays correct behavior (although Lua 5.1 has the same bug as 
LuaJIT):

Lua 5.2.4  Copyright (C) 1994-2015 Lua.org, PUC-Rio
print(string.match("xxx", "xxx\0"))
nil
print(string.gsub("xxx\0xxx", "\0", "<NUL>"))
xxx<NUL>xxx     1
print(string.match("xxx", "[^\0]*"))
xxx

I think the problem arises because the LuaJIT C code for pattern matching 
(str_find_aux() in minilua.c:7360) assumes C-style NUL-terminated strings 
instead of using the Lua string length.

Attachment: signature.asc
Description: Message signed with OpenPGP

Other related posts: