Skip to content

Sema: fix memcpy with C pointers #23174

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 28, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/Sema.zig
Original file line number Diff line number Diff line change
Expand Up @@ -3669,7 +3669,10 @@ fn indexablePtrLenOrNone(
const zcu = pt.zcu;
const operand_ty = sema.typeOf(operand);
try checkMemOperand(sema, block, src, operand_ty);
if (operand_ty.ptrSize(zcu) == .many) return .none;
switch (operand_ty.ptrSize(zcu)) {
.many, .c => return .none,
.one, .slice => {},
}
const field_name = try zcu.intern_pool.getOrPutString(sema.gpa, pt.tid, "len", .no_embedded_nulls);
return sema.fieldVal(block, src, operand, field_name, src);
}
Expand Down
21 changes: 21 additions & 0 deletions test/behavior/memcpy.zig
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,27 @@ fn testMemcpyDestManyPtr() !void {
try expect(buf[4] == 'o');
}

test "@memcpy C pointer" {
if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest;
if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest;
if (builtin.zig_backend == .stage2_sparc64) return error.SkipZigTest;
if (builtin.zig_backend == .stage2_spirv64) return error.SkipZigTest;

try testMemcpyCPointer();
try comptime testMemcpyCPointer();
}

fn testMemcpyCPointer() !void {
const src = "hello";
var buf: [5]u8 = undefined;
@memcpy(@as([*c]u8, &buf), src);
try expect(buf[0] == 'h');
try expect(buf[1] == 'e');
try expect(buf[2] == 'l');
try expect(buf[3] == 'l');
try expect(buf[4] == 'o');
}

test "@memcpy slice" {
if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest;
if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest;
Expand Down
Loading