Skip to content

Commit

Permalink
string last: fix segfault with invalid index
Browse files Browse the repository at this point in the history
[string last foo bar -1] gave segfault due to missing
check for invalid index.

Fixes #161

Signed-off-by: Steve Bennett <steveb@workware.net.au>
  • Loading branch information
msteveb committed Jul 11, 2020
1 parent 4e2cdac commit da293a1
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 4 deletions.
9 changes: 5 additions & 4 deletions jim.c
Expand Up @@ -2590,7 +2590,7 @@ int Jim_StringCompareObj(Jim_Interp *interp, Jim_Obj *firstObjPtr, Jim_Obj *seco
* is out of range. */
static int JimRelToAbsIndex(int len, int idx)
{
if (idx < 0)
if (idx < 0 && idx > -INT_MAX)
return len + idx;
return idx;
}
Expand Down Expand Up @@ -13979,9 +13979,7 @@ static int Jim_StringCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *a
}
str = Jim_String(argv[2]);
len = Jim_Utf8Length(interp, argv[2]);
if (idx != INT_MIN && idx != INT_MAX) {
idx = JimRelToAbsIndex(len, idx);
}
idx = JimRelToAbsIndex(len, idx);
if (idx < 0 || idx >= len || str == NULL) {
Jim_SetResultString(interp, "", 0);
}
Expand Down Expand Up @@ -14015,6 +14013,9 @@ static int Jim_StringCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *a
return JIM_ERR;
}
idx = JimRelToAbsIndex(l2, idx);
if (idx < 0) {
idx = 0;
}
}
else if (option == OPT_LAST) {
idx = l2;
Expand Down
5 changes: 5 additions & 0 deletions regtest.tcl
Expand Up @@ -355,6 +355,11 @@ puts "TEST 51 PASSED"
catch {lsearch -all -command abc def}
puts "TEST 52 PASSED"

# REGTEST 53
# string last with invalid index
catch {string last foo bar -1}
puts "TEST 53 PASSED"


# TAKE THE FOLLOWING puts AS LAST LINE

Expand Down
3 changes: 3 additions & 0 deletions tests/string.test
Expand Up @@ -449,6 +449,9 @@ test string-7.5 {string last} {
test string-7.6 {string last} {
string las x xxxx123xx345x678
} 12
test string-7.7 {string last, bad index} {
string last ba badbad -1
} -1
test string-7.13 {string last, start index} {
## Constrain to last 'a' should work
string last ba badbad end-1
Expand Down

0 comments on commit da293a1

Please sign in to comment.