Skip to content

ShellParams: Add subshell test #922

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
- `MpService::startup_all_aps` and `MpService::startup_this_ap` now accept an
optional `event` parameter to allow non-blocking operation.
- Added `core::error::Error` implementations to all error types.
- Added the `ShellParams` protocol

### Removed
- `BootServices::memmove` and `BootServices::set_mem` have been removed, use
Expand Down
57 changes: 57 additions & 0 deletions uefi-test-runner/examples/shell_params.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// ANCHOR: all
// ANCHOR: features
#![no_main]
#![no_std]
// ANCHOR_END: features

use log::error;
// ANCHOR: use
//use log::info;
use uefi::CStr16;
use uefi::{prelude::*, proto::shell_params::ShellParameters};
use uefi_services::println;

extern crate alloc;
use alloc::string::String;
use alloc::vec::Vec;
// ANCHOR_END: use

// ANCHOR: entry
#[entry]
fn main(image_handle: Handle, mut system_table: SystemTable<Boot>) -> Status {
// ANCHOR_END: entry
// ANCHOR: services
uefi_services::init(&mut system_table).unwrap();
let boot_services = system_table.boot_services();
// ANCHOR_END: services

// ANCHOR: params
let shell_params =
boot_services.open_protocol_exclusive::<ShellParameters>(image_handle);
let shell_params = match shell_params {
Ok(s) => s,
Err(e) => {
error!("Failed to get ShellParameters protocol");
return e.status();
}
};

// Get as Vec of String, only with alloc feature
let args: Vec<String> = shell_params.get_args().collect();
println!("Args: {:?}", args);

// Or without allocating, get a slice of the pointers
let args = shell_params.get_args_slice();
println!("Num args: {}", args.len());
if args.len() > 1 {
unsafe {
println!("First real arg: '{}'", CStr16::from_ptr(args[1]));
}
}
// ANCHOR_END: params

// ANCHOR: return
Status::SUCCESS
}
// ANCHOR_END: return
// ANCHOR_END: all
37 changes: 35 additions & 2 deletions uefi-test-runner/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,39 @@ extern crate log;
#[macro_use]
extern crate alloc;

use alloc::string::ToString;
use uefi::prelude::*;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use uefi::proto::console::serial::Serial;
use uefi::Result;
use uefi::{prelude::*, proto::shell_params::ShellParameters};
use uefi_services::{print, println};

mod boot;
mod fs;
mod proto;
mod runtime;

fn test_subshell(image: Handle, bt: &BootServices) -> Result<bool> {
let shell_params = unsafe {
bt
//.open_protocol_exclusive::<ShellParameters>(image).unwrap();
.open_protocol::<ShellParameters>(
uefi::table::boot::OpenProtocolParams {
handle: image,
agent: bt.image_handle(),
controller: None,
},
uefi::table::boot::OpenProtocolAttributes::GetProtocol,
)
.unwrap()
};

println!("Subshell argc={}", shell_params.argc);
let args: Vec<String> = shell_params.get_args().collect();
println!("Args: {:?}", args);
Ok(shell_params.argc > 1)
}

#[entry]
fn efi_main(image: Handle, mut st: SystemTable<Boot>) -> Status {
// Initialize utilities (logging, memory allocation...)
Expand Down Expand Up @@ -45,6 +67,17 @@ fn efi_main(image: Handle, mut st: SystemTable<Boot>) -> Status {
// Test all the boot services.
let bt = st.boot_services();

// If ShellParametes protocol present and run with arguments,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// If ShellParametes protocol present and run with arguments,
// If ShellParameters protocol present and run with arguments,

// we're running from a subshell started by a test. Thus run the
// ShellParams test.
if let Ok(true) = test_subshell(image, bt) {
println!("Running subshell tests");
proto::shell_params::test_subshell(image, bt);
shutdown(st);
} else {
println!("Couldn't find shell params");
}

// Try retrieving a handle to the file system the image was booted from.
bt.get_image_file_system(image)
.expect("Failed to retrieve boot file system");
Expand Down
2 changes: 2 additions & 0 deletions uefi-test-runner/src/proto/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ pub fn test(image: Handle, st: &mut SystemTable<Boot>) {
network::test(bt);
pi::test(bt);
rng::test(bt);
shell_params::test(image, bt);
string::test(bt);

#[cfg(any(
Expand Down Expand Up @@ -63,6 +64,7 @@ mod media;
mod network;
mod pi;
mod rng;
pub mod shell_params;
#[cfg(any(
target_arch = "x86",
target_arch = "x86_64",
Expand Down
114 changes: 114 additions & 0 deletions uefi-test-runner/src/proto/shell_params.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
use alloc::string::String;
use alloc::vec::Vec;
use log::info;
use uefi::prelude::*;
use uefi::proto::device_path::build::{self, DevicePathBuilder};
use uefi::proto::device_path::{DevicePath, DeviceSubType, DeviceType, LoadedImageDevicePath};
use uefi::proto::loaded_image::LoadedImage;
use uefi::proto::shell_params::ShellParameters;
use uefi::table::boot::{BootServices, LoadImageSource};
use uefi::CStr16;

pub fn test(image: Handle, bt: &BootServices) {
info!("Running loaded image protocol test");

let shell_params = bt
.open_protocol_exclusive::<ShellParameters>(image)
.expect("Failed to open ShellParameters protocol");

info!("Argc: {}", shell_params.argc);
info!("Args:");
for arg in shell_params.get_args_slice() {
let arg_str = unsafe { CStr16::from_ptr(*arg) };
info!(" '{}'", arg_str);
}

assert_eq!(shell_params.argc, shell_params.get_args_slice().len());

// By default a single argument, the executable's path
assert_eq!(shell_params.argc, 1);

subshell_runner(image, bt);
}

/// Get the device path of the shell app. This is the same as the
/// currently-loaded image's device path, but with the file path part changed.
fn get_shell_app_device_path<'a>(
boot_services: &BootServices,
storage: &'a mut Vec<u8>,
) -> &'a DevicePath {
let loaded_image_device_path = boot_services
.open_protocol_exclusive::<LoadedImageDevicePath>(boot_services.image_handle())
.expect("failed to open LoadedImageDevicePath protocol");

let mut builder = DevicePathBuilder::with_vec(storage);
for node in loaded_image_device_path.node_iter() {
if node.full_type() == (DeviceType::MEDIA, DeviceSubType::MEDIA_FILE_PATH) {
break;
}
builder = builder.push(&node).unwrap();
}
builder = builder
.push(&build::media::FilePath {
path_name: cstr16!(r"efi\boot\shell.efi"),
})
.unwrap();
builder.finalize().unwrap()
}

fn subshell_runner(image: Handle, boot_services: &BootServices) {
let mut storage = Vec::new();
let shell_image_path = get_shell_app_device_path(boot_services, &mut storage);

// Load the shell app.
let shell_image_handle = boot_services
.load_image(
image,
LoadImageSource::FromDevicePath {
device_path: shell_image_path,
from_boot_manager: false,
},
)
.expect("failed to load shell app");

// Set the command line passed to the shell app so that it will run the
// test-runner app. This automatically turns off the five-second delay.
let mut shell_loaded_image = boot_services
.open_protocol_exclusive::<LoadedImage>(shell_image_handle)
.expect("failed to open LoadedImage protocol");
let load_options = cstr16!(r"shell.efi test_runner.efi arg1 arg2");
unsafe {
shell_loaded_image.set_load_options(
load_options.as_ptr().cast(),
load_options.num_bytes() as u32,
);
}

info!("launching the sub shell app");
boot_services
.start_image(shell_image_handle)
.expect("failed to launch the shell app");
}

pub fn test_subshell(image: Handle, boot_services: &BootServices) {
info!("Running test from subshell");

let shell_params = boot_services
.open_protocol_exclusive::<ShellParameters>(image)
.expect("Failed to open ShellParameters protocol");

info!("Argc: {}", shell_params.argc);
info!("Args:");
for arg in shell_params.get_args_slice() {
let arg_str = unsafe { CStr16::from_ptr(*arg) };
info!(" '{}'", arg_str);
}

assert_eq!(shell_params.argc, shell_params.get_args_slice().len());

let args: Vec<String> = shell_params.get_args().collect();
assert_eq!(args, vec![r"FS0:\efi\boot\test_runner.efi", "arg1", "arg2"]);

// test_runner.efi arg1 arg2
assert_eq!(shell_params.argc, 3);
}
1 change: 1 addition & 0 deletions uefi/src/proto/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ pub mod network;
pub mod pi;
pub mod rng;
pub mod security;
pub mod shell_params;
pub mod shim;
pub mod string;
pub mod tcg;
49 changes: 49 additions & 0 deletions uefi/src/proto/shell_params.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
//! `ShellParams` protocol

use crate::proto::unsafe_protocol;
use crate::Char16;
use core::ffi::c_void;
use core::slice::from_raw_parts;

#[cfg(feature = "alloc")]
use crate::CStr16;
#[cfg(feature = "alloc")]
use alloc::string::String;
#[cfg(feature = "alloc")]
use alloc::string::ToString;

type ShellFileHandle = *const c_void;

/// The ShellParameters protocol.
#[repr(C)]
#[unsafe_protocol("752f3136-4e16-4fdc-a22a-e5f46812f4ca")]
pub struct ShellParameters {
/// Pointer to a list of arguments
pub argv: *const *const Char16,
/// Number of arguments
pub argc: usize,
/// Handle of the standard input
std_in: ShellFileHandle,
/// Handle of the standard output
std_out: ShellFileHandle,
/// Handle of the standard error output
std_err: ShellFileHandle,
}

impl ShellParameters {
/// Get an iterator of the shell parameter arguments
#[cfg(feature = "alloc")]
pub fn get_args(&self) -> impl Iterator<Item = String> {
unsafe {
from_raw_parts(self.argv, self.argc)
.iter()
.map(|x| CStr16::from_ptr(*x).to_string())
}
}

/// Get a slice of the args, as Char16 pointers
#[must_use]
pub fn get_args_slice(&self) -> &[*const Char16] {
unsafe { from_raw_parts(self.argv, self.argc) }
}
}