Example #1
0
StringData* tvCastToString(const TypedValue* tv) {
  assert(tvIsPlausible(*tv));
  if (tv->m_type == KindOfRef) {
    tv = tv->m_data.pref->tv();
  }

  switch (tv->m_type) {
    case KindOfUninit:
    case KindOfNull:
      return staticEmptyString();

    case KindOfBoolean:
      return tv->m_data.num ? s_1.get() : staticEmptyString();

    case KindOfInt64:
      return buildStringData(tv->m_data.num);

    case KindOfDouble:
      return buildStringData(tv->m_data.dbl);

    case KindOfStaticString:
      return tv->m_data.pstr;

    case KindOfString: {
      auto s = tv->m_data.pstr;
      s->incRefCount();
      return s;
    }

    case KindOfArray:
      raise_notice("Array to string conversion");
      return array_string.get();

    case KindOfObject:
      return tv->m_data.pobj->invokeToString().detach();

    case KindOfResource:
      return tv->m_data.pres->o_toString().detach();

    case KindOfRef:
    case KindOfClass:
      not_reached();
  }
  not_reached();
}
Example #2
0
/**
 * concat_ss will will incRef the output string
 * and decref its first argument
 */
StringData* concat_ss(StringData* v1, StringData* v2) {
  if (v1->hasMultipleRefs()) {
    StringData* ret = StringData::Make(v1, v2);
    ret->setRefCount(1);
    // Because v1->getCount() is greater than 1, we know we will never
    // have to release the string here
    v1->decRefCount();
    return ret;
  }

  auto const ret = v1->append(v2->slice());
  if (UNLIKELY(ret != v1)) {
    assert(v1->hasExactlyOneRef());
    v1->release();
    ret->incRefCount();
  }
  return ret;
}
Example #3
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 #4
0
//--------------------------------------------------------------------------
// Function:	IdComponent::operator=
///\brief	Assignment operator.
///\param	rhs - IN: Reference to the existing object
///\return	Reference to IdComponent instance
///\exception	H5::IdComponentException when attempt to close the HDF5
///		object fails
// Description
//		First, close the current valid id of this object.  Then
//		copy the id from rhs to this object, and increment the
//		reference counter of the id to indicate that another object
//		is referencing that id.
// Programmer	Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
IdComponent& IdComponent::operator=( const IdComponent& rhs )
{
    if (this != &rhs)
    {
	// handling references to this id
  	try {
	    close();
	}
	catch (Exception close_error) {
	    throw FileIException(inMemFunc("operator="), close_error.getDetailMsg());
	}

	// copy the data members from the rhs object
	p_setId(rhs.getId());
	incRefCount(getId()); // a = b, so there are two objects with the same
			      // hdf5 id
    }
    return *this;
}
Example #5
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 #6
0
void c_SleepWaitHandle::initialize(int64_t usecs) {
  auto const session = AsioSession::Get();
  setState(STATE_WAITING);
  setContextIdx(session->getCurrentContextIdx());
  m_waketime =
    AsioSession::TimePoint::clock::now() +
    std::chrono::microseconds(usecs);

  incRefCount();

  session->enqueueSleepEvent(this);

  if (isInContext()) {
    registerToContext();
  }

  if (UNLIKELY(session->hasOnSleepCreate())) {
    session->onSleepCreate(this);
  }
}
void lookupClsMethodHelper(Class* cls, StringData* meth,
                           ActRec* ar, ActRec* fp) {
  try {
    const Func* f;
    auto const ctx = fp->m_func->cls();
    auto const obj = ctx && fp->hasThis() ? fp->getThis() : nullptr;
    auto const res = lookupClsMethod(f, cls, meth, obj, ctx, true);

    ar->m_func = f;

    if (res == LookupResult::MethodFoundNoThis ||
        res == LookupResult::MagicCallStaticFound) {
      if (!f->isStaticInPrologue()) {
        raise_missing_this(f);
      }
      if (forward && ctx) {
        if (fp->hasThis()) {
          cls = fp->getThis()->getVMClass();
        } else {
          cls = fp->getClass();
        }
      }
      ar->setClass(cls);
    } else {
      assertx(obj);
      assertx(res == LookupResult::MethodFoundWithThis ||
              res == LookupResult::MagicCallFound);
      obj->incRefCount();
      ar->setThis(obj);
    }

    if (res == LookupResult::MagicCallFound ||
        res == LookupResult::MagicCallStaticFound) {
      ar->setMagicDispatch(meth);
      meth->incRefCount();
    }
  } catch (...) {
    *arPreliveOverwriteCells(ar) = make_tv<KindOfString>(meth);
    throw;
  }
}
Example #8
0
/**
 * concat_si will incRef the output string
 * and decref its first argument
 */
StringData* concat_si(StringData* v1, int64_t v2) {
  char intbuf[21];
  auto const s2 = conv_10(v2, intbuf + sizeof(intbuf));
  if (v1->hasMultipleRefs()) {
    auto const s1 = v1->slice();
    auto const ret = StringData::Make(s1, s2);
    ret->setRefCount(1);
    // Because v1->getCount() is greater than 1, we know we will never
    // have to release the string here
    v1->decRefCount();
    return ret;
  }

  auto const ret = v1->append(s2);
  if (UNLIKELY(ret != v1)) {
    assert(v1->hasExactlyOneRef());
    v1->release();
    ret->incRefCount();
  }
  return ret;
}
// throws on cycle
void c_BlockableWaitHandle::blockOn(c_WaitableWaitHandle* child) {
  setState(STATE_BLOCKED);
  assert(getChild() == child);

  // detect complete cycles
  if (UNLIKELY(hasCycle(child))) {
    reportCycle(child);
    assert(false);
  }

  // make sure the child is going to do some work
  // throws if cross-context cycle found
  if (isInContext()) {
    child->enterContext(getContextIdx());
  }

  // extend the linked list of parents
  m_nextParent = child->addParent(this);

  // increment ref count so that we won't deallocated before child calls back
  incRefCount();
}
c_AsyncFunctionWaitHandle*
c_AsyncFunctionWaitHandle::Create(const ActRec* fp,
                                  size_t numSlots,
                                  JIT::TCA resumeAddr,
                                  Offset resumeOffset,
                                  c_WaitableWaitHandle* child) {
  assert(fp);
  assert(!fp->resumed());
  assert(fp->func()->isAsyncFunction());
  assert(child);
  assert(child->instanceof(c_WaitableWaitHandle::classof()));
  assert(!child->isFinished());

  checkCreateErrors(child);

  void* obj = Resumable::Create(fp, numSlots, resumeAddr, resumeOffset,
                                sizeof(c_AsyncFunctionWaitHandle));
  auto const waitHandle = new (obj) c_AsyncFunctionWaitHandle();
  waitHandle->incRefCount();
  waitHandle->setNoDestruct();
  waitHandle->initialize(child);
  return waitHandle;
}
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 #12
0
/* virtual */ SysStatus
MemTrans::giveAccessSetClientData(ObjectHandle &oh,
				  ProcessID toProcID,
				  AccessRights match,
				  AccessRights nomatch,
				  TypeID type)
{
    SysStatus rc;
    ClientData *clientData = new ClientData(toProcID);
    rc =  giveAccessInternal(oh, toProcID, match, nomatch,
			     type, (uval)clientData);
    if (_FAILURE(rc)) {
	delete clientData;
    }

    // Remember the process binding
    BaseProcessRef pref;

    rc = DREFGOBJ(TheProcessSetRef)->getRefFromPID(toProcID,pref);

    _IF_FAILURE_RET_VERBOSE(rc);

    XHandle remote = oh.xhandle();

    //Add ref count for xhandle
    incRefCount();

    rc = DREF(pref)->addSMT(getRef(), remote, key);

    _IF_FAILURE_RET(rc);

    clientData->givenOH = oh;
    cdHash.add(toProcID, clientData);
    dprintf("%s: add xh: %lx -> %ld\n",__func__,oh.xhandle(),toProcID);
    return rc;
}
void c_AsyncFunctionWaitHandle::initialize(c_WaitableWaitHandle* child) {
  setState(STATE_BLOCKED);
  setContextIdx(child->getContextIdx());
  m_children[0].setChild(child);
  incRefCount(); // account for child->this back-reference
}
Example #14
0
void ResourceLoader::loadTexture(const String& name, LoadedCallback cb) {
    incRefCount(name, ResourceTypeTexture);
    mTasks.push( std::tr1::bind(&ResourceLoader::loadTextureWork, this, name, cb) );
}
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;
}
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;
}
StringData* convIntToStrHelper(int64_t i) {
  auto r = buildStringData(i);
  r->incRefCount();
  return r;
}
StringData* convDblToStrHelper(int64_t i) {
  double d = reinterpretIntAsDbl(i);
  auto r = buildStringData(d);
  r->incRefCount();
  return r;
}
Example #19
0
void DCMessenger::startCommand( classy_counted_ptr<DCMsg> msg )
{
	MyString error;
	msg->setMessenger( this );

	if( msg->deliveryStatus() == DCMsg::DELIVERY_CANCELED ) {
		msg->callMessageSendFailed( this );
		return;
	}

	time_t deadline = msg->getDeadline();
	if( deadline && deadline < time(NULL) ) {
		msg->addError(CEDAR_ERR_DEADLINE_EXPIRED,
					  "deadline for delivery of this message expired");
		msg->callMessageSendFailed( this );
		return;
	}

		// For a UDP message, we may need to register two sockets, one for
		// the SafeSock and another for a ReliSock to establish the
		// security session.
	Stream::stream_type st = msg->getStreamType();
	if( daemonCore->TooManyRegisteredSockets(-1,&error,st==Stream::safe_sock?2:1) ) {
			// Try again in a sec
			// Eventually, it would be better to queue this centrally
			// (i.e. in DaemonCore) rather than having an independent
			// timer for each case.  Then it would be possible to control
			// priority of different messages etc.
		dprintf(D_FULLDEBUG, "Delaying delivery of %s to %s, because %s\n",
				msg->name(),peerDescription(),error.Value());
		startCommandAfterDelay( 1, msg );
		return;
	}

		// Currently, there may be only one pending operation per messenger.
	ASSERT(!m_callback_msg.get());
	ASSERT(!m_callback_sock);
	ASSERT(m_pending_operation == NOTHING_PENDING);

	m_pending_operation = START_COMMAND_PENDING;
	m_callback_msg = msg;
	m_callback_sock = m_sock.get();
	if( !m_callback_sock ) {

		if (IsDebugLevel(D_COMMAND)) {
			const char * addr = m_daemon->addr();
			const int cmd = msg->m_cmd;
			dprintf (D_COMMAND, "DCMessenger::startCommand(%s,...) making non-blocking connection to %s\n", getCommandStringSafe(cmd), addr ? addr : "NULL");
		}

		const bool nonblocking = true;
		m_callback_sock = m_daemon->makeConnectedSocket(st,msg->getTimeout(),msg->getDeadline(),&msg->m_errstack,nonblocking);
		if( !m_callback_sock ) {
			msg->callMessageSendFailed( this );
			return;
		}
	}

	incRefCount();
	m_daemon->startCommand_nonblocking (
		msg->m_cmd,
		m_callback_sock,
		msg->getTimeout(),
		&msg->m_errstack,
		&DCMessenger::connectCallback,
		this,
		msg->name(),
		msg->getRawProtocol(),
		msg->getSecSessionId());
}
Example #20
0
void ResourceLoader::loadMesh(const String& name, Mesh::MeshdataPtr mesh, const String& skeletonName, LoadedCallback cb) {
    incRefCount(name, ResourceTypeMesh);
    mTasks.push( std::tr1::bind(&ResourceLoader::loadMeshWork, this, name, mesh, skeletonName, cb) );
}
Example #21
0
void ResourceLoader::loadMaterial(const String& name, Mesh::MeshdataPtr mesh, const Mesh::MaterialEffectInfo& mat, const Transfer::URI& uri, TextureBindingsMapPtr textureFingerprints, LoadedCallback cb) {
    incRefCount(name, ResourceTypeMaterial);
    mTasks.push( std::tr1::bind(&ResourceLoader::loadMaterialWork, this, name, mesh, mat, uri, textureFingerprints, cb) );
}
void
DepthFirstStateAction::pushChildren(const NodePtr &pNode, ResultE result)
{
    if(result & (NewActionTypes::Skip  |
                 NewActionTypes::Break |
                 NewActionTypes::Quit   ))
    {
        setChildrenListEnabled(false);
        setNumPasses          (1    );

        getExtraChildrenList().clear();

        return;
    }

    ChildrenList      &cl  = getChildrenList     ();
    ExtraChildrenList &ecl = getExtraChildrenList();

    if(getChildrenListEnabled() == true)
    {
        for(UInt32 i = 0, size = cl.getSize(); i < size; ++i)
        {
            if(( cl.getActive(i)                                 == true  ) &&
               ( cl.getChild (i)                                 != NullFC) &&
               ((cl.getChild (i)->getTravMask() & getTravMask()) != 0     )   )
            {
                // gained refs: child
                incRefCount(_itActiveState);

                _nodeStack.push_back(
                    NodeStackEntry(cl.getChild(i), _itActiveState, 1));
            }
        }
    }
    else
    {
        MFNodePtr::const_iterator itChildren  = pNode->getMFChildren()->begin();
        MFNodePtr::const_iterator endChildren = pNode->getMFChildren()->end  ();

        for(; itChildren != endChildren; ++itChildren)
        {
            if((  *itChildren                                  != NullFC) &&
               (((*itChildren)->getTravMask() & getTravMask()) != 0     )   )
            {
                // gained refs: child
                incRefCount(_itActiveState);

                _nodeStack.push_back(
                    NodeStackEntry(*itChildren, _itActiveState, 1));
            }
        }
    }

    for(UInt32 i = 0, size = ecl.getSize(); i < size; ++i)
    {
        if(( ecl.getActive(i)                                 == true  ) &&
           ( ecl.getChild (i)                                 != NullFC) &&
           ((ecl.getChild (i)->getTravMask() & getTravMask()) != 0     )   )
        {
            // gained refs: extra child
            incRefCount(_itActiveState);

            _nodeStack.push_back(
                NodeStackEntry(ecl.getChild(i), _itActiveState, 1));
        }
    }

    setChildrenListEnabled(false);
    ecl.clear             (     );
    setNumPasses          (1    );
}
Example #23
0
//--------------------------------------------------------------------------
// Function:    IdComponent::incRefCount
///\brief       Increment reference counter for the id of this object.
// Programmer   Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
void IdComponent::incRefCount() const
{
    incRefCount(getId());
}
StringData* convObjToStrHelper(ObjectData* o) {
  auto s = o->invokeToString();
  auto r = s.get();
  if (!r->isStatic()) r->incRefCount();
  return r;
}
Example #25
0
void ResourceLoader::loadBillboardMaterial(const String& name, const String& texuri, const Transfer::URI& uri, TextureBindingsMapPtr textureFingerprints, LoadedCallback cb) {
    incRefCount(name, ResourceTypeMaterial);
    mTasks.push( std::tr1::bind(&ResourceLoader::loadBillboardMaterialWork, this, name, texuri, uri, textureFingerprints, cb) );
}
StringData* convResToStrHelper(ResourceData* o) {
  auto s = o->o_toString();
  auto r = s.get();
  if (!r->isStatic()) r->incRefCount();
  return r;
}
Example #27
0
void ResourceLoader::loadSkeleton(const String& name, Mesh::MeshdataPtr mesh, const std::set<String>& animationList, LoadedCallback cb) {
    incRefCount(name, ResourceTypeSkeleton);
    mTasks.push( std::tr1::bind(&ResourceLoader::loadSkeletonWork, this, name, mesh, animationList, cb) );
}