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
use bitflags::bitflags;
use std::path::Path;
use crate::{read_value, ProcResult};
pub fn enabled() -> ProcResult<bool> {
let val: String = read_value("/proc/sys/fs/binfmt_misc/status")?;
Ok(val == "enabled")
}
fn hex_to_vec(hex: &str) -> ProcResult<Vec<u8>> {
if hex.len() % 2 != 0 {
return Err(build_internal_error!(format!(
"Hex string {:?} has non-even length",
hex
)));
}
let mut idx = 0;
let mut data = Vec::new();
while idx < hex.len() {
let byte = from_str!(u8, &hex[idx..idx + 2], 16);
data.push(byte);
idx += 2;
}
Ok(data)
}
#[derive(Debug, Clone)]
pub enum BinFmtData {
Extension(String),
Magic { offset: u8, magic: Vec<u8>, mask: Vec<u8> },
}
#[derive(Debug, Clone)]
pub struct BinFmtEntry {
pub name: String,
pub enabled: bool,
pub interpreter: String,
pub flags: BinFmtFlags,
pub data: BinFmtData,
}
impl BinFmtEntry {
pub(crate) fn from_string(name: String, data: &str) -> ProcResult<Self> {
let mut enabled = false;
let mut interpreter = String::new();
let mut ext = None;
let mut offset = 0;
let mut magic = Vec::new();
let mut mask = Vec::new();
let mut flags = BinFmtFlags::empty();
for line in data.lines() {
if line == "enabled" {
enabled = true;
} else if let Some(stripped) = line.strip_prefix("interpreter ") {
interpreter = stripped.to_string();
} else if let Some(stripped) = line.strip_prefix("flags:") {
flags = BinFmtFlags::from_str(stripped);
} else if let Some(stripped) = line.strip_prefix("extension .") {
ext = Some(stripped.to_string());
} else if let Some(stripped) = line.strip_prefix("offset ") {
offset = from_str!(u8, stripped);
} else if let Some(stripped) = line.strip_prefix("magic ") {
let hex = stripped;
magic = hex_to_vec(dbg!(hex))?;
} else if let Some(stripped) = line.strip_prefix("mask ") {
let hex = stripped;
mask = hex_to_vec(hex)?;
}
}
if !magic.is_empty() && mask.is_empty() {
mask.resize(magic.len(), 0xff);
}
Ok(BinFmtEntry {
name,
enabled,
interpreter,
flags,
data: if let Some(ext) = ext {
BinFmtData::Extension(ext)
} else {
BinFmtData::Magic { magic, mask, offset }
},
})
}
}
bitflags! {
pub struct BinFmtFlags: u8 {
const P = 0x01;
const O = 0x02;
const C = 0x04;
const F = 0x08;
}
}
impl BinFmtFlags {
pub(crate) fn from_str(s: &str) -> Self {
s.chars()
.filter_map(|c| match c {
'P' => Some(BinFmtFlags::P),
'O' => Some(BinFmtFlags::O),
'C' => Some(BinFmtFlags::C),
'F' => Some(BinFmtFlags::F),
_ => None,
})
.fold(BinFmtFlags::empty(), |a, b| a | b)
}
}
pub fn list() -> ProcResult<Vec<BinFmtEntry>> {
let path = Path::new("/proc/sys/fs/binfmt_misc/");
let mut v = Vec::new();
for entry in wrap_io_error!(path, path.read_dir())? {
let entry = entry?;
if entry.file_name() == "status" || entry.file_name() == "register" {
continue;
}
let name = entry.file_name().to_string_lossy().to_string();
let data = std::fs::read_to_string(entry.path())?;
v.push(BinFmtEntry::from_string(name, &data)?);
}
Ok(v)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_enabled() {
match enabled() {
Ok(_) => {}
Err(crate::ProcError::NotFound(_)) => {}
Err(e) => panic!("{}", e),
}
}
#[test]
fn parse_magic() {
let mask = "7f454c460201010000000000000000000200f300";
let data = hex_to_vec(mask).unwrap();
println!("{:?}", data);
assert_eq!(data.len(), 20);
assert_eq!(data[0], 0x7f);
assert_eq!(data[1], 0x45);
assert!(hex_to_vec("a").is_err());
assert!(hex_to_vec("zz").is_err());
}
#[test]
fn flags_parsing() {
assert!(BinFmtFlags::from_str("").is_empty());
let flags = BinFmtFlags::from_str("F");
assert_eq!(flags, BinFmtFlags::F);
let flags = BinFmtFlags::from_str("OCF");
assert_eq!(flags, BinFmtFlags::F | BinFmtFlags::C | BinFmtFlags::O);
}
#[test]
fn binfmt() {
let data = r#"enabled
interpreter /usr/bin/qemu-riscv64-static
flags: OCF
offset 12
magic 7f454c460201010000000000000000000200f300
mask ffffffffffffff00fffffffffffffffffeffffff"#;
let entry = BinFmtEntry::from_string("test".to_owned(), data).unwrap();
println!("{:#?}", entry);
assert_eq!(entry.flags, BinFmtFlags::F | BinFmtFlags::C | BinFmtFlags::O);
assert!(entry.enabled);
assert_eq!(entry.interpreter, "/usr/bin/qemu-riscv64-static");
if let BinFmtData::Magic { offset, magic, mask } = entry.data {
assert_eq!(offset, 12);
assert_eq!(magic.len(), mask.len());
assert_eq!(
magic,
vec![
0x7f, 0x45, 0x4c, 0x46, 0x02, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x02, 0x00, 0xf3, 0x00
]
);
} else {
panic!("Unexpected data");
}
let data = r#"enabled
interpreter /bin/hello
flags:
extension .hello"#;
let entry = BinFmtEntry::from_string("test".to_owned(), data).unwrap();
println!("{:#?}", entry);
assert_eq!(entry.flags, BinFmtFlags::empty());
assert!(entry.enabled);
assert_eq!(entry.interpreter, "/bin/hello");
if let BinFmtData::Extension(ext) = entry.data {
assert_eq!(ext, "hello");
} else {
panic!("Unexpected data");
}
}
#[test]
fn live() {
for entry in super::list().unwrap() {
println!("{:?}", entry);
}
}
}