forked from rust-lang/rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprocess.rs
727 lines (617 loc) · 21.7 KB
/
process.rs
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
use r_efi::protocols::simple_text_output;
use super::helpers;
pub use crate::ffi::OsString as EnvKey;
use crate::ffi::{OsStr, OsString};
use crate::num::{NonZero, NonZeroI32};
use crate::path::Path;
use crate::sys::fs::File;
use crate::sys::pipe::AnonPipe;
use crate::sys::unsupported;
use crate::sys_common::process::{CommandEnv, CommandEnvs};
use crate::{fmt, io};
////////////////////////////////////////////////////////////////////////////////
// Command
////////////////////////////////////////////////////////////////////////////////
#[derive(Debug)]
pub struct Command {
prog: OsString,
args: Vec<OsString>,
stdout: Option<Stdio>,
stderr: Option<Stdio>,
}
// passed back to std::process with the pipes connected to the child, if any
// were requested
pub struct StdioPipes {
pub stdin: Option<AnonPipe>,
pub stdout: Option<AnonPipe>,
pub stderr: Option<AnonPipe>,
}
#[derive(Copy, Clone, Debug)]
pub enum Stdio {
Inherit,
Null,
MakePipe,
}
impl Command {
pub fn new(program: &OsStr) -> Command {
Command { prog: program.to_os_string(), args: Vec::new(), stdout: None, stderr: None }
}
pub fn arg(&mut self, arg: &OsStr) {
self.args.push(arg.to_os_string());
}
pub fn env_mut(&mut self) -> &mut CommandEnv {
panic!("unsupported")
}
pub fn cwd(&mut self, _dir: &OsStr) {
panic!("unsupported")
}
pub fn stdin(&mut self, _stdin: Stdio) {
panic!("unsupported")
}
pub fn stdout(&mut self, stdout: Stdio) {
self.stdout = Some(stdout);
}
pub fn stderr(&mut self, stderr: Stdio) {
self.stderr = Some(stderr);
}
pub fn get_program(&self) -> &OsStr {
self.prog.as_ref()
}
pub fn get_args(&self) -> CommandArgs<'_> {
CommandArgs { iter: self.args.iter() }
}
pub fn get_envs(&self) -> CommandEnvs<'_> {
panic!("unsupported")
}
pub fn get_current_dir(&self) -> Option<&Path> {
None
}
pub fn spawn(
&mut self,
_default: Stdio,
_needs_stdin: bool,
) -> io::Result<(Process, StdioPipes)> {
unsupported()
}
fn create_pipe(
s: Stdio,
) -> io::Result<Option<helpers::OwnedProtocol<uefi_command_internal::PipeProtocol>>> {
match s {
Stdio::MakePipe => unsafe {
helpers::OwnedProtocol::create(
uefi_command_internal::PipeProtocol::new(),
simple_text_output::PROTOCOL_GUID,
)
}
.map(Some),
Stdio::Null => unsafe {
helpers::OwnedProtocol::create(
uefi_command_internal::PipeProtocol::null(),
simple_text_output::PROTOCOL_GUID,
)
}
.map(Some),
Stdio::Inherit => Ok(None),
}
}
pub fn output(&mut self) -> io::Result<(ExitStatus, Vec<u8>, Vec<u8>)> {
let mut cmd = uefi_command_internal::Image::load_image(&self.prog)?;
// UEFI adds the bin name by default
if !self.args.is_empty() {
let args = uefi_command_internal::create_args(&self.prog, &self.args);
cmd.set_args(args);
}
// Setup Stdout
let stdout = self.stdout.unwrap_or(Stdio::MakePipe);
let stdout = Self::create_pipe(stdout)?;
if let Some(con) = stdout {
cmd.stdout_init(con)
} else {
cmd.stdout_inherit()
};
// Setup Stderr
let stderr = self.stderr.unwrap_or(Stdio::MakePipe);
let stderr = Self::create_pipe(stderr)?;
if let Some(con) = stderr {
cmd.stderr_init(con)
} else {
cmd.stderr_inherit()
};
let stat = cmd.start_image()?;
let stdout = cmd.stdout()?;
let stderr = cmd.stderr()?;
Ok((ExitStatus(stat), stdout, stderr))
}
}
impl From<AnonPipe> for Stdio {
fn from(pipe: AnonPipe) -> Stdio {
pipe.diverge()
}
}
impl From<io::Stdout> for Stdio {
fn from(_: io::Stdout) -> Stdio {
// FIXME: This is wrong.
// Instead, the Stdio we have here should be a unit struct.
panic!("unsupported")
}
}
impl From<io::Stderr> for Stdio {
fn from(_: io::Stderr) -> Stdio {
// FIXME: This is wrong.
// Instead, the Stdio we have here should be a unit struct.
panic!("unsupported")
}
}
impl From<File> for Stdio {
fn from(_file: File) -> Stdio {
// FIXME: This is wrong.
// Instead, the Stdio we have here should be a unit struct.
panic!("unsupported")
}
}
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
#[non_exhaustive]
pub struct ExitStatus(r_efi::efi::Status);
impl ExitStatus {
pub fn exit_ok(&self) -> Result<(), ExitStatusError> {
if self.0 == r_efi::efi::Status::SUCCESS { Ok(()) } else { Err(ExitStatusError(self.0)) }
}
pub fn code(&self) -> Option<i32> {
Some(self.0.as_usize() as i32)
}
}
impl fmt::Display for ExitStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let err_str = super::os::error_string(self.0.as_usize());
write!(f, "{}", err_str)
}
}
impl Default for ExitStatus {
fn default() -> Self {
ExitStatus(r_efi::efi::Status::SUCCESS)
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct ExitStatusError(r_efi::efi::Status);
impl fmt::Debug for ExitStatusError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let err_str = super::os::error_string(self.0.as_usize());
write!(f, "{}", err_str)
}
}
impl Into<ExitStatus> for ExitStatusError {
fn into(self) -> ExitStatus {
ExitStatus(self.0)
}
}
impl ExitStatusError {
pub fn code(self) -> Option<NonZero<i32>> {
NonZeroI32::new(self.0.as_usize() as i32)
}
}
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub struct ExitCode(bool);
impl ExitCode {
pub const SUCCESS: ExitCode = ExitCode(false);
pub const FAILURE: ExitCode = ExitCode(true);
pub fn as_i32(&self) -> i32 {
self.0 as i32
}
}
impl From<u8> for ExitCode {
fn from(code: u8) -> Self {
match code {
0 => Self::SUCCESS,
1..=255 => Self::FAILURE,
}
}
}
pub struct Process(!);
impl Process {
pub fn id(&self) -> u32 {
self.0
}
pub fn kill(&mut self) -> io::Result<()> {
self.0
}
pub fn wait(&mut self) -> io::Result<ExitStatus> {
self.0
}
pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
self.0
}
}
pub struct CommandArgs<'a> {
iter: crate::slice::Iter<'a, OsString>,
}
impl<'a> Iterator for CommandArgs<'a> {
type Item = &'a OsStr;
fn next(&mut self) -> Option<&'a OsStr> {
self.iter.next().map(|x| x.as_ref())
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl<'a> ExactSizeIterator for CommandArgs<'a> {
fn len(&self) -> usize {
self.iter.len()
}
fn is_empty(&self) -> bool {
self.iter.is_empty()
}
}
impl<'a> fmt::Debug for CommandArgs<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.iter.clone()).finish()
}
}
#[allow(dead_code)]
mod uefi_command_internal {
use r_efi::protocols::{loaded_image, simple_text_output};
use super::super::helpers;
use crate::ffi::{OsStr, OsString};
use crate::io::{self, const_error};
use crate::mem::MaybeUninit;
use crate::os::uefi::env::{boot_services, image_handle, system_table};
use crate::os::uefi::ffi::{OsStrExt, OsStringExt};
use crate::ptr::NonNull;
use crate::slice;
use crate::sys::pal::uefi::helpers::OwnedTable;
use crate::sys_common::wstr::WStrUnits;
pub struct Image {
handle: NonNull<crate::ffi::c_void>,
stdout: Option<helpers::OwnedProtocol<PipeProtocol>>,
stderr: Option<helpers::OwnedProtocol<PipeProtocol>>,
st: OwnedTable<r_efi::efi::SystemTable>,
args: Option<(*mut u16, usize)>,
}
impl Image {
pub fn load_image(p: &OsStr) -> io::Result<Self> {
let path = helpers::OwnedDevicePath::from_text(p)?;
let boot_services: NonNull<r_efi::efi::BootServices> = boot_services()
.ok_or_else(|| const_error!(io::ErrorKind::NotFound, "Boot Services not found"))?
.cast();
let mut child_handle: MaybeUninit<r_efi::efi::Handle> = MaybeUninit::uninit();
let image_handle = image_handle();
let r = unsafe {
((*boot_services.as_ptr()).load_image)(
r_efi::efi::Boolean::FALSE,
image_handle.as_ptr(),
path.as_ptr(),
crate::ptr::null_mut(),
0,
child_handle.as_mut_ptr(),
)
};
if r.is_error() {
Err(io::Error::from_raw_os_error(r.as_usize()))
} else {
let child_handle = unsafe { child_handle.assume_init() };
let child_handle = NonNull::new(child_handle).unwrap();
let loaded_image: NonNull<loaded_image::Protocol> =
helpers::open_protocol(child_handle, loaded_image::PROTOCOL_GUID).unwrap();
let st = OwnedTable::from_table(unsafe { (*loaded_image.as_ptr()).system_table });
Ok(Self { handle: child_handle, stdout: None, stderr: None, st, args: None })
}
}
pub fn start_image(&mut self) -> io::Result<r_efi::efi::Status> {
self.update_st_crc32()?;
// Use our system table instead of the default one
let loaded_image: NonNull<loaded_image::Protocol> =
helpers::open_protocol(self.handle, loaded_image::PROTOCOL_GUID).unwrap();
unsafe {
(*loaded_image.as_ptr()).system_table = self.st.as_mut_ptr();
}
let boot_services: NonNull<r_efi::efi::BootServices> = boot_services()
.ok_or_else(|| const_error!(io::ErrorKind::NotFound, "Boot Services not found"))?
.cast();
let mut exit_data_size: usize = 0;
let mut exit_data: MaybeUninit<*mut u16> = MaybeUninit::uninit();
let r = unsafe {
((*boot_services.as_ptr()).start_image)(
self.handle.as_ptr(),
&mut exit_data_size,
exit_data.as_mut_ptr(),
)
};
// Drop exitdata
if exit_data_size != 0 {
unsafe {
let exit_data = exit_data.assume_init();
((*boot_services.as_ptr()).free_pool)(exit_data as *mut crate::ffi::c_void);
}
}
Ok(r)
}
fn set_stdout(
&mut self,
handle: r_efi::efi::Handle,
protocol: *mut simple_text_output::Protocol,
) {
unsafe {
(*self.st.as_mut_ptr()).console_out_handle = handle;
(*self.st.as_mut_ptr()).con_out = protocol;
}
}
fn set_stderr(
&mut self,
handle: r_efi::efi::Handle,
protocol: *mut simple_text_output::Protocol,
) {
unsafe {
(*self.st.as_mut_ptr()).standard_error_handle = handle;
(*self.st.as_mut_ptr()).std_err = protocol;
}
}
pub fn stdout_init(&mut self, protocol: helpers::OwnedProtocol<PipeProtocol>) {
self.set_stdout(
protocol.handle().as_ptr(),
protocol.as_ref() as *const PipeProtocol as *mut simple_text_output::Protocol,
);
self.stdout = Some(protocol);
}
pub fn stdout_inherit(&mut self) {
let st: NonNull<r_efi::efi::SystemTable> = system_table().cast();
unsafe { self.set_stdout((*st.as_ptr()).console_out_handle, (*st.as_ptr()).con_out) }
}
pub fn stderr_init(&mut self, protocol: helpers::OwnedProtocol<PipeProtocol>) {
self.set_stderr(
protocol.handle().as_ptr(),
protocol.as_ref() as *const PipeProtocol as *mut simple_text_output::Protocol,
);
self.stderr = Some(protocol);
}
pub fn stderr_inherit(&mut self) {
let st: NonNull<r_efi::efi::SystemTable> = system_table().cast();
unsafe { self.set_stderr((*st.as_ptr()).standard_error_handle, (*st.as_ptr()).std_err) }
}
pub fn stderr(&self) -> io::Result<Vec<u8>> {
match &self.stderr {
Some(stderr) => stderr.as_ref().utf8(),
None => Ok(Vec::new()),
}
}
pub fn stdout(&self) -> io::Result<Vec<u8>> {
match &self.stdout {
Some(stdout) => stdout.as_ref().utf8(),
None => Ok(Vec::new()),
}
}
pub fn set_args(&mut self, args: Box<[u16]>) {
let loaded_image: NonNull<loaded_image::Protocol> =
helpers::open_protocol(self.handle, loaded_image::PROTOCOL_GUID).unwrap();
let len = args.len();
let args_size: u32 = (len * crate::mem::size_of::<u16>()).try_into().unwrap();
let ptr = Box::into_raw(args).as_mut_ptr();
unsafe {
(*loaded_image.as_ptr()).load_options = ptr as *mut crate::ffi::c_void;
(*loaded_image.as_ptr()).load_options_size = args_size;
}
self.args = Some((ptr, len));
}
fn update_st_crc32(&mut self) -> io::Result<()> {
let bt: NonNull<r_efi::efi::BootServices> = boot_services().unwrap().cast();
let st_size = unsafe { (*self.st.as_ptr()).hdr.header_size as usize };
let mut crc32: u32 = 0;
// Set crc to 0 before calculation
unsafe {
(*self.st.as_mut_ptr()).hdr.crc32 = 0;
}
let r = unsafe {
((*bt.as_ptr()).calculate_crc32)(
self.st.as_mut_ptr() as *mut crate::ffi::c_void,
st_size,
&mut crc32,
)
};
if r.is_error() {
Err(io::Error::from_raw_os_error(r.as_usize()))
} else {
unsafe {
(*self.st.as_mut_ptr()).hdr.crc32 = crc32;
}
Ok(())
}
}
}
impl Drop for Image {
fn drop(&mut self) {
if let Some(bt) = boot_services() {
let bt: NonNull<r_efi::efi::BootServices> = bt.cast();
unsafe {
((*bt.as_ptr()).unload_image)(self.handle.as_ptr());
}
}
if let Some((ptr, len)) = self.args {
let _ = unsafe { Box::from_raw(crate::ptr::slice_from_raw_parts_mut(ptr, len)) };
}
}
}
#[repr(C)]
pub struct PipeProtocol {
reset: simple_text_output::ProtocolReset,
output_string: simple_text_output::ProtocolOutputString,
test_string: simple_text_output::ProtocolTestString,
query_mode: simple_text_output::ProtocolQueryMode,
set_mode: simple_text_output::ProtocolSetMode,
set_attribute: simple_text_output::ProtocolSetAttribute,
clear_screen: simple_text_output::ProtocolClearScreen,
set_cursor_position: simple_text_output::ProtocolSetCursorPosition,
enable_cursor: simple_text_output::ProtocolEnableCursor,
mode: *mut simple_text_output::Mode,
_buffer: Vec<u16>,
}
impl PipeProtocol {
pub fn new() -> Self {
let mode = Box::new(simple_text_output::Mode {
max_mode: 0,
mode: 0,
attribute: 0,
cursor_column: 0,
cursor_row: 0,
cursor_visible: r_efi::efi::Boolean::FALSE,
});
Self {
reset: Self::reset,
output_string: Self::output_string,
test_string: Self::test_string,
query_mode: Self::query_mode,
set_mode: Self::set_mode,
set_attribute: Self::set_attribute,
clear_screen: Self::clear_screen,
set_cursor_position: Self::set_cursor_position,
enable_cursor: Self::enable_cursor,
mode: Box::into_raw(mode),
_buffer: Vec::new(),
}
}
pub fn null() -> Self {
let mode = Box::new(simple_text_output::Mode {
max_mode: 0,
mode: 0,
attribute: 0,
cursor_column: 0,
cursor_row: 0,
cursor_visible: r_efi::efi::Boolean::FALSE,
});
Self {
reset: Self::reset_null,
output_string: Self::output_string_null,
test_string: Self::test_string,
query_mode: Self::query_mode,
set_mode: Self::set_mode,
set_attribute: Self::set_attribute,
clear_screen: Self::clear_screen,
set_cursor_position: Self::set_cursor_position,
enable_cursor: Self::enable_cursor,
mode: Box::into_raw(mode),
_buffer: Vec::new(),
}
}
pub fn utf8(&self) -> io::Result<Vec<u8>> {
OsString::from_wide(&self._buffer)
.into_string()
.map(Into::into)
.map_err(|_| const_error!(io::ErrorKind::Other, "utf8 conversion failed"))
}
extern "efiapi" fn reset(
proto: *mut simple_text_output::Protocol,
_: r_efi::efi::Boolean,
) -> r_efi::efi::Status {
let proto: *mut PipeProtocol = proto.cast();
unsafe {
(*proto)._buffer.clear();
}
r_efi::efi::Status::SUCCESS
}
extern "efiapi" fn reset_null(
_: *mut simple_text_output::Protocol,
_: r_efi::efi::Boolean,
) -> r_efi::efi::Status {
r_efi::efi::Status::SUCCESS
}
extern "efiapi" fn output_string(
proto: *mut simple_text_output::Protocol,
buf: *mut r_efi::efi::Char16,
) -> r_efi::efi::Status {
let proto: *mut PipeProtocol = proto.cast();
let buf_len = unsafe {
if let Some(x) = WStrUnits::new(buf) {
x.count()
} else {
return r_efi::efi::Status::INVALID_PARAMETER;
}
};
let buf_slice = unsafe { slice::from_raw_parts(buf, buf_len) };
unsafe {
(*proto)._buffer.extend_from_slice(buf_slice);
};
r_efi::efi::Status::SUCCESS
}
extern "efiapi" fn output_string_null(
_: *mut simple_text_output::Protocol,
_: *mut r_efi::efi::Char16,
) -> r_efi::efi::Status {
r_efi::efi::Status::SUCCESS
}
extern "efiapi" fn test_string(
_: *mut simple_text_output::Protocol,
_: *mut r_efi::efi::Char16,
) -> r_efi::efi::Status {
r_efi::efi::Status::SUCCESS
}
extern "efiapi" fn query_mode(
_: *mut simple_text_output::Protocol,
_: usize,
_: *mut usize,
_: *mut usize,
) -> r_efi::efi::Status {
r_efi::efi::Status::UNSUPPORTED
}
extern "efiapi" fn set_mode(
_: *mut simple_text_output::Protocol,
_: usize,
) -> r_efi::efi::Status {
r_efi::efi::Status::UNSUPPORTED
}
extern "efiapi" fn set_attribute(
_: *mut simple_text_output::Protocol,
_: usize,
) -> r_efi::efi::Status {
r_efi::efi::Status::UNSUPPORTED
}
extern "efiapi" fn clear_screen(
_: *mut simple_text_output::Protocol,
) -> r_efi::efi::Status {
r_efi::efi::Status::UNSUPPORTED
}
extern "efiapi" fn set_cursor_position(
_: *mut simple_text_output::Protocol,
_: usize,
_: usize,
) -> r_efi::efi::Status {
r_efi::efi::Status::UNSUPPORTED
}
extern "efiapi" fn enable_cursor(
_: *mut simple_text_output::Protocol,
_: r_efi::efi::Boolean,
) -> r_efi::efi::Status {
r_efi::efi::Status::UNSUPPORTED
}
}
impl Drop for PipeProtocol {
fn drop(&mut self) {
unsafe {
let _ = Box::from_raw(self.mode);
}
}
}
pub fn create_args(prog: &OsStr, args: &[OsString]) -> Box<[u16]> {
const QUOTE: u16 = 0x0022;
const SPACE: u16 = 0x0020;
const CARET: u16 = 0x005e;
const NULL: u16 = 0;
// This is the lower bound on the final length under the assumption that
// the arguments only contain ASCII characters.
let mut res = Vec::with_capacity(args.iter().map(|arg| arg.len() + 3).sum());
// Wrap program name in quotes to avoid any problems
res.push(QUOTE);
res.extend(prog.encode_wide());
res.push(QUOTE);
for arg in args {
res.push(SPACE);
// Wrap the argument in quotes to be treat as single arg
res.push(QUOTE);
for c in arg.encode_wide() {
// CARET in quotes is used to escape CARET or QUOTE
if c == QUOTE || c == CARET {
res.push(CARET);
}
res.push(c);
}
res.push(QUOTE);
}
res.into_boxed_slice()
}
}