Debian Codegraph @

cmd/splitdwarf/splitdwarf.go

raw symbols SCIP
1 // Copyright 2018 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 //go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd
6
7 /*
8 Splitdwarf uncompresses and copies the DWARF segment of a Mach-O
9 executable into the "dSYM" file expected by lldb and ports of gdb
10 on OSX.
11
12 Usage: splitdwarf osxMachoFile [ osxDsymFile ]
13
14 Unless a dSYM file name is provided on the command line,
15 splitdwarf will place it where the OSX tools expect it, in
16 "<osxMachoFile>.dSYM/Contents/Resources/DWARF/<osxMachoFile>",
17 creating directories as necessary.
18 */
19 package main // import "golang.org/x/tools/cmd/splitdwarf"
20
21 import (
22 "crypto/sha256"
23 "fmt"
24 "io"
25 "os"
26 "path/filepath"
27 "strings"
28 "syscall"
29
30 "golang.org/x/tools/cmd/splitdwarf/internal/macho"
31 )
32
33 const (
34 pageAlign = 12 // 4096 = 1 << 12
35 )
36
37 func note(format string, why ...any) {
38 fmt.Fprintf(os.Stderr, format+"\n", why...)
39 }
40
41 func fail(format string, why ...any) {
42 note(format, why...)
43 os.Exit(1)
44 }
45
46 // splitdwarf inputexe [ outputdwarf ]
47 func main() {
48 if len(os.Args) < 2 || len(os.Args) > 3 {
49 fmt.Printf(`
50 Usage: %s input_exe [ output_dsym ]
51 Reads the executable input_exe, uncompresses and copies debugging
52 information into output_dsym. If output_dsym is not specified,
53 the path
54 input_exe.dSYM/Contents/Resources/DWARF/input_exe
55 is used instead. That is the path that gdb and lldb expect
56 on OSX. Input_exe needs a UUID segment; if that is missing,
57 then one is created and added. In that case, the permissions
58 for input_exe need to allow writing.
59 `, os.Args[0])
60 return
61 }
62
63 // Read input, find DWARF, be sure it looks right
64 inputExe := os.Args[1]
65 exeFile, err := os.Open(inputExe)
66 if err != nil {
67 fail("%v", err)
68 }
69 exeMacho, err := macho.NewFile(exeFile)
70 if err != nil {
71 fail("(internal) Couldn't create macho, %v", err)
72 }
73 // Postpone dealing with output till input is known-good
74
75 // describe(&exeMacho.FileTOC)
76
77 // Offsets into __LINKEDIT:
78 //
79 // Command LC_SYMTAB =
80 // (1) number of symbols at file offset (within link edit section) of 16-byte symbol table entries
81 // struct {
82 // StringTableIndex uint32
83 // Type, SectionIndex uint8
84 // Description uint16
85 // Value uint64
86 // }
87 //
88 // (2) string table offset and size. Strings are zero-byte terminated. First must be " ".
89 //
90 // Command LC_DYSYMTAB = indices within symtab (above), except for IndSym
91 // IndSym Offset = file offset (within link edit section) of 4-byte indices within symtab.
92 //
93 // Section __TEXT.__symbol_stub1.
94 // Offset and size (Reserved2) locate and describe a table for this section.
95 // Symbols beginning at IndirectSymIndex (Reserved1) (see LC_DYSYMTAB.IndSymOffset) refer to this table.
96 // (These table entries are apparently PLTs [Procedure Linkage Table/Trampoline])
97 //
98 // Section __DATA.__nl_symbol_ptr.
99 // Reserved1 seems to be an index within the Indirect symbols (see LC_DYSYMTAB.IndSymOffset)
100 // Some of these symbols appear to be duplicates of other indirect symbols appearing early
101 //
102 // Section __DATA.__la_symbol_ptr.
103 // Reserved1 seems to be an index within the Indirect symbols (see LC_DYSYMTAB.IndSymOffset)
104 // Some of these symbols appear to be duplicates of other indirect symbols appearing early
105 //
106
107 // Create a File for the output dwarf.
108 // Copy header, file type is MH_DSYM
109 // Copy the relevant load commands
110
111 // LoadCmdUuid
112 // Symtab -- very abbreviated (Use DYSYMTAB Iextdefsym, Nextdefsym to identify these).
113 // Segment __PAGEZERO
114 // Segment __TEXT (zero the size, zero the offset of each section)
115 // Segment __DATA (zero the size, zero the offset of each section)
116 // Segment __LINKEDIT (contains the symbols and strings from Symtab)
117 // Segment __DWARF (uncompressed)
118
119 var uuid *macho.Uuid
120 for _, l := range exeMacho.Loads {
121 switch l.Command() {
122 case macho.LcUuid:
123 uuid = l.(*macho.Uuid)
124 }
125 }
126
127 // Ensure a given load is not nil
128 nonnilC := func(l macho.Load, s string) {
129 if l == nil {
130 fail("input file %s lacks load command %s", inputExe, s)
131 }
132 }
133
134 // Find a segment by name and ensure it is not nil
135 nonnilS := func(s string) *macho.Segment {
136 l := exeMacho.Segment(s)
137 if l == nil {
138 fail("input file %s lacks segment %s", inputExe, s)
139 }
140 return l
141 }
142
143 newtoc := exeMacho.FileTOC.DerivedCopy(macho.MhDsym, 0)
144
145 symtab := exeMacho.Symtab
146 dysymtab := exeMacho.Dysymtab // Not appearing in output, but necessary to construct output
147 nonnilC(symtab, "symtab")
148 nonnilC(dysymtab, "dysymtab")
149 text := nonnilS("__TEXT")
150 data := nonnilS("__DATA")
151 linkedit := nonnilS("__LINKEDIT")
152 pagezero := nonnilS("__PAGEZERO")
153
154 newtext := text.CopyZeroed()
155 newdata := data.CopyZeroed()
156 newsymtab := symtab.Copy()
157
158 // Linkedit segment contain symbols and strings;
159 // Symtab refers to offsets into linkedit.
160 // This next bit initializes newsymtab and sets up data structures for the linkedit segment
161 linkeditsyms := []macho.Nlist64{}
162 linkeditstrings := []string{}
163
164 // Linkedit will begin at the second page, i.e., offset is one page from beginning
165 // Symbols come first
166 linkeditsymbase := uint32(1) << pageAlign
167
168 // Strings come second, offset by the number of symbols times their size.
169 // Only those symbols from dysymtab.defsym are written into the debugging information.
170 linkeditstringbase := linkeditsymbase + exeMacho.FileTOC.SymbolSize()*dysymtab.Nextdefsym
171
172 // The first two bytes of the strings are reserved for space, null (' ', \000)
173 linkeditstringcur := uint32(2)
174
175 newsymtab.Syms = newsymtab.Syms[:0]
176 newsymtab.Symoff = linkeditsymbase
177 newsymtab.Stroff = linkeditstringbase
178 newsymtab.Nsyms = dysymtab.Nextdefsym
179 for i := uint32(0); i < dysymtab.Nextdefsym; i++ {
180 ii := i + dysymtab.Iextdefsym
181 oldsym := symtab.Syms[ii]
182 newsymtab.Syms = append(newsymtab.Syms, oldsym)
183
184 linkeditsyms = append(linkeditsyms, macho.Nlist64{Name: linkeditstringcur,
185 Type: oldsym.Type, Sect: oldsym.Sect, Desc: oldsym.Desc, Value: oldsym.Value})
186 linkeditstringcur += uint32(len(oldsym.Name)) + 1
187 linkeditstrings = append(linkeditstrings, oldsym.Name)
188 }
189 newsymtab.Strsize = linkeditstringcur
190
191 exeNeedsUuid := uuid == nil
192 if exeNeedsUuid {
193 uuid = &macho.Uuid{UuidCmd: macho.UuidCmd{LoadCmd: macho.LcUuid}}
194 uuid.Len = uuid.LoadSize(newtoc)
195 copy(uuid.Id[0:], contentuuid(&exeMacho.FileTOC)[0:16])
196 uuid.Id[6] = uuid.Id[6]&^0xf0 | 0x40 // version 4 (pseudo-random); see section 4.1.3
197 uuid.Id[8] = uuid.Id[8]&^0xc0 | 0x80 // variant bits; see section 4.1.1
198 }
199 newtoc.AddLoad(uuid)
200
201 // For the specified segment (assumed to be in exeMacho) make a copy of its
202 // sections with appropriate fields zeroed out, and append them to the
203 // currently-last segment in newtoc.
204 copyZOdSections := func(g *macho.Segment) {
205 for i := g.Firstsect; i < g.Firstsect+g.Nsect; i++ {
206 s := exeMacho.Sections[i].Copy()
207 s.Offset = 0
208 s.Reloff = 0
209 s.Nreloc = 0
210 newtoc.AddSection(s)
211 }
212 }
213
214 newtoc.AddLoad(newsymtab)
215 newtoc.AddSegment(pagezero)
216 newtoc.AddSegment(newtext)
217 copyZOdSections(text)
218 newtoc.AddSegment(newdata)
219 copyZOdSections(data)
220
221 newlinkedit := linkedit.Copy()
222 newlinkedit.Offset = uint64(linkeditsymbase)
223 newlinkedit.Filesz = uint64(linkeditstringcur)
224 newlinkedit.Addr = macho.RoundUp(newdata.Addr+newdata.Memsz, 1<<pageAlign) // Follows data sections in file
225 newlinkedit.Memsz = macho.RoundUp(newlinkedit.Filesz, 1<<pageAlign)
226 // The rest should copy over fine.
227 newtoc.AddSegment(newlinkedit)
228
229 dwarf := nonnilS("__DWARF")
230 newdwarf := dwarf.CopyZeroed()
231 newdwarf.Offset = macho.RoundUp(newlinkedit.Offset+newlinkedit.Filesz, 1<<pageAlign)
232 newdwarf.Filesz = dwarf.UncompressedSize(&exeMacho.FileTOC, 1)
233 newdwarf.Addr = newlinkedit.Addr + newlinkedit.Memsz // Follows linkedit sections in file.
234 newdwarf.Memsz = macho.RoundUp(newdwarf.Filesz, 1<<pageAlign)
235 newtoc.AddSegment(newdwarf)
236
237 // Map out Dwarf sections (that is, this is section descriptors, not their contents).
238 offset := uint32(newdwarf.Offset)
239 for i := dwarf.Firstsect; i < dwarf.Firstsect+dwarf.Nsect; i++ {
240 o := exeMacho.Sections[i]
241 s := o.Copy()
242 s.Offset = offset
243 us := o.UncompressedSize()
244 if s.Size < us {
245 s.Size = uint64(us)
246 s.Align = 0 // This is apparently true for debugging sections; not sure if it generalizes.
247 }
248 offset += uint32(us)
249 if strings.HasPrefix(s.Name, "__z") {
250 s.Name = "__" + s.Name[3:] // remove "z"
251 }
252 s.Reloff = 0
253 s.Nreloc = 0
254 newtoc.AddSection(s)
255 }
256
257 // Write segments/sections.
258 // Only dwarf and linkedit contain anything interesting.
259
260 // Memory map the output file to get the buffer directly.
261 outDwarf := inputExe + ".dSYM/Contents/Resources/DWARF"
262 if len(os.Args) > 2 {
263 outDwarf = os.Args[2]
264 } else {
265 err := os.MkdirAll(outDwarf, 0755)
266 if err != nil {
267 fail("%v", err)
268 }
269 outDwarf = filepath.Join(outDwarf, filepath.Base(inputExe))
270 }
271 dwarfFile, buffer := CreateMmapFile(outDwarf, int64(newtoc.FileSize()))
272
273 // (1) Linkedit segment
274 // Symbol table
275 offset = uint32(newlinkedit.Offset)
276 for i := range linkeditsyms {
277 if exeMacho.Magic == macho.Magic64 {
278 offset += linkeditsyms[i].Put64(buffer[offset:], newtoc.ByteOrder)
279 } else {
280 offset += linkeditsyms[i].Put32(buffer[offset:], newtoc.ByteOrder)
281 }
282 }
283
284 // Initial two bytes of string table, followed by actual zero-terminated strings.
285 buffer[linkeditstringbase] = ' '
286 buffer[linkeditstringbase+1] = 0
287 offset = linkeditstringbase + 2
288 for _, str := range linkeditstrings {
289 for i := 0; i < len(str); i++ {
290 buffer[offset] = str[i]
291 offset++
292 }
293 buffer[offset] = 0
294 offset++
295 }
296
297 // (2) DWARF segment
298 ioff := newdwarf.Firstsect - dwarf.Firstsect
299 for i := dwarf.Firstsect; i < dwarf.Firstsect+dwarf.Nsect; i++ {
300 s := exeMacho.Sections[i]
301 j := i + ioff
302 s.PutUncompressedData(buffer[newtoc.Sections[j].Offset:])
303 }
304
305 // Because "text" overlaps the header and the loads, write them afterwards, just in case.
306 // Write header.
307 newtoc.Put(buffer)
308
309 err = syscall.Munmap(buffer)
310 if err != nil {
311 fail("Munmap %s for dwarf output failed, %v", outDwarf, err)
312 }
313 err = dwarfFile.Close()
314 if err != nil {
315 fail("Close %s for dwarf output after mmap/munmap failed, %v", outDwarf, err)
316 }
317
318 if exeNeedsUuid { // Map the original exe, modify the header, and write the UUID command
319 hdr := exeMacho.FileTOC.FileHeader
320 oldCommandEnd := hdr.SizeCommands + newtoc.HdrSize()
321 hdr.NCommands += 1
322 hdr.SizeCommands += uuid.LoadSize(newtoc)
323
324 mapf, err := os.OpenFile(inputExe, os.O_RDWR, 0)
325 if err != nil {
326 fail("Updating UUID in binary failed, %v", err)
327 }
328 exebuf, err := syscall.Mmap(int(mapf.Fd()), 0, int(macho.RoundUp(uint64(hdr.SizeCommands), 1<<pageAlign)),
329 syscall.PROT_READ|syscall.PROT_WRITE, syscall.MAP_FILE|syscall.MAP_SHARED)
330 if err != nil {
331 fail("Mmap of %s for UUID update failed, %v", inputExe, err)
332 }
333 _ = hdr.Put(exebuf, newtoc.ByteOrder)
334 _ = uuid.Put(exebuf[oldCommandEnd:], newtoc.ByteOrder)
335 err = syscall.Munmap(exebuf)
336 if err != nil {
337 fail("Munmap of %s for UUID update failed, %v", inputExe, err)
338 }
339 }
340 }
341
342 // CreateMmapFile creates the file 'outDwarf' of the specified size, mmaps that file,
343 // and returns the file descriptor and mapped buffer.
344 func CreateMmapFile(outDwarf string, size int64) (*os.File, []byte) {
345 dwarfFile, err := os.OpenFile(outDwarf, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
346 if err != nil {
347 fail("Open for mmap failed, %v", err)
348 }
349 err = os.Truncate(outDwarf, size)
350 if err != nil {
351 fail("Truncate/extend of %s to %d bytes failed, %v", dwarfFile, size, err)
352 }
353 buffer, err := syscall.Mmap(int(dwarfFile.Fd()), 0, int(size), syscall.PROT_READ|syscall.PROT_WRITE, syscall.MAP_FILE|syscall.MAP_SHARED)
354 if err != nil {
355 fail("Mmap %s for dwarf output update failed, %v", outDwarf, err)
356 }
357 return dwarfFile, buffer
358 }
359
360 // (dead code; retained for debugging)
361 func describe(exem *macho.FileTOC) {
362 note("Type = %s, Flags=0x%x", exem.Type, uint32(exem.Flags))
363 for i, l := range exem.Loads {
364 if s, ok := l.(*macho.Segment); ok {
365 fmt.Printf("Load %d is Segment %s, offset=0x%x, filesz=%d, addr=0x%x, memsz=%d, nsect=%d\n", i, s.Name,
366 s.Offset, s.Filesz, s.Addr, s.Memsz, s.Nsect)
367 for j := uint32(0); j < s.Nsect; j++ {
368 c := exem.Sections[j+s.Firstsect]
369 fmt.Printf(" Section %s, offset=0x%x, size=%d, addr=0x%x, flags=0x%x, nreloc=%d, res1=%d, res2=%d, res3=%d\n", c.Name, c.Offset, c.Size, c.Addr, c.Flags, c.Nreloc, c.Reserved1, c.Reserved2, c.Reserved3)
370 }
371 } else {
372 fmt.Printf("Load %d is %v\n", i, l)
373 }
374 }
375 if exem.SizeCommands != exem.LoadSize() {
376 fail("recorded command size %d does not equal computed command size %d", exem.SizeCommands, exem.LoadSize())
377 } else {
378 note("recorded command size %d, computed command size %d", exem.SizeCommands, exem.LoadSize())
379 }
380 note("File size is %d", exem.FileSize())
381 }
382
383 // contentuuid returns a UUID derived from (some of) the content of an executable.
384 // specifically included are the non-DWARF sections, specifically excluded are things
385 // that surely depend on the presence or absence of DWARF sections (e.g., section
386 // numbers, positions with file, number of load commands).
387 // (It was considered desirable if this was insensitive to the presence of the
388 // __DWARF segment, however because it is not last, it moves other segments,
389 // whose contents appear to contain file offset references.)
390 func contentuuid(exem *macho.FileTOC) []byte {
391 h := sha256.New()
392 for _, l := range exem.Loads {
393 if l.Command() == macho.LcUuid {
394 continue
395 }
396 if s, ok := l.(*macho.Segment); ok {
397 if s.Name == "__DWARF" || s.Name == "__PAGEZERO" {
398 continue
399 }
400 for j := uint32(0); j < s.Nsect; j++ {
401 c := exem.Sections[j+s.Firstsect]
402 io.Copy(h, c.Open())
403 }
404 } // Getting dependence on other load commands right is fiddly.
405 }
406 return h.Sum(nil)
407 }