Skip to content

Commit e34a5cd

Browse files
committed
add bounds check for SliceExpr on string (fixes #543)
1 parent 6f5a3c4 commit e34a5cd

File tree

3 files changed

+21
-3
lines changed

3 files changed

+21
-3
lines changed

compiler/expressions.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -479,11 +479,11 @@ func (c *funcContext) translateExpr(expr ast.Expr) *expression {
479479
case e.Low == nil && e.High == nil:
480480
return c.translateExpr(e.X)
481481
case e.Low == nil:
482-
return c.formatExpr("%e.substring(0, %f)", e.X, e.High)
482+
return c.formatExpr("$substring(%e, 0, %f)", e.X, e.High)
483483
case e.High == nil:
484-
return c.formatExpr("%e.substring(%f)", e.X, e.Low)
484+
return c.formatExpr("$substring(%e, %f)", e.X, e.Low)
485485
default:
486-
return c.formatExpr("%e.substring(%f, %f)", e.X, e.Low, e.High)
486+
return c.formatExpr("$substring(%e, %f, %f)", e.X, e.Low, e.High)
487487
}
488488
}
489489
slice := c.translateConversionToSlice(e.X, exprType)

compiler/prelude/prelude.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,13 @@ var $subslice = function(slice, low, high, max) {
110110
return s;
111111
};
112112
113+
var $substring = function(str, low, high) {
114+
if (low < 0 || high < low || high > str.length) {
115+
$throwRuntimeError("slice bounds out of range");
116+
}
117+
return str.substring(low, high);
118+
};
119+
113120
var $sliceToArray = function(slice) {
114121
if (slice.$length === 0) {
115122
return [];

tests/misc_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -585,3 +585,14 @@ func TestDeferNamedTupleReturnImplicitCast(t *testing.T) {
585585
t.Fail()
586586
}
587587
}
588+
589+
func TestSliceOfString(t *testing.T) {
590+
defer func() {
591+
if err := recover(); err == nil || !strings.Contains(err.(error).Error(), "slice bounds out of range") {
592+
t.Fail()
593+
}
594+
}()
595+
596+
str := "foo"
597+
print(str[0:10])
598+
}

0 commit comments

Comments
 (0)