Ejemplo n.º 1
0
void M6Processor::ProcessFile(const string& inFileName, istream& inFileStream)
{
    mFileName.reset(new string(inFileName));

    io::filtering_stream<io::input> in;

    if (mConfig->find_first("filter"))
        in.push(M6Process(mConfig->find_first("filter")->content(), inFileStream));
    else
        in.push(inFileStream);

    try
    {
        if (mParser != nullptr)
            ParseFile(inFileName, in);
        else
            ParseXML(inFileName, in);
    }
    catch (exception& e)
    {
        cerr << endl
             << "Error parsing file " << inFileName << endl
             << e.what() << endl;
        Error(current_exception());
    }
}
Ejemplo n.º 2
0
const CGHeroInstance * HeroPtr::get(bool doWeExpectNull /*= false*/) const
{
	//TODO? check if these all assertions every time we get info about hero affect efficiency
	//
	//behave terribly when attempting unauthorized access to hero that is not ours (or was lost)
	assert(doWeExpectNull || h);

	if(h)
	{
		auto obj = cb->getObj(hid);
		const bool owned = obj && obj->tempOwner == ai->playerID;

		if(doWeExpectNull && !owned)
		{
			return nullptr;
		}
		else
		{
			assert(obj);
			assert(owned);
		}
	}

	return h;
}
Ejemplo n.º 3
0
 bool run(const char *ns, BSONObj& cmdObj, string& errmsg, BSONObjBuilder& result, bool fromRepl) {
     nonce *n = new nonce(security.getNonce());
     stringstream ss;
     ss << hex << *n;
     result.append("nonce", ss.str() );
     lastNonce.reset(n);
     return true;
 }
Ejemplo n.º 4
0
        bool run(const char *cmdns, BSONObj& cmdObj, string& errmsg, BSONObjBuilder& result, bool){
            string ns = cmdObj["getShardVersion"].valuestrsafe();
            if ( ns.size() == 0 ){
                errmsg = "need to speciy fully namespace";
                return false;
            }
            
            result.append( "configServer" , shardConfigServer.c_str() );

            result.appendTimestamp( "global" , globalVersions[ns] );
            if ( clientShardVersions.get() )
                result.appendTimestamp( "mine" , (*clientShardVersions.get())[ns] );
            else 
                result.appendTimestamp( "mine" , 0 );
            
            return true;
        }
Ejemplo n.º 5
0
 void curopWaitingForLock( int type ){
     Client * c = currentClient.get();
     assert( c );
     CurOp * co = c->curop();
     if ( co ){
         co->waitingForLock( type );
     }
 }
Ejemplo n.º 6
0
ldb::Slice dev::eth::toSlice(uint64_t _n, unsigned _sub)
{
#if ALL_COMPILERS_ARE_CPP11_COMPLIANT
	static thread_local FixedHash<33> h;
	toBigEndian(_n, bytesRef(h.data() + 24, 8));
	h[32] = (uint8_t)_sub;
	return (ldb::Slice)h.ref();
#else
	static boost::thread_specific_ptr<FixedHash<33>> t_h;
	if (!t_h.get())
		t_h.reset(new FixedHash<33>);
	bytesRef ref(t_h->data() + 24, 8);
	toBigEndian(_n, ref);
	(*t_h)[32] = (uint8_t)_sub;
	return (ldb::Slice)t_h->ref();
#endif
}
Ejemplo n.º 7
0
 void curopGotLock(){
     Client * c = currentClient.get();
     assert(c);
     CurOp * co = c->curop();
     if ( co ){
         co->gotLock();
     }
 }
Ejemplo n.º 8
0
    bool handlePossibleShardedMessage( Message &m, DbResponse &dbresponse ){

        if ( shardConfigServer.empty() ){
            return false;
        }

        int op = m.data->operation();
        if ( op < 2000 || op >= 3000 )
            return false;

        
        const char *ns = m.data->_data + 4;
        string errmsg;
        if ( shardVersionOk( ns , errmsg ) ){
            return false;
        }

        log() << "shardVersionOk failed  ns:" << ns << " " << errmsg << endl;
        
        if ( doesOpGetAResponse( op ) ){
            BufBuilder b( 32768 );
            b.skip( sizeof( QueryResult ) );
            {
                BSONObj obj = BSON( "$err" << errmsg );
                b.append( obj.objdata() , obj.objsize() );
            }
            
            QueryResult *qr = (QueryResult*)b.buf();
            qr->_resultFlags() = QueryResult::ResultFlag_ErrSet | QueryResult::ResultFlag_ShardConfigStale;
            qr->len = b.len();
            qr->setOperation( opReply );
            qr->cursorId = 0;
            qr->startingFrom = 0;
            qr->nReturned = 1;
            b.decouple();

            Message * resp = new Message();
            resp->setData( qr , true );
            
            dbresponse.response = resp;
            dbresponse.responseTo = m.data->id;
            return true;
        }
        
        OID * clientID = clientServerIds.get();
        massert( 10422 ,  "write with bad shard config and no server id!" , clientID );
        
        log() << "got write with an old config - writing back" << endl;

        BSONObjBuilder b;
        b.appendBool( "writeBack" , true );
        b.append( "ns" , ns );
        b.appendBinData( "msg" , m.data->len , bdtCustom , (char*)(m.data) );
        log() << "writing back msg with len: " << m.data->len << " op: " << m.data->_operation << endl;
        clientQueues[clientID->str()]->push( b.obj() );

        return true;
    }
Ejemplo n.º 9
0
void foreach_neighbour(const int3 &pos, std::function<void(const int3& pos)> foo)
{
	for(const int3 &dir : dirs)
	{
		const int3 n = pos + dir;
		if(cb->isInTheMap(n))
			foo(pos+dir);
	}
}
Ejemplo n.º 10
0
int howManyTilesWillBeDiscovered(const int3 &pos, int radious)
{ //TODO: do not explore dead-end boundaries
	int ret = 0;
	for(int x = pos.x - radious; x <= pos.x + radious; x++)
	{
		for(int y = pos.y - radious; y <= pos.y + radious; y++)
		{
			int3 npos = int3(x,y,pos.z);
			if(cb->isInTheMap(npos) && pos.dist2d(npos) - 0.5 < radious  && !cb->isVisible(npos))
			{
				if (!boundaryBetweenTwoPoints (pos, npos))
					ret++;
			}
		}
	}

	return ret;
}
Ejemplo n.º 11
0
	void condition_variable_recursive_mutex::check(xrecursive_mutex& mtx)
	{
		if (mtx.pri_level != xrecursive_mutex::NOCARE_PRIMARY_LEVEL)
		{
			quick_int_stack* pri_levels = locks_hold_by_current_thread.get();
			XASSERT((pri_levels != NULL) && (!pri_levels->empty()) &&
				(pri_levels->top() == mtx.pri_level));
		}
	}
Ejemplo n.º 12
0
bool LogAcceptCategory(const char* category)
{
    if (category != NULL) {
        if (!fDebug)
            return false;

        static boost::thread_specific_ptr<set<string> > ptrCategory;
        if (ptrCategory.get() == NULL) {
            const vector<string>& categories = mapMultiArgs["-debug"];
            ptrCategory.reset(new set<string>(categories.begin(), categories.end()));
        }
        const set<string>& setCategories = *ptrCategory.get();

        if (setCategories.count(string("")) == 0 && setCategories.count(string("1")) == 0 && setCategories.count(string(category)) == 0)
            return false;
    }
    return true;
}
Ejemplo n.º 13
0
Archivo: Goals.cpp Proyecto: szpak/vcmi
TSubgoal GetObj::whatToDoToAchieve()
{
	const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(objid));
	if(!obj)
		return sptr (Goals::Explore());
	int3 pos = obj->visitablePos();
	if (hero)
	{
		if (ai->isAccessibleForHero(pos, hero))
			return sptr (Goals::VisitTile(pos).sethero(hero));
	}
	else
	{
		if (isReachable(obj))
			return sptr (Goals::VisitTile(pos).sethero(hero)); //we must visit object with same hero, if any
	}
	return sptr (Goals::ClearWayTo(pos).sethero(hero));
}
Ejemplo n.º 14
0
/**
 * Checks whether the calling thread is one of the worker threads
 * for this work queue.
 *
 * @returns true if called from one of the worker threads, false otherwise
 */
bool WorkQueue::IsWorkerThread(void) const
{
	WorkQueue **pwq = l_ThreadWorkQueue.get();

	if (!pwq)
		return false;

	return *pwq == this;
}
Ejemplo n.º 15
0
Analyzer* AnalyzerFactory::getCurrentThreadAnalyzerWithSynonyms(const CoreInfo_t* config) {

    static boost::thread_specific_ptr<Analyzer> _tsAnalyzerObjectWithSynonyms;
    if (_tsAnalyzerObjectWithSynonyms.get() == NULL)
    {
        Logger::debug("Create Analyzer object for thread = %d ",  pthread_self());
        _tsAnalyzerObjectWithSynonyms.reset(AnalyzerFactory::createAnalyzer(config, false));
    }

    Analyzer* analyzer = _tsAnalyzerObjectWithSynonyms.get();

    // clear the initial states of the filters in the analyzer, e.g.,
    // for those filters that have an internal buffer to keep tokens.
    // Such an internal buffer can have leftover tokens from
    // the previous query (possibly an invalid query)
    analyzer->clearFilterStates();

    return analyzer;
}
Ejemplo n.º 16
0
    void operator()()
    {
        //int* p = manager::instance().get();
        std::string* p = manager::instance().get();
        *p = "hello";

        //ptr.reset(new (std::nothrow) int(200));
        ptr.reset(new (std::nothrow) std::string("world"));
        std::cout << "thread 2: " << *ptr << std::endl;
    }
Ejemplo n.º 17
0
ui64 evaluateDanger(crint3 tile)
{
	const TerrainTile *t = cb->getTile(tile, false);
	if(!t) //we can know about guard but can't check its tile (the edge of fow)
		return 190000000; //MUCH

	ui64 objectDanger = 0, guardDanger = 0;

	auto visObjs = cb->getVisitableObjs(tile);
	if(visObjs.size())
		objectDanger = evaluateDanger(visObjs.back());

	int3 guardPos = cb->guardingCreaturePosition(tile);
	if(guardPos.x >= 0 && guardPos != tile)
		guardDanger = evaluateDanger(guardPos);

	//TODO mozna odwiedzic blockvis nie ruszajac straznika
	return std::max(objectDanger, guardDanger);
}
Ejemplo n.º 18
0
 Client::Context::Context( string ns , Database * db, bool doauth )
     : _client( currentClient.get() ) , _oldContext( _client->_context ) , 
       _path( dbpath ) , _lock(0) , _justCreated(false) {
     assert( db && db->isOk() );
     _ns = ns;
     _db = db;
     _client->_context = this;
     if ( doauth )
         _auth();
 }
Ejemplo n.º 19
0
    int   dlclose(void *handle) {
      g_LastError.reset();
      if (!handle)
        return 0;
#ifdef _WIN32
      // Mimic unix dlclose (0 on success)
      return FreeLibrary((HINSTANCE) handle) != 0 ? 0 : -1;
#else
      return ::dlclose(handle);
#endif
    }
Ejemplo n.º 20
0
void foreach_neighbour(const int3 &pos, std::function<void(const int3& pos)> foo)
{
	CCallback * cbp = cb.get(); // avoid costly retrieval of thread-specific pointer

	for(const int3 &dir : dirs)
	{
		const int3 n = pos + dir;
		if(cbp->isInTheMap(n))
			foo(pos+dir);
	}
}
Ejemplo n.º 21
0
void SectorMap::update()
{
	visibleTiles = cb->getAllVisibleTiles();
	auto shape = visibleTiles->shape();
	sector.resize(boost::extents[shape[0]][shape[1]][shape[2]]);

	clear();
	int curSector = 3; //0 is invisible, 1 is not explored

	CCallback * cbp = cb.get(); //optimization
	foreach_tile_pos([&](crint3 pos)
	{
		if (retrieveTile(pos) == NOT_CHECKED)
		{
			if (!markIfBlocked(retrieveTile(pos), pos))
				exploreNewSector(pos, curSector++, cbp);
		}
	});
	valid = true;
}
Ejemplo n.º 22
0
void getVisibleNeighbours(const std::vector<int3> &tiles, std::vector<int3> &out)
{
	for(const int3 &tile : tiles)
	{
		foreach_neighbour(tile, [&](int3 neighbour)
		{
			if(cb->isVisible(neighbour))
				out.push_back(neighbour);
		});
	}
}
Ejemplo n.º 23
0
Archivo: Goals.cpp Proyecto: szpak/vcmi
TSubgoal VisitHero::whatToDoToAchieve()
{
	const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(objid));
	if(!obj)
		return sptr (Goals::Explore());
	int3 pos = obj->visitablePos();

	if (hero && ai->isAccessibleForHero(pos, hero, true) && isSafeToVisit(hero, pos)) //enemy heroes can get reinforcements
	{
		if (hero->pos == pos)
			logAi->errorStream() << "Hero " << hero.name << " tries to visit himself.";
		else
		{
			//can't use VISIT_TILE here as tile appears blocked by target hero
			//FIXME: elementar goal should not be abstract
			return sptr (Goals::VisitHero(objid).sethero(hero).settile(pos).setisElementar(true));
		}
	}
	return sptr (Goals::Invalid());
}
Ejemplo n.º 24
0
Archivo: Goals.cpp Proyecto: szpak/vcmi
bool GetObj::fulfillsMe (TSubgoal goal)
{
	if (goal->goalType == Goals::VISIT_TILE)
	{
		auto obj = cb->getObj(ObjectInstanceID(objid));
		if (obj && obj->visitablePos() == goal->tile) //object could be removed
			return true;
	}

	return false;
}
Ejemplo n.º 25
0
int3 whereToExplore(HeroPtr h)
{
	TimeCheck tc ("where to explore");
	int radius = h->getSightRadious();
	int3 hpos = h->visitablePos();

	SectorMap sm(h);

	//look for nearby objs -> visit them if they're close enouh
	const int DIST_LIMIT = 3;
	std::vector<const CGObjectInstance *> nearbyVisitableObjs;
	for (int x = hpos.x - DIST_LIMIT; x <= hpos.x + DIST_LIMIT; ++x) //get only local objects instead of all possible objects on the map
	{
		for (int y = hpos.y - DIST_LIMIT; y <= hpos.y + DIST_LIMIT; ++y)
		{
			for (auto obj : cb->getVisitableObjs (int3(x,y,hpos.z), false))
			{
				int3 op = obj->visitablePos();
				CGPath p;
				ai->myCb->getPathsInfo(h.get())->getPath(op, p);
				if (p.nodes.size() && p.endPos() == op && p.nodes.size() <= DIST_LIMIT)
					if (ai->isGoodForVisit(obj, h, sm))
						nearbyVisitableObjs.push_back(obj);
			}
		}
	}
	vstd::removeDuplicates (nearbyVisitableObjs); //one object may occupy multiple tiles
	boost::sort(nearbyVisitableObjs, CDistanceSorter(h.get()));
	if(nearbyVisitableObjs.size())
		return nearbyVisitableObjs.back()->visitablePos();

	try //check if nearby tiles allow us to reveal anything - this is quick
	{
		return ai->explorationBestNeighbour(hpos, radius, h);
	}
	catch(cannotFulfillGoalException &e)
	{
		//perform exhaustive search
		return ai->explorationNewPoint(h);
	}
}
Ejemplo n.º 26
0
void __cxa_throw(void *obj, TYPEINFO_TYPE *pvtinfo, void (*dest)(void *))
{
	auto *tinfo = static_cast<std::type_info *>(pvtinfo);

	typedef void (*cxa_throw_fn)(void *, std::type_info *, void (*)(void *)) __attribute__((noreturn));
	static cxa_throw_fn real_cxa_throw;

#if !defined(__GLIBCXX__) && !defined(_WIN32)
	l_LastExceptionObj.reset(new void *(obj));
	l_LastExceptionPvtInfo.reset(new TYPEINFO_TYPE *(pvtinfo));
	l_LastExceptionDest.reset(new DestCallback(dest));
#endif /* !defined(__GLIBCXX__) && !defined(_WIN32) */

	if (real_cxa_throw == nullptr)
		real_cxa_throw = (cxa_throw_fn)dlsym(RTLD_NEXT, "__cxa_throw");

#ifndef NO_CAST_EXCEPTION
	void *uex = cast_exception(obj, tinfo, &typeid(user_error));
	auto *ex = reinterpret_cast<boost::exception *>(cast_exception(obj, tinfo, &typeid(boost::exception)));

	if (!uex) {
#endif /* NO_CAST_EXCEPTION */
		StackTrace stack;
		SetLastExceptionStack(stack);

#ifndef NO_CAST_EXCEPTION
		if (ex && !boost::get_error_info<StackTraceErrorInfo>(*ex))
			*ex << StackTraceErrorInfo(stack);
	}
#endif /* NO_CAST_EXCEPTION */

	ContextTrace context;
	SetLastExceptionContext(context);

#ifndef NO_CAST_EXCEPTION
	if (ex && !boost::get_error_info<ContextTraceErrorInfo>(*ex))
		*ex << ContextTraceErrorInfo(context);
#endif /* NO_CAST_EXCEPTION */

	real_cxa_throw(obj, tinfo, dest);
}
void FAllocationsTracker::collectLeaks()
{
    if(canRecord())
    {
        ThreadGuard recursiveLock(sRecursiveCallGuard.get());
        FLockGuard_t lock(m_mutex);
        
        UOstringStream_t ss;
        size_t totalAllocs = getTotalAllocs();

        if (likely(totalAllocs == 0))
        {
            ss << UString("AllocationsTracker: No memory leaks").c_str() << std::endl;
        }
        else
        {
            UVectorTmpl<std::pair< void*, Block> > orderedVector(m_allocations.begin(),m_allocations.end());
            
            sort_by_mem memsort;
            std::sort(orderedVector.begin(), orderedVector.end(), memsort);
            
            ss << "AllocationsTracker: Detected memory leaks" << std::endl;
            ss << UFormat("AllocatinsTracker: (%d) Allocation(s) with total %d bytes.") % m_allocations.size() % totalAllocs;
            ss << std::endl << "Allocations dump (first 50 entries):" << std::endl << std::endl;

            ss << " +-------+---------------------------------------------------------------------------------------------------" << std::endl;
            ss << " | BYTES |                                          TAG                                                      " << std::endl;
            ss << " +-------+---------------------------------------------------------------------------------------------------" << std::endl;
            
            int entryCounter = 50;
            for(const auto& pair : orderedVector)
            {
                const Block& block = pair.second;
                
                ss << " | " << UFormat("%-6d| %s") % block.size % block.tag.c_str() << std::endl;
                
                entryCounter--;
                if( entryCounter == 0) break;
            }
            ss << " +-------+---------------------------------------------------------------------------------------------------" << std::endl;
            ss << std::endl;
            ss << UFormat("Warnings: %d") % m_warningMessages.size() << std::endl;
            for(const auto& message : m_warningMessages)
            {
                ss << message << std::endl;
            }

            ss << std::endl;
        }

        FLogNormal((ss.str().c_str()));
    }
}
Ejemplo n.º 28
0
Archivo: Goals.cpp Proyecto: szpak/vcmi
TSubgoal DigAtTile::whatToDoToAchieve()
{
	const CGObjectInstance *firstObj = frontOrNull(cb->getVisitableObjs(tile));
	if(firstObj && firstObj->ID == Obj::HERO && firstObj->tempOwner == ai->playerID) //we have hero at dest
	{
		const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(firstObj);
		sethero(h).setisElementar(true);
		return sptr (*this);
	}

	return sptr (Goals::VisitTile(tile));
}
Ejemplo n.º 29
0
    bool LocateClosestEndPointForCoordinate(const FixedPointCoordinate &input_coordinate,
                                            FixedPointCoordinate &result,
                                            const unsigned zoom_level = 18) override final
    {
        if (!m_static_rtree.get() || CURRENT_TIMESTAMP != m_static_rtree->first)
        {
            LoadRTree();
        }

        return m_static_rtree->second->LocateClosestEndPointForCoordinate(input_coordinate, result,
                                                                          zoom_level);
    }
Ejemplo n.º 30
0
    void LoadRTree()
    {
        BOOST_ASSERT_MSG(!m_coordinate_list->empty(), "coordinates must be loaded before r-tree");

        RTreeNode *tree_ptr =
            data_layout->GetBlockPtr<RTreeNode>(shared_memory, SharedDataLayout::R_SEARCH_TREE);
        m_static_rtree.reset(new TimeStampedRTreePair(
            CURRENT_TIMESTAMP,
            osrm::make_unique<SharedRTree>(
                tree_ptr, data_layout->num_entries[SharedDataLayout::R_SEARCH_TREE],
                file_index_path, m_coordinate_list)));
    }