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
|
package main
import (
"bufio"
"fmt"
"os"
"os/exec"
"strings"
)
func convertStackToAddr2line(inputFile, outputFile, binaryPath string) error {
infile, err := os.Open(inputFile)
if err != nil {
return fmt.Errorf("无法打开输入文件: %v", err)
}
defer func(infile *os.File) {
err := infile.Close()
if err != nil {
fmt.Printf("关闭输入文件时出错: %v\n", err)
}
}(infile)
outfile, err := os.Create(outputFile)
if err != nil {
return fmt.Errorf("无法创建输出文件: %v", err)
}
defer func(outfile *os.File) {
err := outfile.Close()
if err != nil {
fmt.Printf("关闭输出文件时出错: %v\n", err)
}
}(outfile)
scanner := bufio.NewScanner(infile)
writer := bufio.NewWriter(outfile)
defer func(writer *bufio.Writer) {
err := writer.Flush()
if err != nil {
fmt.Printf("刷新输出文件时出错: %v\n", err)
}
}(writer)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if strings.HasPrefix(line, "#") {
parts := strings.Fields(line)
var address string
for _, part := range parts {
if strings.HasPrefix(part, "0x") {
address = part
break
}
}
if address != "" {
cmd := exec.Command("addr2line", "-e", binaryPath, address)
output, err := cmd.Output()
if err != nil {
_, err := fmt.Fprintf(os.Stderr, "执行 addr2line 失败: %v\n", err)
if err != nil {
return err
}
continue
}
s := strings.TrimSpace(string(output))
_, err = writer.WriteString(s + "\n")
if err != nil {
return err
}
fmt.Println(s)
}
} else {
_, err := writer.WriteString(line + "\n")
if err != nil {
return err
}
fmt.Println(line)
}
}
if err := scanner.Err(); err != nil {
return fmt.Errorf("读取文件时出错: %v", err)
}
fmt.Printf("转换完成,结果已保存到 %s\n", outputFile)
return nil
}
func main() {
if len(os.Args) != 4 {
fmt.Println("Usage: go run main.go <input_file> <output_file> <binary_path>")
os.Exit(1)
}
inputFile := os.Args[1]
outputFile := os.Args[2]
binaryPath := os.Args[3]
if err := convertStackToAddr2line(inputFile, outputFile, binaryPath); err != nil {
_, err := fmt.Fprintf(os.Stderr, "错误: %v\n", err)
if err != nil {
return
}
os.Exit(1)
}
}
|