Debian Codegraph @

riscv64/riscv64asm/objdumpext_test.go

raw symbols SCIP
1 // Copyright 2024 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 package riscv64asm
6
7 import (
8 "bytes"
9 "debug/elf"
10 "encoding/binary"
11 "fmt"
12 "io"
13 "log"
14 "os"
15 "os/exec"
16 "regexp"
17 "strconv"
18 "strings"
19 "testing"
20 )
21
22 var objdumpPath = "riscv64-linux-gnu-objdump"
23
24 func testObjdumpRISCV64(t *testing.T, generate func(func([]byte))) {
25 testObjdumpArch(t, generate)
26 }
27
28 func testObjdumpArch(t *testing.T, generate func(func([]byte))) {
29 version := checkObjdumpRISCV64(t)
30 testExtDis(t, "gnu", objdump, generate, func(text string, inst *Inst, dec ExtInst) bool {
31 return allowedMismatchObjdump(text, inst, dec, version)
32 })
33 testExtDis(t, "plan9", objdump, generate, func(text string, inst *Inst, dec ExtInst) bool {
34 return allowedMismatchObjdump(text, inst, dec, version)
35 })
36 }
37
38 func checkObjdumpRISCV64(t *testing.T) string {
39 objdumpPath, err := exec.LookPath(objdumpPath)
40 if err != nil {
41 objdumpPath = "objdump"
42 }
43 out, err := exec.Command(objdumpPath, "-i").Output()
44 if err != nil {
45 t.Skipf("cannot run objdump: %v\n%s", err, out)
46 }
47 if !strings.Contains(string(out), "riscv") {
48 t.Skip("objdump does not have RISC-V support")
49 }
50 return parseObjdumpVersion(string(out))
51 }
52
53 var objdumpVersionRx = regexp.MustCompile(`\b(\d+\.\d+)`)
54
55 // parseObjdumpVersion extracts the version number from objdump -i output.
56 func parseObjdumpVersion(out string) string {
57 m := objdumpVersionRx.FindStringSubmatch(out)
58 if m != nil && len(m) > 1 {
59 return m[1]
60 }
61 return ""
62 }
63
64 func objdump(ext *ExtDis) error {
65 // File already written with instructions; add ELF header.
66 if err := writeELF64(ext.File, ext.Size); err != nil {
67 return err
68 }
69
70 b, err := ext.Run(objdumpPath, "-M numeric", "-d", "-z", ext.File.Name())
71 if err != nil {
72 return err
73 }
74
75 var (
76 nmatch int
77 reading bool
78 next uint64 = start
79 addr uint64
80 encbuf [4]byte
81 enc []byte
82 text string
83 )
84 flush := func() {
85 if addr == next {
86 // PC-relative addresses are translated to absolute addresses based on PC by GNU objdump
87 // Following logical rewrites the absolute addresses back to PC-relative ones for comparing
88 // with our disassembler output which are PC-relative
89 if text == "undefined" && len(enc) == 4 {
90 text = "error: unknown instruction"
91 enc = nil
92 }
93 if len(enc) == 4 {
94 // prints as word but we want to record bytes
95 enc[0], enc[3] = enc[3], enc[0]
96 enc[1], enc[2] = enc[2], enc[1]
97 }
98 ext.Dec <- ExtInst{addr, encbuf, len(enc), text}
99 encbuf = [4]byte{}
100 enc = nil
101 next += 4
102 }
103 }
104 var textangle = []byte("<.text>:")
105 for {
106 line, err := b.ReadSlice('\n')
107 if err != nil {
108 if err == io.EOF {
109 break
110 }
111 return fmt.Errorf("reading objdump output: %v", err)
112 }
113 if bytes.Contains(line, textangle) {
114 reading = true
115 continue
116 }
117 if !reading {
118 continue
119 }
120 if debug {
121 os.Stdout.Write(line)
122 }
123 if enc1 := parseContinuation(line, encbuf[:len(enc)]); enc1 != nil {
124 enc = enc1
125 continue
126 }
127 flush()
128 nmatch++
129 addr, enc, text = parseLine(line, encbuf[:0])
130 if addr > next {
131 return fmt.Errorf("address out of sync expected <= %#x at %q in:\n%s", next, line, line)
132 }
133 }
134 flush()
135 if next != start+uint64(ext.Size) {
136 return fmt.Errorf("not enough results found [%d %d]", next, start+ext.Size)
137 }
138 if err := ext.Wait(); err != nil {
139 return fmt.Errorf("exec: %v", err)
140 }
141
142 return nil
143 }
144
145 var (
146 undefined = []byte("undefined")
147 unpredictable = []byte("unpredictable")
148 slashslash = []byte("//")
149 )
150
151 func parseLine(line []byte, encstart []byte) (addr uint64, enc []byte, text string) {
152 ok := false
153 oline := line
154 i := bytes.Index(line, []byte(":\t"))
155 if i < 0 {
156 log.Fatalf("cannot parse disassembly: %q", oline)
157 }
158 x, err := strconv.ParseUint(string(bytes.TrimSpace(line[:i])), 16, 32)
159 if err != nil {
160 log.Fatalf("cannot parse disassembly: %q", oline)
161 }
162 addr = uint64(x)
163 line = line[i+2:]
164 i = bytes.IndexByte(line, '\t')
165 if i < 0 {
166 log.Fatalf("cannot parse disassembly: %q", oline)
167 }
168 enc, ok = parseHex(line[:i], encstart)
169 if !ok {
170 log.Fatalf("cannot parse disassembly: %q", oline)
171 }
172 line = bytes.TrimSpace(line[i:])
173 if bytes.Contains(line, undefined) {
174 text = "undefined"
175 return
176 }
177 if false && bytes.Contains(line, unpredictable) {
178 text = "unpredictable"
179 return
180 }
181 // Strip trailing comment starting with '#'
182 if i := bytes.IndexByte(line, '#'); i >= 0 {
183 line = bytes.TrimSpace(line[:i])
184 }
185 // Strip trailing comment starting with "//"
186 if i := bytes.Index(line, slashslash); i >= 0 {
187 line = bytes.TrimSpace(line[:i])
188 }
189 text = string(fixSpace(line))
190 return
191 }
192
193 // fixSpace rewrites runs of spaces, tabs, and newline characters into single spaces in s.
194 // If s must be rewritten, it is rewritten in place.
195 func fixSpace(s []byte) []byte {
196 s = bytes.TrimSpace(s)
197 for i := 0; i < len(s); i++ {
198 if s[i] == '\t' || s[i] == '\n' || i > 0 && s[i] == ' ' && s[i-1] == ' ' {
199 goto Fix
200 }
201 }
202 return s
203
204 Fix:
205 b := s
206 w := 0
207 for i := 0; i < len(s); i++ {
208 c := s[i]
209 if c == '\t' || c == '\n' {
210 c = ' '
211 }
212 if c == ' ' && w > 0 && b[w-1] == ' ' {
213 continue
214 }
215 b[w] = c
216 w++
217 }
218 if w > 0 && b[w-1] == ' ' {
219 w--
220 }
221 return b[:w]
222 }
223
224 func parseContinuation(line []byte, enc []byte) []byte {
225 i := bytes.Index(line, []byte(":\t"))
226 if i < 0 {
227 return nil
228 }
229 line = line[i+1:]
230 enc, _ = parseHex(line, enc)
231 return enc
232 }
233
234 // writeELF64 writes an ELF64 header to the file, describing a text
235 // segment that starts at start (0x8000) and extends for size bytes.
236 func writeELF64(f *os.File, size int) error {
237 f.Seek(0, io.SeekStart)
238 var hdr elf.Header64
239 var prog elf.Prog64
240 var sect elf.Section64
241 var buf bytes.Buffer
242 binary.Write(&buf, binary.LittleEndian, &hdr)
243 off1 := buf.Len()
244 binary.Write(&buf, binary.LittleEndian, &prog)
245 off2 := buf.Len()
246 binary.Write(&buf, binary.LittleEndian, &sect)
247 off3 := buf.Len()
248 buf.Reset()
249 data := byte(elf.ELFDATA2LSB)
250 hdr = elf.Header64{
251 Ident: [16]byte{0x7F, 'E', 'L', 'F', 2, data, 1},
252 Type: 2,
253 Machine: uint16(elf.EM_RISCV),
254 Version: 1,
255 Entry: start,
256 Phoff: uint64(off1),
257 Shoff: uint64(off2),
258 Flags: 0x5,
259 Ehsize: uint16(off1),
260 Phentsize: uint16(off2 - off1),
261 Phnum: 1,
262 Shentsize: uint16(off3 - off2),
263 Shnum: 4,
264 Shstrndx: 3,
265 }
266 binary.Write(&buf, binary.LittleEndian, &hdr)
267 prog = elf.Prog64{
268 Type: 1,
269 Off: start,
270 Vaddr: start,
271 Paddr: start,
272 Filesz: uint64(size),
273 Memsz: uint64(size),
274 Flags: 5,
275 Align: start,
276 }
277 binary.Write(&buf, binary.LittleEndian, &prog)
278 binary.Write(&buf, binary.LittleEndian, &sect) // NULL section
279 sect = elf.Section64{
280 Name: 1,
281 Type: uint32(elf.SHT_PROGBITS),
282 Addr: start,
283 Off: start,
284 Size: uint64(size),
285 Flags: uint64(elf.SHF_ALLOC | elf.SHF_EXECINSTR),
286 Addralign: 4,
287 }
288 binary.Write(&buf, binary.LittleEndian, &sect) // .text
289 strtabsize := len("\x00.text\x00.riscv.attributes\x00.shstrtab\x00")
290 // RISC-V objdump needs the .riscv.attributes section to identify extensions.
291 exts := "rv64i2p0_m2p0_a2p0_f2p0_d2p0_q2p0_c2p0_v1p0_" +
292 "zicbom1p0_zicbop1p0_zicboz1p0_zicond1p0_zmmul1p0_" +
293 "zfh1p0_zfhmin1p0_zba1p0_zbb1p0_zbc1p0_zbs1p0_" +
294 "zvkg1p0_zvkned1p0_zvknha1p0_zvknhb1p0_zvksed1p0_zvksh1p0"
295 b := buildRISCVAttributes(exts)
296 sect = elf.Section64{
297 Name: uint32(len("\x00.text\x00")),
298 Type: uint32(0x70000003), // SHT_RISCV_ATTRIBUTES
299 Addr: 0,
300 Off: uint64(off2 + (off3-off2)*4 + strtabsize),
301 Size: uint64(len(b)),
302 Addralign: 1,
303 }
304 binary.Write(&buf, binary.LittleEndian, &sect)
305 sect = elf.Section64{
306 Name: uint32(len("\x00.text\x00.riscv.attributes\x00")),
307 Type: uint32(elf.SHT_STRTAB),
308 Addr: 0,
309 Off: uint64(off2 + (off3-off2)*4),
310 Size: uint64(strtabsize),
311 Addralign: 1,
312 }
313 binary.Write(&buf, binary.LittleEndian, &sect)
314 buf.WriteString("\x00.text\x00.riscv.attributes\x00.shstrtab\x00")
315 buf.Write(b)
316 f.Write(buf.Bytes())
317 return nil
318 }
319
320 func buildRISCVAttributes(exts string) []byte {
321 // Subsection content
322 content := []byte{5} // Tag_RISCV_arch
323 content = append(content, []byte(exts)...) // extensions
324 content = append(content, 0) // NULL
325 content = append(content, 8, 1, 10, 11) // priv_spec
326
327 // Subsection
328 sub := new(bytes.Buffer)
329 sub.WriteByte(1) // Tag_File
330 binary.Write(sub, binary.LittleEndian, uint32(1+4+len(content))) // size
331 sub.Write(content) // content
332
333 // Full section
334 buf := new(bytes.Buffer)
335 buf.WriteByte('A') // Fixed prefix
336 binary.Write(buf, binary.LittleEndian, uint32(4+6+sub.Len())) // size
337 buf.WriteString("riscv\x00") // vendor
338 buf.Write(sub.Bytes()) // subsection
339
340 return buf.Bytes()
341 }