bool EncryptionManager::AddEncryptionMapping( const Address & address, const uint8_t * sendKey, const uint8_t * receiveKey, double time ) { for ( int i = 0; i < m_numEncryptionMappings; ++i ) { if ( m_address[i] == address && m_lastAccessTime[i] + m_encryptionMappingTimeout >= time ) { m_lastAccessTime[i] = time; memcpy( m_sendKey + i*KeyBytes, sendKey, KeyBytes ); memcpy( m_receiveKey + i*KeyBytes, receiveKey, KeyBytes ); return true; } } for ( int i = 0; i < MaxEncryptionMappings; ++i ) { if ( m_lastAccessTime[i] + m_encryptionMappingTimeout < time ) { m_address[i] = address; m_lastAccessTime[i] = time; memcpy( m_sendKey + i*KeyBytes, sendKey, KeyBytes ); memcpy( m_receiveKey + i*KeyBytes, receiveKey, KeyBytes ); if ( i + 1 > m_numEncryptionMappings ) m_numEncryptionMappings = i + 1; return true; } } #if YOJIMBO_DEBUG_SPAM char addressString[MaxAddressLength]; address.ToString( addressString, MaxAddressLength ); debug_printf( "failed to add encryption mapping for %s\n", addressString ); #endif // #if YOJIMBO_DEBUG_SPAM return false; }
void FormatDisassembly::_FormatCell(Address const& rAddress, u32 Flags) { m_rPrintData.AppendSpace(4); auto pCell = m_rCore.GetCell(rAddress); if (pCell == nullptr) m_rPrintData.AppendComment(";; invalid cell!"); else m_rCore.FormatCell(rAddress, *pCell, m_rPrintData); std::string Cmt; u16 CurTextWidth = static_cast<u16>(m_rPrintData.GetCurrentText().length()) + 1; if (Flags & ShowAddress) CurTextWidth -= static_cast<u16>((rAddress.ToString().length() + 9)); if (m_rCore.GetDocument().GetComment(rAddress, Cmt)) { std::vector<std::string> CmtLines; boost::split(CmtLines, Cmt, boost::is_any_of("\n")); auto itCmtLine = std::begin(CmtLines), itCmtLineEnd = std::end(CmtLines); if (itCmtLine == itCmtLineEnd) return; m_rPrintData.AppendSpace(1).AppendComment(";").AppendSpace().AppendComment(*itCmtLine); ++itCmtLine; for (; itCmtLine != itCmtLineEnd; ++itCmtLine) m_rPrintData.AppendNewLine().AppendSpace(CurTextWidth + 1).AppendComment(";").AppendSpace().AppendComment(*itCmtLine); } }
void TcpEdgeListener::HandleSocketClose(QTcpSocket *socket, const QString &reason) { if(_outstanding_sockets.contains(socket) == 0) { return; } Address addr = _outstanding_sockets.value(socket); _outstanding_sockets.remove(socket); qDebug() << "Unable to connect to host: " << addr.ToString() << reason; socket->deleteLater(); ProcessEdgeCreationFailure(addr, reason); }
//////////////////////////////////////////////////////////////////////////////////// /// /// \brief Initializes the Component and all its' Services with a given /// Component ID. /// /// Once initialized, all components can create a periodic event which will call /// the CheckServiceStatus method of each Service. This is designed in the /// Component interface so developers do not need to create their own threads /// within there Services for performing status checks at low frequency /// intervals. Status checks include verifying event subscriptions or control /// status. /// /// \param[in] id The Component ID to use. /// \param[in] serviceUpdateFrequency This is the frequency (Hz) to call the /// CheckServiceStatus method on each Service. This is useful if any /// Service needs to verify connections or check what state it is in /// periodically. This value will depend on the types of Service your /// Component includes and defaults to 10Hz. If value is less than 0, /// no periodic checking happens. /// /// \return True on success, false on failure. /// //////////////////////////////////////////////////////////////////////////////////// bool Component::Initialize(const Address& id, const double serviceUpdateFrequency) { bool result = false; Shutdown(); // Check to see if the ID is locked on the local host. CxUtils::MappedMemory mappedMem; if(mLockID.CreateMappedMemory(std::string("JAUS") + id.ToString(), 256) == 0) { // ID is in use, exit. return false; } mComponentID = id; if(DiscoveryService()->IsEnabled() && DiscoveryService()->GetSubsystemIdentification().empty()) { std::cout << "Component::ERROR - Subsystem Identification Not Set.\n"; return false; } if(mpTransportService->Initialize(id)) { if(serviceUpdateFrequency >= 1.0) { std::stringstream str; str << "JSRVC Check 2 - " << mComponentID.ToString(); mCheckServiceTimer.SetName(str.str()); mCheckServiceTimer.Start(serviceUpdateFrequency); } std::stringstream str; str << "JSRVC Check 1 - " << mComponentID.ToString(); mCheckCoreServicesTimer.SetName(str.str()); mCheckCoreServicesTimer.Start(10); mInitializedFlag = result = true; Service::Map::iterator s; for(s = mServices.begin(); s != mServices.end(); s++) { if(s->second != mpTransportService) { s->second->Initialize(); } } ManagementService()->SetStatus(Management::Status::Standby); } return result; }
void Server::CheckBeacon(int i) { Address from; Packet p; while(beacons[i].ReceiveFrom(&p, sizeof(p), from) == sizeof(p)) { if(p.Control == C_PING) { // Reply with port the server is running on. p.Control = C_ACK; p.Port = htons(port); beacons[i].SendTo(&p, sizeof(p), from); std::wstring name = from.ToString(false); Log(OL_INFO, L"Responded to broadcast from %s\r\n", name.c_str()); } } }
void BufferEdgeListener::CreateEdgeTo(const Address &to) { const BufferAddress &rem_ba = static_cast<const BufferAddress &>(to); BufferEdgeListener *remote_el = _el_map[rem_ba.GetId()]; if(remote_el == 0) { qDebug() << "Attempting to create an Edge to an EL that doesn't exist from " << _local_address.ToString() << " to " << to.ToString(); return; } BufferEdge *local_edge(new BufferEdge(_local_address, remote_el->_local_address, true, 10)); BufferEdge *remote_edge(new BufferEdge(remote_el->_local_address, _local_address, false, 10)); local_edge->SetRemoteEdge(remote_edge); remote_edge->SetRemoteEdge(local_edge); ProcessNewEdge(local_edge); remote_el->ProcessNewEdge(remote_edge); }
//////////////////////////////////////////////////////////////////////////////////// /// /// \brief Prints status info about the Service to the console. /// //////////////////////////////////////////////////////////////////////////////////// void AccessControl::PrintStatus() const { //Mutex::ScopedLock lock(&mControlMutex); std::cout << "[" << GetServiceID().ToString() << "] - " << GetComponentID().ToString() << "\n"; Address controller; Byte authority; Address::Set controlled; std::map<Address, bool> flags; mControlMutex.Lock(); controller = mControllerID; authority = mControllerAuthorityCode; controlled = mControlledComponents; flags = mControlFlags; mControlMutex.Unlock(); if(controller.IsValid()) { std::cout << "Controlled by: " << controller.ToString() << " Authority Code: " << (int)authority << std::endl; } if(controlled.size() > 0) { Address::Set::const_iterator c; std::cout << "In Control of the Following:\n"; for(c = controlled.begin(); c != controlled.end(); c++) { if(flags.find(*c)->second) { std::cout << " - " << c->ToString() << std::endl; } } } }
void BufferEdgeListener::CreateEdgeTo(const Address &to) { if(Stopped()) { qWarning() << "Cannot CreateEdgeTo Stopped EL"; return; } if(!Started()) { qWarning() << "Cannot CreateEdgeTo non-Started EL"; return; } const BufferAddress &rem_ba = static_cast<const BufferAddress &>(to); BufferEdgeListener *remote_el = _el_map.value(rem_ba.GetId()); if(remote_el == 0) { qDebug() << "Attempting to create an Edge to an EL that doesn't exist from " << GetAddress().ToString() << " to " << to.ToString(); ProcessEdgeCreationFailure(to, "No such peer"); return; } int delay = Dissent::Utils::Random::GetInstance().GetInt(10, 50); BufferEdge *local_edge(new BufferEdge(GetAddress(), remote_el->GetAddress(), true, delay)); BufferEdge *remote_edge(new BufferEdge(remote_el->GetAddress(), GetAddress(), false, delay)); QSharedPointer<BufferEdge> ledge(local_edge); SetSharedPointer(ledge); QSharedPointer<BufferEdge> redge(remote_edge); SetSharedPointer(redge); local_edge->SetRemoteEdge(redge); remote_edge->SetRemoteEdge(ledge); ProcessNewEdge(ledge); remote_el->ProcessNewEdge(redge); }
bool EncryptionManager::RemoveEncryptionMapping( const Address & address, double time ) { for ( int i = 0; i < m_numEncryptionMappings; ++i ) { if ( m_address[i] == address ) { m_address[i] = Address(); m_lastAccessTime[i] = -1000.0; memset( m_sendKey + i*KeyBytes, 0, KeyBytes ); memset( m_receiveKey + i*KeyBytes, 0, KeyBytes ); if ( i + 1 == m_numEncryptionMappings ) { int index = i - 1; while ( index >= 0 ) { if ( m_lastAccessTime[index] + m_encryptionMappingTimeout >= time ) break; index--; } m_numEncryptionMappings = index + 1; } return true; } } #if YOJIMBO_DEBUG_SPAM char addressString[MaxAddressLength]; address.ToString( addressString, MaxAddressLength ); debug_printf( "failed to remove encryption mapping for %s\n", addressString ); #endif // #if YOJIMBO_DEBUG_SPAM return false; }
bool Address::operator<(const Address &addr) const { return ToString() < addr.ToString(); }
bool Architecture::FormatInstruction( Document const& rDoc, Address const& rAddr, Instruction const& rInsn, PrintData & rPrintData) const { char const* Sep = nullptr; rPrintData.AppendMnemonic(rInsn.GetName()); std::string OpRefCmt; rDoc.GetComment(rAddr, OpRefCmt); for (unsigned int i = 0; i < OPERAND_NO; ++i) { Operand const* pOprd = rInsn.Operand(i); if (pOprd == nullptr) break; if (pOprd->GetType() == O_NONE) break; if (Sep != nullptr) rPrintData.AppendOperator(Sep).AppendSpace(); else Sep = ","; if (!FormatOperand(rDoc, rAddr, rInsn, *pOprd, i, rPrintData)) return false; Address OpRefAddr; if (OpRefCmt.empty() && rInsn.GetOperandReference(rDoc, i, rAddr, OpRefAddr)) { Id OpId; if (rDoc.RetrieveDetailId(OpRefAddr, 0, OpId)) { FunctionDetail FuncDtl; if (rDoc.GetFunctionDetail(OpId, FuncDtl)) { // TODO: provide helper to avoid this... u16 CmtOff = static_cast<u16>(rPrintData.GetCurrentText().length()) - 6 - 1 - rAddr.ToString().length(); rPrintData.AppendSpace().AppendComment(";").AppendSpace(); FormatTypeDetail(FuncDtl.GetReturnType(), rPrintData); rPrintData.AppendSpace().AppendLabel(FuncDtl.GetName()).AppendOperator("("); if (!FuncDtl.GetParameters().empty()) rPrintData.AppendNewLine().AppendSpace(CmtOff).AppendComment(";").AppendSpace(3); bool FirstParam = true; for (auto const& rParam : FuncDtl.GetParameters()) { if (FirstParam) FirstParam = false; else rPrintData.AppendOperator(",").AppendNewLine().AppendSpace(CmtOff).AppendComment(";").AppendSpace(3); FormatTypeDetail(rParam.GetType(), rPrintData); rPrintData.AppendSpace().AppendLabel(rParam.GetValue().GetName()); } rPrintData.AppendOperator(");"); } } } } return true; }
bool LlvmEmulator::Execute(Address const& rAddress, Expression::List const& rExprList) { auto RegPc = m_pCpuInfo->GetRegisterByType(CpuInformation::ProgramPointerRegister); auto RegSz = m_pCpuInfo->GetSizeOfRegisterInBit(RegPc) / 8; u64 CurPc = 0; m_pCpuCtxt->ReadRegister(RegPc, &CurPc, RegSz); static llvm::FunctionType* s_pExecFuncType = nullptr; if (s_pExecFuncType == nullptr) { auto pBytePtrType = llvm::Type::getInt8PtrTy(llvm::getGlobalContext()); std::vector<llvm::Type*> Params; Params.push_back(pBytePtrType); Params.push_back(pBytePtrType); Params.push_back(pBytePtrType); s_pExecFuncType = llvm::FunctionType::get(llvm::Type::getVoidTy(llvm::getGlobalContext()), Params, false); } u64 LinAddr; if (m_pCpuCtxt->Translate(rAddress, LinAddr) == false) return nullptr; llvm::Function* pExecFunc = m_FunctionCache[LinAddr]; if (pExecFunc == nullptr) { pExecFunc = llvm::Function::Create(s_pExecFuncType, llvm::GlobalValue::ExternalLinkage, std::string("fn_") + rAddress.ToString(), sm_pModule); auto itParam = pExecFunc->arg_begin(); auto pCpuCtxtParam = itParam++; auto pCpuCtxtObjParam = itParam++; auto pMemCtxtObjParam = itParam; auto pBscBlk = llvm::BasicBlock::Create(llvm::getGlobalContext(), "bb", pExecFunc); m_Builder.SetInsertPoint(pBscBlk); CpuContext::RegisterList RegList; m_pCpuCtxt->GetRegisters(RegList); for (u32 Reg : RegList) { u32 RegSize = m_pCpuInfo->GetSizeOfRegisterInBit(Reg); auto RegName = m_pCpuInfo->ConvertIdentifierToName(Reg); auto RegOff = m_pCpuCtxt->GetRegisterOffset(Reg); assert(m_pVarCtxt->AllocateVariable(RegSize, RegName)); auto pSrcPtr = m_Builder.CreateGEP(pCpuCtxtParam, llvm::ConstantInt::get(llvm::getGlobalContext(), llvm::APInt(32, RegOff))); auto pValPtr = m_Builder.CreateBitCast(pSrcPtr, llvm::Type::getIntNPtrTy(llvm::getGlobalContext(), RegSize)); auto pVal = m_Builder.CreateLoad(pValPtr); auto pVarPtr = reinterpret_cast<llvm::Value*>(m_pVarCtxt->GetVariable(RegName)); m_Builder.CreateStore(pVal, pVarPtr); });
//////////////////////////////////////////////////////////////////////////////////// /// /// \brief Method called periodically by external classes and is used to /// verify control of components. /// /// \param[in] timeSinceLastCheckMs Number of milliseconds since the last time /// this method was called. /// //////////////////////////////////////////////////////////////////////////////////// void AccessControl::CheckServiceStatus(const unsigned int timeSinceLastCheckMs) { RequestControl request; Address::Set lostComponents; Time currentTime; // Upgrade/Read lock { #ifdef JAUS_USE_UPGRADE_LOCKS UpgradeLock uLock(mControlMutex); #else WriteLock wLock(mControlMutex); #endif request.SetSourceID(GetComponentID()); request.SetAuthorityCode(mAuthorityCode); Address::Set::iterator component; currentTime.SetCurrentTime(); for(component = mControlledComponents.begin(); component != mControlledComponents.end(); component++) { // If we are releasing control, do not check. if(mToReleaseControl.find(*component) != mToReleaseControl.end()) { continue; } // If we have not checked within timeout - .x seconds, then re-acquire control to // maintain constant control of component. double thresh = mTimeoutPeriods[*component]*mTimeoutThreshold/100.0; double checkTimeDiff = currentTime.ToSeconds() - mControlCheckTimes[*component].ToSeconds(); double timeThresh = (mTimeoutPeriods[*component] - thresh); bool checkConfirmation = true; if(mTimeoutPeriods[*component] > 0 && checkTimeDiff >= thresh) { request.SetDestinationID(*component); if(Send(&request)) { // Update the check time. #ifdef JAUS_USE_UPGRADE_LOCKS UpgradeToUniqueLock upLock(uLock); #endif mControlCheckTimes[*component].SetCurrentTime(); checkConfirmation = false; } } double confirmTimeDiff = currentTime.ToSeconds() - mControlConfirmTimes[*component].ToSeconds(); timeThresh = (mTimeoutPeriods[*component] + thresh); // If we haven't been confirmed in this time, then we have lost control. if(checkConfirmation && confirmTimeDiff > timeThresh) { mControlFlags[*component] = false; lostComponents.insert(*component); } } } // Notify subscribers of any lost control events. { Address::Set::iterator lost; for(lost = lostComponents.begin(); lost != lostComponents.end(); lost++) { // Generate events and callbacks. ReadLock cbrLock(mCallbacksMutex); Callback::Set::iterator cb; for(cb = mCallbacks.begin(); cb != mCallbacks.end(); cb++) { (*cb)->ProcessLossOfControl(*lost); } } } Address controller; // Current controlling component. bool timeout = false; { #ifdef JAUS_USE_UPGRADE_LOCKS UpgradeLock uLock(mControlMutex); #else WriteLock wLock(mControlMutex); #endif controller = mControllerID; currentTime.SetCurrentTime(); double timeSinceRequest = currentTime - mControllerCheckTime; if(mTimeoutPeriod > 0 && controller.IsValid() && timeSinceRequest >= (double)mTimeoutPeriod + mTimeoutPeriod*mTimeoutThreshold/100.0) { timeout = true; // Release control due to timeout. RejectControl reject(controller, GetComponentID()); reject.SetResponseCode(RejectControl::ControlReleased); Send(&reject); if(DebugMessagesEnabled()) { std::stringstream dMessage; dMessage << "[" << GetServiceID().ToString() << "-" << mComponentID.ToString() << "] - Control Time from " << controller.ToString() << " at " << Time::GetUtcTime().ToString(); PrintDebugMessage(dMessage.str()); } { #ifdef JAUS_USE_UPGRADE_LOCKS UpgradeToUniqueLock upLock(uLock); #endif // Clear values. mControllerID.Clear(); mControllerAuthorityCode = 0; mControllerCheckTime.Clear(); mControllerUpdateTime.Clear(); } } } if(timeout) { { ReadLock cbrLock(mCallbacksMutex); Callback::Set::iterator cb; for(cb = mCallbacks.begin(); cb != mCallbacks.end(); cb++) { (*cb)->ProcessReleaseOfControl(controller); } } Service::Map children = GetChildServices(); Service::Map::iterator child; for(child = children.begin(); child != children.end(); child++) { Child* controlChild = dynamic_cast<Child *>(child->second); if(controlChild) { controlChild->ReleaseControl(); } } SignalEvent(REPORT_CONTROL); } }
//////////////////////////////////////////////////////////////////////////////////// /// /// \brief Method to update client connections or create new ones. /// /// \param[in] id The ID of the JAUS component to update connections for. /// \param[in] ipAddress IP Address of source of message. /// \param[in] sourcePort The source port the data was received on. /// /// \return 1 if a new connection was made, 0 otherwise. /// //////////////////////////////////////////////////////////////////////////////////// int JUDP::UpdateClientConnections(const Address& id, const CxUtils::IP4Address& ipAddress, const unsigned short sourcePort) { int result = 0; std::map<Address, Time::Stamp>::iterator times; std::map<Address, CxUtils::UdpClient*>::iterator client; mClientsMutex.Lock(); client = mClients.find(id); if(client == mClients.end()) { // Create connection to the socket, but using the socket that received // the message. This is done so we are sending from the same port that we // received on. CxUtils::UdpClient* udp = mMulticast.CreateNewDestination(ipAddress, sourcePort); if(udp) { mClients[id] = udp; mUpdateTimes[id] = Time::GetUtcTimeMs(); udp = NULL; result = 1; } else { if(mDebugMessagesFlag) { Mutex::ScopedLock lock(&mDebugMessagesMutex); std::cout << "[" << GetServiceID().ToString() << "-" << mComponentID.ToString() << "] - New Connection Made to " << id.ToString() << " at IP:" << ipAddress.mString << std::endl; } } } else { times = mUpdateTimes.find(id); // Check to see if the IP address has changed from this // source, but only check if we haven't received data from // this source for more than a second or so. if(ipAddress != client->second->GetConnectionAddress()) { // Re-create connection. CxUtils::UdpClient* newClient = mMulticast.CreateNewDestination(ipAddress, sourcePort); CxUtils::UdpClient* oldClient = client->second; client->second = newClient; delete oldClient; } // Check that I am sending to the same port they are sending from. else if(sourcePort != client->second->GetDestinationPort()) { // Re-create connection. CxUtils::UdpClient* newClient = mMulticast.CreateNewDestination(ipAddress, sourcePort); CxUtils::UdpClient* oldClient = client->second; client->second = newClient; delete oldClient; } // Update receive time so we don't close this // connection. times->second = Time::GetUtcTimeMs(); } mClientsMutex.Unlock(); return result; }
//////////////////////////////////////////////////////////////////////////////////// /// /// \brief Method called periodically by external classes and is used to /// verify control of components. /// /// \param[in] timeSinceLastCheckMs Number of milliseconds since the last time /// this method was called. /// //////////////////////////////////////////////////////////////////////////////////// void AccessControl::CheckServiceStatus(const unsigned int timeSinceLastCheckMs) { RequestControl request; mControlMutex.Lock(); request.SetSourceID(GetComponentID()); request.SetAuthorityCode(mAuthorityCode); Address::Set::iterator component; Time currentTime; currentTime.SetCurrentTime(); for(component = mControlledComponents.begin(); component != mControlledComponents.end(); component++) { // If we are releasing control, do not check. if(mToReleaseControl.find(*component) != mToReleaseControl.end()) { continue; } // If we have not checked within timeout - .x seconds, then re-acquire control to // maintain constant control of component. double thresh = mTimeoutPeriods[*component]*mTimeoutThreshold/100.0; double checkTimeDiff = currentTime.ToSeconds() - mControlCheckTimes[*component].ToSeconds(); double timeThresh = (mTimeoutPeriods[*component] - thresh); bool checkConfirmation = true; if(mTimeoutPeriods[*component] > 0 && checkTimeDiff >= thresh) { request.SetDestinationID(*component); if(Send(&request)) { // Update the check time. mControlCheckTimes[*component].SetCurrentTime(); checkConfirmation = false; } } double confirmTimeDiff = currentTime.ToSeconds() - mControlConfirmTimes[*component].ToSeconds(); timeThresh = (mTimeoutPeriods[*component] + thresh); // If we haven't been confirmed in this time, then we have lost control. if(checkConfirmation && confirmTimeDiff > timeThresh) { mControlFlags[*component] = false; // Generate events and callbacks. Mutex::ScopedLock clock(&mCallbacksMutex); Callback::Set::iterator cb; for(cb = mCallbacks.begin(); cb != mCallbacks.end(); cb++) { (*cb)->ProcessLossOfControl(*component); } } } mControlMutex.Unlock(); // Allow control check time to update. mControlMutex.Lock(); Address controller = mControllerID; bool timeout = false; currentTime.SetCurrentTime(); double timeSinceRequest = currentTime - mControllerCheckTime; if(mTimeoutPeriod > 0 && controller.IsValid() && timeSinceRequest >= (double)mTimeoutPeriod + mTimeoutPeriod*mTimeoutThreshold/100.0) { timeout = true; // Release control due to timeout. RejectControl reject(controller, GetComponentID()); reject.SetResponseCode(RejectControl::ControlReleased); Send(&reject); if(mDebugMessagesFlag) { Mutex::ScopedLock plock(&mDebugMessagesMutex); std::cout << "[" << GetServiceID().ToString() << "-" << mComponentID.ToString() << "] - Control Time Out From " << controller.ToString() << " at " << Time::GetUtcTime().ToString() << "\n"; } // Clear values. mControllerID.Clear(); mControllerAuthorityCode = 0; mControllerCheckTime.Clear(); mControllerUpdateTime.Clear(); } mControlMutex.Unlock(); if(timeout) { Callback::Set::iterator cb; for(cb = mCallbacks.begin(); cb != mCallbacks.end(); cb++) { (*cb)->ProcessReleaseOfControl(controller); } Service::Map children = GetChildServices(); Service::Map::iterator child; for(child = children.begin(); child != children.end(); child++) { Child* controlChild = dynamic_cast<Child *>(child->second); if(controlChild) { controlChild->ReleaseControl(); } } SignalEvent(REPORT_CONTROL); } }
bool Architecture::FormatInstruction( Document const& rDoc, BinaryStream const& rBinStrm, Address const& rAddr, Instruction const& rInsn, std::string & rStrCell, Cell::Mark::List & rMarks) const { char Sep = '\0'; std::ostringstream oss; oss << rInsn.GetName() << " "; rMarks.push_back(Cell::Mark(Cell::Mark::MnemonicType, oss.str().size())); for (unsigned int i = 0; i < OPERAND_NO; ++i) { Operand const* pOprd = rInsn.Operand(i); if (pOprd == nullptr) break; if (pOprd->GetType() == O_NONE) break; if (Sep != '\0') { oss << Sep << " "; rMarks.push_back(Cell::Mark(Cell::Mark::OperatorType, 2)); } u32 OprdType = pOprd->GetType(); std::string OprdName = pOprd->GetName(); std::string MemBegChar = "["; std::string MemEndChar = "]"; // NOTE: Since we have to mark all characters with good type, we handle O_MEM here. if (pOprd->GetType() & O_MEM) { MemBegChar = *OprdName.begin(); MemEndChar = *OprdName.rbegin(); OprdName = OprdName.substr(1, OprdName.length() - 2); } if (OprdType & O_MEM) { oss << MemBegChar; rMarks.push_back(Cell::Mark(Cell::Mark::OperatorType, 1)); } do { if (OprdType & O_REL || OprdType & O_ABS) { Address DstAddr; if (rInsn.GetOperandReference(rDoc, 0, rAddr, DstAddr)) { auto Lbl = rDoc.GetLabelFromAddress(DstAddr); OprdName = Lbl.GetLabel(); Cell::Mark::Type MarkType = Cell::Mark::LabelType; if (OprdName.empty()) { OprdName = DstAddr.ToString(); MarkType = Cell::Mark::ImmediateType; } oss << OprdName; rMarks.push_back(Cell::Mark(MarkType, OprdName.length())); } else { oss << OprdName; rMarks.push_back(Cell::Mark(Cell::Mark::ImmediateType, OprdName.length())); } } else if (OprdType & O_DISP || OprdType & O_IMM) { if (pOprd->GetType() & O_NO_REF) { std::string ValueName = pOprd->GetName(); oss << ValueName; rMarks.push_back(Cell::Mark(Cell::Mark::ImmediateType, ValueName.length())); break; } Address OprdAddr(Address::UnknownType, pOprd->GetSegValue(), pOprd->GetValue()); auto Lbl = rDoc.GetLabelFromAddress(OprdAddr); std::string LabelName = Lbl.GetLabel(); if (LabelName.empty()) { std::string ValueName = OprdName; oss << ValueName; rMarks.push_back(Cell::Mark(Cell::Mark::ImmediateType, ValueName.length())); break; } oss << LabelName; rMarks.push_back(Cell::Mark(Cell::Mark::LabelType, LabelName.length())); } else if (OprdType & O_REG) { if (OprdName.empty()) { auto pCpuInfo = GetCpuInformation(); OprdName = pCpuInfo->ConvertIdentifierToName(pOprd->GetReg()); } oss << OprdName; rMarks.push_back(Cell::Mark(Cell::Mark::RegisterType, OprdName.length())); } } while (0); if (OprdType & O_MEM) { oss << MemEndChar; rMarks.push_back(Cell::Mark(Cell::Mark::OperatorType, 1)); } Sep = ','; } //auto rExpr = rInsn.GetSemantic(); //if (rExpr.empty() == false) //{ // auto BegMark = oss.str().length(); // oss << " [ "; // auto itExpr = std::begin(rExpr); // oss << (*itExpr)->ToString(); // ++itExpr; // std::for_each(itExpr, std::end(rExpr), [&oss](Expression const* pExpr) // { // oss << "; " << pExpr->ToString(); // }); // oss << " ]"; // rMarks.push_back(Cell::Mark::KeywordType, oss.str().length() - BegMark); //} rStrCell = oss.str(); return true; }
//////////////////////////////////////////////////////////////////////////////////// /// /// \brief Initializes the Transport Service based on configuration values /// set. /// /// \param[in] componentID ID of the component using the Transport Service. /// /// \return True on success, false on failure. /// //////////////////////////////////////////////////////////////////////////////////// bool JUDP::Initialize(const Address& componentID) { if(componentID.IsValid() == false || componentID.IsBroadcast()) { return false; } Shutdown(); // Save ID. mComponentID = componentID; CxUtils::IP4Address::List hostnames; CxUtils::IP4Address::List::iterator eth0; CxUtils::Socket::GetHostAddresses(hostnames); if(hostnames.size() == 0 && mDebugMessagesFlag) { Mutex::ScopedLock lock(&mDebugMessagesMutex); std::cout << "[JUDP-" << mComponentID.ToString() << "] - No Network Interface Found.\n"; } unsigned int count = 0; for(eth0 = hostnames.begin(); eth0 != hostnames.end(); eth0++, count++) { // Use any or specified interface. if(mHostIP.mString == "0.0.0.0" || mHostIP.mString == "127.0.0.1" || mHostIP.mString.empty() || mHostIP == *eth0) { // Initialize UDP receiving. if(mInput.InitializeMulticastSocket(Port, mMulticastIP, true)) { mMulticast.SetNetworkInterface(*eth0); if(mMulticast.InitializeMulticastSocket(mMulticastIP, Port, mTimeToLive, mUseBroadcastingFlag, 0)) { SetComponentID(componentID); mPrimaryThread.CreateThread(JUDP::ReceiveThread, this); CxUtils::SleepMs(250); mSecondaryThread.CreateThread(JUDP::ReceiveThread, this); // Set thread names. mPrimaryThread.SetThreadName(std::string("JUDP 1 ") + componentID.ToString()); mSecondaryThread.SetThreadName(std::string("JUDP 2 ") + componentID.ToString()); return true; } } /* mPrimarySocket.SetNetworkInterface(mHostIP); mSecondarySocket.SetNetworkInterface(mHostIP); // Try initialize on 3794 first, but accept any available. if(mPrimarySocket.InitializeMulticastSocket(mMulticastIP, Port, mTimeToLive, mUseBroadcastingFlag, Port, true) && mSecondarySocket.InitializeMulticastSocket(mMulticastIP, Port, mTimeToLive, mUseBroadcastingFlag, 0, false)) { SetComponentID(componentID); mPrimaryThread.CreateThread(JUDP::PrimaryThread, this); std::string threadName = std::string("JUDP 1 ") + componentID.ToString(); mPrimaryThread.SetThreadName(threadName); // Have a thread to discover new UDP clients that are transmitting. mSecondaryThread.CreateThread(JUDP::SecondaryThread, this); threadName = std::string("JUDP 2 ") + componentID.ToString(); mSecondaryThread.SetThreadName(threadName); return true; } */ } } Shutdown(); return false; }