native: 22 functions analysed · 21 typed · 0 untypeable · 1 timed out · 2 entry points (1 typed) · R: 14 definitions, 2 typed strict, 11 gradual, prelude debt 8 · fuzzing: 3 definitions, 0 unsound, 1 accept calls outside their domain · tyr dc7f1a7 · Rsem 7bcb45f · NativeSem 770a1eb · rstt 2b2696f unpinned
src/void bail_if(int err, const char * what){
if(err)
Rf_errorcall(R_NilValue, "System failure for: %s (%s)", what, strerror(errno));
}static void block_sigchld(void){
sigset_t block_sigchld;
sigemptyset(&block_sigchld);
sigaddset(&block_sigchld, SIGCHLD);
sigprocmask(SIG_BLOCK, &block_sigchld, NULL);
}static void check_child_success(int fd, const char * cmd){
int child_errno;
int n = read(fd, &child_errno, sizeof(child_errno));
close(fd);
if (n) {
Rf_errorcall(R_NilValue, "Failed to execute '%s' (%s)", cmd, strerror(child_errno));
}
}void check_interrupt_fn(void *dummy) {
R_CheckUserInterrupt();
}void kill_process_group(int signum) {
kill(0, SIGKILL); // kills process group
raise(SIGKILL); // just to be sure
}int pending_interrupt(void) {
return !(R_ToplevelExec(check_interrupt_fn, NULL));
}void pipe_set_read(int pipe[2]){
close(pipe[w]);
bail_if(fcntl(pipe[r], F_SETFL, O_NONBLOCK) < 0, "fcntl() in pipe_set_read");
}void print_if(int err, const char * what){
if(err){
FILE *stream = fdopen(STDERR_FILENO, "w");
if(stream){
fprintf(stream, "System failure for: %s (%s)\n", what, strerror(errno));
fclose(stream);
}
}
}void print_output(int pipe_out[2], SEXP fun){
static ssize_t len;
static char buffer[65336];
while ((len = read(pipe_out[r], buffer, sizeof(buffer))) > 0)
R_callback(fun, buffer, len);
}static void R_callback(SEXP fun, const char * buf, ssize_t len){
if(!isFunction(fun)) return;
int ok;
SEXP str = PROTECT(allocVector(RAWSXP, len));
memcpy(RAW(str), buf, len);
SEXP call = PROTECT(LCONS(fun, LCONS(str, R_NilValue)));
R_tryEval(call, R_GlobalEnv, &ok);
UNPROTECT(2);
}(x1: any_sexp, x2: any_sexp) -> INT1| call | verdict | error |
|---|---|---|
| R_exec_status(function(...) as.name("x"), list(local({ p <- unserialize(serialize(new("externalptr"), NULL)); attributes(p) <- NULL; p }))) | error_pkg | System failure for: waitpid() (No such process) |
| R_exec_status(NULL, new.env()) | error_pkg | System failure for: waitpid() (No such process) |
| R_exec_status(c("x y", "NA", "x y", "é", "NA"), function(...) quote(f(x))) | error_pkg | System failure for: waitpid() (No such process) |
| R_exec_status(quote(f(x)), list(complex(0), local({ p <- unserialize(serialize(new("externalptr"), NULL)); attributes(p) <- NULL; p }))) | error_pkg | System failure for: waitpid() (No such process) |
| R_exec_status(local({ p <- unserialize(serialize(new("externalptr"), NULL)); attributes(p) <- NULL; p }), NULL) | error_pkg | System failure for: waitpid() (No such process) |
| R_exec_status(TRUE, NULL) | error_pkg | System failure for: waitpid() (No child processes) |
SEXP R_exec_status(SEXP rpid, SEXP wait){
int wstat = NA_INTEGER;
pid_t pid = asInteger(rpid);
do {
int res = waitpid(pid, &wstat, WNOHANG);
bail_if(res < 0, "waitpid()");
if(res)
break;
usleep(100*1000);
} while (asLogical(wait) && !pending_interrupt());
return ScalarInteger(wstat);
}static void resume_sigchild(void){
sigset_t block_sigchld;
sigemptyset(&block_sigchld);
sigaddset(&block_sigchld, SIGCHLD);
sigprocmask(SIG_UNBLOCK, &block_sigchld, NULL);
}void safe_close(int target){
set_output(target, "/dev/null");
}void set_input(const char * file){
close(STDIN_FILENO);
int fd = open(file, O_RDONLY); //lowest numbered FD should be 0
print_if(fd != 0, "open() set_input not equal to STDIN_FILENO");
}void set_output(int target, const char * file){
close(target);
int fd = open(file, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
print_if(fd < 0, "open() set_output");
if(fd == target)
return;
print_if(fcntl(fd, F_DUPFD, target) < 0, "fcntl() set_output");
close(fd);
}void set_pipe(int input, int output[2]){
print_if(dup2(output[w], input) < 0, "dup2() stdout/stderr");
close(output[r]);
close(output[w]);
}int wait_for_action2(int fd1, int fd2){
short events = POLLIN | POLLERR | POLLHUP;
struct pollfd ufds[2] = {
{fd1, events, events},
{fd2, events, events}
};
return poll(ufds, 2, waitms);
}void warn_if(int err, const char * what){
if(err)
Rf_warningcall(R_NilValue, "System failure for: %s (%s)", what, strerror(errno));
}SEXP C_execute(SEXP command, SEXP args, SEXP outfun, SEXP errfun, SEXP input, SEXP wait, SEXP timeout){
//split process
int block = asLogical(wait);
int pipe_out[2];
int pipe_err[2];
int failure[2];
//setup execvp errno pipe
bail_if(pipe(failure), "pipe(failure)");
//create io pipes only in blocking mode
if(block){
bail_if(pipe(pipe_out) || pipe(pipe_err), "create pipe");
block_sigchld();
}
//fork the main process
pid_t pid = fork();
bail_if(pid < 0, "fork()");
//CHILD PROCESS
if(pid == 0){
if(block){
//undo blocking in child (is this needed at all?)
resume_sigchild();
// send stdout/stderr to pipes
set_pipe(STDOUT_FILENO, pipe_out);
set_pipe(STDERR_FILENO, pipe_err);
} else {
//redirect stdout in background process
if(IS_STRING(outfun)){
set_output(STDOUT_FILENO, CHAR(STRING_ELT(outfun, 0)));
} else if(!IS_TRUE(outfun)){
safe_close(STDOUT_FILENO);
}
//redirect stderr in background process
if(IS_STRING(errfun)){
set_output(STDERR_FILENO, CHAR(STRING_ELT(errfun, 0)));
} else if(!IS_TRUE(errfun)){
safe_close(STDERR_FILENO);
}
}
//Linux only: set pgid and commit suicide when parent dies
#ifdef PR_SET_PDEATHSIG
setpgid(0, 0);
prctl(PR_SET_PDEATHSIG, SIGTERM);
signal(SIGTERM, kill_process_group);
#endif
//OSX: do NOT change pgid, so we receive signals from parent group
// Set STDIN for child (default is /dev/null)
if(IS_FALSE(input)){
//set stdin to unreadable /dev/null (O_WRONLY)
safe_close(STDIN_FILENO);
} else if(!IS_TRUE(input)){
set_input(IS_STRING(input) ? CHAR(STRING_ELT(input, 0)) : "/dev/null");
}
//close all file descriptors before exit, otherwise they can segfault
for (int i = 3; i < sysconf(_SC_OPEN_MAX); i++) {
if(i != failure[w]){
int err = close(i);
if(i > 200 && err < 0)
break;
}
}
//prepare execv
int len = Rf_length(args);
char * argv[len + 1];
argv[len] = NULL;
for(int i = 0; i < len; i++){
argv[i] = strdup(CHAR(STRING_ELT(args, i)));
}
//execvp never returns if successful
fcntl(failure[w], F_SETFD, FD_CLOEXEC);
execvp(CHAR(STRING_ELT(command, 0)), argv);
//execvp failed! Send errno to parent
print_if(write(failure[w], &errno, sizeof(errno)) < 0, "write to failure pipe");
close(failure[w]);
//exit() not allowed by CRAN. raise() should suffice
//exit(EXIT_FAILURE);
raise(SIGKILL);
}
//PARENT PROCESS:
close(failure[w]);
if (!block){
check_child_success(failure[r], CHAR(STRING_ELT(command, 0)));
return ScalarInteger(pid);
}
//blocking: close write end of IO pipes
pipe_set_read(pipe_out);
pipe_set_read(pipe_err);
//start timer
struct timeval start, end;
double elapsed, totaltime = REAL(timeout)[0];
gettimeofday(&start, NULL);
//status -1 means error, 0 means running
int status = 0;
int killcount = 0;
while (waitpid(pid, &status, WNOHANG) >= 0){
//check for timeout
if(totaltime > 0){
gettimeofday(&end, NULL);
elapsed = (end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) / 1e6;
if(killcount == 0 && elapsed > totaltime){
warn_if(kill(pid, SIGINT), "interrupt child");
killcount++;
} else if(killcount == 1 && elapsed > (totaltime + 1)){
warn_if(kill(pid, SIGKILL), "force kill child");
killcount++;
}
}
//for well behaved programs, SIGINT is automatically forwarded
if(pending_interrupt()){
//pass interrupt to child. On second try we SIGKILL.
warn_if(kill(pid, killcount ? SIGKILL : SIGINT), "kill child");
killcount++;
}
//make sure to empty the pipes, even if fun == NULL
wait_for_action2(pipe_out[r], pipe_err[r]);
//print stdout/stderr buffers
print_output(pipe_out, outfun);
print_output(pipe_err, errfun);
}
warn_if(close(pipe_out[r]), "close stdout");
warn_if(close(pipe_err[r]), "close stderr");
// check for execvp() error *after* closing pipes and zombie
resume_sigchild();
check_child_success(failure[r], CHAR(STRING_ELT(command, 0)));
if(WIFEXITED(status)){
return ScalarInteger(WEXITSTATUS(status));
} else {
int signal = WTERMSIG(status);
if(signal != 0){
if(killcount && elapsed > totaltime){
Rf_errorcall(R_NilValue, "Program '%s' terminated (timeout reached: %.2fsec)",
CHAR(STRING_ELT(command, 0)), totaltime);
} else {
Rf_errorcall(R_NilValue, "Program '%s' terminated by SIGNAL (%s)",
CHAR(STRING_ELT(command, 0)), strsignal(signal));
}
}
Rf_errorcall(R_NilValue, "Program terminated abnormally");
}
}rawConnection — a name the prelude does not declarename: rawConnection
as_text <- function(x, ...){
if(length(x)){
con <- rawConnection(x)
on.exit(close(con))
readLines(con, ...)
} else {
character(0)
}
}argument: @("([\\\\]*)\""<>, "\\\\1\\\\1\\\\\\\\\""<>, CHR<> & ~"\"\""<> | 'str & vec, useBytes: tt<>)
failing call: base::gsub("([\\\\]*)\"",
"\\\\1\\\\1\\\\\\\\\"",
NA_character_,
useBytes = TRUE)windows_quote_one <- function(str){
if(!nchar(str)){
return('""')
}
if(!grepl('[ \t"]', str)){
return(str)
}
if(!grepl('["\\]', str)){
return(paste0('"', str, '"'))
}
str <- gsub('([\\]*)"', '\\1\\1\\\\"', str, useBytes = TRUE)
str <- gsub('([\\]+)$', '\\1\\1', str, useBytes = TRUE)
paste0('"', str, '"')
}((args: 'args & null) -> 'args)<>| parameter | change | call | returned |
|---|---|---|---|
| args | kind:chr | windows_quote("args" = "fuzz") | "fuzz"<> with { } |
windows_quote <- function(args){
if(is.null(args))
return(args)
stopifnot(is.character(args))
args <- enc2utf8(args)
vapply(args, windows_quote_one, character(1), USE.NAMES = FALSE)
}path.expand — a name the prelude does not declarename: path.expand
execute <- function(cmd, args, std_out, std_err, std_in, wait, timeout){
stopifnot(is.character(cmd))
if(.Platform$OS.type == 'windows'){
if(!inherits(cmd, 'AsIs'))
cmd <- utils::shortPathName(path.expand(cmd))
if(!inherits(args, 'AsIs'))
args <- windows_quote(args)
} else {
if(!inherits(cmd, 'AsIs'))
cmd <- path.expand(cmd)
}
stopifnot(is.logical(wait))
argv <- enc2utf8(c(cmd, args))
if(length(std_in) && !is.logical(std_in)) # Only files supported for stdin
std_in <- enc2utf8(normalizePath(std_in, mustWork = TRUE))
.Call(C_execute, cmd, argv, std_out, std_err, std_in, wait, timeout)
}stderr — a name the prelude does not declarename: stderr
exec_wait <- function(cmd, args = NULL, std_out = stdout(), std_err = stderr(), std_in = NULL, timeout = 0){
# Convert TRUE or filepath into connection objects
std_out <- if(isTRUE(std_out) || identical(std_out, "")){
stdout()
} else if(is.character(std_out)){
file(normalizePath(std_out, mustWork = FALSE))
} else std_out
std_err <- if(isTRUE(std_err) || identical(std_err, "")){
stderr()
} else if(is.character(std_err)){
std_err <- file(normalizePath(std_err, mustWork = FALSE))
} else std_err
# Define the callbacks
outfun <- if(inherits(std_out, "connection")){
if(!isOpen(std_out)){
open(std_out, "wb")
on.exit(close(std_out), add = TRUE)
}
if(identical(summary(std_out)$text, "text")){
function(x){
cat(rawToChar(x), file = std_out)
flush(std_out)
}
} else {
function(x){
writeBin(x, con = std_out)
flush(std_out)
}
}
} else if(is.function(std_out)){
if(!length(formals(std_out)))
stop("Function std_out must take at least one argument")
std_out
}
errfun <- if(inherits(std_err, "connection")){
if(!isOpen(std_err)){
open(std_err, "wb")
on.exit(close(std_err), add = TRUE)
}
if(identical(summary(std_err)$text, "text")){
function(x){
cat(rawToChar(x), file = std_err)
flush(std_err)
}
} else {
function(x){
writeBin(x, con = std_err)
flush(std_err)
}
}
} else if(is.function(std_err)){
if(!length(formals(std_err)))
stop("Function std_err must take at least one argument")
std_err
}
execute(cmd = cmd, args = args, std_out = outfun, std_err = errfun,
std_in = std_in, wait = TRUE, timeout = timeout)
}execute — one of the package’s own names, itself untypedname: execute
exec_background <- function(cmd, args = NULL, std_out = TRUE, std_err = TRUE, std_in = NULL){
if(!is.character(std_out) && !is.logical(std_out))
stop("argument 'std_out' must be TRUE / FALSE or a filename")
if(!is.character(std_err) && !is.logical(std_err))
stop("argument 'std_err' must be TRUE / FALSE or a filename")
execute(cmd = cmd, args = args, std_out = std_out, std_err = std_err,
wait = FALSE, std_in = std_in, timeout = 0)
}raw — a name the prelude does not declarename: raw
exec_internal <- function(cmd, args = NULL, std_in = NULL, error = TRUE, timeout = 0){
outcon <- rawConnection(raw(0), "r+")
on.exit(close(outcon), add = TRUE)
errcon <- rawConnection(raw(0), "r+")
on.exit(close(errcon), add = TRUE)
status <- exec_wait(cmd, args, std_out = outcon,
std_err = errcon, std_in = std_in, timeout = timeout)
if(isTRUE(error) && !identical(status, 0L))
stop(sprintf("Executing '%s' failed with status %d", cmd, status))
list(
status = status,
stdout = rawConnectionValue(outcon),
stderr = rawConnectionValue(errcon)
)
}| call | verdict | error |
|---|---|---|
| exec_status("pid" = list(new.env(), complex(0))) | error_type | System failure for: waitpid() (No such process) |
| exec_status(as.name("x"), 1) | error_type | System failure for: waitpid() (No such process) |
| exec_status(list(NULL)) | error_type | System failure for: waitpid() (No such process) |
| exec_status("pid" = local({ p <- unserialize(serialize(new("externalptr"), NULL)); attributes(p) <- NULL; p })) | error_type | System failure for: waitpid() (No such process) |
| exec_status("pid" = 0) | error_type | System failure for: waitpid() (No child processes) |
| exec_status("pid" = list(as.name("x"), NULL), "wait" = NULL) | error_type | System failure for: waitpid() (No such process) |
exec_status <- function(pid, wait = TRUE){
.Call(R_exec_status, pid, wait)
}ifelse — a name the prelude does not declarename: ifelse
rbin <- function(){
cmd <- ifelse(.Platform$OS.type == 'windows', 'Rterm', 'R')
file.path(R.home('bin'), cmd)
}stderr — a name the prelude does not declarename: stderr
r_wait <- function(args = '--vanilla', std_out = stdout(), std_err = stderr(), std_in = NULL){
exec_wait(rbin(), args = args, std_out = std_out, std_err = std_err, std_in = std_in)
}rbin — one of the package’s own names, itself untypedname: rbin
r_internal <- function(args = '--vanilla', std_in = NULL, error = TRUE){
exec_internal(rbin(), args = args, std_in = std_in, error = error)
}rbin — one of the package’s own names, itself untypedname: rbin
r_background <- function(args = '--vanilla', std_out = TRUE, std_err = TRUE, std_in = NULL){
exec_background(rbin(), args = args, std_out = std_out, std_err = std_err, std_in = std_in)
}.Deprecated — a name the prelude does not declarename: .Deprecated
eval_safe <- function(...){
.Deprecated('unix::eval_safe', 'sys')
unix::eval_safe(...)
}.Deprecated — a name the prelude does not declarename: .Deprecated
eval_fork <- function(...){
.Deprecated('unix::eval_fork', 'sys')
unix::eval_fork(...)
}