Example #1
0
/* Allocate a block of storage; abort execution if it cannot be done. */
static void *allocate_memory (size_t size) {
   void *address = malloc(size);
   if (address == NULL) {
      system_error("memory allocation");
   }
   return address;
}
Example #2
0
bool loop_impl::run_once( bool block )
{
    
    if (block)
        _sem.wait();
    else {
        if (!_sem.wait(0)) {
            return false;
        }
    }

    shared_ptr<task_t> task;
    {
        concurrency_task_queue::ref ref(_task_queue);
        task = ref->front();
        ref->pop();
    }
    if (task->empty()) {
        throw system_error(-1, "you do run after ended!");
    }
    try
    {
        (*task)();
    }
    catch (std::exception &e)
    {
        LOG_ERROR(e.what());
    }
    return true;
}
Example #3
0
/// Executes an external binary and replaces the current process.
///
/// This differs from process::exec() in that this function reports errors
/// caused by the exec(2) system call to let the caller decide how to handle
/// them.
///
/// This function must not use any of the logging features so that the output
/// of the subprocess is not "polluted" by our own messages.
///
/// This function must also not affect the global state of the current process
/// as otherwise we would not be able to use vfork().  Only state stored in the
/// stack can be touched.
///
/// \param program The binary to execute.
/// \param args The arguments to pass to the binary, without the program name.
///
/// \throw system_error If the exec(2) call fails.
void
process::exec_unsafe(const fs::path& program, const args_vector& args)
{
    PRE(args.size() < MAX_ARGS);
    int original_errno = 0;
    try {
        const char* argv[MAX_ARGS + 1];

        argv[0] = program.c_str();
        for (args_vector::size_type i = 0; i < args.size(); i++)
            argv[1 + i] = args[i].c_str();
        argv[1 + args.size()] = NULL;

        const int ret = ::execv(program.c_str(),
                                (char* const*)(unsigned long)(const void*)argv);
        original_errno = errno;
        INV(ret == -1);
        std::cerr << "Failed to execute " << program << ": "
                  << std::strerror(original_errno) << "\n";
    } catch (const std::runtime_error& error) {
        std::cerr << "Failed to execute " << program << ": "
                  << error.what() << "\n";
        std::abort();
    } catch (...) {
        std::cerr << "Failed to execute " << program << "; got unexpected "
            "exception during exec\n";
        std::abort();
    }

    // We must do this here to prevent our exception from being caught by the
    // generic handlers above.
    INV(original_errno != 0);
    throw system_error("Failed to execute " + program.str(), original_errno);
}
Example #4
0
	TORRENT_DEPRECATED
	void set_piece_hashes(create_torrent& t, std::wstring const& p, Fun f)
	{
		error_code ec;
		set_piece_hashes_deprecated(t, p, f, ec);
		if (ec) throw system_error(ec);
	}
Example #5
0
    void parent(pid_t pid, int* cmd_stdout, int* cmd_stderr) {
        /* We dont need input descriptors, we'll be only reading from
        the child */
        close(cmd_stderr[1]);
        close(cmd_stdout[1]);

        string buf = read_all(cmd_stderr[0]);
        buf += read_all(cmd_stdout[0]);
        /* We've read it all, not needed any more */
        close(cmd_stderr[0]);
        close(cmd_stdout[0]);


        /* Clean up child's status */
        int status;
        if(waitpid(pid, &status, 0/*options*/) == -1)
            throw system_error("waitpid", errno);
#ifdef REPORT_COMPILER_EXIT_STATUS
        /* Compiler process reported errors - throw exception */
        stringstream exit_info;
        if(WIFSIGNALED(status)) {
            exit_info << "Compiler exited due to signal "<<
                WTERMSIG(status) << endl;
        }else if(WIFEXITED(status) && WEXITSTATUS(status) != 0){
            exit_info << "Compiler exited normaly with status " <<
                WEXITSTATUS(status) << endl;
        }
        buf.insert(0, exit_info.str() + "\n");
#endif
        if(!buf.empty()) {
            throw compiler_error(buf);
        }
    }
Example #6
0
static int write_galaxy(const char *filename, struct galaxy *g)
{
    FILE *fp;

    if ((fp = open_file(filename, FMODE_WB)))
    {
        struct head H;

        H.N_num = host_to_net_int(g->N_num);
        H.S_num = host_to_net_int(g->S_num);

        if (fwrite(&H, sizeof (struct head), 1, fp) == 1)
        {
            int i;

            for (i = 0; i < g->N_num; ++i)
                node_write_bin(g->N + i, fp);

            for (i = 0; i < g->S_num; ++i)
                star_write_bin(g->S + i, fp);
        }
        fclose(fp);

        return 1;
    }
    else error("Galaxy file '%s': %s", filename, system_error());

    return 0;
}
Example #7
0
	TORRENT_DEPRECATED
	inline void set_piece_hashes(create_torrent& t, std::wstring const& p)
	{
		error_code ec;
		set_piece_hashes_deprecated(t, p, detail::nop, ec);
		if (ec) throw system_error(ec);
	}
Example #8
0
static int parse_galaxy(const char *filename, struct galaxy *g)
{
    FILE *fp;
    int i;

    if ((fp = open_file(filename, FMODE_RB)))
    {
        struct head H;

        if (fread(&H, sizeof (struct head), 1, fp) == 1)
        {
            g->magnitude = 1.0;
            g->N_num     = ntohl(H.N_num);
            g->S_num     = ntohl(H.S_num);

            if ((g->N = (struct node *) calloc(g->N_num, sizeof(struct node))))
                for (i = 0; i < g->N_num; ++i)
                    node_parse_bin(g->N + i, fp);

            if ((g->S = (struct star *) calloc(g->S_num, sizeof(struct star))))
                for (i = 0; i < g->S_num; ++i)
                    star_parse_bin(g->S + i, fp);
        }
        fclose(fp);

        return 1;
    }
    else error("Galaxy file '%s': %s", filename, system_error());

    return 0;
}
Example #9
0
void
impl::stream_capture::prepare(void)
{
    if (pipe(m_pipefds) == -1)
        throw system_error(IMPL_NAME "::stream_capture::prepare",
                           "Failed to create pipe", errno);
}
Example #10
0
/**
 * Remove inotify watch
 */
void inotify_watch::remove(bool force) {
  if (inotify_rm_watch(m_fd, m_wd) == -1 && !force) {
    throw system_error("Failed to remove inotify watch");
  }
  m_wd = -1;
  m_mask = 0;
}
// public emergency stop
void slight_StepperManager::system_emergencystop() {
    motor.stop();
    motor.disable();
    // something went wrong
    error_type = ERROR_emergencystop;
    system_error();
}
  /**
   * @copydoc
   * data::output::copy_to_destination
   */
  virtual
  void
  copy_to_destination (
   object_type const* src,
   std::size_t src_size
  ) final override
  {
    ::ssize_t swrote;

    while (src_size > 0)
    {
      swrote = ::write(STDOUT_FILENO, src, src_size * sizeof(ObjectT));
      
      if (swrote == 0)
      {
        throw out_of_space("End of file reached.");
      }
      else
      if (swrote == -1)
      {
        throw system_error("write");
      }

      src += static_cast<std::size_t>(swrote);
      src_size -= static_cast<std::size_t>(swrote);
    }
  }
Example #13
0
	basic_string< TargetChar > convert( const basic_string< SourceChar > &sourceString,
			size_t ( *convertFunction )( TargetChar *dst, const SourceChar **src, size_t len, mbstate_t *state )) {

		constexpr auto LENGTH_ERROR = static_cast< size_t >( -1 );

		mbstate_t state = mbstate_t();

		// Find out how much space we need:

		const SourceChar *sourceStringData = sourceString.data();
		size_t expectedTargetStringLength = convertFunction( nullptr, &sourceStringData, sourceString.length(), &state );
		if ( expectedTargetStringLength == LENGTH_ERROR )
			throw make_errno_system_error();

		// Convert the string:

		basic_string< TargetChar > targetString( expectedTargetStringLength, TargetChar() );
		size_t actualTargetStringLength = convertFunction( &targetString[ 0 ], &sourceStringData, sourceString.length(), &state );
		if ( actualTargetStringLength == LENGTH_ERROR )
			throw make_errno_system_error();

		// Could all characters be converted?

		if ( expectedTargetStringLength != actualTargetStringLength )
			throw system_error( make_error_code( errc::illegal_byte_sequence ));

		return targetString;
	}
Example #14
0
//!
//! \brief Configures child process' input streams.
//!
//! Sets up the current process' input streams to behave according to the
//! information in the \a info map.  \a closeflags is modified to reflect
//! those descriptors that should not be closed because they where modified
//! by the function.
//!
//! Modifies the current execution environment, so this should only be run
//! on the child process after the fork(2) has happened.
//!
//! \throw system_error If any error occurs during the configuration.
//!
inline
void
setup_input(info_map& info, bool* closeflags, int maxdescs)
{
    for (info_map::iterator iter = info.begin(); iter != info.end(); iter++) {
        int d = (*iter).first;
        stream_info& si = (*iter).second;

        BOOST_ASSERT(d < maxdescs);
        closeflags[d] = false;

        if (si.m_type == stream_info::use_file) {
            int fd = ::open(si.m_file.c_str(), O_RDONLY);
            if (fd == -1)
                boost::throw_exception
                    (system_error("boost::process::detail::setup_input",
                                  "open(2) of " + si.m_file + " failed",
                                  errno));
            if (fd != d) {
                file_handle h(fd);
                h.posix_remap(d);
                h.disown();
            }
        } else if (si.m_type == stream_info::use_handle) {
            if (si.m_handle.get() != d)
                si.m_handle.posix_remap(d);
        } else if (si.m_type == stream_info::use_pipe) {
            si.m_pipe->wend().close();
            if (d != si.m_pipe->rend().get())
                si.m_pipe->rend().posix_remap(d);
        } else
            BOOST_ASSERT(si.m_type == stream_info::inherit);
    }
}
Example #15
0
  leptr
find_correct_splitedge(evfptr oldsplitedge,vertype breakpos)
{
  leptr forwardle,backle,oldsplitle;
  vertype nearpt;		/* dummy here since we know breakpos */
  evfptr splitedge;
  Boolean searchforwards = TRUE,searchbackwards = TRUE;
  double dummyt;
  ;
  /* change this call to be pt_near_lineseg_3d and make sure *that* routine */
  /* doesn't let t+- tol's to slip through anymore, ok? */
  oldsplitle = oldsplitedge->le1;
  if (pt_near_lineseg_3d(oldsplitle->facevert->pos,
			 oldsplitle->next->facevert->pos,breakpos,nearpt,
			 &dummyt,Ptonlinetol))
      return(oldsplitle);
#ifdef debug
  printf("\t\t*** Doing find_correct_splitedge!\n\n");
#endif
  forwardle = oldsplitle->next;
  backle = oldsplitle->prev;
  while (searchforwards || searchbackwards)
  {
    if (searchforwards)
    {
      if (pt_near_lineseg_3d(forwardle->facevert->pos,
			     Twin_le(forwardle)->facevert->pos,
			     breakpos,nearpt,&dummyt,Ptonlinetol))
	return(forwardle);
      else
      {
	forwardle = forwardle->next;
	/* make sure you didn't branch... if you did you're no longer on */
	/* the broken up edge. */
	if ((forwardle == oldsplitle) || 
	    ((Twin_le(Twin_le(forwardle->prev)->prev)) != forwardle))
	  searchforwards = FALSE;
      }
    }
    if (searchbackwards)
    {
      if (pt_near_lineseg_3d(backle->facevert->pos,
			     Twin_le(backle)->facevert->pos,
			     breakpos,nearpt,&dummyt,Ptonlinetol))
	return(backle);
      else
      {
	backle = backle->prev;
	/* make sure you didn't branch... if you did you're no longer on */
	/* the broken up edge. */
	if ((backle == oldsplitle) || 
	    ((Twin_le(Twin_le(backle->next)->next)) != backle))
	  searchbackwards = FALSE;
      }
    }
  }
  system_error("find_correct_splitedge: break edge search failure!!\n");
  return 0; 			// We'll never get here... -- LJE
}
Example #16
0
void thread::detach() {
  if (joinable()) {
    m_handle = thread_uninitialized;
  } else {
    throw system_error(make_error_code(errc::invalid_argument),
                       "Can not detach an unjoinable thread.");
  }
}
/* Return the name of group GID. The return value is a buffer
 * that the caller must deallocate with free. GID must be a
 * valid group ID. */
static char* get_group_name(gid_t gid)
{
    struct group* entry = getgrgid(gid);
    if (entry == NULL) {
        system_error("getgrgid");
    }
    return xstrdup(entry->gr_name);
}
Example #18
0
 void unix_socket::bind(const std::string& sun_path) {
     struct sockaddr_un local;
     local.sun_family = AF_UNIX;
     strncpy(local.sun_path,sun_path.c_str(), UNIX_PATH_MAX);
     unlink(local.sun_path); 
     if(::bind(sockfd, reinterpret_cast<sockaddr*>(&local), sizeof(local)) == -1)
         throw system_error("bind",errno);
 }
Example #19
0
 void compiler::process(const string& cpp_path, const string& out_path, const vector<string>& params) {
     int cmd_stdout[2];//0-read, 1-write;
     int cmd_stderr[2];//0-read, 1-write;
     if(pipe(cmd_stdout) == -1 || pipe(cmd_stderr) == -1)
             throw system_error("pipe",errno);
     pid_t pid = fork();
     switch(pid){
         case -1:
             throw system_error("fork", errno);
         case 0: //child
             setup_descriptors(cmd_stdout, cmd_stderr);
             compiler_main(cpp_path, out_path, params);            
             break;
         default:
             parent(pid, cmd_stdout, cmd_stderr);
     }
 }
/* Return the name of group GID. The return value is a buffer that the
 * caller must allocate with free. GID must be a valid group ID. */
static char* get_group_name (gid_t gid)
{/*{{{*/
    struct group* entry;
    entry = getgrgid (gid);
    if (entry == NULL)
        system_error ("getgrgid");
    return xstrdup (entry->gr_name);
}/*}}}*/
/* Return the name of user UID. The return value is a buffer that the
 * caller must allocate with free. UID must be a valid user ID. */
static char* get_user_name (uid_t uid)
{/*{{{*/
    struct passwd* entry;
    entry = getpwuid (uid);
    if (entry == NULL)
        system_error ("getpwuid");
    return xstrdup (entry->pw_name);
}/*}}}*/
void Calculator::calculate_answer() throw(ZeroDivide)
{
  if(expression==NULL) throw system_error("in void Calculator::calculate_answer(): call set_expression(const PreExpression& s, Expression& exp) before calling this metod");
  if(has_answer==true) return;
  expression->calculate_answer();
  expression_history.add(*source,*expression);
  has_answer=true;
}
void slight_StepperManager::system_state_calibrating_global_checks() {
    // check if motor is stopped
    if (motor_move_state == 0) {
        // something went wrong
        error_type = ERROR_motorstop;
        system_error();
    } else {
        // check timeout
        uint32_t move_duration =
            millis() - motor_move_started_timestamp;
        if (move_duration > motor_move_timeout) {
            motor.stop();
            error_type = ERROR_timeout;
            system_error();
        }
    }
}
Example #24
0
	torrent_handle add_magnet_uri(session& ses, std::string const& uri
		, add_torrent_params const& p)
	{
		error_code ec;
		torrent_handle ret = add_magnet_uri_deprecated(ses, uri, p, ec);
		if (ec) throw system_error(ec);
		return ret;
	}
/* A核用户数据 */
int dump_st_026(void)
{
    char *p;
    p = kmalloc(4096, GFP_KERNEL);
    memset(p,1,4096);
    system_error(0x88,1,2,p,4096);
    return 0;
}
Example #26
0
void buffered_file::close() {
  if (!file_)
    return;
  int result = FMT_SYSTEM(fclose(file_));
  file_ = FMT_NULL;
  if (result != 0)
    FMT_THROW(system_error(errno, "cannot close file"));
}
Example #27
0
void file::dup2(int fd) {
  int result = 0;
  FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd)));
  if (result == -1) {
    FMT_THROW(system_error(errno,
      "cannot duplicate file descriptor {} to {}", fd_, fd));
  }
}
Example #28
0
file file::dup(int fd) {
  // Don't retry as dup doesn't return EINTR.
  // http://pubs.opengroup.org/onlinepubs/009695399/functions/dup.html
  int new_fd = FMT_POSIX_CALL(dup(fd));
  if (new_fd == -1)
    FMT_THROW(system_error(errno, "cannot duplicate file descriptor {}", fd));
  return file(new_fd);
}
Example #29
0
handle handle::dup() const {
  if (!*this) BOOST_THROW_EXCEPTION(handle_is_closed_error());
#if defined(BOOST_POSIX_API)
  const implementation fd = ::fcntl(**this, F_DUPFD_CLOEXEC, 0);
  if (fd < 0)
    BOOST_THROW_EXCEPTION(system_error("fcntl")
                          << system_error::handle(**this));
#elif defined(BOOST_WINDOWS_API)
  implementation fd;
  if (!::DuplicateHandle(::GetCurrentProcess(), **this, ::GetCurrentProcess(),
                         &fd, 0, /* not inheritable */ false,
                         DUPLICATE_SAME_ACCESS)) {
    BOOST_THROW_EXCEPTION(system_error("DuplicateHandle")
                          << system_error::handle(**this));
  }
#endif
  return handle(fd);
}
Example #30
0
handle handle::dup2(const implementation new_fd) const {
  if (!*this) BOOST_THROW_EXCEPTION(handle_is_closed_error());
  const implementation fd = ::dup3(**this, new_fd, O_CLOEXEC);
  if (fd < 0)
    BOOST_THROW_EXCEPTION(system_error("dup3")
                          << system_error::handle(**this)
                          << system_error::new_handle(new_fd));
  return handle(fd);
}