forked from johnjohnsp1/capsule8
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tracepoint.go
645 lines (576 loc) · 16.1 KB
/
tracepoint.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
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
// Copyright 2017 Capsule8, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package perf
import (
"bufio"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"strings"
"unicode"
"github.com/capsule8/capsule8/pkg/sys"
"github.com/golang/glog"
)
const (
dtString int = iota
dtS8
dtS16
dtS32
dtS64
dtU8
dtU16
dtU32
dtU64
)
type TraceEventField struct {
FieldName string
TypeName string
Offset int
Size int
IsSigned bool
dataType int // data type constant from above
dataTypeSize int
dataLocSize int
arraySize int // 0 == [] array, >0 == # elements
}
func writeTraceCommand(name string, cmd string) error {
filename := filepath.Join(sys.TracingDir(), name)
file, err := os.OpenFile(filename, os.O_WRONLY|os.O_APPEND, 0)
if err != nil {
glog.Fatalf("Couldn't open %s WO+A: %s", filename, err)
}
defer file.Close()
_, err = file.Write([]byte(cmd))
return err
}
func AddKprobe(name string, address string, onReturn bool, output string) (string, error) {
var (
cmd string
definition string
)
// Normalize the output string so we can match it later
if len(output) > 0 &&
(strings.HasPrefix(output, " ") ||
strings.HasSuffix(output, " ") ||
strings.Index(output, " ") != -1) {
var result []string
for _, s := range strings.Split(output, " ") {
if len(s) > 0 {
result = append(result, s)
}
}
output = strings.Join(result, " ")
}
if onReturn {
cmd = "r"
} else {
cmd = "p"
}
if len(name) > 0 {
definition = fmt.Sprintf("%s:%s %s %s", cmd, name, address, output)
} else {
// Let the kernel generate a probe name for us
definition = fmt.Sprintf("%s %s %s", cmd, address, output)
}
glog.V(1).Infof("Adding kprobe: '%s'", definition)
err := writeTraceCommand("kprobe_events", definition)
if err != nil {
return "", err
}
//
// Get kprobe name possibly modified or generated by the kernel
// This isn't ideal: what if something else has added the same probe
// as us, and so we match that one, now assuming that it's ours?
//
var matches []string
filename := filepath.Join(sys.TracingDir(), "kprobe_events")
file, err := os.OpenFile(filename, os.O_RDONLY, 0)
defer file.Close()
cmd += ":"
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if !strings.HasPrefix(line, cmd) {
continue
}
tokens := strings.Split(line, " ")
if address != tokens[1] {
continue
}
fetchargs := strings.Join(tokens[2:], " ")
if output != fetchargs {
continue
}
if name == string(tokens[0][2:]) {
glog.V(1).Infof("Found exact match for kprobe name \"%s\"", name)
return name, nil
}
matches = append(matches, string(tokens[0][2:]))
}
// If our exact name wasn't found, return the last match of command,
// symbol name, and fetchargs
if len(matches) > 0 {
match := matches[len(matches)-1]
glog.V(1).Infof("Matched kprobe name \"%s\" to \"%s\"",
name, match)
return match, nil
}
// If we get here, we've got an error or we found no matching name.
// We have to assume that the kprobe has been added, but in either
// case, we don't have a reliable name to use to remove it.
err = scanner.Err()
if err != nil {
glog.Errorf("Scanner error while scanning kprobe_events: %v", err)
return "", err
}
glog.Errorf("Could not match added kprobe: %s", definition)
return name, nil
}
func RemoveKprobe(name string) error {
return writeTraceCommand("kprobe_events", fmt.Sprintf("-:%s", name))
}
func GetAvailableTraceEvents() ([]string, error) {
var events []string
filename := filepath.Join(sys.TracingDir(), "available_events")
file, err := os.OpenFile(filename, os.O_RDONLY, 0)
if err != nil {
return nil, err
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
events = append(events, scanner.Text())
}
err = scanner.Err()
if err != nil {
return nil, err
}
return events, nil
}
func GetTraceEventID(name string) (uint16, error) {
filename := filepath.Join(sys.TracingDir(), "events", name, "id")
file, err := os.OpenFile(filename, os.O_RDONLY, 0)
if err != nil {
glog.Infof("Couldn't open trace event %s: %v",
filename, err)
return 0, err
}
defer file.Close()
return ReadTraceEventID(name, file)
}
func ReadTraceEventID(name string, reader io.Reader) (uint16, error) {
//
// The tracepoint id is a uint16, so we can assume it'll be
// no longer than 5 characters plus a newline.
//
var buf [6]byte
_, err := reader.Read(buf[:])
if err != nil {
glog.Infof("Couldn't read trace event id: %v", err)
return 0, err
}
idStr := strings.TrimRight(string(buf[:]), "\n\x00")
id, err := strconv.Atoi(idStr)
if err != nil {
glog.Infof("Couldn't parse trace event id %s: %v",
string(buf[:]), err)
return 0, err
}
return uint16(id), nil
}
func (field *TraceEventField) setTypeFromSizeAndSign(isArray bool, arraySize int) (bool, error) {
if isArray {
if arraySize == -1 {
// If this is an array of unknown size, we have to
// skip it, because the field size is ambiguous
return true, nil
}
field.dataTypeSize = field.Size / arraySize
} else {
field.dataTypeSize = field.Size
}
switch field.dataTypeSize {
case 1:
if field.IsSigned {
field.dataType = dtS8
} else {
field.dataType = dtU8
}
case 2:
if field.IsSigned {
field.dataType = dtS16
} else {
field.dataType = dtU16
}
case 4:
if field.IsSigned {
field.dataType = dtS32
} else {
field.dataType = dtU32
}
case 8:
if field.IsSigned {
field.dataType = dtS64
} else {
field.dataType = dtU64
}
default:
// We can't figure out the type from the information given to
// us. We're here likely because of a typedef name we didn't
// recognize that's an array of integers or something. Skip it.
return true, nil
}
return false, nil
}
func (field *TraceEventField) parseTypeName(s string, isArray bool, arraySize int) (bool, error) {
if strings.HasPrefix(s, "const ") {
s = s[6:]
}
switch s {
// Standard C types
case "bool":
// "bool" is usually 1 byte, but it could be defined otherwise?
return field.setTypeFromSizeAndSign(isArray, arraySize)
// These types are going to be consistent in a 64-bit kernel, and in a
// 32-bit kernel as well, except for "long".
case "int", "signed int", "signed", "unsigned int", "unsigned", "uint":
// The kernel is a bit unreliable about reporting "int" with
// different sizes and signs, so try to use size/sign whenever
// possible. If it's not possible, assume 32-bit int
skip, err := field.setTypeFromSizeAndSign(isArray, arraySize)
if skip && err == nil {
if field.IsSigned {
field.dataType = dtS32
} else {
field.dataType = dtU32
}
field.dataTypeSize = 4
return false, nil
}
return skip, err
case "char", "signed char", "unsigned char":
if field.IsSigned {
field.dataType = dtS8
} else {
field.dataType = dtU8
}
field.dataTypeSize = 1
return false, nil
case "short", "signed short", "unsigned short":
if field.IsSigned {
field.dataType = dtS16
} else {
field.dataType = dtU16
}
field.dataTypeSize = 2
return false, nil
case "long", "signed long", "unsigned long":
skip, err := field.setTypeFromSizeAndSign(isArray, arraySize)
if skip && err == nil {
// Assume a 64-bit kernel
if field.IsSigned {
field.dataType = dtS64
} else {
field.dataType = dtU64
}
field.dataTypeSize = 8
return false, nil
}
return skip, err
case "long long", "signed long long", "unsigned long long":
if field.IsSigned {
field.dataType = dtS64
} else {
field.dataType = dtU64
}
field.dataTypeSize = 8
return false, nil
// Fixed-size types
case "s8", "__s8", "int8_t", "__int8_t":
field.dataType = dtS8
field.dataTypeSize = 1
return false, nil
case "u8", "__u8", "uint8_t", "__uint8_t":
field.dataType = dtS16
field.dataTypeSize = 1
return false, nil
case "s16", "__s16", "int16_t", "__int16_t":
field.dataType = dtS16
field.dataTypeSize = 2
return false, nil
case "u16", "__u16", "uint16_t", "__uint16_t":
field.dataType = dtU16
field.dataTypeSize = 2
return false, nil
case "s32", "__s32", "int32_t", "__int32_t":
field.dataType = dtS32
field.dataTypeSize = 4
return false, nil
case "u32", "__u32", "uint32_t", "__uint32_t":
field.dataType = dtU32
field.dataTypeSize = 4
return false, nil
case "s64", "__s64", "int64_t", "__int64_t":
field.dataType = dtS64
field.dataTypeSize = 8
return false, nil
case "u64", "__u64", "uint64_t", "__uint64_t":
field.dataType = dtU64
field.dataTypeSize = 8
return false, nil
/*
// Known kernel typedefs in 4.10
case "clockid_t", "pid_t", "xfs_extnum_t":
field.dataType = dtS32
field.dataTypeSize = 4
case "dev_t", "gfp_t", "gid_t", "isolate_mode_t", "tid_t", "uid_t",
"ext4_lblk_t",
"xfs_agblock_t", "xfs_agino_t", "xfs_agnumber_t", "xfs_btnum_t",
"xfs_dahash_t", "xfs_exntst_t", "xfs_extlen_t", "xfs_lookup_t",
"xfs_nlink_t", "xlog_tid_t":
field.dataType = dtU32
field.dataTypeSize = 4
case "loff_t", "xfs_daddr_t", "xfs_fsize_t", "xfs_lsn_t", "xfs_off_t":
field.dataType = dtS64
field.dataTypeSize = 8
case "aio_context_t", "blkcnt_t", "cap_user_data_t",
"cap_user_header_t", "cputime_t", "dma_addr_t", "fl_owner_t",
"gfn_t", "gpa_t", "gva_t", "ino_t", "key_serial_t", "key_t",
"mqd_t", "off_t", "pgdval_t", "phys_addr_t", "pmdval_t",
"pteval_t", "pudval_t", "qid_t", "resource_size_t", "sector_t",
"timer_t", "umode_t",
"ext4_fsblk_t",
"xfs_ino_t", "xfs_fileoff_t", "xfs_fsblock_t", "xfs_filblks_t":
field.dataType = dtU64
field.dataTypeSize = 8
case "xen_mc_callback_fn_t":
// This is presumably a pointer type
return true, nil
case "uuid_be", "uuid_le":
field.dataType = dtU8
field.dataTypeSize = 1
field.arraySize = 16
return false, nil
*/
default:
// Judging by Linux kernel conventions, it would appear that
// any type name ending in _t is an integer type. Try to figure
// it out from other information the kernel has given us. Note
// that pointer types also fall into this category; however, we
// have no way to know whether the value is to be treated as an
// integer or a pointer unless we try to parse the printf fmt
// string that's also included in the format description (no!)
if strings.HasSuffix(s, "_t") {
return field.setTypeFromSizeAndSign(isArray, arraySize)
}
if len(s) > 0 && s[len(s)-1] == '*' {
return field.setTypeFromSizeAndSign(isArray, arraySize)
}
if strings.HasPrefix(s, "struct ") {
// Skip structs
return true, nil
}
if strings.HasPrefix(s, "union ") {
// Skip unions
return true, nil
}
if strings.HasPrefix(s, "enum ") {
return field.setTypeFromSizeAndSign(isArray, arraySize)
}
// We don't recognize the type name. It's probably a typedef
// for an integer or array of integers or something. Try to
// figure it out from the size and sign information, but the
// odds are not in our favor if we're here.
return field.setTypeFromSizeAndSign(isArray, arraySize)
}
}
var linuxArraySizeSanityWarning bool = false
func (field *TraceEventField) parseTypeAndName(s string) (bool, error) {
if strings.HasPrefix(s, "__data_loc") {
s = s[11:]
field.dataLocSize = field.Size
// We have to use the type name here. The size information will
// always indicate how big the data_loc information is, which
// is normally 4 bytes (offset uint16, length uint16)
x := strings.LastIndexFunc(s, unicode.IsSpace)
field.FieldName = string(strings.TrimSpace(s[x+1:]))
s = s[:x]
if !strings.HasSuffix(s, "[]") {
return true, errors.New("Expected [] suffix on __data_loc type")
}
s = s[:len(s)-2]
field.TypeName = string(s)
if s == "char" {
field.dataType = dtString
field.dataTypeSize = 1
} else {
skip, err := field.parseTypeName(s, true, -1)
if err != nil {
return true, err
}
if skip {
return true, nil
}
}
return false, nil
}
arraySize := -1
isArray := false
x := strings.IndexRune(s, '[')
if x != -1 {
if s[x+1] == ']' {
return true, errors.New("Unexpected __data_loc without __data_loc prefix")
}
// Try to parse out the array size. Most of the time this will
// be possible, but there are some cases where macros or consts
// are used, so it's not possible.
value, err := strconv.Atoi(s[x+1 : len(s)-1])
if err == nil {
arraySize = value
}
s = s[:x]
isArray = true
}
x = strings.LastIndexFunc(s, unicode.IsSpace)
field.TypeName = string(s[:x])
field.FieldName = string(strings.TrimSpace(s[x+1:]))
skip, err := field.parseTypeName(field.TypeName, isArray, arraySize)
if err != nil {
return true, err
}
if skip {
return true, nil
}
if isArray {
if arraySize >= 0 {
field.arraySize = arraySize
// Sanity check what we've determined. Various versions
// of the Linux kernel misreport size information.
if arraySize != field.Size/field.dataTypeSize {
if !linuxArraySizeSanityWarning {
linuxArraySizeSanityWarning = true
glog.Warning("Linux kernel tracepoint format size information is incorrect; compensating")
}
skip, err = field.parseTypeName(field.TypeName, true, -1)
if err != nil {
return true, err
}
if skip {
return true, nil
}
field.arraySize = field.Size / field.dataTypeSize
}
} else {
field.arraySize = field.Size / field.dataTypeSize
}
}
return false, nil
}
func parseTraceEventField(line string) (*TraceEventField, error) {
var err error
var fieldString string
field := &TraceEventField{}
fields := strings.Split(strings.TrimSpace(line), ";")
for i := 0; i < len(fields); i++ {
if fields[i] == "" {
continue
}
parts := strings.Split(fields[i], ":")
if len(parts) != 2 {
return nil, errors.New("malformed format field")
}
switch strings.TrimSpace(parts[0]) {
case "field":
fieldString = parts[1]
case "offset":
field.Offset, err = strconv.Atoi(parts[1])
case "size":
field.Size, err = strconv.Atoi(parts[1])
case "signed":
field.IsSigned, err = strconv.ParseBool(parts[1])
}
if err != nil {
return nil, err
}
}
skip, err := field.parseTypeAndName(fieldString)
if err != nil {
return nil, err
}
if skip {
// If a field is marked as skip, treat it as an array of bytes
field.dataTypeSize = 1
field.arraySize = field.Size
if field.IsSigned {
field.dataType = dtS8
} else {
field.dataType = dtU8
}
}
return field, nil
}
func GetTraceEventFormat(name string) (uint16, map[string]TraceEventField, error) {
filename := filepath.Join(sys.TracingDir(), "events", name, "format")
file, err := os.OpenFile(filename, os.O_RDONLY, 0)
if err != nil {
return 0, nil, err
}
defer file.Close()
return ReadTraceEventFormat(name, file)
}
func ReadTraceEventFormat(name string, reader io.Reader) (uint16, map[string]TraceEventField, error) {
var eventID uint16
inFormat := false
fields := make(map[string]TraceEventField)
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
rawLine := scanner.Text()
line := strings.TrimSpace(rawLine)
if line == "" {
continue
}
if inFormat {
if !unicode.IsSpace(rune(rawLine[0])) {
inFormat = false
continue
}
field, err := parseTraceEventField(line)
if err != nil {
glog.Infof("Couldn't parse trace event format: %v", err)
return 0, nil, err
}
if field != nil {
fields[field.FieldName] = *field
}
} else if strings.HasPrefix(line, "format:") {
inFormat = true
} else if strings.HasPrefix(line, "ID:") {
value := strings.TrimSpace(line[3:])
parsedValue, err := strconv.Atoi(value)
if err != nil {
glog.Infof("Couldn't parse trace event ID: %v", err)
return 0, nil, err
}
eventID = uint16(parsedValue)
}
}
err := scanner.Err()
if err != nil {
return 0, nil, err
}
return eventID, fields, err
}