summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBenoit Giannangeli <giann008@gmail.com>2017-03-31 08:44:13 +0200
committerBenoit Giannangeli <giann008@gmail.com>2017-03-31 08:44:13 +0200
commitfedcb75c0fa087abcaa53a1df3304a97c4516faa (patch)
tree76b1750cf3e747228ae2576c38ee8b735a625237
parent3813f2d43054708bab7221a5ca74a0183a2ebcaf (diff)
downloadfengari-fedcb75c0fa087abcaa53a1df3304a97c4516faa.tar.gz
fengari-fedcb75c0fa087abcaa53a1df3304a97c4516faa.tar.bz2
fengari-fedcb75c0fa087abcaa53a1df3304a97c4516faa.zip
Fixed bad \0 check on %s format
-rw-r--r--src/lstrlib.js10
-rw-r--r--tests/single.lua3
2 files changed, 10 insertions, 3 deletions
diff --git a/src/lstrlib.js b/src/lstrlib.js
index c132e02..9104078 100644
--- a/src/lstrlib.js
+++ b/src/lstrlib.js
@@ -24,6 +24,11 @@ const LUA_MAXCAPTURES = 32;
// (sizeof(size_t) < sizeof(int) ? MAX_SIZET : (size_t)(INT_MAX))
const MAXSIZE = 2147483647;
+/* Give natural (i.e. strings end at the first \0) length of a string represented by an array of bytes */
+const strlen = function(s) {
+ let len = s.indexOf(0);
+ return len > -1 ? len : s.length;
+};
/* translate a relative string position: negative means back from end */
const posrelat = function(pos, len) {
@@ -327,12 +332,11 @@ const str_format = function(L) {
case 's': {
strfrmt = strfrmt.slice(1);
let s = lauxlib.luaL_tolstring(L, arg);
- if (form[2] === char['\0']) { /* no modifiers? */
+ if (form.length <= 2 || form[2] === 0) { /* no modifiers? */
concat(b, s); /* keep entire string */
lapi.lua_pop(L, 1); /* remove result from 'luaL_tolstring' */
} else {
- let zero = s.indexOf(0);
- lauxlib.luaL_argcheck(L, zero < 0 || zero === s.length - 1, arg, lua.to_luastring("string contains zeros"));
+ lauxlib.luaL_argcheck(L, s.length === strlen(s), arg, lua.to_luastring("string contains zeros"));
if (form.indexOf(char['.']) < 0 && s.length >= 100) {
/* no precision and string is too long to be formatted */
concat(b, s); /* keep entire string */
diff --git a/tests/single.lua b/tests/single.lua
index f5f63f3..c1241de 100644
--- a/tests/single.lua
+++ b/tests/single.lua
@@ -187,3 +187,6 @@ do
checkQ(false)
checkerror("no literal", string.format, "%q", {})
end
+
+assert(string.format("\0%s\0", "\0\0\1") == "\0\0\0\1\0")
+checkerror("contains zeros", string.format, "%10s", "\0")