Port AuthHostInstance::activate()
{
	StLock<Mutex> _(*this);
	if (state() != alive)
	{
		if ((mHostType == securityAgent)) {
		    if (!(session().attributes() & sessionHasGraphicAccess))
			CssmError::throwMe(CSSM_ERRCODE_NO_USER_INTERACTION);
		    if (inDarkWake())
			CssmError::throwMe(CSSM_ERRCODE_IN_DARK_WAKE);
		}

		fork();
		switch (ServerChild::state()) {
		case Child::alive:
			secdebug("AuthHostInstance", "%p (pid %d) has launched", this, pid());
			break;
		case Child::dead:
			secdebug("AuthHostInstance", "%p (pid %d) failed on startup", this, pid());
			break;
		default:
			assert(false);
		}
	}

	if (!ready())
		CssmError::throwMe(CSSM_ERRCODE_NO_USER_INTERACTION);

	return servicePort();
}
//------------------------------------------------------------------------------
// Name: kill
// Desc:
//------------------------------------------------------------------------------
void DebuggerCore::kill() {
	if(attached()) {
		clear_breakpoints();
		ptrace(PT_KILL, pid(), 0, 0);
		native::waitpid(pid(), 0, WAIT_ANY);
		pid_ = 0;
		threads_.clear();
	}
}
EXPORT_C void RMemSpySession::GetProcessIdByThreadId( TProcessId& aPID, TThreadId aTID )
	{	
	TPckgBuf<TProcessId> pid(aPID);
	TPckgBuf<TThreadId> tid(aTID);
	
	TIpcArgs args( &pid, &tid );
	User::LeaveIfError( SendReceive( EMemSpyClientServerOpGetProcessIdByThreadId, args ) );
	aPID = pid();
	}
/*******************************************************************************
 forkcmd
*******************************************************************************/
forkcmd::forkcmd(bool wait_term) :
   _pid(fork()),
   _status(0),
   _wait(wait_term)
{
   if (pid())
   {
      std::cout << "Forked " << pid() << std::endl ;
      PCOMN_THROW_MSG_IF(pid() < 0, std::runtime_error, "Error while forking: %s", strerror(errno)) ;
   }
}
//
// Take a living child and cut it loose. This sets its state to abandoned
// and removes it from the child registry.
// This is one thing you can do in the destructor of your subclass to legally
// dispose of your child's process.
//
void Child::abandon()
{
	StLock<Mutex> _(mChildren());
	if (mState == alive) {
		secdebug("unixchild", "%p (pid %d) abandoned", this, pid());
		mState = abandoned;
		mChildren().erase(pid());
	} else {
		secdebug("unixchild", "%p (pid %d) is not alive; abandon() ignored",
			this, pid());
	}
}
Beispiel #6
0
dvl::pid_table::pid_table()
{
	//register internal ids
	set_group(pid().set_group(GROUP_INTERNAL), L"INTERNAL");

	set_element(EMPTY, L"EMPTY");
	set_element(PARSER, L"PARSER");

	//register diagnostic routines
	set_group(pid().set_group(GROUP_DIAGNOSTIC), L"DIAGNOSTIC");

	set_element(ECHO, L"ECHO");
}
Monitor::TreeNode*
Monitor::MonitorDataStorage::getTransportNode(
  const TransportKey& key,
  bool&               create
)
{
  TreeNode* node = 0;
  TransportToTreeMap::iterator location
    = this->transportToTreeMap_.find( key);
  if( location == this->transportToTreeMap_.end()) {
    // We are done if not creating a new node.
    if( !create) return 0;

    // This transport needs to be installed.

    // Find the parent node, if any.  It is ok to not have a parent node
    // for cases of out-of-order updates.  We handle that as the updates
    // are actually processed.
    ProcessKey pid( key.host, key.pid);
    TreeNode* parent = this->getProcessNode( pid, create);

    QList<QVariant> list;
    QString value = QString("0x%1")
                    .arg( key.transport, 8, 16, QLatin1Char('0'));
    list << QString( QObject::tr( "Transport")) << value;
    node = new TreeNode( list, parent);
    if( parent) {
      parent->append( node);
    }

    // Install the new node.
    this->transportToTreeMap_[ key] = std::make_pair( node->row(), node);

  } else {
    node = location->second.second;
    create = false;
  }

  // If there have been some out-of-order reports, we may have been
  // created without a parent node.  We can fill in that information now
  // if we can.  If we created the node, we already know it has a
  // parent so this will be bypassed.
  if( !node->parent()) {
    create = true;
    ProcessKey pid( key.host, key.pid);
    node->parent() = this->getProcessNode( pid, create);
  }

//node->setColor(1,QColor("#ffbfbf"));
  return node;
}
Beispiel #8
0
int main(int argc, char **argv) {

   if(argc < 5) {
      std::cout << "Invalid number of args." << std::endl;
      return 0;
   }

   auto maxPwm = atof(argv[1]);
   if(maxPwm < 1.34 || maxPwm > 1.7) {
      std::cout << "Max pulse width needs to be in range 1.34-1.7." << std::endl;
      return 0;
   }

   auto pGain = atof(argv[2]);
   if(pGain < 0) {
      std::cout << "Proportional gain needs to be larget than zero." << std::endl;
      return 0;
   }

   auto iGain = atof(argv[3]);
   if(iGain < 0) {
      std::cout << "Integral gain needs to be larget than zero." << std::endl;
      return 0;
   }

   auto dGain = atof(argv[4]);
   if(dGain < 0) {
      std::cout << "Derivative gain needs to be larget than zero." << std::endl;
      return 0;
   }

   drone<servo, pid> d(std::vector<servo>({ 
                         servo(4, 1.2, maxPwm, pins::instance().pwm),
                         servo(5, 1.2, maxPwm, pins::instance().pwm),
                         servo(6, 1.2, maxPwm, pins::instance().pwm),
                         servo(7, 1.2, maxPwm, pins::instance().pwm) }),
                       std::vector<pid>({ 
                         pid(pGain, iGain, dGain),
                         pid(pGain, iGain, dGain),
                         pid(pGain, iGain, dGain) }));
   stupid = &d;

   struct sigaction sigIntHandler;
   sigIntHandler.sa_handler = ting;
   sigemptyset(&sigIntHandler.sa_mask);  
   sigIntHandler.sa_flags = 0;
   sigaction(SIGINT, &sigIntHandler, NULL);
 
   d.run();
}
//
// Common kill code.
// Requires caller to hold mChildren() lock.
//
void Child::tryKill(int signal)
{
	assert(mState == alive);	// ... or don't bother us
	secdebug("unixchild", "%p (pid %d) sending signal(%d)", this, pid(), signal);
	if (::kill(pid(), signal))
		switch (errno) {
		case ESRCH: // someone else reaped ths child; or things are just wacky
			secdebug("unixchild", "%p (pid %d) has disappeared!", this, pid());
			mState = invalid;
			mChildren().erase(pid());
			// fall through
		default:
			UnixError::throwMe();
		}
}
//------------------------------------------------------------------------------
// Name: kill
// Desc:
//------------------------------------------------------------------------------
void DebuggerCore::kill() {
	if(attached()) {
		clear_breakpoints();

		ptrace(PTRACE_KILL, pid(), 0, 0);

		// TODO: do i need to actually do this wait?
		native::waitpid(pid(), 0, __WALL);

		delete process_;
		process_ = 0;

		reset();
	}
}
//------------------------------------------------------------------------------
// Name: stop_threads
// Desc:
//------------------------------------------------------------------------------
void DebuggerCore::stop_threads() {
	if(process_) {
		for(auto &thread: process_->threads()) {
			const edb::tid_t tid = thread->tid();

			if(!waited_threads_.contains(tid)) {
			
				if(auto thread_ptr = static_cast<PlatformThread *>(thread.get())) {
			
					syscall(SYS_tgkill, pid(), tid, SIGSTOP);

					int thread_status;
					if(native::waitpid(tid, &thread_status, __WALL) > 0) {
						waited_threads_.insert(tid);
						thread_ptr->status_ = thread_status;

						if(!WIFSTOPPED(thread_status) || WSTOPSIG(thread_status) != SIGSTOP) {
							qDebug("[warning] paused thread [%d] received an event besides SIGSTOP", tid);
						}
					}
				}
			}
		}
	}
}
Beispiel #12
0
TEST (PID, PidEquilibrates)
{
    float target, Kp, Ki, Kd;
    float state, dt;
    int step_time, nsteps;

    const float target_start = 0.f;
    const float target_end   = 1.f;
    const float tolerance = 1e-5;
    
    state = target = 0.f;
    step_time = 20;
    nsteps = 200;

    dt = 0.1;
    Kp = 3.f;
    Ki = 2.f;
    Kd = 3.f;
    
    PidControl<float> pid(target-state, Kp, Ki, Kd);

    for (int i = 0; i < nsteps; ++i) {
        target = i < step_time ? target_start : target_end;
        state += dt * pid.update(target-state);
        // printf("%g\n", state);
    }

    ASSERT_LE(fabs(state - target_end), tolerance);
}
Beispiel #13
0
 /** Caculate the PID for the roll */
 inline float roll(const float &roll) {
   #ifdef PITCH_ROLL_DEBUG
   Serial.print(_roll);
   Serial.print(",");
   #endif
   return pid(P_ROLL, I_ROLL, D_ROLL, _pid_roll[0], _pid_roll[1], roll, _roll * DEG_SEC);
 }
Beispiel #14
0
 /** Caculate the PID for the pitch */
 inline float pitch(const float &pitch) {
   #ifdef PITCH_ROLL_DEBUG
   Serial.print(_pitch);
   Serial.print(",");
   #endif
   return pid(P_PITCH, I_PITCH, D_PITCH, _pid_pitch[0], _pid_pitch[1], pitch, _pitch * DEG_SEC);
 }
Beispiel #15
0
 /** Caculate the PID for the yaw */
 inline float yaw(const float &yaw) {
   #ifdef PITCH_ROLL_DEBUG
   Serial.print(_yaw);
   Serial.println();
   #endif
   return pid(P_YAW, I_YAW, D_YAW, _pid_yaw[0], _pid_yaw[1], yaw, _yaw * DEG_SEC);
 }
Beispiel #16
0
// main loop
void loop()
{
    // setup (unfortunately must be done here as we cannot create a global AC_PID object)
    AC_PID pid(TEST_P, TEST_I, TEST_D, TEST_IMAX * 100, TEST_FILTER, TEST_DT);
    AC_HELI_PID heli_pid(TEST_P, TEST_I, TEST_D, TEST_IMAX * 100, TEST_FILTER, TEST_DT, TEST_INITIAL_FF);
    uint16_t radio_in;
    uint16_t radio_trim;
    int16_t error;
    float control_P, control_I, control_D;

    // display PID gains
    hal.console->printf("P %f  I %f  D %f  imax %f\n", (float)pid.kP(), (float)pid.kI(), (float)pid.kD(), (float)pid.imax());

    // capture radio trim
    radio_trim = hal.rcin->read(0);

    while( true ) {
        radio_in = hal.rcin->read(0);
        error = radio_in - radio_trim;
        pid.set_input_filter_all(error);
        control_P = pid.get_p();
        control_I = pid.get_i();
        control_D = pid.get_d();

        // display pid results
        hal.console->printf("radio: %d\t err: %d\t pid:%4.2f (p:%4.2f i:%4.2f d:%4.2f)\n",
                (int)radio_in, (int)error,
                (float)(control_P+control_I+control_D),
                (float)control_P, (float)control_I, (float)control_D);
        hal.scheduler->delay(50);
    }
}
Beispiel #17
0
CTestInfo::CTestInfo()
{
	const ::testing::TestInfo *pTestInfo =
		::testing::UnitTest::GetInstance()->current_test_info();
	str_format(m_aFilename, sizeof(m_aFilename), "%s.%s-%d.tmp",
		pTestInfo->test_case_name(), pTestInfo->name(), pid());
}
Beispiel #18
0
bool Ipc::connect(enum Cmd code, const QObject *reciever, const char *member)
{
	bool connected = false;
	
	switch (code)
	{
		case CmdStatus:
			connected = QObject::connect(this, SIGNAL(status()), reciever, member);
			break;
		case CmdStop:
			connected = QObject::connect(this, SIGNAL(stop()), reciever, member);
			break;
		case CmdPid:
			connected = QObject::connect(this, SIGNAL(pid()), reciever, member);
			break;
		case CmdConfigRead:
			connected = QObject::connect(this, SIGNAL(configRead()), reciever, member);
			break;
		case CmdLogReopen:
			connected = QObject::connect(this, SIGNAL(logReopen()), reciever, member);
			break;
		case CmdStateSave:
			connected = QObject::connect(this, SIGNAL(stateSave()), reciever, member);
			break;
		default:;
	}
	
	if (connected && !m_cmdConnected.contains(code))
		m_cmdConnected << code;
	
	return connected;
}
int spawncmd::close()
{
   PCOMN_THROW_MSG_IF(!pid(), std::runtime_error, "Child is already terminated") ;
   PCOMN_THROW_MSG_IF(terminate() < 0, std::runtime_error, "Error terminating shell command '%s': %s", _cmd.c_str(), strerror(errno)) ;
   PCOMN_THROW_MSG_IF(_status == 127, std::runtime_error, "Failure running the shell. Cannot run shell command '%s'", _cmd.c_str()) ;
   return _status ;
}
Beispiel #20
0
void regulator( ){

 // Read ADC.
	readAdc( );
	AdcToPercetage( );
	setLED( );

 // Was the line found?
	if(theLineIsLost( )){
		*isFindingLineValue = 1.0;
		isFindingLine = true; //GPIO_SetBits(GPIOD, GPIO_Pin_14);
	}else{
		*isFindingLineValue = -1.0;
		isFindingLine = false; //GPIO_ResetBits(GPIOD, GPIO_Pin_14);
	}

 // Decide upon former.
	if(isFindingLine){
	
		stopTimer++;	
		if(*virtualSensorValue < 0.0){ drive_turn_right(80); }
		else{ drive_turn_left(90); }
	}
	else{
		pid( );
	}
}
Beispiel #21
0
CmdQueueItem* DebuggerDriver::executeCmdString(DbgCommand cmd,
					       QString cmdString, bool clearLow)
{
    // place a new command into the high-priority queue
    CmdQueueItem* cmdItem = new CmdQueueItem(cmd, cmdString);
    m_hipriCmdQueue.push(cmdItem);

    if (clearLow) {
	if (m_state == DSrunningLow) {
	    // take the liberty to interrupt the running command
	    m_state = DSinterrupted;
	    ::kill(pid(), SIGINT);
	    ASSERT(m_activeCmd != 0);
	    TRACE(QString().sprintf("interrupted the command %d",
		  (m_activeCmd ? m_activeCmd->m_cmd : -1)));
	    delete m_activeCmd;
	    m_activeCmd = 0;
	}
	flushLoPriQueue();
    }
    // if gdb is idle, send it the command
    if (m_state == DSidle) {
	ASSERT(m_activeCmd == 0);
	writeCommand();
    }

    return cmdItem;
}
Beispiel #22
0
/**
 * @fn childrenPids
 */
QList<Q_PID> QueuedProcess::childrenPids() const
{
    QStringList allDirectories
        = QDir("/proc").entryList(QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name);
    QStringList directories = allDirectories.filter(QRegExp("(\\d+)"));

    QList<Q_PID> pids
        = std::accumulate(directories.cbegin(), directories.cend(), QList<Q_PID>(),
                          [this](QList<Q_PID> &list, const QString &dir) {
                              QFile statFile(QString("/proc/%1/stat").arg(dir));
                              if (!statFile.open(QIODevice::ReadOnly | QIODevice::Text))
                                  return list;

                              QString output = statFile.readAll();
                              output.remove(QRegExp("\\d+ \\(.*\\) . "));
                              Q_PID ppid = output.split(' ').first().toLongLong();
                              if (ppid == pid())
                                  list.append(dir.toLongLong());

                              statFile.close();

                              return list;
                          });

    return pids;
}
Beispiel #23
0
void CRaceDemo::SaveDemo(const char* pDemo)
{
	char aNewFilename[512];
	char aOldFilename[512];
	if(g_Config.m_ClDemoName)
	{
		char aPlayerName[MAX_NAME_LENGTH];
		str_copy(aPlayerName, m_pClient->m_aClients[m_pClient->m_Snap.m_LocalClientID].m_aName, sizeof(aPlayerName));

		// check the player name
		for(int i = 0; i < MAX_NAME_LENGTH; i++)
		{
			if(!aPlayerName[i])
				break;

			if(aPlayerName[i] == '\\' || aPlayerName[i] == '/' || aPlayerName[i] == '|' || aPlayerName[i] == ':' || aPlayerName[i] == '*' || aPlayerName[i] == '?' || aPlayerName[i] == '<' || aPlayerName[i] == '>' || aPlayerName[i] == '"')
				aPlayerName[i] = '%';

			str_format(aNewFilename, sizeof(aNewFilename), "demos/%s_%5.2f_%s.demo", pDemo, m_Time, aPlayerName);
		}
	}
	else
		str_format(aNewFilename, sizeof(aNewFilename), "demos/%s_%5.2f.demo", pDemo, m_Time);

	str_format(aOldFilename, sizeof(aOldFilename), "demos/%s_tmp_%d.demo", m_pMap, pid());

	Storage()->RenameFile(aOldFilename, aNewFilename, IStorageTW::TYPE_SAVE);

	dbg_msg("racedemo", "saved better demo");
}
Beispiel #24
0
void MainWindow::buildClientsMenu()
{
    if (auto model = dynamic_cast<LogModel*>(ui->tableView->sourceModel()))
    {
        auto actions = ui->menu_Disconnect_Client->actions();
        for (auto it = actions.begin(); it != actions.end(); ++it)
        {
            if (*it == ui->actionDisconnectAll)
            {
                break;
            }
            ui->menuHighlights->removeAction(*it);
            delete *it;
        }
        auto& clients = model->clients();
        QFontMetrics metrics(ui->menu_Disconnect_Client->font());
        for (auto it = clients.begin(); it != clients.end(); ++it)
        {
            auto path = metrics.elidedText(it->path(), Qt::ElideMiddle, 200);
            auto name = QString("[%1] %2").arg(it->pid()).arg(path);
            auto action = new QAction(name, this);
            action->setProperty("socket", quint64(it->socket()));
            connect(action, &QAction::triggered, this, &MainWindow::disconnectClient);
            ui->menu_Disconnect_Client->insertAction(ui->actionDisconnectAll, action);
        }
    }
}
// Null constructor
JobInfo::JobInfo()
:
    runningJobsDir_(getEnv("FOAM_JOB_DIR")/"runningJobs"),
    finishedJobsDir_(getEnv("FOAM_JOB_DIR")/"finishedJobs"),
    jobFileName_(hostName() + '.' + Foam::name(pid())),
    runningJobPath_(runningJobsDir_/jobFileName_),
    finishedJobPath_(finishedJobsDir_/jobFileName_)
{
    name() = "JobInfo";

    if (writeJobInfo && Pstream::master())
    {
        if (!dir(runningJobsDir_) && !mkDir(runningJobsDir_))
        {
            FatalErrorIn("JobInfo::JobInfo()")
                << "Cannot make JobInfo directory " << runningJobsDir_
                << Foam::exit(FatalError);
        }

        if (!dir(finishedJobsDir_) && !mkDir(finishedJobsDir_))
        {
            FatalErrorIn("JobInfo::JobInfo()")
                << "Cannot make JobInfo directory " << finishedJobsDir_
                << Foam::exit(FatalError);
        }
    }

    constructed = true;
}
Beispiel #26
0
const Foam::memInfo& Foam::memInfo::update()
{
    // reset to invalid values first
    peak_ = size_ = rss_ = -1;
    IFstream is("/proc/" + name(pid()) + "/status");

    while (is.good())
    {
        string line;
        is.getLine(line);
        char tag[32];
        int value;

        if (sscanf(line.c_str(), "%30s %d", tag, &value) == 2)
        {
            if (!strcmp(tag, "VmPeak:"))
            {
                peak_ = value;
            }
            else if (!strcmp(tag, "VmSize:"))
            {
                size_ = value;
            }
            else if (!strcmp(tag, "VmRSS:"))
            {
                rss_ = value;
            }
        }
    }

    return *this;
}
void AndroidRunner::logcatProcess(const QByteArray &text, QByteArray &buffer, bool onlyError)
{
    QList<QByteArray> lines = text.split('\n');
    // lines always contains at least one item
    lines[0].prepend(buffer);
    if (!lines.last().endsWith('\n')) {
        // incomplete line
        buffer = lines.last();
        lines.removeLast();
    } else {
        buffer.clear();
    }

    QByteArray pid(QString::fromLatin1("%1):").arg(m_processPID).toLatin1());
    foreach (QByteArray line, lines) {
        if (!line.contains(pid))
            continue;
        if (line.endsWith('\r'))
            line.chop(1);
        line.append('\n');
        if (onlyError || line.startsWith("F/")
                || line.startsWith("E/")
                || line.startsWith("D/Qt")
                || line.startsWith("W/"))
            emit remoteErrorOutput(line);
        else
            emit remoteOutput(line);

    }
}
Beispiel #28
0
static char *name(void) {
	if (!nameinit) {
		// initialize the name of the process based on /proc/PID/comm
		memset(myname, 0, MAXNAME);
		
		pid_t p = pid();
		char *fname;
		if (asprintf(&fname, "/proc/%u/comm", p) == -1)
			return "unknown";

		// read file
		if (!orig_fopen)
			orig_fopen = (orig_fopen_t)dlsym(RTLD_NEXT, "fopen");
		FILE *fp  = orig_fopen(fname, "r");
		if (!fp)
			return "unknown";
		if (fgets(myname, MAXNAME, fp) == NULL) {
			fclose(fp);
			free(fname);
			return "unknown";
		}
		
		// clean '\n'
		char *ptr = strchr(myname, '\n');
		if (ptr)
			*ptr = '\0';
			
		fclose(fp);
		free(fname);
		nameinit = 1;
	}
	
	return myname;
}
Beispiel #29
0
int follow_line(bool(*cond)(void)) {
	int adj = 0, num = 0;
	int i,c_at;
	int m_left = 0,m_right = 0;
	unsigned char lineSensorByte = ReadLineSensor();
	adj = 0;
	num = 0;
	if ((*cond)())
		return NODE_BREAK;
	for (i = 0; i < 8; i++)
	{
		c_at = (int)!(lineSensorByte & 0x01);
		UARTprintf("%d",c_at);
		num += !c_at;
		adj += c_at * 5*((i<4) ? (i-4) : (i-3));
		m_left = (c_at)?((i<4)?(4-i>m_left?4-i:m_left):m_left):m_left;
		m_right = (c_at)?((i>3)?(i-3>m_right?i-3:m_right):m_right):m_right;
		lineSensorByte >>= 1;
	}
	UARTprintf(" ADJ: %3d max: %d %d\r",adj/num,m_left,m_right);
	if (num == 0) return LOST;
	if (m_left + m_right > 5) return FORK;
	pid(64*adj/num,-64*adj/num);
	return RETURN_L;
}
Beispiel #30
0
int PasswdProcess::exec(const char *oldpass, const char *newpass, int check)
{
    if(m_User.isEmpty())
        return -1;
    //    if (check)
    //	setTerminal(true);

    // Try to set the default locale to make the parsing of the output
    // of `passwd' easier.
    setenv("LANG", "C", true /* override */);

    KStringList args;
    if(bOtherUser)
        args += m_User;
    int ret = PtyProcess::exec("passwd", args);
    if(ret < 0)
    {
        kdDebug(1512) << k_lineinfo << "Passwd not found!\n";
        return PasswdNotFound;
    }

    ret = ConversePasswd(oldpass, newpass, check);
    if(ret < 0)
        kdDebug(1512) << k_lineinfo << "Conversation with passwd failed. pid = " << pid() << endl;

    if((waitForChild() != 0) && !check)
        return PasswordNotGood;

    return ret;
}