authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-08-25 04:50:51-04:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2018-08-25 04:50:51-04:00
log4003cd4747019d79ff50aaa22415d2d3dfc15cf4
tree1f77690a5fb7ccbef75bcab9c8c1e008ef3c5068
parentbf1f91595d4d3b5911632c671ef16e44d70dc9a6
parent815950996dcc92ac6ac285f2005dbac51b9cb6f8
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

Merge pull request #1406 from ziglang/macos-stack-traces

MacOS stack traces closes #1365

16 files changed, 1389 insertions(+), 573 deletions(-)

example/shared_library/mathtest.zig+9
......@@ -1,3 +1,12 @@
1// TODO Remove this workaround
2comptime {
3 const builtin = @import("builtin");
4 if (builtin.os == builtin.Os.macosx) {
5 @export("__mh_execute_header", _mh_execute_header, builtin.GlobalLinkage.Weak);
6 }
7}
8var _mh_execute_header = extern struct {x: usize}{.x = 0};
9
110export fn add(a: i32, b: i32) i32 {
211 return a + b;
312}
src/analyze.cpp+129-85
......@@ -19,12 +19,12 @@
1919
2020static const size_t default_backward_branch_quota = 1000;
2121
22static void resolve_enum_type(CodeGen *g, TypeTableEntry *enum_type);
23static void resolve_struct_type(CodeGen *g, TypeTableEntry *struct_type);
22static Error resolve_enum_type(CodeGen *g, TypeTableEntry *enum_type);
23static Error resolve_struct_type(CodeGen *g, TypeTableEntry *struct_type);
2424
25static void resolve_struct_zero_bits(CodeGen *g, TypeTableEntry *struct_type);
26static void resolve_enum_zero_bits(CodeGen *g, TypeTableEntry *enum_type);
27static void resolve_union_zero_bits(CodeGen *g, TypeTableEntry *union_type);
25static Error ATTRIBUTE_MUST_USE resolve_struct_zero_bits(CodeGen *g, TypeTableEntry *struct_type);
26static Error ATTRIBUTE_MUST_USE resolve_enum_zero_bits(CodeGen *g, TypeTableEntry *enum_type);
27static Error ATTRIBUTE_MUST_USE resolve_union_zero_bits(CodeGen *g, TypeTableEntry *union_type);
2828static void analyze_fn_body(CodeGen *g, FnTableEntry *fn_table_entry);
2929
3030ErrorMsg *add_node_error(CodeGen *g, AstNode *node, Buf *msg) {
......@@ -370,15 +370,20 @@ uint64_t type_size_bits(CodeGen *g, TypeTableEntry *type_entry) {
370370 return LLVMSizeOfTypeInBits(g->target_data_ref, type_entry->type_ref);
371371}
372372
373bool type_is_copyable(CodeGen *g, TypeTableEntry *type_entry) {
374 type_ensure_zero_bits_known(g, type_entry);
373Result<bool> type_is_copyable(CodeGen *g, TypeTableEntry *type_entry) {
374 Error err;
375 if ((err = type_ensure_zero_bits_known(g, type_entry)))
376 return err;
377
375378 if (!type_has_bits(type_entry))
376379 return true;
377380
378381 if (!handle_is_ptr(type_entry))
379382 return true;
380383
381 ensure_complete_type(g, type_entry);
384 if ((err = ensure_complete_type(g, type_entry)))
385 return err;
386
382387 return type_entry->is_copyable;
383388}
384389
......@@ -447,7 +452,7 @@ TypeTableEntry *get_pointer_to_type_extra(CodeGen *g, TypeTableEntry *child_type
447452 }
448453 }
449454
450 type_ensure_zero_bits_known(g, child_type);
455 assertNoError(type_ensure_zero_bits_known(g, child_type));
451456
452457 TypeTableEntry *entry = new_type_table_entry(TypeTableEntryIdPointer);
453458 entry->is_copyable = true;
......@@ -554,11 +559,11 @@ TypeTableEntry *get_optional_type(CodeGen *g, TypeTableEntry *child_type) {
554559 TypeTableEntry *entry = child_type->optional_parent;
555560 return entry;
556561 } else {
557 ensure_complete_type(g, child_type);
562 assertNoError(ensure_complete_type(g, child_type));
558563
559564 TypeTableEntry *entry = new_type_table_entry(TypeTableEntryIdOptional);
560565 assert(child_type->type_ref || child_type->zero_bits);
561 entry->is_copyable = type_is_copyable(g, child_type);
566 entry->is_copyable = type_is_copyable(g, child_type).unwrap();
562567
563568 buf_resize(&entry->name, 0);
564569 buf_appendf(&entry->name, "?%s", buf_ptr(&child_type->name));
......@@ -650,7 +655,7 @@ TypeTableEntry *get_error_union_type(CodeGen *g, TypeTableEntry *err_set_type, T
650655 TypeTableEntry *entry = new_type_table_entry(TypeTableEntryIdErrorUnion);
651656 entry->is_copyable = true;
652657 assert(payload_type->di_type);
653 ensure_complete_type(g, payload_type);
658 assertNoError(ensure_complete_type(g, payload_type));
654659
655660 buf_resize(&entry->name, 0);
656661 buf_appendf(&entry->name, "%s!%s", buf_ptr(&err_set_type->name), buf_ptr(&payload_type->name));
......@@ -739,7 +744,7 @@ TypeTableEntry *get_array_type(CodeGen *g, TypeTableEntry *child_type, uint64_t
739744 return entry;
740745 }
741746
742 ensure_complete_type(g, child_type);
747 assertNoError(ensure_complete_type(g, child_type));
743748
744749 TypeTableEntry *entry = new_type_table_entry(TypeTableEntryIdArray);
745750 entry->zero_bits = (array_size == 0) || child_type->zero_bits;
......@@ -1050,13 +1055,13 @@ TypeTableEntry *get_ptr_to_stack_trace_type(CodeGen *g) {
10501055}
10511056
10521057TypeTableEntry *get_fn_type(CodeGen *g, FnTypeId *fn_type_id) {
1058 Error err;
10531059 auto table_entry = g->fn_type_table.maybe_get(fn_type_id);
10541060 if (table_entry) {
10551061 return table_entry->value;
10561062 }
10571063 if (fn_type_id->return_type != nullptr) {
1058 ensure_complete_type(g, fn_type_id->return_type);
1059 if (type_is_invalid(fn_type_id->return_type))
1064 if ((err = ensure_complete_type(g, fn_type_id->return_type)))
10601065 return g->builtin_types.entry_invalid;
10611066 assert(fn_type_id->return_type->id != TypeTableEntryIdOpaque);
10621067 } else {
......@@ -1172,8 +1177,7 @@ TypeTableEntry *get_fn_type(CodeGen *g, FnTypeId *fn_type_id) {
11721177 gen_param_info->src_index = i;
11731178 gen_param_info->gen_index = SIZE_MAX;
11741179
1175 ensure_complete_type(g, type_entry);
1176 if (type_is_invalid(type_entry))
1180 if ((err = ensure_complete_type(g, type_entry)))
11771181 return g->builtin_types.entry_invalid;
11781182
11791183 if (type_has_bits(type_entry)) {
......@@ -1493,6 +1497,7 @@ TypeTableEntry *get_auto_err_set_type(CodeGen *g, FnTableEntry *fn_entry) {
14931497static TypeTableEntry *analyze_fn_type(CodeGen *g, AstNode *proto_node, Scope *child_scope, FnTableEntry *fn_entry) {
14941498 assert(proto_node->type == NodeTypeFnProto);
14951499 AstNodeFnProto *fn_proto = &proto_node->data.fn_proto;
1500 Error err;
14961501
14971502 FnTypeId fn_type_id = {0};
14981503 init_fn_type_id(&fn_type_id, proto_node, proto_node->data.fn_proto.params.length);
......@@ -1550,7 +1555,8 @@ static TypeTableEntry *analyze_fn_type(CodeGen *g, AstNode *proto_node, Scope *c
15501555 return g->builtin_types.entry_invalid;
15511556 }
15521557 if (!calling_convention_allows_zig_types(fn_type_id.cc)) {
1553 type_ensure_zero_bits_known(g, type_entry);
1558 if ((err = type_ensure_zero_bits_known(g, type_entry)))
1559 return g->builtin_types.entry_invalid;
15541560 if (!type_has_bits(type_entry)) {
15551561 add_node_error(g, param_node->data.param_decl.type,
15561562 buf_sprintf("parameter of type '%s' has 0 bits; not allowed in function with calling convention '%s'",
......@@ -1598,7 +1604,8 @@ static TypeTableEntry *analyze_fn_type(CodeGen *g, AstNode *proto_node, Scope *c
15981604 case TypeTableEntryIdUnion:
15991605 case TypeTableEntryIdFn:
16001606 case TypeTableEntryIdPromise:
1601 type_ensure_zero_bits_known(g, type_entry);
1607 if ((err = type_ensure_zero_bits_known(g, type_entry)))
1608 return g->builtin_types.entry_invalid;
16021609 if (type_requires_comptime(type_entry)) {
16031610 add_node_error(g, param_node->data.param_decl.type,
16041611 buf_sprintf("parameter of type '%s' must be declared comptime",
......@@ -1729,24 +1736,28 @@ bool type_is_invalid(TypeTableEntry *type_entry) {
17291736}
17301737
17311738
1732static void resolve_enum_type(CodeGen *g, TypeTableEntry *enum_type) {
1739static Error resolve_enum_type(CodeGen *g, TypeTableEntry *enum_type) {
17331740 assert(enum_type->id == TypeTableEntryIdEnum);
17341741
1742 if (enum_type->data.enumeration.is_invalid)
1743 return ErrorSemanticAnalyzeFail;
1744
17351745 if (enum_type->data.enumeration.complete)
1736 return;
1746 return ErrorNone;
17371747
1738 resolve_enum_zero_bits(g, enum_type);
1739 if (type_is_invalid(enum_type))
1740 return;
1748 Error err;
1749 if ((err = resolve_enum_zero_bits(g, enum_type)))
1750 return err;
17411751
17421752 AstNode *decl_node = enum_type->data.enumeration.decl_node;
17431753
17441754 if (enum_type->data.enumeration.embedded_in_current) {
17451755 if (!enum_type->data.enumeration.reported_infinite_err) {
1756 enum_type->data.enumeration.is_invalid = true;
17461757 enum_type->data.enumeration.reported_infinite_err = true;
17471758 add_node_error(g, decl_node, buf_sprintf("enum '%s' contains itself", buf_ptr(&enum_type->name)));
17481759 }
1749 return;
1760 return ErrorSemanticAnalyzeFail;
17501761 }
17511762
17521763 assert(!enum_type->data.enumeration.zero_bits_loop_flag);
......@@ -1778,7 +1789,7 @@ static void resolve_enum_type(CodeGen *g, TypeTableEntry *enum_type) {
17781789 enum_type->data.enumeration.complete = true;
17791790
17801791 if (enum_type->data.enumeration.is_invalid)
1781 return;
1792 return ErrorSemanticAnalyzeFail;
17821793
17831794 if (enum_type->zero_bits) {
17841795 enum_type->type_ref = LLVMVoidType();
......@@ -1797,7 +1808,7 @@ static void resolve_enum_type(CodeGen *g, TypeTableEntry *enum_type) {
17971808
17981809 ZigLLVMReplaceTemporary(g->dbuilder, enum_type->di_type, replacement_di_type);
17991810 enum_type->di_type = replacement_di_type;
1800 return;
1811 return ErrorNone;
18011812 }
18021813
18031814 TypeTableEntry *tag_int_type = enum_type->data.enumeration.tag_int_type;
......@@ -1815,6 +1826,7 @@ static void resolve_enum_type(CodeGen *g, TypeTableEntry *enum_type) {
18151826
18161827 ZigLLVMReplaceTemporary(g->dbuilder, enum_type->di_type, tag_di_type);
18171828 enum_type->di_type = tag_di_type;
1829 return ErrorNone;
18181830}
18191831
18201832
......@@ -1897,15 +1909,15 @@ TypeTableEntry *get_struct_type(CodeGen *g, const char *type_name, const char *f
18971909 return struct_type;
18981910}
18991911
1900static void resolve_struct_type(CodeGen *g, TypeTableEntry *struct_type) {
1912static Error resolve_struct_type(CodeGen *g, TypeTableEntry *struct_type) {
19011913 assert(struct_type->id == TypeTableEntryIdStruct);
19021914
19031915 if (struct_type->data.structure.complete)
1904 return;
1916 return ErrorNone;
19051917
1906 resolve_struct_zero_bits(g, struct_type);
1907 if (struct_type->data.structure.is_invalid)
1908 return;
1918 Error err;
1919 if ((err = resolve_struct_zero_bits(g, struct_type)))
1920 return err;
19091921
19101922 AstNode *decl_node = struct_type->data.structure.decl_node;
19111923
......@@ -1916,7 +1928,7 @@ static void resolve_struct_type(CodeGen *g, TypeTableEntry *struct_type) {
19161928 add_node_error(g, decl_node,
19171929 buf_sprintf("struct '%s' contains itself", buf_ptr(&struct_type->name)));
19181930 }
1919 return;
1931 return ErrorSemanticAnalyzeFail;
19201932 }
19211933
19221934 assert(!struct_type->data.structure.zero_bits_loop_flag);
......@@ -1943,8 +1955,7 @@ static void resolve_struct_type(CodeGen *g, TypeTableEntry *struct_type) {
19431955 TypeStructField *type_struct_field = &struct_type->data.structure.fields[i];
19441956 TypeTableEntry *field_type = type_struct_field->type_entry;
19451957
1946 ensure_complete_type(g, field_type);
1947 if (type_is_invalid(field_type)) {
1958 if ((err = ensure_complete_type(g, field_type))) {
19481959 struct_type->data.structure.is_invalid = true;
19491960 break;
19501961 }
......@@ -2026,7 +2037,7 @@ static void resolve_struct_type(CodeGen *g, TypeTableEntry *struct_type) {
20262037 struct_type->data.structure.complete = true;
20272038
20282039 if (struct_type->data.structure.is_invalid)
2029 return;
2040 return ErrorSemanticAnalyzeFail;
20302041
20312042 if (struct_type->zero_bits) {
20322043 struct_type->type_ref = LLVMVoidType();
......@@ -2045,7 +2056,7 @@ static void resolve_struct_type(CodeGen *g, TypeTableEntry *struct_type) {
20452056 0, nullptr, di_element_types, (int)debug_field_count, 0, nullptr, "");
20462057 ZigLLVMReplaceTemporary(g->dbuilder, struct_type->di_type, replacement_di_type);
20472058 struct_type->di_type = replacement_di_type;
2048 return;
2059 return ErrorNone;
20492060 }
20502061 assert(struct_type->di_type);
20512062
......@@ -2128,17 +2139,19 @@ static void resolve_struct_type(CodeGen *g, TypeTableEntry *struct_type) {
21282139
21292140 ZigLLVMReplaceTemporary(g->dbuilder, struct_type->di_type, replacement_di_type);
21302141 struct_type->di_type = replacement_di_type;
2142
2143 return ErrorNone;
21312144}
21322145
2133static void resolve_union_type(CodeGen *g, TypeTableEntry *union_type) {
2146static Error resolve_union_type(CodeGen *g, TypeTableEntry *union_type) {
21342147 assert(union_type->id == TypeTableEntryIdUnion);
21352148
21362149 if (union_type->data.unionation.complete)
2137 return;
2150 return ErrorNone;
21382151
2139 resolve_union_zero_bits(g, union_type);
2140 if (type_is_invalid(union_type))
2141 return;
2152 Error err;
2153 if ((err = resolve_union_zero_bits(g, union_type)))
2154 return err;
21422155
21432156 AstNode *decl_node = union_type->data.unionation.decl_node;
21442157
......@@ -2148,7 +2161,7 @@ static void resolve_union_type(CodeGen *g, TypeTableEntry *union_type) {
21482161 union_type->data.unionation.is_invalid = true;
21492162 add_node_error(g, decl_node, buf_sprintf("union '%s' contains itself", buf_ptr(&union_type->name)));
21502163 }
2151 return;
2164 return ErrorSemanticAnalyzeFail;
21522165 }
21532166
21542167 assert(!union_type->data.unionation.zero_bits_loop_flag);
......@@ -2179,8 +2192,7 @@ static void resolve_union_type(CodeGen *g, TypeTableEntry *union_type) {
21792192 TypeUnionField *union_field = &union_type->data.unionation.fields[i];
21802193 TypeTableEntry *field_type = union_field->type_entry;
21812194
2182 ensure_complete_type(g, field_type);
2183 if (type_is_invalid(field_type)) {
2195 if ((err = ensure_complete_type(g, field_type))) {
21842196 union_type->data.unionation.is_invalid = true;
21852197 continue;
21862198 }
......@@ -2219,7 +2231,7 @@ static void resolve_union_type(CodeGen *g, TypeTableEntry *union_type) {
22192231 union_type->data.unionation.most_aligned_union_member = most_aligned_union_member;
22202232
22212233 if (union_type->data.unionation.is_invalid)
2222 return;
2234 return ErrorSemanticAnalyzeFail;
22232235
22242236 if (union_type->zero_bits) {
22252237 union_type->type_ref = LLVMVoidType();
......@@ -2238,7 +2250,7 @@ static void resolve_union_type(CodeGen *g, TypeTableEntry *union_type) {
22382250
22392251 ZigLLVMReplaceTemporary(g->dbuilder, union_type->di_type, replacement_di_type);
22402252 union_type->di_type = replacement_di_type;
2241 return;
2253 return ErrorNone;
22422254 }
22432255
22442256 uint64_t padding_in_bits = biggest_size_in_bits - size_of_most_aligned_member_in_bits;
......@@ -2274,7 +2286,7 @@ static void resolve_union_type(CodeGen *g, TypeTableEntry *union_type) {
22742286
22752287 ZigLLVMReplaceTemporary(g->dbuilder, union_type->di_type, replacement_di_type);
22762288 union_type->di_type = replacement_di_type;
2277 return;
2289 return ErrorNone;
22782290 }
22792291
22802292 LLVMTypeRef union_type_ref;
......@@ -2293,7 +2305,7 @@ static void resolve_union_type(CodeGen *g, TypeTableEntry *union_type) {
22932305
22942306 ZigLLVMReplaceTemporary(g->dbuilder, union_type->di_type, tag_type->di_type);
22952307 union_type->di_type = tag_type->di_type;
2296 return;
2308 return ErrorNone;
22972309 } else {
22982310 union_type_ref = most_aligned_union_member->type_ref;
22992311 }
......@@ -2367,19 +2379,21 @@ static void resolve_union_type(CodeGen *g, TypeTableEntry *union_type) {
23672379
23682380 ZigLLVMReplaceTemporary(g->dbuilder, union_type->di_type, replacement_di_type);
23692381 union_type->di_type = replacement_di_type;
2382
2383 return ErrorNone;
23702384}
23712385
2372static void resolve_enum_zero_bits(CodeGen *g, TypeTableEntry *enum_type) {
2386static Error resolve_enum_zero_bits(CodeGen *g, TypeTableEntry *enum_type) {
23732387 assert(enum_type->id == TypeTableEntryIdEnum);
23742388
23752389 if (enum_type->data.enumeration.zero_bits_known)
2376 return;
2390 return ErrorNone;
23772391
23782392 if (enum_type->data.enumeration.zero_bits_loop_flag) {
23792393 add_node_error(g, enum_type->data.enumeration.decl_node,
23802394 buf_sprintf("'%s' depends on itself", buf_ptr(&enum_type->name)));
23812395 enum_type->data.enumeration.is_invalid = true;
2382 return;
2396 return ErrorSemanticAnalyzeFail;
23832397 }
23842398
23852399 enum_type->data.enumeration.zero_bits_loop_flag = true;
......@@ -2398,7 +2412,7 @@ static void resolve_enum_zero_bits(CodeGen *g, TypeTableEntry *enum_type) {
23982412 enum_type->data.enumeration.is_invalid = true;
23992413 enum_type->data.enumeration.zero_bits_loop_flag = false;
24002414 enum_type->data.enumeration.zero_bits_known = true;
2401 return;
2415 return ErrorSemanticAnalyzeFail;
24022416 }
24032417
24042418 enum_type->data.enumeration.src_field_count = field_count;
......@@ -2525,13 +2539,23 @@ static void resolve_enum_zero_bits(CodeGen *g, TypeTableEntry *enum_type) {
25252539 enum_type->data.enumeration.zero_bits_loop_flag = false;
25262540 enum_type->zero_bits = !type_has_bits(tag_int_type);
25272541 enum_type->data.enumeration.zero_bits_known = true;
2542
2543 if (enum_type->data.enumeration.is_invalid)
2544 return ErrorSemanticAnalyzeFail;
2545
2546 return ErrorNone;
25282547}
25292548
2530static void resolve_struct_zero_bits(CodeGen *g, TypeTableEntry *struct_type) {
2549static Error resolve_struct_zero_bits(CodeGen *g, TypeTableEntry *struct_type) {
25312550 assert(struct_type->id == TypeTableEntryIdStruct);
25322551
2552 Error err;
2553
2554 if (struct_type->data.structure.is_invalid)
2555 return ErrorSemanticAnalyzeFail;
2556
25332557 if (struct_type->data.structure.zero_bits_known)
2534 return;
2558 return ErrorNone;
25352559
25362560 if (struct_type->data.structure.zero_bits_loop_flag) {
25372561 // If we get here it's due to recursion. This is a design flaw in the compiler,
......@@ -2547,7 +2571,7 @@ static void resolve_struct_zero_bits(CodeGen *g, TypeTableEntry *struct_type) {
25472571 struct_type->data.structure.abi_alignment = LLVMABIAlignmentOfType(g->target_data_ref, LLVMPointerType(LLVMInt8Type(), 0));
25482572 }
25492573 }
2550 return;
2574 return ErrorNone;
25512575 }
25522576
25532577 struct_type->data.structure.zero_bits_loop_flag = true;
......@@ -2596,8 +2620,7 @@ static void resolve_struct_zero_bits(CodeGen *g, TypeTableEntry *struct_type) {
25962620 buf_sprintf("enums, not structs, support field assignment"));
25972621 }
25982622
2599 type_ensure_zero_bits_known(g, field_type);
2600 if (type_is_invalid(field_type)) {
2623 if ((err = type_ensure_zero_bits_known(g, field_type))) {
26012624 struct_type->data.structure.is_invalid = true;
26022625 continue;
26032626 }
......@@ -2634,16 +2657,27 @@ static void resolve_struct_zero_bits(CodeGen *g, TypeTableEntry *struct_type) {
26342657 struct_type->data.structure.gen_field_count = (uint32_t)gen_field_index;
26352658 struct_type->zero_bits = (gen_field_index == 0);
26362659 struct_type->data.structure.zero_bits_known = true;
2660
2661 if (struct_type->data.structure.is_invalid) {
2662 return ErrorSemanticAnalyzeFail;
2663 }
2664
2665 return ErrorNone;
26372666}
26382667
2639static void resolve_union_zero_bits(CodeGen *g, TypeTableEntry *union_type) {
2668static Error resolve_union_zero_bits(CodeGen *g, TypeTableEntry *union_type) {
26402669 assert(union_type->id == TypeTableEntryIdUnion);
26412670
2671 Error err;
2672
2673 if (union_type->data.unionation.is_invalid)
2674 return ErrorSemanticAnalyzeFail;
2675
26422676 if (union_type->data.unionation.zero_bits_known)
2643 return;
2677 return ErrorNone;
26442678
26452679 if (type_is_invalid(union_type))
2646 return;
2680 return ErrorSemanticAnalyzeFail;
26472681
26482682 if (union_type->data.unionation.zero_bits_loop_flag) {
26492683 // If we get here it's due to recursion. From this we conclude that the struct is
......@@ -2660,7 +2694,7 @@ static void resolve_union_zero_bits(CodeGen *g, TypeTableEntry *union_type) {
26602694 LLVMPointerType(LLVMInt8Type(), 0));
26612695 }
26622696 }
2663 return;
2697 return ErrorNone;
26642698 }
26652699
26662700 union_type->data.unionation.zero_bits_loop_flag = true;
......@@ -2679,7 +2713,7 @@ static void resolve_union_zero_bits(CodeGen *g, TypeTableEntry *union_type) {
26792713 union_type->data.unionation.is_invalid = true;
26802714 union_type->data.unionation.zero_bits_loop_flag = false;
26812715 union_type->data.unionation.zero_bits_known = true;
2682 return;
2716 return ErrorSemanticAnalyzeFail;
26832717 }
26842718 union_type->data.unionation.src_field_count = field_count;
26852719 union_type->data.unionation.fields = allocate<TypeUnionField>(field_count);
......@@ -2711,13 +2745,13 @@ static void resolve_union_zero_bits(CodeGen *g, TypeTableEntry *union_type) {
27112745 tag_int_type = analyze_type_expr(g, scope, enum_type_node);
27122746 if (type_is_invalid(tag_int_type)) {
27132747 union_type->data.unionation.is_invalid = true;
2714 return;
2748 return ErrorSemanticAnalyzeFail;
27152749 }
27162750 if (tag_int_type->id != TypeTableEntryIdInt) {
27172751 add_node_error(g, enum_type_node,
27182752 buf_sprintf("expected integer tag type, found '%s'", buf_ptr(&tag_int_type->name)));
27192753 union_type->data.unionation.is_invalid = true;
2720 return;
2754 return ErrorSemanticAnalyzeFail;
27212755 }
27222756 } else {
27232757 tag_int_type = get_smallest_unsigned_int_type(g, field_count - 1);
......@@ -2744,13 +2778,13 @@ static void resolve_union_zero_bits(CodeGen *g, TypeTableEntry *union_type) {
27442778 TypeTableEntry *enum_type = analyze_type_expr(g, scope, enum_type_node);
27452779 if (type_is_invalid(enum_type)) {
27462780 union_type->data.unionation.is_invalid = true;
2747 return;
2781 return ErrorSemanticAnalyzeFail;
27482782 }
27492783 if (enum_type->id != TypeTableEntryIdEnum) {
27502784 union_type->data.unionation.is_invalid = true;
27512785 add_node_error(g, enum_type_node,
27522786 buf_sprintf("expected enum tag type, found '%s'", buf_ptr(&enum_type->name)));
2753 return;
2787 return ErrorSemanticAnalyzeFail;
27542788 }
27552789 tag_type = enum_type;
27562790 abi_alignment_so_far = get_abi_alignment(g, enum_type); // this populates src_field_count
......@@ -2789,8 +2823,7 @@ static void resolve_union_zero_bits(CodeGen *g, TypeTableEntry *union_type) {
27892823 }
27902824 } else {
27912825 field_type = analyze_type_expr(g, scope, field_node->data.struct_field.type);
2792 type_ensure_zero_bits_known(g, field_type);
2793 if (type_is_invalid(field_type)) {
2826 if ((err = type_ensure_zero_bits_known(g, field_type))) {
27942827 union_type->data.unionation.is_invalid = true;
27952828 continue;
27962829 }
......@@ -2883,7 +2916,7 @@ static void resolve_union_zero_bits(CodeGen *g, TypeTableEntry *union_type) {
28832916 union_type->data.unionation.abi_alignment = abi_alignment_so_far;
28842917
28852918 if (union_type->data.unionation.is_invalid)
2886 return;
2919 return ErrorSemanticAnalyzeFail;
28872920
28882921 bool src_have_tag = decl_node->data.container_decl.auto_enum ||
28892922 decl_node->data.container_decl.init_arg_expr != nullptr;
......@@ -2905,7 +2938,7 @@ static void resolve_union_zero_bits(CodeGen *g, TypeTableEntry *union_type) {
29052938 add_node_error(g, source_node,
29062939 buf_sprintf("%s union does not support enum tag type", qual_str));
29072940 union_type->data.unionation.is_invalid = true;
2908 return;
2941 return ErrorSemanticAnalyzeFail;
29092942 }
29102943
29112944 if (create_enum_type) {
......@@ -2970,6 +3003,11 @@ static void resolve_union_zero_bits(CodeGen *g, TypeTableEntry *union_type) {
29703003 union_type->data.unionation.gen_field_count = gen_field_index;
29713004 union_type->zero_bits = (gen_field_index == 0 && (field_count < 2 || !src_have_tag));
29723005 union_type->data.unionation.zero_bits_known = true;
3006
3007 if (union_type->data.unionation.is_invalid)
3008 return ErrorSemanticAnalyzeFail;
3009
3010 return ErrorNone;
29733011}
29743012
29753013static void get_fully_qualified_decl_name_internal(Buf *buf, Scope *scope, uint8_t sep) {
......@@ -3463,13 +3501,13 @@ VariableTableEntry *add_variable(CodeGen *g, AstNode *source_node, Scope *parent
34633501 variable_entry->shadowable = false;
34643502 variable_entry->mem_slot_index = SIZE_MAX;
34653503 variable_entry->src_arg_index = SIZE_MAX;
3466 variable_entry->align_bytes = get_abi_alignment(g, value->type);
34673504
34683505 assert(name);
3469
34703506 buf_init_from_buf(&variable_entry->name, name);
34713507
3472 if (value->type->id != TypeTableEntryIdInvalid) {
3508 if (!type_is_invalid(value->type)) {
3509 variable_entry->align_bytes = get_abi_alignment(g, value->type);
3510
34733511 VariableTableEntry *existing_var = find_variable(g, parent_scope, name);
34743512 if (existing_var && !existing_var->shadowable) {
34753513 ErrorMsg *msg = add_node_error(g, source_node,
......@@ -5311,13 +5349,13 @@ ConstExprValue *create_const_arg_tuple(CodeGen *g, size_t arg_index_start, size_
53115349
53125350
53135351void init_const_undefined(CodeGen *g, ConstExprValue *const_val) {
5352 Error err;
53145353 TypeTableEntry *wanted_type = const_val->type;
53155354 if (wanted_type->id == TypeTableEntryIdArray) {
53165355 const_val->special = ConstValSpecialStatic;
53175356 const_val->data.x_array.special = ConstArraySpecialUndef;
53185357 } else if (wanted_type->id == TypeTableEntryIdStruct) {
5319 ensure_complete_type(g, wanted_type);
5320 if (type_is_invalid(wanted_type)) {
5358 if ((err = ensure_complete_type(g, wanted_type))) {
53215359 return;
53225360 }
53235361
......@@ -5350,27 +5388,33 @@ ConstExprValue *create_const_vals(size_t count) {
53505388 return vals;
53515389}
53525390
5353void ensure_complete_type(CodeGen *g, TypeTableEntry *type_entry) {
5391Error ensure_complete_type(CodeGen *g, TypeTableEntry *type_entry) {
5392 if (type_is_invalid(type_entry))
5393 return ErrorSemanticAnalyzeFail;
53545394 if (type_entry->id == TypeTableEntryIdStruct) {
53555395 if (!type_entry->data.structure.complete)
5356 resolve_struct_type(g, type_entry);
5396 return resolve_struct_type(g, type_entry);
53575397 } else if (type_entry->id == TypeTableEntryIdEnum) {
53585398 if (!type_entry->data.enumeration.complete)
5359 resolve_enum_type(g, type_entry);
5399 return resolve_enum_type(g, type_entry);
53605400 } else if (type_entry->id == TypeTableEntryIdUnion) {
53615401 if (!type_entry->data.unionation.complete)
5362 resolve_union_type(g, type_entry);
5402 return resolve_union_type(g, type_entry);
53635403 }
5404 return ErrorNone;
53645405}
53655406
5366void type_ensure_zero_bits_known(CodeGen *g, TypeTableEntry *type_entry) {
5407Error type_ensure_zero_bits_known(CodeGen *g, TypeTableEntry *type_entry) {
5408 if (type_is_invalid(type_entry))
5409 return ErrorSemanticAnalyzeFail;
53675410 if (type_entry->id == TypeTableEntryIdStruct) {
5368 resolve_struct_zero_bits(g, type_entry);
5411 return resolve_struct_zero_bits(g, type_entry);
53695412 } else if (type_entry->id == TypeTableEntryIdEnum) {
5370 resolve_enum_zero_bits(g, type_entry);
5413 return resolve_enum_zero_bits(g, type_entry);
53715414 } else if (type_entry->id == TypeTableEntryIdUnion) {
5372 resolve_union_zero_bits(g, type_entry);
5415 return resolve_union_zero_bits(g, type_entry);
53735416 }
5417 return ErrorNone;
53745418}
53755419
53765420bool ir_get_var_is_comptime(VariableTableEntry *var) {
......@@ -6213,7 +6257,7 @@ LinkLib *add_link_lib(CodeGen *g, Buf *name) {
62136257}
62146258
62156259uint32_t get_abi_alignment(CodeGen *g, TypeTableEntry *type_entry) {
6216 type_ensure_zero_bits_known(g, type_entry);
6260 assertNoError(type_ensure_zero_bits_known(g, type_entry));
62176261 if (type_entry->zero_bits) return 0;
62186262
62196263 // We need to make this function work without requiring ensure_complete_type
src/analyze.hpp+4-3
......@@ -9,6 +9,7 @@
99#define ZIG_ANALYZE_HPP
1010
1111#include "all_types.hpp"
12#include "result.hpp"
1213
1314void semantic_analyze(CodeGen *g);
1415ErrorMsg *add_node_error(CodeGen *g, AstNode *node, Buf *msg);
......@@ -88,8 +89,8 @@ void init_fn_type_id(FnTypeId *fn_type_id, AstNode *proto_node, size_t param_cou
8889AstNode *get_param_decl_node(FnTableEntry *fn_entry, size_t index);
8990FnTableEntry *scope_get_fn_if_root(Scope *scope);
9091bool type_requires_comptime(TypeTableEntry *type_entry);
91void ensure_complete_type(CodeGen *g, TypeTableEntry *type_entry);
92void type_ensure_zero_bits_known(CodeGen *g, TypeTableEntry *type_entry);
92Error ATTRIBUTE_MUST_USE ensure_complete_type(CodeGen *g, TypeTableEntry *type_entry);
93Error ATTRIBUTE_MUST_USE type_ensure_zero_bits_known(CodeGen *g, TypeTableEntry *type_entry);
9394void complete_enum(CodeGen *g, TypeTableEntry *enum_type);
9495bool ir_get_var_is_comptime(VariableTableEntry *var);
9596bool const_values_equal(ConstExprValue *a, ConstExprValue *b);
......@@ -178,7 +179,7 @@ TypeTableEntryId type_id_at_index(size_t index);
178179size_t type_id_len();
179180size_t type_id_index(TypeTableEntry *entry);
180181TypeTableEntry *get_generic_fn_type(CodeGen *g, FnTypeId *fn_type_id);
181bool type_is_copyable(CodeGen *g, TypeTableEntry *type_entry);
182Result<bool> type_is_copyable(CodeGen *g, TypeTableEntry *type_entry);
182183LinkLib *create_link_lib(Buf *name);
183184bool calling_convention_does_first_arg_return(CallingConvention cc);
184185LinkLib *add_link_lib(CodeGen *codegen, Buf *lib);
src/codegen.cpp+9-5
......@@ -5812,12 +5812,16 @@ static void do_code_gen(CodeGen *g) {
58125812
58135813 LLVMValueRef global_value;
58145814 if (var->linkage == VarLinkageExternal) {
5815 global_value = LLVMAddGlobal(g->module, var->value->type->type_ref, buf_ptr(&var->name));
5816
5817 // TODO debug info for the extern variable
5815 LLVMValueRef existing_llvm_var = LLVMGetNamedGlobal(g->module, buf_ptr(&var->name));
5816 if (existing_llvm_var) {
5817 global_value = LLVMConstBitCast(existing_llvm_var, LLVMPointerType(var->value->type->type_ref, 0));
5818 } else {
5819 global_value = LLVMAddGlobal(g->module, var->value->type->type_ref, buf_ptr(&var->name));
5820 // TODO debug info for the extern variable
58185821
5819 LLVMSetLinkage(global_value, LLVMExternalLinkage);
5820 LLVMSetAlignment(global_value, var->align_bytes);
5822 LLVMSetLinkage(global_value, LLVMExternalLinkage);
5823 LLVMSetAlignment(global_value, var->align_bytes);
5824 }
58215825 } else {
58225826 bool exported = (var->linkage == VarLinkageExport);
58235827 const char *mangled_name = buf_ptr(get_mangled_name(g, &var->name, exported));
src/ir.cpp+177-184
......@@ -8711,6 +8711,7 @@ static void update_errors_helper(CodeGen *g, ErrorTableEntry ***errors, size_t *
87118711}
87128712
87138713static TypeTableEntry *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_node, TypeTableEntry *expected_type, IrInstruction **instructions, size_t instruction_count) {
8714 Error err;
87148715 assert(instruction_count >= 1);
87158716 IrInstruction *prev_inst = instructions[0];
87168717 if (type_is_invalid(prev_inst->value.type)) {
......@@ -9172,8 +9173,7 @@ static TypeTableEntry *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_nod
91729173 if (prev_type->id == TypeTableEntryIdEnum && cur_type->id == TypeTableEntryIdUnion &&
91739174 (cur_type->data.unionation.decl_node->data.container_decl.auto_enum || cur_type->data.unionation.decl_node->data.container_decl.init_arg_expr != nullptr))
91749175 {
9175 type_ensure_zero_bits_known(ira->codegen, cur_type);
9176 if (type_is_invalid(cur_type))
9176 if ((err = type_ensure_zero_bits_known(ira->codegen, cur_type)))
91779177 return ira->codegen->builtin_types.entry_invalid;
91789178 if (cur_type->data.unionation.tag_type == prev_type) {
91799179 continue;
......@@ -9183,8 +9183,7 @@ static TypeTableEntry *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_nod
91839183 if (cur_type->id == TypeTableEntryIdEnum && prev_type->id == TypeTableEntryIdUnion &&
91849184 (prev_type->data.unionation.decl_node->data.container_decl.auto_enum || prev_type->data.unionation.decl_node->data.container_decl.init_arg_expr != nullptr))
91859185 {
9186 type_ensure_zero_bits_known(ira->codegen, prev_type);
9187 if (type_is_invalid(prev_type))
9186 if ((err = type_ensure_zero_bits_known(ira->codegen, prev_type)))
91889187 return ira->codegen->builtin_types.entry_invalid;
91899188 if (prev_type->data.unionation.tag_type == cur_type) {
91909189 prev_inst = cur_inst;
......@@ -9999,11 +9998,11 @@ static IrInstruction *ir_analyze_array_to_slice(IrAnalyze *ira, IrInstruction *s
99999998static IrInstruction *ir_analyze_enum_to_int(IrAnalyze *ira, IrInstruction *source_instr,
100009999 IrInstruction *target, TypeTableEntry *wanted_type)
1000110000{
10001 Error err;
1000210002 assert(wanted_type->id == TypeTableEntryIdInt);
1000310003
1000410004 TypeTableEntry *actual_type = target->value.type;
10005 ensure_complete_type(ira->codegen, actual_type);
10006 if (type_is_invalid(actual_type))
10005 if ((err = ensure_complete_type(ira->codegen, actual_type)))
1000710006 return ira->codegen->invalid_instruction;
1000810007
1000910008 if (wanted_type != actual_type->data.enumeration.tag_int_type) {
......@@ -10069,6 +10068,7 @@ static IrInstruction *ir_analyze_undefined_to_anything(IrAnalyze *ira, IrInstruc
1006910068static IrInstruction *ir_analyze_enum_to_union(IrAnalyze *ira, IrInstruction *source_instr,
1007010069 IrInstruction *target, TypeTableEntry *wanted_type)
1007110070{
10071 Error err;
1007210072 assert(wanted_type->id == TypeTableEntryIdUnion);
1007310073 assert(target->value.type->id == TypeTableEntryIdEnum);
1007410074
......@@ -10078,8 +10078,7 @@ static IrInstruction *ir_analyze_enum_to_union(IrAnalyze *ira, IrInstruction *so
1007810078 return ira->codegen->invalid_instruction;
1007910079 TypeUnionField *union_field = find_union_field_by_tag(wanted_type, &val->data.x_enum_tag);
1008010080 assert(union_field != nullptr);
10081 type_ensure_zero_bits_known(ira->codegen, union_field->type_entry);
10082 if (type_is_invalid(union_field->type_entry))
10081 if ((err = type_ensure_zero_bits_known(ira->codegen, union_field->type_entry)))
1008310082 return ira->codegen->invalid_instruction;
1008410083 if (!union_field->type_entry->zero_bits) {
1008510084 AstNode *field_node = wanted_type->data.unionation.decl_node->data.container_decl.fields.at(
......@@ -10169,12 +10168,12 @@ static IrInstruction *ir_analyze_widen_or_shorten(IrAnalyze *ira, IrInstruction
1016910168static IrInstruction *ir_analyze_int_to_enum(IrAnalyze *ira, IrInstruction *source_instr,
1017010169 IrInstruction *target, TypeTableEntry *wanted_type)
1017110170{
10171 Error err;
1017210172 assert(wanted_type->id == TypeTableEntryIdEnum);
1017310173
1017410174 TypeTableEntry *actual_type = target->value.type;
1017510175
10176 ensure_complete_type(ira->codegen, wanted_type);
10177 if (type_is_invalid(wanted_type))
10176 if ((err = ensure_complete_type(ira->codegen, wanted_type)))
1017810177 return ira->codegen->invalid_instruction;
1017910178
1018010179 if (actual_type != wanted_type->data.enumeration.tag_int_type) {
......@@ -10517,6 +10516,7 @@ static void report_recursive_error(IrAnalyze *ira, AstNode *source_node, ConstCa
1051710516static IrInstruction *ir_analyze_cast(IrAnalyze *ira, IrInstruction *source_instr,
1051810517 TypeTableEntry *wanted_type, IrInstruction *value)
1051910518{
10519 Error err;
1052010520 TypeTableEntry *actual_type = value->value.type;
1052110521 AstNode *source_node = source_instr->source_node;
1052210522
......@@ -10796,8 +10796,7 @@ static IrInstruction *ir_analyze_cast(IrAnalyze *ira, IrInstruction *source_inst
1079610796 if (actual_type->id == TypeTableEntryIdComptimeFloat ||
1079710797 actual_type->id == TypeTableEntryIdComptimeInt)
1079810798 {
10799 ensure_complete_type(ira->codegen, wanted_type);
10800 if (type_is_invalid(wanted_type))
10799 if ((err = ensure_complete_type(ira->codegen, wanted_type)))
1080110800 return ira->codegen->invalid_instruction;
1080210801 if (wanted_type->id == TypeTableEntryIdEnum) {
1080310802 IrInstruction *cast1 = ir_analyze_cast(ira, source_instr, wanted_type->data.enumeration.tag_int_type, value);
......@@ -10853,8 +10852,7 @@ static IrInstruction *ir_analyze_cast(IrAnalyze *ira, IrInstruction *source_inst
1085310852
1085410853 // cast from union to the enum type of the union
1085510854 if (actual_type->id == TypeTableEntryIdUnion && wanted_type->id == TypeTableEntryIdEnum) {
10856 type_ensure_zero_bits_known(ira->codegen, actual_type);
10857 if (type_is_invalid(actual_type))
10855 if ((err = type_ensure_zero_bits_known(ira->codegen, actual_type)))
1085810856 return ira->codegen->invalid_instruction;
1085910857
1086010858 if (actual_type->data.unionation.tag_type == wanted_type) {
......@@ -10867,7 +10865,9 @@ static IrInstruction *ir_analyze_cast(IrAnalyze *ira, IrInstruction *source_inst
1086710865 (wanted_type->data.unionation.decl_node->data.container_decl.auto_enum ||
1086810866 wanted_type->data.unionation.decl_node->data.container_decl.init_arg_expr != nullptr))
1086910867 {
10870 type_ensure_zero_bits_known(ira->codegen, wanted_type);
10868 if ((err = type_ensure_zero_bits_known(ira->codegen, wanted_type)))
10869 return ira->codegen->invalid_instruction;
10870
1087110871 if (wanted_type->data.unionation.tag_type == actual_type) {
1087210872 return ir_analyze_enum_to_union(ira, source_instr, value, wanted_type);
1087310873 }
......@@ -10879,7 +10879,9 @@ static IrInstruction *ir_analyze_cast(IrAnalyze *ira, IrInstruction *source_inst
1087910879 if (union_type->data.unionation.decl_node->data.container_decl.auto_enum ||
1088010880 union_type->data.unionation.decl_node->data.container_decl.init_arg_expr != nullptr)
1088110881 {
10882 type_ensure_zero_bits_known(ira->codegen, union_type);
10882 if ((err = type_ensure_zero_bits_known(ira->codegen, union_type)))
10883 return ira->codegen->invalid_instruction;
10884
1088310885 if (union_type->data.unionation.tag_type == actual_type) {
1088410886 IrInstruction *cast1 = ir_analyze_cast(ira, source_instr, union_type, value);
1088510887 if (type_is_invalid(cast1->value.type))
......@@ -10923,8 +10925,7 @@ static IrInstruction *ir_analyze_cast(IrAnalyze *ira, IrInstruction *source_inst
1092310925 types_match_const_cast_only(ira, wanted_type->data.pointer.child_type,
1092410926 actual_type, source_node, !wanted_type->data.pointer.is_const).id == ConstCastResultIdOk)
1092510927 {
10926 type_ensure_zero_bits_known(ira->codegen, actual_type);
10927 if (type_is_invalid(actual_type)) {
10928 if ((err = type_ensure_zero_bits_known(ira->codegen, actual_type))) {
1092810929 return ira->codegen->invalid_instruction;
1092910930 }
1093010931 if (!type_has_bits(actual_type)) {
......@@ -11323,6 +11324,7 @@ static bool optional_value_is_null(ConstExprValue *val) {
1132311324}
1132411325
1132511326static TypeTableEntry *ir_analyze_bin_op_cmp(IrAnalyze *ira, IrInstructionBinOp *bin_op_instruction) {
11327 Error err;
1132611328 IrInstruction *op1 = bin_op_instruction->op1->other;
1132711329 IrInstruction *op2 = bin_op_instruction->op2->other;
1132811330 AstNode *source_node = bin_op_instruction->base.source_node;
......@@ -11458,8 +11460,7 @@ static TypeTableEntry *ir_analyze_bin_op_cmp(IrAnalyze *ira, IrInstructionBinOp
1145811460 TypeTableEntry *resolved_type = ir_resolve_peer_types(ira, source_node, nullptr, instructions, 2);
1145911461 if (type_is_invalid(resolved_type))
1146011462 return resolved_type;
11461 type_ensure_zero_bits_known(ira->codegen, resolved_type);
11462 if (type_is_invalid(resolved_type))
11463 if ((err = type_ensure_zero_bits_known(ira->codegen, resolved_type)))
1146311464 return resolved_type;
1146411465
1146511466 bool operator_allowed;
......@@ -12406,6 +12407,7 @@ static TypeTableEntry *ir_analyze_instruction_bin_op(IrAnalyze *ira, IrInstructi
1240612407}
1240712408
1240812409static TypeTableEntry *ir_analyze_instruction_decl_var(IrAnalyze *ira, IrInstructionDeclVar *decl_var_instruction) {
12410 Error err;
1240912411 VariableTableEntry *var = decl_var_instruction->var;
1241012412
1241112413 IrInstruction *init_value = decl_var_instruction->init_value->other;
......@@ -12439,8 +12441,7 @@ static TypeTableEntry *ir_analyze_instruction_decl_var(IrAnalyze *ira, IrInstruc
1243912441 if (type_is_invalid(result_type)) {
1244012442 result_type = ira->codegen->builtin_types.entry_invalid;
1244112443 } else {
12442 type_ensure_zero_bits_known(ira->codegen, result_type);
12443 if (type_is_invalid(result_type)) {
12444 if ((err = type_ensure_zero_bits_known(ira->codegen, result_type))) {
1244412445 result_type = ira->codegen->builtin_types.entry_invalid;
1244512446 }
1244612447 }
......@@ -12958,6 +12959,7 @@ static VariableTableEntry *get_fn_var_by_index(FnTableEntry *fn_entry, size_t in
1295812959static IrInstruction *ir_get_var_ptr(IrAnalyze *ira, IrInstruction *instruction,
1295912960 VariableTableEntry *var)
1296012961{
12962 Error err;
1296112963 if (var->mem_slot_index != SIZE_MAX && var->owner_exec->analysis == nullptr) {
1296212964 assert(ira->codegen->errors.length != 0);
1296312965 return ira->codegen->invalid_instruction;
......@@ -13012,7 +13014,8 @@ no_mem_slot:
1301213014 instruction->scope, instruction->source_node, var);
1301313015 var_ptr_instruction->value.type = get_pointer_to_type_extra(ira->codegen, var->value->type,
1301413016 var->src_is_const, is_volatile, PtrLenSingle, var->align_bytes, 0, 0);
13015 type_ensure_zero_bits_known(ira->codegen, var->value->type);
13017 if ((err = type_ensure_zero_bits_known(ira->codegen, var->value->type)))
13018 return ira->codegen->invalid_instruction;
1301613019
1301713020 bool in_fn_scope = (scope_fn_entry(var->parent_scope) != nullptr);
1301813021 var_ptr_instruction->value.data.rh_ptr = in_fn_scope ? RuntimeHintPtrStack : RuntimeHintPtrNonStack;
......@@ -13024,6 +13027,7 @@ static TypeTableEntry *ir_analyze_fn_call(IrAnalyze *ira, IrInstructionCall *cal
1302413027 FnTableEntry *fn_entry, TypeTableEntry *fn_type, IrInstruction *fn_ref,
1302513028 IrInstruction *first_arg_ptr, bool comptime_fn_call, FnInline fn_inline)
1302613029{
13030 Error err;
1302713031 FnTypeId *fn_type_id = &fn_type->data.fn.fn_type_id;
1302813032 size_t first_arg_1_or_0 = first_arg_ptr ? 1 : 0;
1302913033
......@@ -13388,8 +13392,7 @@ static TypeTableEntry *ir_analyze_fn_call(IrAnalyze *ira, IrInstructionCall *cal
1338813392 inst_fn_type_id.return_type = specified_return_type;
1338913393 }
1339013394
13391 type_ensure_zero_bits_known(ira->codegen, specified_return_type);
13392 if (type_is_invalid(specified_return_type))
13395 if ((err = type_ensure_zero_bits_known(ira->codegen, specified_return_type)))
1339313396 return ira->codegen->builtin_types.entry_invalid;
1339413397
1339513398 if (type_requires_comptime(specified_return_type)) {
......@@ -13664,12 +13667,12 @@ static TypeTableEntry *ir_analyze_dereference(IrAnalyze *ira, IrInstructionUnOp
1366413667}
1366513668
1366613669static TypeTableEntry *ir_analyze_maybe(IrAnalyze *ira, IrInstructionUnOp *un_op_instruction) {
13670 Error err;
1366713671 IrInstruction *value = un_op_instruction->value->other;
1366813672 TypeTableEntry *type_entry = ir_resolve_type(ira, value);
1366913673 if (type_is_invalid(type_entry))
1367013674 return ira->codegen->builtin_types.entry_invalid;
13671 ensure_complete_type(ira->codegen, type_entry);
13672 if (type_is_invalid(type_entry))
13675 if ((err = ensure_complete_type(ira->codegen, type_entry)))
1367313676 return ira->codegen->builtin_types.entry_invalid;
1367413677
1367513678 switch (type_entry->id) {
......@@ -14023,6 +14026,7 @@ static TypeTableEntry *adjust_ptr_len(CodeGen *g, TypeTableEntry *ptr_type, PtrL
1402314026}
1402414027
1402514028static TypeTableEntry *ir_analyze_instruction_elem_ptr(IrAnalyze *ira, IrInstructionElemPtr *elem_ptr_instruction) {
14029 Error err;
1402614030 IrInstruction *array_ptr = elem_ptr_instruction->array_ptr->other;
1402714031 if (type_is_invalid(array_ptr->value.type))
1402814032 return ira->codegen->builtin_types.entry_invalid;
......@@ -14131,8 +14135,7 @@ static TypeTableEntry *ir_analyze_instruction_elem_ptr(IrAnalyze *ira, IrInstruc
1413114135 return ira->codegen->builtin_types.entry_invalid;
1413214136
1413314137 bool safety_check_on = elem_ptr_instruction->safety_check_on;
14134 ensure_complete_type(ira->codegen, return_type->data.pointer.child_type);
14135 if (type_is_invalid(return_type->data.pointer.child_type))
14138 if ((err = ensure_complete_type(ira->codegen, return_type->data.pointer.child_type)))
1413614139 return ira->codegen->builtin_types.entry_invalid;
1413714140
1413814141 uint64_t elem_size = type_size(ira->codegen, return_type->data.pointer.child_type);
......@@ -14352,9 +14355,10 @@ static IrInstruction *ir_analyze_container_member_access_inner(IrAnalyze *ira,
1435214355static IrInstruction *ir_analyze_container_field_ptr(IrAnalyze *ira, Buf *field_name,
1435314356 IrInstruction *source_instr, IrInstruction *container_ptr, TypeTableEntry *container_type)
1435414357{
14358 Error err;
14359
1435514360 TypeTableEntry *bare_type = container_ref_type(container_type);
14356 ensure_complete_type(ira->codegen, bare_type);
14357 if (type_is_invalid(bare_type))
14361 if ((err = ensure_complete_type(ira->codegen, bare_type)))
1435814362 return ira->codegen->invalid_instruction;
1435914363
1436014364 assert(container_ptr->value.type->id == TypeTableEntryIdPointer);
......@@ -14553,6 +14557,7 @@ static ErrorTableEntry *find_err_table_entry(TypeTableEntry *err_set_type, Buf *
1455314557}
1455414558
1455514559static TypeTableEntry *ir_analyze_instruction_field_ptr(IrAnalyze *ira, IrInstructionFieldPtr *field_ptr_instruction) {
14560 Error err;
1455614561 IrInstruction *container_ptr = field_ptr_instruction->container_ptr->other;
1455714562 if (type_is_invalid(container_ptr->value.type))
1455814563 return ira->codegen->builtin_types.entry_invalid;
......@@ -14654,8 +14659,7 @@ static TypeTableEntry *ir_analyze_instruction_field_ptr(IrAnalyze *ira, IrInstru
1465414659 ConstPtrMutComptimeConst, ptr_is_const, ptr_is_volatile);
1465514660 }
1465614661 if (child_type->id == TypeTableEntryIdEnum) {
14657 ensure_complete_type(ira->codegen, child_type);
14658 if (type_is_invalid(child_type))
14662 if ((err = ensure_complete_type(ira->codegen, child_type)))
1465914663 return ira->codegen->builtin_types.entry_invalid;
1466014664
1466114665 TypeEnumField *field = find_enum_type_field(child_type, field_name);
......@@ -14679,8 +14683,7 @@ static TypeTableEntry *ir_analyze_instruction_field_ptr(IrAnalyze *ira, IrInstru
1467914683 (child_type->data.unionation.decl_node->data.container_decl.init_arg_expr != nullptr ||
1468014684 child_type->data.unionation.decl_node->data.container_decl.auto_enum))
1468114685 {
14682 ensure_complete_type(ira->codegen, child_type);
14683 if (type_is_invalid(child_type))
14686 if ((err = ensure_complete_type(ira->codegen, child_type)))
1468414687 return ira->codegen->builtin_types.entry_invalid;
1468514688 TypeUnionField *field = find_union_type_field(child_type, field_name);
1468614689 if (field) {
......@@ -15257,6 +15260,7 @@ static TypeTableEntry *ir_analyze_instruction_set_float_mode(IrAnalyze *ira,
1525715260static TypeTableEntry *ir_analyze_instruction_slice_type(IrAnalyze *ira,
1525815261 IrInstructionSliceType *slice_type_instruction)
1525915262{
15263 Error err;
1526015264 uint32_t align_bytes;
1526115265 if (slice_type_instruction->align_value != nullptr) {
1526215266 if (!ir_resolve_align(ira, slice_type_instruction->align_value->other, &align_bytes))
......@@ -15268,6 +15272,8 @@ static TypeTableEntry *ir_analyze_instruction_slice_type(IrAnalyze *ira,
1526815272 return ira->codegen->builtin_types.entry_invalid;
1526915273
1527015274 if (slice_type_instruction->align_value == nullptr) {
15275 if ((err = type_ensure_zero_bits_known(ira->codegen, child_type)))
15276 return ira->codegen->builtin_types.entry_invalid;
1527115277 align_bytes = get_abi_alignment(ira->codegen, child_type);
1527215278 }
1527315279
......@@ -15306,7 +15312,8 @@ static TypeTableEntry *ir_analyze_instruction_slice_type(IrAnalyze *ira,
1530615312 case TypeTableEntryIdBoundFn:
1530715313 case TypeTableEntryIdPromise:
1530815314 {
15309 type_ensure_zero_bits_known(ira->codegen, child_type);
15315 if ((err = type_ensure_zero_bits_known(ira->codegen, child_type)))
15316 return ira->codegen->builtin_types.entry_invalid;
1531015317 TypeTableEntry *slice_ptr_type = get_pointer_to_type_extra(ira->codegen, child_type,
1531115318 is_const, is_volatile, PtrLenUnknown, align_bytes, 0, 0);
1531215319 TypeTableEntry *result_type = get_slice_type(ira->codegen, slice_ptr_type);
......@@ -15444,11 +15451,11 @@ static TypeTableEntry *ir_analyze_instruction_promise_type(IrAnalyze *ira, IrIns
1544415451static TypeTableEntry *ir_analyze_instruction_size_of(IrAnalyze *ira,
1544515452 IrInstructionSizeOf *size_of_instruction)
1544615453{
15454 Error err;
1544715455 IrInstruction *type_value = size_of_instruction->type_value->other;
1544815456 TypeTableEntry *type_entry = ir_resolve_type(ira, type_value);
1544915457
15450 ensure_complete_type(ira->codegen, type_entry);
15451 if (type_is_invalid(type_entry))
15458 if ((err = ensure_complete_type(ira->codegen, type_entry)))
1545215459 return ira->codegen->builtin_types.entry_invalid;
1545315460
1545415461 switch (type_entry->id) {
......@@ -15819,6 +15826,7 @@ static TypeTableEntry *ir_analyze_instruction_switch_br(IrAnalyze *ira,
1581915826static TypeTableEntry *ir_analyze_instruction_switch_target(IrAnalyze *ira,
1582015827 IrInstructionSwitchTarget *switch_target_instruction)
1582115828{
15829 Error err;
1582215830 IrInstruction *target_value_ptr = switch_target_instruction->target_value_ptr->other;
1582315831 if (type_is_invalid(target_value_ptr->value.type))
1582415832 return ira->codegen->builtin_types.entry_invalid;
......@@ -15845,8 +15853,7 @@ static TypeTableEntry *ir_analyze_instruction_switch_target(IrAnalyze *ira,
1584515853 if (pointee_val->special == ConstValSpecialRuntime)
1584615854 pointee_val = nullptr;
1584715855 }
15848 ensure_complete_type(ira->codegen, target_type);
15849 if (type_is_invalid(target_type))
15856 if ((err = ensure_complete_type(ira->codegen, target_type)))
1585015857 return ira->codegen->builtin_types.entry_invalid;
1585115858
1585215859 switch (target_type->id) {
......@@ -15910,8 +15917,7 @@ static TypeTableEntry *ir_analyze_instruction_switch_target(IrAnalyze *ira,
1591015917 return tag_type;
1591115918 }
1591215919 case TypeTableEntryIdEnum: {
15913 type_ensure_zero_bits_known(ira->codegen, target_type);
15914 if (type_is_invalid(target_type))
15920 if ((err = type_ensure_zero_bits_known(ira->codegen, target_type)))
1591515921 return ira->codegen->builtin_types.entry_invalid;
1591615922 if (target_type->data.enumeration.src_field_count < 2) {
1591715923 TypeEnumField *only_field = &target_type->data.enumeration.fields[0];
......@@ -16113,10 +16119,10 @@ static TypeTableEntry *ir_analyze_instruction_ref(IrAnalyze *ira, IrInstructionR
1611316119static TypeTableEntry *ir_analyze_container_init_fields_union(IrAnalyze *ira, IrInstruction *instruction,
1611416120 TypeTableEntry *container_type, size_t instr_field_count, IrInstructionContainerInitFieldsField *fields)
1611516121{
16122 Error err;
1611616123 assert(container_type->id == TypeTableEntryIdUnion);
1611716124
16118 ensure_complete_type(ira->codegen, container_type);
16119 if (type_is_invalid(container_type))
16125 if ((err = ensure_complete_type(ira->codegen, container_type)))
1612016126 return ira->codegen->builtin_types.entry_invalid;
1612116127
1612216128 if (instr_field_count != 1) {
......@@ -16145,8 +16151,7 @@ static TypeTableEntry *ir_analyze_container_init_fields_union(IrAnalyze *ira, Ir
1614516151 if (casted_field_value == ira->codegen->invalid_instruction)
1614616152 return ira->codegen->builtin_types.entry_invalid;
1614716153
16148 type_ensure_zero_bits_known(ira->codegen, casted_field_value->value.type);
16149 if (type_is_invalid(casted_field_value->value.type))
16154 if ((err = type_ensure_zero_bits_known(ira->codegen, casted_field_value->value.type)))
1615016155 return ira->codegen->builtin_types.entry_invalid;
1615116156
1615216157 bool is_comptime = ir_should_inline(ira->new_irb.exec, instruction->scope);
......@@ -16180,6 +16185,7 @@ static TypeTableEntry *ir_analyze_container_init_fields_union(IrAnalyze *ira, Ir
1618016185static TypeTableEntry *ir_analyze_container_init_fields(IrAnalyze *ira, IrInstruction *instruction,
1618116186 TypeTableEntry *container_type, size_t instr_field_count, IrInstructionContainerInitFieldsField *fields)
1618216187{
16188 Error err;
1618316189 if (container_type->id == TypeTableEntryIdUnion) {
1618416190 return ir_analyze_container_init_fields_union(ira, instruction, container_type, instr_field_count, fields);
1618516191 }
......@@ -16190,8 +16196,7 @@ static TypeTableEntry *ir_analyze_container_init_fields(IrAnalyze *ira, IrInstru
1619016196 return ira->codegen->builtin_types.entry_invalid;
1619116197 }
1619216198
16193 ensure_complete_type(ira->codegen, container_type);
16194 if (type_is_invalid(container_type))
16199 if ((err = ensure_complete_type(ira->codegen, container_type)))
1619516200 return ira->codegen->builtin_types.entry_invalid;
1619616201
1619716202 size_t actual_field_count = container_type->data.structure.src_field_count;
......@@ -16572,6 +16577,7 @@ static TypeTableEntry *ir_analyze_instruction_err_name(IrAnalyze *ira, IrInstruc
1657216577}
1657316578
1657416579static TypeTableEntry *ir_analyze_instruction_enum_tag_name(IrAnalyze *ira, IrInstructionTagName *instruction) {
16580 Error err;
1657516581 IrInstruction *target = instruction->target->other;
1657616582 if (type_is_invalid(target->value.type))
1657716583 return ira->codegen->builtin_types.entry_invalid;
......@@ -16579,8 +16585,7 @@ static TypeTableEntry *ir_analyze_instruction_enum_tag_name(IrAnalyze *ira, IrIn
1657916585 assert(target->value.type->id == TypeTableEntryIdEnum);
1658016586
1658116587 if (instr_is_comptime(target)) {
16582 type_ensure_zero_bits_known(ira->codegen, target->value.type);
16583 if (type_is_invalid(target->value.type))
16588 if ((err = type_ensure_zero_bits_known(ira->codegen, target->value.type)))
1658416589 return ira->codegen->builtin_types.entry_invalid;
1658516590 TypeEnumField *field = find_enum_field_by_tag(target->value.type, &target->value.data.x_bigint);
1658616591 ConstExprValue *array_val = create_const_str_lit(ira->codegen, field->name);
......@@ -16604,6 +16609,7 @@ static TypeTableEntry *ir_analyze_instruction_enum_tag_name(IrAnalyze *ira, IrIn
1660416609static TypeTableEntry *ir_analyze_instruction_field_parent_ptr(IrAnalyze *ira,
1660516610 IrInstructionFieldParentPtr *instruction)
1660616611{
16612 Error err;
1660716613 IrInstruction *type_value = instruction->type_value->other;
1660816614 TypeTableEntry *container_type = ir_resolve_type(ira, type_value);
1660916615 if (type_is_invalid(container_type))
......@@ -16624,8 +16630,7 @@ static TypeTableEntry *ir_analyze_instruction_field_parent_ptr(IrAnalyze *ira,
1662416630 return ira->codegen->builtin_types.entry_invalid;
1662516631 }
1662616632
16627 ensure_complete_type(ira->codegen, container_type);
16628 if (type_is_invalid(container_type))
16633 if ((err = ensure_complete_type(ira->codegen, container_type)))
1662916634 return ira->codegen->builtin_types.entry_invalid;
1663016635
1663116636 TypeStructField *field = find_struct_type_field(container_type, field_name);
......@@ -16697,13 +16702,13 @@ static TypeTableEntry *ir_analyze_instruction_field_parent_ptr(IrAnalyze *ira,
1669716702static TypeTableEntry *ir_analyze_instruction_offset_of(IrAnalyze *ira,
1669816703 IrInstructionOffsetOf *instruction)
1669916704{
16705 Error err;
1670016706 IrInstruction *type_value = instruction->type_value->other;
1670116707 TypeTableEntry *container_type = ir_resolve_type(ira, type_value);
1670216708 if (type_is_invalid(container_type))
1670316709 return ira->codegen->builtin_types.entry_invalid;
1670416710
16705 ensure_complete_type(ira->codegen, container_type);
16706 if (type_is_invalid(container_type))
16711 if ((err = ensure_complete_type(ira->codegen, container_type)))
1670716712 return ira->codegen->builtin_types.entry_invalid;
1670816713
1670916714 IrInstruction *field_name_value = instruction->field_name->other;
......@@ -16748,19 +16753,15 @@ static void ensure_field_index(TypeTableEntry *type, const char *field_name, siz
1674816753 (buf_deinit(field_name_buf), true));
1674916754}
1675016755
16751static TypeTableEntry *ir_type_info_get_type(IrAnalyze *ira, const char *type_name, TypeTableEntry *root = nullptr)
16752{
16756static TypeTableEntry *ir_type_info_get_type(IrAnalyze *ira, const char *type_name, TypeTableEntry *root) {
16757 Error err;
1675316758 static ConstExprValue *type_info_var = nullptr;
1675416759 static TypeTableEntry *type_info_type = nullptr;
16755 if (type_info_var == nullptr)
16756 {
16760 if (type_info_var == nullptr) {
1675716761 type_info_var = get_builtin_value(ira->codegen, "TypeInfo");
1675816762 assert(type_info_var->type->id == TypeTableEntryIdMetaType);
1675916763
16760 ensure_complete_type(ira->codegen, type_info_var->data.x_type);
16761 if (type_is_invalid(type_info_var->data.x_type))
16762 return ira->codegen->builtin_types.entry_invalid;
16763
16764 assertNoError(ensure_complete_type(ira->codegen, type_info_var->data.x_type));
1676416765 type_info_type = type_info_var->data.x_type;
1676516766 assert(type_info_type->id == TypeTableEntryIdUnion);
1676616767 }
......@@ -16785,8 +16786,7 @@ static TypeTableEntry *ir_type_info_get_type(IrAnalyze *ira, const char *type_na
1678516786
1678616787 VariableTableEntry *var = tld->var;
1678716788
16788 ensure_complete_type(ira->codegen, var->value->type);
16789 if (type_is_invalid(var->value->type))
16789 if ((err = ensure_complete_type(ira->codegen, var->value->type)))
1679016790 return ira->codegen->builtin_types.entry_invalid;
1679116791 assert(var->value->type->id == TypeTableEntryIdMetaType);
1679216792 return var->value->data.x_type;
......@@ -16794,9 +16794,9 @@ static TypeTableEntry *ir_type_info_get_type(IrAnalyze *ira, const char *type_na
1679416794
1679516795static bool ir_make_type_info_defs(IrAnalyze *ira, ConstExprValue *out_val, ScopeDecls *decls_scope)
1679616796{
16797 TypeTableEntry *type_info_definition_type = ir_type_info_get_type(ira, "Definition");
16798 ensure_complete_type(ira->codegen, type_info_definition_type);
16799 if (type_is_invalid(type_info_definition_type))
16797 Error err;
16798 TypeTableEntry *type_info_definition_type = ir_type_info_get_type(ira, "Definition", nullptr);
16799 if ((err = ensure_complete_type(ira->codegen, type_info_definition_type)))
1680016800 return false;
1680116801
1680216802 ensure_field_index(type_info_definition_type, "name", 0);
......@@ -16804,18 +16804,15 @@ static bool ir_make_type_info_defs(IrAnalyze *ira, ConstExprValue *out_val, Scop
1680416804 ensure_field_index(type_info_definition_type, "data", 2);
1680516805
1680616806 TypeTableEntry *type_info_definition_data_type = ir_type_info_get_type(ira, "Data", type_info_definition_type);
16807 ensure_complete_type(ira->codegen, type_info_definition_data_type);
16808 if (type_is_invalid(type_info_definition_data_type))
16807 if ((err = ensure_complete_type(ira->codegen, type_info_definition_data_type)))
1680916808 return false;
1681016809
1681116810 TypeTableEntry *type_info_fn_def_type = ir_type_info_get_type(ira, "FnDef", type_info_definition_data_type);
16812 ensure_complete_type(ira->codegen, type_info_fn_def_type);
16813 if (type_is_invalid(type_info_fn_def_type))
16811 if ((err = ensure_complete_type(ira->codegen, type_info_fn_def_type)))
1681416812 return false;
1681516813
1681616814 TypeTableEntry *type_info_fn_def_inline_type = ir_type_info_get_type(ira, "Inline", type_info_fn_def_type);
16817 ensure_complete_type(ira->codegen, type_info_fn_def_inline_type);
16818 if (type_is_invalid(type_info_fn_def_inline_type))
16815 if ((err = ensure_complete_type(ira->codegen, type_info_fn_def_inline_type)))
1681916816 return false;
1682016817
1682116818 // Loop through our definitions once to figure out how many definitions we will generate info for.
......@@ -16895,8 +16892,7 @@ static bool ir_make_type_info_defs(IrAnalyze *ira, ConstExprValue *out_val, Scop
1689516892 case TldIdVar:
1689616893 {
1689716894 VariableTableEntry *var = ((TldVar *)curr_entry->value)->var;
16898 ensure_complete_type(ira->codegen, var->value->type);
16899 if (type_is_invalid(var->value->type))
16895 if ((err = ensure_complete_type(ira->codegen, var->value->type)))
1690016896 return false;
1690116897
1690216898 if (var->value->type->id == TypeTableEntryIdMetaType)
......@@ -16953,7 +16949,7 @@ static bool ir_make_type_info_defs(IrAnalyze *ira, ConstExprValue *out_val, Scop
1695316949 // calling_convention: TypeInfo.CallingConvention
1695416950 ensure_field_index(fn_def_val->type, "calling_convention", 2);
1695516951 fn_def_fields[2].special = ConstValSpecialStatic;
16956 fn_def_fields[2].type = ir_type_info_get_type(ira, "CallingConvention");
16952 fn_def_fields[2].type = ir_type_info_get_type(ira, "CallingConvention", nullptr);
1695716953 bigint_init_unsigned(&fn_def_fields[2].data.x_enum_tag, fn_node->cc);
1695816954 // is_var_args: bool
1695916955 ensure_field_index(fn_def_val->type, "is_var_args", 3);
......@@ -17027,8 +17023,7 @@ static bool ir_make_type_info_defs(IrAnalyze *ira, ConstExprValue *out_val, Scop
1702717023 case TldIdContainer:
1702817024 {
1702917025 TypeTableEntry *type_entry = ((TldContainer *)curr_entry->value)->type_entry;
17030 ensure_complete_type(ira->codegen, type_entry);
17031 if (type_is_invalid(type_entry))
17026 if ((err = ensure_complete_type(ira->codegen, type_entry)))
1703217027 return false;
1703317028
1703417029 // This is a type.
......@@ -17054,12 +17049,67 @@ static bool ir_make_type_info_defs(IrAnalyze *ira, ConstExprValue *out_val, Scop
1705417049 return true;
1705517050}
1705617051
17052static ConstExprValue *create_ptr_like_type_info(IrAnalyze *ira, TypeTableEntry *ptr_type_entry) {
17053 TypeTableEntry *attrs_type;
17054 uint32_t size_enum_index;
17055 if (is_slice(ptr_type_entry)) {
17056 attrs_type = ptr_type_entry->data.structure.fields[slice_ptr_index].type_entry;
17057 size_enum_index = 2;
17058 } else if (ptr_type_entry->id == TypeTableEntryIdPointer) {
17059 attrs_type = ptr_type_entry;
17060 size_enum_index = (ptr_type_entry->data.pointer.ptr_len == PtrLenSingle) ? 0 : 1;
17061 } else {
17062 zig_unreachable();
17063 }
17064
17065 TypeTableEntry *type_info_pointer_type = ir_type_info_get_type(ira, "Pointer", nullptr);
17066 assertNoError(ensure_complete_type(ira->codegen, type_info_pointer_type));
17067
17068 ConstExprValue *result = create_const_vals(1);
17069 result->special = ConstValSpecialStatic;
17070 result->type = type_info_pointer_type;
17071
17072 ConstExprValue *fields = create_const_vals(5);
17073 result->data.x_struct.fields = fields;
17074
17075 // size: Size
17076 ensure_field_index(result->type, "size", 0);
17077 TypeTableEntry *type_info_pointer_size_type = ir_type_info_get_type(ira, "Size", type_info_pointer_type);
17078 assertNoError(ensure_complete_type(ira->codegen, type_info_pointer_size_type));
17079 fields[0].special = ConstValSpecialStatic;
17080 fields[0].type = type_info_pointer_size_type;
17081 bigint_init_unsigned(&fields[0].data.x_enum_tag, size_enum_index);
17082
17083 // is_const: bool
17084 ensure_field_index(result->type, "is_const", 1);
17085 fields[1].special = ConstValSpecialStatic;
17086 fields[1].type = ira->codegen->builtin_types.entry_bool;
17087 fields[1].data.x_bool = attrs_type->data.pointer.is_const;
17088 // is_volatile: bool
17089 ensure_field_index(result->type, "is_volatile", 2);
17090 fields[2].special = ConstValSpecialStatic;
17091 fields[2].type = ira->codegen->builtin_types.entry_bool;
17092 fields[2].data.x_bool = attrs_type->data.pointer.is_volatile;
17093 // alignment: u32
17094 ensure_field_index(result->type, "alignment", 3);
17095 fields[3].special = ConstValSpecialStatic;
17096 fields[3].type = get_int_type(ira->codegen, false, 29);
17097 bigint_init_unsigned(&fields[3].data.x_bigint, attrs_type->data.pointer.alignment);
17098 // child: type
17099 ensure_field_index(result->type, "child", 4);
17100 fields[4].special = ConstValSpecialStatic;
17101 fields[4].type = ira->codegen->builtin_types.entry_type;
17102 fields[4].data.x_type = attrs_type->data.pointer.child_type;
17103
17104 return result;
17105};
17106
1705717107static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *type_entry) {
17108 Error err;
1705817109 assert(type_entry != nullptr);
1705917110 assert(!type_is_invalid(type_entry));
1706017111
17061 ensure_complete_type(ira->codegen, type_entry);
17062 if (type_is_invalid(type_entry))
17112 if ((err = ensure_complete_type(ira->codegen, type_entry)))
1706317113 return nullptr;
1706417114
1706517115 const auto make_enum_field_val = [ira](ConstExprValue *enum_field_val, TypeEnumField *enum_field,
......@@ -17079,63 +17129,6 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t
1707917129 enum_field_val->data.x_struct.fields = inner_fields;
1708017130 };
1708117131
17082 const auto create_ptr_like_type_info = [ira](TypeTableEntry *ptr_type_entry) {
17083 TypeTableEntry *attrs_type;
17084 uint32_t size_enum_index;
17085 if (is_slice(ptr_type_entry)) {
17086 attrs_type = ptr_type_entry->data.structure.fields[slice_ptr_index].type_entry;
17087 size_enum_index = 2;
17088 } else if (ptr_type_entry->id == TypeTableEntryIdPointer) {
17089 attrs_type = ptr_type_entry;
17090 size_enum_index = (ptr_type_entry->data.pointer.ptr_len == PtrLenSingle) ? 0 : 1;
17091 } else {
17092 zig_unreachable();
17093 }
17094
17095 TypeTableEntry *type_info_pointer_type = ir_type_info_get_type(ira, "Pointer");
17096 ensure_complete_type(ira->codegen, type_info_pointer_type);
17097 assert(!type_is_invalid(type_info_pointer_type));
17098
17099 ConstExprValue *result = create_const_vals(1);
17100 result->special = ConstValSpecialStatic;
17101 result->type = type_info_pointer_type;
17102
17103 ConstExprValue *fields = create_const_vals(5);
17104 result->data.x_struct.fields = fields;
17105
17106 // size: Size
17107 ensure_field_index(result->type, "size", 0);
17108 TypeTableEntry *type_info_pointer_size_type = ir_type_info_get_type(ira, "Size", type_info_pointer_type);
17109 ensure_complete_type(ira->codegen, type_info_pointer_size_type);
17110 assert(!type_is_invalid(type_info_pointer_size_type));
17111 fields[0].special = ConstValSpecialStatic;
17112 fields[0].type = type_info_pointer_size_type;
17113 bigint_init_unsigned(&fields[0].data.x_enum_tag, size_enum_index);
17114
17115 // is_const: bool
17116 ensure_field_index(result->type, "is_const", 1);
17117 fields[1].special = ConstValSpecialStatic;
17118 fields[1].type = ira->codegen->builtin_types.entry_bool;
17119 fields[1].data.x_bool = attrs_type->data.pointer.is_const;
17120 // is_volatile: bool
17121 ensure_field_index(result->type, "is_volatile", 2);
17122 fields[2].special = ConstValSpecialStatic;
17123 fields[2].type = ira->codegen->builtin_types.entry_bool;
17124 fields[2].data.x_bool = attrs_type->data.pointer.is_volatile;
17125 // alignment: u32
17126 ensure_field_index(result->type, "alignment", 3);
17127 fields[3].special = ConstValSpecialStatic;
17128 fields[3].type = get_int_type(ira->codegen, false, 29);
17129 bigint_init_unsigned(&fields[3].data.x_bigint, attrs_type->data.pointer.alignment);
17130 // child: type
17131 ensure_field_index(result->type, "child", 4);
17132 fields[4].special = ConstValSpecialStatic;
17133 fields[4].type = ira->codegen->builtin_types.entry_type;
17134 fields[4].data.x_type = attrs_type->data.pointer.child_type;
17135
17136 return result;
17137 };
17138
1713917132 if (type_entry == ira->codegen->builtin_types.entry_global_error_set) {
1714017133 zig_panic("TODO implement @typeInfo for global error set");
1714117134 }
......@@ -17171,7 +17164,7 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t
1717117164 {
1717217165 result = create_const_vals(1);
1717317166 result->special = ConstValSpecialStatic;
17174 result->type = ir_type_info_get_type(ira, "Int");
17167 result->type = ir_type_info_get_type(ira, "Int", nullptr);
1717517168
1717617169 ConstExprValue *fields = create_const_vals(2);
1717717170 result->data.x_struct.fields = fields;
......@@ -17193,7 +17186,7 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t
1719317186 {
1719417187 result = create_const_vals(1);
1719517188 result->special = ConstValSpecialStatic;
17196 result->type = ir_type_info_get_type(ira, "Float");
17189 result->type = ir_type_info_get_type(ira, "Float", nullptr);
1719717190
1719817191 ConstExprValue *fields = create_const_vals(1);
1719917192 result->data.x_struct.fields = fields;
......@@ -17208,14 +17201,14 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t
1720817201 }
1720917202 case TypeTableEntryIdPointer:
1721017203 {
17211 result = create_ptr_like_type_info(type_entry);
17204 result = create_ptr_like_type_info(ira, type_entry);
1721217205 break;
1721317206 }
1721417207 case TypeTableEntryIdArray:
1721517208 {
1721617209 result = create_const_vals(1);
1721717210 result->special = ConstValSpecialStatic;
17218 result->type = ir_type_info_get_type(ira, "Array");
17211 result->type = ir_type_info_get_type(ira, "Array", nullptr);
1721917212
1722017213 ConstExprValue *fields = create_const_vals(2);
1722117214 result->data.x_struct.fields = fields;
......@@ -17237,7 +17230,7 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t
1723717230 {
1723817231 result = create_const_vals(1);
1723917232 result->special = ConstValSpecialStatic;
17240 result->type = ir_type_info_get_type(ira, "Optional");
17233 result->type = ir_type_info_get_type(ira, "Optional", nullptr);
1724117234
1724217235 ConstExprValue *fields = create_const_vals(1);
1724317236 result->data.x_struct.fields = fields;
......@@ -17254,7 +17247,7 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t
1725417247 {
1725517248 result = create_const_vals(1);
1725617249 result->special = ConstValSpecialStatic;
17257 result->type = ir_type_info_get_type(ira, "Promise");
17250 result->type = ir_type_info_get_type(ira, "Promise", nullptr);
1725817251
1725917252 ConstExprValue *fields = create_const_vals(1);
1726017253 result->data.x_struct.fields = fields;
......@@ -17280,7 +17273,7 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t
1728017273 {
1728117274 result = create_const_vals(1);
1728217275 result->special = ConstValSpecialStatic;
17283 result->type = ir_type_info_get_type(ira, "Enum");
17276 result->type = ir_type_info_get_type(ira, "Enum", nullptr);
1728417277
1728517278 ConstExprValue *fields = create_const_vals(4);
1728617279 result->data.x_struct.fields = fields;
......@@ -17288,7 +17281,7 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t
1728817281 // layout: ContainerLayout
1728917282 ensure_field_index(result->type, "layout", 0);
1729017283 fields[0].special = ConstValSpecialStatic;
17291 fields[0].type = ir_type_info_get_type(ira, "ContainerLayout");
17284 fields[0].type = ir_type_info_get_type(ira, "ContainerLayout", nullptr);
1729217285 bigint_init_unsigned(&fields[0].data.x_enum_tag, type_entry->data.enumeration.layout);
1729317286 // tag_type: type
1729417287 ensure_field_index(result->type, "tag_type", 1);
......@@ -17298,7 +17291,7 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t
1729817291 // fields: []TypeInfo.EnumField
1729917292 ensure_field_index(result->type, "fields", 2);
1730017293
17301 TypeTableEntry *type_info_enum_field_type = ir_type_info_get_type(ira, "EnumField");
17294 TypeTableEntry *type_info_enum_field_type = ir_type_info_get_type(ira, "EnumField", nullptr);
1730217295 uint32_t enum_field_count = type_entry->data.enumeration.src_field_count;
1730317296
1730417297 ConstExprValue *enum_field_array = create_const_vals(1);
......@@ -17330,7 +17323,7 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t
1733017323 {
1733117324 result = create_const_vals(1);
1733217325 result->special = ConstValSpecialStatic;
17333 result->type = ir_type_info_get_type(ira, "ErrorSet");
17326 result->type = ir_type_info_get_type(ira, "ErrorSet", nullptr);
1733417327
1733517328 ConstExprValue *fields = create_const_vals(1);
1733617329 result->data.x_struct.fields = fields;
......@@ -17338,7 +17331,7 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t
1733817331 // errors: []TypeInfo.Error
1733917332 ensure_field_index(result->type, "errors", 0);
1734017333
17341 TypeTableEntry *type_info_error_type = ir_type_info_get_type(ira, "Error");
17334 TypeTableEntry *type_info_error_type = ir_type_info_get_type(ira, "Error", nullptr);
1734217335 uint32_t error_count = type_entry->data.error_set.err_count;
1734317336 ConstExprValue *error_array = create_const_vals(1);
1734417337 error_array->special = ConstValSpecialStatic;
......@@ -17380,7 +17373,7 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t
1738017373 {
1738117374 result = create_const_vals(1);
1738217375 result->special = ConstValSpecialStatic;
17383 result->type = ir_type_info_get_type(ira, "ErrorUnion");
17376 result->type = ir_type_info_get_type(ira, "ErrorUnion", nullptr);
1738417377
1738517378 ConstExprValue *fields = create_const_vals(2);
1738617379 result->data.x_struct.fields = fields;
......@@ -17403,7 +17396,7 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t
1740317396 {
1740417397 result = create_const_vals(1);
1740517398 result->special = ConstValSpecialStatic;
17406 result->type = ir_type_info_get_type(ira, "Union");
17399 result->type = ir_type_info_get_type(ira, "Union", nullptr);
1740717400
1740817401 ConstExprValue *fields = create_const_vals(4);
1740917402 result->data.x_struct.fields = fields;
......@@ -17411,7 +17404,7 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t
1741117404 // layout: ContainerLayout
1741217405 ensure_field_index(result->type, "layout", 0);
1741317406 fields[0].special = ConstValSpecialStatic;
17414 fields[0].type = ir_type_info_get_type(ira, "ContainerLayout");
17407 fields[0].type = ir_type_info_get_type(ira, "ContainerLayout", nullptr);
1741517408 bigint_init_unsigned(&fields[0].data.x_enum_tag, type_entry->data.unionation.layout);
1741617409 // tag_type: ?type
1741717410 ensure_field_index(result->type, "tag_type", 1);
......@@ -17433,7 +17426,7 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t
1743317426 // fields: []TypeInfo.UnionField
1743417427 ensure_field_index(result->type, "fields", 2);
1743517428
17436 TypeTableEntry *type_info_union_field_type = ir_type_info_get_type(ira, "UnionField");
17429 TypeTableEntry *type_info_union_field_type = ir_type_info_get_type(ira, "UnionField", nullptr);
1743717430 uint32_t union_field_count = type_entry->data.unionation.src_field_count;
1743817431
1743917432 ConstExprValue *union_field_array = create_const_vals(1);
......@@ -17445,7 +17438,7 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t
1744517438
1744617439 init_const_slice(ira->codegen, &fields[2], union_field_array, 0, union_field_count, false);
1744717440
17448 TypeTableEntry *type_info_enum_field_type = ir_type_info_get_type(ira, "EnumField");
17441 TypeTableEntry *type_info_enum_field_type = ir_type_info_get_type(ira, "EnumField", nullptr);
1744917442
1745017443 for (uint32_t union_field_index = 0; union_field_index < union_field_count; union_field_index++) {
1745117444 TypeUnionField *union_field = &type_entry->data.unionation.fields[union_field_index];
......@@ -17487,13 +17480,13 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t
1748717480 case TypeTableEntryIdStruct:
1748817481 {
1748917482 if (type_entry->data.structure.is_slice) {
17490 result = create_ptr_like_type_info(type_entry);
17483 result = create_ptr_like_type_info(ira, type_entry);
1749117484 break;
1749217485 }
1749317486
1749417487 result = create_const_vals(1);
1749517488 result->special = ConstValSpecialStatic;
17496 result->type = ir_type_info_get_type(ira, "Struct");
17489 result->type = ir_type_info_get_type(ira, "Struct", nullptr);
1749717490
1749817491 ConstExprValue *fields = create_const_vals(3);
1749917492 result->data.x_struct.fields = fields;
......@@ -17501,12 +17494,12 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t
1750117494 // layout: ContainerLayout
1750217495 ensure_field_index(result->type, "layout", 0);
1750317496 fields[0].special = ConstValSpecialStatic;
17504 fields[0].type = ir_type_info_get_type(ira, "ContainerLayout");
17497 fields[0].type = ir_type_info_get_type(ira, "ContainerLayout", nullptr);
1750517498 bigint_init_unsigned(&fields[0].data.x_enum_tag, type_entry->data.structure.layout);
1750617499 // fields: []TypeInfo.StructField
1750717500 ensure_field_index(result->type, "fields", 1);
1750817501
17509 TypeTableEntry *type_info_struct_field_type = ir_type_info_get_type(ira, "StructField");
17502 TypeTableEntry *type_info_struct_field_type = ir_type_info_get_type(ira, "StructField", nullptr);
1751017503 uint32_t struct_field_count = type_entry->data.structure.src_field_count;
1751117504
1751217505 ConstExprValue *struct_field_array = create_const_vals(1);
......@@ -17562,7 +17555,7 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t
1756217555 {
1756317556 result = create_const_vals(1);
1756417557 result->special = ConstValSpecialStatic;
17565 result->type = ir_type_info_get_type(ira, "Fn");
17558 result->type = ir_type_info_get_type(ira, "Fn", nullptr);
1756617559
1756717560 ConstExprValue *fields = create_const_vals(6);
1756817561 result->data.x_struct.fields = fields;
......@@ -17570,7 +17563,7 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t
1757017563 // calling_convention: TypeInfo.CallingConvention
1757117564 ensure_field_index(result->type, "calling_convention", 0);
1757217565 fields[0].special = ConstValSpecialStatic;
17573 fields[0].type = ir_type_info_get_type(ira, "CallingConvention");
17566 fields[0].type = ir_type_info_get_type(ira, "CallingConvention", nullptr);
1757417567 bigint_init_unsigned(&fields[0].data.x_enum_tag, type_entry->data.fn.fn_type_id.cc);
1757517568 // is_generic: bool
1757617569 ensure_field_index(result->type, "is_generic", 1);
......@@ -17611,7 +17604,7 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t
1761117604 fields[4].data.x_optional = async_alloc_type;
1761217605 }
1761317606 // args: []TypeInfo.FnArg
17614 TypeTableEntry *type_info_fn_arg_type = ir_type_info_get_type(ira, "FnArg");
17607 TypeTableEntry *type_info_fn_arg_type = ir_type_info_get_type(ira, "FnArg", nullptr);
1761517608 size_t fn_arg_count = type_entry->data.fn.fn_type_id.param_count -
1761617609 (is_varargs && type_entry->data.fn.fn_type_id.cc != CallingConventionC);
1761717610
......@@ -17686,7 +17679,7 @@ static TypeTableEntry *ir_analyze_instruction_type_info(IrAnalyze *ira,
1768617679 if (type_is_invalid(type_entry))
1768717680 return ira->codegen->builtin_types.entry_invalid;
1768817681
17689 TypeTableEntry *result_type = ir_type_info_get_type(ira, nullptr);
17682 TypeTableEntry *result_type = ir_type_info_get_type(ira, nullptr, nullptr);
1769017683
1769117684 ConstExprValue *out_val = ir_build_const_from(ira, &instruction->base);
1769217685 out_val->type = result_type;
......@@ -18896,13 +18889,13 @@ static TypeTableEntry *ir_analyze_instruction_slice(IrAnalyze *ira, IrInstructio
1889618889}
1889718890
1889818891static TypeTableEntry *ir_analyze_instruction_member_count(IrAnalyze *ira, IrInstructionMemberCount *instruction) {
18892 Error err;
1889918893 IrInstruction *container = instruction->container->other;
1890018894 if (type_is_invalid(container->value.type))
1890118895 return ira->codegen->builtin_types.entry_invalid;
1890218896 TypeTableEntry *container_type = ir_resolve_type(ira, container);
1890318897
18904 ensure_complete_type(ira->codegen, container_type);
18905 if (type_is_invalid(container_type))
18898 if ((err = ensure_complete_type(ira->codegen, container_type)))
1890618899 return ira->codegen->builtin_types.entry_invalid;
1890718900
1890818901 uint64_t result;
......@@ -18934,13 +18927,13 @@ static TypeTableEntry *ir_analyze_instruction_member_count(IrAnalyze *ira, IrIns
1893418927}
1893518928
1893618929static TypeTableEntry *ir_analyze_instruction_member_type(IrAnalyze *ira, IrInstructionMemberType *instruction) {
18930 Error err;
1893718931 IrInstruction *container_type_value = instruction->container_type->other;
1893818932 TypeTableEntry *container_type = ir_resolve_type(ira, container_type_value);
1893918933 if (type_is_invalid(container_type))
1894018934 return ira->codegen->builtin_types.entry_invalid;
1894118935
18942 ensure_complete_type(ira->codegen, container_type);
18943 if (type_is_invalid(container_type))
18936 if ((err = ensure_complete_type(ira->codegen, container_type)))
1894418937 return ira->codegen->builtin_types.entry_invalid;
1894518938
1894618939
......@@ -18981,13 +18974,13 @@ static TypeTableEntry *ir_analyze_instruction_member_type(IrAnalyze *ira, IrInst
1898118974}
1898218975
1898318976static TypeTableEntry *ir_analyze_instruction_member_name(IrAnalyze *ira, IrInstructionMemberName *instruction) {
18977 Error err;
1898418978 IrInstruction *container_type_value = instruction->container_type->other;
1898518979 TypeTableEntry *container_type = ir_resolve_type(ira, container_type_value);
1898618980 if (type_is_invalid(container_type))
1898718981 return ira->codegen->builtin_types.entry_invalid;
1898818982
18989 ensure_complete_type(ira->codegen, container_type);
18990 if (type_is_invalid(container_type))
18983 if ((err = ensure_complete_type(ira->codegen, container_type)))
1899118984 return ira->codegen->builtin_types.entry_invalid;
1899218985
1899318986 uint64_t member_index;
......@@ -19068,13 +19061,13 @@ static TypeTableEntry *ir_analyze_instruction_handle(IrAnalyze *ira, IrInstructi
1906819061}
1906919062
1907019063static TypeTableEntry *ir_analyze_instruction_align_of(IrAnalyze *ira, IrInstructionAlignOf *instruction) {
19064 Error err;
1907119065 IrInstruction *type_value = instruction->type_value->other;
1907219066 if (type_is_invalid(type_value->value.type))
1907319067 return ira->codegen->builtin_types.entry_invalid;
1907419068 TypeTableEntry *type_entry = ir_resolve_type(ira, type_value);
1907519069
19076 type_ensure_zero_bits_known(ira->codegen, type_entry);
19077 if (type_is_invalid(type_entry))
19070 if ((err = type_ensure_zero_bits_known(ira->codegen, type_entry)))
1907819071 return ira->codegen->builtin_types.entry_invalid;
1907919072
1908019073 switch (type_entry->id) {
......@@ -19930,6 +19923,7 @@ static void buf_read_value_bytes(CodeGen *codegen, uint8_t *buf, ConstExprValue
1993019923}
1993119924
1993219925static TypeTableEntry *ir_analyze_instruction_bit_cast(IrAnalyze *ira, IrInstructionBitCast *instruction) {
19926 Error err;
1993319927 IrInstruction *dest_type_value = instruction->dest_type->other;
1993419928 TypeTableEntry *dest_type = ir_resolve_type(ira, dest_type_value);
1993519929 if (type_is_invalid(dest_type))
......@@ -19940,12 +19934,10 @@ static TypeTableEntry *ir_analyze_instruction_bit_cast(IrAnalyze *ira, IrInstruc
1994019934 if (type_is_invalid(src_type))
1994119935 return ira->codegen->builtin_types.entry_invalid;
1994219936
19943 ensure_complete_type(ira->codegen, dest_type);
19944 if (type_is_invalid(dest_type))
19937 if ((err = ensure_complete_type(ira->codegen, dest_type)))
1994519938 return ira->codegen->builtin_types.entry_invalid;
1994619939
19947 ensure_complete_type(ira->codegen, src_type);
19948 if (type_is_invalid(src_type))
19940 if ((err = ensure_complete_type(ira->codegen, src_type)))
1994919941 return ira->codegen->builtin_types.entry_invalid;
1995019942
1995119943 if (get_codegen_ptr_type(src_type) != nullptr) {
......@@ -20031,6 +20023,7 @@ static TypeTableEntry *ir_analyze_instruction_bit_cast(IrAnalyze *ira, IrInstruc
2003120023}
2003220024
2003320025static TypeTableEntry *ir_analyze_instruction_int_to_ptr(IrAnalyze *ira, IrInstructionIntToPtr *instruction) {
20026 Error err;
2003420027 IrInstruction *dest_type_value = instruction->dest_type->other;
2003520028 TypeTableEntry *dest_type = ir_resolve_type(ira, dest_type_value);
2003620029 if (type_is_invalid(dest_type))
......@@ -20041,7 +20034,8 @@ static TypeTableEntry *ir_analyze_instruction_int_to_ptr(IrAnalyze *ira, IrInstr
2004120034 return ira->codegen->builtin_types.entry_invalid;
2004220035 }
2004320036
20044 type_ensure_zero_bits_known(ira->codegen, dest_type);
20037 if ((err = type_ensure_zero_bits_known(ira->codegen, dest_type)))
20038 return ira->codegen->builtin_types.entry_invalid;
2004520039 if (!type_has_bits(dest_type)) {
2004620040 ir_add_error(ira, dest_type_value,
2004720041 buf_sprintf("type '%s' has 0 bits and cannot store information", buf_ptr(&dest_type->name)));
......@@ -20174,6 +20168,7 @@ static TypeTableEntry *ir_analyze_instruction_ptr_to_int(IrAnalyze *ira, IrInstr
2017420168}
2017520169
2017620170static TypeTableEntry *ir_analyze_instruction_ptr_type(IrAnalyze *ira, IrInstructionPtrType *instruction) {
20171 Error err;
2017720172 TypeTableEntry *child_type = ir_resolve_type(ira, instruction->child_type->other);
2017820173 if (type_is_invalid(child_type))
2017920174 return ira->codegen->builtin_types.entry_invalid;
......@@ -20191,8 +20186,7 @@ static TypeTableEntry *ir_analyze_instruction_ptr_type(IrAnalyze *ira, IrInstruc
2019120186 if (!ir_resolve_align(ira, instruction->align_value->other, &align_bytes))
2019220187 return ira->codegen->builtin_types.entry_invalid;
2019320188 } else {
20194 type_ensure_zero_bits_known(ira->codegen, child_type);
20195 if (type_is_invalid(child_type))
20189 if ((err = type_ensure_zero_bits_known(ira->codegen, child_type)))
2019620190 return ira->codegen->builtin_types.entry_invalid;
2019720191 align_bytes = get_abi_alignment(ira->codegen, child_type);
2019820192 }
......@@ -20312,22 +20306,21 @@ static TypeTableEntry *ir_analyze_instruction_arg_type(IrAnalyze *ira, IrInstruc
2031220306}
2031320307
2031420308static TypeTableEntry *ir_analyze_instruction_tag_type(IrAnalyze *ira, IrInstructionTagType *instruction) {
20309 Error err;
2031520310 IrInstruction *target_inst = instruction->target->other;
2031620311 TypeTableEntry *enum_type = ir_resolve_type(ira, target_inst);
2031720312 if (type_is_invalid(enum_type))
2031820313 return ira->codegen->builtin_types.entry_invalid;
2031920314
2032020315 if (enum_type->id == TypeTableEntryIdEnum) {
20321 ensure_complete_type(ira->codegen, enum_type);
20322 if (type_is_invalid(enum_type))
20316 if ((err = ensure_complete_type(ira->codegen, enum_type)))
2032320317 return ira->codegen->builtin_types.entry_invalid;
2032420318
2032520319 ConstExprValue *out_val = ir_build_const_from(ira, &instruction->base);
2032620320 out_val->data.x_type = enum_type->data.enumeration.tag_int_type;
2032720321 return ira->codegen->builtin_types.entry_type;
2032820322 } else if (enum_type->id == TypeTableEntryIdUnion) {
20329 ensure_complete_type(ira->codegen, enum_type);
20330 if (type_is_invalid(enum_type))
20323 if ((err = ensure_complete_type(ira->codegen, enum_type)))
2033120324 return ira->codegen->builtin_types.entry_invalid;
2033220325
2033320326 AstNode *decl_node = enum_type->data.unionation.decl_node;
......@@ -20830,6 +20823,7 @@ static TypeTableEntry *ir_analyze_instruction_sqrt(IrAnalyze *ira, IrInstruction
2083020823}
2083120824
2083220825static TypeTableEntry *ir_analyze_instruction_enum_to_int(IrAnalyze *ira, IrInstructionEnumToInt *instruction) {
20826 Error err;
2083320827 IrInstruction *target = instruction->target->other;
2083420828 if (type_is_invalid(target->value.type))
2083520829 return ira->codegen->builtin_types.entry_invalid;
......@@ -20840,8 +20834,7 @@ static TypeTableEntry *ir_analyze_instruction_enum_to_int(IrAnalyze *ira, IrInst
2084020834 return ira->codegen->builtin_types.entry_invalid;
2084120835 }
2084220836
20843 type_ensure_zero_bits_known(ira->codegen, target->value.type);
20844 if (type_is_invalid(target->value.type))
20837 if ((err = type_ensure_zero_bits_known(ira->codegen, target->value.type)))
2084520838 return ira->codegen->builtin_types.entry_invalid;
2084620839
2084720840 TypeTableEntry *tag_type = target->value.type->data.enumeration.tag_int_type;
......@@ -20852,6 +20845,7 @@ static TypeTableEntry *ir_analyze_instruction_enum_to_int(IrAnalyze *ira, IrInst
2085220845}
2085320846
2085420847static TypeTableEntry *ir_analyze_instruction_int_to_enum(IrAnalyze *ira, IrInstructionIntToEnum *instruction) {
20848 Error err;
2085520849 IrInstruction *dest_type_value = instruction->dest_type->other;
2085620850 TypeTableEntry *dest_type = ir_resolve_type(ira, dest_type_value);
2085720851 if (type_is_invalid(dest_type))
......@@ -20863,8 +20857,7 @@ static TypeTableEntry *ir_analyze_instruction_int_to_enum(IrAnalyze *ira, IrInst
2086320857 return ira->codegen->builtin_types.entry_invalid;
2086420858 }
2086520859
20866 type_ensure_zero_bits_known(ira->codegen, dest_type);
20867 if (type_is_invalid(dest_type))
20860 if ((err = type_ensure_zero_bits_known(ira->codegen, dest_type)))
2086820861 return ira->codegen->builtin_types.entry_invalid;
2086920862
2087020863 TypeTableEntry *tag_type = dest_type->data.enumeration.tag_int_type;
src/result.hpp created+36
......@@ -0,0 +1,36 @@
1/*
2 * Copyright (c) 2018 Andrew Kelley
3 *
4 * This file is part of zig, which is MIT licensed.
5 * See http://opensource.org/licenses/MIT
6 */
7
8#ifndef ZIG_RESULT_HPP
9#define ZIG_RESULT_HPP
10
11#include "error.hpp"
12
13#include <assert.h>
14
15static inline void assertNoError(Error err) {
16 assert(err == ErrorNone);
17}
18
19template<typename T>
20struct Result {
21 T data;
22 Error err;
23
24 Result(T x) : data(x), err(ErrorNone) {}
25
26 Result(Error err) : err(err) {
27 assert(err != ErrorNone);
28 }
29
30 T unwrap() {
31 assert(err == ErrorNone);
32 return data;
33 }
34};
35
36#endif
src/util.hpp+2
......@@ -21,6 +21,7 @@
2121#define ATTRIBUTE_PRINTF(a, b)
2222#define ATTRIBUTE_RETURNS_NOALIAS __declspec(restrict)
2323#define ATTRIBUTE_NORETURN __declspec(noreturn)
24#define ATTRIBUTE_MUST_USE
2425
2526#else
2627
......@@ -28,6 +29,7 @@
2829#define ATTRIBUTE_PRINTF(a, b) __attribute__((format(printf, a, b)))
2930#define ATTRIBUTE_RETURNS_NOALIAS __attribute__((__malloc__))
3031#define ATTRIBUTE_NORETURN __attribute__((noreturn))
32#define ATTRIBUTE_MUST_USE __attribute__((warn_unused_result))
3133
3234#endif
3335
std/c/darwin.zig+12
......@@ -1,5 +1,8 @@
1const macho = @import("../macho.zig");
2
13extern "c" fn __error() *c_int;
24pub extern "c" fn _NSGetExecutablePath(buf: [*]u8, bufsize: *u32) c_int;
5pub extern "c" fn _dyld_get_image_header(image_index: u32) ?*mach_header;
36
47pub extern "c" fn __getdirentries64(fd: c_int, buf_ptr: [*]u8, buf_len: usize, basep: *i64) usize;
58
......@@ -33,6 +36,15 @@ pub extern "c" fn sysctlnametomib(name: [*]const u8, mibp: ?*c_int, sizep: ?*usi
3336pub extern "c" fn bind(socket: c_int, address: ?*const sockaddr, address_len: socklen_t) c_int;
3437pub extern "c" fn socket(domain: c_int, type: c_int, protocol: c_int) c_int;
3538
39/// The value of the link editor defined symbol _MH_EXECUTE_SYM is the address
40/// of the mach header in a Mach-O executable file type. It does not appear in
41/// any file type other than a MH_EXECUTE file type. The type of the symbol is
42/// absolute as the header is not part of any section.
43pub extern "c" var _mh_execute_header: if (@sizeOf(usize) == 8) mach_header_64 else mach_header;
44
45pub const mach_header_64 = macho.mach_header_64;
46pub const mach_header = macho.mach_header;
47
3648pub use @import("../os/darwin/errno.zig");
3749
3850pub const _errno = __error;
std/c/linux.zig+3
......@@ -8,3 +8,6 @@ pub const pthread_attr_t = extern struct {
88 __size: [56]u8,
99 __align: c_long,
1010};
11
12/// See std.elf for constants for this
13pub extern fn getauxval(__type: c_ulong) c_ulong;
std/debug/index.zig+629-150
......@@ -4,8 +4,8 @@ const mem = std.mem;
44const io = std.io;
55const os = std.os;
66const elf = std.elf;
7const DW = std.dwarf;
87const macho = std.macho;
8const DW = std.dwarf;
99const ArrayList = std.ArrayList;
1010const builtin = @import("builtin");
1111
......@@ -19,9 +19,10 @@ pub const runtime_safety = switch (builtin.mode) {
1919
2020/// Tries to write to stderr, unbuffered, and ignores any error returned.
2121/// Does not append a newline.
22/// TODO atomic/multithread support
2322var stderr_file: os.File = undefined;
2423var stderr_file_out_stream: io.FileOutStream = undefined;
24
25/// TODO multithreaded awareness
2526var stderr_stream: ?*io.OutStream(io.FileOutStream.Error) = null;
2627var stderr_mutex = std.Mutex.init();
2728pub fn warn(comptime fmt: []const u8, args: ...) void {
......@@ -30,6 +31,7 @@ pub fn warn(comptime fmt: []const u8, args: ...) void {
3031 const stderr = getStderrStream() catch return;
3132 stderr.print(fmt, args) catch return;
3233}
34
3335pub fn getStderrStream() !*io.OutStream(io.FileOutStream.Error) {
3436 if (stderr_stream) |st| {
3537 return st;
......@@ -42,14 +44,15 @@ pub fn getStderrStream() !*io.OutStream(io.FileOutStream.Error) {
4244 }
4345}
4446
45var self_debug_info: ?*ElfStackTrace = null;
46pub fn getSelfDebugInfo() !*ElfStackTrace {
47 if (self_debug_info) |info| {
47/// TODO multithreaded awareness
48var self_debug_info: ?DebugInfo = null;
49
50pub fn getSelfDebugInfo() !*DebugInfo {
51 if (self_debug_info) |*info| {
4852 return info;
4953 } else {
50 const info = try openSelfDebugInfo(getDebugInfoAllocator());
51 self_debug_info = info;
52 return info;
54 self_debug_info = try openSelfDebugInfo(getDebugInfoAllocator());
55 return &self_debug_info.?;
5356 }
5457}
5558
......@@ -60,6 +63,7 @@ fn wantTtyColor() bool {
6063}
6164
6265/// Tries to print the current stack trace to stderr, unbuffered, and ignores any error returned.
66/// TODO multithreaded awareness
6367pub fn dumpCurrentStackTrace(start_addr: ?usize) void {
6468 const stderr = getStderrStream() catch return;
6569 const debug_info = getSelfDebugInfo() catch |err| {
......@@ -73,6 +77,7 @@ pub fn dumpCurrentStackTrace(start_addr: ?usize) void {
7377}
7478
7579/// Tries to print a stack trace to stderr, unbuffered, and ignores any error returned.
80/// TODO multithreaded awareness
7681pub fn dumpStackTrace(stack_trace: *const builtin.StackTrace) void {
7782 const stderr = getStderrStream() catch return;
7883 const debug_info = getSelfDebugInfo() catch |err| {
......@@ -127,6 +132,7 @@ pub fn panic(comptime format: []const u8, args: ...) noreturn {
127132 panicExtra(null, first_trace_addr, format, args);
128133}
129134
135/// TODO multithreaded awareness
130136var panicking: u8 = 0; // TODO make this a bool
131137
132138pub fn panicExtra(trace: ?*const builtin.StackTrace, first_trace_addr: ?usize, comptime format: []const u8, args: ...) noreturn {
......@@ -155,7 +161,7 @@ const WHITE = "\x1b[37;1m";
155161const DIM = "\x1b[2m";
156162const RESET = "\x1b[0m";
157163
158pub fn writeStackTrace(stack_trace: *const builtin.StackTrace, out_stream: var, allocator: *mem.Allocator, debug_info: *ElfStackTrace, tty_color: bool) !void {
164pub fn writeStackTrace(stack_trace: *const builtin.StackTrace, out_stream: var, allocator: *mem.Allocator, debug_info: *DebugInfo, tty_color: bool) !void {
159165 var frame_index: usize = undefined;
160166 var frames_left: usize = undefined;
161167 if (stack_trace.index < stack_trace.instruction_addresses.len) {
......@@ -185,7 +191,7 @@ pub inline fn getReturnAddress(frame_count: usize) usize {
185191 return @intToPtr(*const usize, fp + @sizeOf(usize)).*;
186192}
187193
188pub fn writeCurrentStackTrace(out_stream: var, allocator: *mem.Allocator, debug_info: *ElfStackTrace, tty_color: bool, start_addr: ?usize) !void {
194pub fn writeCurrentStackTrace(out_stream: var, allocator: *mem.Allocator, debug_info: *DebugInfo, tty_color: bool, start_addr: ?usize) !void {
189195 const AddressState = union(enum) {
190196 NotLookingForStartAddress,
191197 LookingForStartAddress: usize,
......@@ -218,128 +224,290 @@ pub fn writeCurrentStackTrace(out_stream: var, allocator: *mem.Allocator, debug_
218224 }
219225}
220226
221pub fn printSourceAtAddress(debug_info: *ElfStackTrace, out_stream: var, address: usize, tty_color: bool) !void {
227pub fn printSourceAtAddress(debug_info: *DebugInfo, out_stream: var, address: usize, tty_color: bool) !void {
222228 switch (builtin.os) {
223 builtin.Os.windows => return error.UnsupportedDebugInfo,
224 builtin.Os.macosx => {
225 // TODO(bnoordhuis) It's theoretically possible to obtain the
226 // compilation unit from the symbtab but it's not that useful
227 // in practice because the compiler dumps everything in a single
228 // object file. Future improvement: use external dSYM data when
229 // available.
230 const unknown = macho.Symbol{
231 .name = "???",
232 .address = address,
233 };
234 const symbol = debug_info.symbol_table.search(address) orelse &unknown;
235 try out_stream.print(WHITE ++ "{}" ++ RESET ++ ": " ++ DIM ++ "0x{x}" ++ " in ??? (???)" ++ RESET ++ "\n", symbol.name, address);
229 builtin.Os.macosx => return printSourceAtAddressMacOs(debug_info, out_stream, address, tty_color),
230 builtin.Os.linux => return printSourceAtAddressLinux(debug_info, out_stream, address, tty_color),
231 builtin.Os.windows => {
232 // TODO https://github.com/ziglang/zig/issues/721
233 return error.UnsupportedOperatingSystem;
236234 },
237 else => {
238 const compile_unit = findCompileUnit(debug_info, address) catch {
239 if (tty_color) {
240 try out_stream.print("???:?:?: " ++ DIM ++ "0x{x} in ??? (???)" ++ RESET ++ "\n ???\n\n", address);
241 } else {
242 try out_stream.print("???:?:?: 0x{x} in ??? (???)\n ???\n\n", address);
243 }
244 return;
245 };
246 const compile_unit_name = try compile_unit.die.getAttrString(debug_info, DW.AT_name);
247 if (getLineNumberInfo(debug_info, compile_unit, address - 1)) |line_info| {
248 defer line_info.deinit();
249 if (tty_color) {
250 try out_stream.print(
251 WHITE ++ "{}:{}:{}" ++ RESET ++ ": " ++ DIM ++ "0x{x} in ??? ({})" ++ RESET ++ "\n",
252 line_info.file_name,
253 line_info.line,
254 line_info.column,
255 address,
256 compile_unit_name,
257 );
258 if (printLineFromFile(out_stream, line_info)) {
259 if (line_info.column == 0) {
260 try out_stream.write("\n");
261 } else {
262 {
263 var col_i: usize = 1;
264 while (col_i < line_info.column) : (col_i += 1) {
265 try out_stream.writeByte(' ');
266 }
267 }
268 try out_stream.write(GREEN ++ "^" ++ RESET ++ "\n");
269 }
270 } else |err| switch (err) {
271 error.EndOfFile => {},
272 else => return err,
273 }
274 } else {
275 try out_stream.print(
276 "{}:{}:{}: 0x{x} in ??? ({})\n",
277 line_info.file_name,
278 line_info.line,
279 line_info.column,
280 address,
281 compile_unit_name,
282 );
283 }
284 } else |err| switch (err) {
285 error.MissingDebugInfo, error.InvalidDebugInfo => {
286 try out_stream.print("0x{x} in ??? ({})\n", address, compile_unit_name);
287 },
288 else => return err,
235 else => return error.UnsupportedOperatingSystem,
236 }
237}
238
239fn machoSearchSymbols(symbols: []const MachoSymbol, address: usize) ?*const MachoSymbol {
240 var min: usize = 0;
241 var max: usize = symbols.len - 1; // Exclude sentinel.
242 while (min < max) {
243 const mid = min + (max - min) / 2;
244 const curr = &symbols[mid];
245 const next = &symbols[mid + 1];
246 if (address >= next.address()) {
247 min = mid + 1;
248 } else if (address < curr.address()) {
249 max = mid;
250 } else {
251 return curr;
252 }
253 }
254 return null;
255}
256
257fn printSourceAtAddressMacOs(di: *DebugInfo, out_stream: var, address: usize, tty_color: bool) !void {
258 const base_addr = @ptrToInt(&std.c._mh_execute_header);
259 const adjusted_addr = 0x100000000 + (address - base_addr);
260
261 const symbol = machoSearchSymbols(di.symbols, adjusted_addr) orelse {
262 if (tty_color) {
263 try out_stream.print("???:?:?: " ++ DIM ++ "0x{x} in ??? (???)" ++ RESET ++ "\n\n\n", address);
264 } else {
265 try out_stream.print("???:?:?: 0x{x} in ??? (???)\n\n\n", address);
266 }
267 return;
268 };
269
270 const symbol_name = mem.toSliceConst(u8, di.strings.ptr + symbol.nlist.n_strx);
271 const compile_unit_name = if (symbol.ofile) |ofile| blk: {
272 const ofile_path = mem.toSliceConst(u8, di.strings.ptr + ofile.n_strx);
273 break :blk os.path.basename(ofile_path);
274 } else "???";
275 if (getLineNumberInfoMacOs(di, symbol.*, adjusted_addr)) |line_info| {
276 defer line_info.deinit();
277 try printLineInfo(di, out_stream, line_info, address, symbol_name, compile_unit_name, tty_color);
278 } else |err| switch (err) {
279 error.MissingDebugInfo, error.InvalidDebugInfo => {
280 if (tty_color) {
281 try out_stream.print("???:?:?: " ++ DIM ++ "0x{x} in {} ({})" ++ RESET ++ "\n\n\n", address, symbol_name, compile_unit_name);
282 } else {
283 try out_stream.print("???:?:?: 0x{x} in {} ({})\n\n\n", address, symbol_name, compile_unit_name);
289284 }
290285 },
286 else => return err,
291287 }
292288}
293289
294pub fn openSelfDebugInfo(allocator: *mem.Allocator) !*ElfStackTrace {
295 switch (builtin.object_format) {
296 builtin.ObjectFormat.elf => {
297 const st = try allocator.create(ElfStackTrace{
298 .self_exe_file = undefined,
299 .elf = undefined,
300 .debug_info = undefined,
301 .debug_abbrev = undefined,
302 .debug_str = undefined,
303 .debug_line = undefined,
304 .debug_ranges = null,
305 .abbrev_table_list = ArrayList(AbbrevTableHeader).init(allocator),
306 .compile_unit_list = ArrayList(CompileUnit).init(allocator),
307 });
308 errdefer allocator.destroy(st);
309 st.self_exe_file = try os.openSelfExe();
310 errdefer st.self_exe_file.close();
311
312 try st.elf.openFile(allocator, &st.self_exe_file);
313 errdefer st.elf.close();
314
315 st.debug_info = (try st.elf.findSection(".debug_info")) orelse return error.MissingDebugInfo;
316 st.debug_abbrev = (try st.elf.findSection(".debug_abbrev")) orelse return error.MissingDebugInfo;
317 st.debug_str = (try st.elf.findSection(".debug_str")) orelse return error.MissingDebugInfo;
318 st.debug_line = (try st.elf.findSection(".debug_line")) orelse return error.MissingDebugInfo;
319 st.debug_ranges = (try st.elf.findSection(".debug_ranges"));
320 try scanAllCompileUnits(st);
321 return st;
290pub fn printSourceAtAddressLinux(debug_info: *DebugInfo, out_stream: var, address: usize, tty_color: bool) !void {
291 const compile_unit = findCompileUnit(debug_info, address) catch {
292 if (tty_color) {
293 try out_stream.print("???:?:?: " ++ DIM ++ "0x{x} in ??? (???)" ++ RESET ++ "\n\n\n", address);
294 } else {
295 try out_stream.print("???:?:?: 0x{x} in ??? (???)\n\n\n", address);
296 }
297 return;
298 };
299 const compile_unit_name = try compile_unit.die.getAttrString(debug_info, DW.AT_name);
300 if (getLineNumberInfoLinux(debug_info, compile_unit, address - 1)) |line_info| {
301 defer line_info.deinit();
302 const symbol_name = "???";
303 try printLineInfo(debug_info, out_stream, line_info, address, symbol_name, compile_unit_name, tty_color);
304 } else |err| switch (err) {
305 error.MissingDebugInfo, error.InvalidDebugInfo => {
306 if (tty_color) {
307 try out_stream.print("???:?:?: " ++ DIM ++ "0x{x} in ??? ({})" ++ RESET ++ "\n\n\n", address, compile_unit_name);
308 } else {
309 try out_stream.print("???:?:?: 0x{x} in ??? ({})\n\n\n", address, compile_unit_name);
310 }
322311 },
323 builtin.ObjectFormat.macho => {
324 var exe_file = try os.openSelfExe();
325 defer exe_file.close();
312 else => return err,
313 }
314}
326315
327 const st = try allocator.create(ElfStackTrace{ .symbol_table = try macho.loadSymbols(allocator, &io.FileInStream.init(&exe_file)) });
328 errdefer allocator.destroy(st);
329 return st;
330 },
331 builtin.ObjectFormat.coff => {
332 return error.TodoSupportCoffDebugInfo;
333 },
334 builtin.ObjectFormat.wasm => {
335 return error.TodoSupportCOFFDebugInfo;
336 },
337 builtin.ObjectFormat.unknown => {
338 return error.UnknownObjectFormat;
316fn printLineInfo(
317 debug_info: *DebugInfo,
318 out_stream: var,
319 line_info: LineInfo,
320 address: usize,
321 symbol_name: []const u8,
322 compile_unit_name: []const u8,
323 tty_color: bool,
324) !void {
325 if (tty_color) {
326 try out_stream.print(
327 WHITE ++ "{}:{}:{}" ++ RESET ++ ": " ++ DIM ++ "0x{x} in {} ({})" ++ RESET ++ "\n",
328 line_info.file_name,
329 line_info.line,
330 line_info.column,
331 address,
332 symbol_name,
333 compile_unit_name,
334 );
335 if (printLineFromFile(out_stream, line_info)) {
336 if (line_info.column == 0) {
337 try out_stream.write("\n");
338 } else {
339 {
340 var col_i: usize = 1;
341 while (col_i < line_info.column) : (col_i += 1) {
342 try out_stream.writeByte(' ');
343 }
344 }
345 try out_stream.write(GREEN ++ "^" ++ RESET ++ "\n");
346 }
347 } else |err| switch (err) {
348 error.EndOfFile => {},
349 else => return err,
350 }
351 } else {
352 try out_stream.print(
353 "{}:{}:{}: 0x{x} in {} ({})\n",
354 line_info.file_name,
355 line_info.line,
356 line_info.column,
357 address,
358 symbol_name,
359 compile_unit_name,
360 );
361 }
362}
363
364// TODO use this
365pub const OpenSelfDebugInfoError = error{
366 MissingDebugInfo,
367 OutOfMemory,
368 UnsupportedOperatingSystem,
369};
370
371pub fn openSelfDebugInfo(allocator: *mem.Allocator) !DebugInfo {
372 switch (builtin.os) {
373 builtin.Os.linux => return openSelfDebugInfoLinux(allocator),
374 builtin.Os.macosx, builtin.Os.ios => return openSelfDebugInfoMacOs(allocator),
375 builtin.Os.windows => {
376 // TODO: https://github.com/ziglang/zig/issues/721
377 return error.UnsupportedOperatingSystem;
339378 },
379 else => return error.UnsupportedOperatingSystem,
340380 }
341381}
342382
383fn openSelfDebugInfoLinux(allocator: *mem.Allocator) !DebugInfo {
384 var di = DebugInfo{
385 .self_exe_file = undefined,
386 .elf = undefined,
387 .debug_info = undefined,
388 .debug_abbrev = undefined,
389 .debug_str = undefined,
390 .debug_line = undefined,
391 .debug_ranges = null,
392 .abbrev_table_list = ArrayList(AbbrevTableHeader).init(allocator),
393 .compile_unit_list = ArrayList(CompileUnit).init(allocator),
394 };
395 di.self_exe_file = try os.openSelfExe();
396 errdefer di.self_exe_file.close();
397
398 try di.elf.openFile(allocator, &di.self_exe_file);
399 errdefer di.elf.close();
400
401 di.debug_info = (try di.elf.findSection(".debug_info")) orelse return error.MissingDebugInfo;
402 di.debug_abbrev = (try di.elf.findSection(".debug_abbrev")) orelse return error.MissingDebugInfo;
403 di.debug_str = (try di.elf.findSection(".debug_str")) orelse return error.MissingDebugInfo;
404 di.debug_line = (try di.elf.findSection(".debug_line")) orelse return error.MissingDebugInfo;
405 di.debug_ranges = (try di.elf.findSection(".debug_ranges"));
406 try scanAllCompileUnits(&di);
407 return di;
408}
409
410pub fn findElfSection(elf: *Elf, name: []const u8) ?*elf.Shdr {
411 var file_stream = io.FileInStream.init(elf.in_file);
412 const in = &file_stream.stream;
413
414 section_loop: for (elf.section_headers) |*elf_section| {
415 if (elf_section.sh_type == SHT_NULL) continue;
416
417 const name_offset = elf.string_section.offset + elf_section.name;
418 try elf.in_file.seekTo(name_offset);
419
420 for (name) |expected_c| {
421 const target_c = try in.readByte();
422 if (target_c == 0 or expected_c != target_c) continue :section_loop;
423 }
424
425 {
426 const null_byte = try in.readByte();
427 if (null_byte == 0) return elf_section;
428 }
429 }
430
431 return null;
432}
433
434fn openSelfDebugInfoMacOs(allocator: *mem.Allocator) !DebugInfo {
435 const hdr = &std.c._mh_execute_header;
436 assert(hdr.magic == std.macho.MH_MAGIC_64);
437
438 const hdr_base = @ptrCast([*]u8, hdr);
439 var ptr = hdr_base + @sizeOf(macho.mach_header_64);
440 var ncmd: u32 = hdr.ncmds;
441 const symtab = while (ncmd != 0) : (ncmd -= 1) {
442 const lc = @ptrCast(*std.macho.load_command, ptr);
443 switch (lc.cmd) {
444 std.macho.LC_SYMTAB => break @ptrCast(*std.macho.symtab_command, ptr),
445 else => {},
446 }
447 ptr += lc.cmdsize; // TODO https://github.com/ziglang/zig/issues/1403
448 } else {
449 return error.MissingDebugInfo;
450 };
451 const syms = @ptrCast([*]macho.nlist_64, hdr_base + symtab.symoff)[0..symtab.nsyms];
452 const strings = @ptrCast([*]u8, hdr_base + symtab.stroff)[0..symtab.strsize];
453
454 const symbols_buf = try allocator.alloc(MachoSymbol, syms.len);
455
456 var ofile: ?*macho.nlist_64 = null;
457 var reloc: u64 = 0;
458 var symbol_index: usize = 0;
459 var last_len: u64 = 0;
460 for (syms) |*sym| {
461 if (sym.n_type & std.macho.N_STAB != 0) {
462 switch (sym.n_type) {
463 std.macho.N_OSO => {
464 ofile = sym;
465 reloc = 0;
466 },
467 std.macho.N_FUN => {
468 if (sym.n_sect == 0) {
469 last_len = sym.n_value;
470 } else {
471 symbols_buf[symbol_index] = MachoSymbol{
472 .nlist = sym,
473 .ofile = ofile,
474 .reloc = reloc,
475 };
476 symbol_index += 1;
477 }
478 },
479 std.macho.N_BNSYM => {
480 if (reloc == 0) {
481 reloc = sym.n_value;
482 }
483 },
484 else => continue,
485 }
486 }
487 }
488 const sentinel = try allocator.createOne(macho.nlist_64);
489 sentinel.* = macho.nlist_64{
490 .n_strx = 0,
491 .n_type = 36,
492 .n_sect = 0,
493 .n_desc = 0,
494 .n_value = symbols_buf[symbol_index - 1].nlist.n_value + last_len,
495 };
496
497 const symbols = allocator.shrink(MachoSymbol, symbols_buf, symbol_index);
498
499 // Even though lld emits symbols in ascending order, this debug code
500 // should work for programs linked in any valid way.
501 // This sort is so that we can binary search later.
502 std.sort.sort(MachoSymbol, symbols, MachoSymbol.addressLessThan);
503
504 return DebugInfo{
505 .ofiles = DebugInfo.OFileTable.init(allocator),
506 .symbols = symbols,
507 .strings = strings,
508 };
509}
510
343511fn printLineFromFile(out_stream: var, line_info: *const LineInfo) !void {
344512 var f = try os.File.openRead(line_info.file_name);
345513 defer f.close();
......@@ -372,12 +540,42 @@ fn printLineFromFile(out_stream: var, line_info: *const LineInfo) !void {
372540 }
373541}
374542
375pub const ElfStackTrace = switch (builtin.os) {
376 builtin.Os.macosx => struct {
377 symbol_table: macho.SymbolTable,
543const MachoSymbol = struct {
544 nlist: *macho.nlist_64,
545 ofile: ?*macho.nlist_64,
546 reloc: u64,
547
548 /// Returns the address from the macho file
549 fn address(self: MachoSymbol) u64 {
550 return self.nlist.n_value;
551 }
552
553 fn addressLessThan(lhs: MachoSymbol, rhs: MachoSymbol) bool {
554 return lhs.address() < rhs.address();
555 }
556};
557
558const MachOFile = struct {
559 bytes: []align(@alignOf(macho.mach_header_64)) const u8,
560 sect_debug_info: ?*const macho.section_64,
561 sect_debug_line: ?*const macho.section_64,
562};
378563
379 pub fn close(self: *ElfStackTrace) void {
380 self.symbol_table.deinit();
564pub const DebugInfo = switch (builtin.os) {
565 builtin.Os.macosx => struct {
566 symbols: []const MachoSymbol,
567 strings: []const u8,
568 ofiles: OFileTable,
569
570 const OFileTable = std.HashMap(
571 *macho.nlist_64,
572 MachOFile,
573 std.hash_map.getHashPtrAddrFn(*macho.nlist_64),
574 std.hash_map.getTrivialEqlFn(*macho.nlist_64),
575 );
576
577 pub fn allocator(self: DebugInfo) *mem.Allocator {
578 return self.ofiles.allocator;
381579 }
382580 },
383581 else => struct {
......@@ -391,17 +589,17 @@ pub const ElfStackTrace = switch (builtin.os) {
391589 abbrev_table_list: ArrayList(AbbrevTableHeader),
392590 compile_unit_list: ArrayList(CompileUnit),
393591
394 pub fn allocator(self: *const ElfStackTrace) *mem.Allocator {
592 pub fn allocator(self: DebugInfo) *mem.Allocator {
395593 return self.abbrev_table_list.allocator;
396594 }
397595
398 pub fn readString(self: *ElfStackTrace) ![]u8 {
596 pub fn readString(self: *DebugInfo) ![]u8 {
399597 var in_file_stream = io.FileInStream.init(&self.self_exe_file);
400598 const in_stream = &in_file_stream.stream;
401599 return readStringRaw(self.allocator(), in_stream);
402600 }
403601
404 pub fn close(self: *ElfStackTrace) void {
602 pub fn close(self: *DebugInfo) void {
405603 self.self_exe_file.close();
406604 self.elf.close();
407605 }
......@@ -508,7 +706,7 @@ const Die = struct {
508706 };
509707 }
510708
511 fn getAttrString(self: *const Die, st: *ElfStackTrace, id: u64) ![]u8 {
709 fn getAttrString(self: *const Die, st: *DebugInfo, id: u64) ![]u8 {
512710 const form_value = self.getAttr(id) orelse return error.MissingDebugInfo;
513711 return switch (form_value.*) {
514712 FormValue.String => |value| value,
......@@ -623,7 +821,7 @@ fn readStringRaw(allocator: *mem.Allocator, in_stream: var) ![]u8 {
623821 return buf.toSlice();
624822}
625823
626fn getString(st: *ElfStackTrace, offset: u64) ![]u8 {
824fn getString(st: *DebugInfo, offset: u64) ![]u8 {
627825 const pos = st.debug_str.offset + offset;
628826 try st.self_exe_file.seekTo(pos);
629827 return st.readString();
......@@ -730,7 +928,7 @@ fn parseFormValue(allocator: *mem.Allocator, in_stream: var, form_id: u64, is_64
730928 };
731929}
732930
733fn parseAbbrevTable(st: *ElfStackTrace) !AbbrevTable {
931fn parseAbbrevTable(st: *DebugInfo) !AbbrevTable {
734932 const in_file = &st.self_exe_file;
735933 var in_file_stream = io.FileInStream.init(in_file);
736934 const in_stream = &in_file_stream.stream;
......@@ -760,7 +958,7 @@ fn parseAbbrevTable(st: *ElfStackTrace) !AbbrevTable {
760958
761959/// Gets an already existing AbbrevTable given the abbrev_offset, or if not found,
762960/// seeks in the stream and parses it.
763fn getAbbrevTable(st: *ElfStackTrace, abbrev_offset: u64) !*const AbbrevTable {
961fn getAbbrevTable(st: *DebugInfo, abbrev_offset: u64) !*const AbbrevTable {
764962 for (st.abbrev_table_list.toSlice()) |*header| {
765963 if (header.offset == abbrev_offset) {
766964 return &header.table;
......@@ -781,7 +979,7 @@ fn getAbbrevTableEntry(abbrev_table: *const AbbrevTable, abbrev_code: u64) ?*con
781979 return null;
782980}
783981
784fn parseDie(st: *ElfStackTrace, abbrev_table: *const AbbrevTable, is_64: bool) !Die {
982fn parseDie(st: *DebugInfo, abbrev_table: *const AbbrevTable, is_64: bool) !Die {
785983 const in_file = &st.self_exe_file;
786984 var in_file_stream = io.FileInStream.init(in_file);
787985 const in_stream = &in_file_stream.stream;
......@@ -803,12 +1001,210 @@ fn parseDie(st: *ElfStackTrace, abbrev_table: *const AbbrevTable, is_64: bool) !
8031001 return result;
8041002}
8051003
806fn getLineNumberInfo(st: *ElfStackTrace, compile_unit: *const CompileUnit, target_address: usize) !LineInfo {
807 const compile_unit_cwd = try compile_unit.die.getAttrString(st, DW.AT_comp_dir);
1004fn getLineNumberInfoMacOs(di: *DebugInfo, symbol: MachoSymbol, target_address: usize) !LineInfo {
1005 const ofile = symbol.ofile orelse return error.MissingDebugInfo;
1006 const gop = try di.ofiles.getOrPut(ofile);
1007 const mach_o_file = if (gop.found_existing) &gop.kv.value else blk: {
1008 errdefer _ = di.ofiles.remove(ofile);
1009 const ofile_path = mem.toSliceConst(u8, di.strings.ptr + ofile.n_strx);
1010
1011 gop.kv.value = MachOFile{
1012 .bytes = try std.io.readFileAllocAligned(di.ofiles.allocator, ofile_path, @alignOf(macho.mach_header_64)),
1013 .sect_debug_info = null,
1014 .sect_debug_line = null,
1015 };
1016 const hdr = @ptrCast(*const macho.mach_header_64, gop.kv.value.bytes.ptr);
1017 if (hdr.magic != std.macho.MH_MAGIC_64) return error.InvalidDebugInfo;
1018
1019 const hdr_base = @ptrCast([*]const u8, hdr);
1020 var ptr = hdr_base + @sizeOf(macho.mach_header_64);
1021 var ncmd: u32 = hdr.ncmds;
1022 const segcmd = while (ncmd != 0) : (ncmd -= 1) {
1023 const lc = @ptrCast(*const std.macho.load_command, ptr);
1024 switch (lc.cmd) {
1025 std.macho.LC_SEGMENT_64 => break @ptrCast(*const std.macho.segment_command_64, ptr),
1026 else => {},
1027 }
1028 ptr += lc.cmdsize; // TODO https://github.com/ziglang/zig/issues/1403
1029 } else {
1030 return error.MissingDebugInfo;
1031 };
1032 const sections = @alignCast(@alignOf(macho.section_64), @ptrCast([*]const macho.section_64, ptr + @sizeOf(std.macho.segment_command_64)))[0..segcmd.nsects];
1033 for (sections) |*sect| {
1034 if (sect.flags & macho.SECTION_TYPE == macho.S_REGULAR and
1035 (sect.flags & macho.SECTION_ATTRIBUTES) & macho.S_ATTR_DEBUG == macho.S_ATTR_DEBUG)
1036 {
1037 const sect_name = mem.toSliceConst(u8, &sect.sectname);
1038 if (mem.eql(u8, sect_name, "__debug_line")) {
1039 gop.kv.value.sect_debug_line = sect;
1040 } else if (mem.eql(u8, sect_name, "__debug_info")) {
1041 gop.kv.value.sect_debug_info = sect;
1042 }
1043 }
1044 }
8081045
809 const in_file = &st.self_exe_file;
810 const debug_line_end = st.debug_line.offset + st.debug_line.size;
811 var this_offset = st.debug_line.offset;
1046 break :blk &gop.kv.value;
1047 };
1048
1049 const sect_debug_line = mach_o_file.sect_debug_line orelse return error.MissingDebugInfo;
1050 var ptr = mach_o_file.bytes.ptr + sect_debug_line.offset;
1051
1052 var is_64: bool = undefined;
1053 const unit_length = try readInitialLengthMem(&ptr, &is_64);
1054 if (unit_length == 0) return error.MissingDebugInfo;
1055
1056 const version = readIntMem(&ptr, u16, builtin.Endian.Little);
1057 // TODO support 3 and 5
1058 if (version != 2 and version != 4) return error.InvalidDebugInfo;
1059
1060 const prologue_length = if (is_64)
1061 readIntMem(&ptr, u64, builtin.Endian.Little)
1062 else
1063 readIntMem(&ptr, u32, builtin.Endian.Little);
1064 const prog_start = ptr + prologue_length;
1065
1066 const minimum_instruction_length = readByteMem(&ptr);
1067 if (minimum_instruction_length == 0) return error.InvalidDebugInfo;
1068
1069 if (version >= 4) {
1070 // maximum_operations_per_instruction
1071 ptr += 1;
1072 }
1073
1074 const default_is_stmt = readByteMem(&ptr) != 0;
1075 const line_base = readByteSignedMem(&ptr);
1076
1077 const line_range = readByteMem(&ptr);
1078 if (line_range == 0) return error.InvalidDebugInfo;
1079
1080 const opcode_base = readByteMem(&ptr);
1081
1082 const standard_opcode_lengths = ptr[0 .. opcode_base - 1];
1083 ptr += opcode_base - 1;
1084
1085 var include_directories = ArrayList([]const u8).init(di.allocator());
1086 try include_directories.append("");
1087 while (true) {
1088 const dir = readStringMem(&ptr);
1089 if (dir.len == 0) break;
1090 try include_directories.append(dir);
1091 }
1092
1093 var file_entries = ArrayList(FileEntry).init(di.allocator());
1094 var prog = LineNumberProgram.init(default_is_stmt, include_directories.toSliceConst(), &file_entries, target_address);
1095
1096 while (true) {
1097 const file_name = readStringMem(&ptr);
1098 if (file_name.len == 0) break;
1099 const dir_index = try readULeb128Mem(&ptr);
1100 const mtime = try readULeb128Mem(&ptr);
1101 const len_bytes = try readULeb128Mem(&ptr);
1102 try file_entries.append(FileEntry{
1103 .file_name = file_name,
1104 .dir_index = dir_index,
1105 .mtime = mtime,
1106 .len_bytes = len_bytes,
1107 });
1108 }
1109
1110 ptr = prog_start;
1111 while (true) {
1112 const opcode = readByteMem(&ptr);
1113
1114 if (opcode == DW.LNS_extended_op) {
1115 const op_size = try readULeb128Mem(&ptr);
1116 if (op_size < 1) return error.InvalidDebugInfo;
1117 var sub_op = readByteMem(&ptr);
1118 switch (sub_op) {
1119 DW.LNE_end_sequence => {
1120 prog.end_sequence = true;
1121 if (try prog.checkLineMatch()) |info| return info;
1122 return error.MissingDebugInfo;
1123 },
1124 DW.LNE_set_address => {
1125 const addr = readIntMem(&ptr, usize, builtin.Endian.Little);
1126 prog.address = symbol.reloc + addr;
1127 },
1128 DW.LNE_define_file => {
1129 const file_name = readStringMem(&ptr);
1130 const dir_index = try readULeb128Mem(&ptr);
1131 const mtime = try readULeb128Mem(&ptr);
1132 const len_bytes = try readULeb128Mem(&ptr);
1133 try file_entries.append(FileEntry{
1134 .file_name = file_name,
1135 .dir_index = dir_index,
1136 .mtime = mtime,
1137 .len_bytes = len_bytes,
1138 });
1139 },
1140 else => {
1141 ptr += op_size - 1;
1142 },
1143 }
1144 } else if (opcode >= opcode_base) {
1145 // special opcodes
1146 const adjusted_opcode = opcode - opcode_base;
1147 const inc_addr = minimum_instruction_length * (adjusted_opcode / line_range);
1148 const inc_line = i32(line_base) + i32(adjusted_opcode % line_range);
1149 prog.line += inc_line;
1150 prog.address += inc_addr;
1151 if (try prog.checkLineMatch()) |info| return info;
1152 prog.basic_block = false;
1153 } else {
1154 switch (opcode) {
1155 DW.LNS_copy => {
1156 if (try prog.checkLineMatch()) |info| return info;
1157 prog.basic_block = false;
1158 },
1159 DW.LNS_advance_pc => {
1160 const arg = try readULeb128Mem(&ptr);
1161 prog.address += arg * minimum_instruction_length;
1162 },
1163 DW.LNS_advance_line => {
1164 const arg = try readILeb128Mem(&ptr);
1165 prog.line += arg;
1166 },
1167 DW.LNS_set_file => {
1168 const arg = try readULeb128Mem(&ptr);
1169 prog.file = arg;
1170 },
1171 DW.LNS_set_column => {
1172 const arg = try readULeb128Mem(&ptr);
1173 prog.column = arg;
1174 },
1175 DW.LNS_negate_stmt => {
1176 prog.is_stmt = !prog.is_stmt;
1177 },
1178 DW.LNS_set_basic_block => {
1179 prog.basic_block = true;
1180 },
1181 DW.LNS_const_add_pc => {
1182 const inc_addr = minimum_instruction_length * ((255 - opcode_base) / line_range);
1183 prog.address += inc_addr;
1184 },
1185 DW.LNS_fixed_advance_pc => {
1186 const arg = readIntMem(&ptr, u16, builtin.Endian.Little);
1187 prog.address += arg;
1188 },
1189 DW.LNS_set_prologue_end => {},
1190 else => {
1191 if (opcode - 1 >= standard_opcode_lengths.len) return error.InvalidDebugInfo;
1192 const len_bytes = standard_opcode_lengths[opcode - 1];
1193 ptr += len_bytes;
1194 },
1195 }
1196 }
1197 }
1198
1199 return error.MissingDebugInfo;
1200}
1201
1202fn getLineNumberInfoLinux(di: *DebugInfo, compile_unit: *const CompileUnit, target_address: usize) !LineInfo {
1203 const compile_unit_cwd = try compile_unit.die.getAttrString(di, DW.AT_comp_dir);
1204
1205 const in_file = &di.self_exe_file;
1206 const debug_line_end = di.debug_line.offset + di.debug_line.size;
1207 var this_offset = di.debug_line.offset;
8121208 var this_index: usize = 0;
8131209
8141210 var in_file_stream = io.FileInStream.init(in_file);
......@@ -827,11 +1223,11 @@ fn getLineNumberInfo(st: *ElfStackTrace, compile_unit: *const CompileUnit, targe
8271223 continue;
8281224 }
8291225
830 const version = try in_stream.readInt(st.elf.endian, u16);
1226 const version = try in_stream.readInt(di.elf.endian, u16);
8311227 // TODO support 3 and 5
8321228 if (version != 2 and version != 4) return error.InvalidDebugInfo;
8331229
834 const prologue_length = if (is_64) try in_stream.readInt(st.elf.endian, u64) else try in_stream.readInt(st.elf.endian, u32);
1230 const prologue_length = if (is_64) try in_stream.readInt(di.elf.endian, u64) else try in_stream.readInt(di.elf.endian, u32);
8351231 const prog_start_offset = (try in_file.getPos()) + prologue_length;
8361232
8371233 const minimum_instruction_length = try in_stream.readByte();
......@@ -850,7 +1246,7 @@ fn getLineNumberInfo(st: *ElfStackTrace, compile_unit: *const CompileUnit, targe
8501246
8511247 const opcode_base = try in_stream.readByte();
8521248
853 const standard_opcode_lengths = try st.allocator().alloc(u8, opcode_base - 1);
1249 const standard_opcode_lengths = try di.allocator().alloc(u8, opcode_base - 1);
8541250
8551251 {
8561252 var i: usize = 0;
......@@ -859,19 +1255,19 @@ fn getLineNumberInfo(st: *ElfStackTrace, compile_unit: *const CompileUnit, targe
8591255 }
8601256 }
8611257
862 var include_directories = ArrayList([]u8).init(st.allocator());
1258 var include_directories = ArrayList([]u8).init(di.allocator());
8631259 try include_directories.append(compile_unit_cwd);
8641260 while (true) {
865 const dir = try st.readString();
1261 const dir = try di.readString();
8661262 if (dir.len == 0) break;
8671263 try include_directories.append(dir);
8681264 }
8691265
870 var file_entries = ArrayList(FileEntry).init(st.allocator());
1266 var file_entries = ArrayList(FileEntry).init(di.allocator());
8711267 var prog = LineNumberProgram.init(default_is_stmt, include_directories.toSliceConst(), &file_entries, target_address);
8721268
8731269 while (true) {
874 const file_name = try st.readString();
1270 const file_name = try di.readString();
8751271 if (file_name.len == 0) break;
8761272 const dir_index = try readULeb128(in_stream);
8771273 const mtime = try readULeb128(in_stream);
......@@ -900,11 +1296,11 @@ fn getLineNumberInfo(st: *ElfStackTrace, compile_unit: *const CompileUnit, targe
9001296 return error.MissingDebugInfo;
9011297 },
9021298 DW.LNE_set_address => {
903 const addr = try in_stream.readInt(st.elf.endian, usize);
1299 const addr = try in_stream.readInt(di.elf.endian, usize);
9041300 prog.address = addr;
9051301 },
9061302 DW.LNE_define_file => {
907 const file_name = try st.readString();
1303 const file_name = try di.readString();
9081304 const dir_index = try readULeb128(in_stream);
9091305 const mtime = try readULeb128(in_stream);
9101306 const len_bytes = try readULeb128(in_stream);
......@@ -962,7 +1358,7 @@ fn getLineNumberInfo(st: *ElfStackTrace, compile_unit: *const CompileUnit, targe
9621358 prog.address += inc_addr;
9631359 },
9641360 DW.LNS_fixed_advance_pc => {
965 const arg = try in_stream.readInt(st.elf.endian, u16);
1361 const arg = try in_stream.readInt(di.elf.endian, u16);
9661362 prog.address += arg;
9671363 },
9681364 DW.LNS_set_prologue_end => {},
......@@ -981,7 +1377,7 @@ fn getLineNumberInfo(st: *ElfStackTrace, compile_unit: *const CompileUnit, targe
9811377 return error.MissingDebugInfo;
9821378}
9831379
984fn scanAllCompileUnits(st: *ElfStackTrace) !void {
1380fn scanAllCompileUnits(st: *DebugInfo) !void {
9851381 const debug_info_end = st.debug_info.offset + st.debug_info.size;
9861382 var this_unit_offset = st.debug_info.offset;
9871383 var cu_index: usize = 0;
......@@ -1051,7 +1447,7 @@ fn scanAllCompileUnits(st: *ElfStackTrace) !void {
10511447 }
10521448}
10531449
1054fn findCompileUnit(st: *ElfStackTrace, target_address: u64) !*const CompileUnit {
1450fn findCompileUnit(st: *DebugInfo, target_address: u64) !*const CompileUnit {
10551451 var in_file_stream = io.FileInStream.init(&st.self_exe_file);
10561452 const in_stream = &in_file_stream.stream;
10571453 for (st.compile_unit_list.toSlice()) |*compile_unit| {
......@@ -1085,6 +1481,89 @@ fn findCompileUnit(st: *ElfStackTrace, target_address: u64) !*const CompileUnit
10851481 return error.MissingDebugInfo;
10861482}
10871483
1484fn readIntMem(ptr: *[*]const u8, comptime T: type, endian: builtin.Endian) T {
1485 const result = mem.readInt(ptr.*[0..@sizeOf(T)], T, endian);
1486 ptr.* += @sizeOf(T);
1487 return result;
1488}
1489
1490fn readByteMem(ptr: *[*]const u8) u8 {
1491 const result = ptr.*[0];
1492 ptr.* += 1;
1493 return result;
1494}
1495
1496fn readByteSignedMem(ptr: *[*]const u8) i8 {
1497 return @bitCast(i8, readByteMem(ptr));
1498}
1499
1500fn readInitialLengthMem(ptr: *[*]const u8, is_64: *bool) !u64 {
1501 const first_32_bits = mem.readIntLE(u32, ptr.*[0..4]);
1502 is_64.* = (first_32_bits == 0xffffffff);
1503 if (is_64.*) {
1504 ptr.* += 4;
1505 const result = mem.readIntLE(u64, ptr.*[0..8]);
1506 ptr.* += 8;
1507 return result;
1508 } else {
1509 if (first_32_bits >= 0xfffffff0) return error.InvalidDebugInfo;
1510 ptr.* += 4;
1511 return u64(first_32_bits);
1512 }
1513}
1514
1515fn readStringMem(ptr: *[*]const u8) []const u8 {
1516 const result = mem.toSliceConst(u8, ptr.*);
1517 ptr.* += result.len + 1;
1518 return result;
1519}
1520
1521fn readULeb128Mem(ptr: *[*]const u8) !u64 {
1522 var result: u64 = 0;
1523 var shift: usize = 0;
1524 var i: usize = 0;
1525
1526 while (true) {
1527 const byte = ptr.*[i];
1528 i += 1;
1529
1530 var operand: u64 = undefined;
1531
1532 if (@shlWithOverflow(u64, byte & 0b01111111, @intCast(u6, shift), &operand)) return error.InvalidDebugInfo;
1533
1534 result |= operand;
1535
1536 if ((byte & 0b10000000) == 0) {
1537 ptr.* += i;
1538 return result;
1539 }
1540
1541 shift += 7;
1542 }
1543}
1544fn readILeb128Mem(ptr: *[*]const u8) !i64 {
1545 var result: i64 = 0;
1546 var shift: usize = 0;
1547 var i: usize = 0;
1548
1549 while (true) {
1550 const byte = ptr.*[i];
1551 i += 1;
1552
1553 var operand: i64 = undefined;
1554 if (@shlWithOverflow(i64, byte & 0b01111111, @intCast(u6, shift), &operand)) return error.InvalidDebugInfo;
1555
1556 result |= operand;
1557 shift += 7;
1558
1559 if ((byte & 0b10000000) == 0) {
1560 if (shift < @sizeOf(i64) * 8 and (byte & 0b01000000) != 0) result |= -(i64(1) << @intCast(u6, shift));
1561 ptr.* += i;
1562 return result;
1563 }
1564 }
1565}
1566
10881567fn readInitialLength(comptime E: type, in_stream: *io.InStream(E), is_64: *bool) !u64 {
10891568 const first_32_bits = try in_stream.readIntLe(u32);
10901569 is_64.* = (first_32_bits == 0xffffffff);
......@@ -1141,7 +1620,7 @@ pub const global_allocator = &global_fixed_allocator.allocator;
11411620var global_fixed_allocator = std.heap.ThreadSafeFixedBufferAllocator.init(global_allocator_mem[0..]);
11421621var global_allocator_mem: [100 * 1024]u8 = undefined;
11431622
1144// TODO make thread safe
1623/// TODO multithreaded awareness
11451624var debug_info_allocator: ?*mem.Allocator = null;
11461625var debug_info_direct_allocator: std.heap.DirectAllocator = undefined;
11471626var debug_info_arena_allocator: std.heap.ArenaAllocator = undefined;
std/elf.zig+5
......@@ -869,6 +869,11 @@ pub const Phdr = switch (@sizeOf(usize)) {
869869 8 => Elf64_Phdr,
870870 else => @compileError("expected pointer size of 32 or 64"),
871871};
872pub const Shdr = switch (@sizeOf(usize)) {
873 4 => Elf32_Shdr,
874 8 => Elf64_Shdr,
875 else => @compileError("expected pointer size of 32 or 64"),
876};
872877pub const Sym = switch (@sizeOf(usize)) {
873878 4 => Elf32_Sym,
874879 8 => Elf64_Sym,
std/hash_map.zig+16
......@@ -408,6 +408,22 @@ test "iterator hash map" {
408408 assert(entry.value == values[0]);
409409}
410410
411pub fn getHashPtrAddrFn(comptime K: type) (fn (K) u32) {
412 return struct {
413 fn hash(key: K) u32 {
414 return getAutoHashFn(usize)(@ptrToInt(key));
415 }
416 }.hash;
417}
418
419pub fn getTrivialEqlFn(comptime K: type) (fn (K, K) bool) {
420 return struct {
421 fn eql(a: K, b: K) bool {
422 return a == b;
423 }
424 }.eql;
425}
426
411427pub fn getAutoHashFn(comptime K: type) (fn (K) u32) {
412428 return struct {
413429 fn hash(key: K) u32 {
std/index.zig+1
......@@ -24,6 +24,7 @@ pub const empty_import = @import("empty.zig");
2424pub const event = @import("event.zig");
2525pub const fmt = @import("fmt/index.zig");
2626pub const hash = @import("hash/index.zig");
27pub const hash_map = @import("hash_map.zig");
2728pub const heap = @import("heap.zig");
2829pub const io = @import("io.zig");
2930pub const json = @import("json.zig");
std/io.zig+6
......@@ -207,6 +207,12 @@ pub fn InStream(comptime ReadError: type) type {
207207 _ = try self.readByte();
208208 }
209209 }
210
211 pub fn readStruct(self: *Self, comptime T: type, ptr: *T) !void {
212 // Only extern and packed structs have defined in-memory layout.
213 assert(@typeInfo(T).Struct.layout != builtin.TypeInfo.ContainerLayout.Auto);
214 return self.readNoEof(@sliceToBytes((*[1]T)(ptr)[0..]));
215 }
210216 };
211217}
212218
std/macho.zig+322-146
......@@ -1,16 +1,18 @@
1const builtin = @import("builtin");
2const std = @import("index.zig");
3const io = std.io;
4const mem = std.mem;
51
6const MH_MAGIC_64 = 0xFEEDFACF;
7const MH_PIE = 0x200000;
8const LC_SYMTAB = 2;
2pub const mach_header = extern struct {
3 magic: u32,
4 cputype: cpu_type_t,
5 cpusubtype: cpu_subtype_t,
6 filetype: u32,
7 ncmds: u32,
8 sizeofcmds: u32,
9 flags: u32,
10};
911
10const MachHeader64 = packed struct {
12pub const mach_header_64 = extern struct {
1113 magic: u32,
12 cputype: u32,
13 cpusubtype: u32,
14 cputype: cpu_type_t,
15 cpusubtype: cpu_subtype_t,
1416 filetype: u32,
1517 ncmds: u32,
1618 sizeofcmds: u32,
......@@ -18,19 +20,138 @@ const MachHeader64 = packed struct {
1820 reserved: u32,
1921};
2022
21const LoadCommand = packed struct {
23pub const load_command = extern struct {
2224 cmd: u32,
2325 cmdsize: u32,
2426};
2527
26const SymtabCommand = packed struct {
27 symoff: u32,
28 nsyms: u32,
29 stroff: u32,
30 strsize: u32,
28
29/// The symtab_command contains the offsets and sizes of the link-edit 4.3BSD
30/// "stab" style symbol table information as described in the header files
31/// <nlist.h> and <stab.h>.
32pub const symtab_command = extern struct {
33 cmd: u32, /// LC_SYMTAB
34 cmdsize: u32, /// sizeof(struct symtab_command)
35 symoff: u32, /// symbol table offset
36 nsyms: u32, /// number of symbol table entries
37 stroff: u32, /// string table offset
38 strsize: u32, /// string table size in bytes
39};
40
41/// The linkedit_data_command contains the offsets and sizes of a blob
42/// of data in the __LINKEDIT segment.
43const linkedit_data_command = extern struct {
44 cmd: u32,/// LC_CODE_SIGNATURE, LC_SEGMENT_SPLIT_INFO, LC_FUNCTION_STARTS, LC_DATA_IN_CODE, LC_DYLIB_CODE_SIGN_DRS or LC_LINKER_OPTIMIZATION_HINT.
45 cmdsize: u32, /// sizeof(struct linkedit_data_command)
46 dataoff: u32 , /// file offset of data in __LINKEDIT segment
47 datasize: u32 , /// file size of data in __LINKEDIT segment
48};
49
50/// The segment load command indicates that a part of this file is to be
51/// mapped into the task's address space. The size of this segment in memory,
52/// vmsize, maybe equal to or larger than the amount to map from this file,
53/// filesize. The file is mapped starting at fileoff to the beginning of
54/// the segment in memory, vmaddr. The rest of the memory of the segment,
55/// if any, is allocated zero fill on demand. The segment's maximum virtual
56/// memory protection and initial virtual memory protection are specified
57/// by the maxprot and initprot fields. If the segment has sections then the
58/// section structures directly follow the segment command and their size is
59/// reflected in cmdsize.
60pub const segment_command = extern struct {
61 cmd: u32,/// LC_SEGMENT
62 cmdsize: u32,/// includes sizeof section structs
63 segname: [16]u8,/// segment name
64 vmaddr: u32,/// memory address of this segment
65 vmsize: u32,/// memory size of this segment
66 fileoff: u32,/// file offset of this segment
67 filesize: u32,/// amount to map from the file
68 maxprot: vm_prot_t,/// maximum VM protection
69 initprot: vm_prot_t,/// initial VM protection
70 nsects: u32,/// number of sections in segment
71 flags: u32,
72};
73
74/// The 64-bit segment load command indicates that a part of this file is to be
75/// mapped into a 64-bit task's address space. If the 64-bit segment has
76/// sections then section_64 structures directly follow the 64-bit segment
77/// command and their size is reflected in cmdsize.
78pub const segment_command_64 = extern struct {
79 cmd: u32, /// LC_SEGMENT_64
80 cmdsize: u32, /// includes sizeof section_64 structs
81 segname: [16]u8, /// segment name
82 vmaddr: u64, /// memory address of this segment
83 vmsize: u64, /// memory size of this segment
84 fileoff: u64, /// file offset of this segment
85 filesize: u64, /// amount to map from the file
86 maxprot: vm_prot_t, /// maximum VM protection
87 initprot: vm_prot_t, /// initial VM protection
88 nsects: u32, /// number of sections in segment
89 flags: u32,
90};
91
92/// A segment is made up of zero or more sections. Non-MH_OBJECT files have
93/// all of their segments with the proper sections in each, and padded to the
94/// specified segment alignment when produced by the link editor. The first
95/// segment of a MH_EXECUTE and MH_FVMLIB format file contains the mach_header
96/// and load commands of the object file before its first section. The zero
97/// fill sections are always last in their segment (in all formats). This
98/// allows the zeroed segment padding to be mapped into memory where zero fill
99/// sections might be. The gigabyte zero fill sections, those with the section
100/// type S_GB_ZEROFILL, can only be in a segment with sections of this type.
101/// These segments are then placed after all other segments.
102///
103/// The MH_OBJECT format has all of its sections in one segment for
104/// compactness. There is no padding to a specified segment boundary and the
105/// mach_header and load commands are not part of the segment.
106///
107/// Sections with the same section name, sectname, going into the same segment,
108/// segname, are combined by the link editor. The resulting section is aligned
109/// to the maximum alignment of the combined sections and is the new section's
110/// alignment. The combined sections are aligned to their original alignment in
111/// the combined section. Any padded bytes to get the specified alignment are
112/// zeroed.
113///
114/// The format of the relocation entries referenced by the reloff and nreloc
115/// fields of the section structure for mach object files is described in the
116/// header file <reloc.h>.
117pub const @"section" = extern struct {
118 sectname: [16]u8, /// name of this section
119 segname: [16]u8, /// segment this section goes in
120 addr: u32, /// memory address of this section
121 size: u32, /// size in bytes of this section
122 offset: u32, /// file offset of this section
123 @"align": u32, /// section alignment (power of 2)
124 reloff: u32, /// file offset of relocation entries
125 nreloc: u32, /// number of relocation entries
126 flags: u32, /// flags (section type and attributes
127 reserved1: u32, /// reserved (for offset or index)
128 reserved2: u32, /// reserved (for count or sizeof)
129};
130
131pub const section_64 = extern struct {
132 sectname: [16]u8, /// name of this section
133 segname: [16]u8, /// segment this section goes in
134 addr: u64, /// memory address of this section
135 size: u64, /// size in bytes of this section
136 offset: u32, /// file offset of this section
137 @"align": u32, /// section alignment (power of 2)
138 reloff: u32, /// file offset of relocation entries
139 nreloc: u32, /// number of relocation entries
140 flags: u32, /// flags (section type and attributes
141 reserved1: u32, /// reserved (for offset or index)
142 reserved2: u32, /// reserved (for count or sizeof)
143 reserved3: u32, /// reserved
144};
145
146pub const nlist = extern struct {
147 n_strx: u32,
148 n_type: u8,
149 n_sect: u8,
150 n_desc: i16,
151 n_value: u32,
31152};
32153
33const Nlist64 = packed struct {
154pub const nlist_64 = extern struct {
34155 n_strx: u32,
35156 n_type: u8,
36157 n_sect: u8,
......@@ -38,135 +159,190 @@ const Nlist64 = packed struct {
38159 n_value: u64,
39160};
40161
41pub const Symbol = struct {
42 name: []const u8,
43 address: u64,
162/// After MacOS X 10.1 when a new load command is added that is required to be
163/// understood by the dynamic linker for the image to execute properly the
164/// LC_REQ_DYLD bit will be or'ed into the load command constant. If the dynamic
165/// linker sees such a load command it it does not understand will issue a
166/// "unknown load command required for execution" error and refuse to use the
167/// image. Other load commands without this bit that are not understood will
168/// simply be ignored.
169pub const LC_REQ_DYLD = 0x80000000;
44170
45 fn addressLessThan(lhs: Symbol, rhs: Symbol) bool {
46 return lhs.address < rhs.address;
47 }
48};
171pub const LC_SEGMENT = 0x1; /// segment of this file to be mapped
172pub const LC_SYMTAB = 0x2; /// link-edit stab symbol table info
173pub const LC_SYMSEG = 0x3; /// link-edit gdb symbol table info (obsolete)
174pub const LC_THREAD = 0x4; /// thread
175pub const LC_UNIXTHREAD = 0x5; /// unix thread (includes a stack)
176pub const LC_LOADFVMLIB = 0x6; /// load a specified fixed VM shared library
177pub const LC_IDFVMLIB = 0x7; /// fixed VM shared library identification
178pub const LC_IDENT = 0x8; /// object identification info (obsolete)
179pub const LC_FVMFILE = 0x9; /// fixed VM file inclusion (internal use)
180pub const LC_PREPAGE = 0xa; /// prepage command (internal use)
181pub const LC_DYSYMTAB = 0xb; /// dynamic link-edit symbol table info
182pub const LC_LOAD_DYLIB = 0xc; /// load a dynamically linked shared library
183pub const LC_ID_DYLIB = 0xd; /// dynamically linked shared lib ident
184pub const LC_LOAD_DYLINKER = 0xe; /// load a dynamic linker
185pub const LC_ID_DYLINKER = 0xf; /// dynamic linker identification
186pub const LC_PREBOUND_DYLIB = 0x10; /// modules prebound for a dynamically
187pub const LC_ROUTINES = 0x11; /// image routines
188pub const LC_SUB_FRAMEWORK = 0x12; /// sub framework
189pub const LC_SUB_UMBRELLA = 0x13; /// sub umbrella
190pub const LC_SUB_CLIENT = 0x14; /// sub client
191pub const LC_SUB_LIBRARY = 0x15; /// sub library
192pub const LC_TWOLEVEL_HINTS = 0x16; /// two-level namespace lookup hints
193pub const LC_PREBIND_CKSUM = 0x17; /// prebind checksum
49194
50pub const SymbolTable = struct {
51 allocator: *mem.Allocator,
52 symbols: []const Symbol,
53 strings: []const u8,
54
55 // Doubles as an eyecatcher to calculate the PIE slide, see loadSymbols().
56 // Ideally we'd use _mh_execute_header because it's always at 0x100000000
57 // in the image but as it's located in a different section than executable
58 // code, its displacement is different.
59 pub fn deinit(self: *SymbolTable) void {
60 self.allocator.free(self.symbols);
61 self.symbols = []const Symbol{};
62
63 self.allocator.free(self.strings);
64 self.strings = []const u8{};
65 }
66
67 pub fn search(self: *const SymbolTable, address: usize) ?*const Symbol {
68 var min: usize = 0;
69 var max: usize = self.symbols.len - 1; // Exclude sentinel.
70 while (min < max) {
71 const mid = min + (max - min) / 2;
72 const curr = &self.symbols[mid];
73 const next = &self.symbols[mid + 1];
74 if (address >= next.address) {
75 min = mid + 1;
76 } else if (address < curr.address) {
77 max = mid;
78 } else {
79 return curr;
80 }
81 }
82 return null;
83 }
84};
195/// load a dynamically linked shared library that is allowed to be missing
196/// (all symbols are weak imported).
197pub const LC_LOAD_WEAK_DYLIB = (0x18 | LC_REQ_DYLD);
198
199pub const LC_SEGMENT_64 = 0x19; /// 64-bit segment of this file to be mapped
200pub const LC_ROUTINES_64 = 0x1a; /// 64-bit image routines
201pub const LC_UUID = 0x1b; /// the uuid
202pub const LC_RPATH = (0x1c | LC_REQ_DYLD); /// runpath additions
203pub const LC_CODE_SIGNATURE = 0x1d; /// local of code signature
204pub const LC_SEGMENT_SPLIT_INFO = 0x1e; /// local of info to split segments
205pub const LC_REEXPORT_DYLIB = (0x1f | LC_REQ_DYLD); /// load and re-export dylib
206pub const LC_LAZY_LOAD_DYLIB = 0x20; /// delay load of dylib until first use
207pub const LC_ENCRYPTION_INFO = 0x21; /// encrypted segment information
208pub const LC_DYLD_INFO = 0x22; /// compressed dyld information
209pub const LC_DYLD_INFO_ONLY = (0x22|LC_REQ_DYLD); /// compressed dyld information only
210pub const LC_LOAD_UPWARD_DYLIB = (0x23 | LC_REQ_DYLD); /// load upward dylib
211pub const LC_VERSION_MIN_MACOSX = 0x24; /// build for MacOSX min OS version
212pub const LC_VERSION_MIN_IPHONEOS = 0x25; /// build for iPhoneOS min OS version
213pub const LC_FUNCTION_STARTS = 0x26; /// compressed table of function start addresses
214pub const LC_DYLD_ENVIRONMENT = 0x27; /// string for dyld to treat like environment variable
215pub const LC_MAIN = (0x28|LC_REQ_DYLD); /// replacement for LC_UNIXTHREAD
216pub const LC_DATA_IN_CODE = 0x29; /// table of non-instructions in __text
217pub const LC_SOURCE_VERSION = 0x2A; /// source version used to build binary
218pub const LC_DYLIB_CODE_SIGN_DRS = 0x2B; /// Code signing DRs copied from linked dylibs
219pub const LC_ENCRYPTION_INFO_64 = 0x2C; /// 64-bit encrypted segment information
220pub const LC_LINKER_OPTION = 0x2D; /// linker options in MH_OBJECT files
221pub const LC_LINKER_OPTIMIZATION_HINT = 0x2E; /// optimization hints in MH_OBJECT files
222pub const LC_VERSION_MIN_TVOS = 0x2F; /// build for AppleTV min OS version
223pub const LC_VERSION_MIN_WATCHOS = 0x30; /// build for Watch min OS version
224pub const LC_NOTE = 0x31; /// arbitrary data included within a Mach-O file
225pub const LC_BUILD_VERSION = 0x32; /// build for platform min OS version
226
227pub const MH_MAGIC = 0xfeedface; /// the mach magic number
228pub const MH_CIGAM = 0xcefaedfe; /// NXSwapInt(MH_MAGIC)
229
230pub const MH_MAGIC_64 = 0xfeedfacf; /// the 64-bit mach magic number
231pub const MH_CIGAM_64 = 0xcffaedfe; /// NXSwapInt(MH_MAGIC_64)
232
233pub const MH_OBJECT = 0x1; /// relocatable object file
234pub const MH_EXECUTE = 0x2; /// demand paged executable file
235pub const MH_FVMLIB = 0x3; /// fixed VM shared library file
236pub const MH_CORE = 0x4; /// core file
237pub const MH_PRELOAD = 0x5; /// preloaded executable file
238pub const MH_DYLIB = 0x6; /// dynamically bound shared library
239pub const MH_DYLINKER = 0x7; /// dynamic link editor
240pub const MH_BUNDLE = 0x8; /// dynamically bound bundle file
241pub const MH_DYLIB_STUB = 0x9; /// shared library stub for static linking only, no section contents
242pub const MH_DSYM = 0xa; /// companion file with only debug sections
243pub const MH_KEXT_BUNDLE = 0xb; /// x86_64 kexts
244
245// Constants for the flags field of the mach_header
246
247pub const MH_NOUNDEFS = 0x1; /// the object file has no undefined references
248pub const MH_INCRLINK = 0x2; /// the object file is the output of an incremental link against a base file and can't be link edited again
249pub const MH_DYLDLINK = 0x4; /// the object file is input for the dynamic linker and can't be staticly link edited again
250pub const MH_BINDATLOAD = 0x8; /// the object file's undefined references are bound by the dynamic linker when loaded.
251pub const MH_PREBOUND = 0x10; /// the file has its dynamic undefined references prebound.
252pub const MH_SPLIT_SEGS = 0x20; /// the file has its read-only and read-write segments split
253pub const MH_LAZY_INIT = 0x40; /// the shared library init routine is to be run lazily via catching memory faults to its writeable segments (obsolete)
254pub const MH_TWOLEVEL = 0x80; /// the image is using two-level name space bindings
255pub const MH_FORCE_FLAT = 0x100; /// the executable is forcing all images to use flat name space bindings
256pub const MH_NOMULTIDEFS = 0x200; /// this umbrella guarantees no multiple defintions of symbols in its sub-images so the two-level namespace hints can always be used.
257pub const MH_NOFIXPREBINDING = 0x400; /// do not have dyld notify the prebinding agent about this executable
258pub const MH_PREBINDABLE = 0x800; /// the binary is not prebound but can have its prebinding redone. only used when MH_PREBOUND is not set.
259pub const MH_ALLMODSBOUND = 0x1000; /// indicates that this binary binds to all two-level namespace modules of its dependent libraries. only used when MH_PREBINDABLE and MH_TWOLEVEL are both set.
260pub const MH_SUBSECTIONS_VIA_SYMBOLS = 0x2000;/// safe to divide up the sections into sub-sections via symbols for dead code stripping
261pub const MH_CANONICAL = 0x4000; /// the binary has been canonicalized via the unprebind operation
262pub const MH_WEAK_DEFINES = 0x8000; /// the final linked image contains external weak symbols
263pub const MH_BINDS_TO_WEAK = 0x10000; /// the final linked image uses weak symbols
264
265pub const MH_ALLOW_STACK_EXECUTION = 0x20000;/// When this bit is set, all stacks in the task will be given stack execution privilege. Only used in MH_EXECUTE filetypes.
266pub const MH_ROOT_SAFE = 0x40000; /// When this bit is set, the binary declares it is safe for use in processes with uid zero
267
268pub const MH_SETUID_SAFE = 0x80000; /// When this bit is set, the binary declares it is safe for use in processes when issetugid() is true
269
270pub const MH_NO_REEXPORTED_DYLIBS = 0x100000; /// When this bit is set on a dylib, the static linker does not need to examine dependent dylibs to see if any are re-exported
271pub const MH_PIE = 0x200000; /// When this bit is set, the OS will load the main executable at a random address. Only used in MH_EXECUTE filetypes.
272pub const MH_DEAD_STRIPPABLE_DYLIB = 0x400000; /// Only for use on dylibs. When linking against a dylib that has this bit set, the static linker will automatically not create a LC_LOAD_DYLIB load command to the dylib if no symbols are being referenced from the dylib.
273pub const MH_HAS_TLV_DESCRIPTORS = 0x800000; /// Contains a section of type S_THREAD_LOCAL_VARIABLES
274
275pub const MH_NO_HEAP_EXECUTION = 0x1000000; /// When this bit is set, the OS will run the main executable with a non-executable heap even on platforms (e.g. i386) that don't require it. Only used in MH_EXECUTE filetypes.
276
277pub const MH_APP_EXTENSION_SAFE = 0x02000000; /// The code was linked for use in an application extension.
278
279pub const MH_NLIST_OUTOFSYNC_WITH_DYLDINFO = 0x04000000; /// The external symbols listed in the nlist symbol table do not include all the symbols listed in the dyld info.
280
281
282/// The flags field of a section structure is separated into two parts a section
283/// type and section attributes. The section types are mutually exclusive (it
284/// can only have one type) but the section attributes are not (it may have more
285/// than one attribute).
286/// 256 section types
287pub const SECTION_TYPE = 0x000000ff;
288pub const SECTION_ATTRIBUTES = 0xffffff00; /// 24 section attributes
289
290pub const S_REGULAR = 0x0; /// regular section
291pub const S_ZEROFILL = 0x1; /// zero fill on demand section
292pub const S_CSTRING_LITERALS = 0x2; /// section with only literal C string
293pub const S_4BYTE_LITERALS = 0x3; /// section with only 4 byte literals
294pub const S_8BYTE_LITERALS = 0x4; /// section with only 8 byte literals
295pub const S_LITERAL_POINTERS = 0x5; /// section with only pointers to
296
297
298pub const N_STAB = 0xe0; /// if any of these bits set, a symbolic debugging entry
299pub const N_PEXT = 0x10; /// private external symbol bit
300pub const N_TYPE = 0x0e; /// mask for the type bits
301pub const N_EXT = 0x01; /// external symbol bit, set for external symbols
302
303
304pub const N_GSYM = 0x20; /// global symbol: name,,NO_SECT,type,0
305pub const N_FNAME = 0x22; /// procedure name (f77 kludge): name,,NO_SECT,0,0
306pub const N_FUN = 0x24; /// procedure: name,,n_sect,linenumber,address
307pub const N_STSYM = 0x26; /// static symbol: name,,n_sect,type,address
308pub const N_LCSYM = 0x28; /// .lcomm symbol: name,,n_sect,type,address
309pub const N_BNSYM = 0x2e; /// begin nsect sym: 0,,n_sect,0,address
310pub const N_AST = 0x32; /// AST file path: name,,NO_SECT,0,0
311pub const N_OPT = 0x3c; /// emitted with gcc2_compiled and in gcc source
312pub const N_RSYM = 0x40; /// register sym: name,,NO_SECT,type,register
313pub const N_SLINE = 0x44; /// src line: 0,,n_sect,linenumber,address
314pub const N_ENSYM = 0x4e; /// end nsect sym: 0,,n_sect,0,address
315pub const N_SSYM = 0x60; /// structure elt: name,,NO_SECT,type,struct_offset
316pub const N_SO = 0x64; /// source file name: name,,n_sect,0,address
317pub const N_OSO = 0x66; /// object file name: name,,0,0,st_mtime
318pub const N_LSYM = 0x80; /// local sym: name,,NO_SECT,type,offset
319pub const N_BINCL = 0x82; /// include file beginning: name,,NO_SECT,0,sum
320pub const N_SOL = 0x84; /// #included file name: name,,n_sect,0,address
321pub const N_PARAMS = 0x86; /// compiler parameters: name,,NO_SECT,0,0
322pub const N_VERSION = 0x88; /// compiler version: name,,NO_SECT,0,0
323pub const N_OLEVEL = 0x8A; /// compiler -O level: name,,NO_SECT,0,0
324pub const N_PSYM = 0xa0; /// parameter: name,,NO_SECT,type,offset
325pub const N_EINCL = 0xa2; /// include file end: name,,NO_SECT,0,0
326pub const N_ENTRY = 0xa4; /// alternate entry: name,,n_sect,linenumber,address
327pub const N_LBRAC = 0xc0; /// left bracket: 0,,NO_SECT,nesting level,address
328pub const N_EXCL = 0xc2; /// deleted include file: name,,NO_SECT,0,sum
329pub const N_RBRAC = 0xe0; /// right bracket: 0,,NO_SECT,nesting level,address
330pub const N_BCOMM = 0xe2; /// begin common: name,,NO_SECT,0,0
331pub const N_ECOMM = 0xe4; /// end common: name,,n_sect,0,0
332pub const N_ECOML = 0xe8; /// end common (local name): 0,,n_sect,0,address
333pub const N_LENG = 0xfe; /// second stab entry with length information
334
335/// If a segment contains any sections marked with S_ATTR_DEBUG then all
336/// sections in that segment must have this attribute. No section other than
337/// a section marked with this attribute may reference the contents of this
338/// section. A section with this attribute may contain no symbols and must have
339/// a section type S_REGULAR. The static linker will not copy section contents
340/// from sections with this attribute into its output file. These sections
341/// generally contain DWARF debugging info.
342pub const S_ATTR_DEBUG = 0x02000000; /// a debug section
343
344pub const cpu_type_t = integer_t;
345pub const cpu_subtype_t = integer_t;
346pub const integer_t = c_int;
347pub const vm_prot_t = c_int;
85348
86pub fn loadSymbols(allocator: *mem.Allocator, in: *io.FileInStream) !SymbolTable {
87 var file = in.file;
88 try file.seekTo(0);
89
90 var hdr: MachHeader64 = undefined;
91 try readOneNoEof(in, MachHeader64, &hdr);
92 if (hdr.magic != MH_MAGIC_64) return error.MissingDebugInfo;
93 const is_pie = MH_PIE == (hdr.flags & MH_PIE);
94
95 var pos: usize = @sizeOf(@typeOf(hdr));
96 var ncmd: u32 = hdr.ncmds;
97 while (ncmd != 0) : (ncmd -= 1) {
98 try file.seekTo(pos);
99 var lc: LoadCommand = undefined;
100 try readOneNoEof(in, LoadCommand, &lc);
101 if (lc.cmd == LC_SYMTAB) break;
102 pos += lc.cmdsize;
103 } else {
104 return error.MissingDebugInfo;
105 }
106
107 var cmd: SymtabCommand = undefined;
108 try readOneNoEof(in, SymtabCommand, &cmd);
109
110 try file.seekTo(cmd.symoff);
111 var syms = try allocator.alloc(Nlist64, cmd.nsyms);
112 defer allocator.free(syms);
113 try readNoEof(in, Nlist64, syms);
114
115 try file.seekTo(cmd.stroff);
116 var strings = try allocator.alloc(u8, cmd.strsize);
117 errdefer allocator.free(strings);
118 try in.stream.readNoEof(strings);
119
120 var nsyms: usize = 0;
121 for (syms) |sym|
122 if (isSymbol(sym)) nsyms += 1;
123 if (nsyms == 0) return error.MissingDebugInfo;
124
125 var symbols = try allocator.alloc(Symbol, nsyms + 1); // Room for sentinel.
126 errdefer allocator.free(symbols);
127
128 var pie_slide: usize = 0;
129 var nsym: usize = 0;
130 for (syms) |sym| {
131 if (!isSymbol(sym)) continue;
132 const start = sym.n_strx;
133 const end = mem.indexOfScalarPos(u8, strings, start, 0).?;
134 const name = strings[start..end];
135 const address = sym.n_value;
136 symbols[nsym] = Symbol{ .name = name, .address = address };
137 nsym += 1;
138 if (is_pie and mem.eql(u8, name, "_SymbolTable_deinit")) {
139 pie_slide = @ptrToInt(SymbolTable.deinit) - address;
140 }
141 }
142
143 // Effectively a no-op, lld emits symbols in ascending order.
144 std.sort.sort(Symbol, symbols[0..nsyms], Symbol.addressLessThan);
145
146 // Insert the sentinel. Since we don't know where the last function ends,
147 // we arbitrarily limit it to the start address + 4 KB.
148 const top = symbols[nsyms - 1].address + 4096;
149 symbols[nsyms] = Symbol{ .name = "", .address = top };
150
151 if (pie_slide != 0) {
152 for (symbols) |*symbol|
153 symbol.address += pie_slide;
154 }
155
156 return SymbolTable{
157 .allocator = allocator,
158 .symbols = symbols,
159 .strings = strings,
160 };
161}
162
163fn readNoEof(in: *io.FileInStream, comptime T: type, result: []T) !void {
164 return in.stream.readNoEof(@sliceToBytes(result));
165}
166fn readOneNoEof(in: *io.FileInStream, comptime T: type, result: *T) !void {
167 return readNoEof(in, T, (*[1]T)(result)[0..]);
168}
169
170fn isSymbol(sym: *const Nlist64) bool {
171 return sym.n_value != 0 and sym.n_desc == 0;
172}
std/os/index.zig+29
......@@ -635,6 +635,35 @@ fn posixExecveErrnoToErr(err: usize) PosixExecveError {
635635pub var linux_aux_raw = []usize{0} ** 38;
636636pub var posix_environ_raw: [][*]u8 = undefined;
637637
638/// See std.elf for the constants.
639pub fn linuxGetAuxVal(index: usize) usize {
640 if (builtin.link_libc) {
641 return usize(std.c.getauxval(index));
642 } else {
643 return linux_aux_raw[index];
644 }
645}
646
647pub fn getBaseAddress() usize {
648 switch (builtin.os) {
649 builtin.Os.linux => {
650 const base = linuxGetAuxVal(std.elf.AT_BASE);
651 if (base != 0) {
652 return base;
653 }
654 const phdr = linuxGetAuxVal(std.elf.AT_PHDR);
655 const ElfHeader = switch (@sizeOf(usize)) {
656 4 => std.elf.Elf32_Ehdr,
657 8 => std.elf.Elf64_Ehdr,
658 else => @compileError("Unsupported architecture"),
659 };
660 return phdr - @sizeOf(ElfHeader);
661 },
662 builtin.Os.macosx => return @ptrToInt(&std.c._mh_execute_header),
663 else => @compileError("Unsupported OS"),
664 }
665}
666
638667/// Caller must free result when done.
639668/// TODO make this go through libc when we have it
640669pub fn getEnvMap(allocator: *Allocator) !BufMap {