authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-08-23 16:11:34-04:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-08-23 16:23:33-04:00
log5c1ec20c9a5c788af9f3402b9a065389eb818e76
treed51908c173a8e6201fca9c0acf88aed5f9b15e7a
parent8f96553be81829f1290213d8657d9bc61394b1f7

MacOS stack traces use the already mmapped executable

...rather than trying to find the executable on the file system. Also use a more robust PIE offset calculation based on the available metadata. And for the last function, use the data that tells the end rather than assuming 4K. Also they print in a consistent way with Linux stack traces.

4 files changed, 605 insertions(+), 284 deletions(-)

CMakeLists.txt-1
......@@ -485,7 +485,6 @@ set(ZIG_STD_FILES
485485 "json.zig"
486486 "lazy_init.zig"
487487 "linked_list.zig"
488 "macho.zig"
489488 "math/acos.zig"
490489 "math/acosh.zig"
491490 "math/asin.zig"
std/c/darwin.zig+354
......@@ -1,5 +1,6 @@
11extern "c" fn __error() *c_int;
22pub extern "c" fn _NSGetExecutablePath(buf: [*]u8, bufsize: *u32) c_int;
3pub extern "c" fn _dyld_get_image_header(image_index: u32) ?*mach_header;
34
45pub extern "c" fn __getdirentries64(fd: c_int, buf_ptr: [*]u8, buf_len: usize, basep: *i64) usize;
56
......@@ -33,6 +34,12 @@ pub extern "c" fn sysctlnametomib(name: [*]const u8, mibp: ?*c_int, sizep: ?*usi
3334pub extern "c" fn bind(socket: c_int, address: ?*const sockaddr, address_len: socklen_t) c_int;
3435pub extern "c" fn socket(domain: c_int, type: c_int, protocol: c_int) c_int;
3536
37/// The value of the link editor defined symbol _MH_EXECUTE_SYM is the address
38/// of the mach header in a Mach-O executable file type. It does not appear in
39/// any file type other than a MH_EXECUTE file type. The type of the symbol is
40/// absolute as the header is not part of any section.
41pub extern "c" var _mh_execute_header: if (@sizeOf(usize) == 8) mach_header_64 else mach_header;
42
3643pub use @import("../os/darwin/errno.zig");
3744
3845pub const _errno = __error;
......@@ -139,6 +146,353 @@ pub const Kevent = extern struct {
139146 udata: usize,
140147};
141148
149pub const mach_header = extern struct {
150 magic: u32,
151 cputype: cpu_type_t,
152 cpusubtype: cpu_subtype_t,
153 filetype: u32,
154 ncmds: u32,
155 sizeofcmds: u32,
156 flags: u32,
157};
158
159pub const mach_header_64 = extern struct {
160 magic: u32,
161 cputype: cpu_type_t,
162 cpusubtype: cpu_subtype_t,
163 filetype: u32,
164 ncmds: u32,
165 sizeofcmds: u32,
166 flags: u32,
167 reserved: u32,
168};
169
170pub const load_command = extern struct {
171 cmd: u32,
172 cmdsize: u32,
173};
174
175
176/// The symtab_command contains the offsets and sizes of the link-edit 4.3BSD
177/// "stab" style symbol table information as described in the header files
178/// <nlist.h> and <stab.h>.
179pub const symtab_command = extern struct {
180 cmd: u32, /// LC_SYMTAB
181 cmdsize: u32, /// sizeof(struct symtab_command)
182 symoff: u32, /// symbol table offset
183 nsyms: u32, /// number of symbol table entries
184 stroff: u32, /// string table offset
185 strsize: u32, /// string table size in bytes
186};
187
188/// The linkedit_data_command contains the offsets and sizes of a blob
189/// of data in the __LINKEDIT segment.
190const linkedit_data_command = extern struct {
191 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.
192 cmdsize: u32, /// sizeof(struct linkedit_data_command)
193 dataoff: u32 , /// file offset of data in __LINKEDIT segment
194 datasize: u32 , /// file size of data in __LINKEDIT segment
195};
196
197/// The segment load command indicates that a part of this file is to be
198/// mapped into the task's address space. The size of this segment in memory,
199/// vmsize, maybe equal to or larger than the amount to map from this file,
200/// filesize. The file is mapped starting at fileoff to the beginning of
201/// the segment in memory, vmaddr. The rest of the memory of the segment,
202/// if any, is allocated zero fill on demand. The segment's maximum virtual
203/// memory protection and initial virtual memory protection are specified
204/// by the maxprot and initprot fields. If the segment has sections then the
205/// section structures directly follow the segment command and their size is
206/// reflected in cmdsize.
207pub const segment_command = extern struct {
208 cmd: u32,/// LC_SEGMENT
209 cmdsize: u32,/// includes sizeof section structs
210 segname: [16]u8,/// segment name
211 vmaddr: u32,/// memory address of this segment
212 vmsize: u32,/// memory size of this segment
213 fileoff: u32,/// file offset of this segment
214 filesize: u32,/// amount to map from the file
215 maxprot: vm_prot_t,/// maximum VM protection
216 initprot: vm_prot_t,/// initial VM protection
217 nsects: u32,/// number of sections in segment
218 flags: u32,
219};
220
221/// The 64-bit segment load command indicates that a part of this file is to be
222/// mapped into a 64-bit task's address space. If the 64-bit segment has
223/// sections then section_64 structures directly follow the 64-bit segment
224/// command and their size is reflected in cmdsize.
225pub const segment_command_64 = extern struct {
226 cmd: u32, /// LC_SEGMENT_64
227 cmdsize: u32, /// includes sizeof section_64 structs
228 segname: [16]u8, /// segment name
229 vmaddr: u64, /// memory address of this segment
230 vmsize: u64, /// memory size of this segment
231 fileoff: u64, /// file offset of this segment
232 filesize: u64, /// amount to map from the file
233 maxprot: vm_prot_t, /// maximum VM protection
234 initprot: vm_prot_t, /// initial VM protection
235 nsects: u32, /// number of sections in segment
236 flags: u32,
237};
238
239/// A segment is made up of zero or more sections. Non-MH_OBJECT files have
240/// all of their segments with the proper sections in each, and padded to the
241/// specified segment alignment when produced by the link editor. The first
242/// segment of a MH_EXECUTE and MH_FVMLIB format file contains the mach_header
243/// and load commands of the object file before its first section. The zero
244/// fill sections are always last in their segment (in all formats). This
245/// allows the zeroed segment padding to be mapped into memory where zero fill
246/// sections might be. The gigabyte zero fill sections, those with the section
247/// type S_GB_ZEROFILL, can only be in a segment with sections of this type.
248/// These segments are then placed after all other segments.
249///
250/// The MH_OBJECT format has all of its sections in one segment for
251/// compactness. There is no padding to a specified segment boundary and the
252/// mach_header and load commands are not part of the segment.
253///
254/// Sections with the same section name, sectname, going into the same segment,
255/// segname, are combined by the link editor. The resulting section is aligned
256/// to the maximum alignment of the combined sections and is the new section's
257/// alignment. The combined sections are aligned to their original alignment in
258/// the combined section. Any padded bytes to get the specified alignment are
259/// zeroed.
260///
261/// The format of the relocation entries referenced by the reloff and nreloc
262/// fields of the section structure for mach object files is described in the
263/// header file <reloc.h>.
264pub const @"section" = extern struct {
265 sectname: [16]u8, /// name of this section
266 segname: [16]u8, /// segment this section goes in
267 addr: u32, /// memory address of this section
268 size: u32, /// size in bytes of this section
269 offset: u32, /// file offset of this section
270 @"align": u32, /// section alignment (power of 2)
271 reloff: u32, /// file offset of relocation entries
272 nreloc: u32, /// number of relocation entries
273 flags: u32, /// flags (section type and attributes
274 reserved1: u32, /// reserved (for offset or index)
275 reserved2: u32, /// reserved (for count or sizeof)
276};
277
278pub const section_64 = extern struct {
279 sectname: [16]u8, /// name of this section
280 segname: [16]u8, /// segment this section goes in
281 addr: u64, /// memory address of this section
282 size: u64, /// size in bytes of this section
283 offset: u32, /// file offset of this section
284 @"align": u32, /// section alignment (power of 2)
285 reloff: u32, /// file offset of relocation entries
286 nreloc: u32, /// number of relocation entries
287 flags: u32, /// flags (section type and attributes
288 reserved1: u32, /// reserved (for offset or index)
289 reserved2: u32, /// reserved (for count or sizeof)
290 reserved3: u32, /// reserved
291};
292
293pub const nlist = extern struct {
294 n_strx: u32,
295 n_type: u8,
296 n_sect: u8,
297 n_desc: i16,
298 n_value: u32,
299};
300
301pub const nlist_64 = extern struct {
302 n_strx: u32,
303 n_type: u8,
304 n_sect: u8,
305 n_desc: u16,
306 n_value: u64,
307};
308
309/// After MacOS X 10.1 when a new load command is added that is required to be
310/// understood by the dynamic linker for the image to execute properly the
311/// LC_REQ_DYLD bit will be or'ed into the load command constant. If the dynamic
312/// linker sees such a load command it it does not understand will issue a
313/// "unknown load command required for execution" error and refuse to use the
314/// image. Other load commands without this bit that are not understood will
315/// simply be ignored.
316pub const LC_REQ_DYLD = 0x80000000;
317
318pub const LC_SEGMENT = 0x1; /// segment of this file to be mapped
319pub const LC_SYMTAB = 0x2; /// link-edit stab symbol table info
320pub const LC_SYMSEG = 0x3; /// link-edit gdb symbol table info (obsolete)
321pub const LC_THREAD = 0x4; /// thread
322pub const LC_UNIXTHREAD = 0x5; /// unix thread (includes a stack)
323pub const LC_LOADFVMLIB = 0x6; /// load a specified fixed VM shared library
324pub const LC_IDFVMLIB = 0x7; /// fixed VM shared library identification
325pub const LC_IDENT = 0x8; /// object identification info (obsolete)
326pub const LC_FVMFILE = 0x9; /// fixed VM file inclusion (internal use)
327pub const LC_PREPAGE = 0xa; /// prepage command (internal use)
328pub const LC_DYSYMTAB = 0xb; /// dynamic link-edit symbol table info
329pub const LC_LOAD_DYLIB = 0xc; /// load a dynamically linked shared library
330pub const LC_ID_DYLIB = 0xd; /// dynamically linked shared lib ident
331pub const LC_LOAD_DYLINKER = 0xe; /// load a dynamic linker
332pub const LC_ID_DYLINKER = 0xf; /// dynamic linker identification
333pub const LC_PREBOUND_DYLIB = 0x10; /// modules prebound for a dynamically
334pub const LC_ROUTINES = 0x11; /// image routines
335pub const LC_SUB_FRAMEWORK = 0x12; /// sub framework
336pub const LC_SUB_UMBRELLA = 0x13; /// sub umbrella
337pub const LC_SUB_CLIENT = 0x14; /// sub client
338pub const LC_SUB_LIBRARY = 0x15; /// sub library
339pub const LC_TWOLEVEL_HINTS = 0x16; /// two-level namespace lookup hints
340pub const LC_PREBIND_CKSUM = 0x17; /// prebind checksum
341
342/// load a dynamically linked shared library that is allowed to be missing
343/// (all symbols are weak imported).
344pub const LC_LOAD_WEAK_DYLIB = (0x18 | LC_REQ_DYLD);
345
346pub const LC_SEGMENT_64 = 0x19; /// 64-bit segment of this file to be mapped
347pub const LC_ROUTINES_64 = 0x1a; /// 64-bit image routines
348pub const LC_UUID = 0x1b; /// the uuid
349pub const LC_RPATH = (0x1c | LC_REQ_DYLD); /// runpath additions
350pub const LC_CODE_SIGNATURE = 0x1d; /// local of code signature
351pub const LC_SEGMENT_SPLIT_INFO = 0x1e; /// local of info to split segments
352pub const LC_REEXPORT_DYLIB = (0x1f | LC_REQ_DYLD); /// load and re-export dylib
353pub const LC_LAZY_LOAD_DYLIB = 0x20; /// delay load of dylib until first use
354pub const LC_ENCRYPTION_INFO = 0x21; /// encrypted segment information
355pub const LC_DYLD_INFO = 0x22; /// compressed dyld information
356pub const LC_DYLD_INFO_ONLY = (0x22|LC_REQ_DYLD); /// compressed dyld information only
357pub const LC_LOAD_UPWARD_DYLIB = (0x23 | LC_REQ_DYLD); /// load upward dylib
358pub const LC_VERSION_MIN_MACOSX = 0x24; /// build for MacOSX min OS version
359pub const LC_VERSION_MIN_IPHONEOS = 0x25; /// build for iPhoneOS min OS version
360pub const LC_FUNCTION_STARTS = 0x26; /// compressed table of function start addresses
361pub const LC_DYLD_ENVIRONMENT = 0x27; /// string for dyld to treat like environment variable
362pub const LC_MAIN = (0x28|LC_REQ_DYLD); /// replacement for LC_UNIXTHREAD
363pub const LC_DATA_IN_CODE = 0x29; /// table of non-instructions in __text
364pub const LC_SOURCE_VERSION = 0x2A; /// source version used to build binary
365pub const LC_DYLIB_CODE_SIGN_DRS = 0x2B; /// Code signing DRs copied from linked dylibs
366pub const LC_ENCRYPTION_INFO_64 = 0x2C; /// 64-bit encrypted segment information
367pub const LC_LINKER_OPTION = 0x2D; /// linker options in MH_OBJECT files
368pub const LC_LINKER_OPTIMIZATION_HINT = 0x2E; /// optimization hints in MH_OBJECT files
369pub const LC_VERSION_MIN_TVOS = 0x2F; /// build for AppleTV min OS version
370pub const LC_VERSION_MIN_WATCHOS = 0x30; /// build for Watch min OS version
371pub const LC_NOTE = 0x31; /// arbitrary data included within a Mach-O file
372pub const LC_BUILD_VERSION = 0x32; /// build for platform min OS version
373
374pub const MH_MAGIC = 0xfeedface; /// the mach magic number
375pub const MH_CIGAM = 0xcefaedfe; /// NXSwapInt(MH_MAGIC)
376
377pub const MH_MAGIC_64 = 0xfeedfacf; /// the 64-bit mach magic number
378pub const MH_CIGAM_64 = 0xcffaedfe; /// NXSwapInt(MH_MAGIC_64)
379
380pub const MH_OBJECT = 0x1; /// relocatable object file
381pub const MH_EXECUTE = 0x2; /// demand paged executable file
382pub const MH_FVMLIB = 0x3; /// fixed VM shared library file
383pub const MH_CORE = 0x4; /// core file
384pub const MH_PRELOAD = 0x5; /// preloaded executable file
385pub const MH_DYLIB = 0x6; /// dynamically bound shared library
386pub const MH_DYLINKER = 0x7; /// dynamic link editor
387pub const MH_BUNDLE = 0x8; /// dynamically bound bundle file
388pub const MH_DYLIB_STUB = 0x9; /// shared library stub for static linking only, no section contents
389pub const MH_DSYM = 0xa; /// companion file with only debug sections
390pub const MH_KEXT_BUNDLE = 0xb; /// x86_64 kexts
391
392// Constants for the flags field of the mach_header
393
394pub const MH_NOUNDEFS = 0x1; /// the object file has no undefined references
395pub 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
396pub const MH_DYLDLINK = 0x4; /// the object file is input for the dynamic linker and can't be staticly link edited again
397pub const MH_BINDATLOAD = 0x8; /// the object file's undefined references are bound by the dynamic linker when loaded.
398pub const MH_PREBOUND = 0x10; /// the file has its dynamic undefined references prebound.
399pub const MH_SPLIT_SEGS = 0x20; /// the file has its read-only and read-write segments split
400pub const MH_LAZY_INIT = 0x40; /// the shared library init routine is to be run lazily via catching memory faults to its writeable segments (obsolete)
401pub const MH_TWOLEVEL = 0x80; /// the image is using two-level name space bindings
402pub const MH_FORCE_FLAT = 0x100; /// the executable is forcing all images to use flat name space bindings
403pub 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.
404pub const MH_NOFIXPREBINDING = 0x400; /// do not have dyld notify the prebinding agent about this executable
405pub const MH_PREBINDABLE = 0x800; /// the binary is not prebound but can have its prebinding redone. only used when MH_PREBOUND is not set.
406pub 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.
407pub const MH_SUBSECTIONS_VIA_SYMBOLS = 0x2000;/// safe to divide up the sections into sub-sections via symbols for dead code stripping
408pub const MH_CANONICAL = 0x4000; /// the binary has been canonicalized via the unprebind operation
409pub const MH_WEAK_DEFINES = 0x8000; /// the final linked image contains external weak symbols
410pub const MH_BINDS_TO_WEAK = 0x10000; /// the final linked image uses weak symbols
411
412pub 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.
413pub const MH_ROOT_SAFE = 0x40000; /// When this bit is set, the binary declares it is safe for use in processes with uid zero
414
415pub const MH_SETUID_SAFE = 0x80000; /// When this bit is set, the binary declares it is safe for use in processes when issetugid() is true
416
417pub 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
418pub 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.
419pub 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.
420pub const MH_HAS_TLV_DESCRIPTORS = 0x800000; /// Contains a section of type S_THREAD_LOCAL_VARIABLES
421
422pub 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.
423
424pub const MH_APP_EXTENSION_SAFE = 0x02000000; /// The code was linked for use in an application extension.
425
426pub 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.
427
428
429/// The flags field of a section structure is separated into two parts a section
430/// type and section attributes. The section types are mutually exclusive (it
431/// can only have one type) but the section attributes are not (it may have more
432/// than one attribute).
433/// 256 section types
434pub const SECTION_TYPE = 0x000000ff;
435pub const SECTION_ATTRIBUTES = 0xffffff00; /// 24 section attributes
436
437pub const S_REGULAR = 0x0; /// regular section
438pub const S_ZEROFILL = 0x1; /// zero fill on demand section
439pub const S_CSTRING_LITERALS = 0x2; /// section with only literal C string
440pub const S_4BYTE_LITERALS = 0x3; /// section with only 4 byte literals
441pub const S_8BYTE_LITERALS = 0x4; /// section with only 8 byte literals
442pub const S_LITERAL_POINTERS = 0x5; /// section with only pointers to
443
444
445pub const N_STAB = 0xe0; /// if any of these bits set, a symbolic debugging entry
446pub const N_PEXT = 0x10; /// private external symbol bit
447pub const N_TYPE = 0x0e; /// mask for the type bits
448pub const N_EXT = 0x01; /// external symbol bit, set for external symbols
449
450
451pub const N_GSYM = 0x20; /// global symbol: name,,NO_SECT,type,0
452pub const N_FNAME = 0x22; /// procedure name (f77 kludge): name,,NO_SECT,0,0
453pub const N_FUN = 0x24; /// procedure: name,,n_sect,linenumber,address
454pub const N_STSYM = 0x26; /// static symbol: name,,n_sect,type,address
455pub const N_LCSYM = 0x28; /// .lcomm symbol: name,,n_sect,type,address
456pub const N_BNSYM = 0x2e; /// begin nsect sym: 0,,n_sect,0,address
457pub const N_AST = 0x32; /// AST file path: name,,NO_SECT,0,0
458pub const N_OPT = 0x3c; /// emitted with gcc2_compiled and in gcc source
459pub const N_RSYM = 0x40; /// register sym: name,,NO_SECT,type,register
460pub const N_SLINE = 0x44; /// src line: 0,,n_sect,linenumber,address
461pub const N_ENSYM = 0x4e; /// end nsect sym: 0,,n_sect,0,address
462pub const N_SSYM = 0x60; /// structure elt: name,,NO_SECT,type,struct_offset
463pub const N_SO = 0x64; /// source file name: name,,n_sect,0,address
464pub const N_OSO = 0x66; /// object file name: name,,0,0,st_mtime
465pub const N_LSYM = 0x80; /// local sym: name,,NO_SECT,type,offset
466pub const N_BINCL = 0x82; /// include file beginning: name,,NO_SECT,0,sum
467pub const N_SOL = 0x84; /// #included file name: name,,n_sect,0,address
468pub const N_PARAMS = 0x86; /// compiler parameters: name,,NO_SECT,0,0
469pub const N_VERSION = 0x88; /// compiler version: name,,NO_SECT,0,0
470pub const N_OLEVEL = 0x8A; /// compiler -O level: name,,NO_SECT,0,0
471pub const N_PSYM = 0xa0; /// parameter: name,,NO_SECT,type,offset
472pub const N_EINCL = 0xa2; /// include file end: name,,NO_SECT,0,0
473pub const N_ENTRY = 0xa4; /// alternate entry: name,,n_sect,linenumber,address
474pub const N_LBRAC = 0xc0; /// left bracket: 0,,NO_SECT,nesting level,address
475pub const N_EXCL = 0xc2; /// deleted include file: name,,NO_SECT,0,sum
476pub const N_RBRAC = 0xe0; /// right bracket: 0,,NO_SECT,nesting level,address
477pub const N_BCOMM = 0xe2; /// begin common: name,,NO_SECT,0,0
478pub const N_ECOMM = 0xe4; /// end common: name,,n_sect,0,0
479pub const N_ECOML = 0xe8; /// end common (local name): 0,,n_sect,0,address
480pub const N_LENG = 0xfe; /// second stab entry with length information
481
482/// If a segment contains any sections marked with S_ATTR_DEBUG then all
483/// sections in that segment must have this attribute. No section other than
484/// a section marked with this attribute may reference the contents of this
485/// section. A section with this attribute may contain no symbols and must have
486/// a section type S_REGULAR. The static linker will not copy section contents
487/// from sections with this attribute into its output file. These sections
488/// generally contain DWARF debugging info.
489pub const S_ATTR_DEBUG = 0x02000000; /// a debug section
490
491pub const cpu_type_t = integer_t;
492pub const cpu_subtype_t = integer_t;
493pub const integer_t = c_int;
494pub const vm_prot_t = c_int;
495
142496// sys/types.h on macos uses #pragma pack(4) so these checks are
143497// to make sure the struct is laid out the same. These values were
144498// produced from C code using the offsetof macro.
std/debug/index.zig+251-111
......@@ -5,7 +5,6 @@ const io = std.io;
55const os = std.os;
66const elf = std.elf;
77const DW = std.dwarf;
8const macho = std.macho;
98const ArrayList = std.ArrayList;
109const builtin = @import("builtin");
1110
......@@ -19,9 +18,10 @@ pub const runtime_safety = switch (builtin.mode) {
1918
2019/// Tries to write to stderr, unbuffered, and ignores any error returned.
2120/// Does not append a newline.
22/// TODO atomic/multithread support
2321var stderr_file: os.File = undefined;
2422var stderr_file_out_stream: io.FileOutStream = undefined;
23
24/// TODO multithreaded awareness
2525var stderr_stream: ?*io.OutStream(io.FileOutStream.Error) = null;
2626var stderr_mutex = std.Mutex.init();
2727pub fn warn(comptime fmt: []const u8, args: ...) void {
......@@ -30,6 +30,7 @@ pub fn warn(comptime fmt: []const u8, args: ...) void {
3030 const stderr = getStderrStream() catch return;
3131 stderr.print(fmt, args) catch return;
3232}
33
3334pub fn getStderrStream() !*io.OutStream(io.FileOutStream.Error) {
3435 if (stderr_stream) |st| {
3536 return st;
......@@ -42,14 +43,15 @@ pub fn getStderrStream() !*io.OutStream(io.FileOutStream.Error) {
4243 }
4344}
4445
45var self_debug_info: ?*DebugInfo = null;
46/// TODO multithreaded awareness
47var self_debug_info: ?DebugInfo = null;
48
4649pub fn getSelfDebugInfo() !*DebugInfo {
47 if (self_debug_info) |info| {
50 if (self_debug_info) |*info| {
4851 return info;
4952 } else {
50 const info = try openSelfDebugInfo(getDebugInfoAllocator());
51 self_debug_info = info;
52 return info;
53 self_debug_info = try openSelfDebugInfo(getDebugInfoAllocator());
54 return &self_debug_info.?;
5355 }
5456}
5557
......@@ -127,6 +129,7 @@ pub fn panic(comptime format: []const u8, args: ...) noreturn {
127129 panicExtra(null, first_trace_addr, format, args);
128130}
129131
132/// TODO multithreaded awareness
130133var panicking: u8 = 0; // TODO make this a bool
131134
132135pub fn panicExtra(trace: ?*const builtin.StackTrace, first_trace_addr: ?usize, comptime format: []const u8, args: ...) noreturn {
......@@ -220,80 +223,147 @@ pub fn writeCurrentStackTrace(out_stream: var, allocator: *mem.Allocator, debug_
220223
221224pub fn printSourceAtAddress(debug_info: *DebugInfo, out_stream: var, address: usize, tty_color: bool) !void {
222225 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);
226 builtin.Os.macosx => return printSourceAtAddressMacOs(debug_info, out_stream, address, tty_color),
227 builtin.Os.linux => return printSourceAtAddressLinux(debug_info, out_stream, address, tty_color),
228 builtin.Os.windows => {
229 // TODO https://github.com/ziglang/zig/issues/721
230 return error.UnsupportedOperatingSystem;
236231 },
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,
232 else => return error.UnsupportedOperatingSystem,
233 }
234}
235
236fn machoSearchSymbols(symbols: []const MachoSymbol, address: usize) ?*const MachoSymbol {
237 var min: usize = 0;
238 var max: usize = symbols.len - 1; // Exclude sentinel.
239 while (min < max) {
240 const mid = min + (max - min) / 2;
241 const curr = &symbols[mid];
242 const next = &symbols[mid + 1];
243 if (address >= next.address()) {
244 min = mid + 1;
245 } else if (address < curr.address()) {
246 max = mid;
247 } else {
248 return curr;
249 }
250 }
251 return null;
252}
253
254fn printSourceAtAddressMacOs(debug_info: *DebugInfo, out_stream: var, address: usize, tty_color: bool) !void {
255 const base_addr = @ptrToInt(&std.c._mh_execute_header);
256 const adjusted_addr = 0x100000000 + (address - base_addr);
257
258 const symbol = machoSearchSymbols(debug_info.symbols, adjusted_addr) orelse {
259 if (tty_color) {
260 try out_stream.print("???:?:?: " ++ DIM ++ "0x{x} in ??? (???)" ++ RESET ++ "\n\n\n", address);
261 } else {
262 try out_stream.print("???:?:?: 0x{x} in ??? (???)\n\n\n", address);
263 }
264 return;
265 };
266
267 const symbol_name = mem.toSliceConst(u8, debug_info.strings.ptr + symbol.nlist.n_strx);
268 if (getLineNumberInfoMacOs(debug_info, symbol.*, address)) |line_info| {
269 const compile_unit_name = "???";
270 try printLineInfo(debug_info, out_stream, line_info, address, symbol_name, compile_unit_name, tty_color);
271 } else |err| switch (err) {
272 error.MissingDebugInfo => {
273 if (tty_color) {
274 try out_stream.print("???:?:?: " ++ DIM ++ "0x{x} in {} (???)" ++ RESET ++ "\n\n\n", address, symbol_name);
275 } else {
276 try out_stream.print("???:?:?: 0x{x} in {} (???)\n\n\n", address, symbol_name);
277 }
278 },
279 else => return err,
280 }
281}
282
283pub fn printSourceAtAddressLinux(debug_info: *DebugInfo, out_stream: var, address: usize, tty_color: bool) !void {
284 const compile_unit = findCompileUnit(debug_info, address) catch {
285 if (tty_color) {
286 try out_stream.print("???:?:?: " ++ DIM ++ "0x{x} in ??? (???)" ++ RESET ++ "\n\n\n", address);
287 } else {
288 try out_stream.print("???:?:?: 0x{x} in ??? (???)\n\n\n", address);
289 }
290 return;
291 };
292 const compile_unit_name = try compile_unit.die.getAttrString(debug_info, DW.AT_name);
293 if (getLineNumberInfoLinux(debug_info, compile_unit, address - 1)) |line_info| {
294 defer line_info.deinit();
295 const symbol_name = "???";
296 try printLineInfo(debug_info, out_stream, line_info, address, symbol_name, compile_unit_name, tty_color);
297 } else |err| switch (err) {
298 error.MissingDebugInfo, error.InvalidDebugInfo => {
299 if (tty_color) {
300 try out_stream.print("???:?:?: " ++ DIM ++ "0x{x} in ??? ({})" ++ RESET ++ "\n\n\n", address, compile_unit_name);
301 } else {
302 try out_stream.print("???:?:?: 0x{x} in ??? ({})\n\n\n", address, compile_unit_name);
303 }
304 },
305 else => return err,
306 }
307}
308
309fn printLineInfo(
310 debug_info: *DebugInfo,
311 out_stream: var,
312 line_info: LineInfo,
313 address: usize,
314 symbol_name: []const u8,
315 compile_unit_name: []const u8,
316 tty_color: bool,
317) !void {
318 if (tty_color) {
319 try out_stream.print(
320 WHITE ++ "{}:{}:{}" ++ RESET ++ ": " ++ DIM ++ "0x{x} in {} ({})" ++ RESET ++ "\n",
321 line_info.file_name,
322 line_info.line,
323 line_info.column,
324 address,
325 symbol_name,
326 compile_unit_name,
327 );
328 if (printLineFromFile(out_stream, line_info)) {
329 if (line_info.column == 0) {
330 try out_stream.write("\n");
331 } else {
332 {
333 var col_i: usize = 1;
334 while (col_i < line_info.column) : (col_i += 1) {
335 try out_stream.writeByte(' ');
273336 }
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 );
283337 }
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,
338 try out_stream.write(GREEN ++ "^" ++ RESET ++ "\n");
289339 }
290 },
340 } else |err| switch (err) {
341 error.EndOfFile => {},
342 else => return err,
343 }
344 } else {
345 try out_stream.print(
346 "{}:{}:{}: 0x{x} in {} ({})\n",
347 line_info.file_name,
348 line_info.line,
349 line_info.column,
350 address,
351 symbol_name,
352 compile_unit_name,
353 );
291354 }
292355}
293356
294pub fn openSelfDebugInfo(allocator: *mem.Allocator) !*DebugInfo {
295 switch (builtin.object_format) {
296 builtin.ObjectFormat.elf => {
357// TODO use this
358pub const OpenSelfDebugInfoError = error{
359 MissingDebugInfo,
360 OutOfMemory,
361 UnsupportedOperatingSystem,
362};
363
364pub fn openSelfDebugInfo(allocator: *mem.Allocator) !DebugInfo {
365 switch (builtin.os) {
366 builtin.Os.linux => {
297367 const st = try allocator.create(DebugInfo{
298368 .self_exe_file = undefined,
299369 .elf = undefined,
......@@ -320,24 +390,79 @@ pub fn openSelfDebugInfo(allocator: *mem.Allocator) !*DebugInfo {
320390 try scanAllCompileUnits(st);
321391 return st;
322392 },
323 builtin.ObjectFormat.macho => {
324 var exe_file = try os.openSelfExe();
325 defer exe_file.close();
326
327 const st = try allocator.create(DebugInfo{ .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;
393 builtin.Os.macosx, builtin.Os.ios => return openSelfDebugInfoMacOs(allocator),
394 builtin.Os.windows => {
395 // TODO: https://github.com/ziglang/zig/issues/721
396 return error.UnsupportedOperatingSystem;
339397 },
398 else => return error.UnsupportedOperatingSystem,
399 }
400}
401
402fn openSelfDebugInfoMacOs(allocator: *mem.Allocator) !DebugInfo {
403 const hdr = &std.c._mh_execute_header;
404 assert(hdr.magic == std.c.MH_MAGIC_64);
405
406 const hdr_base = @ptrCast([*]u8, hdr);
407 var ptr = hdr_base + @sizeOf(std.c.mach_header_64);
408 var ncmd: u32 = hdr.ncmds;
409 const symtab = while (ncmd != 0) : (ncmd -= 1) {
410 const lc = @ptrCast(*std.c.load_command, ptr);
411 switch (lc.cmd) {
412 std.c.LC_SYMTAB => break @ptrCast(*std.c.symtab_command, ptr),
413 else => {},
414 }
415 ptr += lc.cmdsize; // TODO https://github.com/ziglang/zig/issues/1403
416 } else {
417 return error.MissingDebugInfo;
418 };
419 const syms = @ptrCast([*]std.c.nlist_64, hdr_base + symtab.symoff)[0..symtab.nsyms];
420 const strings = @ptrCast([*]u8, hdr_base + symtab.stroff)[0..symtab.strsize];
421
422 const symbols_buf = try allocator.alloc(MachoSymbol, syms.len);
423
424 var ofile: ?*std.c.nlist_64 = null;
425 var symbol_index: usize = 0;
426 var last_len: u64 = 0;
427 for (syms) |*sym| {
428 if (sym.n_type & std.c.N_STAB != 0) {
429 switch (sym.n_type) {
430 std.c.N_OSO => ofile = sym,
431 std.c.N_FUN => {
432 if (sym.n_sect == 0) {
433 last_len = sym.n_value;
434 } else {
435 symbols_buf[symbol_index] = MachoSymbol{
436 .nlist = sym,
437 .ofile = ofile,
438 };
439 symbol_index += 1;
440 }
441 },
442 else => continue,
443 }
444 }
340445 }
446 const sentinel = try allocator.createOne(std.c.nlist_64);
447 sentinel.* = std.c.nlist_64{
448 .n_strx = 0,
449 .n_type = 36,
450 .n_sect = 0,
451 .n_desc = 0,
452 .n_value = symbols_buf[symbol_index - 1].nlist.n_value + last_len,
453 };
454
455 const symbols = allocator.shrink(MachoSymbol, symbols_buf, symbol_index);
456
457 // Even though lld emits symbols in ascending order, this debug code
458 // should work for programs linked in any valid way.
459 // This sort is so that we can binary search later.
460 std.sort.sort(MachoSymbol, symbols, MachoSymbol.addressLessThan);
461
462 return DebugInfo{
463 .symbols = symbols,
464 .strings = strings,
465 };
341466}
342467
343468fn printLineFromFile(out_stream: var, line_info: *const LineInfo) !void {
......@@ -372,13 +497,24 @@ fn printLineFromFile(out_stream: var, line_info: *const LineInfo) !void {
372497 }
373498}
374499
500const MachoSymbol = struct {
501 nlist: *std.c.nlist_64,
502 ofile: ?*std.c.nlist_64,
503
504 /// Returns the address from the macho file
505 fn address(self: MachoSymbol) u64 {
506 return self.nlist.n_value;
507 }
508
509 fn addressLessThan(lhs: MachoSymbol, rhs: MachoSymbol) bool {
510 return lhs.address() < rhs.address();
511 }
512};
513
375514pub const DebugInfo = switch (builtin.os) {
376515 builtin.Os.macosx => struct {
377 symbol_table: macho.SymbolTable,
378
379 pub fn close(self: *DebugInfo) void {
380 self.symbol_table.deinit();
381 }
516 symbols: []const MachoSymbol,
517 strings: []const u8,
382518 },
383519 else => struct {
384520 self_exe_file: os.File,
......@@ -803,12 +939,16 @@ fn parseDie(st: *DebugInfo, abbrev_table: *const AbbrevTable, is_64: bool) !Die
803939 return result;
804940}
805941
806fn getLineNumberInfo(st: *DebugInfo, compile_unit: *const CompileUnit, target_address: usize) !LineInfo {
807 const compile_unit_cwd = try compile_unit.die.getAttrString(st, DW.AT_comp_dir);
942fn getLineNumberInfoMacOs(di: *DebugInfo, symbol: MachoSymbol, target_address: usize) !LineInfo {
943 return error.MissingDebugInfo;
944}
808945
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;
946fn getLineNumberInfoLinux(di: *DebugInfo, compile_unit: *const CompileUnit, target_address: usize) !LineInfo {
947 const compile_unit_cwd = try compile_unit.die.getAttrString(di, DW.AT_comp_dir);
948
949 const in_file = &di.self_exe_file;
950 const debug_line_end = di.debug_line.offset + di.debug_line.size;
951 var this_offset = di.debug_line.offset;
812952 var this_index: usize = 0;
813953
814954 var in_file_stream = io.FileInStream.init(in_file);
......@@ -827,11 +967,11 @@ fn getLineNumberInfo(st: *DebugInfo, compile_unit: *const CompileUnit, target_ad
827967 continue;
828968 }
829969
830 const version = try in_stream.readInt(st.elf.endian, u16);
970 const version = try in_stream.readInt(di.elf.endian, u16);
831971 // TODO support 3 and 5
832972 if (version != 2 and version != 4) return error.InvalidDebugInfo;
833973
834 const prologue_length = if (is_64) try in_stream.readInt(st.elf.endian, u64) else try in_stream.readInt(st.elf.endian, u32);
974 const prologue_length = if (is_64) try in_stream.readInt(di.elf.endian, u64) else try in_stream.readInt(di.elf.endian, u32);
835975 const prog_start_offset = (try in_file.getPos()) + prologue_length;
836976
837977 const minimum_instruction_length = try in_stream.readByte();
......@@ -850,7 +990,7 @@ fn getLineNumberInfo(st: *DebugInfo, compile_unit: *const CompileUnit, target_ad
850990
851991 const opcode_base = try in_stream.readByte();
852992
853 const standard_opcode_lengths = try st.allocator().alloc(u8, opcode_base - 1);
993 const standard_opcode_lengths = try di.allocator().alloc(u8, opcode_base - 1);
854994
855995 {
856996 var i: usize = 0;
......@@ -859,19 +999,19 @@ fn getLineNumberInfo(st: *DebugInfo, compile_unit: *const CompileUnit, target_ad
859999 }
8601000 }
8611001
862 var include_directories = ArrayList([]u8).init(st.allocator());
1002 var include_directories = ArrayList([]u8).init(di.allocator());
8631003 try include_directories.append(compile_unit_cwd);
8641004 while (true) {
865 const dir = try st.readString();
1005 const dir = try di.readString();
8661006 if (dir.len == 0) break;
8671007 try include_directories.append(dir);
8681008 }
8691009
870 var file_entries = ArrayList(FileEntry).init(st.allocator());
1010 var file_entries = ArrayList(FileEntry).init(di.allocator());
8711011 var prog = LineNumberProgram.init(default_is_stmt, include_directories.toSliceConst(), &file_entries, target_address);
8721012
8731013 while (true) {
874 const file_name = try st.readString();
1014 const file_name = try di.readString();
8751015 if (file_name.len == 0) break;
8761016 const dir_index = try readULeb128(in_stream);
8771017 const mtime = try readULeb128(in_stream);
......@@ -901,11 +1041,11 @@ fn getLineNumberInfo(st: *DebugInfo, compile_unit: *const CompileUnit, target_ad
9011041 return error.MissingDebugInfo;
9021042 },
9031043 DW.LNE_set_address => {
904 const addr = try in_stream.readInt(st.elf.endian, usize);
1044 const addr = try in_stream.readInt(di.elf.endian, usize);
9051045 prog.address = addr;
9061046 },
9071047 DW.LNE_define_file => {
908 const file_name = try st.readString();
1048 const file_name = try di.readString();
9091049 const dir_index = try readULeb128(in_stream);
9101050 const mtime = try readULeb128(in_stream);
9111051 const len_bytes = try readULeb128(in_stream);
......@@ -963,7 +1103,7 @@ fn getLineNumberInfo(st: *DebugInfo, compile_unit: *const CompileUnit, target_ad
9631103 prog.address += inc_addr;
9641104 },
9651105 DW.LNS_fixed_advance_pc => {
966 const arg = try in_stream.readInt(st.elf.endian, u16);
1106 const arg = try in_stream.readInt(di.elf.endian, u16);
9671107 prog.address += arg;
9681108 },
9691109 DW.LNS_set_prologue_end => {},
......@@ -1142,7 +1282,7 @@ pub const global_allocator = &global_fixed_allocator.allocator;
11421282var global_fixed_allocator = std.heap.ThreadSafeFixedBufferAllocator.init(global_allocator_mem[0..]);
11431283var global_allocator_mem: [100 * 1024]u8 = undefined;
11441284
1145// TODO make thread safe
1285/// TODO multithreaded awareness
11461286var debug_info_allocator: ?*mem.Allocator = null;
11471287var debug_info_direct_allocator: std.heap.DirectAllocator = undefined;
11481288var debug_info_arena_allocator: std.heap.ArenaAllocator = undefined;
std/macho.zig deleted-172
......@@ -1,172 +0,0 @@
1const builtin = @import("builtin");
2const std = @import("index.zig");
3const io = std.io;
4const mem = std.mem;
5
6const MH_MAGIC_64 = 0xFEEDFACF;
7const MH_PIE = 0x200000;
8const LC_SYMTAB = 2;
9
10const MachHeader64 = packed struct {
11 magic: u32,
12 cputype: u32,
13 cpusubtype: u32,
14 filetype: u32,
15 ncmds: u32,
16 sizeofcmds: u32,
17 flags: u32,
18 reserved: u32,
19};
20
21const LoadCommand = packed struct {
22 cmd: u32,
23 cmdsize: u32,
24};
25
26const SymtabCommand = packed struct {
27 symoff: u32,
28 nsyms: u32,
29 stroff: u32,
30 strsize: u32,
31};
32
33const Nlist64 = packed struct {
34 n_strx: u32,
35 n_type: u8,
36 n_sect: u8,
37 n_desc: u16,
38 n_value: u64,
39};
40
41pub const Symbol = struct {
42 name: []const u8,
43 address: u64,
44
45 fn addressLessThan(lhs: Symbol, rhs: Symbol) bool {
46 return lhs.address < rhs.address;
47 }
48};
49
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};
85
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}