From 560449e08722ab85d9e9dcdc78ccdee298bab215 Mon Sep 17 00:00:00 2001 From: Edwin Brady Date: Sat, 16 May 2020 13:50:37 +0100 Subject: [PATCH] Check bounds on substring Fixes #379 --- dist/rts/idris_rts.c | 1 + dist/rts/idris_utf8.c | 2 +- libs/prelude/Prelude.idr | 8 ++++++-- support/chez/support.ss | 4 +++- 4 files changed, 11 insertions(+), 4 deletions(-) diff --git a/dist/rts/idris_rts.c b/dist/rts/idris_rts.c index 9b1be8d..8c05038 100644 --- a/dist/rts/idris_rts.c +++ b/dist/rts/idris_rts.c @@ -572,6 +572,7 @@ VAL idris_concat(VM* vm, VAL l, VAL r) { String * cl = allocStr(vm, llen + rlen, 0); memcpy(cl->str, ls, llen); memcpy(cl->str + llen, rs, rlen); + cl->str[llen+rlen] = '\0'; return (VAL)cl; } diff --git a/dist/rts/idris_utf8.c b/dist/rts/idris_utf8.c index 96832ac..a695ceb 100644 --- a/dist/rts/idris_utf8.c +++ b/dist/rts/idris_utf8.c @@ -105,7 +105,7 @@ char* idris_utf8_advance(char* str, int i) { int idris_utf8_findOffset(char* str, int i) { int offset = 0; - while(i > 0) { + while(i > 0 && str != '\0') { int len = idris_utf8_charlen(str); str+=len; offset+=len; diff --git a/libs/prelude/Prelude.idr b/libs/prelude/Prelude.idr index 9825df2..814aa5c 100644 --- a/libs/prelude/Prelude.idr +++ b/libs/prelude/Prelude.idr @@ -1065,8 +1065,12 @@ reverse = prim__strReverse ||| @ subject The string to return a portion of public export substr : (index : Nat) -> (len : Nat) -> (subject : String) -> String -substr s e = prim__strSubstr (prim__cast_IntegerInt (natToInteger s)) - (prim__cast_IntegerInt (natToInteger e)) +substr s e subj + = if s < length subj + then prim__strSubstr (prim__cast_IntegerInt (natToInteger s)) + (prim__cast_IntegerInt (natToInteger e)) + subj + else "" ||| Adds a character to the front of the specified string. ||| diff --git a/support/chez/support.ss b/support/chez/support.ss index 7eec01b..b6761a2 100644 --- a/support/chez/support.ss +++ b/support/chez/support.ss @@ -41,7 +41,9 @@ (b (max 0 off)) (x (max 0 len)) (end (min l (+ b x)))) - (substring s b end))) + (if (> b l) + "" + (substring s b end)))) (define either-left (lambda (x)