-
-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathmain.rs
More file actions
430 lines (339 loc) · 12.1 KB
/
main.rs
File metadata and controls
430 lines (339 loc) · 12.1 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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
/*
* Copyright (C) 2021-2022 The Aero Project Developers.
*
* This file is part of The Aero Project.
*
* Aero is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Aero is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Aero. If not, see <https://www.gnu.org/licenses/>.
*/
extern crate alloc;
use core::sync::atomic::{AtomicU32, Ordering};
use aero_syscall::signal::*;
use aero_syscall::*;
const MAGENTA_FG: &str = "\x1b[1;35m";
const RESET: &str = "\x1b[0m";
const UWUFETCH_LOGO: &str = r#"
,---,
' .' \
/ ; '.
: : \
: | /\ \
| : ' ;. :
| | ;/ \ \
' : | \ \ ,'
| | ' '--'
| : :
| | ,'
`--''
"#;
macro_rules! error {
($($arg:tt)*) => {
std::print!("\x1b[1;31merror\x1b[0m: {}\n", format_args!($($arg)*))
}
}
static LAST_EXIT_CODE: AtomicU32 = AtomicU32::new(0);
fn repl(history: &mut Vec<String>) -> Result<(), AeroSyscallError> {
let mut hostname_buf = [0; 64];
let mut pwd_buffer = [0; 1024];
let mut cmd_buffer = [0; 1024];
let hostname_len = sys_gethostname(&mut hostname_buf)?;
let hostname = unsafe { core::str::from_utf8_unchecked(&hostname_buf[0..hostname_len]) };
let username = "root"; // TODO: Unhardcode this at some point :^)
let pwd_length = sys_getcwd(&mut pwd_buffer)?;
let pwd = unsafe { core::str::from_utf8_unchecked(&pwd_buffer[0..pwd_length]) };
print!(
"\x1b[1;32m{}@{}\x1b[0m:\x1b[1;34m{}\x1b[0m ",
username, hostname, pwd
);
let cmd_length = sys_read(0, &mut cmd_buffer)?;
let cmd_string = unsafe { core::str::from_utf8_unchecked(&cmd_buffer[0..cmd_length]).trim() };
let mut args = cmd_string.split_whitespace();
if let Some(cmd) = args.next() {
history.push(cmd_string.to_string());
match cmd {
"echo" => {
let message = args.collect::<Vec<_>>().join(" ");
let message = message.replace(
"$?",
LAST_EXIT_CODE.load(Ordering::Relaxed).to_string().as_str(),
);
println!("{}", message);
}
"ls" => list_directory(args.next().unwrap_or("."))?,
"pwd" => println!("{}", pwd),
"cd" => {
sys_chdir(args.next().unwrap_or(".."))?;
}
"mkdir" => match args.next() {
Some(path) => {
sys_mkdir(path)?;
}
None => error!("mkdir: missing operand"),
},
"rmdir" => match args.next() {
Some(path) => {
sys_rmdir(path)?;
}
None => error!("rmdir: missing operand"),
},
"exit" => match args.next() {
Some(status) => match status.parse::<usize>() {
Ok(exit_code) => sys_exit(exit_code),
Err(_) => error!("exit: invalid operand"),
},
None => sys_exit(0),
},
"cat" => cat_file(args.next())?,
"clear" => print!("{esc}[2J{esc}[1;1H", esc = 27 as char),
"dmsg" => print_kernel_log()?,
"uwufetch" => uwufetch()?,
"uname" => uname()?,
"history" => {
for entry in history.iter() {
println!("{}", entry);
}
}
"uwutest" => {
// TODO: Make a uwutest program that is executed by the kernel
// if the test kernel is built instead of randomly bloating the shell
// with tests :).
let fb = sys_open("/dev/fb", OpenFlags::O_RDWR)?;
let buffer = &[u32::MAX; (1024 * 768)];
let casted = buffer.as_ptr() as *mut u8;
let casted = unsafe { core::slice::from_raw_parts(casted, (1024 * 768) as usize) };
println!("writing to fb");
sys_write(fb, casted)?;
sys_close(fb)?;
}
"pid" => {
println!("{}", sys_getpid()?);
}
"uptime" => {
print!("{}", get_uptime()?);
}
"sleep" => {
let duration = args.next().unwrap_or("0").parse::<usize>().unwrap_or(0);
let timespec = TimeSpec {
tv_sec: duration as isize,
tv_nsec: 0,
};
sys_sleep(×pec)?;
}
"doom" => {
let child = sys_fork()?;
if child == 0 {
let args = args.collect::<Vec<_>>();
let mut argv = Vec::new();
argv.push("/bin/doomgeneric");
argv.extend(&["-iwad", "./doom1.wad"]);
argv.extend(args);
let argv = argv.as_slice();
if sys_exec("/bin/doomgeneric", argv, &["TERM=linux"]).is_err() {
println!("{}: command not found", cmd);
sys_exit(1);
}
} else {
// Wait for the child
let mut status = 0;
sys_waitpid(child, &mut status, 0)?;
let exit_code = status & 0xff;
LAST_EXIT_CODE.store(exit_code, Ordering::SeqCst);
if exit_code != 0 {
error!("{} exited with a non-zero status code: {} ", cmd, exit_code);
}
}
}
_ => {
let child = sys_fork()?;
if child == 0 {
let args = args.collect::<Vec<_>>();
let mut argv = Vec::new();
argv.push(cmd);
argv.extend(args);
let argv = argv.as_slice();
match sys_exec(cmd, argv, &["TERM=linux"]) {
Ok(_) => core::unreachable!(),
Err(AeroSyscallError::EISDIR) => error!("{}: is a directory", cmd),
Err(AeroSyscallError::ENOENT) => error!("{}: command not found", cmd),
Err(err) => error!("{}: {:?}", cmd, err),
}
sys_exit(0);
} else {
// Wait for the child
let mut status = 0;
sys_waitpid(child, &mut status, 0)?;
let exit_code = status & 0xff;
LAST_EXIT_CODE.store(exit_code, Ordering::SeqCst);
if exit_code != 0 {
error!("{} exited with a non-zero status code: {} ", cmd, exit_code);
}
}
}
}
}
Ok(())
}
fn list_directory(path: &str) -> Result<(), AeroSyscallError> {
let dir_fd = sys_open(path, OpenFlags::O_DIRECTORY)?;
loop {
let mut dir_ents_buffer = [0; 1024];
let size = sys_getdents(dir_fd, &mut dir_ents_buffer)?;
if size == 0 {
break;
}
let dir_entry = unsafe { &*(dir_ents_buffer.as_ptr() as *const SysDirEntry) };
let name_start = core::mem::size_of::<SysDirEntry>();
let name_end = dir_entry.reclen;
let name =
unsafe { core::str::from_utf8_unchecked(&dir_ents_buffer[name_start..name_end]) };
print!("{} ", name);
}
println!();
Ok(())
}
fn cat_file(path: Option<&str>) -> Result<(), AeroSyscallError> {
// On the `None` arm we default to 0 to take input from stdin.
// This is the behaviour of `cat` that comes with any modern Linux distro.
let fd = match path {
Some(path) => sys_open(path, OpenFlags::O_RDONLY)?,
None => 0,
};
sys_seek(fd, 0, SeekWhence::SeekSet)?;
let mut buffer = [0; 1024];
loop {
let length = sys_read(fd, &mut buffer)?;
if length == 0 {
break;
}
let contents = unsafe { core::str::from_utf8_unchecked(&buffer[0..length]) };
print!("{}", contents);
}
if fd != 0 {
sys_close(fd)?;
}
print!("\n");
Ok(())
}
fn print_kernel_log() -> Result<(), AeroSyscallError> {
// dmsg is just a wrapper around `cat /dev/kmsg`
// TODO: Add colored output back :^)
cat_file(Some("/dev/kmsg"))
}
fn get_uptime() -> Result<String, AeroSyscallError> {
let mut info = unsafe { core::mem::zeroed() };
sys_info(&mut info)?;
let mut uptime = String::new();
let days = info.uptime / (3600 * 24);
let hours = info.uptime % (3600 * 24) / 3600;
let minutes = info.uptime % 3600 / 60;
let seconds = info.uptime % 60;
if days > 0 {
uptime.push_str(&format!(
"{} day{}, ",
days,
if days == 1 { "" } else { "s" }
));
}
if hours > 0 {
uptime.push_str(&format!(
"{} hour{}, ",
hours,
if hours == 1 { "" } else { "s" },
));
}
if minutes > 0 {
uptime.push_str(&format!(
"{} minute{}, ",
minutes,
if minutes == 1 { "" } else { "s" }
));
}
uptime.push_str(&format!(
"{} second{}",
seconds,
if seconds == 1 { "" } else { "s" }
));
Ok(uptime)
}
fn uwufetch() -> Result<(), AeroSyscallError> {
let print_prefix = |prefix| {
print!("{}{}{}: ", MAGENTA_FG, prefix, RESET);
};
let mut hostname_buf = [0; 64];
let hostname_len = sys_gethostname(&mut hostname_buf)?;
let hostname = unsafe { core::str::from_utf8_unchecked(&hostname_buf[0..hostname_len]) };
let username = "root"; // TODO: Unhardcode this at some point :^)
for (i, line) in UWUFETCH_LOGO.lines().skip(1).enumerate() {
print!(" {}{:<19}{}", MAGENTA_FG, line, RESET);
if i == 1 {
println!("{}@{}", username, hostname);
} else if i == 2 {
println!("{}", "-".repeat(username.len() + hostname.len() + 1));
} else if i == 3 {
print_prefix("OS");
println!("Aero");
} else if i == 4 {
let tty_fd = sys_open("/dev/tty", OpenFlags::O_RDONLY)?;
let mut resolution = WinSize::default();
sys_ioctl(tty_fd, TIOCGWINSZ, &mut resolution as *mut _ as usize)?;
sys_close(tty_fd)?;
print_prefix("Resolution");
println!("{}x{}", resolution.ws_xpixel, resolution.ws_ypixel);
} else if i == 5 {
let mut uname_info = Utsname::default();
sys_uname(&mut uname_info)?;
print_prefix("Kernel");
println!(
"{} {} ({})",
uname_info.name(),
uname_info.version(),
uname_info.machine()
);
} else if i == 6 {
print_prefix("Uptime");
println!("{}", get_uptime()?);
} else {
println!();
}
}
Ok(())
}
fn uname() -> Result<(), AeroSyscallError> {
let mut uname_info = Utsname::default();
sys_uname(&mut uname_info)?;
println!(
"{} {} {} {} {}",
uname_info.name(),
uname_info.nodename(),
uname_info.release(),
uname_info.version(),
uname_info.machine()
);
Ok(())
}
fn handle_segmentation_fault(_fault: usize) {
error!("segmentation fault");
sys_exit(0x1);
}
fn main() {
let handler = SignalHandler::Handle(handle_segmentation_fault);
let sigaction = SigAction::new(handler, 0, SignalFlags::empty());
sys_sigaction(SIGSEGV, Some(&sigaction), None)
.expect("failed to install the segmentation fault handler");
let mut history = vec![];
loop {
if let Err(error) = repl(&mut history) {
error!("{:?}", error);
}
}
}