fixes #22852; fixes #23435; fixes #23645; SIGSEGV when slicing string or seq[T] with index out of range (#23279)

follow up https://github.com/nim-lang/Nim/pull/23013

fixes #22852
fixes #23435
fixes #23645

reports rangeDefect correctly

```nim
/workspaces/Nim/test9.nim(1) test9
/workspaces/Nim/lib/system/indices.nim(116) []
/workspaces/Nim/lib/system/fatal.nim(53) sysFatal
Error: unhandled exception: value out of range: -2 notin 0 .. 9223372036854775807 [RangeDefect]
```
This commit is contained in:
ringabout
2024-05-27 20:13:18 +08:00
committed by GitHub
parent 3bda5fc840
commit c615828ccb
2 changed files with 10 additions and 5 deletions

View File

@@ -1070,7 +1070,11 @@ proc allPathsAsgnResult(p: BProc; n: PNode): InitResultEnum =
if result != Unknown: return result
of nkAsgn, nkFastAsgn, nkSinkAsgn:
if n[0].kind == nkSym and n[0].sym.kind == skResult:
if not containsResult(n[1]): result = InitSkippable
if not containsResult(n[1]):
if allPathsAsgnResult(p, n[1]) == InitRequired:
result = InitRequired
else:
result = InitSkippable
else: result = InitRequired
elif containsResult(n):
result = InitRequired
@@ -1148,6 +1152,10 @@ proc allPathsAsgnResult(p: BProc; n: PNode): InitResultEnum =
allPathsInBranch(n[i])
of nkRaiseStmt:
result = InitRequired
of nkChckRangeF, nkChckRange64, nkChckRange:
# TODO: more checks might need to be covered like overflow, indexDefect etc.
# bug #22852
result = InitRequired
else:
for i in 0..<n.safeLen:
allPathsInBranch(n[i])

View File

@@ -114,11 +114,8 @@ proc `[]`*[Idx, T; U, V: Ordinal](a: array[Idx, T], x: HSlice[U, V]): seq[T] {.s
## ```
let xa = a ^^ x.a
let L = (a ^^ x.b) - xa + 1
# Workaround bug #22852:
result = newSeq[T](if L < 0: 0 else: L)
result = newSeq[T](L)
for i in 0..<L: result[i] = a[Idx(i + xa)]
# Workaround bug #22852
discard Natural(L)
proc `[]=`*[Idx, T; U, V: Ordinal](a: var array[Idx, T], x: HSlice[U, V], b: openArray[T]) {.systemRaisesDefect.} =
## Slice assignment for arrays.