Example #1
0
void WeakRef::_notifyDestroy()
{
	incRefCount();

	ListenerList* listeners = _listeners;

	_listeners = NULL; // prevent removeListener mutate this

	if (listeners)
	{
		for (ListenerList::iterator itr = listeners->begin(), end = listeners->end(); itr != end; ++itr)
		{
			(*itr)->onDestroy(_object);
		}

		delete listeners;
	}

	_object = NULL;

	if (_listeners)
	{
		decRefCount();
		NIT_THROW_FMT(EX_INVALID_STATE, "Can't add listener while destroying one");
		return;
	}

	decRefCount();
}
Example #2
0
void U32String::clear() {
	decRefCount(_extern._refCount);

	_size = 0;
	_str = _storage;
	_storage[0] = 0;
}
Example #3
0
void DCMessenger::startReceiveMsg( classy_counted_ptr<DCMsg> msg, Sock *sock )
{
		// Currently, only one pending message per messenger.
	ASSERT( !m_callback_msg.get() );
	ASSERT( !m_callback_sock );
	ASSERT( m_pending_operation == NOTHING_PENDING );

	msg->setMessenger( this );

	std::string name;
	formatstr(name, "DCMessenger::receiveMsgCallback %s", msg->name());

	incRefCount();

	int reg_rc = daemonCore->
		Register_Socket( sock, peerDescription(),
						 (SocketHandlercpp)&DCMessenger::receiveMsgCallback,
						 name.c_str(), this, ALLOW );
	if(reg_rc < 0) {
		msg->addError(
			CEDAR_ERR_REGISTER_SOCK_FAILED,
			"failed to register socket (Register_Socket returned %d)",
			reg_rc );
		msg->callMessageReceiveFailed( this );
		doneWithSock(sock);
		decRefCount();
		return;
	}

	m_callback_msg = msg; // prevent msg from going out of reference
	m_callback_sock = sock;
	m_pending_operation = RECEIVE_MSG_PENDING;
}
Example #4
0
String& String::operator  =(char c) {
	decRefCount(_extern._refCount);
	_str = _storage;
	_size = 1;
	_str[0] = c;
	_str[1] = 0;
	return *this;
}
Example #5
0
bool
CCBListener::DoReversedCCBConnect( char const *address, char const *connect_id, char const *request_id, char const *peer_description )
{
	Daemon daemon( DT_ANY, address );
	CondorError errstack;
	Sock *sock = daemon.makeConnectedSocket(
		Stream::reli_sock,CCB_TIMEOUT,0,&errstack,true /*nonblocking*/);

	ClassAd *msg_ad = new ClassAd;
	ASSERT( msg_ad );
	msg_ad->Assign( ATTR_CLAIM_ID, connect_id );
	msg_ad->Assign( ATTR_REQUEST_ID, request_id );
		// the following is put in the message because that is an easy (lazy)
		// way to make it available to ReportReverseConnectResult
	msg_ad->Assign( ATTR_MY_ADDRESS, address);

	if( !sock ) {
			// Failed to create socket or initiate connect
		ReportReverseConnectResult(msg_ad,false,"failed to initiate connection");
		delete msg_ad;
		return false;
	}

	if( peer_description ) {
		char const *peer_ip = sock->peer_ip_str();
		if( peer_ip && !strstr(peer_description,peer_ip)) {
			MyString desc;
			desc.formatstr("%s at %s",peer_description,sock->get_sinful_peer());
			sock->set_peer_description(desc.Value());
		}
		else {
			sock->set_peer_description(peer_description);
		}
	}

	incRefCount();      // do not delete self until called back

	MyString sock_desc;
	int rc = daemonCore->Register_Socket(
		sock,
		sock->peer_description(),
		(SocketHandlercpp)&CCBListener::ReverseConnected,
		"CCBListener::ReverseConnected",
		this);

	if( rc < 0 ) {
		ReportReverseConnectResult(msg_ad,false,"failed to register socket for non-blocking reversed connection");
		delete msg_ad;
		delete sock;
		decRefCount();
		return false;
	}

	rc = daemonCore->Register_DataPtr(msg_ad);
	ASSERT( rc );

	return true;
}
Example #6
0
/**
 * Ensure that enough storage is available to store at least new_size
 * characters plus a null byte. In addition, if we currently share
 * the storage with another string, unshare it, so that we can safely
 * write to the storage.
 */
void String::ensureCapacity(uint32 new_size, bool keep_old) {
	bool isShared;
	uint32 curCapacity, newCapacity;
	char *newStorage;
	int *oldRefCount = _extern._refCount;

	if (isStorageIntern()) {
		isShared = false;
		curCapacity = _builtinCapacity;
	} else {
		isShared = (oldRefCount && *oldRefCount > 1);
		curCapacity = _extern._capacity;
	}

	// Special case: If there is enough space, and we do not share
	// the storage, then there is nothing to do.
	if (!isShared && new_size < curCapacity)
		return;

	if (isShared && new_size < _builtinCapacity) {
		// We share the storage, but there is enough internal storage: Use that.
		newStorage = _storage;
		newCapacity = _builtinCapacity;
	} else {
		// We need to allocate storage on the heap!

		// Compute a suitable new capacity limit
		newCapacity = MAX(curCapacity * 2, computeCapacity(new_size+1));

		// Allocate new storage
		newStorage = new char[newCapacity];
		assert(newStorage);
	}

	// Copy old data if needed, elsewise reset the new storage.
	if (keep_old) {
		assert(_size < newCapacity);
		memcpy(newStorage, _str, _size + 1);
	} else {
		_size = 0;
		newStorage[0] = 0;
	}

	// Release hold on the old storage ...
	decRefCount(oldRefCount);

	// ... in favor of the new storage
	_str = newStorage;

	if (!isStorageIntern()) {
		// Set the ref count & capacity if we use an external storage.
		// It is important to do this *after* copying any old content,
		// else we would override data that has not yet been copied!
		_extern._refCount = 0;
		_extern._capacity = newCapacity;
	}
}
Example #7
0
void DCMessenger::startCommandAfterDelay_alarm()
{
	QueuedCommand *qc = (QueuedCommand *)daemonCore->GetDataPtr();
	ASSERT(qc);

	startCommand(qc->msg);

	delete qc;
	decRefCount();
}
Example #8
0
int
DCMessenger::receiveMsgCallback(Stream *sock)
{
	Stopwatch watch; watch.start();
	int passes = 0;
	pending_operation_enum cur_state = m_pending_operation;
	do
	{
		// If we've gone through the loop once and there's not another ready message,
		// wait for DC to call us back.
		if (passes)
		{
			if (!static_cast<Sock*>(sock)->msgReady())
			{
				dprintf(D_NETWORK, "No messages left to process (done %d).\n", passes);
				break;
			}
			dprintf(D_NETWORK, "DC Messenger is processing message %d.\n", passes+1);
		}
		passes++;

		classy_counted_ptr<DCMsg> msg = m_callback_msg;
		ASSERT(msg.get());

		m_callback_msg = NULL;
		m_callback_sock = NULL;
		m_pending_operation = NOTHING_PENDING;

		daemonCore->Cancel_Socket( sock );

		ASSERT( sock );

			// Invoke readMsg() to read and process the message.
			// Note that in some cases, the callback to process the
			// message will invoke startReceiveMsg() if it wants to
			// receive another message; this is the case
			// in class ScheddNegotiate for instance.  When this
			// happens, m_pending_operation will get reset to
			// RECEIVE_MSG_PENDING, and we may end up looping
			// again via the do/while block below to read the
			// next message if it is ready without going back to DC.
			// See gt #4928.
		readMsg( msg, (Sock *)sock );

		cur_state = m_pending_operation;
		decRefCount();
	}
		// Note that we do not access m_pending_operation after
		// decRefCount is called - that may have deleted our object.
	while ((cur_state == RECEIVE_MSG_PENDING) &&
		   (m_receive_messages_duration_ms > 0) &&
		   (watch.get_ms() < m_receive_messages_duration_ms));

	return KEEP_STREAM;
}
Example #9
0
FilesystemNode &FilesystemNode::operator  =(const FilesystemNode &node) {
	if (node._refCount)
		++(*node._refCount);

	decRefCount();

	_realNode = node._realNode;
	_refCount = node._refCount;

	return *this;
}
Example #10
0
U32String &U32String::operator=(const U32String &str) {
	if (&str == this)
		return *this;

	if (str.isStorageIntern()) {
		decRefCount(_extern._refCount);
		_size = str._size;
		_str = _storage;
		memcpy(_str, str._str, (_size + 1) * sizeof(value_type));
	} else {
		str.incRefCount();
		decRefCount(_extern._refCount);

		_extern._refCount = str._extern._refCount;
		_extern._capacity = str._extern._capacity;
		_size = str._size;
		_str = str._str;
	}

	return *this;
}
DepthFirstStateAction::ResultE
DepthFirstStateAction::apply(NodePtr pRoot)
{
    ResultE result = NewActionTypes::Continue;

    startEvent();

    result = startActors();

    if(result & NewActionTypes::Quit)
        return result;

    _itInitialState = getState  ();
    _itActiveState  = cloneState();

    // gained refs: active, root
    incRefCount(_itActiveState, 2);

    _nodeStack.push_back(NodeStackEntry(pRoot, _itActiveState, 1));

    if((_extendLeaveActors.empty() == true) &&
       (_basicLeaveActors .empty() == true)    )
    {
        result = traverseEnter();
    }
    else
    {
        result = traverseEnterLeave();
    }

    setState(_itInitialState);

    // lost refs: active, current node
    decRefCount(_itActiveState, 2);

    _itActiveState   = _itInitialState;
    _stateClonedFlag = true;

    _nodeStack         .clear();
#ifndef OSG_NEWACTION_STATESLOTINTERFACE
    _stateStore        .clear();
#endif
    _stateRefCountStore.clear();

    if(result & NewActionTypes::Quit)
        return result;

    result = stopActors();

    stopEvent();

    return result;
}
Example #12
0
File* UserStreamWrapper::open(const String& filename, const String& mode,
                              int options, const Variant& context) {
  auto file = newres<UserFile>(m_cls, context);
  Resource wrapper(file);
  auto ret = file->openImpl(filename, mode, options);
  if (!ret) {
    return nullptr;
  }
  DEBUG_ONLY auto tmp = wrapper.detach();
  assert(tmp == file && file->hasExactlyOneRef());
  file->decRefCount();
  return file;
}
Example #13
0
void petabricks::DynamicTask::runWrapper(bool isAborting){
  JASSERT(_state==S_READY && _numPredecessors==0)(_state)(_numPredecessors);

  if (!isAborting) {
    _continuation = run();
  } else {
    _continuation = NULL;
  }

  std::vector<DynamicTask*> tmp;

  {
    JLOCKSCOPE(_lock);
    _dependents.swap(tmp);
    if(_continuation) _state = S_CONTINUED;
    else             _state = S_COMPLETE;
  }

  if(_continuation){
#ifdef VERBOSE
    JTRACE("task complete, continued")(tmp.size());
#endif
    {
      JLOCKSCOPE(_continuation->_lock);
      if(_continuation->_dependents.empty()){
        //swap is faster than insert
        _continuation->_dependents.swap(tmp);
      }else if(!tmp.empty()){
        _continuation->_dependents.insert(_continuation->_dependents.end(), tmp.begin(), tmp.end());
      }
    }
    _continuation->enqueue();
  }else{
    #ifdef VERBOSE
    if(!isNullTask()) JTRACE("task complete")(tmp.size());
    #endif
    std::vector<DynamicTask*>::iterator it;
    for(it = tmp.begin(); it != tmp.end(); ++it) {
#ifdef DEBUG
      JASSERT(*it != 0)(tmp.size());
#endif
      (*it)->decrementPredecessors(isAborting);
    }
  }
  decRefCount(); //matches with enqueue();
}
Example #14
0
int
DCMessenger::receiveMsgCallback(Stream *sock)
{
	classy_counted_ptr<DCMsg> msg = m_callback_msg;
	ASSERT(msg.get());

	m_callback_msg = NULL;
	m_callback_sock = NULL;
	m_pending_operation = NOTHING_PENDING;

	daemonCore->Cancel_Socket( sock );

	ASSERT( sock );
	readMsg( msg, (Sock *)sock );

	decRefCount();
	return KEEP_STREAM;
}
Example #15
0
int
CCBListener::ReverseConnected(Stream *stream)
{
	Sock *sock = (Sock *)stream;
	ClassAd *msg_ad = (ClassAd *)daemonCore->GetDataPtr();
	ASSERT( msg_ad );

	if( sock ) {
		daemonCore->Cancel_Socket( sock );
	}

	if( !sock || !sock->is_connected() ) {
		ReportReverseConnectResult(msg_ad,false,"failed to connect");
	}
	else {

			// The reverse-connect protocol is designed to look like a
			// raw cedar command, in case the thing we are connecting
			// to is a cedar command socket.

		sock->encode();
		int cmd = CCB_REVERSE_CONNECT;
		if( !sock->put(cmd) ||
			!msg_ad->put( *sock ) ||
			!sock->end_of_message() )
		{
			ReportReverseConnectResult(msg_ad,false,"failure writing reverse connect command");
		}
		else {
			((ReliSock*)sock)->isClient(false);
			daemonCore->HandleReqAsync(sock);
			sock = NULL; // daemonCore took ownership of sock
			ReportReverseConnectResult(msg_ad,true);
		}
	}

	delete msg_ad;
	if( sock ) {
		delete sock;
	}
	decRefCount(); // we incremented ref count when setting up callback

	return KEEP_STREAM;
}
Example #16
0
void
DCMessenger::readMsg( classy_counted_ptr<DCMsg> msg, Sock *sock )
{
	ASSERT( msg.get() );
	ASSERT( sock );

	msg->setMessenger( this );

	incRefCount();

	sock->decode();

	bool done_with_sock = true;

	if( sock->deadline_expired() ) {
		msg->cancelMessage("deadline expired");
	}

	if( msg->deliveryStatus() == DCMsg::DELIVERY_CANCELED ) {
		msg->callMessageReceiveFailed( this );
	}
	else if( !msg->readMsg( this, sock ) ) {
		msg->callMessageReceiveFailed( this );
	}
	else if( !sock->end_of_message() ) {
		msg->addError( CEDAR_ERR_EOM_FAILED, "failed to read EOM" );
		msg->callMessageReceiveFailed( this );
	}
	else {
			// Success
		DCMsg::MessageClosureEnum closure = msg->callMessageReceived( this, sock );

		if( closure == DCMsg::MESSAGE_CONTINUING ) {
			done_with_sock = false;
		}
	}

	if( done_with_sock ) {
		doneWithSock( sock );
	}

	decRefCount();
}
Example #17
0
void DCMessenger::writeMsg( classy_counted_ptr<DCMsg> msg, Sock *sock )
{
	ASSERT( msg.get() );
	ASSERT( sock );

	msg->setMessenger( this );
	incRefCount();

		/* Some day, we may send message asynchronously and call
		   messageSent() later, after the delivery.  For now, we do it
		   all synchronously, right here. */

	sock->encode();

	if( msg->deliveryStatus() == DCMsg::DELIVERY_CANCELED ) {
		msg->callMessageSendFailed( this );
		doneWithSock(sock);
	}
	else if( !msg->writeMsg( this, sock ) ) {
		msg->callMessageSendFailed( this );
		doneWithSock(sock);
	}
	else if( !sock->end_of_message() ) {
		msg->addError( CEDAR_ERR_EOM_FAILED, "failed to send EOM" );
		msg->callMessageSendFailed( this );
		doneWithSock(sock);
	}
	else {
			// Success
		DCMsg::MessageClosureEnum closure = msg->callMessageSent( this, sock );

		switch( closure ) {
		case DCMsg::MESSAGE_FINISHED:
			doneWithSock(sock);
			break;
		case DCMsg::MESSAGE_CONTINUING:
			break;
		}
	}

	decRefCount();
}
Example #18
0
///////////////////////////////////////////////////////////////////////
// Enumerate all the remaining records.
// Return the id of the last record enumerated.
///////////////////////////////////////////////////////////////////
clist_index_t BufferList::enumerateAll() {

	// sort and enumerate the records
	
	thelist.sort(Cmp());
	if (verbose) {
//		cout << "After sorting: "<<endl;
//		toString();
	}
	
	// Get an iterator for the bufferlist
	typedef list<simpRecord>::iterator lsr;
	lsr recIter = thelist.begin();
	clist_index_t nextLowestSeqNum;

	if (verbose) 
		cerr << "BufferList: lowest index: "<<lowestSeqNum<<endl;


	// Enumerate all is simpler than enumerate, all we do is go through the entire list
	// after sorting and enumerate each one. Then decrement the refCount for each one.	
	while (recIter != thelist.end()) {
		simpRecord temp_rec = (*recIter);
		clist_index_t tempSeq = temp_rec.getSeq();
		if (verbose) 
			cerr << "BufferList: in remove: processing seqnum: "<<tempSeq<<endl;
		
		decRefCount(&(*recIter));

		// Now enumerate the element..
		if (verbose) 
			cerr << "BufferList: setting record "<<tempSeq<<" value to: "<<enumerationIndex<<endl;
		setEnumeration(enumerationIndex,*recIter);
		enumerationIndex+=interval;

		++recIter;
	}
	// Remove the elements.
	thelist.erase(thelist.begin(),thelist.end());	

}
Example #19
0
void
CCBListener::Disconnected()
{
	if( m_sock ) {
		daemonCore->Cancel_Socket( m_sock );
		delete m_sock;
		m_sock = NULL;
	}

	if( m_waiting_for_connect ) {
		m_waiting_for_connect = false;
		decRefCount();
	}

	m_waiting_for_registration = false;
	m_registered = false;

	StopHeartbeat();

	if( m_reconnect_timer != -1 ) {
		return; // already in progress
	}

	int reconnect_time = param_integer("CCB_RECONNECT_TIME",60);

	dprintf(D_ALWAYS,
			"CCBListener: connection to CCB server %s failed; "
			"will try to reconnect in %d seconds.\n",
			m_ccb_address.Value(), reconnect_time);

	m_reconnect_timer = daemonCore->Register_Timer(
		reconnect_time,
		(TimerHandlercpp)&CCBListener::ReconnectTime,
		"CCBListener::ReconnectTime",
		this );

	ASSERT( m_reconnect_timer != -1 );
}
void
DepthFirstStateAction::beginEditStateEvent(ActorBase *pActor, UInt32 actorId)
{
    if(_stateClonedFlag == false)
    {
#ifdef OSG_NEWACTION_STATISTICS
        getStatistics()->getElem(statStateClones)->inc();
#endif /* OSG_NEWACTION_STATISTICS */

        _stateClonedFlag = true;

        StateRefCountStoreIt itClonedState = cloneState();

        // gained refs: active and current node
        incRefCount(itClonedState, 2);

        // lost refs: active and current node
        decRefCount(_itActiveState, 2);

        _nodeStack.back().setStateRefCount(itClonedState);

        _itActiveState = itClonedState;
    }
}
Example #21
0
File: unwind.cpp Project: BwRy/hhvm
UnwindAction tearDownFrame(ActRec*& fp, Stack& stack, PC& pc,
                           const Fault& fault) {
  auto const func = fp->func();
  auto const curOp = *reinterpret_cast<const Op*>(pc);
  auto const prevFp = fp->sfp();
  auto const soff = fp->m_soff;

  FTRACE(1, "tearDownFrame: {} ({})\n  fp {} prevFp {}\n",
         func->fullName()->data(),
         func->unit()->filepath()->data(),
         implicit_cast<void*>(fp),
         implicit_cast<void*>(prevFp));

  // When throwing from a constructor, we normally want to avoid running the
  // destructor on an object that hasn't been fully constructed yet. But if
  // we're unwinding through the constructor's RetC, the constructor has
  // logically finished and we're unwinding for some internal reason (timeout
  // or user profiler, most likely). More importantly, fp->m_this may have
  // already been destructed and/or overwritten due to sharing space with
  // fp->m_r.
  if (fp->isFromFPushCtor() && fp->hasThis() && curOp != OpRetC) {
    fp->getThis()->setNoDestruct();
  }

  /*
   * It is possible that locals have already been decref'd.
   *
   * Here's why:
   *
   *   - If a destructor for any of these things throws a php
   *     exception, it's swallowed at the dtor boundary and we keep
   *     running php.
   *
   *   - If the destructor for any of these things throws a fatal,
   *     it's swallowed, and we set surprise flags to throw a fatal
   *     from now on.
   *
   *   - If the second case happened and we have to run another
   *     destructor, its enter hook will throw, but it will be
   *     swallowed again.
   *
   *   - Finally, the exit hook for the returning function can
   *     throw, but this happens last so everything is destructed.
   *
   *   - When that happens, exit hook sets localsDecRefd flag.
   */
  if (!fp->localsDecRefd()) {
    try {
      // Note that we must convert locals and the $this to
      // uninit/zero during unwind.  This is because a backtrace
      // from another destructing object during this unwind may try
      // to read them.
      frame_free_locals_unwind(fp, func->numLocals(), fault);
    } catch (...) {}
  }

  auto action = UnwindAction::Propagate;

  if (LIKELY(!fp->resumed())) {
    if (UNLIKELY(func->isAsyncFunction()) &&
        fault.m_faultType == Fault::Type::UserException) {
      // If in an eagerly executed async function, wrap the user exception
      // into a failed StaticWaitHandle and return it to the caller.
      auto const e = fault.m_userException;
      stack.ndiscard(func->numSlotsInFrame());
      stack.ret();
      assert(stack.topTV() == &fp->m_r);
      tvWriteObject(c_StaticWaitHandle::CreateFailed(e), &fp->m_r);
      e->decRefCount();
      action = UnwindAction::ResumeVM;
    } else {
      // Free ActRec.
      stack.ndiscard(func->numSlotsInFrame());
      stack.discardAR();
    }
  } else if (func->isAsyncFunction()) {
    auto const waitHandle = frame_afwh(fp);
    if (fault.m_faultType == Fault::Type::UserException) {
      // Handle exception thrown by async function.
      waitHandle->fail(fault.m_userException);
      action = UnwindAction::ResumeVM;
    } else {
      // Fail the async function and let the C++ exception propagate.
      waitHandle->fail(AsioSession::Get()->getAbruptInterruptException());
    }
  } else if (func->isAsyncGenerator()) {
    // Do nothing. AsyncGeneratorWaitHandle will handle the exception.
  } else if (func->isNonAsyncGenerator()) {
    // Mark the generator as finished.
    frame_generator(fp)->finish();
  } else {
    not_reached();
  }

  /*
   * At the final ActRec in this nesting level.
   */
  if (UNLIKELY(!prevFp)) {
    pc = nullptr;
    fp = nullptr;
    return action;
  }

  assert(stack.isValidAddress(reinterpret_cast<uintptr_t>(prevFp)) ||
         prevFp->resumed());
  auto const prevOff = soff + prevFp->func()->base();
  pc = prevFp->func()->unit()->at(prevOff);
  fp = prevFp;
  return action;
}
DepthFirstStateAction::ResultE
DepthFirstStateAction::traverseEnterLeave(void)
{
    ResultE              result          = NewActionTypes::Continue;
    Int32                nodePass;        // pass over current node
    UInt32               multiPasses;     // requested passes over current node
    NodePtr              pNode;
    StateRefCountStoreIt itStateRefCount;

    while((_nodeStack.empty() == false) && !(result & NewActionTypes::Quit))
    {
        pNode           = _nodeStack.back().getNode         ();
        nodePass        = _nodeStack.back().getPassCount    ();
        itStateRefCount = _nodeStack.back().getStateRefCount();

        if(itStateRefCount != _itActiveState)
        {
#ifdef OSG_NEWACTION_STATISTICS
            getStatistics()->getElem(statStateRestores)->inc();
#endif /* OSG_NEWACTION_STATISTICS */

            setState(itStateRefCount);

            // gained refs: active
            incRefCount(itStateRefCount);

            // lost refs: active
            decRefCount(_itActiveState);

            _itActiveState = itStateRefCount;
        }

        getChildrenList().setParentNode(pNode);

        if(nodePass > 0)
        {
            // positive pass -> enter node
            
#ifdef OSG_NEWACTION_STATISTICS
            getStatistics()->getElem(statNodesEnter)->inc();
#endif /* OSG_NEWACTION_STATISTICS */
            
            _stateClonedFlag = false;

            result      = enterNode   (pNode, static_cast<UInt32>(nodePass - 1));
            multiPasses = getNumPasses(                                        );

            // only initial pass (nodePass == 1) can request multiPass.
            if((nodePass == 1) && (multiPasses > 1))
            {
                // remove current node from stack
                _nodeStack.pop_back();
                
                for(; multiPasses > 1; -- multiPasses)
                {
                    // gained refs: addtional passs
                    incRefCount(_itActiveState);
                    
                    _nodeStack.push_back(
                        NodeStackEntry(pNode, _itActiveState, multiPasses));
                }
                
                // readd current node - with negative pass -> leave
                _nodeStack.push_back(
                    NodeStackEntry(pNode, _itActiveState, -nodePass));
            }
            else
            {
                // change current node passCount to negative -> leave
                _nodeStack.back().setPassCount(-nodePass);
            }
            
            pushChildren(pNode, result);
        }
        else
        {
            // negative pass -> leave node

#ifdef OSG_NEWACTION_STATISTICS
            getStatistics()->getElem(statNodesLeave)->inc();
#endif /* OSG_NEWACTION_STATISTICS */
            
            _stateClonedFlag = true;

            result = leaveNode(pNode, static_cast<UInt32>(-nodePass - 1));

            _nodeStack.pop_back();

            // lost refs: current node
            decRefCount(_itActiveState);
        }
    }

    return result;
}
DepthFirstStateAction::ResultE
DepthFirstStateAction::traverseEnter(void)
{
    ResultE              result          = NewActionTypes::Continue;
    NodePtr              pNode;
    Int32                nodePass;        // pass over current node
    UInt32               multiPasses;     // requested passes over current node
    StateRefCountStoreIt itStateRefCount; // state for current node

    while((_nodeStack.empty() == false) && !(result & NewActionTypes::Quit))
    {
        pNode           = _nodeStack.back().getNode         ();
        nodePass        = _nodeStack.back().getPassCount    ();
        itStateRefCount = _nodeStack.back().getStateRefCount();

#ifdef OSG_NEWACTION_STATISTICS
        getStatistics()->getElem(statNodesEnter)->inc();
#endif /* OSG_NEWACTION_STATISTICS */

        if(itStateRefCount != _itActiveState)
        {
#ifdef OSG_NEWACTION_STATISTICS
            getStatistics()->getElem(statStateRestores)->inc();
#endif /* OSG_NEWACTION_STATISTICS */

            setState(itStateRefCount);

            // gained refs: active
            incRefCount(itStateRefCount);

            // lost refs: active
            decRefCount(_itActiveState);

            _itActiveState = itStateRefCount;
        }

        _stateClonedFlag = false;

        getChildrenList().setParentNode(pNode);

        result      = enterNode   (pNode, static_cast<UInt32>(nodePass - 1));
        multiPasses = getNumPasses(                                        );

        _nodeStack.pop_back();

        // only initial pass (nodePass == 1) can request multiPasses
        if((nodePass == 1) && (multiPasses > 1))
        {
            for(; multiPasses > 1; --multiPasses)
            {
                // gained refs: additional pass
                incRefCount(_itActiveState);
                
                _nodeStack.push_back(
                    NodeStackEntry(pNode, _itActiveState, multiPasses));
            }
        }
        
        pushChildren(pNode, result);

        // lost refs: current node
        decRefCount(_itActiveState);
    }

    return result;
}
Example #24
0
FilesystemNode::~FilesystemNode() {
	decRefCount();
}
void Gu::TriangleMesh::release()
{
	decRefCount();
}
Example #26
0
U32String::~U32String() {
	decRefCount(_extern._refCount);
}
Example #27
0
///////////////////////////////////////////////////////////////////////
// Return the id of the least record that hasn't been enumerated yet.
// this particular record will be in the next iteration.
///////////////////////////////////////////////////////////////////
clist_index_t BufferList::enumerate() {
	
	// sort and enumerate the records
	
	thelist.sort(Cmp());
	if (verbose) {
//		cerr << "After sorting: "<<endl;
//		toString();
	}
	
	// Get an iterator for the bufferlist
	typedef list<simpRecord>::iterator lsr;
	lsr recIter = thelist.begin();
	clist_index_t nextLowestSeqNum;

	if (lowestSeqNum == std::numeric_limits<uint32_t>::max()) {
		// This means that there weren't any records remaining in the buffer
		// at the end of the last iteration. Now we just set lowestSeqNum to 
		// the value of the first element in the buff list.
		lowestSeqNum = thelist.front().getSeq();
		if (verbose) 
			cerr << "BufferList: lowest index changed to: "<<lowestSeqNum<<endl;
			
	}
	
	if (verbose) 
		cerr << "BufferList: lowest index: "<<lowestSeqNum<<endl;
	// Loop until we have no more records..
	while (recIter != thelist.end()) {
		simpRecord temp_rec = (*recIter);
		clist_index_t tempSeq = temp_rec.getSeq();
		
//		 Now enumerate the element..
		if (verbose) 
			cerr << "BufferList: setting record "<<tempSeq<<" value to: "<<enumerationIndex<<endl;
			
		setEnumeration(enumerationIndex,*recIter);
		enumerationIndex+=interval;



		// If the current record is the one we are searching for..
		if (tempSeq == lowestSeqNum) {
			// .. then we can rejoice! Now we must remove all the records before it, and 
			// find the lowestSeqNum in the remaining records.
			lsr savedRecIter(recIter);
			++recIter;
			// use the maximum value of uint32_t
			nextLowestSeqNum = std::numeric_limits<uint32_t>::max(); //currentIndex;
			// Now loop through the rest of the elements, trying to find the lowest one..
			// We want to keep track of the lowest sequence number in the new buffer..
			while (recIter != thelist.end()) {
				if ((*recIter).getSeq() < nextLowestSeqNum) {
					nextLowestSeqNum = (*recIter).getSeq();
				}
				++recIter;
			}
			
			// Set the sequence number correctly..
			lowestSeqNum = nextLowestSeqNum;
			if (verbose) 
				cerr << "BufferList: in remove: Next lowest sequence number: "<<lowestSeqNum<<endl;
				 
			// Now we will iterate through all the records we have correctly enumerated and
			// decrement the refCount on them and remove them from the list.
			lsr newRecIter = thelist.begin();
			++savedRecIter;
			
			for (;newRecIter != savedRecIter;++newRecIter) {
				decRefCount(&(*newRecIter));
			}
			// Remove the elements.
			thelist.erase(thelist.begin(),savedRecIter);	
			return(lowestSeqNum);		
		}
		++recIter;

	}
	if (verbose) 
		cerr << " BufferList: We shouldn't be getting here!!!"<<endl;
}
Example #28
0
void Highlighter::run()
{
	runWrapped();
	if (keepAlive_->tryAcquire())
		decRefCount(); // allow self destruction after termination
}
Example #29
0
void ResourceLoader::unloadResource(const String& name) {
    decRefCount(name);
}
Example #30
0
//--------------------------------------------------------------------------
// Function:    IdComponent::decRefCount
///\brief       Decrement reference counter for the id of this object.
// Programmer   Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
void IdComponent::decRefCount() const
{
    decRefCount(getId());
}