forked from Arachnid/evmdis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
expressions.go
314 lines (277 loc) · 8.38 KB
/
expressions.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
package evmdis
import (
"fmt"
"math/big"
"strings"
)
type Expression interface {
String() string
Eval() *big.Int
}
var opcodeFormatStrings = map[OpCode]string{
ADD: "%v + %v",
MUL: "%v * %v",
SUB: "%v - %v",
DIV: "%v / %v",
MOD: "%v %% %v",
EXP: "%v ** %v",
NOT: "~%v",
LT: "%v < %v",
GT: "%v > %v",
EQ: "%v == %v",
ISZERO: "!%v",
AND: "%v & %v",
OR: "%v | %v",
XOR: "%v ^ %v",
}
var operatorPrecedences = map[OpCode]int{
NOT: 0,
ISZERO: 0,
EXP: 1,
MUL: 2,
DIV: 2,
MOD: 2,
ADD: 3,
SUB: 3,
AND: 4,
XOR: 5,
OR: 6,
LT: 7,
GT: 7,
EQ: 7,
}
type InstructionExpression struct {
Inst *Instruction
Arguments []Expression
}
func (self *InstructionExpression) Eval() *big.Int {
return self.Inst.Arg
}
func (self *InstructionExpression) String() string {
if self.Inst.Op.IsPush() {
// Print push instructions as just their value
return fmt.Sprintf("0x%X", self.Inst.Arg)
} else if format, ok := opcodeFormatStrings[self.Inst.Op]; ok {
args := make([]interface{}, 0, len(self.Arguments))
for _, arg := range self.Arguments {
if ie, ok := arg.(*InstructionExpression); ok && operatorPrecedences[ie.Inst.Op] > operatorPrecedences[self.Inst.Op] {
args = append(args, fmt.Sprintf("(%s)", arg.String()))
} else {
args = append(args, arg.String())
}
}
return fmt.Sprintf(format, args...)
} else {
// Format the opcode as a function call
args := make([]string, 0, len(self.Arguments))
for _, arg := range self.Arguments {
args = append(args, arg.String())
}
return fmt.Sprintf("%s(%s)", self.Inst.Op, strings.Join(args, ", "))
}
}
type PopExpression struct{
Inst *InstructionPointer
}
func (self *PopExpression) String() string {
if self.Inst != nil {
return "POP("+self.Inst.String()+")"
} else {
return "POP()"
}
}
func (self *PopExpression) Eval() *big.Int {
return nil
}
type SwapExpression struct {
count int
}
func (self *SwapExpression) String() string {
return fmt.Sprintf("SWAP%d", self.count)
}
func (self *SwapExpression) Eval() *big.Int {
return nil
}
type DupExpression struct {
count int
}
func (self *DupExpression) Eval() *big.Int {
return nil
}
func (self *DupExpression) String() string {
return fmt.Sprintf("DUP%d", self.count)
}
type JumpLabel struct {
id int
refCount int
}
func (self *JumpLabel) Eval() *big.Int {
return nil
}
func (self *JumpLabel) String() string {
return fmt.Sprintf(":label%d", self.id)
}
func CreateLabels(prog *Program) {
// Create initial labels, one per block
for _, block := range prog.Blocks {
label := &JumpLabel{}
block.Annotations.Set(&label)
}
// Find all uses of labels and create references
for _, block := range prog.Blocks {
nextInstruction:
for i, inst := range block.Instructions {
if !inst.Op.IsPush() {
continue
}
// Skip any pushes that aren't found in the jump table
targetBlock := prog.JumpDestinations[int(inst.Arg.Int64())]
if targetBlock == nil {
continue
}
// Skip any pushes that aren't consumed exclusively as jump targets
var reaches ReachesDefinition
inst.Annotations.Get(&reaches)
for _, pointer := range reaches {
targetInst := pointer.Get()
if targetInst.Op == JUMPI {
// Check if it's the second argument
var reaching ReachingDefinition
targetInst.Annotations.Get(&reaching)
if !reaching[0][InstructionPointer{block, i}] {
continue nextInstruction
}
} else if targetInst.Op != JUMP {
continue nextInstruction
}
}
// Fetch the label and add a reference as an expression
var label *JumpLabel
targetBlock.Annotations.Get(&label)
label.refCount += 1
expression := Expression(label)
inst.Annotations.Set(&expression)
}
}
// Assign label numbers and delete unused labels
count := 0
for _, block := range prog.Blocks {
var label *JumpLabel
block.Annotations.Get(&label)
if label.refCount == 0 {
block.Annotations.Pop(&label)
} else {
label.id = count
count += 1
}
}
}
func BuildExpressions(prog *Program) error {
for _, block := range prog.Blocks {
var reaching ReachingDefinition
block.Annotations.Get(&reaching)
// If reaching is nil, this block is unreachable; skip processing it
if reaching == nil {
continue
}
// Lifted is a set of subexpressions that can be incorporated into larger expressions;
// they have been 'lifted' out of the stack.
lifted := make(InstructionPointerSet)
for i := 0; i < len(block.Instructions); i++ {
inst := &block.Instructions[i]
// Find all the definitions that reach each argument of this op
var reaching ReachingDefinition
inst.Annotations.Get(&reaching)
if len(reaching) != inst.Op.StackReads() {
return fmt.Errorf("Processing %v@0x%X: expected number of stack reads (%v) to equal reaching definition length (%v)", inst, block.OffsetOf(inst), inst.Op.StackReads(), len(reaching))
}
if inst.Op.IsSwap() {
// Try and reduce the size of swap operations to account for lifted arguments
swapFrom, swapTo := reaching[0], reaching[len(reaching)-1]
leftLifted := len(swapFrom) == 1 && lifted[*swapFrom.First()]
rightLifted := len(swapTo) == 1 && lifted[*swapTo.First()]
if leftLifted {
delete(lifted, *swapFrom.First())
}
if rightLifted {
delete(lifted, *swapTo.First())
}
count := 0
if len(reaching) > 2 || (!leftLifted && !rightLifted) {
if !leftLifted || !rightLifted {
// Count number of non-lifted elements between the operands
for i := 1; i < len(reaching)-1; i++ {
if len(reaching[i]) != 1 || !lifted[*reaching[i].First()] {
count += 1
}
}
}
}
var expression Expression = &SwapExpression{count + 1}
inst.Annotations.Set(&expression)
} else if inst.Op.IsDup() {
// Try and reduce the size of dup operations to account for lifted arguments
dupOf := reaching[len(reaching)-1]
if len(dupOf) == 1 && lifted[*dupOf.First()] {
// 'unlift' any operations that are consumed by DUPs
delete(lifted, *dupOf.First())
}
// Count number of non-lifted elements between the operands
count := 0
for i := 0; i < len(reaching)-1; i++ {
if len(reaching[i]) != 1 || !lifted[*reaching[i].First()] {
count += 1
}
}
var expression Expression = &DupExpression{count + 1}
inst.Annotations.Set(&expression)
} else if inst.Op == POP && (len(reaching[0]) > 1 || !lifted[*reaching[0].First()]) {
// Represent POPs explicitly if the argument is consumed in more than one place
var expression Expression = &PopExpression{}
inst.Annotations.Set(&expression)
} else {
var expression Expression
inst.Annotations.Get(&expression)
// Don't recalculate expressions found by previous passes
if expression == nil {
args := make([]Expression, 0, inst.Op.StackReads())
// Assemble a subexpression for each argument
for _, pointers := range reaching {
if len(pointers) > 1 || !lifted[*pointers.First()] {
// If there's more than one definition reaching the argument
// or it's not in our set of expression fragments, represent it
// as a stack pop.
var expression = &PopExpression{}
if len(pointers) == 1 {
expression.Inst = pointers.First()
}
var converted = Expression(expression)
args = append(args, converted)
} else {
// Inline this argument's expression
sourcePointer := pointers.First()
var sourceExpression Expression
sourcePointer.Get().Annotations.Pop(&sourceExpression)
args = append(args, sourceExpression)
delete(lifted, *sourcePointer)
}
}
expression = &InstructionExpression{inst, args}
inst.Annotations.Set(&expression)
}
var reaches ReachesDefinition
inst.Annotations.Get(&reaches)
if len(reaches) == 1 && reaches[0].OriginBlock == block && !inst.Op.HasSideEffects() {
// 'Lift' this definition out of the stack, since we know it'll be consumed
// later in this block (and only there)
ptr := InstructionPointer{block, i}
lifted[ptr] = true
}
}
}
if len(lifted) != 0 {
return fmt.Errorf("Expected all lifted arguments to be consumed by end of block: %v", lifted)
}
}
return nil
}