Skip to content

Commit b5cef9e

Browse files
authored
Merge pull request #19374 from ziglang/slice-by-len-safety
add OOB safety check for by-length slice of array
2 parents e831313 + 4d5e0a0 commit b5cef9e

File tree

2 files changed

+30
-6
lines changed

2 files changed

+30
-6
lines changed

src/Sema.zig

+10-6
Original file line numberDiff line numberDiff line change
@@ -33284,12 +33284,16 @@ fn analyzeSlice(
3328433284
try sema.addSafetyCheck(block, src, is_non_null, .unwrap_null);
3328533285
}
3328633286

33287-
if (slice_ty.isSlice(mod)) {
33288-
const slice_len_inst = try block.addTyOp(.slice_len, Type.usize, ptr_or_slice);
33289-
const actual_len = if (slice_ty.sentinel(mod) == null)
33290-
slice_len_inst
33291-
else
33292-
try sema.analyzeArithmetic(block, .add, slice_len_inst, .one, src, end_src, end_src, true);
33287+
bounds_check: {
33288+
const actual_len = if (array_ty.zigTypeTag(mod) == .Array)
33289+
try mod.intRef(Type.usize, array_ty.arrayLenIncludingSentinel(mod))
33290+
else if (slice_ty.isSlice(mod)) l: {
33291+
const slice_len_inst = try block.addTyOp(.slice_len, Type.usize, ptr_or_slice);
33292+
break :l if (slice_ty.sentinel(mod) == null)
33293+
slice_len_inst
33294+
else
33295+
try sema.analyzeArithmetic(block, .add, slice_len_inst, .one, src, end_src, end_src, true);
33296+
} else break :bounds_check;
3329333297

3329433298
const actual_end = if (slice_sentinel != null)
3329533299
try sema.analyzeArithmetic(block, .add, end, .one, src, end_src, end_src, true)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
const std = @import("std");
2+
3+
pub fn panic(message: []const u8, stack_trace: ?*std.builtin.StackTrace, _: ?usize) noreturn {
4+
_ = stack_trace;
5+
if (std.mem.eql(u8, message, "index out of bounds: index 16, len 5")) {
6+
std.process.exit(0);
7+
}
8+
std.process.exit(1);
9+
}
10+
pub fn main() !void {
11+
var buf: [5]u8 = undefined;
12+
_ = buf[foo(6)..][0..10];
13+
return error.TestFailed;
14+
}
15+
fn foo(a: u32) u32 {
16+
return a;
17+
}
18+
// run
19+
// backend=llvm
20+
// target=native

0 commit comments

Comments
 (0)