Debian Codegraph @

gopls/internal/golang/assembly.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 golang
6
7 // This file produces the "Browse GOARCH assembly of f" HTML report.
8 //
9 // See also:
10 // - ./codeaction.go - computes the symbol and offers the CodeAction command.
11 // - ../server/command.go - handles the command by opening a web page.
12 // - ../server/server.go - handles the HTTP request and calls this function.
13 //
14 // For language-server behavior in Go assembly language files,
15 // see [golang.org/x/tools/gopls/internal/goasm].
16
17 import (
18 "bytes"
19 "context"
20 "fmt"
21 "html"
22 "io"
23 "net/http"
24 "os"
25 "regexp"
26 "strconv"
27 "strings"
28
29 "golang.org/x/tools/gopls/internal/cache"
30 "golang.org/x/tools/gopls/internal/util/morestrings"
31 )
32
33 // AssemblyHTML returns an HTML document containing an assembly listing of the selected function.
34 //
35 // TODO(adonovan): cross-link jumps and block labels, like github.com/aclements/objbrowse.
36 //
37 // See gopls/internal/test/integration/misc/webserver_test.go for tests.
38 func AssemblyHTML(ctx context.Context, snapshot *cache.Snapshot, w http.ResponseWriter, pkg *cache.Package, symbol string, web Web) {
39 // Prepare to compile the package with -S, and capture its stderr stream.
40 // We use "go test -c" not "go build" as it covers all three packages
41 // (p, "p [p.test]", "p_test [p.test]") in the directory, if they exist.
42 // (See also compileropt.go.)
43 inv, cleanupInvocation, err := snapshot.GoCommandInvocation(cache.NoNetwork, pkg.Metadata().CompiledGoFiles[0].DirPath(),
44 "test", []string{
45 "-c",
46 "-o", os.DevNull,
47 "-gcflags=-S",
48 ".",
49 })
50 if err != nil {
51 // e.g. failed to write overlays (rare)
52 http.Error(w, err.Error(), http.StatusInternalServerError)
53 return
54 }
55 defer cleanupInvocation()
56
57 escape := html.EscapeString
58
59 // Emit the start of the report.
60 titleHTML := fmt.Sprintf("%s assembly for %s",
61 escape(snapshot.View().GOARCH()),
62 escape(symbol))
63 io.WriteString(w, `<!DOCTYPE html>
64 <html>
65 <head>
66 <meta charset="UTF-8">
67 <title>`+titleHTML+`</title>
68 <link rel="stylesheet" href="/assets/common.css">
69 <script src="/assets/common.js"></script>
70 </head>
71 <body>
72 <h1>`+titleHTML+`</h1>
73 <p>
74 <a href='https://go.dev/doc/asm'>A Quick Guide to Go's Assembler</a>
75 </p>
76 <p>
77 Experimental. <a href='https://github.com/golang/go/issues/67478'>Contributions welcome!</a>
78 </p>
79 <p>
80 Click on a source line marker <code>L1234</code> to navigate your editor there.
81 (VS Code users: please upvote <a href='https://github.com/microsoft/vscode/issues/208093'>#208093</a>)
82 </p>
83 <p id='compiling'>Compiling...</p>
84 <pre>
85 `)
86 if flusher, ok := w.(http.Flusher); ok {
87 flusher.Flush()
88 }
89
90 // At this point errors must be reported by writing HTML.
91 // To do this, set "status" return early.
92
93 var buf bytes.Buffer
94 status := "Reload the page to recompile."
95 defer func() {
96 // Update the "Compiling..." message.
97 fmt.Fprintf(&buf, `
98 </pre>
99 <script>
100 document.getElementById('compiling').innerText = %q;
101 </script>
102 </body>`, status)
103 w.Write(buf.Bytes())
104 }()
105
106 // Compile the package.
107 _, stderr, err, _ := snapshot.View().GoCommandRunner().RunRaw(ctx, *inv)
108 if err != nil {
109 status = fmt.Sprintf("compilation failed: %v", err)
110 return
111 }
112
113 // Write the rest of the report.
114 content := stderr.String()
115
116 // insnRx matches an assembly instruction line.
117 // Submatch groups are: (offset-hex-dec, file-line-column, instruction).
118 insnRx := regexp.MustCompile(`^(\s+0x[0-9a-f ]+)\(([^)]*)\)\s+(.*)$`)
119
120 // Parse the functions of interest out of the listing.
121 // Each function is of the form:
122 //
123 // symbol STEXT k=v...
124 // 0x0000 00000 (/file.go:123) NOP...
125 // ...
126 //
127 // Allow matches of symbol, symbol.func1, symbol.deferwrap, etc.
128 on := false
129 for line := range strings.SplitSeq(content, "\n") {
130 // start of function symbol?
131 if strings.Contains(line, " STEXT ") {
132 on = strings.HasPrefix(line, symbol) &&
133 (line[len(symbol)] == ' ' || line[len(symbol)] == '.')
134 }
135 if !on {
136 continue // within uninteresting symbol
137 }
138
139 // In lines of the form
140 // "\t0x0000 00000 (/file.go:123) NOP..."
141 // replace the "(/file.go:123)" portion with an "L0123" source link.
142 // Skip filenames of the form "<foo>".
143 if parts := insnRx.FindStringSubmatch(line); parts != nil {
144 link := " " // if unknown
145 if file, linenum, ok := morestrings.CutLast(parts[2], ":"); ok && !strings.HasPrefix(file, "<") {
146 if linenum, err := strconv.Atoi(linenum); err == nil {
147 text := fmt.Sprintf("L%04d", linenum)
148 link = sourceLink(text, web.SrcURL(file, linenum, 1))
149 }
150 }
151 fmt.Fprintf(&buf, "%s\t%s\t%s", escape(parts[1]), link, escape(parts[3]))
152 } else {
153 buf.WriteString(escape(line))
154 }
155 buf.WriteByte('\n')
156 }
157 }