Skip to content
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

[WIP] Add size-limited command interface #74549

Closed
wants to merge 20 commits into from
Closed
Show file tree
Hide file tree
Changes from 16 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
2 changes: 1 addition & 1 deletion library/std/src/sys/unix/os.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ pub fn errno() -> i32 {
}

/// Sets the platform-specific value of errno
#[cfg(all(not(target_os = "linux"), not(target_os = "dragonfly")))] // needed for readdir and syscall!
#[cfg(not(target_os = "dragonfly"))] // needed for readdir and syscall!
#[allow(dead_code)] // but not all target cfgs actually end up using it
pub fn set_errno(e: i32) {
unsafe { *errno_location() = e as c_int }
Expand Down
141 changes: 127 additions & 14 deletions library/std/src/sys/unix/process/process_common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use crate::collections::BTreeMap;
use crate::ffi::{CStr, CString, OsStr, OsString};
use crate::fmt;
use crate::io;
use crate::mem;
use crate::ptr;
use crate::sys::fd::FileDesc;
use crate::sys::fs::File;
Expand Down Expand Up @@ -75,11 +76,14 @@ pub struct Command {
args: Vec<CString>,
argv: Argv,
env: CommandEnv,
env_size: Option<usize>,
arg_max: Option<isize>,
Copy link
Contributor

@pickfire pickfire Aug 31, 2020

Choose a reason for hiding this comment

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

Can arg_max possibly be Some(0)?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

It wouldn't make sense to be that. Are you suggesting a naked isize?

Copy link
Contributor

Choose a reason for hiding this comment

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

Either that or NonZero types.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

That looks cool. Let me get it changed.

arg_size: usize,

cwd: Option<CString>,
uid: Option<uid_t>,
gid: Option<gid_t>,
saw_nul: bool,
problem: Result<(), Problem>,
closures: Vec<Box<dyn FnMut() -> io::Result<()> + Send + Sync>>,
stdin: Option<Stdio>,
stdout: Option<Stdio>,
Expand Down Expand Up @@ -128,19 +132,36 @@ pub enum Stdio {
Fd(FileDesc),
}

#[derive(Copy, Clone)]
#[unstable(feature = "command_sized", issue = "74549")]
pub enum Problem {
SawNul,
Oversized,
}

/// A terrible interface for expressing how much size an arg takes up.
#[unstable(feature = "command_sized", issue = "74549")]
pub trait Arg {
fn arg_size(&self, force_quotes: bool) -> Result<usize, Problem>;
}

impl Command {
pub fn new(program: &OsStr) -> Command {
let mut saw_nul = false;
let program = os2c(program, &mut saw_nul);
let mut problem = Ok(());
let program = os2c(program, &mut problem);
let program_size = program.to_bytes_with_nul().len();
Command {
argv: Argv(vec![program.as_ptr(), ptr::null()]),
args: vec![program.clone()],
program,
env: Default::default(),
env_size: None,
arg_max: Default::default(),
arg_size: 2 * mem::size_of::<*const u8>() + program_size,
cwd: None,
uid: None,
gid: None,
saw_nul,
problem,
closures: Vec::new(),
stdin: None,
stdout: None,
Expand All @@ -150,16 +171,32 @@ impl Command {

pub fn set_arg_0(&mut self, arg: &OsStr) {
// Set a new arg0
let arg = os2c(arg, &mut self.saw_nul);
let arg = os2c(arg, &mut self.problem);
debug_assert!(self.argv.0.len() > 1);
self.arg_size -= self.args[0].to_bytes().len();
self.arg_size += arg.to_bytes().len();
self.argv.0[0] = arg.as_ptr();
self.args[0] = arg;
}

#[allow(dead_code)]
pub fn maybe_arg(&mut self, arg: &OsStr) -> io::Result<()> {
self.arg(arg);
self.problem?;
if self.check_size(false)? == false {
self.problem = Err(Problem::Oversized);
}
match &self.problem {
Err(err) => Err(err.into()),
Ok(()) => Ok(()),
}
}

pub fn arg(&mut self, arg: &OsStr) {
// Overwrite the trailing NULL pointer in `argv` and then add a new null
// pointer.
let arg = os2c(arg, &mut self.saw_nul);
let arg = os2c(arg, &mut self.problem);
self.arg_size += arg.to_bytes_with_nul().len() + mem::size_of::<*const u8>();
self.argv.0[self.args.len()] = arg.as_ptr();
self.argv.0.push(ptr::null());

Expand All @@ -169,7 +206,7 @@ impl Command {
}

pub fn cwd(&mut self, dir: &OsStr) {
self.cwd = Some(os2c(dir, &mut self.saw_nul));
self.cwd = Some(os2c(dir, &mut self.problem));
}
pub fn uid(&mut self, id: uid_t) {
self.uid = Some(id);
Expand All @@ -178,8 +215,8 @@ impl Command {
self.gid = Some(id);
}

pub fn saw_nul(&self) -> bool {
self.saw_nul
pub fn problem(&self) -> Result<(), Problem> {
self.problem
}
pub fn get_argv(&self) -> &Vec<*const c_char> {
&self.argv.0
Expand All @@ -202,6 +239,48 @@ impl Command {
self.gid
}

pub fn get_size(&mut self) -> io::Result<usize> {
// Envp size calculation is approximate.
let env = &self.env;
let problem = &mut self.problem;
let env_size = self.env_size.get_or_insert_with(|| {
let env_map = env.capture();
env_map
.iter()
.map(|(k, v)| {
os2c(k.as_ref(), problem).to_bytes().len()
+ os2c(v.as_ref(), problem).to_bytes().len()
+ 2
})
.sum::<usize>()
+ (env_map.len() + 1) * mem::size_of::<*const u8>()
});

Ok(self.arg_size + *env_size)
}

pub fn check_size(&mut self, refresh: bool) -> io::Result<bool> {
use crate::sys;
use core::convert::TryInto;
if refresh || self.arg_max.is_none() {
let (limit, errno) = unsafe {
let old_errno = sys::os::errno();
sys::os::set_errno(0);
Comment on lines +292 to +293
Copy link
Contributor

Choose a reason for hiding this comment

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

Why should we clear existing errno?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I don't think the no-error case automatically clears errno. Does it?

let limit = libc::sysconf(libc::_SC_ARG_MAX);
let errno = sys::os::errno();
sys::os::set_errno(old_errno);
Copy link
Member

Choose a reason for hiding this comment

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

This is not necessary, right? I think it is expected that any function in libstd that interacts with the OS in some way can clobber errno.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Hmm, I didn't know that!

(limit, errno)
};

if errno != 0 {
return Err(io::Error::from_raw_os_error(errno));
} else {
self.arg_max = limit.try_into().ok();
}
}
Ok(self.arg_max.unwrap() < 0 || self.get_size()? < (self.arg_max.unwrap() as usize))
Copy link
Contributor

Choose a reason for hiding this comment

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

Shouldn't arg_max be usize so it won't be less than zero?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

No, a negative value indicates that the arg size is unlimited. If my reading of POSIX is right, that is.

Copy link
Contributor

Choose a reason for hiding this comment

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

IIRC -0 of usize is still -1 for unlimited.

}

pub fn get_closures(&mut self) -> &mut Vec<Box<dyn FnMut() -> io::Result<()> + Send + Sync>> {
&mut self.closures
}
Expand All @@ -223,12 +302,13 @@ impl Command {
}

pub fn env_mut(&mut self) -> &mut CommandEnv {
self.env_size = None;
&mut self.env
}

pub fn capture_env(&mut self) -> Option<CStringArray> {
let maybe_env = self.env.capture_if_changed();
maybe_env.map(|env| construct_envp(env, &mut self.saw_nul))
maybe_env.map(|env| construct_envp(env, &mut self.problem))
}
#[allow(dead_code)]
pub fn env_saw_path(&self) -> bool {
Expand All @@ -254,9 +334,9 @@ impl Command {
}
}

fn os2c(s: &OsStr, saw_nul: &mut bool) -> CString {
fn os2c(s: &OsStr, problem: &mut Result<(), Problem>) -> CString {
CString::new(s.as_bytes()).unwrap_or_else(|_e| {
*saw_nul = true;
*problem = Err(Problem::SawNul);
CString::new("<string-with-nul>").unwrap()
})
}
Expand Down Expand Up @@ -287,7 +367,10 @@ impl CStringArray {
}
}

fn construct_envp(env: BTreeMap<OsString, OsString>, saw_nul: &mut bool) -> CStringArray {
fn construct_envp(
env: BTreeMap<OsString, OsString>,
problem: &mut Result<(), Problem>,
) -> CStringArray {
let mut result = CStringArray::with_capacity(env.len());
for (mut k, v) in env {
// Reserve additional space for '=' and null terminator
Expand All @@ -299,7 +382,7 @@ fn construct_envp(env: BTreeMap<OsString, OsString>, saw_nul: &mut bool) -> CStr
if let Ok(item) = CString::new(k.into_vec()) {
result.push(item);
} else {
*saw_nul = true;
*problem = Err(Problem::SawNul);
}
}

Expand Down Expand Up @@ -373,6 +456,36 @@ impl ChildStdio {
}
}

#[unstable(feature = "command_sized", issue = "74549")]
impl From<&Problem> for io::Error {
fn from(problem: &Problem) -> io::Error {
match *problem {
Problem::SawNul => {
io::Error::new(io::ErrorKind::InvalidInput, "nul byte found in provided data")
}
Problem::Oversized => {
io::Error::new(io::ErrorKind::InvalidInput, "command exceeds maximum size")
}
}
}
}

#[unstable(feature = "command_sized", issue = "74549")]
impl From<Problem> for io::Error {
fn from(problem: Problem) -> io::Error {
(&problem).into()
}
}

impl Arg for &OsStr {
fn arg_size(&self, _: bool) -> Result<usize, Problem> {
let mut nul_problem: Result<(), Problem> = Ok(());
let cstr = os2c(self, &mut nul_problem);
nul_problem?;
Ok(cstr.to_bytes_with_nul().len() + mem::size_of::<*const u8>())
}
}

impl fmt::Debug for Command {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.program != self.args[0] {
Expand Down
11 changes: 3 additions & 8 deletions library/std/src/sys/unix/process/process_fuchsia.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,7 @@ impl Command {
) -> io::Result<(Process, StdioPipes)> {
let envp = self.capture_env();

if self.saw_nul() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"nul byte found in provided data",
));
}
self.problem()?;

let (ours, theirs) = self.setup_io(default, needs_stdin)?;

Expand All @@ -36,8 +31,8 @@ impl Command {
}

pub fn exec(&mut self, default: Stdio) -> io::Error {
if self.saw_nul() {
return io::Error::new(io::ErrorKind::InvalidInput, "nul byte found in provided data");
if let Err(err) = self.problem() {
return err.into();
}

match self.setup_io(default, true) {
Expand Down
8 changes: 3 additions & 5 deletions library/std/src/sys/unix/process/process_unix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,7 @@ impl Command {

let envp = self.capture_env();

if self.saw_nul() {
return Err(io::Error::new(ErrorKind::InvalidInput, "nul byte found in provided data"));
}
self.problem()?;

let (ours, theirs) = self.setup_io(default, needs_stdin)?;

Expand Down Expand Up @@ -110,8 +108,8 @@ impl Command {
pub fn exec(&mut self, default: Stdio) -> io::Error {
let envp = self.capture_env();

if self.saw_nul() {
return io::Error::new(ErrorKind::InvalidInput, "nul byte found in provided data");
if let Err(err) = self.problem() {
return err.into();
}

match self.setup_io(default, true) {
Expand Down
Loading