Exemplo n.º 1
0
void		ft_fork(t_process *p, t_gen *env)
{
	pid_t	test;

	if (ft_checkbuiltin(p, env) == 1)
		env->status = ft_run_builtin(p, env);
	else
	{
		env->pid_fork = 0;
		env->pid_fork = fork();
		if (env->pid_fork == 0)
			launch_process(p, env);
		else if (env->pid_fork < 0)
		{
			ft_forkerror(p, env);
			exit(1);
		}
		else
		{
			if ((test = waitpid(env->pid_fork, &(env->status), 0)) == -1)
			{
				env->ret = EEXECV;
				error(p, 0);
			}
			ft_printf("return of wait = %d, status = %d, pid = %d\n", test, WEXITSTATUS(env->status), env->pid_fork);
		}
	}
	if (env->path != NULL)
		free(env->path);
}
Exemplo n.º 2
0
void launch_job (job *j, int foreground) {
	process *p;
	pid_t pid;
	int mypipe[2], infile, outfile;

	infile = j->stdin;
	for (p = j->first_process; p; p = p->next) {
		/* Set up pipes, if necessary.  */
		if (p->next) {
			if (pipe (mypipe) < 0) {
				perror ("pipe");
				exit (1);
			}
			outfile = mypipe[1];
		}
		else
			outfile = j->stdout;

		/* Fork the child processes.  */
		pid = fork ();
		if (pid == 0)
			/* This is the child process.  */
			launch_process (p, j->pgid, infile, outfile, j->stderr, foreground);
		else if (pid < 0) {
			/* The fork failed.  */
			perror ("fork");
			exit (1);
		}
		else {
			/* This is the parent process.  */
			p->pid = pid;
			if (shell_is_interactive) {
				if (!j->pgid)
				j->pgid = pid;
				setpgid (pid, j->pgid);
			}
		}

		/* Clean up after pipes.  */
		if (infile != j->stdin)
			close (infile);
		if (outfile != j->stdout)
			close (outfile);

		infile = mypipe[0];
	}

	format_job_info (j, "launched");

	if (!shell_is_interactive)
		wait_for_job (j);
	else if (foreground)
		put_job_in_foreground (j, 0);
	else
		put_job_in_background (j, 0);
}
int
shell( int argc, char *argv[] ) {

  init_shell(); // initialize the shell
  
  pid_t pid = getpid();	       // get current processe's PID
  pid_t ppid = getppid();      // get parent's PID 
  pid_t cpid, tcpid, cpgid;

  print_welcome( argv[0], pid, ppid );
  print_prompt();
  char *s = malloc(INPUT_STRING_SIZE + 1); // user input string
  
  while( (s = freadln(stdin)) ){ // read in the input string
    process *p = create_process( s );
    if( p != NULL ){ // do we need to run a newly created process?
      cpid = fork(); // fork off a child
      if( cpid == 0 ) { // child
	p->pid = getpid();
	launch_process( p );
      } // if( cpid == 0 )
      else if( cpid > 0 ){ // parent
	p->pid = cpid;
	if( shell_is_interactive ){ // are we running shell from a terminal?
	  // put 'p' into its own process group
	  // since our shell is not supporting pipes, we treat
	  // each process by itself as a 'job' to be done
	  if( setpgid( cpid, cpid ) < 0 ) 
	    printf( "Failed to put the child into its own process group.\n" );
	  if( p->background )
	    put_in_background( p, false );
	  else
	    put_in_foreground( p, false );
	} // if( shell_is_interactive )
	else
	  wait_for_process( p );
      } // else if( cpid > 0 )
      else // fork() failed
	printf( "fork() failed\n" );
    } // if( p != NULL )
    print_prompt();
  } // while

  return EXIT_SUCCESS;
} // shell
Exemplo n.º 4
0
void terminal_cmd(tok_t arg[]) {

    int status;
    process *p=create_process(arg);
    add_process(p);
    latest_process=p;


    pid_t id=fork();

    if(id==0) {

        latest_process->pid=getpid();
        launch_process(latest_process);

    } else if(id>0) {
        latest_process->pid=id;
        //desc_process(latest_process);

        if(latest_process->background) {
            fprintf(stdout,"ID: %d running in background\n",latest_process->pid);
            waitpid(id,&(latest_process->status),WNOHANG | WUNTRACED);
        } else {
            waitpid(id,&(latest_process->status),WUNTRACED);
            tcsetattr(shell_terminal,TCSADRAIN,&shell_tmodes);
            tcsetpgrp(shell_terminal,shell_pgid);

        }

        if(WEXITSTATUS(latest_process->status)==EXIT_FAILURE) {
            if(latest_process->prev) {
                latest_process=p->prev;
                free(p);
            } else {
                first_process=latest_process=NULL;
                free(p);
            }

        }

    } else if(id<0) {
        fprintf(stderr,"failed to fork\n");
    }
}
Exemplo n.º 5
0
int execute(char **args) {
    int status,
        i,
        infile,
        outfile,
        new_pipe[2];
    pid_t pid;

    /*check for shell builtins*/
    for (i = 0; i < num_builtins(); i++) {
        if (strcmp(args[0], bshell_builtins[i]) == 0){
            return (*builtin_funcs[i])(args);
        }
     }

    /*if not shell builtin, execute here*/
    status = launch_process(args);
    return status;
}
Exemplo n.º 6
0
            void start() {
                int pipeEnds[ 2 ];
                assert( pipe( pipeEnds ) != -1 );
                
                fflush( 0 );
                launch_process(pipeEnds[1]); //sets pid_
                
                {
                    stringstream ss;
                    ss << "shell: started program";
                    for (unsigned i=0; i < argv_.size(); i++)
                        ss << " " << argv_[i];
                    ss << '\n';
                    cout << ss.str(); cout.flush();
                }

                if ( port_ > 0 )
                    dbs.insert( make_pair( port_, make_pair( pid_, pipeEnds[ 1 ] ) ) );
                else
                    shells.insert( make_pair( pid_, pipeEnds[ 1 ] ) );
                pipe_ = pipeEnds[ 0 ];
            }
Exemplo n.º 7
0
void run_program(tok_t *t, char *s) {
  // execute another program specified in command
  process* proc;
  if ((proc = create_process(s)) != NULL) {
    add_process(proc);
    pid_t pid = fork();
    // both parent and child should set put the child into its own process group
    if (pid == 0) {
      proc->pid = getpid();
      launch_process(proc);
    } else {
      proc->pid = pid;
      if (shell_is_interactive) {
        setpgid(proc->pid, proc->pid);
      }
      if (proc->background) {
        put_process_in_background(proc, false);
      } else {
        put_process_in_foreground(proc, false);
      }
    }
  }
}
Exemplo n.º 8
0
Arquivo: parser.c Projeto: Zethir/42sh
void			exec_job(t_shell *sh, t_job *job)
{
	t_job	*tmp;

	tmp = job;
	reset_term_no_free(sh);
	while (job)
	{
		launch_process(sh, job);
		if (!job_success(job) && job->linker == AND)
		{
			while (job->next && job->linker == AND)
				job = job->next;
		}
		else if (job_success(job) && job->linker == OR)
		{
			while (job->next && job->linker == OR)
				job = job->next;
		}
		job = job->next;
	}
	job = tmp;
	free_job(job);
}
Exemplo n.º 9
0
Arquivo: exec.c Projeto: CodeMonk/fish
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);
	}
	
}
Exemplo n.º 10
0
int idaapi maclnx_launch_process(
        debmod_t *debmod,
        const char *path,
        const char *args,
        const char *startdir,
        int flags,
        const char *input_path,
        uint32 input_file_crc32,
        void **child_pid)
{
  // immediately switch to the startdir because path/input_path may be relative.
  if ( startdir[0] != '\0' && chdir(startdir) == -1 )
  {
    debmod->dmsg("chdir '%s': %s\n", startdir, winerr(errno));
    return -2;
  }

  // input file specified in the database does not exist
  if ( input_path[0] != '\0' && !qfileexist(input_path) )
    return -2;

  // temporary thing, later we will retrieve the real file name
  // based on the process id
  debmod->input_file_path = input_path;
  debmod->is_dll = (flags & DBG_PROC_IS_DLL) != 0;

  // Parse the program path and extract in/out redirection info
  qstring wpath, redir_in, redir_out;
  bool append_out;
  if ( parse_apppath(path, &wpath, &redir_in, &redir_out, &append_out) )
    path = wpath.c_str();

  if ( !qfileexist(path) )
  {
    debmod->dmsg("%s: %s\n", path, winerr(errno));
    return -1;
  }

  int mismatch = 0;
  if ( !debmod->check_input_file_crc32(input_file_crc32) )
    mismatch = CRC32_MISMATCH;

  launch_process_params_t lpi;
  lpi.cb = sizeof(lpi);

  // Input redir?
  if ( !redir_in.empty() )
  {
    lpi.in_handle = open(redir_in.c_str(), O_RDONLY);
    if ( lpi.in_handle == -1 )
    {
      debmod->dmsg("Failed to open input redirection file '%s': %s\n", redir_in.c_str(), winerr(errno));
      return -1;
    }
  }

  // Output redir?
  if ( !redir_out.empty() )
  {
    lpi.out_handle = open(
      redir_out.c_str(),
      O_CREAT | O_WRONLY | (append_out ? O_APPEND : 0),
      S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
    if ( lpi.out_handle == -1 )
    {
      if ( lpi.in_handle != -1 )
        close(lpi.in_handle);

      debmod->dmsg("Failed to open output redirection file '%s': %s\n", redir_out.c_str(), winerr(errno));
      return -1;
    }
    lpi.err_handle = lpi.out_handle;
  }

  qstring errbuf;
  lpi.path = path;
  lpi.args = args;
  lpi.flags = LP_TRACE;
  *child_pid = launch_process(lpi, &errbuf);

  // Close redir files
  if ( lpi.in_handle != -1 )
    close(lpi.in_handle);
  if ( lpi.out_handle != -1 )
    close(lpi.out_handle);

  if ( *child_pid == NULL )
  {
    debmod->dmsg("launch_process: %s", errbuf.c_str());
    return -1;
  }
  return 1 | mismatch;
}
Exemplo n.º 11
0
int shell (int argc, char *argv[]) {
  char *s = malloc(INPUT_STRING_SIZE+1);			/* user input string */
  char *s2 = malloc(INPUT_STRING_SIZE+1);
  tok_t *t;			/* tokens parsed from parsed input */
  tok_t *t_input; 			/* tokesn parsed from input */
  int lineNum = 0;
  int fundex = -1;
  pid_t pid = getpid();		/* get current processes PID */
  pid_t ppid = getppid();	/* get parents PID */
  pid_t cpid, tcpid, cpgid;
  char cwd[1000];
  init_process_list();
  init_shell();
  int pipe_num = 0;
  printf("%s running as PID %d under %d\n",argv[0],pid,ppid);
  process *p;
  process *next_p;
  lineNum=0;
  fprintf(stdout, "%d: ", lineNum);
  while ((s = freadln(stdin))){
    process *pi;

    p = create_process(s);
    add_process(p);	
    
   process* q;
   q = first_process;

   shell_is_interactive = isatty(shell_terminal);
   if(shell_is_interactive){ 

	next_p = first_process;

	while((next_p->next != NULL)){
		
		if(next_p->pid == 0 ){
			break;	
		}
		else
			next_p = next_p->next;
	}

	

	if(next_p != NULL){
		fundex = lookup(next_p->argv[0]); /* Is first token a shell literal */
		if(fundex >= 0){ 
			cmd_table[fundex].fun(&(next_p->argv[1]));
			next_p->completed = 1;
		}
		else if( next_p->argv[0] == NULL){
			next_p->completed = 1;
		}
		else {
		  launch_process(p);
		 }
	}

	
	for (pi = first_process; pi; pi = pi->next){
		if(pi->stopped == 1){
			if(pi->background == 1)
				printf("bg pid: %d stopped\n", pi->pid);
			else
				printf("fg pid: %d stopped\n", pi->pid);

		}
		if(pi->completed == 1){
			if(pi->background == 1)
				printf("bg pid: %d completed\n", pi->pid);
			else{}		
			//	printf("fg pid: %d completed\n", pi->pid);
		}
	}


	purge_proc_list();
	

    getcwd(cwd,1000);
    fprintf(stdout, "%s %d: ", cwd, lineNum); 

   }


  }
  return 0;
}
//--------------------------------------------------------------------------
bool win32_debmod_t::create_process(
    const char *path,
    const char *args,
    const char *startdir,
    bool is_gui,
    PROCESS_INFORMATION *ProcessInformation)
{
#ifndef __X64__
  linput_t *li = open_linput(path, false);
  if ( li == NULL )
    return false;

  pe_loader_t pl;
  pl.read_header(li, true);
  close_linput(li);
  if ( pl.pe.is_pe_plus() )
  {
    static const char server_name[] = "win64_remotex64.exe";
#ifdef __EA64__
    if ( askyn_c(1, "AUTOHIDE REGISTRY\nHIDECANCEL\nDebugging 64-bit applications is only possible with the %s server. Launch it now?", server_name) == 1 ) do
    {
      // Switch to the remote win32 debugger
      if ( !load_debugger("win32_stub", true))
      {
        warning("Failed to switch to the remote windows debugger!");
        break;
      }

      // Form the server path
      char server_exe[QMAXPATH];
      qmakepath(server_exe, sizeof(server_exe), idadir(NULL), server_name, NULL);

      // Try to launch the server
      STARTUPINFO si = {sizeof(si)};
      PROCESS_INFORMATION pi;
      if ( !::CreateProcess(server_exe, NULL, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi) )
      {
        warning("Failed to run the 64-bit remote server!");
        break;
      }

      // Set the remote debugging options: localhost
      set_remote_debugger("localhost", "", -1);

      // Notify the user
      info("Debugging server has been started, please try debugging the program again.");
    } while ( false );
#else
    dwarning("AUTOHIDE NONE\n"
      "Please use %s remote server to debug 64-bit applications", server_name);
#endif // __EA64__
    SetLastError(ERROR_NOT_SUPPORTED);
    return false;
  }
#endif // __X64__

  // Empty directory means our directory
  if ( startdir != NULL && startdir[0] == '\0' )
    startdir = NULL;

  // Args passed as empty string?
  if ( args != NULL && args[0] == '\0' )
    args = NULL;

  launch_process_params_t lpp;
  lpp.flags |= LP_TRACE | LP_PATH_WITH_ARGS;
  if ( !is_gui )
    lpp.flags |= LP_NEW_CONSOLE;
  lpp.path = path;
  lpp.args = args;
  lpp.startdir = startdir;
  lpp.info = ProcessInformation;

  qstring errbuf;
  if ( launch_process(lpp, &errbuf) == NULL )
  {
    dwarning("AUTOHIDE NONE\n%s", errbuf.c_str());
    return false;
  }
  return true;
}
Exemplo n.º 13
0
int idaapi maclnx_launch_process(
        debmod_t *debmod,
        const char *path,
        const char *args,
        const char *startdir,
        int flags,
        const char *input_path,
        uint32 input_file_crc32,
        void **child_pid)
{
  // prepare full path if the input_path is relative
  char full_input[QMAXPATH];
  if ( startdir[0] != '\0' && !qisabspath(input_path) )
  {
    qmake_full_path(full_input, sizeof(full_input), input_path);
    input_path = full_input;
  }

  // input file specified in the database does not exist
  if ( input_path[0] != '\0' && !qfileexist(input_path) )
  {
    debmod->dwarning("AUTOHIDE NONE\nInput file is missing: %s", input_path);
    return -2;
  }

  // temporary thing, later we will retrieve the real file name
  // based on the process id
  debmod->input_file_path = input_path;
  debmod->is_dll = (flags & DBG_PROC_IS_DLL) != 0;

  if ( !qfileexist(path) )
  {
    debmod->dmsg("%s: %s\n", path, winerr(errno));
    return -1;
  }

  int mismatch = 0;
  if ( !debmod->check_input_file_crc32(input_file_crc32) )
    mismatch = CRC32_MISMATCH;

#ifdef __EA64__
  bool dbg_srv_64 = true;
#else
  bool dbg_srv_64 = false;
  if ( (flags & DBG_PROC_64BIT) != 0 )
  {
    debmod->dwarning("Cannot debug a 64bit process with the 32bit debugger server, sorry\n");
    return -1;
  }
#endif

  launch_process_params_t lpi;
  lpi.path = path;
  lpi.args = args;
  lpi.startdir = startdir[0] != '\0' ? startdir : NULL;
  lpi.flags = LP_NO_ASLR | LP_DETACH_TTY;
  if ( (flags & DBG_NO_TRACE) == 0 )
    lpi.flags |= LP_TRACE;

  if ( (flags & DBG_PROC_64BIT) != 0 )
  {
    lpi.flags |= LP_LAUNCH_64_BIT;
  }
  else if ( (flags & DBG_PROC_32BIT) != 0 )
  {
    lpi.flags |= LP_LAUNCH_32_BIT;
  }
  else
  {
    lpi.flags |= dbg_srv_64 ? LP_LAUNCH_64_BIT : LP_LAUNCH_32_BIT;
    debmod->dmsg("Launching as %sbit process\n", dbg_srv_64 ? "64" : "32");
  }

  qstring errbuf;
  *child_pid = launch_process(lpi, &errbuf);

  if ( *child_pid == NULL )
  {
    debmod->dmsg("launch_process: %s", errbuf.c_str());
    return -1;
  }
  return 1 | mismatch;
}