aboutsummaryrefslogtreecommitdiffstats
path: root/pkg/compiler/consts.go
blob: 338dea4b1336f8621e5ac5e88f3240abec3fc806 (plain)
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
// Copyright 2017 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.

package compiler

import (
	"bufio"
	"bytes"
	"fmt"
	"io/ioutil"
	"path/filepath"
	"sort"
	"strconv"
	"strings"

	"github.com/google/syzkaller/pkg/ast"
	"github.com/google/syzkaller/sys/targets"
)

type ConstInfo struct {
	Consts   []string
	Includes []string
	Incdirs  []string
	Defines  map[string]string
}

// ExtractConsts returns list of literal constants and other info required const value extraction.
func ExtractConsts(desc *ast.Description, target *targets.Target, eh0 ast.ErrorHandler) *ConstInfo {
	errors := 0
	eh := func(pos ast.Pos, msg string, args ...interface{}) {
		errors++
		msg = fmt.Sprintf(msg, args...)
		if eh0 != nil {
			eh0(pos, msg)
		} else {
			ast.LoggingHandler(pos, msg)
		}
	}
	info := &ConstInfo{
		Defines: make(map[string]string),
	}
	includeMap := make(map[string]bool)
	incdirMap := make(map[string]bool)
	constMap := make(map[string]bool)

	ast.Walk(desc, func(n1 ast.Node) {
		switch n := n1.(type) {
		case *ast.Include:
			file := n.File.Value
			if includeMap[file] {
				eh(n.Pos, "duplicate include %q", file)
			}
			includeMap[file] = true
			info.Includes = append(info.Includes, file)
		case *ast.Incdir:
			dir := n.Dir.Value
			if incdirMap[dir] {
				eh(n.Pos, "duplicate incdir %q", dir)
			}
			incdirMap[dir] = true
			info.Incdirs = append(info.Incdirs, dir)
		case *ast.Define:
			v := fmt.Sprint(n.Value.Value)
			switch {
			case n.Value.CExpr != "":
				v = n.Value.CExpr
			case n.Value.Ident != "":
				v = n.Value.Ident
			}
			name := n.Name.Name
			if info.Defines[name] != "" {
				eh(n.Pos, "duplicate define %v", name)
			}
			info.Defines[name] = v
			constMap[name] = true
		case *ast.Call:
			if target.SyscallNumbers && !strings.HasPrefix(n.CallName, "syz_") {
				constMap[target.SyscallPrefix+n.CallName] = true
			}
		case *ast.Type:
			if c := typeConstIdentifier(n); c != nil {
				constMap[c.Ident] = true
				constMap[c.Ident2] = true
			}
		case *ast.Int:
			constMap[n.Ident] = true
		}
	})

	if errors != 0 {
		return nil
	}
	info.Consts = toArray(constMap)
	return info
}

// assignSyscallNumbers assigns syscall numbers, discards unsupported syscalls
// and removes no longer irrelevant nodes from the tree (comments, new lines, etc).
func (comp *compiler) assignSyscallNumbers(consts map[string]uint64) {
	// Pseudo syscalls starting from syz_ are assigned numbers starting from syzbase.
	// Note: the numbers must be stable (not depend on file reading order, etc),
	// so we have to do it in 2 passes.
	const syzbase = 1000000
	syzcalls := make(map[string]bool)
	for _, decl := range comp.desc.Nodes {
		c, ok := decl.(*ast.Call)
		if !ok {
			continue
		}
		if strings.HasPrefix(c.CallName, "syz_") {
			syzcalls[c.CallName] = true
		}
	}
	syznr := make(map[string]uint64)
	for i, name := range toArray(syzcalls) {
		syznr[name] = syzbase + uint64(i)
	}

	var top []ast.Node
	for _, decl := range comp.desc.Nodes {
		switch decl.(type) {
		case *ast.Call:
			c := decl.(*ast.Call)
			if strings.HasPrefix(c.CallName, "syz_") {
				c.NR = syznr[c.CallName]
				top = append(top, decl)
				continue
			}
			if !comp.target.SyscallNumbers {
				top = append(top, decl)
				continue
			}
			// Lookup in consts.
			str := comp.target.SyscallPrefix + c.CallName
			nr, ok := consts[str]
			top = append(top, decl)
			if ok {
				c.NR = nr
				continue
			}
			c.NR = ^uint64(0) // mark as unused to not generate it
			name := "syscall " + c.CallName
			if !comp.unsupported[name] {
				comp.unsupported[name] = true
				comp.warning(c.Pos, "unsupported syscall: %v due to missing const %v",
					c.CallName, str)
			}
		case *ast.IntFlags, *ast.Resource, *ast.Struct, *ast.StrFlags, *ast.TypeDef:
			top = append(top, decl)
		case *ast.NewLine, *ast.Comment, *ast.Include, *ast.Incdir, *ast.Define:
			// These are not needed anymore.
		default:
			panic(fmt.Sprintf("unknown node type: %#v", decl))
		}
	}
	comp.desc.Nodes = top
}

// patchConsts replaces all symbolic consts with their numeric values taken from consts map.
// Updates desc and returns set of unsupported syscalls and flags.
// After this pass consts are not needed for compilation.
func (comp *compiler) patchConsts(consts map[string]uint64) {
	var top []ast.Node
	for _, decl := range comp.desc.Nodes {
		switch decl.(type) {
		case *ast.IntFlags:
			// Unsupported flag values are dropped.
			n := decl.(*ast.IntFlags)
			var values []*ast.Int
			for _, v := range n.Values {
				if comp.patchIntConst(v.Pos, &v.Value, &v.Ident, consts, nil) {
					values = append(values, v)
				}
			}
			n.Values = values
			top = append(top, n)
		case *ast.StrFlags:
			top = append(top, decl)
		case *ast.Resource, *ast.Struct, *ast.Call, *ast.TypeDef:
			// Walk whole tree and replace consts in Int's and Type's.
			missing := ""
			ast.WalkNode(decl, func(n0 ast.Node) {
				switch n := n0.(type) {
				case *ast.Int:
					comp.patchIntConst(n.Pos, &n.Value, &n.Ident, consts, &missing)
				case *ast.Type:
					if c := typeConstIdentifier(n); c != nil {
						comp.patchIntConst(c.Pos, &c.Value, &c.Ident,
							consts, &missing)
						if c.HasColon {
							comp.patchIntConst(c.Pos2, &c.Value2, &c.Ident2,
								consts, &missing)
						}
					}
				}
			})
			if missing == "" {
				top = append(top, decl)
				continue
			}
			// Produce a warning about unsupported syscall/resource/struct.
			// TODO(dvyukov): we should transitively remove everything that
			// depends on unsupported things.
			// Potentially we still can get, say, a bad int range error
			// due to the 0 const value.
			pos, typ, name := decl.Info()
			if id := typ + " " + name; !comp.unsupported[id] {
				comp.unsupported[id] = true
				comp.warning(pos, "unsupported %v: %v due to missing const %v",
					typ, name, missing)
			}
			// We have to keep partially broken resources and structs,
			// because otherwise their usages will error.
			top = append(top, decl)
			if c, ok := decl.(*ast.Call); ok {
				c.NR = ^uint64(0) // mark as unused to not generate it
			}
		}
	}
	comp.desc.Nodes = top
}

func (comp *compiler) patchIntConst(pos ast.Pos, val *uint64, id *string,
	consts map[string]uint64, missing *string) bool {
	if *id == "" {
		return true
	}
	v, ok := consts[*id]
	if !ok {
		name := "const " + *id
		if !comp.unsupported[name] {
			comp.unsupported[name] = true
			comp.warning(pos, "unsupported const: %v", *id)
		}
		if missing != nil && *missing == "" {
			*missing = *id
		}
	}
	*val = v
	*id = ""
	return ok
}

// typeConstIdentifier returns type arg that is an integer constant (subject for const patching), if any.
func typeConstIdentifier(n *ast.Type) *ast.Type {
	// TODO: see if we can extract this info from typeDesc/typeArg.
	if n.Ident == "const" && len(n.Args) > 0 {
		return n.Args[0]
	}
	if n.Ident == "array" && len(n.Args) > 1 && n.Args[1].Ident != "opt" {
		return n.Args[1]
	}
	if n.Ident == "vma" && len(n.Args) > 0 && n.Args[0].Ident != "opt" {
		return n.Args[0]
	}
	if n.Ident == "string" && len(n.Args) > 1 && n.Args[1].Ident != "opt" {
		return n.Args[1]
	}
	if n.Ident == "csum" && len(n.Args) > 2 && n.Args[1].Ident == "pseudo" {
		return n.Args[2]
	}
	switch n.Ident {
	case "int8", "int16", "int16be", "int32", "int32be", "int64", "int64be", "intptr":
		if len(n.Args) > 0 && n.Args[0].Ident != "opt" {
			return n.Args[0]
		}
	}
	return nil
}

func SerializeConsts(consts map[string]uint64) []byte {
	type nameValuePair struct {
		name string
		val  uint64
	}
	var nv []nameValuePair
	for k, v := range consts {
		nv = append(nv, nameValuePair{k, v})
	}
	sort.Slice(nv, func(i, j int) bool {
		return nv[i].name < nv[j].name
	})

	buf := new(bytes.Buffer)
	fmt.Fprintf(buf, "# AUTOGENERATED FILE\n")
	for _, x := range nv {
		fmt.Fprintf(buf, "%v = %v\n", x.name, x.val)
	}
	return buf.Bytes()
}

func DeserializeConsts(data []byte, file string, eh ast.ErrorHandler) map[string]uint64 {
	consts := make(map[string]uint64)
	pos := ast.Pos{
		File: file,
		Line: 1,
	}
	ok := true
	s := bufio.NewScanner(bytes.NewReader(data))
	for ; s.Scan(); pos.Line++ {
		line := s.Text()
		if line == "" || line[0] == '#' {
			continue
		}
		eq := strings.IndexByte(line, '=')
		if eq == -1 {
			eh(pos, "expect '='")
			ok = false
			continue
		}
		name := strings.TrimSpace(line[:eq])
		val, err := strconv.ParseUint(strings.TrimSpace(line[eq+1:]), 0, 64)
		if err != nil {
			eh(pos, fmt.Sprintf("failed to parse int: %v", err))
			ok = false
			continue
		}
		if _, ok := consts[name]; ok {
			eh(pos, fmt.Sprintf("duplicate const %q", name))
			ok = false
			continue
		}
		consts[name] = val
	}
	if err := s.Err(); err != nil {
		eh(pos, fmt.Sprintf("failed to parse: %v", err))
		ok = false
	}
	if !ok {
		return nil
	}
	return consts
}

func DeserializeConstsGlob(glob string, eh ast.ErrorHandler) map[string]uint64 {
	if eh == nil {
		eh = ast.LoggingHandler
	}
	files, err := filepath.Glob(glob)
	if err != nil {
		eh(ast.Pos{}, fmt.Sprintf("failed to find const files: %v", err))
		return nil
	}
	if len(files) == 0 {
		eh(ast.Pos{}, fmt.Sprintf("no const files matched by glob %q", glob))
		return nil
	}
	consts := make(map[string]uint64)
	for _, f := range files {
		data, err := ioutil.ReadFile(f)
		if err != nil {
			eh(ast.Pos{}, fmt.Sprintf("failed to read const file: %v", err))
			return nil
		}
		consts1 := DeserializeConsts(data, filepath.Base(f), eh)
		if consts1 == nil {
			consts = nil
		}
		if consts != nil {
			for n, v := range consts1 {
				if old, ok := consts[n]; ok && old != v {
					eh(ast.Pos{}, fmt.Sprintf(
						"different values for const %q: %v vs %v", n, v, old))
					return nil
				}
				consts[n] = v
			}
		}
	}
	return consts
}