-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathprogram.go
322 lines (262 loc) · 7.2 KB
/
program.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
package skbtrace
import (
"bufio"
"bytes"
"fmt"
"io"
"strings"
"time"
)
const (
programIndent = " "
)
type AggrFunc string
const (
AFCount AggrFunc = "count"
AFSum AggrFunc = "sum"
AFAvg AggrFunc = "avg"
AFMin AggrFunc = "min"
AFMax AggrFunc = "max"
AFHist AggrFunc = "hist"
)
var AggrFuncList = []AggrFunc{AFCount, AFSum, AFAvg, AFMin, AFMax, AFHist}
type Statement struct {
s string
b *Block
}
type Expression string
// Empty expression used as default value in conjuction with error
var NilExpr = Expr("")
type BlockContext map[string]struct{}
// Block is an internal representation for BPFTrace block which stores list of semicolon
// separated statements.
//
// Probe block contains list of BPFTrace statements (and other blocks) to be executed by probe
// Context is a dictionary which maps objects to local variables produced by casts
// or predefined variables passed into probe
type Block struct {
Preamble string
Statements []Statement
prog *Program
probe *Probe
context BlockContext
}
type Program struct {
HeaderFiles map[string]struct{}
StructDefs map[string]*StructDef
Blocks []*Block
}
func NewProgram() *Program {
return &Program{
HeaderFiles: make(map[string]struct{}),
StructDefs: make(map[string]*StructDef),
}
}
func (prog *Program) render(w io.Writer, initialIndent bool) error {
buf := bufio.NewWriter(w)
indent := ""
if initialIndent {
indent = programIndent
}
writeSep := func() {}
writeSep1 := func() { buf.WriteString("\n") }
writeSep2 := func() { buf.WriteString("\n\n") }
for headerFile := range prog.HeaderFiles {
buf.WriteString(indent)
buf.WriteString(fmt.Sprintf("#include <%s>\n", headerFile))
writeSep = writeSep1
}
for _, structDef := range prog.StructDefs {
writeSep()
structDef.render(buf, indent)
writeSep = writeSep2
}
for _, block := range prog.Blocks {
writeSep()
block.render(buf, indent)
writeSep = writeSep2
}
return buf.Flush()
}
func (structDef *StructDef) render(buf *bufio.Writer, indent string) {
buf.WriteString(indent)
buf.WriteString(fmt.Sprintf("struct %s {\n", structDef.TypeName))
lineIndent := indent + programIndent
for _, line := range structDef.Text {
if len(line) == 0 {
continue
}
buf.WriteString(lineIndent)
buf.WriteString(line)
buf.WriteByte('\n')
}
buf.WriteString(indent)
buf.WriteByte('}')
}
func (block *Block) render(buf *bufio.Writer, indent string) {
buf.WriteString(indent)
if len(block.Preamble) > 0 {
buf.WriteString(block.Preamble)
buf.WriteByte(' ')
}
buf.WriteString("{\n")
blockIndent := indent + programIndent
for _, stmt := range block.Statements {
if stmt.b != nil {
stmt.b.render(buf, blockIndent)
buf.WriteByte('\n')
continue
}
lines := []string{stmt.s}
if strings.IndexByte(stmt.s, '\n') > 0 {
lines = strings.Split(stmt.s, "\n")
}
for i, line := range lines {
if i > 0 {
buf.WriteByte('\n')
}
buf.WriteString(blockIndent)
buf.WriteString(line)
}
buf.WriteString(";\n")
}
buf.WriteString(indent)
buf.WriteByte('}')
}
func (prog *Program) AddProbeBlock(probeDef string, probe *Probe) *Block {
block := &Block{
Preamble: probeDef,
probe: probe,
prog: prog,
context: make(BlockContext),
}
prog.Blocks = append(prog.Blocks, block)
return block
}
func (prog *Program) AddIntervalBlock(d time.Duration) *Block {
if d.Seconds() > 0 {
return prog.AddProbeBlock(fmt.Sprintf("interval:s:%d", int(d.Seconds())), nil)
}
return prog.AddProbeBlock(fmt.Sprintf("interval:ms:%d", int(d.Milliseconds())), nil)
}
func (prog *Program) AddIntervalOrEndBlock(d time.Duration) *Block {
block := prog.AddIntervalBlock(d)
block.Preamble = fmt.Sprintf("%s, END", block.Preamble)
return block
}
func (prog *Program) addCommonBlock(opt *CommonOptions) {
timeoutBlock := prog.AddIntervalBlock(opt.Timeout)
timeoutBlock.Add(Stmt("exit()"))
}
func (prog *Program) addAggrDumpBlock(interval time.Duration, truncate int) {
printStmt := Stmt("print(@)")
if truncate > 0 {
printStmt = Stmtf("print(@, %d)", truncate)
}
block := prog.AddIntervalBlock(interval)
block.Add(
Stmt("time()"),
printStmt,
Stmt("clear(@)"))
}
func (prog *Program) addAggrCleanupBlock(aggrs ...string) {
// Cleanup start_time map in case it will leak
block := prog.AddIntervalOrEndBlock(aggrCleanupInterval)
for _, aggr := range aggrs {
block.Addf("clear(%s)", aggr)
}
}
// Add adds single-string statements to the block
func (block *Block) Add(stmts ...Statement) {
block.Statements = append(block.Statements, stmts...)
}
// Addf formats a single-string statement and adds it to the list of block statements
func (block *Block) Addf(format string, args ...interface{}) {
block.Statements = append(block.Statements, Stmtf(format, args...))
}
// AddBlock adds block statement
func (block *Block) AddBlock(preamble string) *Block {
block2 := &Block{
Preamble: preamble,
probe: block.probe,
prog: block.prog,
context: make(BlockContext),
}
for k, v := range block.context {
block2.context[k] = v
}
block.Statements = append(block.Statements, Statement{b: block2})
return block2
}
// AddIfBlock adds block statement with if preamble containing conditions
func (block *Block) AddIfBlock(conds ...Expression) *Block {
return block.AddBlock(fmt.Sprintf("if (%s)", ExprJoinOp(conds, "&&")))
}
// Finds a block which already have object fetched, converted and sanity filters
// applied (minor deduplication of casts)
func (block *Block) findBlockWithObject(objName string) *Block {
if _, ok := block.context[objName]; ok {
return block
}
for _, stmt := range block.Statements {
if stmt.b == nil {
continue
}
b2 := stmt.b.findBlockWithObject(objName)
if b2 != nil {
return b2
}
}
return nil
}
// Stmt creates a new statement that consists from single string
func Stmt(s string) Statement {
return Statement{s: s}
}
// Stmtf creates a formats a single-string statement using a format string and its argument
func Stmtf(format string, args ...interface{}) Statement {
return Statement{s: fmt.Sprintf(format, args...)}
}
// Wraps block into statement
func stmtBlock(block *Block) Statement {
return Statement{b: block}
}
// Expr converts a string to expression
func Expr(e string) Expression {
return Expression(e)
}
// Exprf formats an expression
func Exprf(format string, args ...interface{}) Expression {
return Expression(fmt.Sprintf(format, args...))
}
// ExprField formats an expression for accessing the field
func ExprField(obj, field string) Expression {
// Some fields do not have objects (like raw arguments with values)
if len(obj) == 0 {
return Expr(field)
}
if len(field) == 0 {
return Expr(obj)
}
return Exprf("%s->%s", obj, field)
}
// ExprJoin joins expressions as list separated by comma
func ExprJoin(exprs []Expression) Expression {
return exprJoin(exprs, "", ",", " ")
}
// ExprJoinOp joins expressions using operator op
func ExprJoinOp(exprs []Expression, op string) Expression {
return exprJoin(exprs, " ", op, " ")
}
func exprJoin(exprs []Expression, pre, sep, post string) Expression {
buf := bytes.NewBuffer(nil)
for i, expr := range exprs {
if i > 0 {
buf.WriteString(pre)
buf.WriteString(sep)
buf.WriteString(post)
}
buf.WriteString(string(expr))
}
return Expr(buf.String())
}