void io_buffer_t::read() { exec_close(pipe_fd[1]); if (io_mode == IO_BUFFER) { #if 0 if (fcntl( pipe_fd[0], F_SETFL, 0)) { wperror( L"fcntl" ); return; } #endif debug(4, L"io_buffer_t::read: blocking read on fd %d", pipe_fd[0]); while (1) { char b[4096]; long l; l = read_blocked(pipe_fd[0], b, 4096); if (l == 0) { break; } else if (l < 0) { // exec_read_io_buffer is only called on jobs that have exited, and will therefore // never block. But a broken pipe seems to cause some flags to reset, causing the // EOF flag to not be set. Therefore, EAGAIN is ignored and we exit anyway. if (errno != EAGAIN) { debug(1, _(L"An error occured while reading output from code block on file " L"descriptor %d"), pipe_fd[0]); wperror(L"io_buffer_t::read"); } break; } else { out_buffer_append(b, l); } } } }
static void exec_close_1 (void) { using_exec_ops = 0; { struct program_space *ss; struct cleanup *old_chain; old_chain = save_current_program_space (); ALL_PSPACES (ss) { set_current_program_space (ss); /* Delete all target sections. */ resize_section_table (current_target_sections, -resize_section_table (current_target_sections, 0)); exec_close (); } do_cleanups (old_chain); } }
int move_fd_to_unused(int fd, const io_chain_t &io_chain, bool cloexec) { if (fd < 0 || io_chain.get_io_for_fd(fd).get() == NULL) { return fd; } // We have fd >= 0, and it's a conflict. dup it and recurse. Note that we recurse before // anything is closed; this forces the kernel to give us a new one (or report fd exhaustion). int new_fd = fd; int tmp_fd; do { tmp_fd = dup(fd); } while (tmp_fd < 0 && errno == EINTR); assert(tmp_fd != fd); if (tmp_fd < 0) { // Likely fd exhaustion. new_fd = -1; } else { // Ok, we have a new candidate fd. Recurse. If we get a valid fd, either it's the same as // what we gave it, or it's a new fd and what we gave it has been closed. If we get a // negative value, the fd also has been closed. if (cloexec) set_cloexec(tmp_fd); new_fd = move_fd_to_unused(tmp_fd, io_chain); } // We're either returning a new fd or an error. In both cases, we promise to close the old one. assert(new_fd != fd); int saved_errno = errno; exec_close(fd); errno = saved_errno; return new_fd; }
void io_buffer_t::read() { exec_close(pipe_fd[1]); if (io_mode == IO_BUFFER) { debug(4, L"io_buffer_t::read: blocking read on fd %d", pipe_fd[0]); while (1) { char b[4096]; long len = read_blocked(pipe_fd[0], b, 4096); if (len == 0) { break; } else if (len < 0) { // exec_read_io_buffer is only called on jobs that have exited, and will therefore // never block. But a broken pipe seems to cause some flags to reset, causing the // EOF flag to not be set. Therefore, EAGAIN is ignored and we exit anyway. if (errno != EAGAIN) { const wchar_t *fmt = _(L"An error occured while reading output from code block on fd %d"); debug(1, fmt, pipe_fd[0]); wperror(L"io_buffer_t::read"); } break; } else { buffer_.append(&b[0], &b[len]); } } } }
io_buffer_t::~io_buffer_t() { if (pipe_fd[0] >= 0) { exec_close(pipe_fd[0]); } // Dont free fd for writing. This should already be free'd before calling exec_read_io_buffer on // the buffer. }
void exec_file_clear (int from_tty) { /* Remove exec file. */ exec_close (); if (from_tty) printf_unfiltered (_("No executable file now.\n")); }
static int exec_simple_node(t_node *tree, t_shell *sh) { int ret; ret = exec_convert(tree, sh); if (tree->fdtoclose == -1) ret += wait_node(tree, sh); exec_close(tree); return (ret); }
io_buffer_t::~io_buffer_t() { /** If this is an input buffer, then io_read_buffer will not have been called, and we need to close the output fd as well. */ if (is_input) { exec_close(pipe_fd[1]); } exec_close(pipe_fd[0]); /* Dont free fd for writing. This should already be free'd before calling exec_read_io_buffer on the buffer */ }
void io_buffer_destroy(io_data_t *io_buffer) { /** If this is an input buffer, then io_read_buffer will not have been called, and we need to close the output fd as well. */ if (io_buffer->is_input) { exec_close(io_buffer->param1.pipe_fd[1]); } exec_close(io_buffer->param1.pipe_fd[0]); /* Dont free fd for writing. This should already be free'd before calling exec_read_io_buffer on the buffer */ delete io_buffer; }
/* * check_process_limits: checks each running process to see if it's reached * the user selected maximum number of output lines. If so, the processes is * effectively killed */ void check_process_limits(void) { int limit; int i; Process *proc; if ((limit = get_int_var(SHELL_LIMIT_VAR)) && process_list) { for (i = 0; i < process_list_size; i++) { if ((proc = process_list[i]) != NULL) { if (proc->counter >= limit) { proc->p_stdin = exec_close(proc->p_stdin); proc->p_stdout = exec_close(proc->p_stdout); proc->p_stderr = exec_close(proc->p_stderr); if (proc->exited) delete_process(i); } } } } }
/** Free a transmogrified io chain. Only the chain itself and resources used by a transmogrified IO_FILE redirection are freed, since the original chain may still be needed. */ static void io_untransmogrify( io_data_t * in, io_data_t *out ) { if( !out ) return; io_untransmogrify( in->next, out->next ); switch( in->io_mode ) { case IO_FILE: exec_close( out->param1.old_fd ); break; } free(out); }
int main(int argc, char* argv[]) { struct t_exec exec; struct item *item; struct t_var *var; if (argc > 1) { debug_level = atoi(argv[1]); } else { debug_level = 1; } printf("debug_level: %d\n", debug_level); do { if (exec_init(&exec, stdin) < 0) { fprintf(stderr, "Failed to exec\n"); break; } core_apply(&exec); exec.parser.max_output = 100; exec_addfunc2(&exec, "funcA", &myfunc); if (exec_statements(&exec) < 0) { fprintf(stderr, "exec_statements() failed\n"); break; } /* * Print all the vars */ item = exec.vars.first; if (item) { printf("Vars:\n"); while (item) { var = (struct t_var *) item->value; printf(" %s=%s\n", var->name, value_to_s(var->value)); item = item->next; } } } while (0); exec_close(&exec); printf("Done.\n"); return 0; }
io_buffer_t::~io_buffer_t() { //fprintf(stderr, "Deallocating pipes {%d, %d} for %p\n", this->pipe_fd[0], this->pipe_fd[1], this); /** If this is an input buffer, then io_read_buffer will not have been called, and we need to close the output fd as well. */ if (is_input && pipe_fd[1] >= 0) { exec_close(pipe_fd[1]); } if (pipe_fd[0] >= 0) { exec_close(pipe_fd[0]); } /* Dont free fd for writing. This should already be free'd before calling exec_read_io_buffer on the buffer */ }
static void exec_close_1 (int quitting) { int need_symtab_cleanup = 0; struct vmap *vp, *nxt; using_exec_ops = 0; for (nxt = vmap; nxt != NULL;) { vp = nxt; nxt = vp->nxt; /* if there is an objfile associated with this bfd, free_objfile() will do proper cleanup of objfile *and* bfd. */ if (vp->objfile) { free_objfile (vp->objfile); need_symtab_cleanup = 1; } else if (vp->bfd != exec_bfd) /* FIXME-leak: We should be freeing vp->name too, I think. */ gdb_bfd_close_or_warn (vp->bfd); xfree (vp); } vmap = NULL; { struct program_space *ss; struct cleanup *old_chain; old_chain = save_current_program_space (); ALL_PSPACES (ss) { set_current_program_space (ss); /* Delete all target sections. */ resize_section_table (current_target_sections, -resize_section_table (current_target_sections, 0)); exec_close (); } do_cleanups (old_chain); } }
void exec_close_all (struct htlc_conn *htlc) { struct exec_file *execp; int i; for (i = 0; i <= high_fd; i++) { if (FD_ISSET(i, &exec_fds)) { execp = (struct exec_file *)hxd_files[i].conn.ptr; if (execp->htlc == htlc) exec_close(i); } } htlc->nr_execs = 0; }
static void exec_close_1 (struct target_ops *self) { struct program_space *ss; struct cleanup *old_chain; old_chain = save_current_program_space (); ALL_PSPACES (ss) { set_current_program_space (ss); clear_section_table (current_target_sections); exec_close (); } do_cleanups (old_chain); }
static void exec_ready_read (int fd) { struct exec_file *execp = (struct exec_file *)hxd_files[fd].conn.ptr; ssize_t r; u_int8_t buf[16384]; r = read(fd, buf, sizeof(buf)); if (r <= 0) { if (execp->htlc->nr_execs) execp->htlc->nr_execs--; exec_close(fd); } else { cmd_snd_chat(execp->htlc, execp->cid, buf, r); } }
void exec_file_attach (char *filename, int from_tty) { /* Remove any previous exec file. */ exec_close (); if (!ptid_equal (inferior_ptid, null_ptid)) { target_kill (); init_thread_list (); struct program_space *ss; ALL_PSPACES (ss) { set_current_program_space (ss); breakpoint_program_space_exit (ss); } symbol_file_clear (0); }
/** Close all fds in open_fds, except for those that are mentioned in the redirection list io. This should make sure that there are no stray opened file descriptors in the child. \param io the list of io redirections for this job. Pipes mentioned here should not be closed. */ static void close_unused_internal_pipes( io_data_t *io ) { int i=0; if( open_fds ) { for( ;i<al_get_count( open_fds ); i++ ) { int n = (long)al_get_long( open_fds, i ); if( !use_fd_in_pipe( n, io) ) { debug( 4, L"Close fd %d, used in other context", n ); exec_close( n ); i--; } } } }
int exec_node(t_node *tree, t_shell *sh) { t_ntype types[EXEC_FUNC_N]; int (*func[EXEC_FUNC_N])(t_node *, t_shell *); int i; if (tree->type == node_filename) return (exec_close(tree)); init_tab(types, func); exec_convert(NULL, sh); i = 0; while (i < EXEC_FUNC_N) { if (tree->type == types[i]) return (func[i](tree, sh)); i++; } return (EXIT_FAILURE); }
static void exec_close_1 (int quitting) { struct vmap *vp, *nxt; using_exec_ops = 0; for (nxt = vmap; nxt != NULL;) { vp = nxt; nxt = vp->nxt; if (vp->objfile) free_objfile (vp->objfile); gdb_bfd_unref (vp->bfd); xfree (vp); } vmap = NULL; { struct program_space *ss; struct cleanup *old_chain; old_chain = save_current_program_space (); ALL_PSPACES (ss) { set_current_program_space (ss); /* Delete all target sections. */ resize_section_table (current_target_sections, -resize_section_table (current_target_sections, 0)); exec_close (); } do_cleanups (old_chain); } }
int exec_tree(t_node *tree, t_shell *sh) { int ret; if (tree == NULL || sh == NULL || tree->pid != -1) return (EXIT_SUCCESS); reset_fd_save(sh); ret = exec_node(tree, sh); if (tree->type >= node_redirect_r && tree->type <= node_redirect_dl) { if (tree->left != NULL && tree->left->pid == -1) ret += exec_node(tree->left, sh); if (tree->right != NULL && tree->right->pid == -1) ret += exec_node(tree->right, sh); } exec_close(tree); reset_fd_restore(sh); if (ret) return (EXIT_FAILURE); return (EXIT_SUCCESS); }
int main(int argc, char* argv[]) { struct t_exec exec; do { if (exec_init(&exec, stdin) < 0) { fprintf(stderr, "Failed to exec\n"); break; } core_apply(&exec); exec.parser.max_output = 100; if (exec_statements(&exec) < 0) { break; } } while (0); exec_close(&exec); return 0; }
static bool pipe_avoid_conflicts_with_io_chain(int fds[2], const io_chain_t &ios) { bool success = true; for (int i = 0; i < 2; i++) { fds[i] = move_fd_to_unused(fds[i], ios); if (fds[i] < 0) { success = false; break; } } // If any fd failed, close all valid fds. if (!success) { int saved_errno = errno; for (int i = 0; i < 2; i++) { if (fds[i] >= 0) { exec_close(fds[i]); fds[i] = -1; } } errno = saved_errno; } return success; }
/** Set up a childs io redirections. Should only be called by setup_child_process(). Does the following: First it closes any open file descriptors not related to the child by calling close_unused_internal_pipes() and closing the universal variable server file descriptor. It then goes on to perform all the redirections described by \c io. \param io the list of IO redirections for the child \return 0 on sucess, -1 on failiure */ static int handle_child_io(const io_chain_t &io_chain) { for (size_t idx = 0; idx < io_chain.size(); idx++) { const io_data_t *io = io_chain.at(idx).get(); int tmp; if (io->io_mode == IO_FD && io->fd == static_cast<const io_fd_t*>(io)->old_fd) { continue; } switch (io->io_mode) { case IO_CLOSE: { if (log_redirections) fprintf(stderr, "%d: close %d\n", getpid(), io->fd); if (close(io->fd)) { debug_safe_int(0, "Failed to close file descriptor %s", io->fd); safe_perror("close"); } break; } case IO_FILE: { // Here we definitely do not want to set CLO_EXEC because our child needs access CAST_INIT(const io_file_t *, io_file, io); if ((tmp=open(io_file->filename_cstr, io_file->flags, OPEN_MASK))==-1) { if ((io_file->flags & O_EXCL) && (errno ==EEXIST)) { debug_safe(1, NOCLOB_ERROR, io_file->filename_cstr); } else { debug_safe(1, FILE_ERROR, io_file->filename_cstr); safe_perror("open"); } return -1; } else if (tmp != io->fd) { /* This call will sometimes fail, but that is ok, this is just a precausion. */ close(io->fd); if (dup2(tmp, io->fd) == -1) { debug_safe_int(1, FD_ERROR, io->fd); safe_perror("dup2"); return -1; } exec_close(tmp); } break; } case IO_FD: { int old_fd = static_cast<const io_fd_t *>(io)->old_fd; if (log_redirections) fprintf(stderr, "%d: fd dup %d to %d\n", getpid(), old_fd, io->fd); /* This call will sometimes fail, but that is ok, this is just a precausion. */ close(io->fd); if (dup2(old_fd, io->fd) == -1) { debug_safe_int(1, FD_ERROR, io->fd); safe_perror("dup2"); return -1; } break; } case IO_BUFFER: case IO_PIPE: { CAST_INIT(const io_pipe_t *, io_pipe, io); /* If write_pipe_idx is 0, it means we're connecting to the read end (first pipe fd). If it's 1, we're connecting to the write end (second pipe fd). */ unsigned int write_pipe_idx = (io_pipe->is_input ? 0 : 1); /* debug( 0, L"%ls %ls on fd %d (%d %d)", write_pipe?L"write":L"read", (io->io_mode == IO_BUFFER)?L"buffer":L"pipe", io->fd, io->pipe_fd[0], io->pipe_fd[1]); */ if (log_redirections) fprintf(stderr, "%d: %s dup %d to %d\n", getpid(), io->io_mode == IO_BUFFER ? "buffer" : "pipe", io_pipe->pipe_fd[write_pipe_idx], io->fd); if (dup2(io_pipe->pipe_fd[write_pipe_idx], io->fd) != io->fd) { debug_safe(1, LOCAL_PIPE_ERROR); safe_perror("dup2"); return -1; } if (io_pipe->pipe_fd[0] >= 0) exec_close(io_pipe->pipe_fd[0]); if (io_pipe->pipe_fd[1] >= 0) exec_close(io_pipe->pipe_fd[1]); break; } } } return 0; }
void exec_file_attach (char *filename, int from_tty) { /* Remove any previous exec file. */ exec_close (); /* Now open and digest the file the user requested, if any. */ if (!filename) { if (from_tty) printf_unfiltered (_("No executable file now.\n")); set_gdbarch_from_file (NULL); } else { struct cleanup *cleanups; char *scratch_pathname, *canonical_pathname; int scratch_chan; struct target_section *sections = NULL, *sections_end = NULL; char **matching; scratch_chan = openp (getenv ("PATH"), OPF_TRY_CWD_FIRST, filename, write_files ? O_RDWR | O_BINARY : O_RDONLY | O_BINARY, &scratch_pathname); #if defined(__GO32__) || defined(_WIN32) || defined(__CYGWIN__) if (scratch_chan < 0) { char *exename = alloca (strlen (filename) + 5); strcat (strcpy (exename, filename), ".exe"); scratch_chan = openp (getenv ("PATH"), OPF_TRY_CWD_FIRST, exename, write_files ? O_RDWR | O_BINARY : O_RDONLY | O_BINARY, &scratch_pathname); } #endif if (scratch_chan < 0) perror_with_name (filename); cleanups = make_cleanup (xfree, scratch_pathname); /* gdb_bfd_open (and its variants) prefers canonicalized pathname for better BFD caching. */ canonical_pathname = gdb_realpath (scratch_pathname); make_cleanup (xfree, canonical_pathname); if (write_files) exec_bfd = gdb_bfd_fopen (canonical_pathname, gnutarget, FOPEN_RUB, scratch_chan); else exec_bfd = gdb_bfd_open (canonical_pathname, gnutarget, scratch_chan); if (!exec_bfd) { error (_("\"%s\": could not open as an executable file: %s"), scratch_pathname, bfd_errmsg (bfd_get_error ())); } gdb_assert (exec_filename == NULL); exec_filename = gdb_realpath_keepfile (scratch_pathname); if (!bfd_check_format_matches (exec_bfd, bfd_object, &matching)) { /* Make sure to close exec_bfd, or else "run" might try to use it. */ exec_close (); error (_("\"%s\": not in executable format: %s"), scratch_pathname, gdb_bfd_errmsg (bfd_get_error (), matching)); } if (build_section_table (exec_bfd, §ions, §ions_end)) { /* Make sure to close exec_bfd, or else "run" might try to use it. */ exec_close (); error (_("\"%s\": can't find the file sections: %s"), scratch_pathname, bfd_errmsg (bfd_get_error ())); } exec_bfd_mtime = bfd_get_mtime (exec_bfd); validate_files (); set_gdbarch_from_file (exec_bfd); /* Add the executable's sections to the current address spaces' list of sections. This possibly pushes the exec_ops target. */ add_target_sections (&exec_bfd, sections, sections_end); xfree (sections); /* Tell display code (if any) about the changed file name. */ if (deprecated_exec_file_display_hook) (*deprecated_exec_file_display_hook) (filename); do_cleanups (cleanups); } bfd_cache_close_all (); observer_notify_executable_changed (); }
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); } }
/** Set up a childs io redirections. Should only be called by setup_child_process(). Does the following: First it closes any open file descriptors not related to the child by calling close_unused_internal_pipes() and closing the universal variable server file descriptor. It then goes on to perform all the redirections described by \c io. \param io the list of IO redirections for the child \return 0 on sucess, -1 on failiure */ static int handle_child_io( io_data_t *io ) { close_unused_internal_pipes( io ); for( ; io; io=io->next ) { int tmp; if( io->io_mode == IO_FD && io->fd == io->param1.old_fd ) { continue; } if( io->fd > 2 ) { /* Make sure the fd used by this redirection is not used by e.g. a pipe. */ free_fd( io, io->fd ); } switch( io->io_mode ) { case IO_CLOSE: { if( close(io->fd) ) { debug( 0, _(L"Failed to close file descriptor %d"), io->fd ); wperror( L"close" ); } break; } case IO_FILE: { if( (tmp=wopen( io->param1.filename, io->param2.flags, OPEN_MASK ) )==-1 ) { if( ( io->param2.flags & O_EXCL ) && ( errno ==EEXIST ) ) { debug( 1, NOCLOB_ERROR, io->param1.filename ); } else { debug( 1, FILE_ERROR, io->param1.filename ); wperror( L"open" ); } return -1; } else if( tmp != io->fd) { /* This call will sometimes fail, but that is ok, this is just a precausion. */ close(io->fd); if(dup2( tmp, io->fd ) == -1 ) { debug( 1, FD_ERROR, io->fd ); wperror( L"dup2" ); return -1; } exec_close( tmp ); } break; } case IO_FD: { /* This call will sometimes fail, but that is ok, this is just a precausion. */ close(io->fd); if( dup2( io->param1.old_fd, io->fd ) == -1 ) { debug( 1, FD_ERROR, io->fd ); wperror( L"dup2" ); return -1; } break; } case IO_BUFFER: case IO_PIPE: { int write_pipe; write_pipe = !io->is_input; /* debug( 0, L"%ls %ls on fd %d (%d %d)", write_pipe?L"write":L"read", (io->io_mode == IO_BUFFER)?L"buffer":L"pipe", io->fd, io->param1.pipe_fd[0], io->param1.pipe_fd[1]); */ if( dup2( io->param1.pipe_fd[write_pipe], io->fd ) != io->fd ) { debug( 1, PIPE_ERROR ); wperror( L"dup2" ); return -1; } if( write_pipe ) { exec_close( io->param1.pipe_fd[0]); exec_close( io->param1.pipe_fd[1]); } else { exec_close( io->param1.pipe_fd[0] ); } break; } } } return 0; }
void exec_file_attach (const char *filename, int from_tty) { struct cleanup *cleanups; /* First, acquire a reference to the current exec_bfd. We release this at the end of the function; but acquiring it now lets the BFD cache return it if this call refers to the same file. */ gdb_bfd_ref (exec_bfd); cleanups = make_cleanup_bfd_unref (exec_bfd); /* Remove any previous exec file. */ exec_close (); /* Now open and digest the file the user requested, if any. */ if (!filename) { if (from_tty) printf_unfiltered (_("No executable file now.\n")); set_gdbarch_from_file (NULL); } else { int load_via_target = 0; char *scratch_pathname, *canonical_pathname; int scratch_chan; struct target_section *sections = NULL, *sections_end = NULL; char **matching; if (is_target_filename (filename)) { if (target_filesystem_is_local ()) filename += strlen (TARGET_SYSROOT_PREFIX); else load_via_target = 1; } if (load_via_target) { /* gdb_bfd_fopen does not support "target:" filenames. */ if (write_files) warning (_("writing into executable files is " "not supported for %s sysroots"), TARGET_SYSROOT_PREFIX); scratch_pathname = xstrdup (filename); make_cleanup (xfree, scratch_pathname); scratch_chan = -1; canonical_pathname = scratch_pathname; } else { scratch_chan = openp (getenv ("PATH"), OPF_TRY_CWD_FIRST, filename, write_files ? O_RDWR | O_BINARY : O_RDONLY | O_BINARY, &scratch_pathname); #if defined(__GO32__) || defined(_WIN32) || defined(__CYGWIN__) if (scratch_chan < 0) { char *exename = alloca (strlen (filename) + 5); strcat (strcpy (exename, filename), ".exe"); scratch_chan = openp (getenv ("PATH"), OPF_TRY_CWD_FIRST, exename, write_files ? O_RDWR | O_BINARY : O_RDONLY | O_BINARY, &scratch_pathname); } #endif if (scratch_chan < 0) perror_with_name (filename); make_cleanup (xfree, scratch_pathname); /* gdb_bfd_open (and its variants) prefers canonicalized pathname for better BFD caching. */ canonical_pathname = gdb_realpath (scratch_pathname); make_cleanup (xfree, canonical_pathname); } if (write_files && !load_via_target) exec_bfd = gdb_bfd_fopen (canonical_pathname, gnutarget, FOPEN_RUB, scratch_chan); else exec_bfd = gdb_bfd_open (canonical_pathname, gnutarget, scratch_chan); if (!exec_bfd) { error (_("\"%s\": could not open as an executable file: %s"), scratch_pathname, bfd_errmsg (bfd_get_error ())); } /* gdb_realpath_keepfile resolves symlinks on the local filesystem and so cannot be used for "target:" files. */ gdb_assert (exec_filename == NULL); if (load_via_target) exec_filename = xstrdup (bfd_get_filename (exec_bfd)); else exec_filename = gdb_realpath_keepfile (scratch_pathname); if (!bfd_check_format_matches (exec_bfd, bfd_object, &matching)) { /* Make sure to close exec_bfd, or else "run" might try to use it. */ exec_close (); error (_("\"%s\": not in executable format: %s"), scratch_pathname, gdb_bfd_errmsg (bfd_get_error (), matching)); } if (build_section_table (exec_bfd, §ions, §ions_end)) { /* Make sure to close exec_bfd, or else "run" might try to use it. */ exec_close (); error (_("\"%s\": can't find the file sections: %s"), scratch_pathname, bfd_errmsg (bfd_get_error ())); } exec_bfd_mtime = bfd_get_mtime (exec_bfd); validate_files (); set_gdbarch_from_file (exec_bfd); /* Add the executable's sections to the current address spaces' list of sections. This possibly pushes the exec_ops target. */ add_target_sections (&exec_bfd, sections, sections_end); xfree (sections); /* Tell display code (if any) about the changed file name. */ if (deprecated_exec_file_display_hook) (*deprecated_exec_file_display_hook) (filename); } do_cleanups (cleanups); bfd_cache_close_all (); observer_notify_executable_changed (); }
void exec_file_attach (char *filename, int from_tty) { /* Remove any previous exec file. */ exec_close (); /* Now open and digest the file the user requested, if any. */ if (!filename) { if (from_tty) printf_unfiltered (_("No executable file now.\n")); set_gdbarch_from_file (NULL); } else { struct cleanup *cleanups; char *scratch_pathname; int scratch_chan; struct target_section *sections = NULL, *sections_end = NULL; char **matching; scratch_chan = openp (getenv ("PATH"), OPF_TRY_CWD_FIRST, filename, write_files ? O_RDWR | O_BINARY : O_RDONLY | O_BINARY, &scratch_pathname); #if defined(__GO32__) || defined(_WIN32) || defined(__CYGWIN__) if (scratch_chan < 0) { char *exename = alloca (strlen (filename) + 5); strcat (strcpy (exename, filename), ".exe"); scratch_chan = openp (getenv ("PATH"), OPF_TRY_CWD_FIRST, exename, write_files ? O_RDWR | O_BINARY : O_RDONLY | O_BINARY, &scratch_pathname); } #endif if (scratch_chan < 0) perror_with_name (filename); exec_bfd = bfd_fopen (scratch_pathname, gnutarget, write_files ? FOPEN_RUB : FOPEN_RB, scratch_chan); if (!exec_bfd) { close (scratch_chan); error (_("\"%s\": could not open as an executable file: %s"), scratch_pathname, bfd_errmsg (bfd_get_error ())); } /* At this point, scratch_pathname and exec_bfd->name both point to the same malloc'd string. However exec_close() will attempt to free it via the exec_bfd->name pointer, so we need to make another copy and leave exec_bfd as the new owner of the original copy. */ scratch_pathname = xstrdup (scratch_pathname); cleanups = make_cleanup (xfree, scratch_pathname); if (!bfd_check_format_matches (exec_bfd, bfd_object, &matching)) { /* Make sure to close exec_bfd, or else "run" might try to use it. */ exec_close (); error (_("\"%s\": not in executable format: %s"), scratch_pathname, gdb_bfd_errmsg (bfd_get_error (), matching)); } /* FIXME - This should only be run for RS6000, but the ifdef is a poor way to accomplish. */ #ifdef DEPRECATED_IBM6000_TARGET /* Setup initial vmap. */ map_vmap (exec_bfd, 0); if (vmap == NULL) { /* Make sure to close exec_bfd, or else "run" might try to use it. */ exec_close (); error (_("\"%s\": can't find the file sections: %s"), scratch_pathname, bfd_errmsg (bfd_get_error ())); } #endif /* DEPRECATED_IBM6000_TARGET */ if (build_section_table (exec_bfd, §ions, §ions_end)) { /* Make sure to close exec_bfd, or else "run" might try to use it. */ exec_close (); error (_("\"%s\": can't find the file sections: %s"), scratch_pathname, bfd_errmsg (bfd_get_error ())); } exec_bfd_mtime = bfd_get_mtime (exec_bfd); validate_files (); set_gdbarch_from_file (exec_bfd); /* Add the executable's sections to the current address spaces' list of sections. This possibly pushes the exec_ops target. */ add_target_sections (sections, sections_end); xfree (sections); /* Tell display code (if any) about the changed file name. */ if (deprecated_exec_file_display_hook) (*deprecated_exec_file_display_hook) (filename); do_cleanups (cleanups); } bfd_cache_close_all (); observer_notify_executable_changed (); }