static bool read_script(struct key *key) { static struct buffer input_buffer; static const char *line = ""; enum status_code code; if (!line || !*line) { if (input_buffer.data && *input_buffer.data == ':') { line = "<Enter>"; memset(&input_buffer, 0, sizeof(input_buffer)); } else if (!io_get(&script_io, &input_buffer, '\n', true)) { io_done(&script_io); return false; } else { line = input_buffer.data; } } code = get_key_value(&line, key); if (code != SUCCESS) die("Error reading script: %s", get_status_message(code)); return true; }
static int skip_whitespace(Input* in) { int ch; do { ch = io_get(in); } while (ch != -1 && isspace(ch)); return ch; }
/* we process an entire file at a time... */ static void ex_hexdump_read_fd_write_stdout(Vstr_base *s1, Vstr_base *s2, int fd) { /* read/process/write loop */ while (TRUE) { int io_w_state = IO_OK; int io_r_state = io_get(s2, fd); if (io_r_state == IO_EOF) break; ex_hexdump_process(s1, s1->len, s2, 1, s2->len, prnt_high_chars, EX_MAX_W_DATA_INCORE, TRUE, FALSE); if (s1->conf->malloc_bad) errno = ENOMEM, err(EXIT_FAILURE, "adding data"); io_w_state = io_put(s1, STDOUT_FILENO); io_limit(io_r_state, fd, io_w_state, STDOUT_FILENO, s1); } /* write out all of the end of the file, * so the next file starts on a new line */ ex_hexdump_process_limit(s1, s2, 0); }
static void read_string(JSONSource* self) { Input* in = self->in; string_output_reset(self->buf); for (;;) { int ch = io_get(in); if (ch == '"') { break; } else if (ch == -1) { RAISE(EOF); } if (ch == '\\') { ch = io_get(in); switch (ch) { case '\\': case '/': case '"': break; case 'b': ch = '\b'; break; case 'f': ch = '\f'; break; case 'n': ch = '\n'; break; case 'r': ch = '\r'; break; case 't': ch = '\t'; break; case 'u': // Not supported yet; I'm not sure how to handle unicode characters etc RAISE(MALFORMED); default: RAISE(MALFORMED); } } io_put(self->buf, ch); } io_put(self->buf, 0); self->sval.ptr = (char*)string_output_data(self->buf, &self->sval.size); self->sval.size--; // Don't count the NULL-character }
bool io_eof(Input* in) { if (in->_impl->eof) { return call(in, eof); } assert(in->_impl->unget); int c = io_get(in); io_unget(in); return c == -1; }
static int limited_get(void* _self) { LimitedInput* self = _self; if (self->read < self->limit) { int ch = io_get(self->in); self->read += (ch == -1) ? 0 : 1; return ch; } else { return -1; } }
bool index_diff(struct index_diff *diff, bool untracked, bool count_all) { const char *untracked_arg = !untracked ? "--untracked-files=no" : count_all ? "--untracked-files=all" : "--untracked-files=normal"; const char *status_argv[] = { "git", "status", "--porcelain", "-z", untracked_arg, NULL }; struct io io; struct buffer buf; bool ok = true; memset(diff, 0, sizeof(*diff)); if (!io_run(&io, IO_RD, repo.cdup, NULL, status_argv)) return false; while (io_get(&io, &buf, 0, true) && (ok = buf.size > 3)) { if (buf.data[0] == '?') diff->untracked++; /* Ignore staged but unmerged entries. */ else if (buf.data[0] != ' ' && buf.data[0] != 'U') diff->staged++; if (buf.data[1] != ' ') diff->unstaged++; if (!count_all && diff->staged && diff->unstaged && (!untracked || diff->untracked)) break; /* Skip source filename in rename */ if (buf.data[0] == 'R') { io_get(&io, &buf, 0, true); } } if (io_error(&io)) ok = false; io_done(&io); return ok; }
/** * Updates the parser. * * Takes all available bytes from the incoming buffer and * then puts them in the parser. * @todo Abort when parser_add_byte fails, or better get a * test function to check for more space. */ void parser_update(void) { uint8_t value = 0, times = 255 - io_get_free_buffer_size(); for (; 0 < times; times--) { io_get(&value); if (parser_add_byte(value) == 0) { io_pop(); } else { break; } } }
bool io_read_buf(struct io *io, char buf[], size_t bufsize) { struct buffer result = {0}; if (io_get(io, &result, '\n', TRUE)) { result.data = chomp_string(result.data); string_ncopy_do(buf, bufsize, result.data, strlen(result.data)); } return io_done(io) && result.data; }
/* Keep reading on the file descriptor until there is no more data (ERR_EOF) * abort if there is an error reading or writing */ static void ex_cat_read_fd_write_stdout(Vstr_base *s1, int fd) { while (TRUE) { int io_w_state = IO_OK; int io_r_state = io_get(s1, fd); if (io_r_state == IO_EOF) break; io_w_state = io_put(s1, STDOUT_FILENO); io_limit(io_r_state, fd, io_w_state, STDOUT_FILENO, s1); } }
/* files are merged */ static void ex_phones_name_read_fd_write_stdout(Vstr_base *s1, Vstr_base *s2, int fd) { while (TRUE) { int io_w_state = IO_OK; int io_r_state = io_get(s2, fd); if (io_r_state == IO_EOF) break; ex_phones_name_process(s1, s2, FALSE); io_w_state = io_put(s1, 1); io_limit(io_r_state, fd, io_w_state, 1, s1); } }
static void setup_blame_parent_line(struct view *view, struct blame *blame) { char from[SIZEOF_REF + SIZEOF_STR]; char to[SIZEOF_REF + SIZEOF_STR]; const char *diff_tree_argv[] = { "git", "diff", encoding_arg, "--no-textconv", "--no-extdiff", "--no-color", "-U0", from, to, "--", NULL }; struct io io; int parent_lineno = -1; int blamed_lineno = -1; char *line; if (!string_format(from, "%s:%s", view->env->ref, view->env->file) || !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) || !io_run(&io, IO_RD, NULL, opt_env, diff_tree_argv)) return; while ((line = io_get(&io, '\n', TRUE))) { if (*line == '@') { char *pos = strchr(line, '+'); parent_lineno = atoi(line + 4); if (pos) blamed_lineno = atoi(pos + 1); } else if (*line == '+' && parent_lineno != -1) { if (blame->lineno == blamed_lineno - 1 && !strcmp(blame->text, line + 1)) { view->pos.lineno = parent_lineno ? parent_lineno - 1 : 0; break; } blamed_lineno++; } } io_done(&io); }
static void ex_dir_list2html_read_fd_write_fd(Vstr_base *s1, Vstr_base *s2, int rfd, int wfd) { int parsed_header[1] = {FALSE}; int row_num[1] = {0}; while (TRUE) { int io_w_state = IO_OK; int io_r_state = io_get(s2, rfd); if (io_r_state == IO_EOF) break; ex_dir_list2html_process(s1, s2, parsed_header, row_num); io_w_state = io_put(s1, wfd); io_limit(io_r_state, rfd, io_w_state, wfd, s1); } ex_dir_list2html_process_limit(s1, s2, parsed_header, row_num, wfd); }
static void ex_sock_filter_read_fd_write_stdout(Vstr_base *s1, Vstr_base *s2, int fd) { /* read/process/write loop */ while (TRUE) { int io_w_state = IO_OK; int io_r_state = io_get(s2, fd); if (io_r_state == IO_EOF) break; ex_sock_filter_process(s1, s2); io_w_state = io_put(s1, STDOUT_FILENO); io_limit(io_r_state, fd, io_w_state, STDOUT_FILENO, s1); } /* write out all of the end of the file, * so the next file starts on a new line */ ex_sock_filter_process_limit(s1, s2, 0); }
bool index_diff(struct index_diff *diff, bool untracked, bool count_all) { const char *untracked_arg = !untracked ? "--untracked-files=no" : count_all ? "--untracked-files=all" : "--untracked-files=normal"; const char *status_argv[] = { "git", "status", "--porcelain", "-z", untracked_arg, NULL }; struct io io; struct buffer buf; bool ok = TRUE; memset(diff, 0, sizeof(*diff)); if (!io_run(&io, IO_RD, repo.cdup, NULL, status_argv)) return FALSE; while (io_get(&io, &buf, 0, TRUE) && (ok = buf.size > 3)) { if (buf.data[0] == '?') diff->untracked++; else if (buf.data[0] != ' ') diff->staged++; if (buf.data[1] != ' ') diff->unstaged++; if (!count_all && diff->staged && diff->unstaged && (!untracked || diff->untracked)) break; } if (io_error(&io)) ok = FALSE; io_done(&io); return ok; }
void exec( job_t *j ) { process_t *p; pid_t pid; int mypipe[2]; sigset_t chldset; int skip_fork; io_data_t pipe_read, pipe_write; io_data_t *tmp; io_data_t *io_buffer =0; /* Set to 1 if something goes wrong while exec:ing the job, in which case the cleanup code will kick in. */ int exec_error=0; int needs_keepalive = 0; process_t keepalive; CHECK( j, ); CHECK_BLOCK(); if( no_exec ) return; sigemptyset( &chldset ); sigaddset( &chldset, SIGCHLD ); debug( 4, L"Exec job '%ls' with id %d", j->command, j->job_id ); if( block_io ) { if( j->io ) { j->io = io_add( io_duplicate( j, block_io), j->io ); } else { j->io=io_duplicate( j, block_io); } } io_data_t *input_redirect; for( input_redirect = j->io; input_redirect; input_redirect = input_redirect->next ) { if( (input_redirect->io_mode == IO_BUFFER) && input_redirect->is_input ) { /* Input redirection - create a new gobetween process to take care of buffering */ process_t *fake = halloc( j, sizeof(process_t) ); fake->type = INTERNAL_BUFFER; fake->pipe_write_fd = 1; j->first_process->pipe_read_fd = input_redirect->fd; fake->next = j->first_process; j->first_process = fake; break; } } if( j->first_process->type==INTERNAL_EXEC ) { /* Do a regular launch - but without forking first... */ signal_block(); /* setup_child_process makes sure signals are properly set up. It will also call signal_unblock */ if( !setup_child_process( j, 0 ) ) { /* launch_process _never_ returns */ launch_process( j->first_process ); } else { job_set_flag( j, JOB_CONSTRUCTED, 1 ); j->first_process->completed=1; return; } } pipe_read.fd=0; pipe_write.fd=1; pipe_read.io_mode=IO_PIPE; pipe_read.param1.pipe_fd[0] = -1; pipe_read.param1.pipe_fd[1] = -1; pipe_read.is_input = 1; pipe_write.io_mode=IO_PIPE; pipe_write.is_input = 0; pipe_read.next=0; pipe_write.next=0; pipe_write.param1.pipe_fd[0]=pipe_write.param1.pipe_fd[1]=-1; j->io = io_add( j->io, &pipe_write ); signal_block(); /* See if we need to create a group keepalive process. This is a process that we create to make sure that the process group doesn't die accidentally, and is often needed when a builtin/block/function is inside a pipeline, since that usually means we have to wait for one program to exit before continuing in the pipeline, causing the group leader to exit. */ if( job_get_flag( j, JOB_CONTROL ) ) { for( p=j->first_process; p; p = p->next ) { if( p->type != EXTERNAL ) { if( p->next ) { needs_keepalive = 1; break; } if( p != j->first_process ) { needs_keepalive = 1; break; } } } } if( needs_keepalive ) { keepalive.pid = exec_fork(); if( keepalive.pid == 0 ) { keepalive.pid = getpid(); set_child_group( j, &keepalive, 1 ); pause(); exit(0); } else { set_child_group( j, &keepalive, 0 ); } } /* This loop loops over every process_t in the job, starting it as appropriate. This turns out to be rather complex, since a process_t can be one of many rather different things. The loop also has to handle pipelining between the jobs. */ for( p=j->first_process; p; p = p->next ) { mypipe[1]=-1; skip_fork=0; pipe_write.fd = p->pipe_write_fd; pipe_read.fd = p->pipe_read_fd; // debug( 0, L"Pipe created from fd %d to fd %d", pipe_write.fd, pipe_read.fd ); /* This call is used so the global environment variable array is regenerated, if needed, before the fork. That way, we avoid a lot of duplicate work where EVERY child would need to generate it, since that result would not get written back to the parent. This call could be safely removed, but it would result in slightly lower performance - at least on uniprocessor systems. */ if( p->type == EXTERNAL ) env_export_arr( 1 ); /* Set up fd:s that will be used in the pipe */ if( p == j->first_process->next ) { j->io = io_add( j->io, &pipe_read ); } if( p->next ) { // debug( 1, L"%ls|%ls" , p->argv[0], p->next->argv[0]); if( exec_pipe( mypipe ) == -1 ) { debug( 1, PIPE_ERROR ); wperror (L"pipe"); exec_error=1; break; } memcpy( pipe_write.param1.pipe_fd, mypipe, sizeof(int)*2); } else { /* This is the last element of the pipeline. Remove the io redirection for pipe output. */ j->io = io_remove( j->io, &pipe_write ); } switch( p->type ) { case INTERNAL_FUNCTION: { const wchar_t * orig_def; wchar_t * def=0; array_list_t *named_arguments; int shadows; /* Calls to function_get_definition might need to source a file as a part of autoloading, hence there must be no blocks. */ signal_unblock(); orig_def = function_get_definition( p->argv[0] ); named_arguments = function_get_named_arguments( p->argv[0] ); shadows = function_get_shadows( p->argv[0] ); signal_block(); if( orig_def ) { def = halloc_register( j, wcsdup(orig_def) ); } if( def == 0 ) { debug( 0, _( L"Unknown function '%ls'" ), p->argv[0] ); break; } parser_push_block( shadows?FUNCTION_CALL:FUNCTION_CALL_NO_SHADOW ); current_block->param2.function_call_process = p; current_block->param1.function_call_name = halloc_register( current_block, wcsdup( p->argv[0] ) ); /* set_argv might trigger an event handler, hence we need to unblock signals. */ signal_unblock(); parse_util_set_argv( p->argv+1, named_arguments ); signal_block(); parser_forbid_function( p->argv[0] ); if( p->next ) { io_buffer = io_buffer_create( 0 ); j->io = io_add( j->io, io_buffer ); } internal_exec_helper( def, TOP, j->io ); parser_allow_function(); parser_pop_block(); break; } case INTERNAL_BLOCK: { if( p->next ) { io_buffer = io_buffer_create( 0 ); j->io = io_add( j->io, io_buffer ); } internal_exec_helper( p->argv[0], TOP, j->io ); break; } case INTERNAL_BUILTIN: { int builtin_stdin=0; int fg; int close_stdin=0; /* If this is the first process, check the io redirections and see where we should be reading from. */ if( p == j->first_process ) { io_data_t *in = io_get( j->io, 0 ); if( in ) { switch( in->io_mode ) { case IO_FD: { builtin_stdin = in->param1.old_fd; break; } case IO_PIPE: { builtin_stdin = in->param1.pipe_fd[0]; break; } case IO_FILE: { builtin_stdin=wopen( in->param1.filename, in->param2.flags, OPEN_MASK ); if( builtin_stdin == -1 ) { debug( 1, FILE_ERROR, in->param1.filename ); wperror( L"open" ); } else { close_stdin = 1; } break; } case IO_CLOSE: { /* FIXME: When requesting that stdin be closed, we really don't do anything. How should this be handled? */ builtin_stdin = -1; break; } default: { builtin_stdin=-1; debug( 1, _( L"Unknown input redirection type %d" ), in->io_mode); break; } } } } else { builtin_stdin = pipe_read.param1.pipe_fd[0]; } if( builtin_stdin == -1 ) { exec_error=1; break; } else { int old_out = builtin_out_redirect; int old_err = builtin_err_redirect; /* Since this may be the foreground job, and since a builtin may execute another foreground job, we need to pretend to suspend this job while running the builtin, in order to avoid a situation where two jobs are running at once. The reason this is done here, and not by the relevant builtins, is that this way, the builtin does not need to know what job it is part of. It could probably figure that out by walking the job list, but it seems more robust to make exec handle things. */ builtin_push_io( builtin_stdin ); builtin_out_redirect = has_fd( j->io, 1 ); builtin_err_redirect = has_fd( j->io, 2 ); fg = job_get_flag( j, JOB_FOREGROUND ); job_set_flag( j, JOB_FOREGROUND, 0 ); signal_unblock(); p->status = builtin_run( p->argv, j->io ); builtin_out_redirect=old_out; builtin_err_redirect=old_err; signal_block(); /* Restore the fg flag, which is temporarily set to false during builtin execution so as not to confuse some job-handling builtins. */ job_set_flag( j, JOB_FOREGROUND, fg ); } /* If stdin has been redirected, close the redirection stream. */ if( close_stdin ) { exec_close( builtin_stdin ); } break; } } if( exec_error ) { break; } switch( p->type ) { case INTERNAL_BLOCK: case INTERNAL_FUNCTION: { int status = proc_get_last_status(); /* Handle output from a block or function. This usually means do nothing, but in the case of pipes, we have to buffer such io, since otherwise the internal pipe buffer might overflow. */ if( !io_buffer ) { /* No buffer, so we exit directly. This means we have to manually set the exit status. */ if( p->next == 0 ) { proc_set_last_status( job_get_flag( j, JOB_NEGATE )?(!status):status); } p->completed = 1; break; } j->io = io_remove( j->io, io_buffer ); io_buffer_read( io_buffer ); if( io_buffer->param2.out_buffer->used != 0 ) { pid = exec_fork(); if( pid == 0 ) { /* This is the child process. Write out the contents of the pipeline. */ p->pid = getpid(); setup_child_process( j, p ); exec_write_and_exit(io_buffer->fd, io_buffer->param2.out_buffer->buff, io_buffer->param2.out_buffer->used, status); } else { /* This is the parent process. Store away information on the child, and possibly give it control over the terminal. */ p->pid = pid; set_child_group( j, p, 0 ); } } else { if( p->next == 0 ) { proc_set_last_status( job_get_flag( j, JOB_NEGATE )?(!status):status); } p->completed = 1; } io_buffer_destroy( io_buffer ); io_buffer=0; break; } case INTERNAL_BUFFER: { pid = exec_fork(); if( pid == 0 ) { /* This is the child process. Write out the contents of the pipeline. */ p->pid = getpid(); setup_child_process( j, p ); exec_write_and_exit( 1, input_redirect->param2.out_buffer->buff, input_redirect->param2.out_buffer->used, 0); } else { /* This is the parent process. Store away information on the child, and possibly give it control over the terminal. */ p->pid = pid; set_child_group( j, p, 0 ); } break; } case INTERNAL_BUILTIN: { int skip_fork; /* Handle output from builtin commands. In the general case, this means forking of a worker process, that will write out the contents of the stdout and stderr buffers to the correct file descriptor. Since forking is expensive, fish tries to avoid it wehn possible. */ /* If a builtin didn't produce any output, and it is not inside a pipeline, there is no need to fork */ skip_fork = ( !sb_out->used ) && ( !sb_err->used ) && ( !p->next ); /* If the output of a builtin is to be sent to an internal buffer, there is no need to fork. This helps out the performance quite a bit in complex completion code. */ io_data_t *io = io_get( j->io, 1 ); int buffer_stdout = io && io->io_mode == IO_BUFFER; if( ( !sb_err->used ) && ( !p->next ) && ( sb_out->used ) && ( buffer_stdout ) ) { char *res = wcs2str( (wchar_t *)sb_out->buff ); b_append( io->param2.out_buffer, res, strlen( res ) ); skip_fork = 1; free( res ); } for( io = j->io; io; io=io->next ) { if( io->io_mode == IO_FILE && wcscmp(io->param1.filename, L"/dev/null" )) { skip_fork = 0; } } if( skip_fork ) { p->completed=1; if( p->next == 0 ) { debug( 3, L"Set status of %ls to %d using short circut", j->command, p->status ); int status = proc_format_status(p->status); proc_set_last_status( job_get_flag( j, JOB_NEGATE )?(!status):status ); } break; } /* Ok, unfortunatly, we have to do a real fork. Bummer. */ pid = exec_fork(); if( pid == 0 ) { /* This is the child process. Setup redirections, print correct output to stdout and stderr, and then exit. */ p->pid = getpid(); setup_child_process( j, p ); do_builtin_io( sb_out->used ? (wchar_t *)sb_out->buff : 0, sb_err->used ? (wchar_t *)sb_err->buff : 0 ); exit( p->status ); } else { /* This is the parent process. Store away information on the child, and possibly give it control over the terminal. */ p->pid = pid; set_child_group( j, p, 0 ); } break; } case EXTERNAL: { pid = exec_fork(); if( pid == 0 ) { /* This is the child process. */ p->pid = getpid(); setup_child_process( j, p ); launch_process( p ); /* launch_process _never_ returns... */ } else { /* This is the parent process. Store away information on the child, and possibly fice it control over the terminal. */ p->pid = pid; set_child_group( j, p, 0 ); } break; } } if( p->type == INTERNAL_BUILTIN ) builtin_pop_io(); /* Close the pipe the current process uses to read from the previous process_t */ if( pipe_read.param1.pipe_fd[0] >= 0 ) exec_close( pipe_read.param1.pipe_fd[0] ); /* Set up the pipe the next process uses to read from the current process_t */ if( p->next ) pipe_read.param1.pipe_fd[0] = mypipe[0]; /* If there is a next process in the pipeline, close the output end of the current pipe (the surrent child subprocess already has a copy of the pipe - this makes sure we don't leak file descriptors either in the shell or in the children). */ if( p->next ) { exec_close(mypipe[1]); } } /* The keepalive process is no longer needed, so we terminate it with extreme prejudice */ if( needs_keepalive ) { kill( keepalive.pid, SIGKILL ); } signal_unblock(); debug( 3, L"Job is constructed" ); j->io = io_remove( j->io, &pipe_read ); for( tmp = block_io; tmp; tmp=tmp->next ) j->io = io_remove( j->io, tmp ); job_set_flag( j, JOB_CONSTRUCTED, 1 ); if( !job_get_flag( j, JOB_FOREGROUND ) ) { proc_last_bg_pid = j->pgid; } if( !exec_error ) { job_continue (j, 0); } }
/** Check if the IO redirection chains contains redirections for the specified file descriptor */ static int has_fd( io_data_t *d, int fd ) { return io_get( d, fd ) != 0; }
static void read_primitive(Input* in, const char* rest) { for (unsigned i = 0; rest[i]; i++) { int ch = io_get(in); if (ch != rest[i]) RAISE(MALFORMED); } }
static int unclosable_get(void* _self) { UnclosableInput* self = _self; return io_get(self->wrap); }
static void read_number(Input* in, int ch, rich_Sink* to) { bool floating = false; bool negative = false; int64_t integral = 0; double decimal = 0; int exponent = 0; if (ch == '-') { negative = true; ch = io_get(in); } else if (ch == '+') { ch = io_get(in); } // Integral part if (!isdigit(ch)) RAISE(MALFORMED); do { integral = integral*10 + (ch - '0'); ch = io_get(in); } while (isdigit(ch)); // Decimal part if (ch == '.') { floating = true; ch = io_get(in); if (!isdigit(ch)) RAISE(MALFORMED); double power = 0.1; do { decimal += (ch - '0') * power; power /= 10; ch = io_get(in); } while (isdigit(ch)); } // Exponent part if (ch == 'e' || ch == 'E') { floating = true; bool negexp = false; ch = io_get(in); if (ch == '-') { negexp = true; ch = io_get(in); } else if (ch == '+') { ch = io_get(in); } if (!isdigit(ch)) RAISE(MALFORMED); do { exponent = exponent*10 + (ch - '0'); ch = io_get(in); } while (isdigit(ch)); if (negexp) exponent = -exponent; } io_unget(in); if (floating) { double value = (double)integral + decimal; if (negative) value = -value; if (exponent) value = value * pow(10, exponent); call(to, sink, RICH_FLOAT, &value); } else { if (negative) integral = -integral; call(to, sink, RICH_INT, &integral); } }
static inline uint64_t mustget(Input* in) { int c = io_get(in); if (c == -1) RAISE(EOF); return ((uint64_t)c) & 0xFF; }