authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2017-02-06 03:10:32-05:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2017-02-06 03:10:32-05:00
log07a71fc3221dfba05caea5a50ebe3dac5c76d643
treea7c56f5069bd9a04cbc2b590f4120691deb8fa06
parent28f63b8a4f2e55d2596a0e3daea106500a479791

improved behavior on debug safety crash

* instead of emitting a breakpoint for a debug safety crash, zig calls a panic function which prints an error message and a stack trace and then calls abort. * on freestanding OS, this panic function has a default implementation of a simple infinite loop. * users can override the panic implementation by providing `pub fn panic(message: []const u8) -> unreachable { }` * workaround for LLVM segfaulting when you try to use cold calling convention on ARM. closes #245

10 files changed, 255 insertions(+), 64 deletions(-)

CMakeLists.txt+8-7
......@@ -68,6 +68,10 @@ set(TEST_SOURCES
6868)
6969
7070set(C_HEADERS
71 "${CMAKE_SOURCE_DIR}/c_headers/Intrin.h"
72 "${CMAKE_SOURCE_DIR}/c_headers/__stddef_max_align_t.h"
73 "${CMAKE_SOURCE_DIR}/c_headers/__wmmintrin_aes.h"
74 "${CMAKE_SOURCE_DIR}/c_headers/__wmmintrin_pclmul.h"
7175 "${CMAKE_SOURCE_DIR}/c_headers/adxintrin.h"
7276 "${CMAKE_SOURCE_DIR}/c_headers/ammintrin.h"
7377 "${CMAKE_SOURCE_DIR}/c_headers/arm_acle.h"
......@@ -95,14 +99,13 @@ set(C_HEADERS
9599 "${CMAKE_SOURCE_DIR}/c_headers/htmxlintrin.h"
96100 "${CMAKE_SOURCE_DIR}/c_headers/ia32intrin.h"
97101 "${CMAKE_SOURCE_DIR}/c_headers/immintrin.h"
98 "${CMAKE_SOURCE_DIR}/c_headers/Intrin.h"
99102 "${CMAKE_SOURCE_DIR}/c_headers/inttypes.h"
100103 "${CMAKE_SOURCE_DIR}/c_headers/iso646.h"
101104 "${CMAKE_SOURCE_DIR}/c_headers/limits.h"
102105 "${CMAKE_SOURCE_DIR}/c_headers/lzcntintrin.h"
103106 "${CMAKE_SOURCE_DIR}/c_headers/mm3dnow.h"
104 "${CMAKE_SOURCE_DIR}/c_headers/mmintrin.h"
105107 "${CMAKE_SOURCE_DIR}/c_headers/mm_malloc.h"
108 "${CMAKE_SOURCE_DIR}/c_headers/mmintrin.h"
106109 "${CMAKE_SOURCE_DIR}/c_headers/nmmintrin.h"
107110 "${CMAKE_SOURCE_DIR}/c_headers/pmmintrin.h"
108111 "${CMAKE_SOURCE_DIR}/c_headers/popcntintrin.h"
......@@ -117,7 +120,6 @@ set(C_HEADERS
117120 "${CMAKE_SOURCE_DIR}/c_headers/stdatomic.h"
118121 "${CMAKE_SOURCE_DIR}/c_headers/stdbool.h"
119122 "${CMAKE_SOURCE_DIR}/c_headers/stddef.h"
120 "${CMAKE_SOURCE_DIR}/c_headers/__stddef_max_align_t.h"
121123 "${CMAKE_SOURCE_DIR}/c_headers/stdint.h"
122124 "${CMAKE_SOURCE_DIR}/c_headers/stdnoreturn.h"
123125 "${CMAKE_SOURCE_DIR}/c_headers/tbmintrin.h"
......@@ -127,9 +129,7 @@ set(C_HEADERS
127129 "${CMAKE_SOURCE_DIR}/c_headers/vadefs.h"
128130 "${CMAKE_SOURCE_DIR}/c_headers/varargs.h"
129131 "${CMAKE_SOURCE_DIR}/c_headers/vecintrin.h"
130 "${CMAKE_SOURCE_DIR}/c_headers/__wmmintrin_aes.h"
131132 "${CMAKE_SOURCE_DIR}/c_headers/wmmintrin.h"
132 "${CMAKE_SOURCE_DIR}/c_headers/__wmmintrin_pclmul.h"
133133 "${CMAKE_SOURCE_DIR}/c_headers/x86intrin.h"
134134 "${CMAKE_SOURCE_DIR}/c_headers/xmmintrin.h"
135135 "${CMAKE_SOURCE_DIR}/c_headers/xopintrin.h"
......@@ -202,6 +202,8 @@ install(FILES "${CMAKE_SOURCE_DIR}/std/bootstrap.zig" DESTINATION "${ZIG_STD_DES
202202install(FILES "${CMAKE_SOURCE_DIR}/std/builtin.zig" DESTINATION "${ZIG_STD_DEST}")
203203install(FILES "${CMAKE_SOURCE_DIR}/std/compiler_rt.zig" DESTINATION "${ZIG_STD_DEST}")
204204install(FILES "${CMAKE_SOURCE_DIR}/std/cstr.zig" DESTINATION "${ZIG_STD_DEST}")
205install(FILES "${CMAKE_SOURCE_DIR}/std/darwin.zig" DESTINATION "${ZIG_STD_DEST}")
206install(FILES "${CMAKE_SOURCE_DIR}/std/darwin_x86_64.zig" DESTINATION "${ZIG_STD_DEST}")
205207install(FILES "${CMAKE_SOURCE_DIR}/std/debug.zig" DESTINATION "${ZIG_STD_DEST}")
206208install(FILES "${CMAKE_SOURCE_DIR}/std/dwarf.zig" DESTINATION "${ZIG_STD_DEST}")
207209install(FILES "${CMAKE_SOURCE_DIR}/std/elf.zig" DESTINATION "${ZIG_STD_DEST}")
......@@ -214,13 +216,12 @@ install(FILES "${CMAKE_SOURCE_DIR}/std/io.zig" DESTINATION "${ZIG_STD_DEST}")
214216install(FILES "${CMAKE_SOURCE_DIR}/std/linux.zig" DESTINATION "${ZIG_STD_DEST}")
215217install(FILES "${CMAKE_SOURCE_DIR}/std/linux_i386.zig" DESTINATION "${ZIG_STD_DEST}")
216218install(FILES "${CMAKE_SOURCE_DIR}/std/linux_x86_64.zig" DESTINATION "${ZIG_STD_DEST}")
217install(FILES "${CMAKE_SOURCE_DIR}/std/darwin.zig" DESTINATION "${ZIG_STD_DEST}")
218install(FILES "${CMAKE_SOURCE_DIR}/std/darwin_x86_64.zig" DESTINATION "${ZIG_STD_DEST}")
219219install(FILES "${CMAKE_SOURCE_DIR}/std/list.zig" DESTINATION "${ZIG_STD_DEST}")
220220install(FILES "${CMAKE_SOURCE_DIR}/std/math.zig" DESTINATION "${ZIG_STD_DEST}")
221221install(FILES "${CMAKE_SOURCE_DIR}/std/mem.zig" DESTINATION "${ZIG_STD_DEST}")
222222install(FILES "${CMAKE_SOURCE_DIR}/std/net.zig" DESTINATION "${ZIG_STD_DEST}")
223223install(FILES "${CMAKE_SOURCE_DIR}/std/os.zig" DESTINATION "${ZIG_STD_DEST}")
224install(FILES "${CMAKE_SOURCE_DIR}/std/panic.zig" DESTINATION "${ZIG_STD_DEST}")
224225install(FILES "${CMAKE_SOURCE_DIR}/std/rand.zig" DESTINATION "${ZIG_STD_DEST}")
225226install(FILES "${CMAKE_SOURCE_DIR}/std/rand_test.zig" DESTINATION "${ZIG_STD_DEST}")
226227install(FILES "${CMAKE_SOURCE_DIR}/std/sort.zig" DESTINATION "${ZIG_STD_DEST}")
example/guess_number/main.zig+1-3
......@@ -18,9 +18,7 @@ pub fn main(args: [][]u8) -> %void {
1818 var line_buf : [20]u8 = undefined;
1919
2020 const line_len = io.stdin.read(line_buf) %% |err| {
21 %%io.stdout.printf("Unable to read from stdin: ");
22 %%io.stdout.printf(@errorName(err));
23 %%io.stdout.printf("\n");
21 %%io.stdout.printf("Unable to read from stdin: {}\n", @errorName(err));
2422 return err;
2523 };
2624
src/all_types.hpp+21
......@@ -1132,6 +1132,22 @@ struct BuiltinFnEntry {
11321132 LLVMValueRef fn_val;
11331133};
11341134
1135enum PanicMsgId {
1136 PanicMsgIdUnreachable,
1137 PanicMsgIdBoundsCheckFailure,
1138 PanicMsgIdCastNegativeToUnsigned,
1139 PanicMsgIdCastTruncatedData,
1140 PanicMsgIdIntegerOverflow,
1141 PanicMsgIdShiftOverflowedBits,
1142 PanicMsgIdDivisionByZero,
1143 PanicMsgIdExactDivisionRemainder,
1144 PanicMsgIdSliceWidenRemainder,
1145 PanicMsgIdUnwrapMaybeFail,
1146 PanicMsgIdUnwrapErrFail,
1147
1148 PanicMsgIdCount,
1149};
1150
11351151uint32_t fn_eval_hash(Scope*);
11361152bool fn_eval_eql(Scope *a, Scope *b);
11371153
......@@ -1210,6 +1226,7 @@ struct CodeGen {
12101226 bool strip_debug_symbols;
12111227 bool want_h_file;
12121228 bool have_exported_main;
1229 bool have_exported_panic;
12131230 bool link_libc;
12141231 Buf *libc_lib_dir;
12151232 Buf *libc_static_lib_dir;
......@@ -1230,6 +1247,7 @@ struct CodeGen {
12301247 bool is_native_target;
12311248 PackageTableEntry *root_package;
12321249 PackageTableEntry *std_package;
1250 PackageTableEntry *panic_package;
12331251 Buf *root_out_name;
12341252 bool windows_subsystem_windows;
12351253 bool windows_subsystem_console;
......@@ -1252,6 +1270,7 @@ struct CodeGen {
12521270 OutType out_type;
12531271 FnTableEntry *cur_fn;
12541272 FnTableEntry *main_fn;
1273 FnTableEntry *panic_fn;
12551274 LLVMValueRef cur_ret_ptr;
12561275 LLVMValueRef cur_fn_val;
12571276 ZigList<LLVMBasicBlockRef> break_block_stack;
......@@ -1292,6 +1311,8 @@ struct CodeGen {
12921311
12931312 IrInstruction *invalid_instruction;
12941313 ConstExprValue const_void_val;
1314
1315 ConstExprValue panic_msg_vals[PanicMsgIdCount];
12951316};
12961317
12971318enum VarLinkage {
src/analyze.cpp+68-22
......@@ -713,7 +713,13 @@ TypeTableEntry *get_fn_type(CodeGen *g, FnTypeId *fn_type_id) {
713713 fn_type->data.fn.fn_type_id = *fn_type_id;
714714
715715 if (fn_type_id->is_cold) {
716 fn_type->data.fn.calling_convention = LLVMColdCallConv;
716 if (g->zig_target.arch.arch == ZigLLVM_arm) {
717 // TODO we want to use coldcc here but it's causing a segfault on ARM
718 // https://llvm.org/bugs/show_bug.cgi?id=31875
719 fn_type->data.fn.calling_convention = LLVMCCallConv;
720 } else {
721 fn_type->data.fn.calling_convention = LLVMColdCallConv;
722 }
717723 } else if (fn_type_id->is_extern) {
718724 fn_type->data.fn.calling_convention = LLVMCCallConv;
719725 } else {
......@@ -725,8 +731,8 @@ TypeTableEntry *get_fn_type(CodeGen *g, FnTypeId *fn_type_id) {
725731 // populate the name of the type
726732 buf_resize(&fn_type->name, 0);
727733 const char *extern_str = fn_type_id->is_extern ? "extern " : "";
728 const char *naked_str = fn_type_id->is_naked ? "naked " : "";
729 const char *cold_str = fn_type_id->is_cold ? "cold " : "";
734 const char *naked_str = fn_type_id->is_naked ? "nakedcc " : "";
735 const char *cold_str = fn_type_id->is_cold ? "coldcc " : "";
730736 buf_appendf(&fn_type->name, "%s%s%sfn(", extern_str, naked_str, cold_str);
731737 for (size_t i = 0; i < fn_type_id->param_count; i += 1) {
732738 FnTypeParamInfo *param_info = &fn_type_id->param_info[i];
......@@ -1572,6 +1578,33 @@ static bool scope_is_root_decls(Scope *scope) {
15721578 zig_unreachable();
15731579}
15741580
1581static void wrong_panic_prototype(CodeGen *g, AstNode *proto_node, TypeTableEntry *fn_type) {
1582 add_node_error(g, proto_node,
1583 buf_sprintf("expected 'fn([]const u8) -> unreachable', found '%s'",
1584 buf_ptr(&fn_type->name)));
1585}
1586
1587static void typecheck_panic_fn(CodeGen *g) {
1588 assert(g->panic_fn);
1589
1590 AstNode *proto_node = g->panic_fn->proto_node;
1591 assert(proto_node->type == NodeTypeFnProto);
1592 TypeTableEntry *fn_type = g->panic_fn->type_entry;
1593 FnTypeId *fn_type_id = &fn_type->data.fn.fn_type_id;
1594 if (fn_type_id->param_count != 1) {
1595 return wrong_panic_prototype(g, proto_node, fn_type);
1596 }
1597 TypeTableEntry *const_u8_slice = get_slice_type(g, g->builtin_types.entry_u8, true);
1598 if (fn_type_id->param_info[0].type != const_u8_slice) {
1599 return wrong_panic_prototype(g, proto_node, fn_type);
1600 }
1601
1602 TypeTableEntry *actual_return_type = fn_type_id->return_type;
1603 if (actual_return_type != g->builtin_types.entry_unreachable) {
1604 return wrong_panic_prototype(g, proto_node, fn_type);
1605 }
1606}
1607
15751608static void resolve_decl_fn(CodeGen *g, TldFn *tld_fn) {
15761609 ImportTableEntry *import = tld_fn->base.import;
15771610 AstNode *proto_node = tld_fn->base.source_node;
......@@ -1612,27 +1645,39 @@ static void resolve_decl_fn(CodeGen *g, TldFn *tld_fn) {
16121645 if (fn_def_node)
16131646 g->fn_defs.append(fn_table_entry);
16141647
1615 bool is_main_fn = scope_is_root_decls(tld_fn->base.parent_scope) &&
1616 (import == g->root_import) && buf_eql_str(&fn_table_entry->symbol_name, "main");
1617 if (is_main_fn)
1618 g->main_fn = fn_table_entry;
1619
1620 if (is_main_fn && !g->link_libc && tld_fn->base.visib_mod != VisibModExport) {
1621 TypeTableEntry *err_void = get_error_type(g, g->builtin_types.entry_void);
1622 TypeTableEntry *actual_return_type = fn_table_entry->type_entry->data.fn.fn_type_id.return_type;
1623 if (actual_return_type != err_void) {
1624 add_node_error(g, fn_proto->return_type,
1625 buf_sprintf("expected return type of main to be '%%void', instead is '%s'",
1626 buf_ptr(&actual_return_type->name)));
1648 if (import == g->root_import && scope_is_root_decls(tld_fn->base.parent_scope)) {
1649 if (buf_eql_str(&fn_table_entry->symbol_name, "main")) {
1650 g->main_fn = fn_table_entry;
1651
1652 if (!g->link_libc && tld_fn->base.visib_mod != VisibModExport) {
1653 TypeTableEntry *err_void = get_error_type(g, g->builtin_types.entry_void);
1654 TypeTableEntry *actual_return_type = fn_table_entry->type_entry->data.fn.fn_type_id.return_type;
1655 if (actual_return_type != err_void) {
1656 add_node_error(g, fn_proto->return_type,
1657 buf_sprintf("expected return type of main to be '%%void', instead is '%s'",
1658 buf_ptr(&actual_return_type->name)));
1659 }
1660 }
1661 } else if (buf_eql_str(&fn_table_entry->symbol_name, "panic")) {
1662 g->panic_fn = fn_table_entry;
1663 typecheck_panic_fn(g);
1664 }
1665 } else if (import->package == g->panic_package && scope_is_root_decls(tld_fn->base.parent_scope)) {
1666 if (buf_eql_str(&fn_table_entry->symbol_name, "panic")) {
1667 g->panic_fn = fn_table_entry;
1668 typecheck_panic_fn(g);
16271669 }
16281670 }
16291671 }
16301672}
16311673
16321674static void add_top_level_decl(CodeGen *g, ScopeDecls *decls_scope, Tld *tld) {
1633 bool want_to_resolve = (g->check_unused || g->is_test_build || tld->visib_mod == VisibModExport);
1634 if (want_to_resolve)
1675 if (g->check_unused || g->is_test_build || tld->visib_mod == VisibModExport ||
1676 (buf_eql_str(tld->name, "panic") &&
1677 (decls_scope->import->package == g->panic_package || decls_scope->import == g->root_import)))
1678 {
16351679 g->resolve_queue.append(tld);
1680 }
16361681
16371682 auto entry = decls_scope->decl_table.put_unique(tld->name, tld);
16381683 if (entry) {
......@@ -2548,9 +2593,6 @@ ImportTableEntry *add_source_file(CodeGen *g, PackageTableEntry *package,
25482593 assert(import_entry->root);
25492594 if (g->verbose) {
25502595 ast_print(stderr, import_entry->root, 0);
2551 //fprintf(stderr, "\nReformatted Source:\n");
2552 //fprintf(stderr, "---------------------\n");
2553 //ast_render(stderr, import_entry->root, 4);
25542596 }
25552597
25562598 import_entry->di_file = ZigLLVMCreateFile(g->dbuilder, buf_ptr(src_basename), buf_ptr(src_dirname));
......@@ -2571,8 +2613,12 @@ ImportTableEntry *add_source_file(CodeGen *g, PackageTableEntry *package,
25712613
25722614 bool is_pub = (proto_node->data.fn_proto.visib_mod == VisibModPub);
25732615
2574 if (buf_eql_str(proto_name, "main") && is_pub) {
2575 g->have_exported_main = true;
2616 if (is_pub) {
2617 if (buf_eql_str(proto_name, "main")) {
2618 g->have_exported_main = true;
2619 } else if (buf_eql_str(proto_name, "panic")) {
2620 g->have_exported_panic = true;
2621 }
25762622 }
25772623 }
25782624 }
src/codegen.cpp+71-13
......@@ -450,8 +450,56 @@ static bool ir_want_debug_safety(CodeGen *g, IrInstruction *instruction) {
450450 return true;
451451}
452452
453static void gen_debug_safety_crash(CodeGen *g) {
454 LLVMBuildCall(g->builder, g->trap_fn_val, nullptr, 0, "");
453static Buf *panic_msg_buf(PanicMsgId msg_id) {
454 switch (msg_id) {
455 case PanicMsgIdCount:
456 zig_unreachable();
457 case PanicMsgIdBoundsCheckFailure:
458 return buf_create_from_str("index out of bounds");
459 case PanicMsgIdCastNegativeToUnsigned:
460 return buf_create_from_str("attempt to cast negative value to unsigned integer");
461 case PanicMsgIdCastTruncatedData:
462 return buf_create_from_str("integer cast truncated bits");
463 case PanicMsgIdIntegerOverflow:
464 return buf_create_from_str("integer overflow");
465 case PanicMsgIdShiftOverflowedBits:
466 return buf_create_from_str("left shift overflowed bits");
467 case PanicMsgIdDivisionByZero:
468 return buf_create_from_str("division by zero");
469 case PanicMsgIdExactDivisionRemainder:
470 return buf_create_from_str("exact division produced remainder");
471 case PanicMsgIdSliceWidenRemainder:
472 return buf_create_from_str("slice widening size mismatch");
473 case PanicMsgIdUnwrapMaybeFail:
474 return buf_create_from_str("attempt to unwrap null");
475 case PanicMsgIdUnwrapErrFail:
476 return buf_create_from_str("attempt to unwrap error");
477 case PanicMsgIdUnreachable:
478 return buf_create_from_str("reached unreachable code");
479 }
480 zig_unreachable();
481}
482
483static LLVMValueRef get_panic_msg_ptr_val(CodeGen *g, PanicMsgId msg_id) {
484 ConstExprValue *val = &g->panic_msg_vals[msg_id];
485 if (val->llvm_global)
486 return val->llvm_global;
487
488 Buf *buf_msg = panic_msg_buf(msg_id);
489 ConstExprValue *array_val = create_const_str_lit(g, buf_msg);
490 init_const_slice(g, val, array_val, 0, buf_len(buf_msg), true);
491
492 render_const_val_global(g, val, "");
493 render_const_val(g, val);
494
495 assert(val->llvm_global);
496 return val->llvm_global;
497}
498
499static void gen_debug_safety_crash(CodeGen *g, PanicMsgId msg_id) {
500 LLVMValueRef fn_val = fn_llvm_value(g, g->panic_fn);
501 LLVMValueRef msg_arg = get_panic_msg_ptr_val(g, msg_id);
502 ZigLLVMBuildCall(g->builder, fn_val, &msg_arg, 1, g->panic_fn->type_entry->data.fn.calling_convention, "");
455503 LLVMBuildUnreachable(g->builder);
456504}
457505
......@@ -477,7 +525,7 @@ static void add_bounds_check(CodeGen *g, LLVMValueRef target_val,
477525 LLVMBuildCondBr(g->builder, lower_ok_val, lower_ok_block, bounds_check_fail_block);
478526
479527 LLVMPositionBuilderAtEnd(g->builder, bounds_check_fail_block);
480 gen_debug_safety_crash(g);
528 gen_debug_safety_crash(g, PanicMsgIdBoundsCheckFailure);
481529
482530 if (upper_value) {
483531 LLVMPositionBuilderAtEnd(g->builder, lower_ok_block);
......@@ -520,7 +568,7 @@ static LLVMValueRef gen_widen_or_shorten(CodeGen *g, bool want_debug_safety, Typ
520568 LLVMBuildCondBr(g->builder, ok_bit, ok_block, fail_block);
521569
522570 LLVMPositionBuilderAtEnd(g->builder, fail_block);
523 gen_debug_safety_crash(g);
571 gen_debug_safety_crash(g, PanicMsgIdCastNegativeToUnsigned);
524572
525573 LLVMPositionBuilderAtEnd(g->builder, ok_block);
526574 }
......@@ -559,7 +607,7 @@ static LLVMValueRef gen_widen_or_shorten(CodeGen *g, bool want_debug_safety, Typ
559607 LLVMBuildCondBr(g->builder, ok_bit, ok_block, fail_block);
560608
561609 LLVMPositionBuilderAtEnd(g->builder, fail_block);
562 gen_debug_safety_crash(g);
610 gen_debug_safety_crash(g, PanicMsgIdCastTruncatedData);
563611
564612 LLVMPositionBuilderAtEnd(g->builder, ok_block);
565613 return trunc_val;
......@@ -587,7 +635,7 @@ static LLVMValueRef gen_overflow_op(CodeGen *g, TypeTableEntry *type_entry, AddS
587635 LLVMBuildCondBr(g->builder, overflow_bit, fail_block, ok_block);
588636
589637 LLVMPositionBuilderAtEnd(g->builder, fail_block);
590 gen_debug_safety_crash(g);
638 gen_debug_safety_crash(g, PanicMsgIdIntegerOverflow);
591639
592640 LLVMPositionBuilderAtEnd(g->builder, ok_block);
593641 return result;
......@@ -748,7 +796,7 @@ static LLVMValueRef gen_overflow_shl_op(CodeGen *g, TypeTableEntry *type_entry,
748796 LLVMBuildCondBr(g->builder, ok_bit, ok_block, fail_block);
749797
750798 LLVMPositionBuilderAtEnd(g->builder, fail_block);
751 gen_debug_safety_crash(g);
799 gen_debug_safety_crash(g, PanicMsgIdShiftOverflowedBits);
752800
753801 LLVMPositionBuilderAtEnd(g->builder, ok_block);
754802 return result;
......@@ -773,7 +821,7 @@ static LLVMValueRef gen_div(CodeGen *g, bool want_debug_safety, LLVMValueRef val
773821 LLVMBuildCondBr(g->builder, is_zero_bit, fail_block, ok_block);
774822
775823 LLVMPositionBuilderAtEnd(g->builder, fail_block);
776 gen_debug_safety_crash(g);
824 gen_debug_safety_crash(g, PanicMsgIdDivisionByZero);
777825
778826 LLVMPositionBuilderAtEnd(g->builder, ok_block);
779827 }
......@@ -801,7 +849,7 @@ static LLVMValueRef gen_div(CodeGen *g, bool want_debug_safety, LLVMValueRef val
801849 LLVMBuildCondBr(g->builder, ok_bit, ok_block, fail_block);
802850
803851 LLVMPositionBuilderAtEnd(g->builder, fail_block);
804 gen_debug_safety_crash(g);
852 gen_debug_safety_crash(g, PanicMsgIdExactDivisionRemainder);
805853
806854 LLVMPositionBuilderAtEnd(g->builder, ok_block);
807855 }
......@@ -1038,7 +1086,7 @@ static LLVMValueRef ir_render_cast(CodeGen *g, IrExecutable *executable,
10381086 LLVMBuildCondBr(g->builder, ok_bit, ok_block, fail_block);
10391087
10401088 LLVMPositionBuilderAtEnd(g->builder, fail_block);
1041 gen_debug_safety_crash(g);
1089 gen_debug_safety_crash(g, PanicMsgIdSliceWidenRemainder);
10421090
10431091 LLVMPositionBuilderAtEnd(g->builder, ok_block);
10441092 }
......@@ -1162,7 +1210,7 @@ static LLVMValueRef ir_render_unreachable(CodeGen *g, IrExecutable *executable,
11621210 IrInstructionUnreachable *unreachable_instruction)
11631211{
11641212 if (ir_want_debug_safety(g, &unreachable_instruction->base) || g->is_test_build) {
1165 gen_debug_safety_crash(g);
1213 gen_debug_safety_crash(g, PanicMsgIdUnreachable);
11661214 } else {
11671215 LLVMBuildUnreachable(g->builder);
11681216 }
......@@ -1622,7 +1670,7 @@ static LLVMValueRef ir_render_unwrap_maybe(CodeGen *g, IrExecutable *executable,
16221670 LLVMBuildCondBr(g->builder, non_null_bit, ok_block, fail_block);
16231671
16241672 LLVMPositionBuilderAtEnd(g->builder, fail_block);
1625 gen_debug_safety_crash(g);
1673 gen_debug_safety_crash(g, PanicMsgIdUnwrapMaybeFail);
16261674
16271675 LLVMPositionBuilderAtEnd(g->builder, ok_block);
16281676 }
......@@ -2107,7 +2155,7 @@ static LLVMValueRef ir_render_unwrap_err_payload(CodeGen *g, IrExecutable *execu
21072155 LLVMBuildCondBr(g->builder, cond_val, ok_block, err_block);
21082156
21092157 LLVMPositionBuilderAtEnd(g->builder, err_block);
2110 gen_debug_safety_crash(g);
2158 gen_debug_safety_crash(g, PanicMsgIdUnwrapErrFail);
21112159
21122160 LLVMPositionBuilderAtEnd(g->builder, ok_block);
21132161 }
......@@ -3849,6 +3897,12 @@ static PackageTableEntry *create_bootstrap_pkg(CodeGen *g) {
38493897 return package;
38503898}
38513899
3900static PackageTableEntry *create_panic_pkg(CodeGen *g) {
3901 PackageTableEntry *package = new_package(buf_ptr(g->zig_std_dir), "");
3902 package->package_table.put(buf_create_from_str("std"), g->std_package);
3903 return package;
3904}
3905
38523906void codegen_add_root_code(CodeGen *g, Buf *src_dir, Buf *src_basename, Buf *source_code) {
38533907 Buf source_path = BUF_INIT;
38543908 os_path_join(src_dir, src_basename, &source_path);
......@@ -3873,6 +3927,10 @@ void codegen_add_root_code(CodeGen *g, Buf *src_dir, Buf *src_basename, Buf *sou
38733927 g->bootstrap_import = add_special_code(g, create_bootstrap_pkg(g), "bootstrap.zig");
38743928 }
38753929 }
3930 if (!g->have_exported_panic) {
3931 g->panic_package = create_panic_pkg(g);
3932 add_special_code(g, g->panic_package, "panic.zig");
3933 }
38763934
38773935 if (g->verbose) {
38783936 fprintf(stderr, "\nIR Generation and Semantic Analysis:\n");
src/ir.cpp-10
......@@ -3878,20 +3878,10 @@ static IrInstruction *ir_gen_builtin_fn_call(IrBuilder *irb, Scope *scope, AstNo
38783878 if (arg0_value == irb->codegen->invalid_instruction)
38793879 return arg0_value;
38803880
3881 if (exec_fn_entry(irb->exec)) {
3882 add_node_error(irb->codegen, node, buf_sprintf("import valid only at global scope"));
3883 return irb->codegen->invalid_instruction;
3884 }
3885
38863881 return ir_build_import(irb, scope, node, arg0_value);
38873882 }
38883883 case BuiltinFnIdCImport:
38893884 {
3890 if (exec_fn_entry(irb->exec)) {
3891 add_node_error(irb->codegen, node, buf_sprintf("C import valid only at global scope"));
3892 return irb->codegen->invalid_instruction;
3893 }
3894
38953885 return ir_build_c_import(irb, scope, node);
38963886 }
38973887 case BuiltinFnIdCInclude:
std/bootstrap.zig+3-2
......@@ -1,8 +1,9 @@
11// This file is in a package which has the root source file exposed as "@root".
22
33const root = @import("@root");
4const linux = @import("linux.zig");
5const cstr = @import("cstr.zig");
4const std = @import("std");
5const linux = std.linux;
6const cstr = std.cstr;
67
78const want_start_symbol = switch(@compileVar("os")) {
89 Os.linux => true,
std/debug.zig+2
......@@ -42,6 +42,8 @@ pub fn writeStackTrace(out_stream: &io.OutStream) -> %void {
4242 st.debug_str = (%return st.elf.findSection(".debug_str")) ?? return error.MissingDebugInfo;
4343 %return scanAllCompileUnits(st);
4444
45 %return out_stream.printf("(...work-in-progress stack unwinding code follows...)\n");
46
4547 var maybe_fp: ?&const u8 = @frameAddress();
4648 while (true) {
4749 const fp = maybe_fp ?? break;
std/panic.zig created+33
......@@ -0,0 +1,33 @@
1// This file is included if and only if the user's main source file does not
2// include a public panic function.
3// If this file wants to import other files *by name*, support for that would
4// have to be added in the compiler.
5
6var panicking = false;
7pub coldcc fn panic(message: []const u8) -> unreachable {
8 if (@compileVar("os") == Os.freestanding) {
9 while (true) {}
10 } else {
11 const std = @import("std");
12 const io = std.io;
13 const debug = std.debug;
14 const os = std.os;
15
16 // TODO
17 // if (@atomicRmw(AtomicOp.XChg, &panicking, true, AtomicOrder.SeqCst)) {
18 if (panicking) {
19 // Panicked during a panic.
20 // TODO detect if a different thread caused the panic, because in that case
21 // we would want to return here instead of calling abort, so that the thread
22 // which first called panic can finish printing a stack trace.
23 os.abort();
24 } else {
25 panicking = true;
26 }
27
28 %%io.stderr.printf("{}\n", message);
29 %%debug.printStackTrace();
30
31 os.abort();
32 }
33}
test/run_tests.cpp+48-7
......@@ -1167,13 +1167,6 @@ fn f(n: Number) -> i32 {
11671167}
11681168 )SOURCE", 1, ".tmp_source.zig:9:5: error: enumeration value 'Number.Four' not handled in switch");
11691169
1170 add_compile_fail_case("import inside function body", R"SOURCE(
1171fn f() {
1172 const std = @import("std");
1173}
1174 )SOURCE", 1, ".tmp_source.zig:3:17: error: import valid only at global scope");
1175
1176
11771170 add_compile_fail_case("normal string with newline", R"SOURCE(
11781171const foo = "a
11791172b";
......@@ -1675,6 +1668,10 @@ const some_data: [100]u8 = {
16751668
16761669static void add_debug_safety_test_cases(void) {
16771670 add_debug_safety_case("out of bounds slice access", R"SOURCE(
1671pub fn panic(message: []const u8) -> unreachable {
1672 @breakpoint();
1673 while (true) {}
1674}
16781675pub fn main(args: [][]u8) -> %void {
16791676 const a = []i32{1, 2, 3, 4};
16801677 baz(bar(a));
......@@ -1686,6 +1683,10 @@ fn baz(a: i32) { }
16861683 )SOURCE");
16871684
16881685 add_debug_safety_case("integer addition overflow", R"SOURCE(
1686pub fn panic(message: []const u8) -> unreachable {
1687 @breakpoint();
1688 while (true) {}
1689}
16891690error Whatever;
16901691pub fn main(args: [][]u8) -> %void {
16911692 const x = add(65530, 10);
......@@ -1697,6 +1698,10 @@ fn add(a: u16, b: u16) -> u16 {
16971698 )SOURCE");
16981699
16991700 add_debug_safety_case("integer subtraction overflow", R"SOURCE(
1701pub fn panic(message: []const u8) -> unreachable {
1702 @breakpoint();
1703 while (true) {}
1704}
17001705error Whatever;
17011706pub fn main(args: [][]u8) -> %void {
17021707 const x = sub(10, 20);
......@@ -1708,6 +1713,10 @@ fn sub(a: u16, b: u16) -> u16 {
17081713 )SOURCE");
17091714
17101715 add_debug_safety_case("integer multiplication overflow", R"SOURCE(
1716pub fn panic(message: []const u8) -> unreachable {
1717 @breakpoint();
1718 while (true) {}
1719}
17111720error Whatever;
17121721pub fn main(args: [][]u8) -> %void {
17131722 const x = mul(300, 6000);
......@@ -1719,6 +1728,10 @@ fn mul(a: u16, b: u16) -> u16 {
17191728 )SOURCE");
17201729
17211730 add_debug_safety_case("integer negation overflow", R"SOURCE(
1731pub fn panic(message: []const u8) -> unreachable {
1732 @breakpoint();
1733 while (true) {}
1734}
17221735error Whatever;
17231736pub fn main(args: [][]u8) -> %void {
17241737 const x = neg(-32768);
......@@ -1730,6 +1743,10 @@ fn neg(a: i16) -> i16 {
17301743 )SOURCE");
17311744
17321745 add_debug_safety_case("signed shift left overflow", R"SOURCE(
1746pub fn panic(message: []const u8) -> unreachable {
1747 @breakpoint();
1748 while (true) {}
1749}
17331750error Whatever;
17341751pub fn main(args: [][]u8) -> %void {
17351752 const x = shl(-16385, 1);
......@@ -1741,6 +1758,10 @@ fn shl(a: i16, b: i16) -> i16 {
17411758 )SOURCE");
17421759
17431760 add_debug_safety_case("unsigned shift left overflow", R"SOURCE(
1761pub fn panic(message: []const u8) -> unreachable {
1762 @breakpoint();
1763 while (true) {}
1764}
17441765error Whatever;
17451766pub fn main(args: [][]u8) -> %void {
17461767 const x = shl(0b0010111111111111, 3);
......@@ -1752,6 +1773,10 @@ fn shl(a: u16, b: u16) -> u16 {
17521773 )SOURCE");
17531774
17541775 add_debug_safety_case("integer division by zero", R"SOURCE(
1776pub fn panic(message: []const u8) -> unreachable {
1777 @breakpoint();
1778 while (true) {}
1779}
17551780error Whatever;
17561781pub fn main(args: [][]u8) -> %void {
17571782 const x = div0(999, 0);
......@@ -1762,6 +1787,10 @@ fn div0(a: i32, b: i32) -> i32 {
17621787 )SOURCE");
17631788
17641789 add_debug_safety_case("exact division failure", R"SOURCE(
1790pub fn panic(message: []const u8) -> unreachable {
1791 @breakpoint();
1792 while (true) {}
1793}
17651794error Whatever;
17661795pub fn main(args: [][]u8) -> %void {
17671796 const x = divExact(10, 3);
......@@ -1773,6 +1802,10 @@ fn divExact(a: i32, b: i32) -> i32 {
17731802 )SOURCE");
17741803
17751804 add_debug_safety_case("cast []u8 to bigger slice of wrong size", R"SOURCE(
1805pub fn panic(message: []const u8) -> unreachable {
1806 @breakpoint();
1807 while (true) {}
1808}
17761809error Whatever;
17771810pub fn main(args: [][]u8) -> %void {
17781811 const x = widenSlice([]u8{1, 2, 3, 4, 5});
......@@ -1784,6 +1817,10 @@ fn widenSlice(slice: []u8) -> []i32 {
17841817 )SOURCE");
17851818
17861819 add_debug_safety_case("value does not fit in shortening cast", R"SOURCE(
1820pub fn panic(message: []const u8) -> unreachable {
1821 @breakpoint();
1822 while (true) {}
1823}
17871824error Whatever;
17881825pub fn main(args: [][]u8) -> %void {
17891826 const x = shorten_cast(200);
......@@ -1795,6 +1832,10 @@ fn shorten_cast(x: i32) -> i8 {
17951832 )SOURCE");
17961833
17971834 add_debug_safety_case("signed integer not fitting in cast to unsigned integer", R"SOURCE(
1835pub fn panic(message: []const u8) -> unreachable {
1836 @breakpoint();
1837 while (true) {}
1838}
17981839error Whatever;
17991840pub fn main(args: [][]u8) -> %void {
18001841 const x = unsigned_cast(-10);