Skip to content

Commit

Permalink
add bounds check for SliceExpr on string (fixes #543)
Browse files Browse the repository at this point in the history
  • Loading branch information
neelance committed Oct 31, 2016
1 parent 6f5a3c4 commit a9c3bca
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 3 deletions.
6 changes: 3 additions & 3 deletions compiler/expressions.go
Original file line number Diff line number Diff line change
Expand Up @@ -479,11 +479,11 @@ func (c *funcContext) translateExpr(expr ast.Expr) *expression {
case e.Low == nil && e.High == nil:
return c.translateExpr(e.X)
case e.Low == nil:
return c.formatExpr("%e.substring(0, %f)", e.X, e.High)
return c.formatExpr("$substring(%e, 0, %f)", e.X, e.High)
case e.High == nil:
return c.formatExpr("%e.substring(%f)", e.X, e.Low)
return c.formatExpr("$substring(%e, %f)", e.X, e.Low)
default:
return c.formatExpr("%e.substring(%f, %f)", e.X, e.Low, e.High)
return c.formatExpr("$substring(%e, %f, %f)", e.X, e.Low, e.High)
}
}
slice := c.translateConversionToSlice(e.X, exprType)
Expand Down
7 changes: 7 additions & 0 deletions compiler/prelude/prelude.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,13 @@ var $subslice = function(slice, low, high, max) {
return s;
};
var $substring = function(str, low, high) {
if (low < 0 || high < low || high > str.length) {
$throwRuntimeError("slice bounds out of range");
}
return str.substring(low, high);
}
var $sliceToArray = function(slice) {
if (slice.$length === 0) {
return [];
Expand Down
11 changes: 11 additions & 0 deletions tests/misc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -585,3 +585,14 @@ func TestDeferNamedTupleReturnImplicitCast(t *testing.T) {
t.Fail()
}
}

func TestSliceOfString(t *testing.T) {
defer func() {
if err := recover(); err == nil || !strings.Contains(err.(error).Error(), "slice bounds out of range") {
t.Fail()
}
}()

str := "foo"
print(str[0:10])
}

0 comments on commit a9c3bca

Please sign in to comment.