Permalink
Browse files

add bounds check for SliceExpr on string (fixes #543)

1 parent 6f5a3c4 commit e34a5cd6a1bc7c4fde759f2d3039852fc68b5fcc @neelance neelance committed Oct 31, 2016
Showing with 21 additions and 3 deletions.
  1. +3 −3 compiler/expressions.go
  2. +7 −0 compiler/prelude/prelude.go
  3. +11 −0 tests/misc_test.go
@@ -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)
@@ -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 [];
View
@@ -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 e34a5cd

Please sign in to comment.