Beispiel #1
0
CLevelDBWrapper::CLevelDBWrapper(const boost::filesystem::path &path, size_t nCacheSize, bool fMemory, bool fWipe) {
    penv = NULL;
    readoptions.verify_checksums = true;
    iteroptions.verify_checksums = true;
    iteroptions.fill_cache = false;
    syncoptions.sync = true;
    options = GetOptions(nCacheSize);
    options.create_if_missing = true;
    if (fMemory) {
        penv = leveldb::NewMemEnv(leveldb::Env::Default());
        options.env = penv;
    } else {
        if (fWipe) {
            LogPrintf("Wiping LevelDB in %s\n", path.string().c_str());
            leveldb::DestroyDB(path.string(), options);
        }
        boost::filesystem::create_directory(path);
        LogPrintf("Opening LevelDB in %s\n", path.string().c_str());
    }
    leveldb::Status status = leveldb::DB::Open(options, path.string(), &pdb);
    HandleError(status);
    LogPrintf("Opened LevelDB successfully\n");
}
nsresult
SourceBuffer::ExpectLength(size_t aExpectedLength)
{
  MOZ_ASSERT(aExpectedLength > 0, "Zero expected size?");

  MutexAutoLock lock(mMutex);

  if (MOZ_UNLIKELY(mStatus)) {
    MOZ_ASSERT_UNREACHABLE("ExpectLength after SourceBuffer is complete");
    return NS_OK;
  }

  if (MOZ_UNLIKELY(mChunks.Length() > 0)) {
    MOZ_ASSERT_UNREACHABLE("Duplicate or post-Append call to ExpectLength");
    return NS_OK;
  }

  if (MOZ_UNLIKELY(NS_FAILED(AppendChunk(CreateChunk(aExpectedLength))))) {
    return HandleError(NS_ERROR_OUT_OF_MEMORY);
  }

  return NS_OK;
}
void FOutputDeviceWindowsError::Serialize( const TCHAR* Msg, ELogVerbosity::Type Verbosity, const class FName& Category )
{
	FPlatformMisc::DebugBreak();
   
	if( !GIsCriticalError )
	{   
		const int32 LastError = ::GetLastError();

		// First appError.
		GIsCriticalError = 1;
		TCHAR ErrorBuffer[1024];
		ErrorBuffer[0] = 0;

		// Windows error.
		UE_LOG( LogWindows, Error, TEXT( "Windows GetLastError: %s (%i)" ), FPlatformMisc::GetSystemErrorMessage( ErrorBuffer, 1024, LastError ), LastError );
	}
	else
	{
		UE_LOG(LogWindows, Error, TEXT("Error reentered: %s"), Msg );
	}

	if( GIsGuarded )
	{
		// Propagate error so structured exception handler can perform necessary work.
#if PLATFORM_EXCEPTIONS_DISABLED
		FPlatformMisc::DebugBreak();
#endif
		FPlatformMisc::RaiseException( 1 );
	}
	else
	{
		// We crashed outside the guarded code (e.g. appExit).
		HandleError();
		FPlatformMisc::RequestExit( true );
	}
}
Beispiel #4
0
// Encrypt/Decrypt functionality, called by pager.c
void* sqlite3Codec(void *pCodec, void *data, Pgno nPageNum, int nMode)
{
    if (pCodec == NULL) //Db not encrypted
        return data;

    switch(nMode)
    {
    case 0: // Undo a "case 7" journal file encryption
    case 2: // Reload a page
    case 3: // Load a page
        if (HasReadKey(pCodec))
            Decrypt(pCodec, nPageNum, (unsigned char*) data);
        break;
    case 6: // Encrypt a page for the main database file
        if (HasWriteKey(pCodec))
            data = Encrypt(pCodec, nPageNum, (unsigned char*) data, 1);
        break;
    case 7: // Encrypt a page for the journal file
    /*
    *Under normal circumstances, the readkey is the same as the writekey.  However,
    *when the database is being rekeyed, the readkey is not the same as the writekey.
    *(The writekey is the "destination key" for the rekey operation and the readkey
    *is the key the db is currently encrypted with)
    *Therefore, for case 7, when the rollback is being written, always encrypt using
    *the database's readkey, which is guaranteed to be the same key that was used to
    *read and write the original data.
    */
        if (HasReadKey(pCodec))
            data = Encrypt(pCodec, nPageNum, (unsigned char*) data, 0);
        break;
    }
    
    HandleError(pCodec);

    return data;
}
Beispiel #5
0
    void TCPSocket::WriteThread()
    {
        this->mutex.lock();
        while (!this->writeQueue.empty())
        {
            BytesRef data = this->writeQueue.front();
            char* buffer = data->Pointer();
            size_t remaining = data->Length();

            // Release lock while sending data to avoid blocking write().
            this->mutex.unlock();
            while (true)
            {
                try
                {
                    size_t sent = this->socket.sendBytes(buffer, remaining);
                    if (sent == remaining) break;

                    buffer += sent;
                    remaining -= sent;
                }
                catch (Poco::Exception& e)
                {
                    HandleError(e);
                    return;
                }
            }

            this->mutex.lock();
            this->writeQueue.pop();
        }

        // Notify listeners we have fully drained the queue.
        this->mutex.unlock();
        FireEvent("drain");
    }
Beispiel #6
0
void CSoundGroup::Reload()
{
	m_index = 0; // reset our index

#if CONFIG2_AUDIO
	ReleaseGroup();

	if ( g_SoundManager ) {
		for (size_t i = 0; i < filenames.size(); i++)
		{
			VfsPath  thePath =  m_filepath/filenames[i];
			CSoundData* itemData = CSoundData::SoundDataFromFile(thePath);

			if (itemData == NULL)
				HandleError(L"error loading sound", thePath, ERR::FAIL);
			else
				snd_group.push_back(itemData->IncrementCount());
		}

		if (TestFlag(eRandOrder))
			random_shuffle(snd_group.begin(), snd_group.end());	
	}
#endif // CONFIG2_AUDIO
}
void
find_libdir (void)
{
    const char searchfile[] = "Colour.pal";
    /* default_dir will be something like "C:\\LINCITY1.11" */
    const char default_dir[] = "C:\\LINCITY" VERSION;

    /* Check 1: environment variable */
    _searchenv (searchfile, "LINCITY_HOME", LIBDIR);
    if (*LIBDIR != '\0') {
	int endofpath_offset = strlen (LIBDIR) - strlen (searchfile) - 1;
	LIBDIR[endofpath_offset] = '\0';
	return;
    }

    /* Check 2: default location */
    if ((_access (default_dir, 0)) != -1) {
	strcpy (LIBDIR, default_dir);
	return;
    }

    /* Finally give up */
    HandleError ("Error. Can't find LINCITY_HOME", FATAL);
}
Beispiel #8
0
BOOL 
CUdpCommClient::Push(CUdpPacketNode* pcPktNode)
{
	if (pcPktNode->GetRawLen() >= m_ulMaxSndPktLen)
	{
		HandleError(OCFCLIENT_ERROR_USERDEF, OCFCLIENT_ERROR_USERDEF_CATEGORY_PKTMAXSIZE, 0, pcPktNode->GetRawLen(), pcPktNode->GetRawBuff());
		return FALSE;
	}

	//
	Lock();

	m_cSndPktList.Add(pcPktNode);

	if (TRUE == m_bConnectFlag && FALSE == m_bWouldBlock)
	{
		SetEvent(m_hWrEvent);
	}

	//
	Unlock();

	return TRUE;
}
Beispiel #9
0
/**
* Prints out the name value records of the matching results.
*/
int printMetadataResults(hc_nvr_t *nvr, hc_session_t *session)
{
	char **names = NULL;
	char **values = NULL;
	int count = 0;

	hcerr_t hcError = hc_nvr_convert_to_string_arrays(nvr,
							  &names,
							  &values,
							  &count);

	if (hcError != HCERR_OK)
	{
		HandleError(session, hcError);	
		hc_session_free(session);
		return RETURN_STORAGETEK_ERROR;
	}	/* if error occurred */

	/* Print metadata record. printMetadataRecord is example specific code (in example_metadata.h) */
	/* and is not part of the @HoneycombProductName@ API. */
	printMetadataRecord(names, values, count);
	
	return RETURN_SUCCESS;
}   /* printMetadataResults */
Beispiel #10
0
BOOL CUdpClient::ProcessNetworkEvent()
{
	BOOL bContinue = TRUE;
	WSANETWORKEVENTS events;
	
	int rc = ::WSAEnumNetworkEvents(m_soClient, m_evSocket, &events);

	if(rc == SOCKET_ERROR)
		bContinue = HandleError();

	if(bContinue && events.lNetworkEvents & FD_READ)
		bContinue = HandleRead(events);

	if(bContinue && events.lNetworkEvents & FD_WRITE)
		bContinue = HandleWrite(events);

	if(m_bAsyncConnect && bContinue && events.lNetworkEvents & FD_CONNECT)
		bContinue = HandleConnect(events);

	if(bContinue && events.lNetworkEvents & FD_CLOSE)
		bContinue = HandleClosse(events);

	return bContinue;
}
bool CFI::CompileCFI(const string &str)
{
    // strip the 'epubcfi(...)' wrapping
    string cfi(str);
    if ( str.find("epubcfi(") == 0 )
    {
        cfi = cfi.substr(8, (str.size()-1)-8);
    }
    else if ( str.size() == 0 )
    {
        HandleError(EPUBError::CFIParseFailed, "Empty CFI string");
        return false;
    }
    else if ( str[0] != '/' )
    {
        HandleError(EPUBError::CFINonSlashStartCharacter);
    }
    
    StringList rangePieces = RangedCFIComponents(cfi);
    if ( rangePieces.size() != 1 && rangePieces.size() != 3 )
    {
        HandleError(EPUBError::CFIRangeComponentCountInvalid, _Str("Expected 1 or 3 range components, got ", rangePieces.size()));
        if ( rangePieces.size() == 0 )
            return false;
    }
    
    if ( CompileComponentsToList(CFIComponentStrings(rangePieces[0]), &_components) == false )
        return false;
    
    if ( rangePieces.size() >= 3 )
    {
        if ( CompileComponentsToList(CFIComponentStrings(rangePieces[1]), &_rangeStart) == false )
            return false;
        if ( CompileComponentsToList(CFIComponentStrings(rangePieces[2]), &_rangeEnd) == false )
            return false;
        
        // now sanity-check the range delimiters:
        
        // neither should be empty
        if ( _rangeStart.empty() || _rangeEnd.empty() )
        {
            HandleError(EPUBError::CFIRangeInvalid, "One of the supplied range components was empty.");
            return false;
        }
        
        // check the offsets at the end of each— they should be the same type
        if ( (_rangeStart.back().flags & Component::OffsetsMask) != (_rangeEnd.back().flags & Component::OffsetsMask) )
        {
            HandleError(EPUBError::CFIRangeInvalid, "Offsets at the end of range components are of different types.");
            return false;
        }
        
        // ensure that there are no side-bias values
        if ( (_rangeStart.back().sideBias != SideBias::Unspecified) ||
             (_rangeEnd.back().sideBias != SideBias::Unspecified) )
        {
            HandleError(EPUBError::CFIRangeContainsSideBias);
            // can safely ignore this one
        }
        
        // where the delimiters' component ranges overlap, start must be <= end
        auto maxsz = std::max(_rangeStart.size(), _rangeEnd.size());
        bool inequalNodeIndexFound = false;
        for ( decltype(maxsz) i = 0; i < maxsz; i++ )
        {
            if ( _rangeStart[i].nodeIndex > _rangeEnd[i].nodeIndex )
            {
                HandleError(EPUBError::CFIRangeInvalid, "Range components appear to be out of order.");
            }
            else if ( !inequalNodeIndexFound && _rangeStart[i].nodeIndex < _rangeEnd[i].nodeIndex )
            {
                inequalNodeIndexFound = true;
            }
        }
        
        // if the two ranges are equal aside from their offsets, the end offset must be > the start offset
        if ( !inequalNodeIndexFound && _rangeStart.size() == _rangeEnd.size() )
        {
            Component &s = _rangeStart.back(), &e = _rangeEnd.back();
            if ( s.HasCharacterOffset() && s.characterOffset > e.characterOffset )
            {
                HandleError(EPUBError::CFIRangeInvalid, "Range components appear to be out of order.");
            }
            else
            {
                if ( s.HasTemporalOffset() && s.temporalOffset > e.temporalOffset )
                    HandleError(EPUBError::CFIRangeInvalid, "Range components appear to be out of order.");
                if ( s.HasSpatialOffset() && s.spatialOffset > e.spatialOffset )
                    HandleError(EPUBError::CFIRangeInvalid, "Range components appear to be out of order.");
            }
        }
        
        _options |= RangeTriplet;
    }
    
    return true;
}
Beispiel #12
0
void
ClientUserLua::Diff( FileSys *f1, FileSys *f2, int doPage,
					char *diffFlags, Error *e )
{

	if ( P4LUADEBUG_CALLS )
		fprintf( stderr, "[P4] Diff() - comparing files\n" );

	//
	// Duck binary files. Much the same as ClientUser::Diff, we just
	// put the output into Ruby space rather than stdout.
	//
	if( !f1->IsTextual() || !f2->IsTextual() )
	{
		if ( f1->Compare( f2, e ) )
			results.AddOutput( "(... files differ ...)" );
		return;
	}

	// Time to diff the two text files. Need to ensure that the
	// files are in binary mode, so we have to create new FileSys
	// objects to do this.

	FileSys *f1_bin = FileSys::Create( FST_BINARY );
	FileSys *f2_bin = FileSys::Create( FST_BINARY );
	FileSys *t = FileSys::CreateGlobalTemp( f1->GetType() );

	f1_bin->Set( f1->Name() );
	f2_bin->Set( f2->Name() );

	{
		//
		// In its own block to make sure that the diff object is deleted
		// before we delete the FileSys objects.
		//
#ifndef OS_NEXT
		::
#endif
			Diff d;

		d.SetInput( f1_bin, f2_bin, diffFlags, e );
		if ( ! e->Test() ) d.SetOutput( t->Name(), e );
		if ( ! e->Test() ) d.DiffWithFlags( diffFlags );
		d.CloseOutput( e );

		// OK, now we have the diff output, read it in and add it to
		// the output.
		if ( ! e->Test() ) t->Open( FOM_READ, e );
		if ( ! e->Test() )
		{
			StrBuf 	b;
			while( t->ReadLine( &b, e ) )
				results.AddOutput( b.Text() );
		}
	}

	delete t;
	delete f1_bin;
	delete f2_bin;

	if ( e->Test() ) HandleError( e );
}
Beispiel #13
0
void
ClientUserLua::OutputStat( StrDict *values )
{
	StrPtr *		spec 	= values->GetVar( "specdef" );
	StrPtr *		data 	= values->GetVar( "data" );
	StrPtr *		sf	= values->GetVar( "specFormatted" );
	StrDict *		dict	= values;
	SpecDataTable	specData;
	Error		e;

	//
	// Determine whether or not the data we've got contains a spec in one form
	// or another. 2000.1 -> 2005.1 servers supplied the form in a data variable
	// and we use the spec variable to parse the form. 2005.2 and later servers
	// supply the spec ready-parsed but set the 'specFormatted' variable to tell
	// the client what's going on. Either way, we need the specdef variable set
	// to enable spec parsing.
	//
	int			isspec	= spec && ( sf || data );

	//
	// Save the spec definition for later
	//
	if( spec )
		specMgr->AddSpecDef( cmd.Text(), spec->Text() );

	//
	// Parse any form supplied in the 'data' variable and convert it into a
	// dictionary.
	//
	if( spec && data )
	{
		// 2000.1 -> 2005.1 server's handle tagged form output by supplying the form
		// as text in the 'data' variable. We need to convert it to a dictionary
		// using the supplied spec.
		if( P4LUADEBUG_CALLS )
			fprintf( stderr, "[P4] OutputStat() - parsing form\n" );


		// Parse the form. Use the ParseNoValid() interface to prevent
		// errors caused by the use of invalid defaults for select items in
		// jobspecs.

//#if P4APIVER_ID >= 513538
		Spec s( spec->Text(), "", &e );
//#else
		//Spec s( spec->Text(), "" );
//#endif
		if( !e.Test() ) s.ParseNoValid( data->Text(), &specData, &e );
		if( e.Test() )
		{
			HandleError( &e );
			return;
		}
		dict = specData.Dict();
	}

	//
	// If what we've got is a parsed form, then we'll convert it to a P4::Spec
	// object. Otherwise it's a plain hash.
	//
	if( isspec )
	{
		if( P4LUADEBUG_CALLS )
			fprintf(stderr ,"[P4] OutputStat() - Converting to P4::Spec object\n");
		results.AddOutput( specMgr->StrDictToSpec( dict, spec ) );
		lua_pop( L, 1 );
	}
	else
	{
		if( P4LUADEBUG_CALLS )
			fprintf(stderr ,"[P4] OutputStat() - Converting to hash\n");
		results.AddOutput( specMgr->StrDictToHash( dict ) );
		lua_pop( L, 1 );
	}
}
Beispiel #14
0
int main(int argc, char* argv[])
{
	hc_session_t *session = NULL;

	hc_oid returnedOid;
	hc_long_t count = 0;
	int finished = 0;
	int32_t response_code = RETURN_SUCCESS;
	hc_query_result_set_t *rset = NULL;
	hc_nvr_t *nvr = NULL;
	hc_long_t query_integrity_time;
	int query_complete;

	
	hcerr_t	res = HCERR_OK;

	int parametersUsed = USES_SERVERADDRESS | USES_QUERY | USES_SELECT_METADATA | USES_MAXRESULTS;

	/* Initialize commandline structure */
	cmdLine.storagetekServerAddress = NULL;
	cmdLine.query = NULL;
	cmdLine.help = 0;
	cmdLine.debug_flags = 0;
	cmdLine.storagetekPort = 0;
	cmdLine.maxResults = DEFAULT_MAX_RESULTS;

	/* Initialize metadata map.  The metadata map structure is not part of the API but common */
	/* code written for the convenience of these examples.  See example_metadata.c. */
        if (initMetadataMap(&cmdLine.cmdlineMetadata) == 0)
        {
                return exitApp(RETURN_MAPINITERROR);
        }       /* if initMetadataMap == 0 */

	/* Get commandline (see example_commandline.c) */
	if (parseCommandline(	argc,
				argv,
				parametersUsed) == 0)
	{
		printUsage();
		return RETURN_COMMANDLINE_ERROR;
	}	/* if parseCommandline failed */
	else
	{
		if (cmdLine.help == 1)
		{
			printUsage();
			return RETURN_SUCCESS;
		}	/* if help requested */
	}	/* else parseCommandline succeeded */

	/* Initialize @HoneycombProductName@ API */
        res = hc_init(malloc,free,realloc);
        if (res != HCERR_OK)
        {
                printf("An error occurred while initializing the API.\n");
                return res;
        }  /* if error */

       if (cmdLine.debug_flags) {
		/* Internal debug flags */
		hc_set_global_parameter(HCOPT_DEBUG_FLAGS, cmdLine.debug_flags);
       }

	res = hc_session_create_ez(cmdLine.storagetekServerAddress, 
				(cmdLine.storagetekPort > 0 ? 
				 cmdLine.storagetekPort : 
				 STORAGETEK_PORT),
				&session);
	
	if (res != HCERR_OK)
	{
		HandleError(session,res);
		return RETURN_STORAGETEK_ERROR;
	}	/* if initialization failed */

	/* Run queryplus if we have a select clause (-s option on the commandline), otherwise run query */
	if (cmdLine.cmdlineMetadata.mapSize > 0)
	{
		res = hc_query_ez(session,
				cmdLine.query,
				cmdLine.cmdlineMetadata.namePointerArray,	
				cmdLine.cmdlineMetadata.mapSize,
                                100,
				&rset);
	}	/* if outputing metadata */
	else
	{	
		res = hc_query_ez(session,
				cmdLine.query,
                                NULL,
                                0,
                                100,
				&rset);
	}

	if (res != HCERR_OK)
        {
                HandleError(session, res);
                hc_session_free(session);
                hc_cleanup();
                return RETURN_STORAGETEK_ERROR;
        }       /* if not successful */

	/* Loop up until the maximum result size */
	for (count = 0; count < cmdLine.maxResults; count++) 
	{
		/* Get the next result */
		res = hc_qrs_next_ez(rset, &returnedOid, &nvr, &finished);	

 		if (res != HCERR_OK)
   		{
			HandleError(session, res);
			hc_session_free(session);
			hc_cleanup();
			return RETURN_STORAGETEK_ERROR;
    		}	/* if not successful */

                if (finished)
                        break;

		/* Print the next result to standard output */
		if (cmdLine.cmdlineMetadata.mapSize > 0)
		{
			printMetadataResults(nvr, session);
		}
		else
		{
    			printOIDResults((char *) &returnedOid);
		}
	}	/* loop through results */

	res = hc_qrs_is_query_complete(rset,&query_complete);
	if (res != HCERR_OK) 
	{
    		HandleError(session, res);
    		response_code = RETURN_STORAGETEK_ERROR;
	}
	res = hc_qrs_get_query_integrity_time(rset,&query_integrity_time);
	if (res != HCERR_OK) 
	{
    		HandleError(session, res);
    		response_code = RETURN_STORAGETEK_ERROR;
	}

	printf("Query Integrity Status %s at time %lld\n",
	       query_complete ? "true" : "false",
	       query_integrity_time);

        res = hc_qrs_free(rset);

	if (res != HCERR_OK) 
	{
    		HandleError(session, res);
    		response_code = RETURN_STORAGETEK_ERROR;
	}

	hc_session_free(session);
	hc_cleanup();

        return exitApp(response_code);
}	/* main */
Beispiel #15
0
PyObject *Connection_connect(Connection *self, PyObject *args)
{
  /*
  Args:
  UMConnection conn, const char *_host, int _port, const char *_username, const char *_password, const char *_database, int _autoCommit, const char *_charset*/

  char *host;
  int port;
  char *username;
  char *password;
  char *database;

  int autoCommit;
  char *pstrCharset = NULL;
  PyObject *acObj = NULL;

  if (!PyArg_ParseTuple (args, "sisss|Os", &host, &port, &username, &password, &database, &acObj, &pstrCharset))
  {
    return NULL;
  }

  if (acObj)
  {
    PRINTMARK();
    autoCommit = (PyObject_IsTrue(acObj) == 1) ? 1 : 0;
  }
  if (pstrCharset)
  {
    if (strcmp (pstrCharset, "utf8") == 0)
    {
      self->charset = MCS_utf8_general_ci;
      self->PFN_PyUnicode_Encode = PyUnicode_EncodeUTF8;
    }
    else
      if (strcmp (pstrCharset, "latin1") == 0)
      {
        self->charset = MCS_latin1_general_ci;
        self->PFN_PyUnicode_Encode = PyUnicode_EncodeLatin1;
      }
      else
        if (strcmp (pstrCharset, "ascii") == 0)
        {
          self->charset = MCS_ascii_general_ci;
          self->PFN_PyUnicode_Encode = PyUnicode_EncodeASCII;
        }
        else
          if (strcmp (pstrCharset, "cp1250") == 0)
          {
            self->charset = MCS_cp1250_general_ci;
            self->PFN_PyUnicode_Encode = PyUnicode_EncodeCP1250Helper;
          }
          else
          {
            return PyErr_Format (PyExc_ValueError, "Unsupported character set '%s' specified", pstrCharset);
          }
  }
  else
  {
    self->charset = MCS_utf8_general_ci;
    self->PFN_PyUnicode_Encode = PyUnicode_EncodeUTF8;
  }

  if (!UMConnection_Connect (self->conn, host, port, username, password, database, acObj ? &autoCommit : NULL, self->charset))
  {
    return HandleError(self, "connect");
  }

  Py_RETURN_NONE;
}
Beispiel #16
0
/* This function generates a batch named prepare.bat (default).
 * The batch contains 6 experiments
 * Exp1: SPE - (Special) - runs IOCount SR then IOCount RW then IOCount SR
 * 		 The goal is here to determine the Pause value
 * Exp2: SIO.SR - runs IOCount2 SR - goal: determine IOIgnoreSR and IOCountSR
 * Exp3-5 : same for RR, SW, RW
 * Exp6 : Random format of the device 
 */ 
 	void GenPrepare(sParams* PB) {
	FILE*		fp2 = NULL;	// file pointer
	int32 		size;

	fp2 = fopen(PB->outName, "w");
	if (fp2 == NULL) HandleError("GenBench", "Could not open output file", GetLastError(), ERR_ABORT);
	strcpy(PB->comment, "SPE");
	strcpy(PB->base, "SR");
	PB->expID = 1;
	PB->microBenchID = 0;
	PB->pauseExp = 10000;
	size = PB->IOSize * PB->IOCount;
	for (PB->runID = 0; PB->runID < PB->nbRun; (PB->runID)++) {
		PB->targetOffset = rg.IRandom(0,(int32)((PB->deviceSize/2 - size)/BLOCK))*BLOCK; // We choose a random location in the first half of the device
		PB->targetSize = PB->deviceSize - PB->targetOffset;
		GenExp(fp2, PB);
	}
	PB->IOCount = PB->IOCount2;
	size = PB->IOSize * PB->IOCount;
	strcpy(PB->comment, "SIO.SR");
	PB->expID = 2;
	for (PB->runID = 0; PB->runID < PB->nbRun; (PB->runID)++) {
		PB->targetOffset = rg.IRandom(0,(int32)((PB->deviceSize/2 - size)/BLOCK))*BLOCK; // We choose a random location in the first half of the device
		PB->targetSize = PB->deviceSize - PB->targetOffset;
		GenExp(fp2, PB);
	}
	strcpy(PB->base, "RR");
	strcpy(PB->comment, "SIO.RR");
	PB->expID++;
	for (PB->runID = 0; PB->runID < PB->nbRun; (PB->runID)++) {
		PB->targetOffset = rg.IRandom(0,(int32)((PB->deviceSize/2 - size)/BLOCK))*BLOCK; // We choose a random location in the first half of the device
		PB->targetSize = PB->deviceSize - PB->targetOffset;
		GenExp(fp2, PB);
	}
	strcpy(PB->base, "SW");
	strcpy(PB->comment, "SIO.SW");
	PB->expID++;
	for (PB->runID = 0; PB->runID < PB->nbRun; (PB->runID)++) {
		PB->targetOffset = rg.IRandom(0,(int32)((PB->deviceSize/2 - size)/BLOCK))*BLOCK; // We choose a random location in the first half of the device
		PB->targetSize = PB->deviceSize - PB->targetOffset;
		GenExp(fp2, PB);
	}
	strcpy(PB->base, "RW");
	strcpy(PB->comment, "SIO.RW");
	PB->expID++;
	for (PB->runID = 0; PB->runID < PB->nbRun; (PB->runID)++) {
		PB->targetOffset = rg.IRandom(0,(int32)((PB->deviceSize/2 - size)/BLOCK))*BLOCK; // We choose a random location in the first half of the device
		PB->targetSize = PB->deviceSize - PB->targetOffset;
		GenExp(fp2, PB);
	}
	PB->expID++;
	fprintf(fp2, "FlashIO RandomFormat Dev %d Bench %d Exp %d ", PB->deviceNum, PB->microBenchID, PB->expID);

	if (PB->trimBeforeRun == TRUE)
			fprintf(fp2, "TrimBeforeRun True\n");
		else
			fprintf(fp2, "\n");

	if (PB->fake == TRUE) 
		fprintf(fp2, "Fake True\n Pause\n");
	else
		fprintf(fp2, "\n Pause\n");

	fclose(fp2);
}
Beispiel #17
0
bool DoPrepared(HDBC	lpDbc, TCHAR* szInput)
{
	int arrIdx = 0;
	RETCODE		RetCode;
	SQLSMALLINT	sNumResults;
	HSTMT	lpStmt = NULL;
	TCHAR* szIter = szInput;
	int cnt = 0;

	TRYODBCP(lpDbc,
	         SQL_HANDLE_DBC,
	         SQLAllocHandle(SQL_HANDLE_STMT, lpDbc, &lpStmt));

	RetCode = SQLPrepare(lpStmt, (SQLCHAR*) szInput, SQL_NTS);

	while (NULL != (szIter = strstr(szIter, "?"))) {
		++cnt;
		++szIter;
	}

	TCHAR	szParams[MAX_PARAMS][SQL_QUERY_SIZE];
	SQLLEN	lenParams[MAX_PARAMS];
	for (int sqlIdx = 1; sqlIdx <= cnt; ++sqlIdx) {
		arrIdx = sqlIdx - 1;
		_fgetts(szParams[arrIdx], SQL_QUERY_SIZE - 1, stdin);
		lenParams[arrIdx] = strlen(szParams[arrIdx]);
		szParams[arrIdx][lenParams[arrIdx]] = '\0';
		lenParams[arrIdx] -= 1;
		TRYODBCP(lpStmt, SQL_HANDLE_STMT,
		         SQLBindParameter(lpStmt, sqlIdx, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, 255, 0, szParams[arrIdx],
		                          SQL_QUERY_SIZE, &lenParams[arrIdx]));
	}

	RetCode = SQLExecute(lpStmt);

	switch (RetCode)
	{
	case	SQL_SUCCESS_WITH_INFO:
	{
		HandleError(lpStmt, SQL_HANDLE_STMT, RetCode);
		// fall through
	}
	case	SQL_SUCCESS:
	{
		// If this is a row-returning query, display
		// results
		TRYODBCP(lpStmt,
		         SQL_HANDLE_STMT,
		         SQLNumResultCols(lpStmt, &sNumResults));

		if (sNumResults > 0)
		{
			DisplayResults(lpStmt, sNumResults);
		} else
		{
			SQLLEN		siRowCount;

			TRYODBCP(lpStmt,
			         SQL_HANDLE_STMT,
			         SQLRowCount(lpStmt, &siRowCount));
			if (siRowCount >= 0)
			{
				_tprintf(TEXT("%ld %s affected\n"),
				         static_cast<long>(siRowCount),
				         siRowCount == 1 ? TEXT("row") : TEXT("rows"));
			}
		}
		break;
	}

	case	SQL_ERROR:
	{
		HandleError(lpStmt, SQL_HANDLE_STMT, RetCode);
		break;
	}

	default:
		fprintf(stderr, "Unexpected return code %d!\n", RetCode);
	}

	SQLFreeStmt(lpStmt, SQL_DROP);
	return true;
ExitP:
	return false;
}
Beispiel #18
0
/**
 * Restarts a running task.
 * If the task isn't started, it starts it.
 * @return false if the task is running and we are unable to kill the previous instance
 */
bool Task::Restart()
{
    return HandleError(taskRestart(m_taskID));
}
Beispiel #19
0
/**
 * This routine changes a task's priority to a specified priority.
 * Priorities range from 0, the highest priority, to 255, the lowest priority.
 * Default task priority is 100.
 * @param priority The priority the task should run at.
 * @returns true on success.
 */
bool Task::SetPriority(INT32 priority)
{
    m_priority = priority;
    return HandleError(taskPrioritySet(m_taskID, m_priority));
}
Beispiel #20
0
/**
 * Resumes a paused task.
 * Returns true on success, false if unable to resume or if the task isn't running/paused.
 */
bool Task::Resume()
{
    return HandleError(taskResume(m_taskID));
}
Beispiel #21
0
/**
 * Pauses a running task.
 * Returns true on success, false if unable to pause or the task isn't running.
 */
bool Task::Suspend()
{
    return HandleError(taskSuspend(m_taskID));
}
void CFI::Component::Parse(const string &str)
{
    if ( str.empty() )
    {
        HandleError(EPUBError::CFIParseFailed, "Empty string supplied to CFI::Component");
        return;
    }
    
    std::string utf8 = str.stl_str();
    std::istringstream iss(utf8);
    
    // read an integer
    iss >> nodeIndex;
    if ( nodeIndex == 0 && iss.fail() )
    {
        HandleError(EPUBError::CFIParseFailed, _Str("No node value at start of CFI::Component string '", str, "'"));
        return;
    }
    
    while ( !iss.eof() )
    {
        char next = 0;
        iss >> next;
        
        switch ( next )
        {
            case '[':
            {
                size_t pos = static_cast<size_t>(iss.tellg());
                iss.ignore(std::numeric_limits<std::streamsize>::max(), ']');
                size_t end = ((size_t)iss.tellg()) - 1;
                
                if ( iss.eof() )
                {
                    HandleError(EPUBError::CFIParseFailed);
                    return;
                }
                
                if ( characterOffset != 0 )
                {
                    // this is a text qualifier
                    flags |= TextQualifier;
                    std::string sub = utf8.substr(pos, end-pos);
                    
                    // is there a side-bias?
                    auto biasPos = sub.find(";s=");
                    if ( biasPos == std::string::npos )
                    {
                        textQualifier = std::move(sub);
                    }
                    else
                    {
                        textQualifier = sub.substr(0, biasPos);
                        if ( sub.size() > biasPos + 3 )
                        {
                            switch ( sub[biasPos+3] )
                            {
                                case 'b':
                                    sideBias = SideBias::Before;
                                    break;
                                case 'a':
                                    sideBias = SideBias::After;
                                    break;
                                default:
                                    sideBias = SideBias::Unspecified;
                                    break;
                            }
                        }
                    }
                }
                else
                {
                    // it's a position qualifier
                    qualifier = utf8.substr(pos, end-pos);
                    flags |= Qualifier;
                }
                
                break;
            }
                
            case '~':
            {
                // character offsets and spatial/temporal offsets are mutually exclusive
                if ( HasCharacterOffset() )
                    break;
                
                // read a numeral
                iss >> temporalOffset;
                flags |= TemporalOffset;
                break;
            }
                
            case '@':
            {
                // character offsets and spatial/temporal offsets are mutually exclusive
                if ( HasCharacterOffset() )
                    break;
                
                // two floats, separated by a colon
                float x, y;
                
                // read x
                iss >> x;
                
                // check for and skip delimiter
                if ( iss.peek() != ':' )
                    break;
                iss.ignore(1);
                
                // read y
                iss >> y;
                
                spatialOffset.x = x;
                spatialOffset.y = y;
                flags |= SpatialOffset;
                break;
            }
                
            case ':':
            {
                // character offsets and spatial/temporal offsets are mutually exclusive
                if ( HasSpatialTemporalOffset() )
                    break;
                
                iss >> characterOffset;
                flags |= CharacterOffset;
                break;
            }
                
            case '!':
            {
                // must be the last character, and no offsets
                if ( ((int)iss.peek()) != -1 || HasSpatialTemporalOffset() || HasCharacterOffset() )
                    break;
                
                flags |= Indirector;
                break;
            }
                
            default:
                break;
        }
    }
}
bool CLevelDBWrapper::WriteBatch(CLevelDBBatch& batch, bool fSync) throw(leveldb_error)
{
    leveldb::Status status = pdb->Write(fSync ? syncoptions : writeoptions, &batch.batch);
    HandleError(status);
    return true;
}
Beispiel #24
0
void 
get_cert_time_left(
	char				*realm,
	CTimeSpan			*ptimeLeft
)
{
	HCERTSTORE			hStoreHandle		= NULL;
	PCCERT_CONTEXT		pCertContext		= NULL;      
	PCCERT_CONTEXT		prev_pCertContext	= NULL;      
	DWORD				dwCertEncodingType	= X509_ASN_ENCODING | PKCS_7_ASN_ENCODING;
	DWORD				dwAddDisposition	= CERT_STORE_ADD_REPLACE_EXISTING;
	DWORD				dwFindFlags			= 0;
# define				OID_KCA_AUTHREALM	"1.3.6.1.4.1.250.42.1"
	DWORD				dwFindType			= CERT_FIND_ANY;
	CERT_INFO			*pCertInfo			= NULL;
	PCERT_EXTENSION		pCertExt			= NULL;
	CRYPT_OBJID_BLOB	*p					= NULL;
	int					i					= 0;
	char				tmpRealm[250]		= { 0 };
	CTime				startTime			= 0;
	CTime				endTime				= 0;



	memset(ptimeLeft, 0, sizeof(*ptimeLeft));

	if (!realm || !strlen(realm))
		return;

	//--------------------------------------------------------------------
	// Open a store as the source of the certificates to be deleted and added

	if(!(hStoreHandle = CertOpenSystemStore(
			0,
			MY_STORE)))
	{
		HandleError("get_cert_time_left: Strange.  Unable to access your place in the Registry for certificates");
		goto EXIT_RTN;
	}


	// Find first MY store cert issued by our Certificate Authority

	while ((pCertContext = CertFindCertificateInStore(
						hStoreHandle,					// in
						dwCertEncodingType,				// in
						dwFindFlags,					// in
						dwFindType,						// in
						NULL,							// in
						prev_pCertContext				// in
						)))
	{
		if (pCertInfo = pCertContext->pCertInfo)
			for (i = pCertInfo->cExtension; i; i--)
			{
				pCertExt = &pCertInfo->rgExtension[i-1];
				if (!strcmp(pCertExt->pszObjId, OID_KCA_AUTHREALM))
				{
					log_printf("get_cert_time_left: Found KCA_AUTHREALM Extension\n");

					p = &pCertExt->Value;
					memcpy(tmpRealm, &p->pbData[2], p->cbData-2);
					tmpRealm[p->cbData-2] ='\0';
					log_printf("get_cert_time_left:    value is: '%s'\n", tmpRealm);

					/* only match if realm of current TGT matches AuthRealm of this cert */
					if (realm && !strcmp(realm, tmpRealm))
					{
						// It matches, determine remaining certificate's remaining minutes
						startTime	= CTime::GetCurrentTime();
						endTime		= pCertContext->pCertInfo->NotAfter;
						*ptimeLeft	= endTime - startTime;

						goto EXIT_RTN;
					}
				}
			}

		prev_pCertContext = pCertContext;
	}

EXIT_RTN:
	if ((prev_pCertContext != pCertContext) && pCertContext)
	{
		CertFreeCertificateContext(pCertContext);
		pCertContext = NULL;
	}

	if (pCertContext)
		CertFreeCertificateContext(pCertContext);

	if(hStoreHandle &&!CertCloseStore(
							hStoreHandle,
#ifdef DEBUG
							CERT_CLOSE_STORE_CHECK_FLAG
#else // !DEBUG
							CERT_CLOSE_STORE_FORCE_FLAG
#endif // ! DEBUG
			))
	{
		log_printf("get_cert_time_left: The store was closed, but certificates still in use.\n");
	}
} // get_cert_time_left
NS_IMETHODIMP
nsExpatDriver::ConsumeToken(nsScanner& aScanner, PRBool& aFlushTokens)
{
  // We keep the scanner pointing to the position where Expat will start
  // parsing.
  nsScannerIterator currentExpatPosition;
  aScanner.CurrentPosition(currentExpatPosition);

  // This is the start of the first buffer that we need to pass to Expat.
  nsScannerIterator start = currentExpatPosition;
  start.advance(mExpatBuffered);

  // This is the end of the last buffer (at this point, more data could come in
  // later).
  nsScannerIterator end;
  aScanner.EndReading(end);

  PR_LOG(gExpatDriverLog, PR_LOG_DEBUG,
         ("Remaining in expat's buffer: %i, remaining in scanner: %i.",
          mExpatBuffered, Distance(start, end)));

  // We want to call Expat if we have more buffers, or if we know there won't
  // be more buffers (and so we want to flush the remaining data), or if we're
  // currently blocked and there's data in Expat's buffer.
  while (start != end || (mIsFinalChunk && !mMadeFinalCallToExpat) ||
         (BlockedOrInterrupted() && mExpatBuffered > 0)) {
    PRBool noMoreBuffers = start == end && mIsFinalChunk;
    PRBool blocked = BlockedOrInterrupted();

    const PRUnichar *buffer;
    PRUint32 length;
    if (blocked || noMoreBuffers) {
      // If we're blocked we just resume Expat so we don't need a buffer, if
      // there aren't any more buffers we pass a null buffer to Expat.
      buffer = nsnull;
      length = 0;

#if defined(PR_LOGGING) || defined (DEBUG)
      if (blocked) {
        PR_LOG(gExpatDriverLog, PR_LOG_DEBUG,
               ("Resuming Expat, will parse data remaining in Expat's "
                "buffer.\nContent of Expat's buffer:\n-----\n%s\n-----\n",
                NS_ConvertUTF16toUTF8(currentExpatPosition.get(),
                                      mExpatBuffered).get()));
      }
      else {
        NS_ASSERTION(mExpatBuffered == Distance(currentExpatPosition, end),
                     "Didn't pass all the data to Expat?");
        PR_LOG(gExpatDriverLog, PR_LOG_DEBUG,
               ("Last call to Expat, will parse data remaining in Expat's "
                "buffer.\nContent of Expat's buffer:\n-----\n%s\n-----\n",
                NS_ConvertUTF16toUTF8(currentExpatPosition.get(),
                                      mExpatBuffered).get()));
      }
#endif
    }
    else {
      buffer = start.get();
      length = PRUint32(start.size_forward());

      PR_LOG(gExpatDriverLog, PR_LOG_DEBUG,
             ("Calling Expat, will parse data remaining in Expat's buffer and "
              "new data.\nContent of Expat's buffer:\n-----\n%s\n-----\nNew "
              "data:\n-----\n%s\n-----\n",
              NS_ConvertUTF16toUTF8(currentExpatPosition.get(),
                                    mExpatBuffered).get(),
              NS_ConvertUTF16toUTF8(start.get(), length).get()));
    }

    PRUint32 consumed;
    ParseBuffer(buffer, length, noMoreBuffers, &consumed);
    if (consumed > 0) {
      nsScannerIterator oldExpatPosition = currentExpatPosition;
      currentExpatPosition.advance(consumed);

      // We consumed some data, we want to store the last line of data that
      // was consumed in case we run into an error (to show the line in which
      // the error occurred).

      // The length of the last line that Expat has parsed.
      XML_Size lastLineLength = XML_GetCurrentColumnNumber(mExpatParser);

      if (lastLineLength <= consumed) {
        // The length of the last line was less than what expat consumed, so
        // there was at least one line break in the consumed data. Store the
        // last line until the point where we stopped parsing.
        nsScannerIterator startLastLine = currentExpatPosition;
        startLastLine.advance(-((ptrdiff_t)lastLineLength));
        CopyUnicodeTo(startLastLine, currentExpatPosition, mLastLine);
      }
      else {
        // There was no line break in the consumed data, append the consumed
        // data.
        AppendUnicodeTo(oldExpatPosition, currentExpatPosition, mLastLine);
      }
    }

    mExpatBuffered += length - consumed;

    if (BlockedOrInterrupted()) {
      PR_LOG(gExpatDriverLog, PR_LOG_DEBUG,
             ("Blocked or interrupted parser (probably for loading linked "
              "stylesheets or scripts)."));

      aScanner.SetPosition(currentExpatPosition, PR_TRUE);
      aScanner.Mark();

      return mInternalState;
    }

    if (noMoreBuffers && mExpatBuffered == 0) {
      mMadeFinalCallToExpat = PR_TRUE;
    }

    if (NS_FAILED(mInternalState)) {
      if (XML_GetErrorCode(mExpatParser) != XML_ERROR_NONE) {
        NS_ASSERTION(mInternalState == NS_ERROR_HTMLPARSER_STOPPARSING,
                     "Unexpected error");

        // Look for the next newline after the last one we consumed
        nsScannerIterator lastLine = currentExpatPosition;
        while (lastLine != end) {
          length = PRUint32(lastLine.size_forward());
          PRUint32 endOffset = 0;
          const PRUnichar *buffer = lastLine.get();
          while (endOffset < length && buffer[endOffset] != '\n' &&
                 buffer[endOffset] != '\r') {
            ++endOffset;
          }
          mLastLine.Append(Substring(buffer, buffer + endOffset));
          if (endOffset < length) {
            // We found a newline.
            break;
          }

          lastLine.advance(length);
        }

        HandleError();
      }

      return mInternalState;
    }

    // Either we have more buffers, or we were blocked (and we'll flush in the
    // next iteration), or we should have emptied Expat's buffer.
    NS_ASSERTION(!noMoreBuffers || blocked ||
                 (mExpatBuffered == 0 && currentExpatPosition == end),
                 "Unreachable data left in Expat's buffer");

    start.advance(length);

    // It's possible for start to have passed end if we received more data
    // (e.g. if we spun the event loop in an inline script). Reload end now
    // to compensate.
    aScanner.EndReading(end);
  }

  aScanner.SetPosition(currentExpatPosition, PR_TRUE);
  aScanner.Mark();

  PR_LOG(gExpatDriverLog, PR_LOG_DEBUG,
         ("Remaining in expat's buffer: %i, remaining in scanner: %i.",
          mExpatBuffered, Distance(currentExpatPosition, end)));

  return NS_SUCCEEDED(mInternalState) ? kEOF : NS_OK;
}
Beispiel #26
0
PyObject *Connection_query(Connection *self, PyObject *args)
{
  void *ret;
  PyObject *inQuery = NULL;
  PyObject *query = NULL;
  PyObject *iterable = NULL;
  PyObject *escapedQuery = NULL;

  if (!UMConnection_IsConnected(self->conn))
  {
    return PyErr_Format(PyExc_RuntimeError, "Not connected");
  }

  if (!PyArg_ParseTuple (args, "O|O", &inQuery, &iterable))
  {
    return NULL;
  }

  if (iterable)
  {
    PyObject *iterator = PyObject_GetIter(iterable);

    if (iterator == NULL)
    {
      PyErr_Clear();
      return PyErr_Format(PyExc_TypeError, "Expected iterable");
    }

    Py_DECREF(iterator);
  }

  if (!PyString_Check(inQuery))
  {
    if (!PyUnicode_Check(inQuery))
    {
      PRINTMARK();
      return PyErr_Format(PyExc_TypeError, "Query argument must be either String or Unicode");
    }

    query = self->PFN_PyUnicode_Encode(PyUnicode_AS_UNICODE(inQuery), PyUnicode_GET_SIZE(inQuery), NULL);

    if (query == NULL)
    {
      if (!PyErr_Occurred())
      {
        PyErr_SetObject(PyExc_ValueError, query);
        return NULL;
      }

      return NULL;
    }
  }
  else
  {
    query = inQuery;
    Py_INCREF(query);
  }

  if (iterable)
  {
    PRINTMARK();
    escapedQuery = EscapeQueryArguments(self, query, iterable);
    Py_DECREF(query);

    if (escapedQuery == NULL)
    {
      if (!PyErr_Occurred())
      {
        return PyErr_Format(PyExc_RuntimeError, "Exception not set in EscapeQueryArguments chain");
      }

      return NULL;
    }

  }
  else
  {
    escapedQuery = query;
  }

  ret =  UMConnection_Query(self->conn, PyString_AS_STRING(escapedQuery), PyString_GET_SIZE(escapedQuery));

  Py_DECREF(escapedQuery);

  PRINTMARK();
  if (ret == NULL)
  {
    return HandleError(self, "query");
  }

  PRINTMARK();
  return (PyObject *) ret;
}
Beispiel #27
0
void ComputeParams(sParams* PB, item* memList, int32 value, int32 nbVal ) {
	
	static 	int32 	startAddress = 0;
	static int32 	shift = 0;
	int32 			size;
	int32 			size1;
	int32 			size2;
	bool 			isRead;
	bool 			isSeq;
	
	
	printf("Generates %d.%d with param %d\n", PB->microBenchID, PB->expID,  value);
	
	if (strcasecmp(PB->base, "SR") == 0) {
		PB->ignoreIO = PB->ignoreIOSR;
		PB->IOCount = PB->IOCountSR;
		isSeq = TRUE;
		isRead = TRUE;
	}
	if (strcasecmp(PB->base, "SW") == 0) {
		PB->ignoreIO = PB->ignoreIORR;
		PB->IOCount = PB->IOCountRR;
		isSeq = TRUE;
		isRead = FALSE;
	}
	if (strcasecmp(PB->base, "RR") == 0) {
		PB->ignoreIO = PB->ignoreIOSW;
		PB->IOCount = PB->IOCountSW;
		isSeq = FALSE;
		isRead = TRUE;
	}
	if (strcasecmp(PB->base, "RW") == 0) {
		PB->ignoreIO = PB->ignoreIORW;
		PB->IOCount = PB->IOCountRW;
		isSeq = FALSE;
		isRead = FALSE;
	}
	
	PB->targetSize = PB->deviceSize; // Default value for target size
	if (PB->microBenchID == GRA) PB->IOSize = value;
	if (PB->microBenchID == ALI) PB->IOShift = value;
	if (PB->microBenchID == LOC) PB->targetSize = value * PB->IOSize ;
	if (PB->microBenchID == PAT) PB->nbPartition = value;
	if (PB->microBenchID == ORD) PB->order = value;
	if (PB->microBenchID == PAR) PB->parDeg = value;
	if (PB->microBenchID == MIX) PB->ratio = value;
	if (PB->microBenchID == PIO) PB->pauseIO = value;
	if (PB->microBenchID == PBU) PB->burstIO = value;

	// Number of sectors potentially touched by the experiment 
	size = PB->IOSize * PB->IOCount;
	if (PB->IOShift != 0) size += PB->IOSize; 
		
	if (PB->microBenchID == LOC) size = PB->targetSize;
	if (PB->microBenchID == ORD) size = PB->IOSize * abs(PB->order)* PB->IOCount;
	
	// 1-GRANULARITY , 2-ALIGNMENT, 8-PAUSE, 9-BURST
	if ((PB->microBenchID == GRA) || (PB->microBenchID == ALI)|| 
		(PB->microBenchID == PIO)|| (PB->microBenchID == PBU)) {
		
		if (isSeq == FALSE) 
			PB->targetOffset = 0;
		else if (isRead == TRUE) {
			PB->targetOffset = rg.IRandom(0,(int32)((PB->targetSize - size)/BLOCK))*BLOCK;
			PB->targetSize = size;
		}
		else {
			PB->targetOffset = MemSearch(memList, size);
			PB->targetSize = size;
		}
	}
	// 3-LOCALITY
	else if (PB->microBenchID == LOC) {
		if ((isRead == TRUE) || (value > 1024)) 
			PB->targetOffset = rg.IRandom(0,(int32)((PB->deviceSize - size)/BLOCK))*BLOCK;
		else {
			PB->targetOffset = MemSearch(memList, size);
			//printf("==>%d  %d\n",size, PB->targetOffset );
		}
	}
	// 07-MIX 
	else if (PB->microBenchID == MIX) {
		int32 I1, I2, C1, C2;
		
		I1 = PB->ignoreIO;
		C1 = PB->IOCount;
		if (strcasecmp(PB->base2, "SR") == 0) {
			I2 = PB->ignoreIOSR;
			C2 = PB->IOCountSR;
		}
		
		if (strcasecmp(PB->base2, "SW") == 0) {
			I2 = PB->ignoreIOSW;
			C2 = PB->IOCountSW;
		}
				
		if (strcasecmp(PB->base2, "RR") == 0) {
			I2 = PB->ignoreIORR;
			C2 = PB->IOCountRR;
		}

		if (strcasecmp(PB->base2, "RW") == 0) {
			I2 = PB->ignoreIORW;
			C2 = PB->IOCountRW;
		}

		if (PB->ratio < 0) {
			PB->ignoreIO = max(I1 + (I1-1)*(-PB->ratio) + 1, I2 * (-PB->ratio + 1)/(-PB->ratio) + 1);
			PB->IOCount = max(C1-I1, C2-I2) + PB->ignoreIO;
			size1 = PB->IOSize * (1+ (int32)(PB->IOCount/(-PB->ratio + 1)));
			size2 = PB->IOSize * (1+ (int32)((PB->IOCount/(-PB->ratio + 1)) * (-PB->ratio)));
		}
		else if (PB->ratio > 0) {
			PB->ignoreIO = max(I2 + (I2-1) * PB->ratio + 1, (I1 * (PB->ratio + 1)/PB->ratio) + 1);
			PB->IOCount = max(C1-I1, C2-I2) + PB->ignoreIO;
			size1 = PB->IOSize * (1+ (int32)(PB->IOCount/(PB->ratio + 1)));
			size2 = PB->IOSize * (1+ (int32)((PB->IOCount/(PB->ratio + 1)) * (PB->ratio)));
		}
		else {
			PB->ignoreIO = I2;
			PB->IOCount = C2;
			size1 = 0;
			size2 = PB->IOSize * PB->IOCount;
		}
		
		if (((strcasecmp(PB->base, "SR") == 0) &&  (strcasecmp(PB->base2, "RR") == 0)) ||
			((strcasecmp(PB->base, "SR") == 0) &&  (strcasecmp(PB->base2, "RW") == 0))) {
			PB->targetSize = size1;
			PB->targetOffset = rg.IRandom(0,(int32)((PB->deviceSize - size1)/BLOCK))*BLOCK;
			PB->targetOffset2 = 0;
			PB->targetSize2 = PB->deviceSize;
		}
		if ((strcasecmp(PB->base, "RR") == 0) &&  (strcasecmp(PB->base2, "RW") == 0)) {
			PB->targetSize = PB->deviceSize;
			PB->targetOffset = 0;
			PB->targetOffset2 = 0;
			PB->targetSize2 = PB->deviceSize;
		}
		if ((strcasecmp(PB->base, "RR") == 0) &&  (strcasecmp(PB->base2, "SW") == 0)) {
			PB->targetOffset2 = MemSearch(memList, size2);
			PB->targetSize2 = size2;
			PB->targetOffset = MemMinAddress(memList);
			PB->targetSize = PB->deviceSize - PB->targetOffset;
		}
		if ((strcasecmp(PB->base, "SW") == 0) &&  (strcasecmp(PB->base2, "RW") == 0)) {
			PB->targetOffset = MemSearch(memList, size1);
			PB->targetSize = size1;
			PB->targetOffset2 = MemMinAddress(memList);
			PB->targetSize2 = PB->deviceSize - PB->targetOffset2;
		}
		if ((strcasecmp(PB->base, "SR") == 0) &&  (strcasecmp(PB->base2, "SW") == 0)) {
			PB->targetOffset2 = MemSearch(memList, size2);
			PB->targetSize2 = size2;
			PB->targetOffset = rg.IRandom((int32)((PB->deviceSize - MemMinAddress(memList))/2)/BLOCK,(int32)((PB->deviceSize - size1)/BLOCK))*BLOCK;
			PB->targetSize = size1;
		}
	}
	// 6-PARALLELISM
	else if (PB->microBenchID == PAR) {
		PB->targetSize = ((int32)((PB->deviceSize / PB->parDeg)/BLOCK))*BLOCK;
		if (isSeq == FALSE) 
			PB->targetOffset =  PB->processID * PB->targetSize;
		else if (isRead == TRUE) {
			PB->targetOffset =  rg.IRandom((PB->processID * PB->targetSize)/BLOCK, 
									 		 ((PB->processID + 1) * PB->targetSize - size)/BLOCK) * BLOCK;
			PB->targetSize = size;
		}
		else { // SEQUENTIAL WRITE..... // CAUTION : PARALLEL EXPERIMENT MUST BE AFTER PARTITIONING
			PB->targetSize = (PB->deviceSize - startAddress) / PB->parDeg;
			if (PB->targetSize < size) HandleError("ComputeParam", "device too small", 0, ERR_ABORT);
			PB->targetOffset =  MemAllocNearestAfterA(memList, (PB->processID) * PB->targetSize + startAddress, size);
			PB->targetSize = size;
		}
	}
	// 4-PARTITIONING
	else if (PB->microBenchID == PAT) {
		if ((isRead == TRUE) || (PB->nbPartition > 16)) {
			PB->targetOffset =  0;
			PB->targetSize = ((int32) (PB->deviceSize/(MAX_PARTITIONS * BLOCK))) * MAX_PARTITIONS * BLOCK;
		}
		else { // SEQUENTIAL WRITE..... // CAUTION : PARTITIONNING EXPERIMENT MUST BE THE FIRST ...
			if (startAddress == 0)
				startAddress = MemMinAddress(memList);
			if ((size % (16*BLOCK)) != 0)
				size = ((int32) (size / (16*BLOCK)) + 1 ) * (16 * BLOCK);
			PB->targetSize = PB->deviceSize - startAddress - size * nbVal * PB->nbRun;
			PB->targetSize = (int32) (PB->targetSize/ (16 * BLOCK)) * (16 * BLOCK); 
			if (PB->targetSize < size) HandleError("ComputeParam", "device too small", 0, ERR_ABORT);
			PB->targetOffset = startAddress + shift;
			for (int32 k = 0; k < PB->nbPartition; ++k) {
				long temp;
				temp = MemAlloc(memList, PB->targetOffset + k * PB->targetSize/PB->nbPartition,  
						PB->targetOffset + k * PB->targetSize/PB->nbPartition + size/PB->nbPartition);
			}	
			shift = shift + size/PB->nbPartition;
		}
		
	}
	// 5-ORDER
	else if (PB->microBenchID == ORD) {
		size = PB->IOSize * PB->IOCount * PB->order;
		if (size == 0)  size = BLOCK;
		PB->targetSize = abs(size);
		if (isRead == TRUE) {
			PB->targetOffset =  rg.IRandom(0,(int32)((PB->deviceSize - PB->targetSize)/BLOCK))*BLOCK;
			if (size < 0)
				PB->targetOffset =  PB->deviceSize - PB->targetOffset;
		}
		else {
			PB->targetOffset =  MemSearch(memList, abs(size));
			if (PB->targetOffset == INT32_MAX) {
				PB->targetOffset = rg.IRandom(0,(int32)((PB->deviceSize - abs(size))/BLOCK))*BLOCK;
				PB->warning = DEVICE_TOO_SMALL;
				OutputString(OUT_LOG, "DEVICE TOO SMALL \n");
			}	
			if (size <0)
				PB->targetOffset =  PB->targetOffset - size;
		}
	}

	if (PB->targetOffset == INT32_MAX) HandleError("ComputeParam", "device too small", 0, ERR_ABORT);
		
	if ((PB->order >= 0) && (PB->targetOffset + PB->targetSize > PB->deviceSize)) {
		char st[MAX_STR];
		
		sprintf(st, "Adjusting TargetSize (TO = %d, TS = %d DS = %d\n", PB->targetOffset, PB->targetSize, PB->deviceSize);
		PB->targetSize = PB->deviceSize - PB->targetOffset;
		PB->warning = PB->warning | TEST_EXCEED_DEVICE;
		OutputString(OUT_LOG, st);
	}
	if ((PB->order < 0) && (PB->targetOffset - PB->targetSize < 0)) {
		char st[MAX_STR];

		sprintf(st, "Adjusting TargetSize Reverse Order (TO = %d, TS = %d DS = %d\n", PB->targetOffset, PB->targetSize, PB->deviceSize);		PB->targetSize = PB->targetOffset;
		PB->warning = PB->warning | TEST_EXCEED_DEVICE;
		OutputString(OUT_LOG, st);
	}
}
void ScoreLoopThread::LoadLeaderboardCompletionCallback(void *userData, SC_Error_t completionStatus) {
	/* Get the application from userData argument */
	AppData_t *app = (AppData_t *) userData;

	/* Check completion status */
	if (completionStatus != SC_OK) {
		SC_ScoresController_Release(app->scoresController); /* Cleanup Controller */
		HandleError(app, completionStatus);
		return;
	}

	/* Just log the scores here for demonstration purposes */
	SC_ScoreList_h scoreList = SC_ScoresController_GetScores(app->scoresController);
	if (scoreList == NULL) {
		SC_ScoresController_Release(app->scoresController); /* Cleanup Controller */
		HandleError(app, SC_NOT_FOUND);
		return;
	}
	qDebug() << "Done loading Leaderboard";

	/* Get the score formatter here - remember that you need to add a
	 * scoreloop/SLScoreFormatter.strings file to your asset files in order to retrieve a formatter.
	 */
	SC_ScoreFormatter_h scoreFormatter = SC_Client_GetScoreFormatter(app->client);
	if (!scoreFormatter) {
		SC_ScoresController_Release(app->scoresController); /* Cleanup Controller */
		HandleError(app, SC_NOT_FOUND);
		return;
	}

	QVariantList leaderboardData;

	unsigned int i, numScores = SC_ScoreList_GetCount(scoreList);
	for (i = 0; i < numScores; ++i) {
		SC_Score_h score = SC_ScoreList_GetAt(scoreList, i);
		SC_User_h user = SC_Score_GetUser(score);
		SC_String_h login = user ? SC_User_GetLogin(user) : NULL;
		SC_String_h formattedScore;

		/* Format the score - we take ownership of string */
		int rc = SC_ScoreFormatter_FormatScore(scoreFormatter, score, SC_SCORE_FORMAT_DEFAULT, &formattedScore);
		if (rc != SC_OK) {
			HandleError(app, rc);
			return;
		}
		qDebug() << "  Rank: " << SC_Score_GetRank(score) << ", Result: " << SC_String_GetData(formattedScore) << ", User: "******"<unknown>");

		QVariantMap scoreData;
		scoreData["rank"] = SC_Score_GetRank(score);
		scoreData["formattedScore"] = SC_String_GetData(formattedScore);
		scoreData["username"] = login ? SC_String_GetData(login) : "<unknown>";

		leaderboardData.append(scoreData);

		/* Release the string */
		SC_String_Release(formattedScore);
	}

	emit(instance()->LoadLeaderboardCompleted(leaderboardData));

	/* Cleanup Controller */
	SC_ScoresController_Release(app->scoresController);

	/* Set an Award as achieved here just for demonstration purposes */
	//AchieveAward(app, SCORELOOP_AN_AWARD_ID);
}
Beispiel #29
0
void GenBench(sParams* PBBench) {

	boolean 	finished = FALSE;
	int32		prevExp = 0;
	int32		currExp;
	int32 		numExp;
	FILE*		fp = NULL;	// file pointer
	FILE*		fp2 = NULL;	// file pointer
	char 		str[MAX_STR];
	int32		tabVal[MAX_VARYING_VAL];
	sParams		PBExp;
	int32		nbVal;
	item* 		memList;
	bool		tabSel[MAXBENCH*MAXMODE];
	int32		nbExp = 0;
	int32		key = 0;
	
	parseSel(PBBench, tabSel);
	// Allocate data structure for computing target offset
	memList = InitMemList((int32)(PBBench->deviceSize));
	fp2 = fopen(PBBench->outName, "w");
	if (fp2 == NULL) HandleError("GenBench", "Could not open output file", GetLastError(), ERR_ABORT);
	
	while (finished == FALSE) {
	// find the next experiment - it is the smallest numExp, greater than prevExp 
		if ((fp  = fopen(PBBench->expPlan, "r")) == NULL ) 
			HandleError("GenBench", "Cannot open experimentation plan file", GetLastError(), ERR_ABORT);
		currExp = INT32_MAX;
		while (fgets(str, MAX_STR,fp) != NULL) {
			numExp = atoi(str);
			if ((numExp > prevExp) && (numExp < currExp)) {
				currExp = numExp;
			}
		}
		if ((currExp > prevExp) && (currExp != INT32_MAX)) {
			printf("===================  Order Number %d\n", currExp);
			
			//New param structure
			InitParams(&PBExp);
			PBExp.deviceNum = PBBench->deviceNum;
			PBExp.IOSize = PBBench->IOSize;
			PBExp.IOCount = PBBench->IOCount;
			PBExp.IOCountSR = PBBench->IOCountSR;
			PBExp.IOCountRR = PBBench->IOCountRR;
			PBExp.IOCountSW = PBBench->IOCountSW;
			PBExp.IOCountRW = PBBench->IOCountRW;
			PBExp.ignoreIO = PBBench->ignoreIO;
			PBExp.ignoreIOSR = PBBench->ignoreIOSR;
			PBExp.ignoreIORR = PBBench->ignoreIORR;
			PBExp.ignoreIOSW = PBBench->ignoreIOSW;
			PBExp.ignoreIORW = PBBench->ignoreIORW;
			PBExp.collectErase = PBBench->collectErase;
			PBExp.pauseExp = PBBench->pauseExp;
			PBExp.fake = PBBench->fake;
			PBExp.bufferType = PBBench->bufferType;
			PBExp.deviceSize = PBBench->deviceSize;	
			PBExp.burstIO = PBBench->burstIO;
			PBExp.nbRun = PBBench->nbRun;  
			
			// parse the experiment
			nbVal = parseExp(fp, currExp, &PBExp, tabVal);
			if (tabSel[(PBExp.microBenchID - 1) * MAXMODE + PBExp.expID - 1] == TRUE) {
				for (int32 exp = 0; exp < nbVal; ++exp) {
					// Compute the different parameters
					if (PBExp.microBenchID == PAR)  {
						for (PBExp.runID = 0; PBExp.runID < PBExp.nbRun; (PBExp.runID)++) {
							PBExp.parDeg = tabVal[exp];
							for (int32 pID = 0; pID < PBExp.parDeg; ++pID) {
								PBExp.processID = PBExp.parDeg - pID - 1;
								PBExp.key = key++;
								ComputeParams(&PBExp, memList,PBExp.parDeg, nbVal );
								GenExp(fp2, &PBExp);
								nbExp++;
								PBExp.IOSize = PBBench->IOSize;
								PBExp.IOCount = PBBench->IOCount;
								PBExp.ignoreIO = PBBench->ignoreIO;
								
							}
						}
					}
					else {
						for (PBExp.runID = 0; PBExp.runID < PBExp.nbRun; (PBExp.runID)++) {
							PBExp.key = key++;
							ComputeParams(&PBExp, memList, tabVal[exp], nbVal);
							GenExp(fp2, &PBExp);
							nbExp ++;
							PBExp.IOSize = PBBench->IOSize;
							PBExp.IOCount = PBBench->IOCount;
							PBExp.ignoreIO = PBBench->ignoreIO;
						}
					}
				}
			}
			else
				printf("===================  Not Selected\n");
			fprintf(fp2, "\n");		
		}
		else finished = TRUE;
		prevExp = currExp;
		if (fp) fclose(fp);
	}
	fclose(fp2);							// close the output file if we opened it
	while (memList) {
		item *tmp = memList->next;
		free(memList);
		memList = tmp;
	}
	sprintf(str, "%d Experiments have been generated\n", nbExp);
	OutputString(OUT_LOG, str);

}
void ScoreLoopThread::run() {
	qDebug() << "ScoreLoopThread run() started";

	AppData_t app;
	SC_InitData_t initData;
	SC_Error_t rc;
	char versionBuffer[0x100]; /* Thats 256 bytes */

	qDebug() << "Starting Scoreloop Sample...";

	/* Initialize the BPS event system */
	bps_initialize();
	bps_set_verbosity(0); /* Set to 1 or 2 for more output if you like */

	memset(&app, 0, sizeof(AppData_t));

	/* Initialize the Scoreloop platform dependent SC_InitData_t structure to default values. */
	SC_InitData_Init(&initData);

	/* What version of the Scoreloop library do we use? */
	if (SC_GetVersionInfo(&initData, versionBuffer, sizeof(versionBuffer))) {
		qDebug() << "Version-Info: " << versionBuffer;
	}

	/* Now, create the Scoreloop Client with the initialized SC_InitData_t structure
	 * as well as the game-id and game-secret as found on the developer portal.
	 */
	rc = SC_Client_New(&app.client, &initData, SCORELOOP_GAME_ID, SCORELOOP_GAME_SECRET, SCORELOOP_GAME_VERSION, SCORELOOP_GAME_CURRENCY, SCORELOOP_GAME_LANGUAGE);
	if (rc != SC_OK) {
		HandleError(&app, rc);
	} else {
		//InformUser(&app, "Note", "Scoreloop Sample started...");

		/* Request the user here just for demonstration purposes */
		RequestUser(&app);
	}

	while (!m_quit) {
		/* Get next BPS event */
		bps_event_t *event;
		bps_get_event(&event, -1);

		/* Scoreloop event handling  */
		if (bps_event_get_domain(event) == SC_GetBPSEventDomain(&initData)) {
			SC_HandleBPSEvent(&initData, event);
		}

		else if (bps_event_get_domain(event) == dialog_get_domain()) {
			dialog_destroy(dialog_event_get_dialog_instance(event));
			app.dialog = 0;
		}
		/* Add more BPS event handling here... */

	}

	/* Cleanup the Scoreloop client */
	SC_Client_Release(app.client);

	/* Shutdown BPS */
	bps_shutdown();
	qDebug() << "SensorsThread run() finished.";
}