authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2017-04-24 12:01:19-04:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2017-04-24 12:14:45-04:00
log245eed8afee899cb0d0a2dac60c8a1edc6be654d
treec8aae712c859577218e818350d82ba24500a2d4e
parent08a871f625aaf75ca47ea6bbc6304587c4bbae86

better stack traces for ELF x86_64


10 files changed, 573 insertions(+), 68 deletions(-)

src/analyze.cpp+1
......@@ -2894,6 +2894,7 @@ ImportTableEntry *add_source_file(CodeGen *g, PackageTableEntry *package,
28942894 ast_print(stderr, import_entry->root, 0);
28952895 }
28962896
2897 // TODO: assert that src_basename has no '/' in it
28972898 import_entry->di_file = ZigLLVMCreateFile(g->dbuilder, buf_ptr(src_basename), buf_ptr(src_dirname));
28982899 g->import_table.put(abs_full_path, import_entry);
28992900 g->import_queue.append(import_entry);
src/codegen.cpp+1-1
......@@ -4647,7 +4647,7 @@ static void init(CodeGen *g, Buf *source_path) {
46474647 bool is_optimized = g->is_release_build;
46484648 const char *flags = "";
46494649 unsigned runtime_version = 0;
4650 ZigLLVMDIFile *compile_unit_file = ZigLLVMCreateFile(g->dbuilder, buf_ptr(source_path),
4650 ZigLLVMDIFile *compile_unit_file = ZigLLVMCreateFile(g->dbuilder, buf_ptr(g->root_out_name),
46514651 buf_ptr(&g->root_package->root_src_dir));
46524652 g->compile_unit = ZigLLVMCreateCompileUnit(g->dbuilder, ZigLLVMLang_DW_LANG_C99(),
46534653 compile_unit_file, buf_ptr(producer), is_optimized, flags, runtime_version,
src/main.cpp+1-1
......@@ -475,7 +475,7 @@ int main(int argc, char **argv) {
475475 }
476476 }
477477
478 bool need_name = (cmd == CmdBuild || cmd == CmdAsm || cmd == CmdLink);
478 bool need_name = (cmd == CmdBuild || cmd == CmdAsm || cmd == CmdLink || cmd == CmdParseH);
479479
480480 Buf in_file_buf = BUF_INIT;
481481
std/debug.zig+453-58
......@@ -29,17 +29,27 @@ pub coldcc fn panic(comptime format: []const u8, args: ...) -> noreturn {
2929 }
3030
3131 %%io.stderr.printf(format ++ "\n", args);
32 %%printStackTrace();
32 %%writeStackTrace(&io.stderr, &global_allocator, io.stderr.isTty(), 1);
33 %%io.stderr.flush();
3334
3435 os.abort();
3536}
3637
3738pub fn printStackTrace() -> %void {
38 %return writeStackTrace(&io.stderr);
39 %return writeStackTrace(&io.stderr, &global_allocator, io.stderr.isTty(), 1);
3940 %return io.stderr.flush();
4041}
4142
42pub fn writeStackTrace(out_stream: &io.OutStream) -> %void {
43const GREEN = "\x1b[32;1m";
44const WHITE = "\x1b[37;1m";
45const DIM = "\x1b[2m";
46const RESET = "\x1b[0m";
47
48pub var user_main_fn: ?fn() -> %void = null;
49
50pub fn writeStackTrace(out_stream: &io.OutStream, allocator: &mem.Allocator, tty_color: bool,
51 ignore_frame_count: usize) -> %void
52{
4353 switch (@compileVar("object_format")) {
4454 ObjectFormat.elf => {
4555 var stack_trace = ElfStackTrace {
......@@ -48,33 +58,67 @@ pub fn writeStackTrace(out_stream: &io.OutStream) -> %void {
4858 .debug_info = undefined,
4959 .debug_abbrev = undefined,
5060 .debug_str = undefined,
51 .abbrev_table_list = List(AbbrevTableHeader).init(&global_allocator),
52 .compile_unit_list = List(CompileUnit).init(&global_allocator),
61 .debug_line = undefined,
62 .abbrev_table_list = List(AbbrevTableHeader).init(allocator),
63 .compile_unit_list = List(CompileUnit).init(allocator),
5364 };
5465 const st = &stack_trace;
5566 st.self_exe_stream = %return io.openSelfExe();
5667 defer st.self_exe_stream.close();
5768
58 %return st.elf.openStream(&global_allocator, &st.self_exe_stream);
69 %return st.elf.openStream(allocator, &st.self_exe_stream);
5970 defer st.elf.close();
6071
6172 st.debug_info = (%return st.elf.findSection(".debug_info")) ?? return error.MissingDebugInfo;
6273 st.debug_abbrev = (%return st.elf.findSection(".debug_abbrev")) ?? return error.MissingDebugInfo;
6374 st.debug_str = (%return st.elf.findSection(".debug_str")) ?? return error.MissingDebugInfo;
75 st.debug_line = (%return st.elf.findSection(".debug_line")) ?? return error.MissingDebugInfo;
6476 %return scanAllCompileUnits(st);
6577
66 %return out_stream.printf("(...work-in-progress stack unwinding code follows...)\n");
78 var ignored_count: usize = 0;
6779
68 var maybe_fp: ?&const u8 = @frameAddress();
69 while (true) {
70 const fp = maybe_fp ?? break;
71 const return_address = *@intToPtr(&const usize, usize(fp) + @sizeOf(usize));
80 var fp = usize(@frameAddress());
81 while (fp != 0; fp = *@intToPtr(&const usize, fp)) {
82 if (ignored_count < ignore_frame_count) {
83 ignored_count += 1;
84 continue;
85 }
7286
73 const compile_unit = findCompileUnit(st, return_address) ?? return error.MissingDebugInfo;
74 const name = %return compile_unit.die.getAttrString(st, DW.AT_name);
87 const return_address = *@intToPtr(&const usize, fp + @sizeOf(usize));
7588
76 %return out_stream.printf("{} -> {}\n", return_address, name);
77 maybe_fp = *@ptrCast(&const ?&const u8, fp);
89 // TODO we really should be able to convert @sizeOf(usize) * 2 to a string literal
90 // at compile time. I'll call it issue #313
91 const ptr_hex = if (@sizeOf(usize) == 4) "0x{x8}" else "0x{x16}";
92
93 const compile_unit = findCompileUnit(st, return_address) ?? return error.MissingDebugInfo;
94 const compile_unit_name = %return compile_unit.die.getAttrString(st, DW.AT_name);
95 try (getLineNumberInfo(st, compile_unit, usize(return_address) - 1)) |line_info| {
96 defer line_info.deinit();
97 %return out_stream.print(WHITE ++ "{}:{}:{}" ++ RESET ++ ": " ++
98 DIM ++ ptr_hex ++ " in ??? ({})" ++ RESET ++ "\n",
99 line_info.file_name, line_info.line, line_info.column,
100 return_address, compile_unit_name);
101 try (printLineFromFile(st.allocator(), out_stream, line_info)) {
102 if (line_info.column == 0) {
103 %return out_stream.write("\n");
104 } else {
105 {var col_i: usize = 1; while (col_i < line_info.column; col_i += 1) {
106 %return out_stream.writeByte(' ');
107 }}
108 %return out_stream.write(GREEN ++ "^" ++ RESET ++ "\n");
109 }
110 } else |err| switch (err) {
111 error.EndOfFile, error.PathNotFound => {},
112 else => return err,
113 }
114 } else |err| switch (err) {
115 error.MissingDebugInfo, error.InvalidDebugInfo => {
116 %return out_stream.print(ptr_hex ++ " in ??? ({})\n",
117 return_address, compile_unit_name);
118 },
119 else => return err,
120 };
121 %return out_stream.flush();
78122 }
79123 },
80124 ObjectFormat.coff => {
......@@ -89,14 +133,56 @@ pub fn writeStackTrace(out_stream: &io.OutStream) -> %void {
89133 }
90134}
91135
136fn printLineFromFile(allocator: &mem.Allocator, out_stream: &io.OutStream, line_info: &const LineInfo) -> %void {
137 var f = %return io.InStream.open(line_info.file_name, allocator);
138 defer f.close();
139 // TODO fstat and make sure that the file has the correct size
140
141 var buf: [os.page_size]u8 = undefined;
142 var line: usize = 1;
143 var column: usize = 1;
144 var abs_index: usize = 0;
145 while (true) {
146 const amt_read = %return f.read(buf[0...]);
147 const slice = buf[0...amt_read];
148
149 for (slice) |byte| {
150 if (line == line_info.line) {
151 %return out_stream.writeByte(byte);
152 if (byte == '\n') {
153 return;
154 }
155 }
156 if (byte == '\n') {
157 line += 1;
158 column = 1;
159 } else {
160 column += 1;
161 }
162 }
163
164 if (amt_read < buf.len)
165 return error.EndOfFile;
166 }
167}
168
92169const ElfStackTrace = struct {
93170 self_exe_stream: io.InStream,
94171 elf: elf.Elf,
95172 debug_info: &elf.SectionHeader,
96173 debug_abbrev: &elf.SectionHeader,
97174 debug_str: &elf.SectionHeader,
175 debug_line: &elf.SectionHeader,
98176 abbrev_table_list: List(AbbrevTableHeader),
99177 compile_unit_list: List(CompileUnit),
178
179 pub fn allocator(self: &const ElfStackTrace) -> &mem.Allocator {
180 return self.abbrev_table_list.allocator;
181 }
182
183 pub fn readString(self: &ElfStackTrace) -> %[]u8 {
184 return readStringRaw(self.allocator(), &self.self_exe_stream);
185 }
100186};
101187
102188const CompileUnit = struct {
......@@ -104,6 +190,7 @@ const CompileUnit = struct {
104190 die: &Die,
105191 pc_start: u64,
106192 pc_end: u64,
193 index: usize,
107194};
108195
109196const AbbrevTable = List(AbbrevTableEntry);
......@@ -197,44 +284,142 @@ const Die = struct {
197284 }
198285};
199286
200fn readString(in_stream: &io.InStream) -> %[]u8 {
201 var buf = List(u8).init(&global_allocator);
287const FileEntry = struct {
288 file_name: []const u8,
289 dir_index: usize,
290 mtime: usize,
291 len_bytes: usize,
292};
293
294const LineInfo = struct {
295 line: usize,
296 column: usize,
297 file_name: []u8,
298 allocator: &mem.Allocator,
299
300 fn deinit(self: &const LineInfo) {
301 self.allocator.free(self.file_name);
302 }
303};
304
305const LineNumberProgram = struct {
306 address: usize,
307 file: usize,
308 line: isize,
309 column: usize,
310 is_stmt: bool,
311 basic_block: bool,
312 end_sequence: bool,
313
314 target_address: usize,
315 include_dirs: []const []const u8,
316 file_entries: &List(FileEntry),
317
318 prev_address: usize,
319 prev_file: usize,
320 prev_line: isize,
321 prev_column: usize,
322 prev_is_stmt: bool,
323 prev_basic_block: bool,
324 prev_end_sequence: bool,
325
326 pub fn init(is_stmt: bool, include_dirs: []const []const u8,
327 file_entries: &List(FileEntry), target_address: usize) -> LineNumberProgram
328 {
329 LineNumberProgram {
330 .address = 0,
331 .file = 1,
332 .line = 1,
333 .column = 0,
334 .is_stmt = is_stmt,
335 .basic_block = false,
336 .end_sequence = false,
337 .include_dirs = include_dirs,
338 .file_entries = file_entries,
339 .target_address = target_address,
340 .prev_address = 0,
341 .prev_file = undefined,
342 .prev_line = undefined,
343 .prev_column = undefined,
344 .prev_is_stmt = undefined,
345 .prev_basic_block = undefined,
346 .prev_end_sequence = undefined,
347 }
348 }
349
350 pub fn checkLineMatch(self: &LineNumberProgram) -> %?LineInfo {
351 if (self.target_address >= self.prev_address and self.target_address < self.address) {
352 const file_entry = if (self.prev_file == 0) {
353 return error.MissingDebugInfo;
354 } else if (self.prev_file - 1 >= self.file_entries.len) {
355 return error.InvalidDebugInfo;
356 } else {
357 &self.file_entries.items[self.prev_file - 1]
358 };
359 const dir_name = if (file_entry.dir_index >= self.include_dirs.len) {
360 return error.InvalidDebugInfo;
361 } else {
362 self.include_dirs[file_entry.dir_index]
363 };
364 const file_name = %return os.path.join(self.file_entries.allocator, dir_name, file_entry.file_name);
365 %defer self.file_entries.allocator.free(file_name);
366 return LineInfo {
367 .line = if (self.prev_line >= 0) usize(self.prev_line) else 0,
368 .column = self.prev_column,
369 .file_name = file_name,
370 .allocator = self.file_entries.allocator,
371 };
372 }
373
374 self.prev_address = self.address;
375 self.prev_file = self.file;
376 self.prev_line = self.line;
377 self.prev_column = self.column;
378 self.prev_is_stmt = self.is_stmt;
379 self.prev_basic_block = self.basic_block;
380 self.prev_end_sequence = self.end_sequence;
381 return null;
382 }
383};
384
385fn readStringRaw(allocator: &mem.Allocator, in_stream: &io.InStream) -> %[]u8 {
386 var buf = List(u8).init(allocator);
202387 while (true) {
203388 const byte = %return in_stream.readByte();
204389 if (byte == 0)
205390 break;
206391 %return buf.append(byte);
207392 }
208 return buf.items;
393 return buf.toSlice();
209394}
210395
211396fn getString(st: &ElfStackTrace, offset: u64) -> %[]u8 {
212397 const pos = st.debug_str.offset + offset;
213398 %return st.self_exe_stream.seekTo(pos);
214 return readString(&st.self_exe_stream);
399 return st.readString();
215400}
216401
217fn readAllocBytes(in_stream: &io.InStream, size: usize) -> %[]u8 {
402fn readAllocBytes(allocator: &mem.Allocator, in_stream: &io.InStream, size: usize) -> %[]u8 {
218403 const buf = %return global_allocator.alloc(u8, size);
219404 %defer global_allocator.free(buf);
220 if ((%return in_stream.read(buf)) < size) return error.Eof;
405 if ((%return in_stream.read(buf)) < size) return error.EndOfFile;
221406 return buf;
222407}
223408
224fn parseFormValueBlockLen(in_stream: &io.InStream, size: usize) -> %FormValue {
225 const buf = %return readAllocBytes(in_stream, size);
409fn parseFormValueBlockLen(allocator: &mem.Allocator, in_stream: &io.InStream, size: usize) -> %FormValue {
410 const buf = %return readAllocBytes(allocator, in_stream, size);
226411 return FormValue.Block { buf };
227412}
228413
229fn parseFormValueBlock(in_stream: &io.InStream, size: usize) -> %FormValue {
414fn parseFormValueBlock(allocator: &mem.Allocator, in_stream: &io.InStream, size: usize) -> %FormValue {
230415 const block_len = %return in_stream.readVarInt(false, usize, size);
231 return parseFormValueBlockLen(in_stream, block_len);
416 return parseFormValueBlockLen(allocator, in_stream, block_len);
232417}
233418
234fn parseFormValueConstant(in_stream: &io.InStream, signed: bool, size: usize) -> %FormValue {
419fn parseFormValueConstant(allocator: &mem.Allocator, in_stream: &io.InStream, signed: bool, size: usize) -> %FormValue {
235420 FormValue.Const { Constant {
236421 .signed = signed,
237 .payload = %return readAllocBytes(in_stream, size),
422 .payload = %return readAllocBytes(allocator, in_stream, size),
238423 }}
239424}
240425
......@@ -256,38 +441,38 @@ fn parseFormValueTargetAddrSize(in_stream: &io.InStream) -> %u64 {
256441 };
257442}
258443
259fn parseFormValueRefLen(in_stream: &io.InStream, size: usize) -> %FormValue {
260 const buf = %return readAllocBytes(in_stream, size);
444fn parseFormValueRefLen(allocator: &mem.Allocator, in_stream: &io.InStream, size: usize) -> %FormValue {
445 const buf = %return readAllocBytes(allocator, in_stream, size);
261446 return FormValue.Ref { buf };
262447}
263448
264fn parseFormValueRef(in_stream: &io.InStream, comptime T: type) -> %FormValue {
449fn parseFormValueRef(allocator: &mem.Allocator, in_stream: &io.InStream, comptime T: type) -> %FormValue {
265450 const block_len = %return in_stream.readIntLe(T);
266 return parseFormValueRefLen(in_stream, block_len);
451 return parseFormValueRefLen(allocator, in_stream, block_len);
267452}
268453
269fn parseFormValue(in_stream: &io.InStream, form_id: u64, is_64: bool) -> %FormValue {
454fn parseFormValue(allocator: &mem.Allocator, in_stream: &io.InStream, form_id: u64, is_64: bool) -> %FormValue {
270455 return switch (form_id) {
271456 DW.FORM_addr => FormValue.Address { %return parseFormValueTargetAddrSize(in_stream) },
272 DW.FORM_block1 => parseFormValueBlock(in_stream, 1),
273 DW.FORM_block2 => parseFormValueBlock(in_stream, 2),
274 DW.FORM_block4 => parseFormValueBlock(in_stream, 4),
457 DW.FORM_block1 => parseFormValueBlock(allocator, in_stream, 1),
458 DW.FORM_block2 => parseFormValueBlock(allocator, in_stream, 2),
459 DW.FORM_block4 => parseFormValueBlock(allocator, in_stream, 4),
275460 DW.FORM_block => {
276461 const block_len = %return readULeb128(in_stream);
277 parseFormValueBlockLen(in_stream, block_len)
462 parseFormValueBlockLen(allocator, in_stream, block_len)
278463 },
279 DW.FORM_data1 => parseFormValueConstant(in_stream, false, 1),
280 DW.FORM_data2 => parseFormValueConstant(in_stream, false, 2),
281 DW.FORM_data4 => parseFormValueConstant(in_stream, false, 4),
282 DW.FORM_data8 => parseFormValueConstant(in_stream, false, 8),
464 DW.FORM_data1 => parseFormValueConstant(allocator, in_stream, false, 1),
465 DW.FORM_data2 => parseFormValueConstant(allocator, in_stream, false, 2),
466 DW.FORM_data4 => parseFormValueConstant(allocator, in_stream, false, 4),
467 DW.FORM_data8 => parseFormValueConstant(allocator, in_stream, false, 8),
283468 DW.FORM_udata, DW.FORM_sdata => {
284469 const block_len = %return readULeb128(in_stream);
285470 const signed = form_id == DW.FORM_sdata;
286 parseFormValueConstant(in_stream, signed, block_len)
471 parseFormValueConstant(allocator, in_stream, signed, block_len)
287472 },
288473 DW.FORM_exprloc => {
289474 const size = %return readULeb128(in_stream);
290 const buf = %return readAllocBytes(in_stream, size);
475 const buf = %return readAllocBytes(allocator, in_stream, size);
291476 return FormValue.ExprLoc { buf };
292477 },
293478 DW.FORM_flag => FormValue.Flag { (%return in_stream.readByte()) != 0 },
......@@ -296,30 +481,31 @@ fn parseFormValue(in_stream: &io.InStream, form_id: u64, is_64: bool) -> %FormVa
296481 %return parseFormValueDwarfOffsetSize(in_stream, is_64)
297482 },
298483
299 DW.FORM_ref1 => parseFormValueRef(in_stream, u8),
300 DW.FORM_ref2 => parseFormValueRef(in_stream, u16),
301 DW.FORM_ref4 => parseFormValueRef(in_stream, u32),
302 DW.FORM_ref8 => parseFormValueRef(in_stream, u64),
484 DW.FORM_ref1 => parseFormValueRef(allocator, in_stream, u8),
485 DW.FORM_ref2 => parseFormValueRef(allocator, in_stream, u16),
486 DW.FORM_ref4 => parseFormValueRef(allocator, in_stream, u32),
487 DW.FORM_ref8 => parseFormValueRef(allocator, in_stream, u64),
303488 DW.FORM_ref_udata => {
304489 const ref_len = %return readULeb128(in_stream);
305 parseFormValueRefLen(in_stream, ref_len)
490 parseFormValueRefLen(allocator, in_stream, ref_len)
306491 },
307492
308493 DW.FORM_ref_addr => FormValue.RefAddr { %return parseFormValueDwarfOffsetSize(in_stream, is_64) },
309494 DW.FORM_ref_sig8 => FormValue.RefSig8 { %return in_stream.readIntLe(u64) },
310495
311 DW.FORM_string => FormValue.String { %return readString(in_stream) },
496 DW.FORM_string => FormValue.String { %return readStringRaw(allocator, in_stream) },
312497 DW.FORM_strp => FormValue.StrPtr { %return parseFormValueDwarfOffsetSize(in_stream, is_64) },
313498 DW.FORM_indirect => {
314499 const child_form_id = %return readULeb128(in_stream);
315 parseFormValue(in_stream, child_form_id, is_64)
500 parseFormValue(allocator, in_stream, child_form_id, is_64)
316501 },
317502 else => error.InvalidDebugInfo,
318503 }
319504}
320505
321fn parseAbbrevTable(in_stream: &io.InStream) -> %AbbrevTable {
322 var result = AbbrevTable.init(&global_allocator);
506fn parseAbbrevTable(st: &ElfStackTrace) -> %AbbrevTable {
507 const in_stream = &st.self_exe_stream;
508 var result = AbbrevTable.init(st.allocator());
323509 while (true) {
324510 const abbrev_code = %return readULeb128(in_stream);
325511 if (abbrev_code == 0)
......@@ -328,7 +514,7 @@ fn parseAbbrevTable(in_stream: &io.InStream) -> %AbbrevTable {
328514 .abbrev_code = abbrev_code,
329515 .tag_id = %return readULeb128(in_stream),
330516 .has_children = (%return in_stream.readByte()) == DW.CHILDREN_yes,
331 .attrs = List(AbbrevAttr).init(&global_allocator),
517 .attrs = List(AbbrevAttr).init(st.allocator()),
332518 });
333519 const attrs = &result.items[result.len - 1].attrs;
334520
......@@ -356,7 +542,7 @@ fn getAbbrevTable(st: &ElfStackTrace, abbrev_offset: u64) -> %&const AbbrevTable
356542 %return st.self_exe_stream.seekTo(st.debug_abbrev.offset + abbrev_offset);
357543 %return st.abbrev_table_list.append(AbbrevTableHeader {
358544 .offset = abbrev_offset,
359 .table = %return parseAbbrevTable(&st.self_exe_stream),
545 .table = %return parseAbbrevTable(st),
360546 });
361547 return &st.abbrev_table_list.items[st.abbrev_table_list.len - 1].table;
362548}
......@@ -369,28 +555,235 @@ fn getAbbrevTableEntry(abbrev_table: &const AbbrevTable, abbrev_code: u64) -> ?&
369555 return null;
370556}
371557
372fn parseDie(in_stream: &io.InStream, abbrev_table: &const AbbrevTable, is_64: bool) -> %Die {
558fn parseDie(st: &ElfStackTrace, abbrev_table: &const AbbrevTable, is_64: bool) -> %Die {
559 const in_stream = &st.self_exe_stream;
373560 const abbrev_code = %return readULeb128(in_stream);
374561 const table_entry = getAbbrevTableEntry(abbrev_table, abbrev_code) ?? return error.InvalidDebugInfo;
375562
376563 var result = Die {
377564 .tag_id = table_entry.tag_id,
378565 .has_children = table_entry.has_children,
379 .attrs = List(Die.Attr).init(&global_allocator),
566 .attrs = List(Die.Attr).init(st.allocator()),
380567 };
381568 %return result.attrs.resize(table_entry.attrs.len);
382569 for (table_entry.attrs.toSliceConst()) |attr, i| {
383570 result.attrs.items[i] = Die.Attr {
384571 .id = attr.attr_id,
385 .value = %return parseFormValue(in_stream, attr.form_id, is_64),
572 .value = %return parseFormValue(st.allocator(), &st.self_exe_stream, attr.form_id, is_64),
386573 };
387574 }
388575 return result;
389576}
390577
578fn getLineNumberInfo(st: &ElfStackTrace, compile_unit: &const CompileUnit, target_address: usize) -> %LineInfo {
579 const compile_unit_cwd = %return compile_unit.die.getAttrString(st, DW.AT_comp_dir);
580
581 const in_stream = &st.self_exe_stream;
582 const debug_line_end = st.debug_line.offset + st.debug_line.size;
583 var this_offset = st.debug_line.offset;
584 var this_index: usize = 0;
585
586 while (this_offset < debug_line_end; this_index += 1) {
587 %return in_stream.seekTo(this_offset);
588
589 var is_64: bool = undefined;
590 const unit_length = %return readInitialLength(in_stream, &is_64);
591 if (unit_length == 0)
592 return error.MissingDebugInfo;
593 const next_offset = unit_length + (if (is_64) usize(12) else usize(4));
594
595 if (compile_unit.index != this_index) {
596 this_offset += next_offset;
597 continue;
598 }
599
600 const version = %return in_stream.readInt(st.elf.is_big_endian, u16);
601 if (version != 2) return error.InvalidDebugInfo;
602
603 const prologue_length = %return in_stream.readInt(st.elf.is_big_endian, u32);
604 const prog_start_offset = (%return in_stream.getPos()) + prologue_length;
605
606 const minimum_instruction_length = %return in_stream.readByte();
607 if (minimum_instruction_length == 0) return error.InvalidDebugInfo;
608
609 const default_is_stmt = (%return in_stream.readByte()) != 0;
610 const line_base = %return in_stream.readByteSigned();
611
612 const line_range = %return in_stream.readByte();
613 if (line_range == 0)
614 return error.InvalidDebugInfo;
615
616 const opcode_base = %return in_stream.readByte();
617
618 const standard_opcode_lengths = %return st.allocator().alloc(u8, opcode_base - 1);
619
620 {var i: usize = 0; while (i < opcode_base - 1; i += 1) {
621 standard_opcode_lengths[i] = %return in_stream.readByte();
622 }}
623
624 var include_directories = List([]u8).init(st.allocator());
625 %return include_directories.append(compile_unit_cwd);
626 while (true) {
627 const dir = %return st.readString();
628 if (dir.len == 0)
629 break;
630 %return include_directories.append(dir);
631 }
632
633 var file_entries = List(FileEntry).init(st.allocator());
634 var prog = LineNumberProgram.init(default_is_stmt, include_directories.toSliceConst(),
635 &file_entries, target_address);
636
637 while (true) {
638 const file_name = %return st.readString();
639 if (file_name.len == 0)
640 break;
641 const dir_index = %return readULeb128(in_stream);
642 const mtime = %return readULeb128(in_stream);
643 const len_bytes = %return readULeb128(in_stream);
644 %return file_entries.append(FileEntry {
645 .file_name = file_name,
646 .dir_index = dir_index,
647 .mtime = mtime,
648 .len_bytes = len_bytes,
649 });
650 }
651
652 %return in_stream.seekTo(prog_start_offset);
653
654 while (true) {
655 //const pos = (%return in_stream.getPos()) - this_offset;
656 //if (pos == 0x1a3) @breakpoint();
657 //%%io.stderr.printf("\n{x8}\n", pos);
658
659 const opcode = %return in_stream.readByte();
660
661 var sub_op: u8 = undefined; // TODO move this to the correct scope and fix the compiler crash
662 if (opcode == DW.LNS_extended_op) {
663 const op_size = %return readULeb128(in_stream);
664 if (op_size < 1)
665 return error.InvalidDebugInfo;
666 sub_op = %return in_stream.readByte();
667 switch (sub_op) {
668 DW.LNE_end_sequence => {
669 //%%io.stdout.printf(" [0x{x8}] End Sequence\n", pos);
670 prog.end_sequence = true;
671 test (%return prog.checkLineMatch()) |info| return info;
672 return error.MissingDebugInfo;
673 },
674 DW.LNE_set_address => {
675 const addr = %return in_stream.readInt(st.elf.is_big_endian, usize);
676 prog.address = addr;
677
678 //%%io.stdout.printf(" [0x{x8}] Extended opcode {}: set Address to 0x{x}\n",
679 // pos, sub_op, addr);
680 },
681 DW.LNE_define_file => {
682 //%%io.stdout.printf(" [0x{x8}] Define File\n", pos);
683
684 const file_name = %return st.readString();
685 const dir_index = %return readULeb128(in_stream);
686 const mtime = %return readULeb128(in_stream);
687 const len_bytes = %return readULeb128(in_stream);
688 %return file_entries.append(FileEntry {
689 .file_name = file_name,
690 .dir_index = dir_index,
691 .mtime = mtime,
692 .len_bytes = len_bytes,
693 });
694 },
695 else => {
696 %return in_stream.seekForward(op_size - 1);
697 },
698 }
699 } else if (opcode >= opcode_base) {
700 // special opcodes
701 const adjusted_opcode = opcode - opcode_base;
702 const inc_addr = minimum_instruction_length * (adjusted_opcode / line_range);
703 const inc_line = i32(line_base) + i32(adjusted_opcode % line_range);
704 prog.line += inc_line;
705 prog.address += inc_addr;
706 //%%io.stdout.printf(
707 // " [0x{x8}] Special opcode {}: advance Address by {} to 0x{x} and Line by {} to {}\n",
708 // pos, adjusted_opcode, inc_addr, prog.address, inc_line, prog.line);
709 test (%return prog.checkLineMatch()) |info| return info;
710 prog.basic_block = false;
711 } else {
712 switch (opcode) {
713 DW.LNS_copy => {
714 //%%io.stdout.printf(" [0x{x8}] Copy\n", pos);
715
716 test (%return prog.checkLineMatch()) |info| return info;
717 prog.basic_block = false;
718 },
719 DW.LNS_advance_pc => {
720 const arg = %return readULeb128(in_stream);
721 prog.address += arg * minimum_instruction_length;
722
723 //%%io.stdout.printf(" [0x{x8}] Advance PC by {} to 0x{x}\n", pos, arg, prog.address);
724 },
725 DW.LNS_advance_line => {
726 const arg = %return readILeb128(in_stream);
727 prog.line += arg;
728
729 //%%io.stdout.printf(" [0x{x8}] Advance Line by {} to {}\n", pos, arg, prog.line);
730 },
731 DW.LNS_set_file => {
732 const arg = %return readULeb128(in_stream);
733 prog.file = arg;
734
735 //%%io.stdout.printf(" [0x{x8}] Set File Name to entry {} in the File Name Table\n",
736 // pos, arg);
737 },
738 DW.LNS_set_column => {
739 const arg = %return readULeb128(in_stream);
740 prog.column = arg;
741
742 //%%io.stdout.printf(" [0x{x8}] Set column to {}\n", pos, arg);
743 },
744 DW.LNS_negate_stmt => {
745 prog.is_stmt = !prog.is_stmt;
746
747 //%%io.stdout.printf(" [0x{x8}] Set is_stmt to {}\n", pos, if (prog.is_stmt) u8(1) else u8(0));
748 },
749 DW.LNS_set_basic_block => {
750 prog.basic_block = true;
751 },
752 DW.LNS_const_add_pc => {
753 const inc_addr = minimum_instruction_length * ((255 - opcode_base) / line_range);
754 prog.address += inc_addr;
755
756 //%%io.stdout.printf(" [0x{x8}] Advance PC by constant {} to 0x{x}\n",
757 // pos, inc_addr, prog.address);
758 },
759 DW.LNS_fixed_advance_pc => {
760 const arg = %return in_stream.readInt(st.elf.is_big_endian, u16);
761 prog.address += arg;
762 },
763 DW.LNS_set_prologue_end => {
764 //%%io.stdout.printf(" [0x{x8}] Set prologue_end to true\n", pos);
765 },
766 else => {
767 if (opcode - 1 >= standard_opcode_lengths.len)
768 return error.InvalidDebugInfo;
769 //%%io.stdout.printf(" [0x{x8}] unknown op code {}\n", pos, opcode);
770 const len_bytes = standard_opcode_lengths[opcode - 1];
771 %return in_stream.seekForward(len_bytes);
772 },
773 }
774 }
775 }
776
777 this_offset += next_offset;
778 }
779
780 return error.MissingDebugInfo;
781}
782
391783fn scanAllCompileUnits(st: &ElfStackTrace) -> %void {
392784 const debug_info_end = st.debug_info.offset + st.debug_info.size;
393785 var this_unit_offset = st.debug_info.offset;
786 var cu_index: usize = 0;
394787 while (this_unit_offset < debug_info_end) {
395788 %return st.self_exe_stream.seekTo(this_unit_offset);
396789
......@@ -417,8 +810,8 @@ fn scanAllCompileUnits(st: &ElfStackTrace) -> %void {
417810
418811 %return st.self_exe_stream.seekTo(compile_unit_pos);
419812
420 const compile_unit_die = (%return global_allocator.alloc(Die, 1)).ptr;
421 *compile_unit_die = %return parseDie(&st.self_exe_stream, abbrev_table, is_64);
813 const compile_unit_die = %return st.allocator().create(Die);
814 *compile_unit_die = %return parseDie(st, abbrev_table, is_64);
422815
423816 if (compile_unit_die.tag_id != DW.TAG_compile_unit)
424817 return error.InvalidDebugInfo;
......@@ -439,9 +832,11 @@ fn scanAllCompileUnits(st: &ElfStackTrace) -> %void {
439832 .pc_start = low_pc,
440833 .pc_end = pc_end,
441834 .die = compile_unit_die,
835 .index = cu_index,
442836 });
443837
444838 this_unit_offset += next_offset;
839 cu_index += 1;
445840 }
446841}
447842
std/dwarf.zig+21
......@@ -620,3 +620,24 @@ pub const CFA_GNU_negative_offset_extended = 0x2f;
620620
621621pub const CHILDREN_no = 0x00;
622622pub const CHILDREN_yes = 0x01;
623
624pub const LNS_extended_op = 0x00;
625pub const LNS_copy = 0x01;
626pub const LNS_advance_pc = 0x02;
627pub const LNS_advance_line = 0x03;
628pub const LNS_set_file = 0x04;
629pub const LNS_set_column = 0x05;
630pub const LNS_negate_stmt = 0x06;
631pub const LNS_set_basic_block = 0x07;
632pub const LNS_const_add_pc = 0x08;
633pub const LNS_fixed_advance_pc = 0x09;
634pub const LNS_set_prologue_end = 0x0a;
635pub const LNS_set_epilogue_begin = 0x0b;
636pub const LNS_set_isa = 0x0c;
637
638pub const LNE_end_sequence = 0x01;
639pub const LNE_set_address = 0x02;
640pub const LNE_define_file = 0x03;
641pub const LNE_set_discriminator = 0x04;
642pub const LNE_lo_user = 0x80;
643pub const LNE_hi_user = 0xff;
std/elf.zig+2-3
......@@ -250,14 +250,13 @@ pub const Elf = struct {
250250
251251 {
252252 const null_byte = %return elf.in_stream.readByte();
253 if (null_byte == 0) return (?&SectionHeader)(section);
253 if (null_byte == 0) return section;
254254 }
255255
256256 next_section:
257257 }
258258
259 const null_sh: ?&SectionHeader = null;
260 return null_sh;
259 return null;
261260 }
262261
263262 pub fn seekToSection(elf: &Elf, section: &SectionHeader) -> %void {
std/io.zig+16-2
......@@ -55,7 +55,7 @@ error NoDevice;
5555error PathNotFound;
5656error NoMem;
5757error Unseekable;
58error Eof;
58error EndOfFile;
5959
6060pub const OpenRead = 0b0001;
6161pub const OpenWrite = 0b0010;
......@@ -153,6 +153,10 @@ pub const OutStream = struct {
153153 assert(self.index == 0);
154154 os.posixClose(self.fd);
155155 }
156
157 pub fn isTty(self: &const OutStream) -> bool {
158 return os.posix.isatty(self.fd);
159 }
156160};
157161
158162// TODO created a BufferedInStream struct and move some of this code there
......@@ -219,7 +223,7 @@ pub const InStream = struct {
219223
220224 pub fn readNoEof(is: &InStream, buf: []u8) -> %void {
221225 const amt_read = %return is.read(buf);
222 if (amt_read < buf.len) return error.Eof;
226 if (amt_read < buf.len) return error.EndOfFile;
223227 }
224228
225229 pub fn readByte(is: &InStream) -> %u8 {
......@@ -228,6 +232,12 @@ pub const InStream = struct {
228232 return result[0];
229233 }
230234
235 pub fn readByteSigned(is: &InStream) -> %i8 {
236 var result: [1]i8 = undefined;
237 %return is.readNoEof(([]u8)(result[0...]));
238 return result[0];
239 }
240
231241 pub fn readIntLe(is: &InStream, comptime T: type) -> %T {
232242 is.readInt(false, T)
233243 }
......@@ -342,6 +352,10 @@ pub const InStream = struct {
342352 %return buf.resize(actual_buf_len + os.page_size);
343353 }
344354 }
355
356 pub fn isTty(self: &const InStream) -> bool {
357 return os.posix.isatty(self.fd);
358 }
345359};
346360
347361pub fn openSelfExe() -> %InStream {
std/os/linux.zig+72-2
......@@ -251,6 +251,63 @@ pub const DT_LNK = 10;
251251pub const DT_SOCK = 12;
252252pub const DT_WHT = 14;
253253
254
255pub const TCGETS = 0x5401;
256pub const TCSETS = 0x5402;
257pub const TCSETSW = 0x5403;
258pub const TCSETSF = 0x5404;
259pub const TCGETA = 0x5405;
260pub const TCSETA = 0x5406;
261pub const TCSETAW = 0x5407;
262pub const TCSETAF = 0x5408;
263pub const TCSBRK = 0x5409;
264pub const TCXONC = 0x540A;
265pub const TCFLSH = 0x540B;
266pub const TIOCEXCL = 0x540C;
267pub const TIOCNXCL = 0x540D;
268pub const TIOCSCTTY = 0x540E;
269pub const TIOCGPGRP = 0x540F;
270pub const TIOCSPGRP = 0x5410;
271pub const TIOCOUTQ = 0x5411;
272pub const TIOCSTI = 0x5412;
273pub const TIOCGWINSZ = 0x5413;
274pub const TIOCSWINSZ = 0x5414;
275pub const TIOCMGET = 0x5415;
276pub const TIOCMBIS = 0x5416;
277pub const TIOCMBIC = 0x5417;
278pub const TIOCMSET = 0x5418;
279pub const TIOCGSOFTCAR = 0x5419;
280pub const TIOCSSOFTCAR = 0x541A;
281pub const FIONREAD = 0x541B;
282pub const TIOCINQ = FIONREAD;
283pub const TIOCLINUX = 0x541C;
284pub const TIOCCONS = 0x541D;
285pub const TIOCGSERIAL = 0x541E;
286pub const TIOCSSERIAL = 0x541F;
287pub const TIOCPKT = 0x5420;
288pub const FIONBIO = 0x5421;
289pub const TIOCNOTTY = 0x5422;
290pub const TIOCSETD = 0x5423;
291pub const TIOCGETD = 0x5424;
292pub const TCSBRKP = 0x5425;
293pub const TIOCSBRK = 0x5427;
294pub const TIOCCBRK = 0x5428;
295pub const TIOCGSID = 0x5429;
296pub const TIOCGRS485 = 0x542E;
297pub const TIOCSRS485 = 0x542F;
298pub const TIOCGPTN = 0x80045430;
299pub const TIOCSPTLCK = 0x40045431;
300pub const TIOCGDEV = 0x80045432;
301pub const TCGETX = 0x5432;
302pub const TCSETX = 0x5433;
303pub const TCSETXF = 0x5434;
304pub const TCSETXW = 0x5435;
305pub const TIOCSIG = 0x40045436;
306pub const TIOCVHANGUP = 0x5437;
307pub const TIOCGPKT = 0x80045438;
308pub const TIOCGPTLCK = 0x80045439;
309pub const TIOCGEXCL = 0x80045440;
310
254311fn unsigned(s: i32) -> u32 { *@ptrCast(&u32, &s) }
255312fn signed(s: u32) -> i32 { *@ptrCast(&i32, &s) }
256313pub fn WEXITSTATUS(s: i32) -> i32 { signed((unsigned(s) & 0xff00) >> 8) }
......@@ -260,6 +317,14 @@ pub fn WIFEXITED(s: i32) -> bool { WTERMSIG(s) == 0 }
260317pub fn WIFSTOPPED(s: i32) -> bool { (u16)(((unsigned(s)&0xffff)*%0x10001)>>8) > 0x7f00 }
261318pub fn WIFSIGNALED(s: i32) -> bool { (unsigned(s)&0xffff)-%1 < 0xff }
262319
320
321pub const winsize = extern struct {
322 ws_row: u16,
323 ws_col: u16,
324 ws_xpixel: u16,
325 ws_ypixel: u16,
326};
327
263328/// Get the errno from a syscall return value, or 0 for no error.
264329pub fn getErrno(r: usize) -> usize {
265330 const signed_r = *@ptrCast(&const isize, &r);
......@@ -286,6 +351,11 @@ pub fn getdents(fd: i32, dirp: &u8, count: usize) -> usize {
286351 arch.syscall3(arch.SYS_getdents, usize(fd), usize(dirp), usize(count))
287352}
288353
354pub fn isatty(fd: i32) -> bool {
355 var wsz: winsize = undefined;
356 return arch.syscall3(arch.SYS_ioctl, usize(fd), TIOCGWINSZ, usize(&wsz)) == 0;
357}
358
289359pub fn mkdir(path: &const u8, mode: usize) -> usize {
290360 arch.syscall2(arch.SYS_mkdir, usize(path), mode)
291361}
......@@ -440,7 +510,7 @@ pub const iovec = extern struct {
440510//
441511//export struct ifreq {
442512// ifrn_name: [IF_NAMESIZE]u8,
443// union {
513// union {
444514// ifru_addr: sockaddr,
445515// ifru_dstaddr: sockaddr,
446516// ifru_broadaddr: sockaddr,
......@@ -453,7 +523,7 @@ pub const iovec = extern struct {
453523// ifru_slave: [IF_NAMESIZE]u8,
454524// ifru_newname: [IF_NAMESIZE]u8,
455525// ifru_data: &u8,
456// } ifr_ifru;
526// } ifr_ifru;
457527//}
458528//
459529
std/os/path.zig+4-1
......@@ -30,7 +30,7 @@ pub fn join(allocator: &Allocator, paths: ...) -> %[]u8 {
3030 mem.copy(u8, buf[buf_index...], arg);
3131 buf_index += arg.len;
3232 if (path_i >= paths.len) break;
33 if (arg[arg.len - 1] != sep) {
33 if (buf[buf_index - 1] != sep) {
3434 buf[buf_index] = sep;
3535 buf_index += 1;
3636 }
......@@ -45,6 +45,9 @@ test "os.path.join" {
4545
4646 assert(mem.eql(u8, %%join(&debug.global_allocator, "/", "a", "b/", "c"), "/a/b/c"));
4747 assert(mem.eql(u8, %%join(&debug.global_allocator, "/a/", "b/", "c"), "/a/b/c"));
48
49 assert(mem.eql(u8, %%join(&debug.global_allocator, "/home/andy/dev/zig/build/lib/zig/std", "io.zig"),
50 "/home/andy/dev/zig/build/lib/zig/std/io.zig"));
4851}
4952
5053pub fn isAbsolute(path: []const u8) -> bool {
std/special/bootstrap.zig+2
......@@ -44,6 +44,8 @@ fn callMain(argc: usize, argv: &&u8, envp: &?&u8) -> %void {
4444 while (envp[env_count] != null; env_count += 1) {}
4545 std.os.environ_raw = @ptrCast(&&u8, envp)[0...env_count];
4646
47 std.debug.user_main_fn = root.main;
48
4749 return root.main();
4850}
4951