authorgravatar for mlugg@mlugg.co.ukMatthew Lugg <mlugg@mlugg.co.uk> 2024-12-16 22:59:45+00:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2024-12-16 22:59:45+00:00
log32354d1190a9d319f0f7970d6e39d2d951f2d3f4
tree936abf79b8deb54ff154f96144e846e086144503
parentd12c0bf90911339c8db0741b257eac251b827b2c
parent512cb22d838adb7fc52c2b8b6c14d16a624d8605
signaturebadge-check Signed by PGP key B5690EEEBB952194

Merge pull request #22243 from mlugg/better-imc

Sema: disallow unsafe in-memory coercions

11 files changed, 279 insertions(+), 144 deletions(-)

lib/compiler/build_runner.zig+3-3
......@@ -1364,20 +1364,20 @@ fn usage(b: *std.Build, out_stream: anytype) !void {
13641364 );
13651365}
13661366
1367fn nextArg(args: [][:0]const u8, idx: *usize) ?[:0]const u8 {
1367fn nextArg(args: []const [:0]const u8, idx: *usize) ?[:0]const u8 {
13681368 if (idx.* >= args.len) return null;
13691369 defer idx.* += 1;
13701370 return args[idx.*];
13711371}
13721372
1373fn nextArgOrFatal(args: [][:0]const u8, idx: *usize) [:0]const u8 {
1373fn nextArgOrFatal(args: []const [:0]const u8, idx: *usize) [:0]const u8 {
13741374 return nextArg(args, idx) orelse {
13751375 std.debug.print("expected argument after '{s}'\n access the help menu with 'zig build -h'\n", .{args[idx.* - 1]});
13761376 process.exit(1);
13771377 };
13781378}
13791379
1380fn argsRest(args: [][:0]const u8, idx: usize) ?[][:0]const u8 {
1380fn argsRest(args: []const [:0]const u8, idx: usize) ?[]const [:0]const u8 {
13811381 if (idx >= args.len) return null;
13821382 return args[idx..];
13831383}
lib/std/c/darwin.zig+4-4
......@@ -1232,16 +1232,16 @@ pub extern "c" fn posix_spawn(
12321232 path: [*:0]const u8,
12331233 actions: ?*const posix_spawn_file_actions_t,
12341234 attr: ?*const posix_spawnattr_t,
1235 argv: [*:null]?[*:0]const u8,
1236 env: [*:null]?[*:0]const u8,
1235 argv: [*:null]const ?[*:0]const u8,
1236 env: [*:null]const ?[*:0]const u8,
12371237) c_int;
12381238pub extern "c" fn posix_spawnp(
12391239 pid: *pid_t,
12401240 path: [*:0]const u8,
12411241 actions: ?*const posix_spawn_file_actions_t,
12421242 attr: ?*const posix_spawnattr_t,
1243 argv: [*:null]?[*:0]const u8,
1244 env: [*:null]?[*:0]const u8,
1243 argv: [*:null]const ?[*:0]const u8,
1244 env: [*:null]const ?[*:0]const u8,
12451245) c_int;
12461246
12471247pub const E = enum(u16) {
src/DarwinPosixSpawn.zig+4-4
......@@ -161,8 +161,8 @@ pub fn spawn(
161161 path: []const u8,
162162 actions: ?Actions,
163163 attr: ?Attr,
164 argv: [*:null]?[*:0]const u8,
165 envp: [*:null]?[*:0]const u8,
164 argv: [*:null]const ?[*:0]const u8,
165 envp: [*:null]const ?[*:0]const u8,
166166) Error!std.c.pid_t {
167167 const posix_path = try std.posix.toPosixPath(path);
168168 return spawnZ(&posix_path, actions, attr, argv, envp);
......@@ -172,8 +172,8 @@ pub fn spawnZ(
172172 path: [*:0]const u8,
173173 actions: ?Actions,
174174 attr: ?Attr,
175 argv: [*:null]?[*:0]const u8,
176 envp: [*:null]?[*:0]const u8,
175 argv: [*:null]const ?[*:0]const u8,
176 envp: [*:null]const ?[*:0]const u8,
177177) Error!std.c.pid_t {
178178 var pid: std.c.pid_t = undefined;
179179 switch (errno(std.c.posix_spawn(
src/Sema.zig+179-120
......@@ -30797,7 +30797,8 @@ const InMemoryCoercionResult = union(enum) {
3079730797 ptr_addrspace: AddressSpace,
3079830798 ptr_sentinel: Sentinel,
3079930799 ptr_size: Size,
30800 ptr_qualifiers: Qualifiers,
30800 ptr_const: Pair,
30801 ptr_volatile: Pair,
3080130802 ptr_allowzero: Pair,
3080230803 ptr_bit_range: BitRange,
3080330804 ptr_alignment: AlignPair,
......@@ -30861,13 +30862,6 @@ const InMemoryCoercionResult = union(enum) {
3086130862 wanted: std.builtin.Type.Pointer.Size,
3086230863 };
3086330864
30864 const Qualifiers = struct {
30865 actual_const: bool,
30866 wanted_const: bool,
30867 actual_volatile: bool,
30868 wanted_volatile: bool,
30869 };
30870
3087130865 const AddressSpace = struct {
3087230866 actual: std.builtin.AddressSpace,
3087330867 wanted: std.builtin.AddressSpace,
......@@ -31067,16 +31061,6 @@ const InMemoryCoercionResult = union(enum) {
3106731061 try sema.errNote(src, msg, "a {s} pointer cannot cast into a {s} pointer", .{ pointerSizeString(size.actual), pointerSizeString(size.wanted) });
3106831062 break;
3106931063 },
31070 .ptr_qualifiers => |qualifiers| {
31071 const ok_const = !qualifiers.actual_const or qualifiers.wanted_const;
31072 const ok_volatile = !qualifiers.actual_volatile or qualifiers.wanted_volatile;
31073 if (!ok_const) {
31074 try sema.errNote(src, msg, "cast discards const qualifier", .{});
31075 } else if (!ok_volatile) {
31076 try sema.errNote(src, msg, "cast discards volatile qualifier", .{});
31077 }
31078 break;
31079 },
3108031064 .ptr_allowzero => |pair| {
3108131065 const wanted_allow_zero = pair.wanted.ptrAllowsZero(pt.zcu);
3108231066 const actual_allow_zero = pair.actual.ptrAllowsZero(pt.zcu);
......@@ -31085,8 +31069,32 @@ const InMemoryCoercionResult = union(enum) {
3108531069 pair.actual.fmt(pt), pair.wanted.fmt(pt),
3108631070 });
3108731071 } else {
31088 try sema.errNote(src, msg, "mutable '{}' allows illegal null values stored to type '{}'", .{
31089 pair.actual.fmt(pt), pair.wanted.fmt(pt),
31072 try sema.errNote(src, msg, "mutable '{}' would allow illegal null values stored to type '{}'", .{
31073 pair.wanted.fmt(pt), pair.actual.fmt(pt),
31074 });
31075 }
31076 break;
31077 },
31078 .ptr_const => |pair| {
31079 const wanted_const = pair.wanted.isConstPtr(pt.zcu);
31080 const actual_const = pair.actual.isConstPtr(pt.zcu);
31081 if (actual_const and !wanted_const) {
31082 try sema.errNote(src, msg, "cast discards const qualifier", .{});
31083 } else {
31084 try sema.errNote(src, msg, "mutable '{}' would allow illegal const pointers stored to type '{}'", .{
31085 pair.wanted.fmt(pt), pair.actual.fmt(pt),
31086 });
31087 }
31088 break;
31089 },
31090 .ptr_volatile => |pair| {
31091 const wanted_volatile = pair.wanted.isVolatilePtr(pt.zcu);
31092 const actual_volatile = pair.actual.isVolatilePtr(pt.zcu);
31093 if (actual_volatile and !wanted_volatile) {
31094 try sema.errNote(src, msg, "cast discards volatile qualifier", .{});
31095 } else {
31096 try sema.errNote(src, msg, "mutable '{}' would allow illegal volatile pointers stored to type '{}'", .{
31097 pair.wanted.fmt(pt), pair.actual.fmt(pt),
3109031098 });
3109131099 }
3109231100 break;
......@@ -31136,20 +31144,22 @@ fn pointerSizeString(size: std.builtin.Type.Pointer.Size) []const u8 {
3113631144 };
3113731145}
3113831146
31139/// If pointers have the same representation in runtime memory, a bitcast AIR instruction
31140/// may be used for the coercion.
31141/// * `const` attribute can be gained
31142/// * `volatile` attribute can be gained
31143/// * `allowzero` attribute can be gained (whether from explicit attribute, C pointer, or optional pointer) but only if !dest_is_mut
31144/// * alignment can be decreased
31145/// * bit offset attributes must match exactly
31146/// * `*`/`[*]` must match exactly, but `[*c]` matches either one
31147/// * sentinel-terminated pointers can coerce into `[*]`
31147/// If types `A` and `B` have identical representations in runtime memory, they are considered
31148/// "in-memory coercible". This is a subset of normal coercions. Not only can `A` coerce to `B`, but
31149/// also, coercions can happen through pointers. For instance, `*const A` can coerce to `*const B`.
31150///
31151/// If this function is called, the coercion must be applied, or a compile error emitted if `.ok`
31152/// is not returned. This is because this function may modify inferred error sets to make a
31153/// coercion possible, even if `.ok` is not returned.
3114831154pub fn coerceInMemoryAllowed(
3114931155 sema: *Sema,
3115031156 block: *Block,
3115131157 dest_ty: Type,
3115231158 src_ty: Type,
31159 /// If `true`, this query comes from an attempted coercion of the form `*Src` -> `*Dest`, where
31160 /// both pointers are mutable. If this coercion is allowed, one could store to the `*Dest` and
31161 /// load from the `*Src` to effectively perform an in-memory coercion from `Dest` to `Src`.
31162 /// Therefore, when `dest_is_mut`, the in-memory coercion must be valid in *both directions*.
3115331163 dest_is_mut: bool,
3115431164 target: std.Target,
3115531165 dest_src: LazySrcLoc,
......@@ -31224,7 +31234,7 @@ pub fn coerceInMemoryAllowed(
3122431234
3122531235 // Functions
3122631236 if (dest_tag == .@"fn" and src_tag == .@"fn") {
31227 return try sema.coerceInMemoryAllowedFns(block, dest_ty, src_ty, target, dest_src, src_src);
31237 return try sema.coerceInMemoryAllowedFns(block, dest_ty, src_ty, dest_is_mut, target, dest_src, src_src);
3122831238 }
3122931239
3123031240 // Error Unions
......@@ -31233,7 +31243,7 @@ pub fn coerceInMemoryAllowed(
3123331243 const src_payload = src_ty.errorUnionPayload(zcu);
3123431244 const child = try sema.coerceInMemoryAllowed(block, dest_payload, src_payload, dest_is_mut, target, dest_src, src_src, null);
3123531245 if (child != .ok) {
31236 return InMemoryCoercionResult{ .error_union_payload = .{
31246 return .{ .error_union_payload = .{
3123731247 .child = try child.dupe(sema.arena),
3123831248 .actual = src_payload,
3123931249 .wanted = dest_payload,
......@@ -31244,7 +31254,11 @@ pub fn coerceInMemoryAllowed(
3124431254
3124531255 // Error Sets
3124631256 if (dest_tag == .error_set and src_tag == .error_set) {
31247 return try sema.coerceInMemoryAllowedErrorSets(block, dest_ty, src_ty, dest_src, src_src);
31257 const res1 = try sema.coerceInMemoryAllowedErrorSets(block, dest_ty, src_ty, dest_src, src_src);
31258 if (!dest_is_mut or res1 != .ok) return res1;
31259 // src -> dest is okay, but `dest_is_mut`, so it needs to be allowed in the other direction.
31260 const res2 = try sema.coerceInMemoryAllowedErrorSets(block, src_ty, dest_ty, src_src, dest_src);
31261 return res2;
3124831262 }
3124931263
3125031264 // Arrays
......@@ -31252,7 +31266,7 @@ pub fn coerceInMemoryAllowed(
3125231266 const dest_info = dest_ty.arrayInfo(zcu);
3125331267 const src_info = src_ty.arrayInfo(zcu);
3125431268 if (dest_info.len != src_info.len) {
31255 return InMemoryCoercionResult{ .array_len = .{
31269 return .{ .array_len = .{
3125631270 .actual = src_info.len,
3125731271 .wanted = dest_info.len,
3125831272 } };
......@@ -31263,7 +31277,7 @@ pub fn coerceInMemoryAllowed(
3126331277 .ok => {},
3126431278 .no_match => return child,
3126531279 else => {
31266 return InMemoryCoercionResult{ .array_elem = .{
31280 return .{ .array_elem = .{
3126731281 .child = try child.dupe(sema.arena),
3126831282 .actual = src_info.elem_type,
3126931283 .wanted = dest_info.elem_type,
......@@ -31279,7 +31293,7 @@ pub fn coerceInMemoryAllowed(
3127931293 zcu,
3128031294 ));
3128131295 if (!ok_sent) {
31282 return InMemoryCoercionResult{ .array_sentinel = .{
31296 return .{ .array_sentinel = .{
3128331297 .actual = src_info.sentinel orelse Value.@"unreachable",
3128431298 .wanted = dest_info.sentinel orelse Value.@"unreachable",
3128531299 .ty = dest_info.elem_type,
......@@ -31293,7 +31307,7 @@ pub fn coerceInMemoryAllowed(
3129331307 const dest_len = dest_ty.vectorLen(zcu);
3129431308 const src_len = src_ty.vectorLen(zcu);
3129531309 if (dest_len != src_len) {
31296 return InMemoryCoercionResult{ .vector_len = .{
31310 return .{ .vector_len = .{
3129731311 .actual = src_len,
3129831312 .wanted = dest_len,
3129931313 } };
......@@ -31303,7 +31317,7 @@ pub fn coerceInMemoryAllowed(
3130331317 const src_elem_ty = src_ty.scalarType(zcu);
3130431318 const child = try sema.coerceInMemoryAllowed(block, dest_elem_ty, src_elem_ty, dest_is_mut, target, dest_src, src_src, null);
3130531319 if (child != .ok) {
31306 return InMemoryCoercionResult{ .vector_elem = .{
31320 return .{ .vector_elem = .{
3130731321 .child = try child.dupe(sema.arena),
3130831322 .actual = src_elem_ty,
3130931323 .wanted = dest_elem_ty,
......@@ -31320,7 +31334,7 @@ pub fn coerceInMemoryAllowed(
3132031334 const dest_len = dest_ty.arrayLen(zcu);
3132131335 const src_len = src_ty.arrayLen(zcu);
3132231336 if (dest_len != src_len) {
31323 return InMemoryCoercionResult{ .array_len = .{
31337 return .{ .array_len = .{
3132431338 .actual = src_len,
3132531339 .wanted = dest_len,
3132631340 } };
......@@ -31330,7 +31344,7 @@ pub fn coerceInMemoryAllowed(
3133031344 const src_elem_ty = src_ty.childType(zcu);
3133131345 const child = try sema.coerceInMemoryAllowed(block, dest_elem_ty, src_elem_ty, dest_is_mut, target, dest_src, src_src, null);
3133231346 if (child != .ok) {
31333 return InMemoryCoercionResult{ .array_elem = .{
31347 return .{ .array_elem = .{
3133431348 .child = try child.dupe(sema.arena),
3133531349 .actual = src_elem_ty,
3133631350 .wanted = dest_elem_ty,
......@@ -31340,7 +31354,7 @@ pub fn coerceInMemoryAllowed(
3134031354 if (dest_tag == .array) {
3134131355 const dest_info = dest_ty.arrayInfo(zcu);
3134231356 if (dest_info.sentinel != null) {
31343 return InMemoryCoercionResult{ .array_sentinel = .{
31357 return .{ .array_sentinel = .{
3134431358 .actual = Value.@"unreachable",
3134531359 .wanted = dest_info.sentinel.?,
3134631360 .ty = dest_info.elem_type,
......@@ -31360,7 +31374,7 @@ pub fn coerceInMemoryAllowed(
3136031374 // Optionals
3136131375 if (dest_tag == .optional and src_tag == .optional) {
3136231376 if ((maybe_dest_ptr_ty != null) != (maybe_src_ptr_ty != null)) {
31363 return InMemoryCoercionResult{ .optional_shape = .{
31377 return .{ .optional_shape = .{
3136431378 .actual = src_ty,
3136531379 .wanted = dest_ty,
3136631380 } };
......@@ -31370,7 +31384,7 @@ pub fn coerceInMemoryAllowed(
3137031384
3137131385 const child = try sema.coerceInMemoryAllowed(block, dest_child_type, src_child_type, dest_is_mut, target, dest_src, src_src, null);
3137231386 if (child != .ok) {
31373 return InMemoryCoercionResult{ .optional_child = .{
31387 return .{ .optional_child = .{
3137431388 .child = try child.dupe(sema.arena),
3137531389 .actual = src_child_type,
3137631390 .wanted = dest_child_type,
......@@ -31382,7 +31396,6 @@ pub fn coerceInMemoryAllowed(
3138231396
3138331397 // Tuples (with in-memory-coercible fields)
3138431398 if (dest_ty.isTuple(zcu) and src_ty.isTuple(zcu)) tuple: {
31385 if (dest_ty.containerLayout(zcu) != src_ty.containerLayout(zcu)) break :tuple;
3138631399 if (dest_ty.structFieldCount(zcu) != src_ty.structFieldCount(zcu)) break :tuple;
3138731400 const field_count = dest_ty.structFieldCount(zcu);
3138831401 for (0..field_count) |field_idx| {
......@@ -31396,7 +31409,7 @@ pub fn coerceInMemoryAllowed(
3139631409 return .ok;
3139731410 }
3139831411
31399 return InMemoryCoercionResult{ .no_match = .{
31412 return .{ .no_match = .{
3140031413 .actual = dest_ty,
3140131414 .wanted = src_ty,
3140231415 } };
......@@ -31505,6 +31518,8 @@ fn coerceInMemoryAllowedFns(
3150531518 block: *Block,
3150631519 dest_ty: Type,
3150731520 src_ty: Type,
31521 /// If set, the coercion must be valid in both directions.
31522 dest_is_mut: bool,
3150831523 target: std.Target,
3150931524 dest_src: LazySrcLoc,
3151031525 src_src: LazySrcLoc,
......@@ -31525,40 +31540,49 @@ fn coerceInMemoryAllowedFns(
3152531540 return InMemoryCoercionResult{ .fn_generic = dest_info.is_generic };
3152631541 }
3152731542
31528 if (!callconvCoerceAllowed(target, src_info.cc, dest_info.cc)) {
31543 const callconv_ok = callconvCoerceAllowed(target, src_info.cc, dest_info.cc) and
31544 (!dest_is_mut or callconvCoerceAllowed(target, dest_info.cc, src_info.cc));
31545
31546 if (!callconv_ok) {
3152931547 return .{ .fn_cc = .{
3153031548 .actual = src_info.cc,
3153131549 .wanted = dest_info.cc,
3153231550 } };
3153331551 }
3153431552
31535 switch (src_info.return_type) {
31536 .noreturn_type, .generic_poison_type => {},
31537 else => {
31538 const dest_return_type = Type.fromInterned(dest_info.return_type);
31539 const src_return_type = Type.fromInterned(src_info.return_type);
31540 const rt = try sema.coerceInMemoryAllowed(block, dest_return_type, src_return_type, false, target, dest_src, src_src, null);
31541 if (rt != .ok) {
31542 return InMemoryCoercionResult{ .fn_return_type = .{
31543 .child = try rt.dupe(sema.arena),
31544 .actual = src_return_type,
31545 .wanted = dest_return_type,
31546 } };
31547 }
31548 },
31553 if (!switch (src_info.return_type) {
31554 .generic_poison_type => true,
31555 .noreturn_type => !dest_is_mut,
31556 else => false,
31557 }) {
31558 const rt = try sema.coerceInMemoryAllowed(
31559 block,
31560 .fromInterned(dest_info.return_type),
31561 .fromInterned(src_info.return_type),
31562 dest_is_mut,
31563 target,
31564 dest_src,
31565 src_src,
31566 null,
31567 );
31568 if (rt != .ok) return .{ .fn_return_type = .{
31569 .child = try rt.dupe(sema.arena),
31570 .actual = .fromInterned(src_info.return_type),
31571 .wanted = .fromInterned(dest_info.return_type),
31572 } };
3154931573 }
3155031574 }
3155131575
3155231576 const params_len = params_len: {
3155331577 if (dest_info.param_types.len != src_info.param_types.len) {
31554 return InMemoryCoercionResult{ .fn_param_count = .{
31578 return .{ .fn_param_count = .{
3155531579 .actual = src_info.param_types.len,
3155631580 .wanted = dest_info.param_types.len,
3155731581 } };
3155831582 }
3155931583
3156031584 if (dest_info.noalias_bits != src_info.noalias_bits) {
31561 return InMemoryCoercionResult{ .fn_param_noalias = .{
31585 return .{ .fn_param_noalias = .{
3156231586 .actual = src_info.noalias_bits,
3156331587 .wanted = dest_info.noalias_bits,
3156431588 } };
......@@ -31568,14 +31592,15 @@ fn coerceInMemoryAllowedFns(
3156831592 };
3156931593
3157031594 for (0..params_len) |param_i| {
31571 const dest_param_ty = Type.fromInterned(dest_info.param_types.get(ip)[param_i]);
31572 const src_param_ty = Type.fromInterned(src_info.param_types.get(ip)[param_i]);
31595 const dest_param_ty: Type = .fromInterned(dest_info.param_types.get(ip)[param_i]);
31596 const src_param_ty: Type = .fromInterned(src_info.param_types.get(ip)[param_i]);
3157331597
31574 const param_i_small: u5 = @intCast(param_i);
31575 if (dest_info.paramIsComptime(param_i_small) != src_info.paramIsComptime(param_i_small)) {
31576 return InMemoryCoercionResult{ .fn_param_comptime = .{
31598 const src_is_comptime = src_info.paramIsComptime(@intCast(param_i));
31599 const dest_is_comptime = dest_info.paramIsComptime(@intCast(param_i));
31600 if (src_is_comptime != dest_is_comptime) {
31601 return .{ .fn_param_comptime = .{
3157731602 .index = param_i,
31578 .wanted = dest_info.paramIsComptime(param_i_small),
31603 .wanted = dest_is_comptime,
3157931604 } };
3158031605 }
3158131606
......@@ -31583,9 +31608,9 @@ fn coerceInMemoryAllowedFns(
3158331608 .generic_poison_type => {},
3158431609 else => {
3158531610 // Note: Cast direction is reversed here.
31586 const param = try sema.coerceInMemoryAllowed(block, src_param_ty, dest_param_ty, false, target, dest_src, src_src, null);
31611 const param = try sema.coerceInMemoryAllowed(block, src_param_ty, dest_param_ty, dest_is_mut, target, dest_src, src_src, null);
3158731612 if (param != .ok) {
31588 return InMemoryCoercionResult{ .fn_param = .{
31613 return .{ .fn_param = .{
3158931614 .child = try param.dupe(sema.arena),
3159031615 .actual = src_param_ty,
3159131616 .wanted = dest_param_ty,
......@@ -31644,6 +31669,7 @@ fn coerceInMemoryAllowedPtrs(
3164431669 src_ty: Type,
3164531670 dest_ptr_ty: Type,
3164631671 src_ptr_ty: Type,
31672 /// If set, the coercion must be valid in both directions.
3164731673 dest_is_mut: bool,
3164831674 target: std.Target,
3164931675 dest_src: LazySrcLoc,
......@@ -31663,21 +31689,34 @@ fn coerceInMemoryAllowedPtrs(
3166331689 } };
3166431690 }
3166531691
31666 const ok_cv_qualifiers =
31667 (!src_info.flags.is_const or dest_info.flags.is_const) and
31668 (!src_info.flags.is_volatile or dest_info.flags.is_volatile);
31692 const ok_const = src_info.flags.is_const == dest_info.flags.is_const or
31693 (!dest_is_mut and dest_info.flags.is_const);
3166931694
31670 if (!ok_cv_qualifiers) {
31671 return InMemoryCoercionResult{ .ptr_qualifiers = .{
31672 .actual_const = src_info.flags.is_const,
31673 .wanted_const = dest_info.flags.is_const,
31674 .actual_volatile = src_info.flags.is_volatile,
31675 .wanted_volatile = dest_info.flags.is_volatile,
31676 } };
31677 }
31695 if (!ok_const) return .{ .ptr_const = .{
31696 .actual = src_ty,
31697 .wanted = dest_ty,
31698 } };
31699
31700 const ok_volatile = src_info.flags.is_volatile == dest_info.flags.is_volatile or
31701 (!dest_is_mut and dest_info.flags.is_volatile);
31702
31703 if (!ok_volatile) return .{ .ptr_volatile = .{
31704 .actual = src_ty,
31705 .wanted = dest_ty,
31706 } };
31707
31708 const dest_allowzero = dest_ty.ptrAllowsZero(zcu);
31709 const src_allowzero = src_ty.ptrAllowsZero(zcu);
31710 const ok_allowzero = src_allowzero == dest_allowzero or
31711 (!dest_is_mut and dest_allowzero);
31712
31713 if (!ok_allowzero) return .{ .ptr_allowzero = .{
31714 .actual = src_ty,
31715 .wanted = dest_ty,
31716 } };
3167831717
3167931718 if (dest_info.flags.address_space != src_info.flags.address_space) {
31680 return InMemoryCoercionResult{ .ptr_addrspace = .{
31719 return .{ .ptr_addrspace = .{
3168131720 .actual = src_info.flags.address_space,
3168231721 .wanted = dest_info.flags.address_space,
3168331722 } };
......@@ -31685,8 +31724,28 @@ fn coerceInMemoryAllowedPtrs(
3168531724
3168631725 const dest_child = Type.fromInterned(dest_info.child);
3168731726 const src_child = Type.fromInterned(src_info.child);
31688 const child = try sema.coerceInMemoryAllowed(block, dest_child, src_child, !dest_info.flags.is_const, target, dest_src, src_src, null);
31689 if (child != .ok) allow: {
31727 const child = try sema.coerceInMemoryAllowed(
31728 block,
31729 dest_child,
31730 src_child,
31731 // We must also include `dest_is_mut`.
31732 // Otherwise, this code is valid:
31733 //
31734 // const b: B = ...;
31735 // var pa: *const A = undefined;
31736 // const ppa: **const A = &pa;
31737 // const ppb: **const B = ppa; // <-- this is what that allows
31738 // ppb.* = &b;
31739 // const a: A = pa.*;
31740 //
31741 // ...effectively performing an in-memory coercion from B to A.
31742 dest_is_mut or !dest_info.flags.is_const,
31743 target,
31744 dest_src,
31745 src_src,
31746 null,
31747 );
31748 if (child != .ok and !dest_is_mut) allow: {
3169031749 // As a special case, we also allow coercing `*[n:s]T` to `*[n]T`, akin to dropping the sentinel from a slice.
3169131750 // `*[n:s]T` cannot coerce in memory to `*[n]T` since they have different sizes.
3169231751 if (src_child.zigTypeTag(zcu) == .array and dest_child.zigTypeTag(zcu) == .array and
......@@ -31695,30 +31754,17 @@ fn coerceInMemoryAllowedPtrs(
3169531754 {
3169631755 break :allow;
3169731756 }
31698 return InMemoryCoercionResult{ .ptr_child = .{
31757 return .{ .ptr_child = .{
3169931758 .child = try child.dupe(sema.arena),
31700 .actual = Type.fromInterned(src_info.child),
31701 .wanted = Type.fromInterned(dest_info.child),
31702 } };
31703 }
31704
31705 const dest_allow_zero = dest_ty.ptrAllowsZero(zcu);
31706 const src_allow_zero = src_ty.ptrAllowsZero(zcu);
31707
31708 const ok_allows_zero = (dest_allow_zero and
31709 (src_allow_zero or !dest_is_mut)) or
31710 (!dest_allow_zero and !src_allow_zero);
31711 if (!ok_allows_zero) {
31712 return InMemoryCoercionResult{ .ptr_allowzero = .{
31713 .actual = src_ty,
31714 .wanted = dest_ty,
31759 .actual = .fromInterned(src_info.child),
31760 .wanted = .fromInterned(dest_info.child),
3171531761 } };
3171631762 }
3171731763
3171831764 if (src_info.packed_offset.host_size != dest_info.packed_offset.host_size or
3171931765 src_info.packed_offset.bit_offset != dest_info.packed_offset.bit_offset)
3172031766 {
31721 return InMemoryCoercionResult{ .ptr_bit_range = .{
31767 return .{ .ptr_bit_range = .{
3172231768 .actual_host = src_info.packed_offset.host_size,
3172331769 .wanted_host = dest_info.packed_offset.host_size,
3172431770 .actual_offset = src_info.packed_offset.bit_offset,
......@@ -31726,11 +31772,20 @@ fn coerceInMemoryAllowedPtrs(
3172631772 } };
3172731773 }
3172831774
31729 const ok_sent = dest_info.sentinel == .none or src_info.flags.size == .C or
31730 (src_info.sentinel != .none and
31731 dest_info.sentinel == try zcu.intern_pool.getCoerced(sema.gpa, pt.tid, src_info.sentinel, dest_info.child));
31732 if (!ok_sent) {
31733 return InMemoryCoercionResult{ .ptr_sentinel = .{
31775 const sentinel_ok = ok: {
31776 const ss = src_info.sentinel;
31777 const ds = dest_info.sentinel;
31778 if (ss == .none and ds == .none) break :ok true;
31779 if (ss != .none and ds != .none) {
31780 if (ds == try zcu.intern_pool.getCoerced(sema.gpa, pt.tid, ss, dest_info.child)) break :ok true;
31781 }
31782 if (src_info.flags.size == .C) break :ok true;
31783 if (!dest_is_mut and dest_info.sentinel == .none) break :ok true;
31784 break :ok false;
31785 };
31786
31787 if (!sentinel_ok) {
31788 return .{ .ptr_sentinel = .{
3173431789 .actual = switch (src_info.sentinel) {
3173531790 .none => Value.@"unreachable",
3173631791 else => Value.fromInterned(src_info.sentinel),
......@@ -31760,7 +31815,7 @@ fn coerceInMemoryAllowedPtrs(
3176031815 else
3176131816 try Type.fromInterned(dest_info.child).abiAlignmentSema(pt);
3176231817
31763 if (dest_align.compare(.gt, src_align)) {
31818 if (dest_align.compare(if (dest_is_mut) .neq else .gt, src_align)) {
3176431819 return InMemoryCoercionResult{ .ptr_alignment = .{
3176531820 .actual = src_align,
3176631821 .wanted = dest_align,
......@@ -32252,19 +32307,23 @@ fn checkPtrAttributes(sema: *Sema, dest_ty: Type, inst_ty: Type, in_memory_resul
3225232307 (Type.fromInterned(inst_info.child).arrayLen(zcu) == 0 and dest_info.sentinel == .none and dest_info.flags.size != .C and dest_info.flags.size != .Many))) or
3225332308 (Type.fromInterned(inst_info.child).isTuple(zcu) and Type.fromInterned(inst_info.child).structFieldCount(zcu) == 0);
3225432309
32255 const ok_cv_qualifiers =
32256 ((!inst_info.flags.is_const or dest_info.flags.is_const) or len0) and
32257 (!inst_info.flags.is_volatile or dest_info.flags.is_volatile);
32258
32259 if (!ok_cv_qualifiers) {
32260 in_memory_result.* = .{ .ptr_qualifiers = .{
32261 .actual_const = inst_info.flags.is_const,
32262 .wanted_const = dest_info.flags.is_const,
32263 .actual_volatile = inst_info.flags.is_volatile,
32264 .wanted_volatile = dest_info.flags.is_volatile,
32310 const ok_const = (!inst_info.flags.is_const or dest_info.flags.is_const) or len0;
32311 const ok_volatile = !inst_info.flags.is_volatile or dest_info.flags.is_volatile;
32312 if (!ok_const) {
32313 in_memory_result.* = .{ .ptr_const = .{
32314 .actual = inst_ty,
32315 .wanted = dest_ty,
3226532316 } };
3226632317 return false;
3226732318 }
32319 if (!ok_volatile) {
32320 in_memory_result.* = .{ .ptr_volatile = .{
32321 .actual = inst_ty,
32322 .wanted = dest_ty,
32323 } };
32324 return false;
32325 }
32326
3226832327 if (dest_info.flags.address_space != inst_info.flags.address_space) {
3226932328 in_memory_result.* = .{ .ptr_addrspace = .{
3227032329 .actual = inst_info.flags.address_space,
......@@ -35441,11 +35500,11 @@ fn resolvePeerTypesInner(
3544135500 .peer_idx_b = i,
3544235501 } };
3544335502 // ty -> cur_ty
35444 if (.ok == try sema.coerceInMemoryAllowedFns(block, cur_ty, ty, target, src, src)) {
35503 if (.ok == try sema.coerceInMemoryAllowedFns(block, cur_ty, ty, false, target, src, src)) {
3544535504 continue;
3544635505 }
3544735506 // cur_ty -> ty
35448 if (.ok == try sema.coerceInMemoryAllowedFns(block, ty, cur_ty, target, src, src)) {
35507 if (.ok == try sema.coerceInMemoryAllowedFns(block, ty, cur_ty, false, target, src, src)) {
3544935508 opt_cur_ty = ty;
3545035509 continue;
3545135510 }
......@@ -35834,12 +35893,12 @@ fn resolvePairInMemoryCoercible(sema: *Sema, block: *Block, src: LazySrcLoc, ty_
3583435893 const target = sema.pt.zcu.getTarget();
3583535894
3583635895 // ty_b -> ty_a
35837 if (.ok == try sema.coerceInMemoryAllowed(block, ty_a, ty_b, true, target, src, src, null)) {
35896 if (.ok == try sema.coerceInMemoryAllowed(block, ty_a, ty_b, false, target, src, src, null)) {
3583835897 return ty_a;
3583935898 }
3584035899
3584135900 // ty_a -> ty_b
35842 if (.ok == try sema.coerceInMemoryAllowed(block, ty_b, ty_a, true, target, src, src, null)) {
35901 if (.ok == try sema.coerceInMemoryAllowed(block, ty_b, ty_a, false, target, src, src, null)) {
3584335902 return ty_b;
3584435903 }
3584535904
src/clang.zig+2-2
......@@ -2224,8 +2224,8 @@ pub const ErrorMsg = extern struct {
22242224
22252225pub const LoadFromCommandLine = ZigClangLoadFromCommandLine;
22262226extern fn ZigClangLoadFromCommandLine(
2227 args_begin: [*]?[*]const u8,
2228 args_end: [*]?[*]const u8,
2227 args_begin: [*]?[*:0]const u8,
2228 args_end: [*]?[*:0]const u8,
22292229 errors_ptr: *[*]ErrorMsg,
22302230 errors_len: *usize,
22312231 resources_path: [*:0]const u8,
src/link/Coff.zig+1-1
......@@ -997,7 +997,7 @@ fn markRelocsDirtyByAddress(coff: *Coff, addr: u32) void {
997997 }
998998}
999999
1000fn resolveRelocs(coff: *Coff, atom_index: Atom.Index, relocs: []*const Relocation, code: []u8, image_base: u64) void {
1000fn resolveRelocs(coff: *Coff, atom_index: Atom.Index, relocs: []const *const Relocation, code: []u8, image_base: u64) void {
10011001 log.debug("relocating '{s}'", .{coff.getAtom(atom_index).getName(coff)});
10021002 for (relocs) |reloc| {
10031003 reloc.resolve(atom_index, code, image_base, coff);
src/translate_c.zig+2-2
......@@ -79,8 +79,8 @@ pub const Context = struct {
7979
8080pub fn translate(
8181 gpa: mem.Allocator,
82 args_begin: [*]?[*]const u8,
83 args_end: [*]?[*]const u8,
82 args_begin: [*]?[*:0]const u8,
83 args_end: [*]?[*:0]const u8,
8484 errors: *std.zig.ErrorBundle,
8585 resources_path: [*:0]const u8,
8686) !std.zig.Ast {
test/cases/compile_errors/implicit_cast_between_C_pointer_and_Zig_pointer-bad_const-align-child.zig+1-1
......@@ -38,7 +38,7 @@ export fn f() void {
3838// :8:18: error: expected type '*u8', found '[*c]const u8'
3939// :8:18: note: cast discards const qualifier
4040// :13:19: error: expected type '*u32', found '[*c]u8'
41// :13:19: note: pointer type child 'u8' cannot cast into pointer type child 'u32'
41// :13:19: note: '[*c]u8' could have null values which are illegal in type '*u32'
4242// :18:22: error: expected type '[*c]u32', found '*align(1) u32'
4343// :18:22: note: pointer alignment '1' cannot cast into pointer alignment '4'
4444// :23:21: error: expected type '[*c]u8', found '*const u8'
test/cases/compile_errors/implicit_casting_C_pointers_which_would_mess_up_null_semantics.zig+5-6
......@@ -13,7 +13,7 @@ export fn entry2() void {
1313 var slice: []u8 = &buf;
1414 var opt_many_ptr: [*]u8 = slice.ptr;
1515 var ptr_opt_many_ptr = &opt_many_ptr;
16 var c_ptr: [*c][*c]const u8 = ptr_opt_many_ptr;
16 var c_ptr: [*c][*c]u8 = ptr_opt_many_ptr;
1717 _ = &slice;
1818 _ = &ptr_opt_many_ptr;
1919 _ = &c_ptr;
......@@ -24,8 +24,7 @@ export fn entry2() void {
2424// target=native
2525//
2626// :6:24: error: expected type '*const [*]const u8', found '[*c]const [*c]const u8'
27// :6:24: note: pointer type child '[*c]const u8' cannot cast into pointer type child '[*]const u8'
28// :6:24: note: '[*c]const u8' could have null values which are illegal in type '[*]const u8'
29// :16:35: error: expected type '[*c][*c]const u8', found '*[*]u8'
30// :16:35: note: pointer type child '[*]u8' cannot cast into pointer type child '[*c]const u8'
31// :16:35: note: mutable '[*]u8' allows illegal null values stored to type '[*c]const u8'
27// :6:24: note: '[*c]const [*c]const u8' could have null values which are illegal in type '*const [*]const u8'
28// :16:29: error: expected type '[*c][*c]u8', found '*[*]u8'
29// :16:29: note: pointer type child '[*]u8' cannot cast into pointer type child '[*c]u8'
30// :16:29: note: mutable '[*c]u8' would allow illegal null values stored to type '[*]u8'
test/cases/compile_errors/invalid_pointer_coercions.zig created+77
......@@ -0,0 +1,77 @@
1//! This file contains pointer coercions which are invalid because the element types are only
2//! in-memory coercible *in one direction*. When casting a mutable pointer, the element type
3//! must coerce in both directions for the pointer to coerce. Otherwise, you could do something
4//! like this, where `A` coerces to `B` but not vice-versa:
5//!
6//! ```
7//! var x: A = undefined;
8//! const p: *B = &x; // `*A` -> `*B`
9//! p.* = some_b;
10//! const some_b_as_a = x;
11//! ```
12
13export fn error_set_to_larger() void {
14 var x: error{Foo} = undefined;
15 _ = @as(*const error{ Foo, Bar }, &x); // this is ok
16 _ = @as(*error{ Foo, Bar }, &x); // compile error
17}
18
19export fn error_set_to_anyerror() void {
20 var x: error{Foo} = undefined;
21 _ = @as(*const anyerror, &x); // this is ok
22 _ = @as(*anyerror, &x); // compile error
23}
24
25export fn error_union_to_anyerror_union() void {
26 var x: error{Foo}!u32 = undefined;
27 _ = @as(*const anyerror!u32, &x); // this is ok
28 _ = @as(*anyerror!u32, &x); // compile error
29}
30
31export fn ptr_to_const_ptr() void {
32 var x: *u32 = undefined;
33 _ = @as(*const *const u32, &x); // this is ok
34 _ = @as(**const u32, &x); // compile error
35}
36
37export fn ptr_to_allowzero_ptr() void {
38 var x: *u32 = undefined;
39 _ = @as(*const *allowzero u32, &x); // this is ok
40 _ = @as(**allowzero u32, &x); // compile error
41}
42
43export fn ptr_to_volatile_ptr() void {
44 var x: *u32 = undefined;
45 _ = @as(*const *volatile u32, &x); // this is ok
46 _ = @as(**volatile u32, &x); // compile error
47}
48
49export fn ptr_to_underaligned_ptr() void {
50 var x: *u32 = undefined;
51 _ = @as(*const *align(1) u32, &x); // this is ok
52 _ = @as(**align(1) u32, &x); // compile error
53}
54
55// error
56//
57// :16:33: error: expected type '*error{Foo,Bar}', found '*error{Foo}'
58// :16:33: note: pointer type child 'error{Foo}' cannot cast into pointer type child 'error{Foo,Bar}'
59// :16:33: note: 'error.Bar' not a member of destination error set
60// :22:24: error: expected type '*anyerror', found '*error{Foo}'
61// :22:24: note: pointer type child 'error{Foo}' cannot cast into pointer type child 'anyerror'
62// :22:24: note: global error set cannot cast into a smaller set
63// :28:28: error: expected type '*anyerror!u32', found '*error{Foo}!u32'
64// :28:28: note: pointer type child 'error{Foo}!u32' cannot cast into pointer type child 'anyerror!u32'
65// :28:28: note: global error set cannot cast into a smaller set
66// :34:26: error: expected type '**const u32', found '**u32'
67// :34:26: note: pointer type child '*u32' cannot cast into pointer type child '*const u32'
68// :34:26: note: mutable '*const u32' would allow illegal const pointers stored to type '*u32'
69// :40:30: error: expected type '**allowzero u32', found '**u32'
70// :40:30: note: pointer type child '*u32' cannot cast into pointer type child '*allowzero u32'
71// :40:30: note: mutable '*allowzero u32' would allow illegal null values stored to type '*u32'
72// :46:29: error: expected type '**volatile u32', found '**u32'
73// :46:29: note: pointer type child '*u32' cannot cast into pointer type child '*volatile u32'
74// :46:29: note: mutable '*volatile u32' would allow illegal volatile pointers stored to type '*u32'
75// :52:29: error: expected type '**align(1) u32', found '**u32'
76// :52:29: note: pointer type child '*u32' cannot cast into pointer type child '*align(1) u32'
77// :52:29: note: pointer alignment '4' cannot cast into pointer alignment '1'
test/cases/compile_errors/use_implicit_casts_to_assign_null_to_non-nullable_pointer.zig+1-1
......@@ -12,4 +12,4 @@ export fn entry() void {
1212//
1313// :4:24: error: expected type '*?*i32', found '**i32'
1414// :4:24: note: pointer type child '*i32' cannot cast into pointer type child '?*i32'
15// :4:24: note: mutable '*i32' allows illegal null values stored to type '?*i32'
15// :4:24: note: mutable '?*i32' would allow illegal null values stored to type '*i32'