forked from paultag/go-modprobe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathelf.go
218 lines (185 loc) · 4.75 KB
/
elf.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
package modprobe
import (
"bytes"
"compress/gzip"
"debug/elf"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/klauspost/compress/zstd"
"github.com/pierrec/lz4"
"github.com/xi2/xz"
"golang.org/x/sys/unix"
)
var (
// get the root directory for the kernel modules. If this line panics,
// it's because getModuleRoot has failed to get the uname of the running
// kernel (likely a non-POSIX system, but maybe a broken kernel?)
moduleRoot = getModuleRoot()
// koFileExtRegexp is used to match kernel extension file names.
koFileExt = regexp.MustCompile(`\.ko`)
)
// Get the module root (/lib/modules/$(uname -r)/)
func getModuleRoot() string {
uname := unix.Utsname{}
if err := unix.Uname(&uname); err != nil {
panic(err)
}
i := 0
for ; uname.Release[i] != 0; i++ {
}
return filepath.Join(
"/lib/modules",
string(uname.Release[:i]),
)
}
// Get a path relitive to the module root directory.
func modulePath(path string) string {
return filepath.Join(moduleRoot, path)
}
// ResolveName will, given a module name (such as `g_ether`) return an absolute
// path to the .ko that provides that module.
func ResolveName(name string) (string, error) {
// Optimistically check via filename first.
var res string
err := filepath.WalkDir(
moduleRoot,
func(path string, info fs.DirEntry, err error) error {
if strings.HasPrefix(filepath.Base(path), name+".ko") {
res = path
return filepath.SkipAll
}
return nil
})
if err == nil && res != "" {
fd, err := os.Open(res)
if err != nil {
return "", fmt.Errorf("failed to open %s: %w", res, err)
}
defer fd.Close()
elfName, err := Name(fd)
if err != nil {
return "", err
}
if elfName == name {
return res, nil
}
}
// Fallback to full file search if no match is found.
paths, err := generateMap()
if err != nil {
return "", err
}
fsPath := paths[name]
if !strings.HasPrefix(fsPath, moduleRoot) {
return "", fmt.Errorf("Module '%s' isn't in the module directory", name)
}
return fsPath, nil
}
// Open every single kernel module under the kernel module directory
// (/lib/modules/$(uname -r)/), and parse the ELF headers to extract the
// module name.
func generateMap() (map[string]string, error) {
return elfMap(moduleRoot)
}
// Open every single kernel module under the root, and parse the ELF headers to
// extract the module name.
func elfMap(root string) (map[string]string, error) {
ret := map[string]string{}
err := filepath.WalkDir(
root,
func(path string, info fs.DirEntry, err error) error {
if !koFileExt.MatchString(path) {
return nil
}
fd, err := os.Open(path)
if err != nil {
return err
}
defer fd.Close()
name, err := Name(fd)
if err != nil {
/* For now, let's just ignore that and avoid adding to it */
return nil
}
ret[name] = path
return nil
})
if err != nil {
return nil, err
}
return ret, nil
}
func ModInfo(file *os.File) (map[string]string, error) {
content, err := readModuleFile(file)
if err != nil {
return nil, err
}
f, err := elf.NewFile(bytes.NewReader(content))
if err != nil {
return nil, err
}
attrs := map[string]string{}
sec := f.Section(".modinfo")
if sec == nil {
return nil, errors.New("missing modinfo section")
}
data, err := sec.Data()
if err != nil {
return nil, fmt.Errorf("failed to get section data: %w", err)
}
for _, info := range bytes.Split(data, []byte{0}) {
if parts := strings.SplitN(string(info), "=", 2); len(parts) == 2 {
attrs[parts[0]] = parts[1]
}
}
return attrs, nil
}
// Name will, given a file descriptor to a Kernel Module (.ko file), parse the
// binary to get the module name. For instance, given a handle to the file at
// `kernel/drivers/usb/gadget/legacy/g_ether.ko`, return `g_ether`.
func Name(file *os.File) (string, error) {
mi, err := ModInfo(file)
if err != nil {
return "", fmt.Errorf("failed to get module information: %w", err)
}
if name, ok := mi["name"]; !ok {
return "", errors.New("module information is missing name")
} else {
return name, nil
}
}
// readModuleFile returns the contents of the given file descriptor, extracting
// it if necessary.
func readModuleFile(file *os.File) ([]byte, error) {
ext := filepath.Ext(file.Name())
var r io.Reader
var err error
switch ext {
case ".ko":
r = file
case ".zst":
r, err = zstd.NewReader(file)
case ".xz":
r, err = xz.NewReader(file, 0)
case ".lz4":
r = lz4.NewReader(file)
case ".gz":
r, err = gzip.NewReader(file)
default:
err = fmt.Errorf("unknown module format: %s", ext)
}
if err != nil {
return nil, fmt.Errorf("failed to extract module %s: %w", file.Name(), err)
}
b, err := io.ReadAll(r)
if err != nil {
return nil, fmt.Errorf("failed to read module %s: %w", file.Name(), err)
}
return b, nil
}