Skip to content

Commit 285e2f6

Browse files
committed
disallow C pointers to non-C-ABI-compatible element types
See #1059
1 parent 0abe6d6 commit 285e2f6

File tree

4 files changed

+16
-2
lines changed

4 files changed

+16
-2
lines changed

src/analyze.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1469,7 +1469,7 @@ static bool type_allowed_in_packed_struct(ZigType *type_entry) {
14691469
zig_unreachable();
14701470
}
14711471

1472-
static bool type_allowed_in_extern(CodeGen *g, ZigType *type_entry) {
1472+
bool type_allowed_in_extern(CodeGen *g, ZigType *type_entry) {
14731473
switch (type_entry->id) {
14741474
case ZigTypeIdInvalid:
14751475
zig_unreachable();

src/analyze.hpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ void find_libc_include_path(CodeGen *g);
4444
void find_libc_lib_path(CodeGen *g);
4545

4646
bool type_has_bits(ZigType *type_entry);
47-
47+
bool type_allowed_in_extern(CodeGen *g, ZigType *type_entry);
4848

4949
ImportTableEntry *add_source_file(CodeGen *g, PackageTableEntry *package, Buf *abs_full_path, Buf *source_code);
5050

src/ir.cpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21145,6 +21145,10 @@ static IrInstruction *ir_analyze_instruction_ptr_type(IrAnalyze *ira, IrInstruct
2114521145
} else if (child_type->id == ZigTypeIdOpaque && instruction->ptr_len == PtrLenUnknown) {
2114621146
ir_add_error(ira, &instruction->base, buf_sprintf("unknown-length pointer to opaque"));
2114721147
return ira->codegen->invalid_instruction;
21148+
} else if (instruction->ptr_len == PtrLenC && !type_allowed_in_extern(ira->codegen, child_type)) {
21149+
ir_add_error(ira, &instruction->base,
21150+
buf_sprintf("C pointers cannot point to non-C-ABI-compatible type '%s'", buf_ptr(&child_type->name)));
21151+
return ira->codegen->invalid_instruction;
2114821152
}
2114921153

2115021154
uint32_t align_bytes;

test/compile_errors.zig

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,16 @@
11
const tests = @import("tests.zig");
22

33
pub fn addCases(cases: *tests.CompileErrorContext) void {
4+
cases.addTest(
5+
"C pointer pointing to non C ABI compatible type",
6+
\\const Foo = struct {};
7+
\\export fn entry() [*c]Foo {
8+
\\ return undefined;
9+
\\}
10+
,
11+
".tmp_source.zig:2:19: error: C pointers cannot point to non-C-ABI-compatible type 'Foo'",
12+
);
13+
414
cases.addTest(
515
"@truncate undefined value",
616
\\export fn entry() void {

0 commit comments

Comments
 (0)