summaryrefslogtreecommitdiffstats
path: root/src/internal/coverage/decodecounter/decodecounterfile.go
blob: 83934fe68b389ab811af74fd54f31057167d7f48 (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
372
373
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package decodecounter

import (
	"encoding/binary"
	"fmt"
	"internal/coverage"
	"internal/coverage/slicereader"
	"internal/coverage/stringtab"
	"io"
	"os"
	"strconv"
	"unsafe"
)

// This file contains helpers for reading counter data files created
// during the executions of a coverage-instrumented binary.

type CounterDataReader struct {
	stab     *stringtab.Reader
	args     map[string]string
	osargs   []string
	goarch   string // GOARCH setting from run that produced counter data
	goos     string // GOOS setting from run that produced counter data
	mr       io.ReadSeeker
	hdr      coverage.CounterFileHeader
	ftr      coverage.CounterFileFooter
	shdr     coverage.CounterSegmentHeader
	u32b     []byte
	u8b      []byte
	fcnCount uint32
	segCount uint32
	debug    bool
}

func NewCounterDataReader(fn string, rs io.ReadSeeker) (*CounterDataReader, error) {
	cdr := &CounterDataReader{
		mr:   rs,
		u32b: make([]byte, 4),
		u8b:  make([]byte, 1),
	}
	// Read header
	if err := binary.Read(rs, binary.LittleEndian, &cdr.hdr); err != nil {
		return nil, err
	}
	if cdr.debug {
		fmt.Fprintf(os.Stderr, "=-= counter file header: %+v\n", cdr.hdr)
	}
	if !checkMagic(cdr.hdr.Magic) {
		return nil, fmt.Errorf("invalid magic string: not a counter data file")
	}
	if cdr.hdr.Version > coverage.CounterFileVersion {
		return nil, fmt.Errorf("version data incompatibility: reader is %d data is %d", coverage.CounterFileVersion, cdr.hdr.Version)
	}

	// Read footer.
	if err := cdr.readFooter(); err != nil {
		return nil, err
	}
	// Seek back to just past the file header.
	hsz := int64(unsafe.Sizeof(cdr.hdr))
	if _, err := cdr.mr.Seek(hsz, io.SeekStart); err != nil {
		return nil, err
	}
	// Read preamble for first segment.
	if err := cdr.readSegmentPreamble(); err != nil {
		return nil, err
	}
	return cdr, nil
}

func checkMagic(v [4]byte) bool {
	g := coverage.CovCounterMagic
	return v[0] == g[0] && v[1] == g[1] && v[2] == g[2] && v[3] == g[3]
}

func (cdr *CounterDataReader) readFooter() error {
	ftrSize := int64(unsafe.Sizeof(cdr.ftr))
	if _, err := cdr.mr.Seek(-ftrSize, io.SeekEnd); err != nil {
		return err
	}
	if err := binary.Read(cdr.mr, binary.LittleEndian, &cdr.ftr); err != nil {
		return err
	}
	if !checkMagic(cdr.ftr.Magic) {
		return fmt.Errorf("invalid magic string (not a counter data file)")
	}
	if cdr.ftr.NumSegments == 0 {
		return fmt.Errorf("invalid counter data file (no segments)")
	}
	return nil
}

// readSegmentPreamble reads and consumes the segment header, segment string
// table, and segment args table.
func (cdr *CounterDataReader) readSegmentPreamble() error {
	// Read segment header.
	if err := binary.Read(cdr.mr, binary.LittleEndian, &cdr.shdr); err != nil {
		return err
	}
	if cdr.debug {
		fmt.Fprintf(os.Stderr, "=-= read counter segment header: %+v", cdr.shdr)
		fmt.Fprintf(os.Stderr, " FcnEntries=0x%x StrTabLen=0x%x ArgsLen=0x%x\n",
			cdr.shdr.FcnEntries, cdr.shdr.StrTabLen, cdr.shdr.ArgsLen)
	}

	// Read string table and args.
	if err := cdr.readStringTable(); err != nil {
		return err
	}
	if err := cdr.readArgs(); err != nil {
		return err
	}
	// Seek past any padding to bring us up to a 4-byte boundary.
	if of, err := cdr.mr.Seek(0, io.SeekCurrent); err != nil {
		return err
	} else {
		rem := of % 4
		if rem != 0 {
			pad := 4 - rem
			if _, err := cdr.mr.Seek(pad, io.SeekCurrent); err != nil {
				return err
			}
		}
	}
	return nil
}

func (cdr *CounterDataReader) readStringTable() error {
	b := make([]byte, cdr.shdr.StrTabLen)
	nr, err := cdr.mr.Read(b)
	if err != nil {
		return err
	}
	if nr != int(cdr.shdr.StrTabLen) {
		return fmt.Errorf("error: short read on string table")
	}
	slr := slicereader.NewReader(b, false /* not readonly */)
	cdr.stab = stringtab.NewReader(slr)
	cdr.stab.Read()
	return nil
}

func (cdr *CounterDataReader) readArgs() error {
	b := make([]byte, cdr.shdr.ArgsLen)
	nr, err := cdr.mr.Read(b)
	if err != nil {
		return err
	}
	if nr != int(cdr.shdr.ArgsLen) {
		return fmt.Errorf("error: short read on args table")
	}
	slr := slicereader.NewReader(b, false /* not readonly */)
	sget := func() (string, error) {
		kidx := slr.ReadULEB128()
		if int(kidx) >= cdr.stab.Entries() {
			return "", fmt.Errorf("malformed string table ref")
		}
		return cdr.stab.Get(uint32(kidx)), nil
	}
	nents := slr.ReadULEB128()
	cdr.args = make(map[string]string, int(nents))
	for i := uint64(0); i < nents; i++ {
		k, errk := sget()
		if errk != nil {
			return errk
		}
		v, errv := sget()
		if errv != nil {
			return errv
		}
		if _, ok := cdr.args[k]; ok {
			return fmt.Errorf("malformed args table")
		}
		cdr.args[k] = v
	}
	if argcs, ok := cdr.args["argc"]; ok {
		argc, err := strconv.Atoi(argcs)
		if err != nil {
			return fmt.Errorf("malformed argc in counter data file args section")
		}
		cdr.osargs = make([]string, 0, argc)
		for i := 0; i < argc; i++ {
			arg := cdr.args[fmt.Sprintf("argv%d", i)]
			cdr.osargs = append(cdr.osargs, arg)
		}
	}
	if goos, ok := cdr.args["GOOS"]; ok {
		cdr.goos = goos
	}
	if goarch, ok := cdr.args["GOARCH"]; ok {
		cdr.goarch = goarch
	}
	return nil
}

// OsArgs returns the program arguments (saved from os.Args during
// the run of the instrumented binary) read from the counter
// data file. Not all coverage data files will have os.Args values;
// for example, if a data file is produced by merging coverage
// data from two distinct runs, no os args will be available (an
// empty list is returned).
func (cdr *CounterDataReader) OsArgs() []string {
	return cdr.osargs
}

// Goos returns the GOOS setting in effect for the "-cover" binary
// that produced this counter data file. The GOOS value may be
// empty in the case where the counter data file was produced
// from a merge in which more than one GOOS value was present.
func (cdr *CounterDataReader) Goos() string {
	return cdr.goos
}

// Goarch returns the GOARCH setting in effect for the "-cover" binary
// that produced this counter data file. The GOARCH value may be
// empty in the case where the counter data file was produced
// from a merge in which more than one GOARCH value was present.
func (cdr *CounterDataReader) Goarch() string {
	return cdr.goarch
}

// FuncPayload encapsulates the counter data payload for a single
// function as read from a counter data file.
type FuncPayload struct {
	PkgIdx   uint32
	FuncIdx  uint32
	Counters []uint32
}

// NumSegments returns the number of execution segments in the file.
func (cdr *CounterDataReader) NumSegments() uint32 {
	return cdr.ftr.NumSegments
}

// BeginNextSegment sets up the reader to read the next segment,
// returning TRUE if we do have another segment to read, or FALSE
// if we're done with all the segments (also an error if
// something went wrong).
func (cdr *CounterDataReader) BeginNextSegment() (bool, error) {
	if cdr.segCount >= cdr.ftr.NumSegments {
		return false, nil
	}
	cdr.segCount++
	cdr.fcnCount = 0
	// Seek past footer from last segment.
	ftrSize := int64(unsafe.Sizeof(cdr.ftr))
	if _, err := cdr.mr.Seek(ftrSize, io.SeekCurrent); err != nil {
		return false, err
	}
	// Read preamble for this segment.
	if err := cdr.readSegmentPreamble(); err != nil {
		return false, err
	}
	return true, nil
}

// NumFunctionsInSegment returns the number of live functions
// in the currently selected segment.
func (cdr *CounterDataReader) NumFunctionsInSegment() uint32 {
	return uint32(cdr.shdr.FcnEntries)
}

const supportDeadFunctionsInCounterData = false

// NextFunc reads data for the next function in this current segment
// into "p", returning TRUE if the read was successful or FALSE
// if we've read all the functions already (also an error if
// something went wrong with the read or we hit a premature
// EOF).
func (cdr *CounterDataReader) NextFunc(p *FuncPayload) (bool, error) {
	if cdr.fcnCount >= uint32(cdr.shdr.FcnEntries) {
		return false, nil
	}
	cdr.fcnCount++
	var rdu32 func() (uint32, error)
	if cdr.hdr.CFlavor == coverage.CtrULeb128 {
		rdu32 = func() (uint32, error) {
			var shift uint
			var value uint64
			for {
				_, err := cdr.mr.Read(cdr.u8b)
				if err != nil {
					return 0, err
				}
				b := cdr.u8b[0]
				value |= (uint64(b&0x7F) << shift)
				if b&0x80 == 0 {
					break
				}
				shift += 7
			}
			return uint32(value), nil
		}
	} else if cdr.hdr.CFlavor == coverage.CtrRaw {
		if cdr.hdr.BigEndian {
			rdu32 = func() (uint32, error) {
				n, err := cdr.mr.Read(cdr.u32b)
				if err != nil {
					return 0, err
				}
				if n != 4 {
					return 0, io.EOF
				}
				return binary.BigEndian.Uint32(cdr.u32b), nil
			}
		} else {
			rdu32 = func() (uint32, error) {
				n, err := cdr.mr.Read(cdr.u32b)
				if err != nil {
					return 0, err
				}
				if n != 4 {
					return 0, io.EOF
				}
				return binary.LittleEndian.Uint32(cdr.u32b), nil
			}
		}
	} else {
		panic("internal error: unknown counter flavor")
	}

	// Alternative/experimental path: one way we could handling writing
	// out counter data would be to just memcpy the counter segment
	// out to a file, meaning that a region in the counter memory
	// corresponding to a dead (never-executed) function would just be
	// zeroes. The code path below handles this case.
	var nc uint32
	var err error
	if supportDeadFunctionsInCounterData {
		for {
			nc, err = rdu32()
			if err == io.EOF {
				return false, io.EOF
			} else if err != nil {
				break
			}
			if nc != 0 {
				break
			}
		}
	} else {
		nc, err = rdu32()
	}
	if err != nil {
		return false, err
	}

	// Read package and func indices.
	p.PkgIdx, err = rdu32()
	if err != nil {
		return false, err
	}
	p.FuncIdx, err = rdu32()
	if err != nil {
		return false, err
	}
	if cap(p.Counters) < 1024 {
		p.Counters = make([]uint32, 0, 1024)
	}
	p.Counters = p.Counters[:0]
	for i := uint32(0); i < nc; i++ {
		v, err := rdu32()
		if err != nil {
			return false, err
		}
		p.Counters = append(p.Counters, v)
	}
	return true, nil
}