Skip to content

Commit

Permalink
fixes #22852; fixes #23435; fixes #23645; SIGSEGV when slicing string…
Browse files Browse the repository at this point in the history
… or seq[T] with index out of range (#23279)

follow up #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]
```
  • Loading branch information
ringabout committed May 27, 2024
1 parent 3bda5fc commit c615828
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
10 changes: 9 additions & 1 deletion compiler/cgen.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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])
Expand Down
5 changes: 1 addition & 4 deletions lib/system/indices.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down

0 comments on commit c615828

Please sign in to comment.