Skip to content

Commit 06075e1

Browse files
committed
sema: add OOB safety check for by-length slice of array
This adds a out-of-bounds safety check for by-length slices of arrays with a comptime-known length but runtime known start/end.
1 parent ec358d6 commit 06075e1

File tree

1 file changed

+7
-3
lines changed

1 file changed

+7
-3
lines changed

src/Sema.zig

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32955,19 +32955,23 @@ fn analyzeSlice(
3295532955
try sema.addSafetyCheck(block, src, is_non_null, .unwrap_null);
3295632956
}
3295732957

32958-
if (slice_ty.isSlice(mod)) {
32958+
const opt_len_inst = if (array_ty.zigTypeTag(mod) == .Array)
32959+
try mod.intRef(Type.usize, array_ty.arrayLenIncludingSentinel(mod))
32960+
else if (slice_ty.isSlice(mod)) blk: {
3295932961
const slice_len_inst = try block.addTyOp(.slice_len, Type.usize, ptr_or_slice);
3296032962
const actual_len = if (slice_ty.sentinel(mod) == null)
3296132963
slice_len_inst
3296232964
else
3296332965
try sema.analyzeArithmetic(block, .add, slice_len_inst, .one, src, end_src, end_src, true);
32964-
32966+
break :blk actual_len;
32967+
} else null;
32968+
if (opt_len_inst) |len_inst| {
3296532969
const actual_end = if (slice_sentinel != null)
3296632970
try sema.analyzeArithmetic(block, .add, end, .one, src, end_src, end_src, true)
3296732971
else
3296832972
end;
3296932973

32970-
try sema.panicIndexOutOfBounds(block, src, actual_end, actual_len, .cmp_lte);
32974+
try sema.panicIndexOutOfBounds(block, src, actual_end, len_inst, .cmp_lte);
3297132975
}
3297232976

3297332977
// requirement: result[new_len] == slice_sentinel

0 commit comments

Comments
 (0)