void NetworkSimulator::SendPacket( const Address & from, const Address & to, uint8_t * packetData, int packetSize ) { assert( from.IsValid() ); assert( to.IsValid() ); assert( packetData ); assert( packetSize > 0 ); if ( random_float( 0.0f, 100.0f ) <= m_packetLoss ) { m_allocator->Free( packetData ); return; } PacketEntry & packetEntry = m_packetEntries[m_currentIndex]; if ( packetEntry.packetData ) { m_allocator->Free( packetEntry.packetData ); packetEntry = PacketEntry(); } double delay = m_latency / 1000.0; if ( m_jitter > 0 ) delay += random_float( -m_jitter, +m_jitter ) / 1000.0; packetEntry.from = from; packetEntry.to = to; packetEntry.packetData = packetData; packetEntry.packetSize = packetSize; packetEntry.deliveryTime = m_time + delay; m_currentIndex = ( m_currentIndex + 1 ) % m_numPacketEntries; if ( random_float( 0.0f, 100.0f ) <= m_duplicates ) { uint8_t * duplicatePacketData = (uint8_t*) m_allocator->Allocate( packetSize ); memcpy( duplicatePacketData, packetData, packetSize ); PacketEntry & nextPacketEntry = m_packetEntries[m_currentIndex]; nextPacketEntry.from = from; nextPacketEntry.to = to; nextPacketEntry.packetData = duplicatePacketData; nextPacketEntry.packetSize = packetSize; nextPacketEntry.deliveryTime = m_time + delay + random_float( -10.0, +10.0 ); m_currentIndex = ( m_currentIndex + 1 ) % m_numPacketEntries; } }
//////////////////////////////////////////////////////////////////////////////////// /// /// \brief Method to add a new connection manually to a component at an /// IP address. /// /// \param[in] networkIP IP Address of component. /// \param[in] jausID JAUS ID of component. /// \param[in] port Network port to use (default is 3794). /// /// \return True on success, false on failure. /// //////////////////////////////////////////////////////////////////////////////////// bool JUDP::AddConnection(const CxUtils::IP4Address& networkIP, const Address& jausID, const unsigned short port) { bool result = false; if(jausID.IsValid() && !jausID.IsBroadcast()) { Mutex::ScopedLock lock(&mClientsMutex); std::map<Address, CxUtils::UdpClient*>::iterator citer; citer = mClients.find(jausID); if(citer == mClients.end()) { CxUtils::UdpClient* udp = mMulticast.CreateNewDestination(networkIP, port); if(udp) { mClients[jausID] = udp; mUpdateTimes[jausID] = Time::GetUtcTimeMs(); mPermanentConnections[jausID] = true; udp = NULL; result = true; } else { if(mDebugMessagesFlag) { Mutex::ScopedLock lock(&mDebugMessagesMutex); std::cout << "[" << GetServiceID().ToString() << "-" << mComponentID.ToString() << "] - New Connection Made to " << jausID << " at IP:" << networkIP.mString << std::endl; } } } } return result; }
static void ResolveAddress (const ExecutionContext &exe_ctx, const Address &addr, Address &resolved_addr) { if (!addr.IsSectionOffset()) { // If we weren't passed in a section offset address range, // try and resolve it to something Target *target = exe_ctx.GetTargetPtr(); if (target) { if (target->GetSectionLoadList().IsEmpty()) { target->GetImages().ResolveFileAddress (addr.GetOffset(), resolved_addr); } else { target->GetSectionLoadList().ResolveLoadAddress (addr.GetOffset(), resolved_addr); } // We weren't able to resolve the address, just treat it as a // raw address if (resolved_addr.IsValid()) return; } } resolved_addr = addr; }
//////////////////////////////////////////////////////////////////////////////////// /// /// \return ID of the controlling component. /// //////////////////////////////////////////////////////////////////////////////////// void AccessControl::SetControllerID(const Address& id) { if(id.IsValid() && !id.IsBroadcast()) { Mutex::ScopedLock lock(&mControlMutex); mControllerID = id; } }
//////////////////////////////////////////////////////////////////////////////////// /// /// \brief Set the ID of controlling component. /// /// \param[in] ID of the controlling component. /// //////////////////////////////////////////////////////////////////////////////////// void AccessControl::SetControllerID(const Address& id) { if(id.IsValid() && !id.IsBroadcast()) { WriteLock wLock(mControlMutex); mControllerID = id; } }
bool UnwindPlan::PlanValidAtAddress (Address addr) { // If this UnwindPlan has no rows, it is an invalid UnwindPlan. if (GetRowCount() == 0) { Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_UNWIND)); if (log) { StreamString s; if (addr.Dump (&s, nullptr, Address::DumpStyleSectionNameOffset)) { log->Printf ("UnwindPlan is invalid -- no unwind rows for UnwindPlan '%s' at address %s", m_source_name.GetCString(), s.GetData()); } else { log->Printf ("UnwindPlan is invalid -- no unwind rows for UnwindPlan '%s'", m_source_name.GetCString()); } } return false; } // If the 0th Row of unwind instructions is missing, or if it doesn't provide // a register to use to find the Canonical Frame Address, this is not a valid UnwindPlan. if (GetRowAtIndex(0).get() == nullptr || GetRowAtIndex(0)->GetCFAValue().GetValueType() == Row::CFAValue::unspecified) { Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_UNWIND)); if (log) { StreamString s; if (addr.Dump (&s, nullptr, Address::DumpStyleSectionNameOffset)) { log->Printf ("UnwindPlan is invalid -- no CFA register defined in row 0 for UnwindPlan '%s' at address %s", m_source_name.GetCString(), s.GetData()); } else { log->Printf ("UnwindPlan is invalid -- no CFA register defined in row 0 for UnwindPlan '%s'", m_source_name.GetCString()); } } return false; } if (!m_plan_valid_address_range.GetBaseAddress().IsValid() || m_plan_valid_address_range.GetByteSize() == 0) return true; if (!addr.IsValid()) return true; if (m_plan_valid_address_range.ContainsFileAddress (addr)) return true; return false; }
//////////////////////////////////////////////////////////////////////////////////// /// /// \brief Sets the destination ID of the message. /// /// \param[in] dest Destination ID. Must be a valid ID. /// /// \return OK on success, FAILURE on error. /// //////////////////////////////////////////////////////////////////////////////////// int Message::SetDestinationID(const Address& dest) { if(dest.IsValid()) { mDestinationID = dest; return OK; } return FAILURE; }
//////////////////////////////////////////////////////////////////////////////////// /// /// \brief Sets the source ID of the message. /// /// \param[in] src Source ID. Must be valid and non-broadcast. /// /// \return OK on success, FAILURE on error. /// //////////////////////////////////////////////////////////////////////////////////// int Message::SetSourceID(const Address& src) { if(src.IsValid() && !src.IsBroadcast()) { mSourceID = src; return OK; } return FAILURE; }
addr_t ProcessFreeBSD::GetImageInfoAddress() { Target *target = &GetTarget(); ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile(); Address addr = obj_file->GetImageInfoAddress(target); if (addr.IsValid()) return addr.GetLoadAddress(target); return LLDB_INVALID_ADDRESS; }
lldb::addr_t ProcessElfCore::GetImageInfoAddress() { ObjectFile *obj_file = GetTarget().GetExecutableModule()->GetObjectFile(); Address addr = obj_file->GetImageInfoAddress(&GetTarget()); if (addr.IsValid()) return addr.GetLoadAddress(&GetTarget()); return LLDB_INVALID_ADDRESS; }
lldb::addr_t ProcessWindows::GetImageInfoAddress() { Target &target = GetTarget(); ObjectFile *obj_file = target.GetExecutableModule()->GetObjectFile(); Address addr = obj_file->GetImageInfoAddress(&target); if (addr.IsValid()) return addr.GetLoadAddress(&target); else return LLDB_INVALID_ADDRESS; }
bool EmulateInstruction::SetInstruction(const Opcode &opcode, const Address &inst_addr, Target *target) { m_opcode = opcode; m_addr = LLDB_INVALID_ADDRESS; if (inst_addr.IsValid()) { if (target != nullptr) m_addr = inst_addr.GetLoadAddress(target); if (m_addr == LLDB_INVALID_ADDRESS) m_addr = inst_addr.GetFileAddress(); } return true; }
//////////////////////////////////////////////////////////////////////////////////// /// /// \brief If synchronization is enabled, then this method is used to /// subscribe to sensor data from the component we are synchronizing /// with. /// /// \param[in] timeSinceLastCheckMs Time since last update in ms. /// //////////////////////////////////////////////////////////////////////////////////// void TimeService::CheckServiceSynchronization(const unsigned int timeSinceLastCheckMs) { Address syncID = GetSynchronizeID(); if(syncID.IsValid()) { // See if we have an active subscription if(EventsService()->HaveSubscription(REPORT_TIME, syncID) == false) { QueryTime query(syncID, GetComponentID()); query.SetPresenceVector(query.GetPresenceVectorMask()); EventsService()->RequestEveryChangeEvent(syncID, &query); } } }
bool UnwindPlan::PlanValidAtAddress (Address addr) { if (!m_plan_valid_address_range.GetBaseAddress().IsValid() || m_plan_valid_address_range.GetByteSize() == 0) return true; if (!addr.IsValid()) return true; if (m_plan_valid_address_range.ContainsFileAddress (addr)) return true; return false; }
size_t Disassembler::ParseInstructions (const ExecutionContext *exe_ctx, const Address &start, uint32_t num_instructions, bool prefer_file_cache) { m_instruction_list.Clear(); if (exe_ctx == NULL || num_instructions == 0 || !start.IsValid()) return 0; Target *target = exe_ctx->GetTargetPtr(); // Calculate the max buffer size we will need in order to disassemble const addr_t byte_size = num_instructions * m_arch.GetMaximumOpcodeByteSize(); if (target == NULL || byte_size == 0) return 0; DataBufferHeap *heap_buffer = new DataBufferHeap (byte_size, '\0'); DataBufferSP data_sp (heap_buffer); Error error; lldb::addr_t load_addr = LLDB_INVALID_ADDRESS; const size_t bytes_read = target->ReadMemory (start, prefer_file_cache, heap_buffer->GetBytes(), byte_size, error, &load_addr); const bool data_from_file = load_addr == LLDB_INVALID_ADDRESS; if (bytes_read == 0) return 0; DataExtractor data (data_sp, m_arch.GetByteOrder(), m_arch.GetAddressByteSize()); const bool append_instructions = true; DecodeInstructions (start, data, 0, num_instructions, append_instructions, data_from_file); return m_instruction_list.GetSize(); }
//////////////////////////////////////////////////////////////////////////////////// /// /// \brief Check if control has been established for a component. /// /// \param[in] id The ID of the component to check for control of. If a /// ID of 0.0.0 is passed, then the method will check if we /// are in control of any components. /// /// \return True if you have control, false otherwise. /// //////////////////////////////////////////////////////////////////////////////////// bool AccessControl::HaveControl(const Address& id) const { Mutex::ScopedLock lock(&mControlMutex); if(id.IsValid() == false && mControlledComponents.size() != 0) { return true; } Address::Set::const_iterator c; c = mControlledComponents.find(id); if(c != mControlledComponents.end()) { return mControlFlags.find(*c)->second; } return false; }
//////////////////////////////////////////////////////////////////////////////////// /// /// \brief If synchronization is enabled, then this method is used to /// subscribe to sensor data from the component we are synchronizing /// with. /// /// \param[in] timeSinceLastCheckMs Time since last update in ms. /// //////////////////////////////////////////////////////////////////////////////////// void GlobalPoseSensor::CheckServiceSynchronization(const unsigned int timeSinceLastCheckMs) { Address syncID = GetSynchronizeID(); if(syncID.IsValid()) { // See if we have an active subscription, and if not create it. if(EventsService()->HaveSubscription(REPORT_GLOBAL_POSE, syncID) == false) { QueryGlobalPose query(syncID, GetComponentID()); query.SetPresenceVector(query.GetPresenceVectorMask()); EventsService()->RequestEveryChangeEvent(syncID, &query); } if(EventsService()->HaveSubscription(REPORT_GEOMAGNETIC_PROPERTY, syncID) == false) { QueryGeomagneticProperty query(syncID, GetComponentID()); EventsService()->RequestEveryChangeEvent(syncID, &query); } } }
SimulatorTransport::SimulatorTransport( Allocator & allocator, NetworkSimulator & networkSimulator, PacketFactory & packetFactory, const Address & address, uint32_t protocolId, int maxPacketSize, int sendQueueSize, int receiveQueueSize ) : BaseTransport( allocator, packetFactory, address, protocolId, maxPacketSize, sendQueueSize, receiveQueueSize ) { assert( address.IsValid() ); m_networkSimulator = &networkSimulator; }
addr_t JITLoaderGDB::GetSymbolAddress(ModuleList &module_list, const ConstString &name, SymbolType symbol_type) const { SymbolContextList target_symbols; Target &target = m_process->GetTarget(); if (!module_list.FindSymbolsWithNameAndType(name, symbol_type, target_symbols)) return LLDB_INVALID_ADDRESS; SymbolContext sym_ctx; target_symbols.GetContextAtIndex(0, sym_ctx); const Address jit_descriptor_addr = sym_ctx.symbol->GetAddress(); if (!jit_descriptor_addr.IsValid()) return LLDB_INVALID_ADDRESS; const addr_t jit_addr = jit_descriptor_addr.GetLoadAddress(&target); return jit_addr; }
//////////////////////////////////////////////////////////////////////////////////// /// /// \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 BaseTransport::SendPacket( const Address & address, Packet * packet, uint64_t sequence, bool immediate ) { assert( m_allocator ); assert( m_packetFactory ); assert( packet ); assert( packet->IsValid() ); assert( address.IsValid() ); if ( immediate ) { m_counters[TRANSPORT_COUNTER_PACKETS_SENT]++; WriteAndFlushPacket( address, packet, sequence ); m_packetFactory->DestroyPacket( packet ); } else { if ( !m_sendQueue.IsFull() ) { PacketEntry entry; entry.sequence = sequence; entry.address = address; entry.packet = packet; m_sendQueue.Push( entry ); } else { debug_printf( "base transport send queue overflow\n" ); m_counters[TRANSPORT_COUNTER_SEND_QUEUE_OVERFLOW]++; m_packetFactory->DestroyPacket( packet ); return; } } m_counters[TRANSPORT_COUNTER_PACKETS_SENT]++; }
void BaseTransport::WriteAndFlushPacket( const Address & address, Packet * packet, uint64_t sequence ) { assert( packet ); assert( packet->IsValid() ); assert( address.IsValid() ); const int packetType = packet->GetType(); assert( packetType >= 0 ); assert( packetType < m_packetFactory->GetNumPacketTypes() ); const double time = GetTime(); int packetBytes; const uint8_t * key = m_encryptionManager.GetSendKey( address, time ); #if YOJIMBO_INSECURE_CONNECT const bool encrypt = ( GetFlags() & TRANSPORT_FLAG_INSECURE_MODE ) ? IsEncryptedPacketType( packetType ) && key : IsEncryptedPacketType( packetType ); #else // #if YOJIMBO_INSECURE_CONNECT const bool encrypt = IsEncryptedPacketType( packetType ); #endif // #if YOJIMBO_INSECURE_CONNECT const uint8_t * packetData = m_packetProcessor->WritePacket( packet, sequence, packetBytes, encrypt, key ); if ( !packetData ) { switch ( m_packetProcessor->GetError() ) { case PACKET_PROCESSOR_ERROR_KEY_IS_NULL: { debug_printf( "base transport packet processor key is null (write packet)\n" ); m_counters[TRANSPORT_COUNTER_ENCRYPTION_MAPPING_FAILURES]++; } break; case PACKET_PROCESSOR_ERROR_ENCRYPT_FAILED: { debug_printf( "base transport encrypt failed (write packet)\n" ); m_counters[TRANSPORT_COUNTER_ENCRYPT_PACKET_FAILURES]++; } break; case PACKET_PROCESSOR_ERROR_WRITE_PACKET_FAILED: { debug_printf( "base transport write packet failed (write packet)\n" ); m_counters[TRANSPORT_COUNTER_WRITE_PACKET_FAILURES]++; } break; default: break; } return; } InternalSendPacket( address, packetData, packetBytes ); m_counters[TRANSPORT_COUNTER_PACKETS_WRITTEN]++; if ( encrypt ) m_counters[TRANSPORT_COUNTER_ENCRYPTED_PACKETS_WRITTEN]++; else m_counters[TRANSPORT_COUNTER_UNENCRYPTED_PACKETS_WRITTEN]++; }
//////////////////////////////////////////////////////////////////////////////////// /// /// \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); } }
/// Locates the address of the rendezvous structure. Returns the address on /// success and LLDB_INVALID_ADDRESS on failure. static addr_t ResolveRendezvousAddress(Process *process) { Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); addr_t info_location; addr_t info_addr; Error error; if (!process) { if (log) log->Printf ("%s null process provided", __FUNCTION__); return LLDB_INVALID_ADDRESS; } // Try to get it from our process. This might be a remote process and might // grab it via some remote-specific mechanism. info_location = process->GetImageInfoAddress(); if (log) log->Printf ("%s info_location = 0x%" PRIx64, __FUNCTION__, info_location); // If the process fails to return an address, fall back to seeing if the local object file can help us find it. if (info_location == LLDB_INVALID_ADDRESS) { Target *target = &process->GetTarget(); if (target) { ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile(); Address addr = obj_file->GetImageInfoAddress(target); if (addr.IsValid()) { info_location = addr.GetLoadAddress(target); if (log) log->Printf ("%s resolved via direct object file approach to 0x%" PRIx64, __FUNCTION__, info_location); } else { if (log) log->Printf ("%s FAILED - direct object file approach did not yield a valid address", __FUNCTION__); } } } if (info_location == LLDB_INVALID_ADDRESS) { if (log) log->Printf ("%s FAILED - invalid info address", __FUNCTION__); return LLDB_INVALID_ADDRESS; } if (log) log->Printf ("%s reading pointer (%" PRIu32 " bytes) from 0x%" PRIx64, __FUNCTION__, process->GetAddressByteSize(), info_location); info_addr = process->ReadPointerFromMemory(info_location, error); if (error.Fail()) { if (log) log->Printf ("%s FAILED - could not read from the info location: %s", __FUNCTION__, error.AsCString ()); return LLDB_INVALID_ADDRESS; } if (info_addr == 0) { if (log) log->Printf ("%s FAILED - the rendezvous address contained at 0x%" PRIx64 " returned a null value", __FUNCTION__, info_location); return LLDB_INVALID_ADDRESS; } return info_addr; }
//////////////////////////////////////////////////////////////////////////////////// /// /// \brief Method to release exclusive control of a component. /// /// \param[in] id The ID of the component to request control of. If ID is /// invalid (all zeros), then control is released to all /// components. /// \param[in] waitTimeMs How long to wait for a response in milliseconds /// from the component being requested. /// /// \return True if control is established, otherwise false. /// //////////////////////////////////////////////////////////////////////////////////// bool AccessControl::ReleaseComponentControl(const Address& id, const unsigned int waitTimeMs) { bool result = false; if(id.IsValid() == false) { result = true; Address::Set controlled; mControlMutex.Lock(); controlled = mControlledComponents; mControlMutex.Unlock(); Address::Set::iterator component; for(component = controlled.begin(); component != controlled.end(); component++) { result &= ReleaseComponentControl(*component, waitTimeMs); } } else { std::map<Address, bool>::iterator flag; mControlMutex.Lock(); flag = mControlFlags.find(id); if(flag != mControlFlags.end()) { // If we lost control at some point, then // we don't need to release it, just remove // the component from our lists. if(flag->second == false) { result = true; // Remove the component from our lists. EraseComponentControlInfo(id); } } else { // Can't release control of a component // we never requested control from. result = true; EraseComponentControlInfo(id); } mControlMutex.Unlock(); if(!result) { // Signal control routines to not // try and maintain control for this component anymore. mControlMutex.Lock(); mToReleaseControl.insert(id); mControlMutex.Unlock(); // Send request to release control, and verify response. ReleaseControl release(id, GetComponentID()); RejectControl reject; if(Send(&release, &reject, waitTimeMs)) { if(reject.GetResponseCode() == RejectControl::ControlReleased) { result = true; Mutex::ScopedLock lock(&mControlMutex); EraseComponentControlInfo(id); } } // Remove ID. mControlMutex.Lock(); mToReleaseControl.erase(mToReleaseControl.find(id)); mControlMutex.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 SymbolContext::DumpStopContext ( Stream *s, ExecutionContextScope *exe_scope, const Address &addr, bool show_fullpaths, bool show_module, bool show_inlined_frames ) const { bool dumped_something = false; if (show_module && module_sp) { if (show_fullpaths) *s << module_sp->GetFileSpec(); else *s << module_sp->GetFileSpec().GetFilename(); s->PutChar('`'); dumped_something = true; } if (function != NULL) { SymbolContext inline_parent_sc; Address inline_parent_addr; if (function->GetMangled().GetName()) { dumped_something = true; function->GetMangled().GetName().Dump(s); } if (addr.IsValid()) { const addr_t function_offset = addr.GetOffset() - function->GetAddressRange().GetBaseAddress().GetOffset(); if (function_offset) { dumped_something = true; s->Printf(" + %" PRIu64, function_offset); } } if (GetParentOfInlinedScope (addr, inline_parent_sc, inline_parent_addr)) { dumped_something = true; Block *inlined_block = block->GetContainingInlinedBlock(); const InlineFunctionInfo* inlined_block_info = inlined_block->GetInlinedFunctionInfo(); s->Printf (" [inlined] %s", inlined_block_info->GetName().GetCString()); lldb_private::AddressRange block_range; if (inlined_block->GetRangeContainingAddress(addr, block_range)) { const addr_t inlined_function_offset = addr.GetOffset() - block_range.GetBaseAddress().GetOffset(); if (inlined_function_offset) { s->Printf(" + %" PRIu64, inlined_function_offset); } } const Declaration &call_site = inlined_block_info->GetCallSite(); if (call_site.IsValid()) { s->PutCString(" at "); call_site.DumpStopContext (s, show_fullpaths); } if (show_inlined_frames) { s->EOL(); s->Indent(); return inline_parent_sc.DumpStopContext (s, exe_scope, inline_parent_addr, show_fullpaths, show_module, show_inlined_frames); } } else { if (line_entry.IsValid()) { dumped_something = true; s->PutCString(" at "); if (line_entry.DumpStopContext(s, show_fullpaths)) dumped_something = true; } } } else if (symbol != NULL) { if (symbol->GetMangled().GetName()) { dumped_something = true; if (symbol->GetType() == eSymbolTypeTrampoline) s->PutCString("symbol stub for: "); symbol->GetMangled().GetName().Dump(s); } if (addr.IsValid() && symbol->ValueIsAddress()) { const addr_t symbol_offset = addr.GetOffset() - symbol->GetAddress().GetOffset(); if (symbol_offset) { dumped_something = true; s->Printf(" + %" PRIu64, symbol_offset); } } } else if (addr.IsValid()) { addr.Dump(s, exe_scope, Address::DumpStyleModuleWithFileAddress); dumped_something = true; } return dumped_something; }
//////////////////////////////////////////////////////////////////////////////////// /// /// \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; }