This repository has been archived by the owner on Dec 1, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 110
/
assembly.go
412 lines (320 loc) · 12.1 KB
/
assembly.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
/*
* Minio Cloud Storage, (C) 2017 Minio, 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 main
import (
"fmt"
"regexp"
"strconv"
"strings"
"unicode"
)
const originalStackPointer = 8
var registers = [...]string{"DI", "SI", "DX", "CX", "R8", "R9"}
var registersAdditional = [...]string{"R10", "R11", "R12", "R13", "R14", "R15", "AX", "BX"}
var regexpCall = regexp.MustCompile(`^\s*call\s*`)
var regexpPushInstr = regexp.MustCompile(`^\s*push\s*`)
var regexpPopInstr = regexp.MustCompile(`^\s*pop\s*`)
var regexpLabel = regexp.MustCompile(`^(\.?LBB.*?:)`)
var regexpJumpTableRef = regexp.MustCompile(`\[rip \+ (\.?LJTI[_0-9]*)\]\s*$`)
var regexpJumpWithLabel = regexp.MustCompile(`^(\s*j\w*)\s*(\.?LBB.*)`)
var regexpRbpLoadHigher = regexp.MustCompile(`\[rbp \+ ([0-9]+)\]`)
var regexpRbpLoadLower = regexp.MustCompile(`\[rbp - ([0-9]+)\]`)
var regexpStripComments = regexp.MustCompile(`\s*#?#\s.*$`)
// Write the prologue for the subroutine
func writeGoasmPrologue(sub Subroutine, stack Stack, arguments, returnValues []string) []string {
//if sub.name == "SimdSse2MedianFilterRhomb3x3" {
// fmt.Println("sub.name", sub.name)
// fmt.Println("sub.epilogue", sub.epilogue)
// fmt.Println("arguments", arguments)
// fmt.Println("returnValues", returnValues)
// fmt.Println("table.Name", sub.table.Name)
//}
var result []string
// Output definition of subroutine
result = append(result, fmt.Sprintf("TEXT ·_%s(SB), $%d-%d", sub.name, stack.GolangLocalStackFrameSize(),
getTotalSizeOfArgumentsAndReturnValues(0, len(arguments)-1, returnValues)), "")
// Load Golang arguments into registers
for iarg, arg := range arguments {
if iarg < len(registers) {
// Load initial arguments (up to 6) in corresponding registers
result = append(result, fmt.Sprintf(" MOVQ %s+%d(FP), %s", arg, iarg*8, registers[iarg]))
} else if iarg-len(registers) < len(registersAdditional) {
// Load following arguments into additional registers
result = append(result, fmt.Sprintf(" MOVQ %s+%d(FP), %s", arg, iarg*8, registersAdditional[iarg-len(registers)]))
} else {
panic("Trying to pass in too many arguments")
}
}
// Setup the stack pointer for the C code
if sub.epilogue.AlignedStack {
// Align stack pointer to next multiple of alignment space
result = append(result, fmt.Sprintf(" MOVQ SP, BP"))
result = append(result, fmt.Sprintf(" ADDQ $%d, SP", stack.StackPointerOffsetForC() /*sub.epilogue.AlignValue*/))
result = append(result, fmt.Sprintf(" ANDQ $-%d, SP", sub.epilogue.AlignValue))
// Save original stack pointer right below newly aligned stack pointer
result = append(result, fmt.Sprintf(" MOVQ BP, %d(SP)", stack.OffsetForSavedSP())) // Save original SP
} else if stack.StackPointerOffsetForC() != 0 { // sub.epilogue.getStackSpace(len(arguments)) != 0 {
// Create stack space as needed
result = append(result, fmt.Sprintf(" ADDQ $%d, SP", stack.StackPointerOffsetForC() /*sub.epilogue.getFreeSpaceAtBottom())*/))
}
// Save Golang arguments beyond 6 onto stack
for iarg := len(arguments) - 1; iarg-len(registers) >= 0; iarg-- {
result = append(result, fmt.Sprintf(" MOVQ %s, %d(SP)", registersAdditional[iarg-len(registers)], stack.OffsetForGoArg(iarg)))
}
// Setup base pointer for loading constants
if sub.table.isPresent() {
result = append(result, fmt.Sprintf(" LEAQ %s<>(SB), BP", sub.table.Name))
}
return append(result, ``)
}
func writeGoasmBody(sub Subroutine, stack Stack, stackArgs StackArgs, arguments, returnValues []string) ([]string, error) {
var result []string
for iline, line := range sub.body {
// If part of epilogue
if iline >= sub.epilogue.Start && iline < sub.epilogue.End {
// Instead of last line, output go assembly epilogue
if iline == sub.epilogue.End-1 {
result = append(result, writeGoasmEpilogue(sub, stack, arguments, returnValues)...)
}
continue
}
// Remove ## comments
var skipLine bool
line, skipLine = stripComments(line)
if skipLine {
continue
}
// Skip lines with aligns
if strings.Contains(line, ".align") || strings.Contains(line, ".p2align") {
continue
}
line, _ = fixLabels(line)
line, _, _ = upperCaseJumps(line)
line, _ = upperCaseCalls(line)
fields := strings.Fields(line)
// Test for any non-jmp instruction (lower case mnemonic)
if len(fields) > 0 && !strings.Contains(fields[0], ":") && isLower(fields[0]) {
// prepend line with comment for subsequent asm2plan9s assembly
line = " // " + strings.TrimSpace(line)
}
line = removeUndefined(line, "ptr")
line = removeUndefined(line, "# NOREX")
// https://github.com/vertis/objconv/blob/master/src/disasm2.cpp
line = replaceUndefined(line, "xmmword", "oword")
line = replaceUndefined(line, "ymmword", "yword")
line = fixShiftInstructions(line)
line = fixMovabsInstructions(line)
if sub.table.isPresent() {
line = fixPicLabels(line, sub.table)
}
line = fixRbpPlusLoad(line, stackArgs, stack)
detectRbpMinusMemoryAccess(line)
detectJumpTable(line)
detectPushInstruction(line)
detectPopInstruction(line)
result = append(result, line)
}
return result, nil
}
// Write the epilogue for the subroutine
func writeGoasmEpilogue(sub Subroutine, stack Stack, arguments, returnValues []string) []string {
var result []string
// Restore the stack pointer
if sub.epilogue.AlignedStack {
// For an aligned stack, restore the stack pointer from the stack itself
result = append(result, fmt.Sprintf(" MOVQ %d(SP), SP", stack.OffsetForSavedSP()))
} else if stack.StackPointerOffsetForC() != 0 {
// For an unaligned stack, reverse addition in order restore the stack pointer
result = append(result, fmt.Sprintf(" SUBQ $%d, SP", stack.StackPointerOffsetForC()))
}
// Clear upper half of YMM register, if so done in the original code
if sub.epilogue.VZeroUpper {
result = append(result, " VZEROUPPER")
}
if len(returnValues) == 1 {
// Store return value of subroutine
result = append(result, fmt.Sprintf(" MOVQ AX, %s+%d(FP)", returnValues[0],
getTotalSizeOfArgumentsAndReturnValues(0, len(arguments)-1, returnValues)-8))
} else if len(returnValues) > 1 {
panic(fmt.Sprintf("Fix multiple return values: %s", returnValues))
}
// Finally, return out of the subroutine
result = append(result, " RET")
return result
}
func scanBodyForCalls(sub Subroutine) uint {
stackSize := uint(0)
for _, line := range sub.body {
_, size := upperCaseCalls(line)
if stackSize < size {
stackSize = size
}
}
return stackSize
}
// Strip comments from assembly lines
func stripComments(line string) (result string, skipLine bool) {
if match := regexpStripComments.FindStringSubmatch(line); len(match) > 0 {
line = line[:len(line)-len(match[0])]
if line == "" {
return "", true
}
}
return line, false
}
// Remove leading `.` from labels
func fixLabels(line string) (string, string) {
label := ""
if match := regexpLabel.FindStringSubmatch(line); len(match) > 0 {
label = strings.Replace(match[1], ".", "", 1)
line = label
label = strings.Replace(label, ":", "", 1)
}
return line, label
}
// Make jmps uppercase
func upperCaseJumps(line string) (string, string, string) {
instruction, label := "", ""
if match := regexpJumpWithLabel.FindStringSubmatch(line); len(match) > 1 {
// make jmp statement uppercase
instruction = strings.ToUpper(match[1])
label = strings.Replace(match[2], ".", "", 1)
line = instruction + " " + label
}
return line, strings.TrimSpace(instruction), label
}
// Make calls uppercase
func upperCaseCalls(line string) (string, uint) {
// TODO: Make determination of required stack size more sophisticated
stackSize := uint(0)
// Make 'call' instructions uppercase
if match := regexpCall.FindStringSubmatch(line); len(match) > 0 {
parts := strings.SplitN(line, `call`, 2)
fname := strings.TrimSpace(parts[1])
// replace c stdlib functions with equivalents
if fname == "_memcpy" || fname == "memcpy@PLT" { // (Procedure Linkage Table)
parts[1] = "clib·_memcpy(SB)"
stackSize = 64
} else if fname == "_memset" || fname == "memset@PLT" { // (Procedure Linkage Table)
parts[1] = "clib·_memset(SB)"
stackSize = 64
} else if fname == "_floor" || fname == "floor@PLT" { // (Procedure Linkage Table)
parts[1] = "clib·_floor(SB)"
stackSize = 64
} else if fname == "___bzero" {
parts[1] = "clib·_bzero(SB)"
stackSize = 64
}
line = parts[0] + "CALL " + strings.TrimSpace(parts[1])
}
return line, stackSize
}
func isLower(str string) bool {
for _, r := range str {
return unicode.IsLower(r)
}
return false
}
func removeUndefined(line, undef string) string {
if parts := strings.SplitN(line, undef, 2); len(parts) > 1 {
line = parts[0] + strings.TrimSpace(parts[1])
}
return line
}
func replaceUndefined(line, undef, repl string) string {
if parts := strings.SplitN(line, undef, 2); len(parts) > 1 {
line = parts[0] + repl + parts[1]
}
return line
}
// fix Position Independent Labels
func fixPicLabels(line string, table Table) string {
if strings.Contains(line, "[rip + ") {
parts := strings.SplitN(line, "[rip + ", 2)
label := parts[1][:len(parts[1])-1]
i := -1
var l Label
for i, l = range table.Labels {
if l.Name == label {
line = parts[0] + fmt.Sprintf("%d[rbp] /* [rip + %s */", l.Offset, parts[1])
break
}
}
if i == len(table.Labels) {
panic(fmt.Sprintf("Failed to find label to replace of position independent code: %s", label))
}
}
return line
}
func fixShiftNoArgument(line, ins string) string {
if strings.Contains(line, ins) {
parts := strings.SplitN(line, ins, 2)
args := strings.SplitN(parts[1], ",", 2)
if len(args) == 1 {
line += ", 1"
}
}
return line
}
func fixShiftInstructions(line string) string {
line = fixShiftNoArgument(line, "shr")
line = fixShiftNoArgument(line, "sar")
return line
}
func fixMovabsInstructions(line string) string {
if strings.Contains(line, "movabs") {
parts := strings.SplitN(line, "movabs", 2)
line = parts[0] + "mov" + parts[1]
}
return line
}
// Fix loads in the form of '[rbp + constant]'
// These are load instructions for stack-based arguments that occur after the first 6 arguments
// Remap to stack pointer
func fixRbpPlusLoad(line string, stackArgs StackArgs, stack Stack) string {
if match := regexpRbpLoadHigher.FindStringSubmatch(line); len(match) > 1 {
offset, _ := strconv.Atoi(match[1])
// TODO: Get proper offset for non 64-bit arguments
iarg := len(registers) + (offset-stackArgs.OffsetToFirst)/8
parts := strings.SplitN(line, match[0], 2)
line = parts[0] + fmt.Sprintf("%d[rsp]%s /* %s */", stack.OffsetForGoArg(iarg), parts[1], match[0])
}
return line
}
// Detect memory accesses in the form of '[rbp - constant]'
func detectRbpMinusMemoryAccess(line string) {
if match := regexpRbpLoadLower.FindStringSubmatch(line); len(match) > 1 {
panic(fmt.Sprintf("Not expected to find [rbp -] based loads: %s\n\nDid you specify `-mno-red-zone`?\n\n", line))
}
}
// Detect jump tables
func detectJumpTable(line string) {
if match := regexpJumpTableRef.FindStringSubmatch(line); len(match) > 0 {
panic(fmt.Sprintf("Jump table detected: %s\n\nCircumvent using '-fno-jump-tables', see 'clang -cc1 -help' (version 3.9+)\n\n", match[1]))
}
}
// Detect push instructions
func detectPushInstruction(line string) {
if match := regexpPushInstr.FindStringSubmatch(line); len(match) > 0 {
panic(fmt.Sprintf("push instruction detected: %s\n\nCannot modify `rsp` in body of assembly\n\n", match[1]))
}
}
// Detect pop instructions
func detectPopInstruction(line string) {
if match := regexpPopInstr.FindStringSubmatch(line); len(match) > 0 {
panic(fmt.Sprintf("pop instruction detected: %s\n\nCannot modify `rsp` in body of assembly\n\n", match[1]))
}
}