Skip to content

Correctly handle a SystemExit unwound to the top level of execution #1459

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

Merged
merged 2 commits into from
Oct 5, 2019
Merged
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 Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ rustpython-compiler = {path = "compiler", version = "0.1.1"}
rustpython-parser = {path = "parser", version = "0.1.1"}
rustpython-vm = {path = "vm", version = "0.1.1"}
dirs = "2.0"
num-traits = "0.2.8"

flame = { version = "0.2", optional = true }
flamescope = { version = "0.1", optional = true }
Expand Down
12 changes: 6 additions & 6 deletions Lib/_sre.py
Original file line number Diff line number Diff line change
Expand Up @@ -1155,17 +1155,17 @@ def set_bigcharset(self, ctx):
block_index = char_code >> 8
# NB: there are CODESIZE block indices per bytecode
a = array.array("B")
a.fromstring(array.array(CODESIZE == 2 and "H" or "I",
[ctx.peek_code(block_index / CODESIZE)]).tostring())
a.frombytes(array.array(CODESIZE == 2 and "H" or "I",
[ctx.peek_code(block_index // CODESIZE)]).tobytes())
block = a[block_index % CODESIZE]
ctx.skip_code(256 / CODESIZE) # skip block indices
block_value = ctx.peek_code(block * (32 / CODESIZE)
ctx.skip_code(256 // CODESIZE) # skip block indices
block_value = ctx.peek_code(block * (32 // CODESIZE)
+ ((char_code & 255) >> (CODESIZE == 2 and 4 or 5)))
if block_value & (1 << (char_code & ((8 * CODESIZE) - 1))):
return self.ok
else:
ctx.skip_code(256 / CODESIZE) # skip block indices
ctx.skip_code(count * (32 / CODESIZE)) # skip blocks
ctx.skip_code(256 // CODESIZE) # skip block indices
ctx.skip_code(count * (32 // CODESIZE)) # skip blocks
def unknown(self, ctx):
return False

Expand Down
51 changes: 40 additions & 11 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ use clap::{App, AppSettings, Arg, ArgMatches};
use rustpython_compiler::{compile, error::CompileError, error::CompileErrorType};
use rustpython_parser::error::ParseErrorType;
use rustpython_vm::{
import, print_exception,
import, match_class,
obj::{objint::PyInt, objtuple::PyTuple, objtype},
print_exception,
pyobject::{ItemProtocol, PyObjectRef, PyResult},
scope::Scope,
util, PySettings, VirtualMachine,
Expand All @@ -30,17 +32,47 @@ fn main() {
let vm = VirtualMachine::new(settings);

let res = run_rustpython(&vm, &matches);
// See if any exception leaked out:
handle_exception(&vm, res);

#[cfg(feature = "flame-it")]
{
main_guard.end();
if let Err(e) = write_profile(&matches) {
error!("Error writing profile information: {}", e);
process::exit(1);
}
}

// See if any exception leaked out:
if let Err(err) = res {
if objtype::isinstance(&err, &vm.ctx.exceptions.system_exit) {
let args = vm.get_attribute(err.clone(), "args").unwrap();
let args = args.downcast::<PyTuple>().expect("'args' must be a tuple");
match args.elements.len() {
0 => return,
1 => match_class!(match args.elements[0].clone() {
i @ PyInt => {
use num_traits::cast::ToPrimitive;
process::exit(i.as_bigint().to_i32().unwrap());
}
arg => {
if vm.is_none(&arg) {
return;
}
if let Ok(s) = vm.to_str(&arg) {
println!("{}", s);
}
}
}),
_ => {
Copy link
Member

Choose a reason for hiding this comment

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

is this arm same to print!("{}", vm.to_str(&args))?

Copy link
Member Author

Choose a reason for hiding this comment

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

Yep, I think I was trying to emulate code from exceptions.rs but it's just the str of it I guess.

Copy link
Member Author

Choose a reason for hiding this comment

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

Actually, it's the repr of the args tuple.

if let Ok(r) = vm.to_repr(args.as_object()) {
println!("{}", r);
}
}
}
} else {
print_exception(&vm, &err);
}
process::exit(1);
}
}

fn parse_arguments<'a>(app: App<'a, '_>) -> ArgMatches<'a> {
Expand Down Expand Up @@ -349,13 +381,6 @@ fn _run_string(vm: &VirtualMachine, scope: Scope, source: &str, source_path: Str
vm.run_code_obj(code_obj, scope)
}

fn handle_exception<T>(vm: &VirtualMachine, result: PyResult<T>) {
if let Err(err) = result {
print_exception(vm, &err);
process::exit(1);
}
}

fn run_command(vm: &VirtualMachine, scope: Scope, source: String) -> PyResult<()> {
debug!("Running command {}", source);
_run_string(vm, scope, &source, "<stdin>".to_string())?;
Expand Down Expand Up @@ -560,6 +585,10 @@ fn run_shell(vm: &VirtualMachine, scope: Scope) -> PyResult<()> {
};

if let Err(exc) = result {
if objtype::isinstance(&exc, &vm.ctx.exceptions.system_exit) {
repl.save_history(&repl_history_path).unwrap();
return Err(exc);
}
print_exception(vm, &exc);
}
}
Expand Down
11 changes: 5 additions & 6 deletions vm/src/cformat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -225,14 +225,13 @@ impl CFormatSpec {
"-"
};

// TODO: Support precision
let magnitude_string = match self.format_type {
CFormatType::Float(CFloatType::PointDecimal) => {
if Some(CFormatQuantity::Amount(6)) != self.precision {
return Err("Not yet implemented for %#.#f types".to_string());
} else {
format!("{:.6}", magnitude)
}
let precision = match self.precision {
Some(CFormatQuantity::Amount(p)) => p,
_ => 6,
};
format!("{:.*}", precision, magnitude)
}
CFormatType::Float(CFloatType::Exponent(_)) => {
return Err("Not yet implemented for %e and %E".to_string())
Expand Down
7 changes: 3 additions & 4 deletions vm/src/sysmodule.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,10 +171,9 @@ fn sys_git_info(vm: &VirtualMachine) -> PyObjectRef {
])
}

// TODO: raise a SystemExit here
fn sys_exit(code: OptionalArg<i32>, _vm: &VirtualMachine) -> PyResult<()> {
let code = code.unwrap_or(0);
std::process::exit(code)
fn sys_exit(code: OptionalArg<PyObjectRef>, vm: &VirtualMachine) -> PyResult {
let code = code.unwrap_or_else(|| vm.new_int(0));
Err(vm.new_exception_obj(vm.ctx.exceptions.system_exit.clone(), vec![code])?)
}

pub fn make_module(vm: &VirtualMachine, module: PyObjectRef, builtins: PyObjectRef) {
Expand Down
2 changes: 1 addition & 1 deletion vm/src/vm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ impl VirtualMachine {
}

#[cfg_attr(feature = "flame-it", flame("VirtualMachine"))]
fn new_exception_obj(&self, exc_type: PyClassRef, args: Vec<PyObjectRef>) -> PyResult {
pub fn new_exception_obj(&self, exc_type: PyClassRef, args: Vec<PyObjectRef>) -> PyResult {
// TODO: add repr of args into logging?
vm_trace!("New exception created: {}", exc_type.name);
self.invoke(&exc_type.into_object(), args)
Expand Down