aboutsummaryrefslogtreecommitdiffstats
path: root/pkg/host/machine_info_linux.go
blob: 8bb5e8188c64a19db7f0e723a3ce1a9441668468 (plain)
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
// Copyright 2020 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.

package host

import (
	"bufio"
	"bytes"
	"fmt"
	"os"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"
)

func init() {
	machineInfoFuncs = []machineInfoFunc{
		{"CPU Info", readCPUInfo},
		{"KVM", readKVMInfo},
	}
	machineModulesInfo = getModulesInfo
	machineGlobsInfo = getGlobsInfo
}

func readCPUInfo(buffer *bytes.Buffer) error {
	file, err := os.Open("/proc/cpuinfo")
	if err != nil {
		return err
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	scanCPUInfo(buffer, scanner)
	return nil
}

func scanCPUInfo(buffer *bytes.Buffer, scanner *bufio.Scanner) {
	keyIndices := make(map[string]int)
	type keyValues struct {
		key    string
		values []string
	}
	var info []keyValues

	for scanner.Scan() {
		splitted := strings.Split(scanner.Text(), ":")
		if len(splitted) != 2 {
			continue
		}
		key := strings.TrimSpace(splitted[0])
		val := strings.TrimSpace(splitted[1])

		if idx, ok := keyIndices[key]; !ok {
			idx = len(keyIndices)
			keyIndices[key] = idx
			info = append(info, keyValues{key, []string{val}})
		} else {
			info[idx].values = append(info[idx].values, val)
		}
	}

	for _, kv := range info {
		// It is guaranteed that len(vals) >= 1
		key := kv.key
		vals := kv.values
		if allEqual(vals) {
			fmt.Fprintf(buffer, "%-20s: %s\n", key, vals[0])
		} else {
			fmt.Fprintf(buffer, "%-20s: %s\n", key, strings.Join(vals, ", "))
		}
	}
}

func allEqual(slice []string) bool {
	if len(slice) == 0 {
		return true
	}
	for i := 1; i < len(slice); i++ {
		if slice[i] != slice[0] {
			return false
		}
	}
	return true
}

func readKVMInfo(buffer *bytes.Buffer) error {
	files, err := os.ReadDir("/sys/module/")
	if err != nil {
		return err
	}

	for _, file := range files {
		name := file.Name()
		if !strings.HasPrefix(name, "kvm") {
			continue
		}

		paramPath := filepath.Join("/sys", "module", name, "parameters")
		params, err := os.ReadDir(paramPath)
		if err != nil {
			if os.IsNotExist(err) {
				continue
			}
			return err
		}

		if len(params) == 0 {
			continue
		}

		fmt.Fprintf(buffer, "/sys/module/%s:\n", name)
		for _, key := range params {
			keyName := key.Name()
			data, err := os.ReadFile(filepath.Join(paramPath, keyName))
			if err != nil {
				return err
			}
			fmt.Fprintf(buffer, "\t%s: ", keyName)
			buffer.Write(data)
		}
		buffer.WriteByte('\n')
	}
	return nil
}

func getModuleTextAddr(moduleName string) (uint64, error) {
	addrPath := filepath.Join("/sys", "module", moduleName, "sections", ".text")
	addrContent, err := os.ReadFile(addrPath)
	if err != nil {
		return 0, fmt.Errorf("could not read module .text address file: %w", err)
	}
	addrString := strings.TrimSpace(string(addrContent))
	addr, err := strconv.ParseUint(addrString, 0, 64)
	if err != nil {
		return 0, fmt.Errorf("address parsing error in %v: %w", moduleName, err)
	}
	return addr, nil
}

func getModulesInfo() ([]KernelModule, error) {
	var modules []KernelModule
	re := regexp.MustCompile(`(\w+) ([0-9]+) .*(0[x|X][a-fA-F0-9]+)[^\n]*`)
	modulesText, _ := os.ReadFile("/proc/modules")
	for _, m := range re.FindAllSubmatch(modulesText, -1) {
		name := string(m[1])
		modAddr, err := strconv.ParseUint(string(m[3]), 0, 64)
		if err != nil {
			// /proc/modules is broken, bail out.
			return nil, fmt.Errorf("address parsing error in /proc/modules: %w", err)
		}
		textAddr, err := getModuleTextAddr(name)
		if err != nil {
			// Module address unavailable, .text is probably 0. Skip this module.
			continue
		}
		modSize, err := strconv.ParseUint(string(m[2]), 0, 64)
		if err != nil {
			// /proc/modules is broken, bail out.
			return nil, fmt.Errorf("module size parsing error in /proc/modules: %w", err)
		}
		offset := modAddr - textAddr
		modules = append(modules, KernelModule{
			Name: string(m[1]),
			Addr: textAddr,
			Size: modSize - offset,
		})
	}
	return modules, nil
}

func getGlobsInfo(globs map[string]bool) (map[string][]string, error) {
	var err error
	files := make(map[string][]string, len(globs))
	for glob := range globs {
		var (
			addglobs []string
			subglobs []string
			matches  []string
		)
		tokens := strings.Split(glob, ":")
		for _, tok := range tokens {
			if strings.HasPrefix(tok, "-") {
				subglobs = append(subglobs, tok[1:])
			} else {
				addglobs = append(addglobs, tok)
			}
		}
		for _, g := range addglobs {
			m, err := filepath.Glob(g)
			if err != nil {
				return nil, err
			}
			matches = append(matches, m...)
		}
		files[glob], err = excludeGlobs(removeDupValues(matches), subglobs)
		if err != nil {
			return nil, err
		}
	}
	return files, nil
}

func excludeGlobs(items, subglobs []string) ([]string, error) {
	var results []string
	excludes := make(map[string]bool)
	for _, glob := range subglobs {
		matches, err := filepath.Glob(glob)
		if err != nil {
			return nil, err
		}
		for _, m := range matches {
			excludes[m] = true
		}
	}

	for _, item := range items {
		if !excludes[item] {
			results = append(results, item)
		}
	}
	return results, nil
}

func removeDupValues(slice []string) []string {
	keys := make(map[string]bool)
	list := []string{}
	for _, entry := range slice {
		if !keys[entry] {
			keys[entry] = true
			list = append(list, entry)
		}
	}
	return list
}