/
main.go
287 lines (264 loc) · 7.79 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
// TODO: Add support for parsing from standard input.
// The restructure tool recovers control flow primitives from DOT control flow
// graphs (*.dot -> *.json).
//
// The input of restructure is a Graphviz DOT file, containing the unstructured
// control flow graph of a function, and the output is a JSON stream describing
// how the recovered high-level control flow primitives relate to the nodes of
// the control flow graph.
//
// Usage:
//
// restructure [OPTION]... FILE.dot
//
// Flags:
//
// -entry string
// entry node of the control flow graph
// -indent
// indent JSON output
// -o string
// output path
// -q suppress non-error messages
// -steps
// output intermediate control flow graphs at each step
package main
import (
"bytes"
"encoding/json"
goerrors "errors"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"strconv"
"github.com/decomp/decomp/cfa"
"github.com/decomp/decomp/cfa/primitive"
"github.com/decomp/decomp/graph/cfg"
"github.com/mewkiz/pkg/pathutil"
"github.com/mewkiz/pkg/term"
"github.com/pkg/errors"
"gonum.org/v1/gonum/graph"
"gonum.org/v1/gonum/graph/encoding/dot"
)
// dbg represents a logger with the "restructure:" prefix, which logs debug
// messages to standard error.
var dbg = log.New(os.Stderr, term.MagentaBold("restructure:")+" ", 0)
func usage() {
const use = `
Recover control flow primitives from DOT control flow graphs (*.dot -> *.json).
Usage:
restructure [OPTION]... FILE.dot
Flags:
`
fmt.Fprintln(os.Stderr, use[1:])
flag.PrintDefaults()
}
func main() {
// Parse command line flags.
var (
// entryLabel specifies the entry node of the control flow graph.
entryLabel string
// indent specifies whether to indent JSON output.
indent bool
// output specifies the output path.
output string
// quiet specifies whether to suppress non-error messages.
quiet bool
// steps specifies whether to output intermediate control flow graphs at
// each step.
steps bool
)
flag.StringVar(&entryLabel, "entry", "", "entry node of the control flow graph")
flag.BoolVar(&indent, "indent", false, "indent JSON output")
flag.StringVar(&output, "o", "", "output path")
flag.BoolVar(&quiet, "q", false, "suppress non-error messages")
flag.BoolVar(&steps, "steps", false, "output intermediate control flow graphs at each step")
flag.Usage = usage
flag.Parse()
if flag.NArg() != 1 {
flag.Usage()
os.Exit(1)
}
// Mute debug messages if `-q` is set.
if quiet {
dbg.SetOutput(ioutil.Discard)
}
// Parse DOT file.
dotPath := flag.Arg(0)
name := pathutil.FileName(dotPath)
g, err := cfg.ParseFile(dotPath)
if err != nil {
log.Fatalf("%+v", err)
}
// Locate entry node.
entry, err := locateEntryNode(g, entryLabel)
if err != nil {
log.Fatalf("%+v", err)
}
// Perform control flow analysis.
prims, err := restructure(g, entry, steps, name)
if err != nil {
if errors.Cause(err) == ErrIncomplete {
// Do _not_ terminate on incomplete control flow recovery. Instead
// print partial results.
dbg.Printf("WARNING: %v", err)
} else {
log.Fatalf("%+v", err)
}
}
// Store JSON output.
w := os.Stdout
if len(output) > 0 {
f, err := os.Create(output)
if err != nil {
log.Fatal(err)
}
defer f.Close()
w = f
}
if err := writeJSON(w, prims, indent); err != nil {
log.Fatalf("%+v", err)
}
}
// locateEntryNode attempts to locate the entry node of the control flow graph,
// either by label if specified, or by searching for a single node in the
// control flow graph with no incoming edges.
func locateEntryNode(g *cfg.Graph, entryLabel string) (graph.Node, error) {
if len(entryLabel) > 0 {
entry, ok := g.NodeByLabel(entryLabel)
if !ok {
return nil, errors.Errorf("unable to locate entry node with node label %q", entryLabel)
}
return entry, nil
}
var entry graph.Node
nodes := g.Nodes()
for nodes.Next() {
n := nodes.Node()
preds := g.To(n.ID())
if preds.Len() == 0 {
if entry != nil {
return nil, errors.Errorf("more than one candidate for the entry node located; prev %q, new %q", label(entry), label(n))
}
entry = n
}
}
if entry == nil {
return nil, errors.Errorf("unable to locate entry node; try specifying an entry node label using the -entry flag")
}
return entry, nil
}
// ErrIncomplete signals an incomplete control flow recovery.
var ErrIncomplete = goerrors.New("incomplete control flow recovery")
// restructure attempts to recover the control flow primitives of a given
// control flow graph. It does so by repeatedly locating and merging structured
// subgraphs (graph representations of control flow primitives) into single
// nodes until the entire graph is reduced into a single node or no structured
// subgraphs may be located. The steps argument specifies whether to record the
// intermediate CFGs at each step. The returned list of primitives is ordered in
// the same sequence as they were located.
func restructure(g *cfg.Graph, entry graph.Node, steps bool, name string) ([]*primitive.Primitive, error) {
prims := make([]*primitive.Primitive, 0)
// Locate control flow primitives.
for step := 1; g.Nodes().Len() > 1; step++ {
// Locate primitive.
dom := cfg.NewDom(g, entry)
prim, err := cfa.FindPrim(g, dom)
if err != nil {
return prims, errors.Wrap(ErrIncomplete, err.Error())
}
prims = append(prims, prim)
// Output pre-merge intermediate CFG.
if steps {
path := fmt.Sprintf("%s_%04da.dot", name, step)
var highlight []string
for _, node := range prim.Nodes {
highlight = append(highlight, node)
}
if err := storeStep(g, name, path, highlight); err != nil {
return nil, errors.WithStack(err)
}
}
// Merge the nodes of the primitive into a single node.
if err := cfa.Merge(g, prim); err != nil {
return nil, errors.WithStack(err)
}
// Handle special case where entry node has been replaced by primitive
// node.
if g.Node(entry.ID()) == nil {
var ok bool
entry, ok = g.NodeByLabel(prim.Entry)
if !ok {
return nil, errors.Errorf("unable to locate entry node %q", prim.Entry)
}
}
// Output post-merge intermediate CFG.
if steps {
path := fmt.Sprintf("%s_%04db.dot", name, step)
highlight := []string{prim.Entry}
if err := storeStep(g, name, path, highlight); err != nil {
return nil, errors.WithStack(err)
}
}
}
return prims, nil
}
// storeStep stores a DOT representation of g to path with the specified nodes
// highlighted in red.
func storeStep(g *cfg.Graph, name, path string, highlight []string) error {
for _, h := range highlight {
n, ok := g.NodeByLabel(h)
if !ok {
return errors.Errorf("unable to located node %q to be highlighted", h)
}
n.Attrs["style"] = "filled"
n.Attrs["fillcolor"] = "red"
}
buf, err := dot.Marshal(g, strconv.Quote(name), "", "\t")
if err != nil {
return errors.WithStack(err)
}
for _, h := range highlight {
n, ok := g.NodeByLabel(h)
if !ok {
return errors.Errorf("unable to located node %q to be highlighted", h)
}
delete(n.Attrs, "style")
delete(n.Attrs, "fillcolor")
}
if err := ioutil.WriteFile(path, buf, 0644); err != nil {
return errors.WithStack(err)
}
return nil
}
// writeJSON writes the primitives in JSON format to w.
func writeJSON(w io.Writer, prims []*primitive.Primitive, indent bool) error {
// Output indented JSON.
if indent {
buf, err := json.MarshalIndent(prims, "", "\t")
if err != nil {
return errors.WithStack(err)
}
buf = append(buf, '\n')
if _, err := io.Copy(w, bytes.NewReader(buf)); err != nil {
return errors.WithStack(err)
}
return nil
}
// Output JSON.
enc := json.NewEncoder(w)
if err := enc.Encode(prims); err != nil {
return errors.WithStack(err)
}
return nil
}
// label returns the label of the node.
func label(n graph.Node) string {
if n, ok := n.(*cfg.Node); ok {
return n.Label
}
panic(fmt.Sprintf("invalid node type; expected *cfg.Node, got %T", n))
}