forked from DragonOS-Community/NovaShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.rs
More file actions
271 lines (243 loc) · 9.39 KB
/
mod.rs
File metadata and controls
271 lines (243 loc) · 9.39 KB
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
use help::Helper;
use std::collections::HashMap;
use std::os::fd::{AsFd, AsRawFd};
use std::os::unix::process::CommandExt;
use std::sync::{Arc, Mutex};
use std::{fs::File, io::Read, print};
use crate::env::{EnvManager, ROOT_PATH};
use crate::parser::ExecuteErrorType;
mod help;
macro_rules! build {
($cmd:expr,$func:expr) => {
(
$cmd.to_string(),
$func as fn(&Vec<String>) -> Result<(), ExecuteErrorType>,
)
};
}
type CommandMap = HashMap<String, fn(&Vec<String>) -> Result<(), ExecuteErrorType>>;
static mut BUILD_IN_CMD: Option<Arc<Mutex<CommandMap>>> = None;
#[derive(Debug)]
pub struct BuildInCmd;
impl BuildInCmd {
// pub const BUILD_IN_CMD: &'static [BuildInCmd] = &[
// BuildInCmd("cd"),
// BuildInCmd("exec"),
// BuildInCmd("reboot"),
// BuildInCmd("free"),
// BuildInCmd("help"),
// BuildInCmd("export"),
// BuildInCmd("compgen"),
// BuildInCmd("complete"),
// ];
pub fn map() -> Option<Arc<Mutex<CommandMap>>> {
unsafe { BUILD_IN_CMD.clone() }
}
pub unsafe fn init() {
BUILD_IN_CMD = Some(Arc::new(Mutex::new(CommandMap::new())));
let mut map = BUILD_IN_CMD.as_ref().unwrap().lock().unwrap();
let mut insert = |tuple: (String, fn(&Vec<String>) -> Result<(), ExecuteErrorType>)| {
map.insert(tuple.0, tuple.1)
};
insert(build!("cd", Self::shell_cmd_cd));
insert(build!("exec", Self::shell_cmd_exec));
insert(build!("reboot", Self::shell_cmd_reboot));
insert(build!("help", Self::shell_cmd_help));
insert(build!("free", Self::shell_cmd_free));
insert(build!("export", Self::shell_cmd_export));
}
pub fn shell_cmd_cd(args: &Vec<String>) -> Result<(), ExecuteErrorType> {
let path = match args.len() {
0 => String::from(ROOT_PATH),
1 => match std::fs::canonicalize(args.get(0).unwrap()) {
Ok(path) => {
if !path.is_dir() {
return Err(ExecuteErrorType::NotDir(path.to_str().unwrap().to_string()));
}
path.to_str().unwrap().to_string()
}
Err(_) => return Err(ExecuteErrorType::FileNotFound(args.get(0).unwrap().clone())),
},
_ => return Err(ExecuteErrorType::TooManyArguments),
};
if let Err(_) = std::env::set_current_dir(&path) {
return Err(ExecuteErrorType::ExecuteFailed);
}
Ok(())
}
pub fn shell_cmd_exec(args: &Vec<String>) -> Result<(), ExecuteErrorType> {
if let Some((name, args)) = args.split_first() {
let real_path = if name.contains('/') {
// 为路径,获取规范的绝对路径
if let Ok(path) = std::fs::canonicalize(name) {
if path.is_file() {
Ok(path)
} else {
// 路径不为文件,返回错误
Err(ExecuteErrorType::NotFile(name.clone()))
}
} else {
Err(ExecuteErrorType::CommandNotFound)
}
} else {
// 不为路径,从环境变量中查找命令
which::which(name).map_err(|_| ExecuteErrorType::CommandNotFound)
}?;
let pgrp = unsafe { libc::tcgetpgrp(libc::STDIN_FILENO) };
// 如果当前终端的前台进程等于当前进程,则设置前台进程
let run_foreground = if pgrp >= 0 {
if pgrp as u32 == std::process::id() {
true
} else {
false
}
} else {
false
};
let mut child_command = std::process::Command::new(real_path);
child_command
.args(args)
.current_dir(EnvManager::current_dir());
let (rfd, wfd) = nix::unistd::pipe().expect("Failed to create pipe");
unsafe {
child_command.pre_exec(move || {
let mut b = [0u8; 1];
loop {
let x = nix::unistd::read(rfd.as_raw_fd(), &mut b)?;
if x != 0 {
break;
} else {
std::thread::sleep(std::time::Duration::from_millis(30));
}
}
Ok(())
});
}
let mut err: Option<ExecuteErrorType> = None;
match child_command.spawn() {
Ok(mut child) => {
if run_foreground {
unsafe { libc::tcsetpgrp(libc::STDIN_FILENO, child.id() as i32) };
}
// 让子进程继续执行
nix::unistd::write(wfd.as_fd(), &[1u8]).expect("Failed to write to pipe");
drop(wfd);
match child.wait() {
Ok(exit_status) => match exit_status.code() {
Some(exit_code) => {
if exit_code != 0 {
err = Some(ExecuteErrorType::ExitWithCode(exit_code));
}
}
None => err = Some(ExecuteErrorType::ProcessTerminated),
},
Err(_) => err = Some(ExecuteErrorType::ExecuteFailed),
}
if run_foreground {
unsafe { libc::tcsetpgrp(libc::STDIN_FILENO, std::process::id() as i32) };
}
}
Err(_) => todo!(),
};
return if let Some(err) = err {
Err(err)
} else {
Ok(())
};
} else {
return Err(ExecuteErrorType::TooFewArguments);
}
}
fn shell_cmd_reboot(args: &Vec<String>) -> Result<(), ExecuteErrorType> {
if args.len() == 0 {
unsafe { libc::syscall(libc::SYS_reboot, 0, 0, 0, 0, 0, 0) };
return Ok(());
} else {
return Err(ExecuteErrorType::TooManyArguments);
}
}
fn shell_cmd_free(args: &Vec<String>) -> Result<(), ExecuteErrorType> {
if args.len() == 1 && args.get(0).unwrap() != "-m" {
return Err(ExecuteErrorType::InvalidArgument(
args.get(0).unwrap().to_string(),
));
}
struct Mstat {
total: u64, // 计算机的总内存数量大小
used: u64, // 已使用的内存大小
free: u64, // 空闲物理页所占的内存大小
shared: u64, // 共享的内存大小
cache_used: u64, // 位于slab缓冲区中的已使用的内存大小
cache_free: u64, // 位于slab缓冲区中的空闲的内存大小
available: u64, // 系统总空闲内存大小(包括kmalloc缓冲区)
}
let mut mst = Mstat {
total: 0,
used: 0,
free: 0,
shared: 0,
cache_used: 0,
cache_free: 0,
available: 0,
};
let mut info_file = File::open("/proc/meminfo").unwrap();
let mut buf: Vec<u8> = Vec::new();
info_file.read_to_end(&mut buf).unwrap();
let str = String::from_utf8(buf).unwrap();
let info = str
.split(&['\n', '\t', ' '])
.filter_map(|str| str.parse::<u64>().ok())
.collect::<Vec<u64>>();
mst.total = *info.get(0).unwrap();
mst.free = *info.get(1).unwrap();
mst.used = mst.total - mst.free;
print!("\ttotal\t\tused\t\tfree\t\tshared\t\tcache_used\tcache_free\tavailable\n");
print!("Mem:\t");
if args.len() == 0 {
print!(
"{}\t\t{}\t\t{}\t\t{}\t\t{}\t\t{}\t\t{}\n",
mst.total,
mst.used,
mst.free,
mst.shared,
mst.cache_used,
mst.cache_free,
mst.available
);
} else {
print!(
"{}\t\t{}\t\t{}\t\t{}\t\t{}\t\t{}\n",
mst.total >> 10,
mst.used >> 10,
mst.free >> 10,
mst.shared >> 10,
mst.cache_used >> 10,
mst.available >> 10
);
}
Ok(())
}
fn shell_cmd_help(args: &Vec<String>) -> Result<(), ExecuteErrorType> {
if args.len() == 0 {
unsafe { Helper::help() };
return Ok(());
}
return Err(ExecuteErrorType::TooManyArguments);
}
fn shell_cmd_export(args: &Vec<String>) -> Result<(), ExecuteErrorType> {
if args.len() == 1 {
let pair = args.get(0).unwrap().split('=').collect::<Vec<&str>>();
if pair.len() == 2 && !pair.contains(&"") {
let name = pair.get(0).unwrap().to_string();
let value = pair.get(1).unwrap().to_string();
std::env::set_var(name, value);
return Ok(());
} else {
return Err(ExecuteErrorType::InvalidArgument(
args.get(0).unwrap().clone(),
));
}
}
return Err(ExecuteErrorType::TooManyArguments);
}
}