Beispiel #1
0
// Spike logic is driven by TrgSpikeParams:
// {periEvtSecs, refractSecs, inarow, nS, T}.
// Corresponding states defined above.
//
void TrigSpike::run()
{
    Debug() << "Trigger thread started.";

    setYieldPeriod_ms( 100 );

    initState();

    while( !isStopped() ) {

        double  loopT = getTime();
        bool    inactive;

        // -------
        // Active?
        // -------

        inactive = ISSTATE_Done || !isGateHi();

        if( inactive )
            goto next_loop;

        // -------------
        // If gate start
        // -------------

        // Set gateHiT as place from which to start
        // searching for edge in getEdge().

        if( !imCnt.edgeCt || !niCnt.edgeCt ) {

            usrFlt->reset();

            double  gateT = getGateHiT();

            if( imQ && !imQ->mapTime2Ct( imCnt.edgeCt, gateT ) )
                goto next_loop;

            if( niQ && !niQ->mapTime2Ct( niCnt.edgeCt, gateT ) )
                goto next_loop;
        }

        // --------------
        // Seek next edge
        // --------------

        if( ISSTATE_GetEdge ) {

            if( p.trgSpike.stream == "imec" ) {

                if( !getEdge( imCnt, imQ, niCnt, niQ ) )
                    goto next_loop;
            }
            else {

                if( !getEdge( niCnt, niQ, imCnt, imQ ) )
                    goto next_loop;
            }

            QMetaObject::invokeMethod(
                gw, "blinkTrigger",
                Qt::QueuedConnection );

            // ---------------
            // Start new files
            // ---------------

            imCnt.remCt = -1;
            niCnt.remCt = -1;

            {
                int ig, it;

                if( !newTrig( ig, it, false ) )
                    break;

                setSyncWriteMode();
            }

            SETSTATE_Write();
        }

        // ----------------
        // Handle this edge
        // ----------------

        if( ISSTATE_Write ) {

            if( !writeSome( DstImec, imQ, imCnt )
                || !writeSome( DstNidq, niQ, niCnt ) ) {

                break;
            }

            // -----
            // Done?
            // -----

            if( imCnt.remCt <= 0 && niCnt.remCt <= 0 ) {

                endTrig();

                usrFlt->reset();
                imCnt.edgeCt += imCnt.refracCt;
                niCnt.edgeCt += niCnt.refracCt;

                if( ++nS >= nCycMax )
                    SETSTATE_Done;
                else
                    SETSTATE_GetEdge;
            }
        }

        // ------
        // Status
        // ------

next_loop:
       if( loopT - statusT > 0.25 ) {

            QString sOn, sWr;
            int     ig, it;

            getGT( ig, it );
            statusOnSince( sOn, loopT, ig, it );
            statusWrPerf( sWr );

            Status() << sOn << sWr;

            statusT = loopT;
        }

        // -------------------
        // Moderate fetch rate
        // -------------------

        yield( loopT );
    }

    endRun();

    Debug() << "Trigger thread stopped.";

    emit finished();
}
int main(int argc, char* argv[]) {

    double discountFactor;
    unsigned int maxNbEvaluations;
    char isTerminal = 0;
    char keepingTree = 0;
    int nbTimestep = -1;
    unsigned int branchingFactor = 0;

#ifdef USE_SDL
    char isDisplayed = 1;
    char isFullscreen = 1;
    char verbose = 0;
    char resolution[255] = "640x480";
#else
    char verbose = 1;
#endif

    uniform_instance* instance = NULL;

    state* crtState = NULL;
    state* nextState = NULL;
    double reward = 0.0;
    action* optimalAction = NULL;

    struct arg_dbl* g = arg_dbl1("g", "discountFactor", "<d>", "The discount factor for the problem");
    struct arg_int* n = arg_int1("n", "nbEvaluations", "<n>", "The number of evaluations");
    struct arg_int* s = arg_int0("s", "nbtimestep", "<n>", "The number of timestep");
    struct arg_int* b = arg_int0("b", "branchingFactor", "<n>", "The branching factor of the problem");
    struct arg_lit* k = arg_lit0("k", NULL, "Keep the subtree");
    struct arg_str* i = arg_str0(NULL, "state", "<s>", "The initial state to use");

#ifdef USE_SDL
    struct arg_lit* d = arg_lit0("d", NULL, "Display the viewer");
    struct arg_lit* f = arg_lit0("f", NULL, "Fullscreen");
    struct arg_lit* v = arg_lit0("v", NULL, "Verbose");
    struct arg_str* r = arg_str0(NULL, "resolution", "<s>", "The resolution of the display window");
    void* argtable[11];
    int nbArgs = 10;
#else
    void* argtable[7];
    int nbArgs = 6;
#endif

    struct arg_end* end = arg_end(nbArgs+1);
    int nerrors = 0;

    s->ival[0] = -1;
    b->ival[0] = 0;

    argtable[0] = g; argtable[1] = n; argtable[2] = s; argtable[3] = k; argtable[4] = b; argtable[5] = i;

#ifdef USE_SDL
    argtable[6] = d;
    argtable[7] = f;
    argtable[8] = v;
    argtable[9] = r;
#endif

    argtable[nbArgs] = end;

    if(arg_nullcheck(argtable) != 0) {
        printf("error: insufficient memory\n");
        arg_freetable(argtable, nbArgs+1);
        return EXIT_FAILURE;
    }

    nerrors = arg_parse(argc, argv, argtable);

    if(nerrors > 0) {
        printf("%s:", argv[0]);
        arg_print_syntax(stdout, argtable, "\n");
        arg_print_errors(stdout, end, argv[0]);
        arg_freetable(argtable, nbArgs+1);
        return EXIT_FAILURE;
    }

    discountFactor = g->dval[0];
    maxNbEvaluations = n->ival[0];

    branchingFactor = b->ival[0];

    initGenerativeModelParameters();
    if(branchingFactor)
        K = branchingFactor;
    initGenerativeModel();
    if(i->count)
        crtState = makeState(i->sval[0]);
    else
        crtState = initState();

#if USE_SDL
    isDisplayed = d->count;
    isFullscreen = f->count;
    verbose = v->count;
    if(r->count)
        strcpy(resolution, r->sval[0]);
#endif

    nbTimestep = s->ival[0];
    keepingTree = k->count;

    arg_freetable(argtable, nbArgs+1);

    instance = uniform_initInstance(crtState, discountFactor);

#ifdef USE_SDL
    if(isDisplayed) {
        if(initViewer(resolution, uniform_drawingProcedure, isFullscreen) == -1)
            return EXIT_FAILURE;
        viewer(crtState, NULL, 0.0, instance);
    }
#endif

    do {
        if(keepingTree)
            uniform_keepSubtree(instance);
        else
            uniform_resetInstance(instance, crtState);

        optimalAction = uniform_planning(instance, maxNbEvaluations);

        isTerminal = nextStateReward(crtState, optimalAction, &nextState, &reward);
        freeState(crtState);
        crtState = nextState;

        if(verbose) {
            printState(crtState);
            printAction(optimalAction);
            printf("reward: %f depth: %u\n", reward, uniform_getMaxDepth(instance));
        }

#ifdef USE_SDL
    } while(!isTerminal && (nbTimestep < 0 || --nbTimestep) && !viewer(crtState, optimalAction, reward, instance));
#else
    } while(!isTerminal && (nbTimestep < 0 || --nbTimestep));
Beispiel #3
0
/**
 * Executes Lyra2 based on the G function from Blake2b or BlaMka. This version supports salts and passwords
 * whose combined length is smaller than the size of the memory matrix, (i.e., (nRows x nCols x b) bits,
 * where "b" is the underlying sponge's bitrate). In this implementation, the "params" is composed by all 
 * integer parameters (treated as type "unsigned int") in the order they are provided, plus the value 
 * of nCols, (i.e., params = kLen || pwdlen || saltlen || timeCost || nRows || nCols).
 *
 * @param K The derived key to be output by the algorithm
 * @param kLen Desired key length
 * @param pwd User password
 * @param pwdlen Password length
 * @param salt Salt
 * @param saltlen Salt length
 * @param timeCost Parameter to determine the processing time (T)
 * @param nRows Number or rows of the memory matrix (R)
 * @param nCols Number of columns of the memory matrix (C)
 *
 * @return 0 if the key is generated correctly; -1 if there is an error (usually due to lack of memory for allocation)
 */
int LYRA2_singleThread(void *K, unsigned int kLen, const void *pwd, unsigned int pwdlen, const void *salt, unsigned int saltlen, unsigned int timeCost, unsigned int nRows, unsigned int nCols){
    //============================= Basic variables ============================//
    int64_t gap = 1;            //Modifier to the step, assuming the values 1 or -1
    uint64_t step = 1;          //Visitation step (used during Setup to dictate the sequence in which rows are read)
    uint64_t window = 2;        //Visitation window (used to define which rows can be revisited during Setup)
    uint64_t sqrt = 2;          //Square of window (i.e., square(window)), when a window is a square number;
                                //otherwise, sqrt = 2*square(window/2) 
    
    uint64_t row0 = 3;          //row0: sequentially written during Setup; randomly picked during Wandering
    uint64_t prev0 = 2;         //prev0: stores the previous value of row0
    uint64_t row1 = 1;          //row1: revisited during Setup, and then read [and written]; randomly picked during Wandering
    uint64_t prev1 = 0;         //prev1: stores the previous value of row1

    uint64_t i;                 //auxiliary iteration counter
    //==========================================================================/
    if (nRows < 3)
      return -1;
    if (timeCost < 1)
      return -1;
    //========== Initializing the Memory Matrix and pointers to it =============//
    //Tries to allocate enough space for the whole memory matrix
    i = (uint64_t) ((uint64_t)nRows * (uint64_t)ROW_LEN_BYTES);
    __m128i *wholeMatrix = malloc(i);
    if (wholeMatrix == NULL) {
        return -1;
    }
    //Allocates pointers to each row of the matrix
    __m128i **memMatrix = malloc(nRows * sizeof (uint64_t*));
    if (memMatrix == NULL) {
        return -1;
    }
    //Places the pointers in the correct positions
    __m128i *ptrWord = wholeMatrix;
    for (i = 0; i < nRows; i++) {
        memMatrix[i] = ptrWord;
        ptrWord += ROW_LEN_INT128;
    }
    
    //==========================================================================/

    //============= Padding (password + salt + params) with 10*1 ===============//

    //OBS.:The memory matrix will temporarily hold the password: not for saving memory,
    //but this ensures that the password copied locally will be overwritten as soon as possible

    //First, we clean enough blocks for the password, salt, params and padding
    //Change the ''6'' if different amounts of parameters were passed 
    uint64_t nBlocksInput = ((saltlen + pwdlen + 6 * sizeof (int)) / BLOCK_LEN_BLAKE2_SAFE_BYTES) + 1;
    byte *ptrByte = (byte*) wholeMatrix;
    memset(ptrByte, 0, nBlocksInput * BLOCK_LEN_BLAKE2_SAFE_BYTES);

    //Prepends the password
    memcpy(ptrByte, pwd, pwdlen);
    ptrByte += pwdlen;

    //Concatenates the salt
    memcpy(ptrByte, salt, saltlen);
    ptrByte += saltlen;

    //Concatenates the params: every integer passed as parameter, in the order they are provided by the interface
    memcpy(ptrByte, &kLen, sizeof (int));
    ptrByte += sizeof (int);
    memcpy(ptrByte, &pwdlen, sizeof (int));
    ptrByte += sizeof (int);
    memcpy(ptrByte, &saltlen, sizeof (int));
    ptrByte += sizeof (int);
    memcpy(ptrByte, &timeCost, sizeof (int));
    ptrByte += sizeof (int);
    memcpy(ptrByte, &nRows, sizeof (int));
    ptrByte += sizeof (int);
    memcpy(ptrByte, &nCols, sizeof (int));
    ptrByte += sizeof (int);

    //Now comes the padding
    *ptrByte = 0x80;                                            //first byte of padding: right after the password
    ptrByte = (byte*) wholeMatrix;                              //resets the pointer to the start of the memory matrix
    ptrByte += nBlocksInput * BLOCK_LEN_BLAKE2_SAFE_BYTES - 1;  //sets the pointer to the correct position: end of incomplete block
    *ptrByte ^= 0x01;                                           //last byte of padding: at the end of the last incomplete block
    
    //==========================================================================/

    //============== Initializing the Sponge State =============/
    //Sponge state: 8 __m128i, BLOCK_LEN_INT128 words of them for the bitrate (b) and the remainder for the capacity (c)
    __m128i *state = malloc(8 * sizeof (__m128i));
    if (state == NULL) {
	return -1;
    }
    initState(state);
    
    //==========================================================================/
    
    //============= Absorbing the input data with the sponge ===============//
    
    //Absorbing salt, password and params: this is the only place in which the block length is hard-coded to 512 bits, for compatibility with Blake2b and BlaMka
    ptrWord = wholeMatrix;
    for (i = 0; i < nBlocksInput; i++) {
	absorbBlockBlake2Safe(state, ptrWord);           //absorbs each block of pad(pwd || salt || params)
	ptrWord += BLOCK_LEN_BLAKE2_SAFE_INT128;         //goes to next block of pad(pwd || salt || params)
    }
    
    //================================================================================/
    
    //================================ Setup Phase ==================================//
    //==Initializes a (nRows x nCols) memory matrix, it's cells having b bits each)==//

    //Initializes M[0]
    reducedSqueezeRow0(state, memMatrix[0]); //The locally copied password is most likely overwritten here
    //Initializes M[1]
    reducedDuplexRow1and2(state, memMatrix[0], memMatrix[1]);
    //Initializes M[2]
    reducedDuplexRow1and2(state, memMatrix[1], memMatrix[2]);
    
    //Filling Loop
    for(row0 = 3 ; row0 < nRows; row0++){
	//Performs a reduced-round duplexing operation over "M[row1][col] [+] M[prev0][col] [+] M[prev1][col]", filling M[row0] and updating M[row1]
	//M[row0][N_COLS-1-col] = M[prev0][col] XOR rand;
        //M[row1][col] = M[row1][col] XOR rot(rand)                    rot(): right rotation by 'omega' bits (e.g., 1 or more words)
	reducedDuplexRowFilling(state, memMatrix[row1], memMatrix[prev0], memMatrix[prev1], memMatrix[row0]);

        //Updates the "prev" indices: the rows more recently updated
        prev0 = row0;
        prev1 = row1;
        
        //updates the value of row1: deterministically picked, with a variable step
        row1 = (row1 + step) & (window - 1);
	
	//Checks if all rows in the window where visited.
	if (row1 == 0) {
	    window *= 2;                        //doubles the size of the re-visitation window
	    step = sqrt + gap;                  //changes the step: approximately doubles its value
	    gap = -gap;                         //inverts the modifier to the step 
            if (gap == -1){
                sqrt *= 2;                      //Doubles sqrt every other iteration
            }
	}
    }
    
    //============================ Wandering Phase =============================//
    //=====Iteratively overwrites pseudorandom cells of the memory matrix=======//
    
    //Visitation Loop
    for (i = 0 ; i < timeCost*nRows ; i++) {            
        //Selects a pseudorandom indices row0 and row1
        //------------------------------------------------------------------------------------------
        /*(USE THIS IF nRows IS A POWER OF 2)*/
        //row0 = ((uint64_t)(((__uint128_t *)state)[0])) & (nRows-1);	
        //row1 = ((uint64_t)(((__uint128_t *)state)[1])) & (nRows-1);
        /*(USE THIS FOR THE "GENERIC" CASE)*/
        row0 = ((uint64_t)(((__uint128_t *)state)[0])) % nRows;         //row0 = lsw(rand) mod nRows
        row1 = ((uint64_t)(((__uint128_t *)state)[1])) % nRows;         //row1 = lsw(rot(rand)) mod nRows                

        //Performs a reduced-round duplexing operation over "M[row0][col] [+] M[row1][col] [+] M[prev0][col0] [+] M[prev1][col1]", updating both M[row0] and M[row1]
        //M[row0][col] = M[row0][col] XOR rand; 
        //M[row1][col] = M[row1][col] XOR rot(rand)                     rot(): right rotation by 'omega' bits (e.g., 1 or more words)
        reducedDuplexRowWandering(state, memMatrix[row0], memMatrix[row1], memMatrix[prev0], memMatrix[prev1]);

        //update prev's: they now point to the last rows ever updated
        prev0 = row0;
        prev1 = row1;   
    }
    
    //==========================================================================/

    //============================ Wrap-up Phase ===============================//
    //========================= Output computation =============================//
    //Absorbs one last block of the memory matrix with the full-round sponge
    absorbColumn(state, memMatrix[row0]);
    
    //Squeezes the key with the full-round sponge
    squeeze(state, K, kLen);
    //==========================================================================/

    //========================= Freeing the memory =============================//
    free(memMatrix);
    free(wholeMatrix);

    //Wiping out the sponge's internal state before freeing it
    memset(state, 0, 8 * sizeof (__m128i));
    free(state);
    //==========================================================================/


    return 0;
}
void RPCRequestHandler::handleRequest(Transport *transport) {
  if (needReset()) {
    cleanupState();
    initState();
  }
  ++m_requestsSinceReset;

  ExecutionProfiler ep(ThreadInfo::RuntimeFunctions);

  Logger::OnNewRequest();
  HttpRequestHandler::GetAccessLog().onNewRequest();
  m_context->setTransport(transport);
  transport->enableCompression();

  ServerStatsHelper ssh("all", ServerStatsHelper::TRACK_MEMORY);
  Logger::Verbose("receiving %s", transport->getCommand().c_str());

  // will clear all extra logging when this function goes out of scope
  StackTraceNoHeap::ExtraLoggingClearer clearer;
  StackTraceNoHeap::AddExtraLogging("RPC-URL", transport->getUrl());

  // authentication
  const set<string> &passwords = m_serverInfo->getPasswords();
  if (!passwords.empty()) {
    set<string>::const_iterator iter =
      passwords.find(transport->getParam("auth"));
    if (iter == passwords.end()) {
      transport->sendString("Unauthorized", 401);
      transport->onSendEnd();
      HttpRequestHandler::GetAccessLog().log(transport, nullptr);
      /*
       * HPHP logs may need to access data in ServerStats, so we have to
       * clear the hashtable after writing the log entry.
       */
      ServerStats::Reset();
      return;
    }
  } else {
    const string &password = m_serverInfo->getPassword();
    if (!password.empty() && password != transport->getParam("auth")) {
      transport->sendString("Unauthorized", 401);
      transport->onSendEnd();
      HttpRequestHandler::GetAccessLog().log(transport, nullptr);
      /*
       * HPHP logs may need to access data in ServerStats, so we have to
       * clear the hashtable after writing the log entry.
       */
      ServerStats::Reset();
      return;
    }
  }

  // return encoding type
  ReturnEncodeType returnEncodeType = m_returnEncodeType;
  if (transport->getParam("return") == "serialize") {
    returnEncodeType = ReturnEncodeType::Serialize;
  }

  // resolve virtual host
  const VirtualHost *vhost = HttpProtocol::GetVirtualHost(transport);
  assert(vhost);
  if (vhost->disabled()) {
    transport->sendString("Virtual host disabled.", 404);
    transport->onSendEnd();
    HttpRequestHandler::GetAccessLog().log(transport, vhost);
    return;
  }
  ThreadInfo::s_threadInfo->m_reqInjectionData.
    setTimeout(vhost->getRequestTimeoutSeconds(getDefaultTimeout()));

  // resolve source root
  string host = transport->getHeader("Host");
  SourceRootInfo sourceRootInfo(host.c_str());

  // set thread type
  switch (m_serverInfo->getType()) {
  case SatelliteServer::Type::KindOfRPCServer:
    transport->setThreadType(Transport::ThreadType::RpcThread);
    break;
  case SatelliteServer::Type::KindOfXboxServer:
    transport->setThreadType(Transport::ThreadType::XboxThread);
    break;
  default:
    break;
  }

  // record request for debugging purpose
  std::string tmpfile = HttpProtocol::RecordRequest(transport);
  bool ret = executePHPFunction(transport, sourceRootInfo, returnEncodeType);
  HttpRequestHandler::GetAccessLog().log(transport, vhost);
  /*
   * HPHP logs may need to access data in ServerStats, so we have to
   * clear the hashtable after writing the log entry.
   */
  ServerStats::Reset();
  HttpProtocol::ClearRecord(ret, tmpfile);
}
Beispiel #5
0
void EKF::init(const cv::Mat &image)
{
    if (_logFile.is_open())
    {
        time_t seed = time(NULL);
        srand(static_cast<uint>(seed));

        _logFile << "Random Seed: " << seed << std::endl << std::endl;

        _logFile << "~~~~~~~~~~~~ STEP " << _ekfSteps << " ~~~~~~~~~~~~" << std::endl;
    }

    ExtendedKalmanFilterParameters *ekfParams = ConfigurationManager::getInstance().ekfParams;

    initState(state);

    state.mapFeatures.reserve(ekfParams->reserveFeaturesDepth);
    state.mapFeaturesDepth.reserve(ekfParams->reserveFeaturesDepth);
    state.mapFeaturesInvDepth.reserve(ekfParams->reserveFeaturesInvDepth);

    initCovariance(stateCovarianceMatrix);

    // Detectar features en la imagen
    VectorFeatureMatch noMatches; // Al principio no tiene nada ya que no hay matches
    VectorImageFeaturePrediction noPredictions;
    VectorImageFeatureMeasurement newFeatureMeasurements;
    detectNewImageFeatures(image, noPredictions, ekfParams->minMatchesPerImage, newFeatureMeasurements);

#ifdef DEBUG_SHOW_IMAGES
    cv::Mat imageWithKeypoints;
    image.copyTo(imageWithKeypoints);

    for (uint i = 0; i < newFeatureMeasurements.size(); ++i)
    {
        drawPoint(imageWithKeypoints, newFeatureMeasurements[i]->imagePos, cv::Scalar(0, 0, 255));
    }

    std::cout << std::endl;

    std::string windowName = "Features detectados en la primer imagen (";

    std::stringstream convert;
    convert << newFeatureMeasurements.size();

    windowName += convert.str();
    windowName += ")";

    cv::namedWindow(windowName);
    cv::imshow(windowName, imageWithKeypoints);
    cv::waitKey(0);

    cv::destroyWindow(windowName);
#endif

    // Agregar los features nuevos al estado
    addFeaturesToStateAndCovariance(newFeatureMeasurements, state, stateCovarianceMatrix);

    size_t newFeatureMeasurementsSize = newFeatureMeasurements.size();
    for (uint i = 0; i < newFeatureMeasurementsSize; ++i)
    {
        delete newFeatureMeasurements[i];
    }

    if (_logFile.is_open())
    {
        state.showDetailed(_logFile);
    }
}
Beispiel #6
0
void run_tests(TestState *parent, int selectedTest)
{
    TestState state;

    initState(&state, "Test", parent);
    state.selectedTest = selectedTest;

    if (startTest(&state, "the empty command")) {
        if (serialRequest(&state, ""))
            checkSerialResponse(&state, "=S,0");
    }

    if (startTest(&state, "an invalid command")) {
        if (serialRequest(&state, "FOO"))
            checkSerialResponse(&state, "=E,1");
    }

#ifdef DO_BLINK_TEST
    if (startTest(&state, "Blink LEDs on GPIO13 and GPIO15")) {
        if (test_blink(&state))
            passTest(&state, "");
        else
            failTest(&state, "");
    }
#endif

    if (state.ssid) {
        if (startTest(&state, "switch to STA+AP mode")) {
            if (serialRequest(&state, "SET:wifi-mode,3"))
                checkSerialResponse(&state, "=S,0");
        }
        if (startTest(&state, "JOIN")) {
            if (serialRequest(&state, "JOIN:%s,%s", state.ssid, state.passwd))
                checkSerialResponse(&state, "=S,0");
            if (state.testPassed)
                msleep(10000); // wait for WX to disconnect. It has a .5 second delay
        }
        beginGroup(&state);
        if (startTest(&state, "CHECK:station-ipaddr")) {
            if (!skipTest(&state)) {
                char ipaddr[32];
                do {
                    if (!serialRequest(&state, "CHECK:station-ipaddr"))
                        break;
                } while (!waitAndCheckSerialResponse(&state, "=S,0.0.0.0", "=S,^s", ipaddr, sizeof(ipaddr)));
                if (state.testPassed) {
                    infoTest(&state, "got '%s'", ipaddr);
                    if (GetInternetAddress(ipaddr, 80, &state.moduleAddr) != 0)
                        infoTest(&state, "error: failed to parse IP address '%s'", ipaddr);
                }
            }
        }
    }

    if (startTest(&state, "simple transaction")) {
        if (test_001(&state))
            passTest(&state, "");
        else
            failTest(&state, "");
    }

    testResults(&state);
}
Beispiel #7
0
void HiRes1Engine::restartGame() {
	_display->printString(_strings.pressReturn);
	initState();
	_display->printAsciiString(_strings.lineFeeds);
}
int main(int argc, char* argv[]) {

    double discountFactor = 0.9;

    FILE* initFileFd = NULL;
    double* setPoints = NULL;
    FILE* results = NULL;
    char str[1024];
    unsigned int i = 0;
    unsigned int nbSetPoints = 0;
    unsigned int* ns = NULL;
    unsigned int nbN = 0;
    unsigned int* hs = NULL;
    unsigned int nbH = 0;
    unsigned int nbSteps = 0;
    unsigned int timestamp = time(NULL);
    int readFscanf = -1;

    struct arg_file* initFile = arg_file1(NULL, "init", "<file>", "File containing the set points");
    struct arg_int* s = arg_int1("s", NULL, "<n>", "Number of steps");
    struct arg_str* r = arg_str1("n", NULL, "<s>", "List of ressources");
    struct arg_str* z = arg_str1("h", NULL, "<s>", "List of length for the sequences");
    struct arg_file* where = arg_file1(NULL, "where", "<file>", "Directory where we save the outputs");
    struct arg_end* end = arg_end(6);

    int nerrors = 0;
    void* argtable[6];

    argtable[0] = initFile;
    argtable[1] = r;
    argtable[2] = s;
    argtable[3] = z;
    argtable[4] = where;
    argtable[5] = end;

    if(arg_nullcheck(argtable) != 0) {
        printf("error: insufficient memory\n");
        arg_freetable(argtable, 6);
        return EXIT_FAILURE;
    }

    nerrors = arg_parse(argc, argv, argtable);

    if(nerrors > 0) {
        printf("%s:", argv[0]);
        arg_print_syntax(stdout, argtable, "\n");
        arg_print_errors(stdout, end, argv[0]);
        arg_freetable(argtable, 6);
        return EXIT_FAILURE;
    }

    initGenerativeModelParameters();
    initGenerativeModel();

    initFileFd = fopen(initFile->filename[0], "r");
    readFscanf = fscanf(initFileFd, "%u\n", &nbSetPoints);
    setPoints = (double*)malloc(sizeof(double) * nbSetPoints);
    
    for(; i < nbSetPoints; i++) {
        readFscanf = fscanf(initFileFd, "%s\n", str);
        setPoints[i] = strtod(str, NULL);
    }
    fclose(initFileFd);

    nbSteps = s->ival[0];
    hs = parseUnsignedIntList((char*)z->sval[0], &nbH);
    ns = parseUnsignedIntList((char*)r->sval[0], &nbN);

    sprintf(str, "%s/%u_results_%s_%s.csv", where->filename[0], timestamp, z->sval[0], r->sval[0]);
    results = fopen(str, "w");

    for(i = 0; i < nbN; i++) {                                          /* Loop on the computational ressources */
        printf("Starting with %u computational ressources\n", ns[i]);
        fprintf(results, "%u", ns[i]);
        fflush(NULL);
        unsigned int j = 0;
        for(; j < nbH; j++) {                                           /* Loop on the length of the sequences */
            unsigned int k = 0;
            state* crt1 = initState();
            state* crt2 = copyState(crt1);
            double averages[2] = {0.0,0.0};
            for(; k < nbSetPoints; k++) {                           /* Loop on the initial states */
                unsigned int l = 0;
                parameters[10] = setPoints[k];

                for(; l < nbSteps; l++) {                               /* Loop on the step */
                    char isTerminal = 0;
                    double reward = 0.0;
                    state* nextState = NULL;
                    sequential_direct_instance* sequential_direct = sequential_direct_initInstance(crt1, discountFactor, hs[j],1);

                    double* optimalAction = sequential_direct_planning(sequential_direct, ns[i]);
                    isTerminal = nextStateReward(crt1, optimalAction, &nextState, &reward) < 0 ? 1 : 0;
                    freeState(crt1);
                    crt1 = nextState;
                    averages[0] += reward;
                    sequential_direct_uninitInstance(&sequential_direct);
                    if(isTerminal)
                        break;
                }
                printf("direct: %u set point done for h=%u\n", k, hs[j]);
                fflush(NULL);

                for(l = 0; l < nbSteps; l++) {                               /* Loop on the step */
                    char isTerminal = 0;
                    double reward = 0.0;
                    state* nextState = NULL;
                    sequential_soo_instance* sequential_soo = sequential_soo_initInstance(crt2, discountFactor, hs[j],1);

                    double* optimalAction = sequential_soo_planning(sequential_soo, ns[i]);
                    isTerminal = nextStateReward(crt2, optimalAction, &nextState, &reward);
                    freeState(crt2);
                    crt2 = nextState;
                    averages[1] += reward;
                    sequential_soo_uninitInstance(&sequential_soo);
                    if(isTerminal)
                        break;
                }
                printf("soo: %u set point done for h=%u\n", k, hs[j]);
                fflush(NULL);
            }
            freeState(crt1);
            freeState(crt2);
            averages[0] = averages[0] /(double)nbSetPoints;
            averages[1] = averages[1] /(double)nbSetPoints;
            printf("Computation with h=%u and n=%u done\n", hs[j], ns[i]);
            fprintf(results, ",%.15f,%.15f", averages[0],averages[1]);
            fflush(NULL);
        }
        printf("Computation with %u computational ressources done\n\n", ns[i]);
        fprintf(results, "\n");
        fflush(NULL);
    }

    fclose(results);

    arg_freetable(argtable, 6);

    free(setPoints);

    freeGenerativeModel();
    freeGenerativeModelParameters();

    return EXIT_SUCCESS;

}
void Deformable::loadFromFile(char *filename)
{
    FILE *f = fopen(filename, "r");
    if (!f)
    {
        std::cout<<"no file"<<" "<<filename<<std::endl;
        return;
    }
    const int len = 100;
    char s[100];
    Eigen::Vector2d pos;
    double mass;
    int i;
    double x, y;
    reset();
    
    int original;
    int oheight;
    int owidth;
    int worldToScreen;
    fgets(s, len, f); sscanf(s, "%i", &original);
    //std::cout<<"origial "<<original<<std::endl;
    if(original==1)
    {
        fgets(s, len, f); sscanf(s, "%i", &oheight);
        fgets(s, len, f); sscanf(s, "%i", &owidth);
        //std::cout<<oheight<<" "<<owidth<<std::endl;
        worldToScreen = owidth;
    }
    
    int numVerts;
    fgets(s, len, f); sscanf(s, "%i", &numVerts);
    
    for (i = 0; i < numVerts; i++) {
        
        fgets(s, len, f); sscanf(s, "%lf %lf %lf", &x, &y, &mass);
        if(original==1)
        {
            x=x/worldToScreen;
            y=(oheight-y)/worldToScreen;
            //std::cout<<x<<" "<<y<<std::endl;
        }
        pos(0)=x;
        pos(1)=y;
        //std::cout<<pos(0)<<" "<<pos(1)<<std::endl;
        addVertex(pos, mass);
    }
    fgets(s, len, f); sscanf(s, "%lf", &params.timeStep);
    fgets(s, len, f); sscanf(s, "%lf %lf", &params.gravity(0), &params.gravity(1));
    
    fgets(s, len, f); sscanf(s, "%lf", &params.alpha);
    fgets(s, len, f); sscanf(s, "%lf", &params.beta);
    
    fgets(s, len, f); sscanf(s, "%i", &i); params.quadraticMatch = i;
    fgets(s, len, f); sscanf(s, "%i", &i); params.volumeConservation = i;
    fgets(s, len, f); sscanf(s, "%i", &i); params.allowFlip = i;
    fgets(s, len, f); sscanf(s, "%i", &i); params.isCluster = i;
    
    fclose(f);
    
    initState();
    
    if(params.isCluster)
        clusterVertex();
}
Beispiel #10
0
void Autom_State::init(AutomAllocator& alloc) {
  initState(alloc, this);
  deleted = false;
}
Beispiel #11
0
int crypto_aead_decrypt(
	unsigned char *m,unsigned long long *mlen,
	unsigned char *nsec,
	const unsigned char *c,unsigned long long clen,
	const unsigned char *ad,unsigned long long adlen,
	const unsigned char *npub,
	const unsigned char *k
)
{
    ICESTATE S;
    unsigned char Tcomp[ICEPOLETAGLEN]; /* computed authentication tag */
    unsigned int frameBit;
    
    /* ciphertext cannot be shorter than the tag length */
    if (clen < ICEPOLETAGLEN) {
        return -1;
    }
    
    initState(S, k, npub);

    /* process 128-bit secret message number */
    frameBit = 0;
    processDataBlockRev(S, c, &nsec, ICEPOLENSECLEN, frameBit);
    c += ICEPOLENSECLEN;
   
    /* process associated data blocks */
    do {
        unsigned long long blocklen = ICEPOLEDATABLOCKLEN;
        frameBit = (adlen <= blocklen ? 1 : 0);
        if (adlen < blocklen) {
            blocklen = adlen;
        }
        /* apply the permutation to the state */
        P6(S,S);
        /* absorb a data block */
        processDataBlock(S, ad, NULL, blocklen, frameBit);
        ad += blocklen;
        adlen -= blocklen;
    } while (adlen > 0);
    
    /* process ciphertext blocks to get auth tag */
    *mlen = 0;
    clen -= ICEPOLETAGLEN+ICEPOLENSECLEN; /* need to stop before auth tag*/
    do {
        unsigned long long blocklen = ICEPOLEDATABLOCKLEN;
        frameBit = (clen <= blocklen ? 0 : 1);
        if (clen < blocklen) {
            blocklen = clen;
        }
        /* apply the permutation to the state */
        P6(S,S);
        /* absorb a ciphertext block and produce a plaintext block */
        processDataBlockRev(S, c, &m, blocklen, frameBit);
        c += blocklen;
        *mlen += blocklen;
        clen -= blocklen;    
    } while (clen > 0);

    /* compare computed and received auth tags */
    generateTag(S, Tcomp);
    if (memcmp(Tcomp, c, ICEPOLETAGLEN)) {
        *mlen = 0;
        return -1;
    }
    
    return 0;
}
Beispiel #12
0
static pos createFood(int width, int height, posList snake) {
  // The high level view of how this code works: (1) Creates a list of
  // open positions (i.e positions not occuipied by the snake) and (2)
  // grabs a random element from that list. But it does this without
  // creating a list of open positions.
  int maxRand = width*height - snake.len;
  if (maxRand <= 0) {
    return (pos){ .x = -1, .y = -1 };
  }
  int randIndex = rand() % maxRand;
  int curRandIndex = 0;
  for (int y = 0; y < height; y++) {
    for (int x = 0; x < width; x++) {
      pos p = { .x = x, .y = y };
      if (posList_contains(snake, p)) {
	continue;
      }
      if (curRandIndex == randIndex) {
	return p;
      }
      curRandIndex++;
    }
  }
  // This should never be reached but I added it to get rid of the
  // compiler warning.
  return (pos){ .x = -1, .y = -1 };
}

static const dir NO_DIRECTION = { .x = 0, .y = 0 };

static dir actionToDirection(playeraction a) {
  if (a == UP) {
    return (dir){ .x = 0, .y = -1 };
  }
  if (a == DOWN) {
    return (dir){ .x = 0, .y = 1 };
  }
  if (a == LEFT) {
    return (dir){ .x = -1, .y = 0 };
  }
  if (a == RIGHT) {
    return (dir){ .x = 1, .y = 0 };
  }
  return NO_DIRECTION;
}

static void initState(int width, int height, posList *snake, pos *food, playeractionQueue *queue, dir *curDirection, bool *paused, int *score) {
  srand(time(NULL));
  snake->len = 4;
  snake->list[0] = (pos){ .x = 0, .y = 1 };
  snake->list[1] = (pos){ .x = 0, .y = 0 };
  snake->list[2] = (pos){ .x = 1, .y = 0 };
  snake->list[3] = (pos){ .x = 1, .y = 1 };
  *food = createFood(width, height, *snake);
  while (playeractionQueue_dequeue(queue) != NO_ACTION);
  *curDirection = actionToDirection(DOWN);
  *paused = false;
  *score = 0;
}

static bool gameIsWon(int width, int height, posList snake) {
  return width*height == snake.len;
}

static bool gameIsLost(int width, int height, posList snake) {
  {
    posList headless = snake;
    headless.len--;
    if (posList_contains(headless, snake.list[snake.len-1])) {
      return true;
    }
  }
  {
    pos head = snake.list[snake.len-1];
    if (head.x < 0 || width <= head.x) {
      return true;
    }
    if (head.y < 0 || height <= head.y) {
      return true;
    }
  }
  return false;
}

static void updateGameState(playeraction action, int width, int height, bool *paused, posList *snake, pos *food, dir *d, int *score) {
  if (action == PAUSE) {
    *paused = !(*paused);
    return;
  }
  if (*paused) {
    return;
  }
  dir newDir = actionToDirection(action);
  if (!dir_equal(newDir, NO_DIRECTION)) {
    *d = newDir;
  }
  pos newHead = { .x = snake->list[snake->len-1].x + d->x, .y = snake->list[snake->len-1].y + d->y };
  if (pos_equal(newHead, *food)) {
    *snake = posList_append(*snake, newHead);
    *food = createFood(width, height, *snake);
    (*score)++;
  } else {
    for (int i = 0; i < snake->len-1; i++) {
      snake->list[i] = snake->list[i+1];
    }
    snake->list[snake->len-1].x += d->x;
    snake->list[snake->len-1].y += d->y;
  }
}

char *playeraction_toString(playeraction p) {
  switch (p) {
  case NO_ACTION:
    return "no action";
  case UP:
    return "move the snake up";
  case DOWN:
    return "move the snake down";
  case LEFT:
    return "move the snake left";
  case RIGHT:
    return "move the snake right";
  case PAUSE:
    return "pause the game";
  case QUIT:
    return "quit the game";
  case NEW_GAME:
    return "start a new game";
  default:
    return "BUG!!! Unknown player action, please add another case to the switch statement";
  }
}

void playeractionQueue_enqueue(playeractionQueue *q, playeraction c) {
  if (q->isFull) {
    return;
  }
  pthread_mutex_lock(q->mu);
  q->arr[q->tail] = c;
  q->tail = (q->tail+1) % PLAYERACTIONQUEUE_SIZE;
  if (q->tail == q->head) {
    q->isFull = 1;
  }
  pthread_mutex_unlock(q->mu);
}

size_t snakeSpaceRequired(int width, int height) {
  posList snake;
  return width * height * sizeof(*snake.list);
}

void snake(int width, int height, struct timespec frameRate, void *snakeMem, playeractionQueue *actionsQueue, void (*render)(int width, int height, posList snake, pos food, bool paused, int score, bool gameIsWon, bool gameIsLost)) {
  posList snake;
  pos food;
  dir curDirection;
  bool paused;
  int score;

  snake.list = snakeMem;
  
  initState(width, height, &snake, &food, actionsQueue, &curDirection, &paused, &score);

  while (true) {
    bool won = gameIsWon(width, height, snake);
    bool lost = gameIsLost(width, height, snake);
    render(width, height, snake, food, paused, score, won, lost);
    nanosleep(&frameRate, NULL);
    playeraction action = playeractionQueue_dequeue(actionsQueue);
    while (!dir_orthogonal(curDirection, actionToDirection(action))) {
      action = playeractionQueue_dequeue(actionsQueue);
    }
    if (action == QUIT) {
      break;
    }
    if (action == NEW_GAME) {
        initState(width, height, &snake, &food, actionsQueue, &curDirection, &paused, &score);
	continue;
    }
    if (won || lost) {
      continue;
    }
    updateGameState(action, width, height, &paused, &snake, &food, &curDirection, &score);
  }
}
Beispiel #13
0
void getBestChainTest()
{
        State current;
        PLAYER winner;

        initState(&current);
        current.field[0][0] = PLAYER2;
        current.field[0][1] = PLAYER1;
        current.field[1][2] = NOPLAYER;
        current.field[1][0] = PLAYER2;
        current.field[1][1] = PLAYER2;
        current.field[1][2] = PLAYER1;
        current.field[2][0] = PLAYER1;
        current.field[2][1] = PLAYER1;
        current.current_player = PLAYER2;
        StateChain res;
        initStateChain(&res);
        getBestChain(current, &res);
        printStateChain(res);
        assert(res.chain[1].field[2][2] == PLAYER2);

        initState(&current);
        current.field[1][1] = PLAYER1;
        current.current_player = PLAYER2;
        initStateChain(&res);
        getBestChain(current, &res);
        printStateChain(res);
        assert(res.val == 0);

        /*initState(&current);
        current.field[0][0] = PLAYER1;
        current.field[2][2] = PLAYER2;
        current.current_player = PLAYER1;
        initStateChain(&res);
        getBestChain(current, &res);
        printStateChain(res);
        assert(res.val == 0);*/

        initState(&current);
        current.field[0][0] = PLAYER2;
        current.field[0][1] = PLAYER1;
        current.field[1][0] = PLAYER1;
        current.field[1][1] = PLAYER1;
        current.field[1][2] = PLAYER2;
        current.field[2][1] = PLAYER2;
        current.field[2][2] = PLAYER1;
        current.current_player = PLAYER2;
        initStateChain(&res);
        getBestChain(current, &res);
        printStateChain(res);
        assert(res.val == 0);

        initState(&current);
        current.field[2][0] = PLAYER1;
        current.current_player = PLAYER2;
        initStateChain(&res);
        getBestChain(current, &res);
        printStateChain(res);
        assert(res.val == 0);

        initState(&current);
        current.field[0][2] = PLAYER1;
        current.current_player = PLAYER2;
        initStateChain(&res);
        getBestChain(current, &res);
        printStateChain(res);
        assert(res.val == 0);

        initState(&current);
        current.field[2][2] = PLAYER1;
        current.current_player = PLAYER2;
        initStateChain(&res);
        getBestChain(current, &res);
        printStateChain(res);
        assert(res.val == 0);

        initState(&current);
        current.field[0][0] = PLAYER1;
        current.field[1][1] = PLAYER2;
        current.field[1][0] = PLAYER1;
        current.field[2][0] = PLAYER2;
        current.current_player = PLAYER1;
        initStateChain(&res);
        getBestChain(current, &res);
        printStateChain(res);
        assert(res.val == 0);
}
Beispiel #14
0
void getWinnerTest()
{
        State current;
        PLAYER winner;

        initState(&current);
        current.field[1][1] = PLAYER1;
        current.field[0][0] = PLAYER1;
        current.field[2][2] = PLAYER1;
        getWinner(current, &winner);
        assert(winner == PLAYER1);

        initState(&current);
        current.field[1][1] = PLAYER1;
        current.field[0][2] = PLAYER1;
        current.field[2][0] = PLAYER1;
        getWinner(current, &winner);
        assert(winner == PLAYER1);

        initState(&current);
        current.field[0][0] = PLAYER1;
        current.field[0][1] = PLAYER1;
        current.field[0][2] = PLAYER1;
        getWinner(current, &winner);
        assert(winner == PLAYER1);

        initState(&current);
        current.field[0][0] = PLAYER1;
        current.field[1][0] = PLAYER1;
        current.field[2][0] = PLAYER1;
        getWinner(current, &winner);
        assert(winner == PLAYER1); 
        
        initState(&current);
        current.field[1][1] = PLAYER2;
        current.field[0][0] = PLAYER2;
        current.field[2][2] = PLAYER2;
        getWinner(current, &winner);
        assert(winner == PLAYER2);

        initState(&current);
        current.field[1][1] = PLAYER2;
        current.field[0][2] = PLAYER2;
        current.field[2][0] = PLAYER2;
        getWinner(current, &winner);
        assert(winner == PLAYER2);

        initState(&current);
        current.field[0][0] = PLAYER2;
        current.field[0][1] = PLAYER2;
        current.field[0][2] = PLAYER2;
        getWinner(current, &winner);
        assert(winner == PLAYER2);

        initState(&current);
        current.field[0][0] = PLAYER2;
        current.field[1][0] = PLAYER2;
        current.field[2][0] = PLAYER2;
        getWinner(current, &winner);
        assert(winner == PLAYER2);
}
Beispiel #15
0
/**
 * Executes Lyra2 based on the G function from Blake2b. This version supports salts and passwords
 * whose combined length is smaller than the size of the memory matrix, (i.e., (nRows x nCols x b) bits,
 * where "b" is the underlying sponge's bitrate). In this implementation, the "basil" is composed by all 
 * integer parameters, in the order they are provided (i.e., basil = kLen || pwdlen || saltlen || timeCost || nRows || nCols).
 *
 * @param K The derived key to be output by the algorithm
 * @param kLen Desired key length
 * @param pwd User password
 * @param pwdlen Password length
 * @param salt Salt
 * @param saltlen Salt length
 * @param timeCost Parameter to determine the processing time (T)
 * @param nRows Number or rows of the memory matrix (R)
 * @param nCols Number of columns of the memory matrix (C)
 *
 * @return 0 if the key is generated correctly; -1 if there is an error (usually due to lack of memory for allocation)
 */
int LYRA2(unsigned char *K, int kLen, const unsigned char *pwd, int pwdlen, const unsigned char *salt, int saltlen, int timeCost, int nRows, int nCols) {

    //============================= Basic variables ============================//
    int row = 2; //index of row to be processed
    int prev = 1; //index of prev (last row ever computed/modified)
    int rowa = 0; //index of row* (a previous row, deterministically picked during Setup and randomly picked during Wandering)
    int tau; //Time Loop iterator
    int i; //auxiliary iteration counter
    //==========================================================================/

    if (nRows < 3)
      return -1;

    //========== Initializing the Memory Matrix and pointers to it =============//
    //Allocates enough space for the whole memory matrix
    uint64_t *wholeMatrix = malloc(nRows * ROW_LEN_BYTES);
    if (wholeMatrix == NULL) {
	return -1;
    }
    //Allocates pointers to each row of the matrix
    uint64_t **memMatrix = malloc(nRows * sizeof (uint64_t*));
    if (memMatrix == NULL) {
	return -1;
    }
    //Places the pointers in the correct positions
    uint64_t *ptrWord = wholeMatrix;
    for (i = 0; i < nRows; i++) {
	memMatrix[i] = ptrWord;
	ptrWord += ROW_LEN_INT64;
    }
    //==========================================================================/

    //============= Getting the password + salt + basil padded with 10*1 ===============//

    //OBS.:The memory matrix will temporarily hold the password: not for saving memory,
    //but this ensures that the password copied locally will be overwritten as soon as possible

    //First, we clean enough blocks for the password, salt, basil and padding
    int nBlocksInput = ((saltlen + pwdlen + 6*sizeof(int)) / BLOCK_LEN_BYTES) + 1;
    byte *ptrByte = (byte*) wholeMatrix;
    memset(ptrByte, 0, nBlocksInput * BLOCK_LEN_BYTES);

    //Prepends the password
    memcpy(ptrByte, pwd, pwdlen);
    ptrByte += pwdlen;
    
    //Concatenates the salt
    memcpy(ptrByte, salt, saltlen);
    ptrByte += saltlen;
    
    //Concatenates the basil: every integer passed as parameter, in the order they are provided by the interface
    memcpy(ptrByte, &kLen, sizeof(int));
    ptrByte += sizeof(int);
    memcpy(ptrByte, &pwdlen, sizeof(int));
    ptrByte += sizeof(int);
    memcpy(ptrByte, &saltlen, sizeof(int));
    ptrByte += sizeof(int);
    memcpy(ptrByte, &timeCost, sizeof(int));
    ptrByte += sizeof(int);
    memcpy(ptrByte, &nRows, sizeof(int));
    ptrByte += sizeof(int);
    memcpy(ptrByte, &nCols, sizeof(int));
    ptrByte += sizeof(int);
    

    //Now comes the padding
    *ptrByte = 0x80; //first byte of padding: right after the password
    ptrByte = (byte*) wholeMatrix; //resets the pointer to the start of the memory matrix
    ptrByte += nBlocksInput * BLOCK_LEN_BYTES - 1; //sets the pointer to the correct position: end of incomplete block
    *ptrByte ^= 0x01; //last byte of padding: at the end of the last incomplete block

    //==========================================================================/

    //======================= Initializing the Sponge State ====================//
    //Sponge state: 16 uint64_t, BLOCK_LEN_INT64 words of them for the bitrate (b) and the remainder for the capacity (c)
    uint64_t *state = malloc(16 * sizeof (uint64_t));
    if (state == NULL) {
	return -1;
    }
    initState(state);
    //==========================================================================/

    //================================ Setup Phase =============================//

    //Absorbing salt, password and basil
    ptrWord = wholeMatrix;
    for (i = 0; i < nBlocksInput; i++) {
	absorbBlock(state, ptrWord); //absorbs each block of pad(pwd || salt || basil)
	ptrWord += BLOCK_LEN_INT64; //goes to next block of pad(pwd || salt || basil)
    }

    //Initializes M[0] and M[1]
    reducedSqueezeRow(state, memMatrix[0]); //The locally copied password is most likely overwritten here
    reducedSqueezeRow(state, memMatrix[1]);

    do {
	//M[row] = rand; //M[row*] = M[row*] XOR rotW(rand)
	reducedDuplexRowSetup(state, memMatrix[prev], memMatrix[rowa], memMatrix[row]);

	//updates the value of row* (deterministically picked during Setup))
	rowa--;
	if (rowa < 0) {
	    rowa = prev;
	}
	//update prev: it now points to the last row ever computed
	prev = row;
	//updates row: does to the next row to be computed
	row++;
    } while (row < nRows);
    //==========================================================================/

    //============================ Wandering Phase =============================//
    int maxIndex = nRows - 1;
    for (tau = 1; tau <= timeCost; tau++) {
	//========= Iterations for an odd tau ==========
	row = maxIndex; //Odd iterations of the Wandering phase start with the last row ever computed
	prev = 0; //The companion "prev" is 0
	do {
	    //Selects a pseudorandom index row*
	    //rowa = ((unsigned int)state[0] ^ prev) & maxIndex; //(USE THIS IF nRows IS A POWER OF 2)
	    rowa = ((unsigned int) (state[0] ^ prev)) % nRows; //(USE THIS FOR THE "GENERIC" CASE)

	    //Performs a reduced-round duplexing operation over M[row*] XOR M[prev], updating both M[row*] and M[row]
	    reducedDuplexRow(state, memMatrix[prev], memMatrix[rowa], memMatrix[row]);

	    //Goes to the next row (inverse order)
	    prev = row;
	    row--;
	} while (row >= 0);

	if (++tau > timeCost) {
	    break; //end of the Wandering phase
	}

	//========= Iterations for an even tau ==========
	row = 0; //Even iterations of the Wandering phase start with row = 0
	prev = maxIndex; //The companion "prev" is the last row in the memory matrix
	do {
	    //rowa = ((unsigned int)state[0] ^ prev) & maxIndex; //(USE THIS IF nRows IS A POWER OF 2)
	    rowa = ((unsigned int) (state[0] ^ prev)) % nRows; //(USE THIS FOR THE "GENERIC" CASE)

	    //Performs a reduced-round duplexing operation over M[row*] XOR M[prev], updating both M[row*] and M[row]
	    reducedDuplexRow(state, memMatrix[prev], memMatrix[rowa], memMatrix[row]);

	    //Goes to the next row (direct order)
	    prev = row;
	    row++;
	} while (row <= maxIndex);
    }
    //==========================================================================/

    //============================ Wrap-up Phase ===============================//
    //Absorbs the last block of the memory matrix
    absorbBlock(state, memMatrix[rowa]);

    //Squeezes the key
    squeeze(state, K, kLen);
    //==========================================================================/

    //========================= Freeing the memory =============================//
    free(memMatrix);
    free(wholeMatrix);
    
    //Wiping out the sponge's internal state before freeing it
    memset(state, 0, 16 * sizeof (uint64_t));
    free(state);
    //==========================================================================/

    return 0;
}
Beispiel #16
0
int main(int argc, const char *argv[])
{
    poptContext optCon;   /* context for parsing command-line options */

    int rc, version = 0, debugMask = 0, pipeFD[2] = {-1, -1}, magic = FORKMAGIC;
    char *logdest = NULL, *configfile = "/etc/parastation.conf";
    FILE *logfile = NULL;

    struct poptOption optionsTable[] = {
	{ "debug", 'd', POPT_ARG_INT, &debugMask, 0,
	  "enable debugging with mask <mask>", "mask"},
	{ "configfile", 'f', POPT_ARG_STRING, &configfile, 0,
	  "use <file> as config-file (default is /etc/parastation.conf)",
	  "file"},
	{ "logfile", 'l', POPT_ARG_STRING, &logdest, 0,
	  "use <file> for logging (default is syslog(3))."
	  " <file> may be 'stderr' or 'stdout'", "file"},
	{ "version", 'v', POPT_ARG_NONE, &version, 0,
	  "output version information and exit", NULL},
	POPT_AUTOHELP
	{ NULL, '\0', 0, NULL, 0, NULL, NULL}
    };

    optCon = poptGetContext(NULL, argc, argv, optionsTable, 0);
    rc = poptGetNextOpt(optCon);

    /* Store arguments for later modification in forwarders, etc. */
    PSID_argc = argc;
    PSID_argv = argv;

    if (version) {
	printVersion();
	return 0;
    }

    if (logdest) {
	if (strcasecmp(logdest, "stderr")==0) {
	    logfile = stderr;
	} else if (strcasecmp(logdest, "stdout")==0) {
	    logfile = stdout;
	} else {
	    logfile = fopen(logdest, "a+");
	    if (!logfile) {
		char *errstr = strerror(errno);
		fprintf(stderr, "Cannot open logfile '%s': %s\n", logdest,
			errstr ? errstr : "UNKNOWN");
		exit(1);
	    }
	}
    }

    if (!logfile) {
	openlog("psid", LOG_PID|LOG_CONS, LOG_DAEMON);
    }
    PSID_initLogs(logfile);

    printWelcome();

    if (rc < -1) {
	/* an error occurred during option processing */
	poptPrintUsage(optCon, stderr, 0);
	PSID_log(-1, "%s: %s\n",
		 poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
		 poptStrerror(rc));
	if (!logfile)
	    fprintf(stderr, "%s: %s\n",
		    poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
		    poptStrerror(rc));

	return 1;
    }

    /* Save some space in order to modify the cmdline later on */
    PSC_saveTitleSpace(PSID_argc, PSID_argv, 1);

    if (logfile!=stderr && logfile!=stdout) {
	/* Daemonize only if neither stdout nor stderr is used for logging */
	if (pipe(pipeFD) < 0) {
	    PSID_exit(errno, "unable to create pipe");
	}

	/* Start as daemon */
	switch (fork()) {
	case -1:
	    PSID_exit(errno, "unable to fork server process");
	    break;
	case 0: /* I'm the child (and running further) */
	    close (pipeFD[0]);
	    break;
	default: /* I'm the parent and exiting */
	    close (pipeFD[1]);

	    /* Wait for child's magic data */
	    rc = read(pipeFD[0], &magic, sizeof(magic));
	    if (rc != sizeof(magic) || magic != (FORKMAGIC)) return -1;

	    return 0;
       }
    }

#define _PATH_TTY "/dev/tty"
    /* First disconnect from the old controlling tty. */
    {
	int fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
	if (fd >= 0) {
	    if (ioctl(fd, TIOCNOTTY, NULL)) {
		PSID_warn(-1, errno, "%s: ioctl(TIOCNOTTY)", __func__);
	    }
	    close(fd);
	}
    }


    /*
     * Disable stdin,stdout,stderr and install dummy replacement
     * Take care if stdout/stderr is used for logging
     */
    {
	int dummy_fd;

	dummy_fd=open("/dev/null", O_WRONLY , 0);
	dup2(dummy_fd, STDIN_FILENO);
	if (logfile!=stdout) dup2(dummy_fd, STDOUT_FILENO);
	if (logfile!=stderr) dup2(dummy_fd, STDERR_FILENO);
	close(dummy_fd);
    }

    /* Forget about inherited window sizes */
    unsetenv("LINES");
    unsetenv("COLUMNS");

    if (debugMask) {
	PSID_setDebugMask(debugMask);
	PSC_setDebugMask(debugMask);
	PSID_log(-1, "Debugging mode (mask 0x%x) enabled\n", debugMask);
    }

    /* Init the Selector facility as soon as possible */
    if (!Selector_isInitialized()) Selector_init(logfile);
    PSID_registerLoopAct(Selector_gc);

    /* Initialize timer facility explicitely to ensure correct logging */
    if (!Timer_isInitialized()) Timer_init(logfile);

    /*
     * Create the Local Service Port as early as possible. Actual
     * handling is enabled later. This gives psiadmin the chance to
     * connect. Additionally, this will guarantee exclusiveness
     */
    PSID_createMasterSock(PSmasterSocketName);

    PSID_checkMaxPID();

    /* read the config file */
    PSID_readConfigFile(logfile, configfile);
    /* Now we can rely on the config structure */

    {
	in_addr_t addr;

	PSID_log(-1, "My ID is %d\n", PSC_getMyID());

	addr = PSIDnodes_getAddr(PSC_getMyID());
	PSID_log(-1, "My IP is %s\n", inet_ntoa(*(struct in_addr *) &addr));
    }

    if (!logfile && PSID_config->logDest!=LOG_DAEMON) {
	PSID_log(-1, "Changing logging dest from LOG_DAEMON to %s\n",
		 PSID_config->logDest==LOG_KERN ? "LOG_KERN":
		 PSID_config->logDest==LOG_LOCAL0 ? "LOG_LOCAL0" :
		 PSID_config->logDest==LOG_LOCAL1 ? "LOG_LOCAL1" :
		 PSID_config->logDest==LOG_LOCAL2 ? "LOG_LOCAL2" :
		 PSID_config->logDest==LOG_LOCAL3 ? "LOG_LOCAL3" :
		 PSID_config->logDest==LOG_LOCAL4 ? "LOG_LOCAL4" :
		 PSID_config->logDest==LOG_LOCAL5 ? "LOG_LOCAL5" :
		 PSID_config->logDest==LOG_LOCAL6 ? "LOG_LOCAL6" :
		 PSID_config->logDest==LOG_LOCAL7 ? "LOG_LOCAL7" :
		 "UNKNOWN");
	closelog();

	openlog("psid", LOG_PID|LOG_CONS, PSID_config->logDest);
	printWelcome();
    }

    /* call startupScript, if any */
    if (PSID_config->startupScript && *PSID_config->startupScript) {
	int ret = PSID_execScript(PSID_config->startupScript, NULL, NULL, NULL);

	if (ret > 1) {
	    PSID_log(-1, "startup script '%s' failed. Exiting...\n",
		     PSID_config->startupScript);
	    PSID_finalizeLogs();
	    exit(1);
	}
    }

    /* Setup handling of signals */
    initSigHandlers();

    if (PSID_config->coreDir) {
	if (chdir(PSID_config->coreDir) < 0) {
	    PSID_warn(-1, errno, "Unable to chdir() to coreDirectory '%s'",
		      PSID_config->coreDir);
	}
    }

    PSIDnodes_setProtoV(PSC_getMyID(), PSProtocolVersion);
    PSIDnodes_setDmnProtoV(PSC_getMyID(), PSDaemonProtocolVersion);
    PSIDnodes_setHWStatus(PSC_getMyID(), 0);
    PSIDnodes_setKillDelay(PSC_getMyID(), PSID_config->killDelay);
    PSIDnodes_setAcctPollI(PSC_getMyID(), PSID_config->acctPollInterval);

    /* Bring node up with correct numbers of CPUs */
    declareNodeAlive(PSC_getMyID(), PSID_getPhysCPUs(), PSID_getVirtCPUs());

    /* Initialize timeouts, etc. */
    PSID_initStarttime();

    /* initialize various modules */
    PSIDcomm_init();  /* This has to be first since it gives msgHandler hash */

    PSIDclient_init();
    initState();
    initOptions();
    initStatus();
    initSignal();
    PSIDspawn_init();
    initPartition();
    initHW();
    initAccount();
    initInfo();
    initEnvironment();
    /* Plugins shall be last since they use most of the ones before */
    initPlugins();

    /* Now we start all the hardware -- this might include the accounter */
    PSID_log(PSID_LOG_HW, "%s: starting up the hardware\n", __func__);
    PSID_startAllHW();

    /*
     * Prepare hostlist to initialize RDP and MCast
     */
    {
	in_addr_t *hostlist;
	int i;

	hostlist = malloc(PSC_getNrOfNodes() * sizeof(unsigned int));
	if (!hostlist) {
	    PSID_exit(errno, "Failed to get memory for hostlist");
	}

	for (i=0; i<PSC_getNrOfNodes(); i++) {
	    hostlist[i] = PSIDnodes_getAddr(i);
	}

	if (PSID_config->useMCast) {
	    /* Initialize MCast */
	    int MCastSock = initMCast(PSC_getNrOfNodes(),
				      PSID_config->MCastGroup,
				      PSID_config->MCastPort,
				      logfile, hostlist,
				      PSC_getMyID(), MCastCallBack);
	    if (MCastSock<0) {
		PSID_exit(errno, "Error while trying initMCast");
	    }
	    setDeadLimitMCast(PSID_config->deadInterval);

	    PSID_log(-1, "MCast and ");
	} else {
	    setStatusTimeout(PSID_config->statusTimeout);
	    setMaxStatBCast(PSID_config->statusBroadcasts);
	    setDeadLimit(PSID_config->deadLimit);
	    setTmOutRDP(PSID_config->RDPTimeout);
	}

	/* Initialize RDP */
	RDPSocket = RDP_init(PSC_getNrOfNodes(),
			     PSIDnodes_getAddr(PSC_getMyID()),
			     PSID_config->RDPPort, logfile, hostlist,
			     PSIDRDP_handleMsg, RDPCallBack);
	if (RDPSocket<0) {
	    PSID_exit(errno, "Error while trying initRDP");
	}

	PSID_log(-1, "RDP (%d) initialized.\n", RDPSocket);

	free(hostlist);
    }

    /* Now start to listen for clients */
    PSID_enableMasterSock();

    /* Once RDP and the master socket are ready parents might be released */
    if (pipeFD[1] > -1) {
	if (write(pipeFD[1], &magic, sizeof(magic)) <= 0) {
	    /* We don't care */
	}
	close(pipeFD[1]);
    }

    PSID_log(-1, "SelectTime=%d sec    DeadInterval=%d\n",
	     PSID_config->selectTime, PSID_config->deadInterval);

    /* Trigger status stuff, if necessary */
    if (PSID_config->useMCast) {
	declareMaster(PSC_getMyID());
    } else {
	int id = 0;
	while (id < PSC_getMyID()
	       && (send_DAEMONCONNECT(id) < 0 && errno == EHOSTUNREACH)) {
	    id++;
	}
	if (id == PSC_getMyID()) declareMaster(id);
    }

    /*
     * Main loop
     */
    while (1) {
	int res = Swait(PSID_config->selectTime * 1000);

	if (res < 0) PSID_warn(-1, errno, "Error while Swait()");

	/* Handle actions registered to main-loop */
	PSID_handleLoopActions();
    }
}
Beispiel #17
0
int
main (int argc, char **argv)
{

  int c;
  extern char *optarg;
  extern int optind, opterr, optopt;
  dsd_opts opts;
  dsd_state state;
  char versionstr[25];
  mbe_printVersion (versionstr);

  printf ("Digital Speech Decoder 1.7.0-dev (build:%s)\n", GIT_TAG);
  printf ("mbelib version %s\n", versionstr);

  initOpts (&opts);
  initState (&state);

  exitflag = 0;
  signal (SIGINT, sigfun);

  while ((c = getopt (argc, argv, "hep:qstv:z:i:o:d:g:nw:B:C:R:f:m:u:x:A:S:M:rl")) != -1)
    {
      opterr = 0;
      switch (c)
        {
        case 'h':
          usage ();
          exit (0);
        case 'e':
          opts.errorbars = 1;
          opts.datascope = 0;
          break;
        case 'p':
          if (optarg[0] == 'e')
            {
              opts.p25enc = 1;
            }
          else if (optarg[0] == 'l')
            {
              opts.p25lc = 1;
            }
          else if (optarg[0] == 's')
            {
              opts.p25status = 1;
            }
          else if (optarg[0] == 't')
            {
              opts.p25tg = 1;
            }
          else if (optarg[0] == 'u')
            {
        	  opts.unmute_encrypted_p25 = 1;
            }
          break;
        case 'q':
          opts.errorbars = 0;
          opts.verbose = 0;
          break;
        case 's':
          opts.errorbars = 0;
          opts.p25enc = 0;
          opts.p25lc = 0;
          opts.p25status = 0;
          opts.p25tg = 0;
          opts.datascope = 1;
          opts.symboltiming = 0;
          break;
        case 't':
          opts.symboltiming = 1;
          opts.errorbars = 1;
          opts.datascope = 0;
          break;
        case 'v':
          sscanf (optarg, "%d", &opts.verbose);
          break;
        case 'z':
          sscanf (optarg, "%d", &opts.scoperate);
          opts.errorbars = 0;
          opts.p25enc = 0;
          opts.p25lc = 0;
          opts.p25status = 0;
          opts.p25tg = 0;
          opts.datascope = 1;
          opts.symboltiming = 0;
          printf ("Setting datascope frame rate to %i frame per second.\n", opts.scoperate);
          break;
        case 'i':
          strncpy(opts.audio_in_dev, optarg, 1023);
          opts.audio_in_dev[1023] = '\0';
          break;
        case 'o':
          strncpy(opts.audio_out_dev, optarg, 1023);
          opts.audio_out_dev[1023] = '\0';
          break;
        case 'd':
          strncpy(opts.mbe_out_dir, optarg, 1023);
          opts.mbe_out_dir[1023] = '\0';
          printf ("Writing mbe data files to directory %s\n", opts.mbe_out_dir);
          break;
        case 'g':
          sscanf (optarg, "%f", &opts.audio_gain);
          if (opts.audio_gain < (float) 0 )
            {
              printf ("Disabling audio out gain setting\n");
            }
          else if (opts.audio_gain == (float) 0)
            {
              opts.audio_gain = (float) 0;
              printf ("Enabling audio out auto-gain\n");
            }
          else
            {
              printf ("Setting audio out gain to %f\n", opts.audio_gain);
              state.aout_gain = opts.audio_gain;
            }
          break;
        case 'n':
          opts.audio_out = 0;
          printf ("Disabling audio output to soundcard.\n");
          break;
        case 'w':
          strncpy(opts.wav_out_file, optarg, 1023);
          opts.wav_out_file[1023] = '\0';
          printf ("Writing audio to file %s\n", opts.wav_out_file);
          openWavOutFile (&opts, &state);
          break;
        case 'B':
          sscanf (optarg, "%d", &opts.serial_baud);
          break;
        case 'C':
          strncpy(opts.serial_dev, optarg, 1023);
          opts.serial_dev[1023] = '\0';
          break;
        case 'R':
          sscanf (optarg, "%d", &opts.resume);
          printf ("Enabling scan resume after %i TDULC frames\n", opts.resume);
          break;
        case 'f':
          if (optarg[0] == 'a')
            {
              opts.frame_dstar = 1;
              opts.frame_x2tdma = 1;
              opts.frame_p25p1 = 1;
              opts.frame_nxdn48 = 0;
              opts.frame_nxdn96 = 1;
              opts.frame_dmr = 1;
              opts.frame_provoice = 0;
            }
          else if (optarg[0] == 'd')
            {
              opts.frame_dstar = 1;
              opts.frame_x2tdma = 0;
              opts.frame_p25p1 = 0;
              opts.frame_nxdn48 = 0;
              opts.frame_nxdn96 = 0;
              opts.frame_dmr = 0;
              opts.frame_provoice = 0;
              printf ("Decoding only D-STAR frames.\n");
            }
          else if (optarg[0] == 'x')
            {
              opts.frame_dstar = 0;
              opts.frame_x2tdma = 1;
              opts.frame_p25p1 = 0;
              opts.frame_nxdn48 = 0;
              opts.frame_nxdn96 = 0;
              opts.frame_dmr = 0;
              opts.frame_provoice = 0;
              printf ("Decoding only X2-TDMA frames.\n");
            }
          else if (optarg[0] == 'p')
            {
              opts.frame_dstar = 0;
              opts.frame_x2tdma = 0;
              opts.frame_p25p1 = 0;
              opts.frame_nxdn48 = 0;
              opts.frame_nxdn96 = 0;
              opts.frame_dmr = 0;
              opts.frame_provoice = 1;
              state.samplesPerSymbol = 5;
              state.symbolCenter = 2;
              opts.mod_c4fm = 0;
              opts.mod_qpsk = 0;
              opts.mod_gfsk = 1;
              state.rf_mod = 2;
              printf ("Setting symbol rate to 9600 / second\n");
              printf ("Enabling only GFSK modulation optimizations.\n");
              printf ("Decoding only ProVoice frames.\n");
            }
          else if (optarg[0] == '1')
            {
              opts.frame_dstar = 0;
              opts.frame_x2tdma = 0;
              opts.frame_p25p1 = 1;
              opts.frame_nxdn48 = 0;
              opts.frame_nxdn96 = 0;
              opts.frame_dmr = 0;
              opts.frame_provoice = 0;
              printf ("Decoding only P25 Phase 1 frames.\n");
            }
          else if (optarg[0] == 'i')
            {
              opts.frame_dstar = 0;
              opts.frame_x2tdma = 0;
              opts.frame_p25p1 = 0;
              opts.frame_nxdn48 = 1;
              opts.frame_nxdn96 = 0;
              opts.frame_dmr = 0;
              opts.frame_provoice = 0;
              state.samplesPerSymbol = 20;
              state.symbolCenter = 10;
              opts.mod_c4fm = 0;
              opts.mod_qpsk = 0;
              opts.mod_gfsk = 1;
              state.rf_mod = 2;
              printf ("Setting symbol rate to 2400 / second\n");
              printf ("Enabling only GFSK modulation optimizations.\n");
              printf ("Decoding only NXDN 4800 baud frames.\n");
            }
          else if (optarg[0] == 'n')
            {
              opts.frame_dstar = 0;
              opts.frame_x2tdma = 0;
              opts.frame_p25p1 = 0;
              opts.frame_nxdn48 = 0;
              opts.frame_nxdn96 = 1;
              opts.frame_dmr = 0;
              opts.frame_provoice = 0;
              opts.mod_c4fm = 0;
              opts.mod_qpsk = 0;
              opts.mod_gfsk = 1;
              state.rf_mod = 2;
              printf ("Enabling only GFSK modulation optimizations.\n");
              printf ("Decoding only NXDN 9600 baud frames.\n");
            }
          else if (optarg[0] == 'r')
            {
              opts.frame_dstar = 0;
              opts.frame_x2tdma = 0;
              opts.frame_p25p1 = 0;
              opts.frame_nxdn48 = 0;
              opts.frame_nxdn96 = 0;
              opts.frame_dmr = 1;
              opts.frame_provoice = 0;
              printf ("Decoding only DMR/MOTOTRBO frames.\n");
            }
          break;
        case 'm':
          if (optarg[0] == 'a')
            {
              opts.mod_c4fm = 1;
              opts.mod_qpsk = 1;
              opts.mod_gfsk = 1;
              state.rf_mod = 0;
            }
          else if (optarg[0] == 'c')
            {
              opts.mod_c4fm = 1;
              opts.mod_qpsk = 0;
              opts.mod_gfsk = 0;
              state.rf_mod = 0;
              printf ("Enabling only C4FM modulation optimizations.\n");
            }
          else if (optarg[0] == 'g')
            {
              opts.mod_c4fm = 0;
              opts.mod_qpsk = 0;
              opts.mod_gfsk = 1;
              state.rf_mod = 2;
              printf ("Enabling only GFSK modulation optimizations.\n");
            }
          else if (optarg[0] == 'q')
            {
              opts.mod_c4fm = 0;
              opts.mod_qpsk = 1;
              opts.mod_gfsk = 0;
              state.rf_mod = 1;
              printf ("Enabling only QPSK modulation optimizations.\n");
            }
          break;
        case 'u':
          sscanf (optarg, "%i", &opts.uvquality);
          if (opts.uvquality < 1)
            {
              opts.uvquality = 1;
            }
          else if (opts.uvquality > 64)
            {
              opts.uvquality = 64;
            }
          printf ("Setting unvoice speech quality to %i waves per band.\n", opts.uvquality);
          break;
        case 'x':
          if (optarg[0] == 'x')
            {
              opts.inverted_x2tdma = 0;
              printf ("Expecting non-inverted X2-TDMA signals.\n");
            }
          else if (optarg[0] == 'r')
            {
              opts.inverted_dmr = 1;
              printf ("Expecting inverted DMR/MOTOTRBO signals.\n");
            }
          break;
        case 'A':
          sscanf (optarg, "%i", &opts.mod_threshold);
          printf ("Setting C4FM/QPSK auto detection threshold to %i\n", opts.mod_threshold);
          break;
        case 'S':
          sscanf (optarg, "%i", &opts.ssize);
          if (opts.ssize > 128)
            {
              opts.ssize = 128;
            }
          else if (opts.ssize < 1)
            {
              opts.ssize = 1;
            }
          printf ("Setting QPSK symbol buffer to %i\n", opts.ssize);
          break;
        case 'M':
          sscanf (optarg, "%i", &opts.msize);
          if (opts.msize > 1024)
            {
              opts.msize = 1024;
            }
          else if (opts.msize < 1)
            {
              opts.msize = 1;
            }
          printf ("Setting QPSK Min/Max buffer to %i\n", opts.msize);
          break;
        case 'r':
          opts.playfiles = 1;
          opts.errorbars = 0;
          opts.datascope = 0;
          state.optind = optind;
          break;
        case 'l':
          opts.use_cosine_filter = 0;
          break;
        default:
          usage ();
          exit (0);
        }
    }


  if (opts.resume > 0)
    {
      openSerial (&opts, &state);
    }

  if (opts.playfiles == 1)
    {
      opts.split = 1;
      opts.playoffset = 0;
      opts.delay = 0;
      if(strlen(opts.wav_out_file) > 0) {
        openWavOutFile (&opts, &state);
      }
      else {
        openAudioOutDevice (&opts, 8000);
      }
    }
  else if (strcmp (opts.audio_in_dev, opts.audio_out_dev) != 0)
    {
      opts.split = 1;
      opts.playoffset = 0;
      opts.delay = 0;
      if(strlen(opts.wav_out_file) > 0) {
        openWavOutFile (&opts, &state);
      }
      else {
        openAudioOutDevice (&opts, 8000);
      }
      openAudioInDevice (&opts);
    }
  else
    {
      opts.split = 0;
      opts.playoffset = 25;     // 38
      opts.delay = 0;
      openAudioInDevice (&opts);
      opts.audio_out_fd = opts.audio_in_fd;
    }

  if (opts.playfiles == 1)
    {
      playMbeFiles (&opts, &state, argc, argv);
    }
  else
    {
      liveScanner (&opts, &state);
    }
  cleanupAndExit (&opts, &state);
  return (0);
}
Beispiel #18
0
Random::Random()
{
	initState(getRandSeed());
}
Beispiel #19
0
static int test_001(TestState *state)
{
    TestState state2;
    int listener1, listener2, connection1, count, result;
    char response[1024];

    initState(&state2, "  Subtest", state);

    if (startTest(&state2, "LISTEN")) {
        if (serialRequest(&state2, "LISTEN:HTTP,/robot*"))
            checkSerialResponse(&state2, "=S,^i", &listener1);
    }

    beginGroup(&state2);

    if (startTest(&state2, "PATH of a listener")) {
        if (!skipTest(&state2) && serialRequest(&state2, "PATH:%d", listener1))
            checkSerialResponse(&state2, "=S,/robot*");
    }

    if (startTest(&state2, "Send request to WX module")) {
        if (!skipTest(&state2)) {
            if (sendRequest(&state->moduleAddr, "POST", "/robot?gto=f", "") >= 0)
                passTest(&state2, "");
            else
                failTest(&state2, "");
        }
    }

    beginGroup(&state2);

    if (startTest(&state2, "POLL for incoming POST request")) {
        if (!skipTest(&state2)) {
            do {
                if (!serialRequest(&state2, "POLL"))
                    break;
            } while (!waitAndCheckSerialResponse(&state2, "=N,0,0", "=P,^i,^i", &connection1, &listener2));
        }
    }

    beginGroup(&state2);

    if (startTest(&state2, "listener handle returned by POLL")) {
        if (listener1 == listener2)
            passTest(&state2, "");
        else
            failTest(&state2, ": got %d", listener2);
    }

    if (startTest(&state2, "PATH of a connection")) {
        if (!skipTest(&state2) && serialRequest(&state2, "PATH:%d", connection1))
            checkSerialResponse(&state2, "=S,/robot");
    }

    if (startTest(&state2, "ARG")) {
        if (!skipTest(&state2) && serialRequest(&state2, "ARG:%d,gto", connection1))
            checkSerialResponse(&state2, "=S,f");
    }

    if (startTest(&state2, "REPLY")) {
        if (!skipTest(&state2) && serialRequest(&state2, "REPLY:%d,200", connection1))
            checkSerialResponse(&state2, "=S,^i", &count);
    }

    if (startTest(&state2, "POLL for send complete")) {
        if (!skipTest(&state2)) {
            do {
                if (!serialRequest(&state2, "POLL"))
                    break;
            } while (!waitAndCheckSerialResponse(&state2, "=N,0,0", "=S,^i,0", &count, &listener2));
        }
    }

    if (startTest(&state2, "Receive response from WX")) {
        if (!skipTest(&state2)) {
            if (receiveResponse((uint8_t *)response, sizeof(response), &result) >= 0)
                passTest(&state2, "");
            else
                failTest(&state2, "");
        }
    }

    if (startTest(&state2, "CLOSE")) {
        if (!skipTest(&state2) && serialRequest(&state2, "CLOSE:%d", listener1))
            checkSerialResponse(&state2, "=S,0");
    }

    testResults(&state2);

    return state2.testPassed;
}
Beispiel #20
0
Random::Random(UInt64 seed)
{
	initState(seed);
}
Beispiel #21
0
/**
 * Executes Lyra2 based on the G function from Blake2b. This version supports salts and passwords
 * whose combined length is smaller than the size of the memory matrix, (i.e., (nRows x nCols x b) bits,
 * where "b" is the underlying sponge's bitrate). In this implementation, the "basil" is composed by all
 * integer parameters (treated as type "unsigned int") in the order they are provided, plus the value
 * of nCols, (i.e., basil = kLen || pwdlen || saltlen || timeCost || nRows || nCols).
 *
 * @param K The derived key to be output by the algorithm
 * @param kLen Desired key length
 * @param pwd User password
 * @param pwdlen Password length
 * @param salt Salt
 * @param saltlen Salt length
 * @param timeCost Parameter to determine the processing time (T)
 * @param nRows Number or rows of the memory matrix (R)
 * @param nCols Number of columns of the memory matrix (C)
 *
 * @return 0 if the key is generated correctly; -1 if there is an error (usually due to lack of memory for allocation)
 */
int LYRA2O(void *K, uint64_t kLen, const void *pwd, uint64_t pwdlen, const void *salt, uint64_t saltlen, uint64_t timeCost, uint64_t nRows, uint64_t nCols) {

    //============================= Basic variables ============================//
    int64_t row = 2; //index of row to be processed
    int64_t prev = 1; //index of prev (last row ever computed/modified)
    int64_t rowa = 0; //index of row* (a previous row, deterministically picked during Setup and randomly picked while Wandering)
    int64_t tau; //Time Loop iterator
    int64_t step = 1; //Visitation step (used during Setup and Wandering phases)
    int64_t window = 2; //Visitation window (used to define which rows can be revisited during Setup)
    int64_t gap = 1; //Modifier to the step, assuming the values 1 or -1
    int64_t i; //auxiliary iteration counter
    //==========================================================================/

    //========== Initializing the Memory Matrix and pointers to it =============//
    //Tries to allocate enough space for the whole memory matrix
    i = (int64_t) ((int64_t) nRows * (int64_t) ROW_LEN_BYTES);
    uint64_t *wholeMatrix = malloc(i);
    if (wholeMatrix == NULL) {
      return -1;
    }
	memset(wholeMatrix, 0, i);

    //Allocates pointers to each row of the matrix
    uint64_t **memMatrix = malloc(nRows * sizeof (uint64_t*));
    if (memMatrix == NULL) {
      return -1;
    }
    //Places the pointers in the correct positions
    uint64_t *ptrWord = wholeMatrix;
    for (i = 0; i < nRows; i++) {
      memMatrix[i] = ptrWord;
      ptrWord += ROW_LEN_INT64;
    }
    //==========================================================================/

    //============= Getting the password + salt + basil padded with 10*1 ===============//
    //OBS.:The memory matrix will temporarily hold the password: not for saving memory,
    //but this ensures that the password copied locally will be overwritten as soon as possible

    //First, we clean enough blocks for the password, salt, basil and padding
    uint64_t nBlocksInput = ((saltlen + pwdlen + 6 * sizeof (uint64_t)) / BLOCK_LEN_BLAKE2_SAFE_BYTES) + 1;
    byte *ptrByte = (byte*) wholeMatrix;
    memset(ptrByte, 0, nBlocksInput * BLOCK_LEN_BLAKE2_SAFE_BYTES);

    //Prepends the password
    memcpy(ptrByte, pwd, pwdlen);
    ptrByte += pwdlen;

    //Concatenates the salt
    memcpy(ptrByte, salt, saltlen);
    ptrByte += saltlen;

    //Concatenates the basil: every integer passed as parameter, in the order they are provided by the interface
    memcpy(ptrByte, &kLen, sizeof (uint64_t));
    ptrByte += sizeof (uint64_t);
    memcpy(ptrByte, &pwdlen, sizeof (uint64_t));
    ptrByte += sizeof (uint64_t);
    memcpy(ptrByte, &saltlen, sizeof (uint64_t));
    ptrByte += sizeof (uint64_t);
    memcpy(ptrByte, &timeCost, sizeof (uint64_t));
    ptrByte += sizeof (uint64_t);
    memcpy(ptrByte, &nRows, sizeof (uint64_t));
    ptrByte += sizeof (uint64_t);
    memcpy(ptrByte, &nCols, sizeof (uint64_t));
    ptrByte += sizeof (uint64_t);

    //Now comes the padding
    *ptrByte = 0x80; //first byte of padding: right after the password
    ptrByte = (byte*) wholeMatrix; //resets the pointer to the start of the memory matrix
    ptrByte += nBlocksInput * BLOCK_LEN_BLAKE2_SAFE_BYTES - 1; //sets the pointer to the correct position: end of incomplete block
    *ptrByte ^= 0x01; //last byte of padding: at the end of the last incomplete block
    //==========================================================================/

    //======================= Initializing the Sponge State ====================//
    //Sponge state: 16 uint64_t, BLOCK_LEN_INT64 words of them for the bitrate (b) and the remainder for the capacity (c)
    uint64_t *state = malloc(16 * sizeof (uint64_t));
    if (state == NULL) {
      return -1;
    }
    initState(state);
    //==========================================================================/

    //================================ Setup Phase =============================//
    //Absorbing salt, password and basil: this is the only place in which the block length is hard-coded to 512 bits
    ptrWord = wholeMatrix;
    for (i = 0; i < nBlocksInput; i++) {
      absorbBlockBlake2SafeO(state, ptrWord); //absorbs each block of pad(pwd || salt || basil)
      ptrWord += BLOCK_LEN_BLAKE2_SAFE_BYTES; //goes to next block of pad(pwd || salt || basil)
    }

    //Initializes M[0] and M[1]
    reducedSqueezeRow0O(state, memMatrix[0]); //The locally copied password is most likely overwritten here
    reducedDuplexRow1O(state, memMatrix[0], memMatrix[1]);

    do {
      //M[row] = rand; //M[row*] = M[row*] XOR rotW(rand)
      reducedDuplexRowSetupO(state, memMatrix[prev], memMatrix[rowa], memMatrix[row]);


      //updates the value of row* (deterministically picked during Setup))
      rowa = (rowa + step) & (window - 1);
      //update prev: it now points to the last row ever computed
      prev = row;
      //updates row: goes to the next row to be computed
      row++;

      //Checks if all rows in the window where visited.
      if (rowa == 0) {
      step = window + gap; //changes the step: approximately doubles its value
      window *= 2; //doubles the size of the re-visitation window
      gap = -gap; //inverts the modifier to the step
    }

    } while (row < nRows);
    //==========================================================================/

    //============================ Wandering Phase =============================//
    row = 0; //Resets the visitation to the first row of the memory matrix
    for (tau = 1; tau <= timeCost; tau++) {
    	//Step is approximately half the number of all rows of the memory matrix for an odd tau; otherwise, it is -1
    	step = (tau % 2 == 0) ? -1 : nRows / 2 - 1;
    	do {
  	    //Selects a pseudorandom index row*
  	    //------------------------------------------------------------------------------------------
  	    //rowa = ((unsigned int)state[0]) & (nRows-1);	//(USE THIS IF nRows IS A POWER OF 2)
  	    rowa = ((uint64_t) (state[0])) % nRows; //(USE THIS FOR THE "GENERIC" CASE)
  	    //------------------------------------------------------------------------------------------

  	    //Performs a reduced-round duplexing operation over M[row*] XOR M[prev], updating both M[row*] and M[row]
  	    reducedDuplexRowO(state, memMatrix[prev], memMatrix[rowa], memMatrix[row]);

  	    //update prev: it now points to the last row ever computed
  	    prev = row;

  	    //updates row: goes to the next row to be computed
  	    //------------------------------------------------------------------------------------------
  	    //row = (row + step) & (nRows-1);	//(USE THIS IF nRows IS A POWER OF 2)
  	    row = (row + step) % nRows; //(USE THIS FOR THE "GENERIC" CASE)
  	    //------------------------------------------------------------------------------------------

      } while (row != 0);
    }
    //==========================================================================/

    //============================ Wrap-up Phase ===============================//
    //Absorbs the last block of the memory matrix
    absorbBlockO(state, memMatrix[rowa]);

    //Squeezes the key
    squeezeO(state, K, kLen);
    //==========================================================================/

    //========================= Freeing the memory =============================//
    free(memMatrix);
    free(wholeMatrix);

    //Wiping out the sponge's internal state before freeing it
    memset(state, 0, 16 * sizeof (uint64_t));
    free(state);
    //==========================================================================/

    return 0;
}
ContextInfo *eglContextFromConfig(EGLDisplay *dpy, EGLConfig config) {

    EGLSurface surface = getDummyWindowSurface(dpy, config);

    EGLint contextAttrs[] = {
        EGL_CONTEXT_CLIENT_VERSION, 2,
        EGL_NONE
    };

    EGLContext context = eglCreateContext(dpy, config, NULL, contextAttrs);
    if (context == EGL_NO_CONTEXT) {
        fprintf(stderr, "eglCreateContext() failed - %d\n", eglGetError());
        return 0;
    }

    if (!eglMakeCurrent(dpy, surface, surface, context)) {
        fprintf(stderr, "eglMakeCurrent failed - %d\n", eglGetError());
        return 0;
    }
    ContextInfo *ctxInfo = NULL;

    /* Note: We are only storing the string information of a driver.
     Assuming a system with a single or homogeneous GPUs. For the case
     of heterogeneous GPUs system the string information will need to move to
     GLContext class. */
    /* allocate the structure */
    ctxInfo = (ContextInfo *) malloc(sizeof(ContextInfo));
    if (ctxInfo == NULL) {
        fprintf(stderr, "nInitialize: Failed in malloc\n");
        return 0;
    }
    /* initialize the structure */
    initializeCtxInfo(ctxInfo);

    const char *glVersion = (char *)glGetString(GL_VERSION);
    const char *glVendor = (char *)glGetString(GL_VENDOR);
    const char *glRenderer = (char *)glGetString(GL_RENDERER);
    // Make a copy, at least one platform does not preserve the string beyond the call.
    char *glExtensions = strdup((char *)glGetString(GL_EXTENSIONS));
    char *eglExtensions = strdup((char *)eglQueryString(dpy, EGL_EXTENSIONS));

    /* find out the version, major and minor version number */
    char *tmpVersionStr = strdup(glVersion);
    int versionNumbers[2];
    extractVersionInfo(tmpVersionStr, versionNumbers);
    free(tmpVersionStr);

    ctxInfo->versionStr = strdup(glVersion);
    ctxInfo->vendorStr = strdup(glVendor);
    ctxInfo->rendererStr = strdup(glRenderer);
    ctxInfo->glExtensionStr = strdup(glExtensions);
    ctxInfo->glxExtensionStr = strdup(eglExtensions);
    ctxInfo->versionNumbers[0] = versionNumbers[0];
    ctxInfo->versionNumbers[1] = versionNumbers[1];

    ctxInfo->display = getNativeDisplayType();
    ctxInfo->context = context;
    ctxInfo->egldisplay = dpy;

    // cleanup
    free(glExtensions);
    free(eglExtensions);

    // from the wrapped_egl.c
    void *handle = getLibGLEShandle();

    /* set function pointers */
    ctxInfo->glActiveTexture = (PFNGLACTIVETEXTUREPROC)
                               GET_DLSYM(handle, "glActiveTexture");
    ctxInfo->glAttachShader = (PFNGLATTACHSHADERPROC)
                              GET_DLSYM(handle, "glAttachShader");
    ctxInfo->glBindAttribLocation = (PFNGLBINDATTRIBLOCATIONPROC)
                                    GET_DLSYM(handle, "glBindAttribLocation");
    ctxInfo->glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC)
                                 GET_DLSYM(handle, "glBindFramebuffer");
    ctxInfo->glBindRenderbuffer = (PFNGLBINDRENDERBUFFERPROC)
                                  GET_DLSYM(handle, "glBindRenderbuffer");
    ctxInfo->glCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSPROC)
                                        GET_DLSYM(handle, "glCheckFramebufferStatus");
    ctxInfo->glCreateProgram = (PFNGLCREATEPROGRAMPROC)
                               GET_DLSYM(handle, "glCreateProgram");
    ctxInfo->glCreateShader = (PFNGLCREATESHADERPROC)
                              GET_DLSYM(handle, "glCreateShader");
    ctxInfo->glCompileShader = (PFNGLCOMPILESHADERPROC)
                               GET_DLSYM(handle, "glCompileShader");
    ctxInfo->glDeleteBuffers = (PFNGLDELETEBUFFERSPROC)
                               GET_DLSYM(handle, "glDeleteBuffers");
    ctxInfo->glDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC)
                                    GET_DLSYM(handle, "glDeleteFramebuffers");
    ctxInfo->glDeleteProgram = (PFNGLDELETEPROGRAMPROC)
                               GET_DLSYM(handle, "glDeleteProgram");
    ctxInfo->glDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSPROC)
                                     GET_DLSYM(handle, "glDeleteRenderbuffers");
    ctxInfo->glDeleteShader = (PFNGLDELETESHADERPROC)
                              GET_DLSYM(handle, "glDeleteShader");
    ctxInfo->glDetachShader = (PFNGLDETACHSHADERPROC)
                              GET_DLSYM(handle, "glDetachShader");
    ctxInfo->glDisableVertexAttribArray = (PFNGLDISABLEVERTEXATTRIBARRAYPROC)
                                         GET_DLSYM(handle, "glDisableVertexAttribArray");
    ctxInfo->glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)
                                         GET_DLSYM(handle, "glEnableVertexAttribArray");
    ctxInfo->glFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFERPROC)
                                         GET_DLSYM(handle, "glFramebufferRenderbuffer");
    ctxInfo->glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC)
                                      GET_DLSYM(handle, "glFramebufferTexture2D");
    ctxInfo->glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)
                                 GET_DLSYM(handle, "glGenFramebuffers");
    ctxInfo->glGenRenderbuffers = (PFNGLGENRENDERBUFFERSPROC)
                                  GET_DLSYM(handle, "glGenRenderbuffers");
    ctxInfo->glGetProgramiv = (PFNGLGETPROGRAMIVPROC)
                              GET_DLSYM(handle, "glGetProgramiv");
    ctxInfo->glGetShaderiv = (PFNGLGETSHADERIVPROC)
                             GET_DLSYM(handle, "glGetShaderiv");
    ctxInfo->glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC)
                                    GET_DLSYM(handle, "glGetUniformLocation");
    ctxInfo->glLinkProgram = (PFNGLLINKPROGRAMPROC)
                             GET_DLSYM(handle, "glLinkProgram");
    ctxInfo->glRenderbufferStorage = (PFNGLRENDERBUFFERSTORAGEPROC)
                                     GET_DLSYM(handle, "glRenderbufferStorage");
    ctxInfo->glShaderSource = (PFNGLSHADERSOURCEPROC)
                              GET_DLSYM(handle, "glShaderSource");
    ctxInfo->glUniform1f = (PFNGLUNIFORM1FPROC)
                           GET_DLSYM(handle, "glUniform1f");
    ctxInfo->glUniform2f = (PFNGLUNIFORM2FPROC)
                           GET_DLSYM(handle, "glUniform2f");
    ctxInfo->glUniform3f = (PFNGLUNIFORM3FPROC)
                           GET_DLSYM(handle, "glUniform3f");
    ctxInfo->glUniform4f = (PFNGLUNIFORM4FPROC)
                           GET_DLSYM(handle, "glUniform4f");
    ctxInfo->glUniform4fv = (PFNGLUNIFORM4FVPROC)
                            GET_DLSYM(handle, "glUniform4fv");
    ctxInfo->glUniform1i = (PFNGLUNIFORM1IPROC)
                           GET_DLSYM(handle, "glUniform1i");
    ctxInfo->glUniform2i = (PFNGLUNIFORM2IPROC)
                           GET_DLSYM(handle, "glUniform2i");
    ctxInfo->glUniform3i = (PFNGLUNIFORM3IPROC)
                           GET_DLSYM(handle, "glUniform3i");
    ctxInfo->glUniform4i = (PFNGLUNIFORM4IPROC)
                           GET_DLSYM(handle, "glUniform4i");
    ctxInfo->glUniform4iv = (PFNGLUNIFORM4IVPROC)
                            GET_DLSYM(handle, "glUniform4iv");
    ctxInfo->glUniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC)
                                  GET_DLSYM(handle, "glUniformMatrix4fv");
    ctxInfo->glUseProgram = (PFNGLUSEPROGRAMPROC)
                            GET_DLSYM(handle, "glUseProgram");
    ctxInfo->glValidateProgram = (PFNGLVALIDATEPROGRAMPROC)
                                 GET_DLSYM(handle, "glValidateProgram");
    ctxInfo->glVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC)
                                     GET_DLSYM(handle, "glVertexAttribPointer");
    ctxInfo->glGenBuffers = (PFNGLGENBUFFERSPROC)
                            GET_DLSYM(handle, "glGenBuffers");
    ctxInfo->glBindBuffer = (PFNGLBINDBUFFERPROC)
                            GET_DLSYM(handle, "glBindBuffer");
    ctxInfo->glBufferData = (PFNGLBUFFERDATAPROC)
                            GET_DLSYM(handle, "glBufferData");
    ctxInfo->glBufferSubData = (PFNGLBUFFERSUBDATAPROC)
                              GET_DLSYM(handle, "glBufferSubData");
    ctxInfo->glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)
                                  GET_DLSYM(handle, "glGetShaderInfoLog");
    ctxInfo->glGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC)
                                   GET_DLSYM(handle, "glGetProgramInfoLog");
    ctxInfo->glTexImage2DMultisample = (PFNGLTEXIMAGE2DMULTISAMPLEPROC)
                            GET_DLSYM(handle, "glTexImage2DMultisample");
    ctxInfo->glRenderbufferStorageMultisample = (PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC)
                            GET_DLSYM(handle, "glRenderbufferStorageMultisample");
    ctxInfo->glBlitFramebuffer = (PFNGLBLITFRAMEBUFFERPROC)
                            GET_DLSYM(handle, "glBlitFramebuffer");

    initState(ctxInfo);
    /* Releasing native resources */
    eglMakeCurrent(ctxInfo->egldisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
    //eglDestroySurface(ctxInfo->egldisplay, surface);
    return ctxInfo;
}
Beispiel #23
0
int main (int argc, char *argv[]) {
    // so that redirected stdout won't be insanely buffered.
    setvbuf (stdout, (char *) NULL, _IONBF, 0);

    maebot_shared_state_t sharedState;
    initState(&sharedState);
    sharedState.running = 1;

    lcm_t *lcm = lcm_create(NULL);
    if(!lcm) return EXIT_FAILURE;

    maebot_sensor_data_t_subscribe(lcm, "MAEBOT_SENSOR_DATA",
            sensor_data_handler, &sharedState);

    maebot_processed_sensor_data_t_subscribe(lcm, "MAEBOT_PROCESSED_SENSOR_DATA",
            processed_sensor_data_handler, &sharedState);

    maebot_motor_feedback_t_subscribe(lcm, "MAEBOT_MOTOR_FEEDBACK",
            motor_feedback_handler, &sharedState);

    pose_xyt_t_subscribe(lcm, "BOTLAB_ODOMETRY",
            pose_xyt_handler, &sharedState);

    pthread_t lcm_thread;
    pthread_create(&lcm_thread, NULL, lcm_handler, lcm);

    // Wait for first sensor data to come in
    //printf("Waiting for a sensor datum to come in ... ");
    waitForSensorUpdate(&sharedState.sData.utime_sama5, &sensor_data_mutex);
    //printf("Done\n");

    //printf("Waiting for a odometry datum to come in ... ");
    waitForSensorUpdate(&sharedState.oData.utime,       &sensor_data_mutex);
    //printf("Done\n");
    
   // printf("Waiting for a processed sensor datum to come in ... ");
    waitForSensorUpdate(&sharedState.pData.utime_sama5, &sensor_data_mutex);
    //printf("Done\n");

    pthread_mutex_lock(  &sensor_data_mutex);
    for(int i=0; i<3; i++) {
        sharedState.startup_int[i] = sharedState.sData.gyro_int[i];
    }
    pthread_mutex_unlock(&sensor_data_mutex);


    //pthread_t print_thread;
    //pthread_create(&print_thread, NULL, print_handler, &sharedState);

    pthread_t plot_thread;  // data for plots and graphs
    pthread_create(&plot_thread, NULL, plot_handler, &sharedState);

    for(;;){;}

    // will probably never get here, 
    // but if for some reason I do, close gracefully

    sharedState.running = 0;

    usleep(10000);   // a little time to let buffers clear
    return EXIT_SUCCESS;
}
Beispiel #24
0
 QWSPcMouseSubHandler(int f) : fd(f)
 {
     initState();
 }
Beispiel #25
0
/* run a match of numHands hands of the supplied game

   cards are dealt using rng, error conditions like timeouts
   are controlled and stored in errorInfo

   actions are read/sent to seat p on seatFD[ p ]

   if quiet is not zero, only print out errors, warnings, and final value

   if logFile is not NULL, print out a single line for each completed
   match with the final state and all player values.  The values are
   printed in player, not seat order.

   if transactionFile is not NULL, a transaction log of actions made
   is written to the file, and if there is any input left to read on
   the stream when gameLoop is called, it will be processed to
   initialise the state

   returns >=0 if the match finished correctly, -1 on error */
static int gameLoop( const Game *game, char *seatName[ MAX_PLAYERS ],
		     const uint32_t numHands, const int quiet,
		     const int fixedSeats, rng_state_t *rng,
		     ErrorInfo *errorInfo, const int seatFD[ MAX_PLAYERS ],
		     ReadBuf *readBuf[ MAX_PLAYERS ],
		     FILE *logFile, FILE *transactionFile )
{
  uint32_t handId;
  uint8_t seat, p, player0Seat, currentP, currentSeat;
  struct timeval t, sendTime, recvTime;
  Action action;
  MatchState state;
  double value[ MAX_PLAYERS ], totalValue[ MAX_PLAYERS ];

  /* check version string for each player */
  for( seat = 0; seat < game->numPlayers; ++seat ) {

    if( checkVersion( seat, readBuf[ seat ] ) < 0 ) {
      /* error messages already handled in function */

      return -1;
    }
  }

  gettimeofday( &sendTime, NULL );
  if( !quiet ) {
    fprintf( stderr, "STARTED at %zu.%06zu\n",
	     sendTime.tv_sec, sendTime.tv_usec );
  }

  /* start at the first hand */
  handId = 0;
  if( checkErrorNewHand( game, errorInfo ) < 0 ) {

    fprintf( stderr, "ERROR: unexpected game\n" );
    return -1;
  }
  initState( game, handId, &state.state );
  dealCards( game, rng, &state.state );
  for( seat = 0; seat < game->numPlayers; ++seat ) {
    totalValue[ seat ] = 0.0;
  }

  /* seat 0 is player 0 in first game */
  player0Seat = 0;

  /* process the transaction file */
  if( transactionFile != NULL ) {

    if( processTransactionFile( game, fixedSeats, &handId, &player0Seat,
				rng, errorInfo, totalValue,
				&state, transactionFile ) < 0 ) {
      /* error messages already handled in function */

      return -1;
    }
  }

  if( handId >= numHands ) {
    goto finishedGameLoop;
  }

  /* play all the (remaining) hands */
  while( 1 ) {

    /* play the hand */
    while( !stateFinished( &state.state ) ) {

      /* find the current player */
      currentP = currentPlayer( game, &state.state );

      /* send state to each player */
      for( seat = 0; seat < game->numPlayers; ++seat ) {

	state.viewingPlayer = seatToPlayer( game, player0Seat, seat );
	if( sendPlayerMessage( game, &state, quiet, seat,
			       seatFD[ seat ], &t ) < 0 ) {
	  /* error messages already handled in function */

	  return -1;
	}

	/* remember the seat and send time if player is acting */
	if( state.viewingPlayer == currentP ) {

	  sendTime = t;
	}
      }

      /* get action from current player */
      state.viewingPlayer = currentP;
      currentSeat = playerToSeat( game, player0Seat, currentP );
      if( readPlayerResponse( game, &state, quiet, currentSeat, &sendTime,
			      errorInfo, readBuf[ currentSeat ],
			      &action, &recvTime ) < 0 ) {
	/* error messages already handled in function */

	return -1;
      }

      /* log the transaction */
      if( transactionFile != NULL ) {

	if( logTransaction( game, &state.state, &action,
			    &sendTime, &recvTime, transactionFile ) < 0 ) {
	  /* error messages already handled in function */

	  return -1;
	}
      }

      /* do the action */
      doAction( game, &action, &state.state );
    }

    /* get values */
    for( p = 0; p < game->numPlayers; ++p ) {

      value[ p ] = valueOfState( game, &state.state, p );
      totalValue[ playerToSeat( game, player0Seat, p ) ] += value[ p ];
    }

    /* add the game to the log */
    if( logFile != NULL ) {

      if( addToLogFile( game, &state.state, value, player0Seat,
			seatName, logFile ) < 0 ) {
	/* error messages already handled in function */

	return -1;
      }
    }

    /* send final state to each player */
    for( seat = 0; seat < game->numPlayers; ++seat ) {

      state.viewingPlayer = seatToPlayer( game, player0Seat, seat );
      if( sendPlayerMessage( game, &state, quiet, seat,
			     seatFD[ seat ], &t ) < 0 ) {
	/* error messages already handled in function */

	return -1;
      }
    }

    if ( !quiet ) {
      if ( handId % 100 == 0) {
	for( seat = 0; seat < game->numPlayers; ++seat ) {
	  fprintf(stderr, "Seconds cumulatively spent in match for seat %i: "
		  "%i\n", seat,
		  (int)(errorInfo->usedMatchMicros[ seat ] / 1000000));
	}
      }
    }

    /* start a new hand */
    if( setUpNewHand( game, fixedSeats, &handId, &player0Seat,
		      rng, errorInfo, &state.state ) < 0 ) {
      /* error messages already handled in function */

      return -1;
    }
    if( handId >= numHands ) {
      break;
    }
  }

 finishedGameLoop:
  /* print out the final values */
  if( !quiet ) {
    gettimeofday( &t, NULL );
    fprintf( stderr, "FINISHED at %zu.%06zu\n",
	     sendTime.tv_sec, sendTime.tv_usec );
  }
  if( printFinalMessage( game, seatName, totalValue, logFile ) < 0 ) {
    /* error messages already handled in function */

    return -1;
  }

  return 0;
}
int main(int argc, char* argv[]) {

    double discountFactor = 0.9;

    FILE* initFileFd = NULL;
    double* setPoints = NULL;
    unsigned int nbSetPoints = 0;
    unsigned int maxDepth = 0;
    FILE* results = NULL;
    char str[1024];
    unsigned int i = 0;
    unsigned int minDepth = 1;
    unsigned int crtDepth = 0;
    unsigned int maxNbIterations = 0;
    unsigned int nbSteps = 0;
    unsigned int timestamp = time(NULL);
    int readFscanf = -1;

    optimistic_instance* optimistic = NULL;
    random_search_instance* random_search = NULL;
    uct_instance* uct = NULL;
    uniform_instance* uniform = NULL;

    struct arg_file* initFile = arg_file1(NULL, "init", "<file>", "File containing the set points");
    struct arg_int* d2 = arg_int0(NULL, "min", "<n>", "Minimum depth to start from (min>0)");
    struct arg_int* d = arg_int1("d", NULL, "<n>", "Maximum depth of an uniform tree which the number of call per step");
    struct arg_int* s = arg_int1("s", NULL, "<n>", "Number of steps");
    struct arg_int* k = arg_int1("k", NULL, "<n>", "Branching factor of the problem");
    struct arg_file* where = arg_file1(NULL, "where", "<file>", "Directory where we save the outputs");
    struct arg_end* end = arg_end(7);

    int nerrors = 0;
    void* argtable[7];

    argtable[0] = initFile;
    argtable[1] = d2;
    argtable[2] = d;
    argtable[3] = s;
    argtable[4] = k;
    argtable[5] = where;
    argtable[6] = end;

    if(arg_nullcheck(argtable) != 0) {
        printf("error: insufficient memory\n");
        arg_freetable(argtable, 7);
        return EXIT_FAILURE;
    }

    nerrors = arg_parse(argc, argv, argtable);

    if(nerrors > 0) {
        printf("%s:", argv[0]);
        arg_print_syntax(stdout, argtable, "\n");
        arg_print_errors(stdout, end, argv[0]);
        arg_freetable(argtable, 7);
        return EXIT_FAILURE;
    }

    initGenerativeModelParameters();
    K = k->ival[0];
    initGenerativeModel();

    initFileFd = fopen(initFile->filename[0], "r");
    readFscanf = fscanf(initFileFd, "%u\n", &nbSetPoints);
    setPoints = (double*)malloc(sizeof(double) * nbSetPoints);
    
    for(; i < nbSetPoints; i++) {
        readFscanf = fscanf(initFileFd, "%s\n", str);
        setPoints[i] = strtod(str, NULL);
    }
    fclose(initFileFd);

    if(d2->count)
        minDepth = d2->ival[0];
    maxDepth = d->ival[0];
    maxNbIterations = K;
    nbSteps = s->ival[0];

    optimistic = optimistic_initInstance(NULL, discountFactor);
    random_search = random_search_initInstance(NULL, discountFactor);
    uct = uct_initInstance(NULL, discountFactor);
    uniform = uniform_initInstance(NULL, discountFactor);

    sprintf(str, "%s/%u_results_%u_%u.csv", where->filename[0], timestamp, K, nbSteps);
    results = fopen(str, "w");

    for(crtDepth = 1; crtDepth < minDepth; crtDepth++)
        maxNbIterations += pow(K, crtDepth+1);

    for(crtDepth = minDepth; crtDepth <= maxDepth; crtDepth++) {
        double averages[4] = {0.0, 0.0, 0.0, 0.0};
        state* crt1 = initState();
        state* crt2 = copyState(crt1);
        state* crt3 = copyState(crt1);
        state* crt4 = copyState(crt1);

        optimistic_resetInstance(optimistic, crt1);
        uct_resetInstance(uct, crt3);
        uniform_resetInstance(uniform, crt4);
        for(i = 0; i < nbSetPoints; i++) {
            unsigned int j = 0;

            parameters[10] = setPoints[i];

            for(; j < nbSteps; j++) {
                char isTerminal = 0;
                double reward = 0.0;
                state* nextState = NULL;

                optimistic_keepSubtree(optimistic);
                action* optimalAction = optimistic_planning(optimistic, maxNbIterations);
                isTerminal = nextStateReward(crt1, optimalAction, &nextState, &reward);
                freeState(crt1);
                crt1 = nextState;
                averages[0] += reward;
                if(isTerminal < 0)
                    break;
            }
            optimistic_resetInstance(optimistic, crt1);

            printf("Optimistic   : %uth set point processed\n", i + 1);

            for(j = 0; j < nbSteps; j++) {
                char isTerminal = 0;
                double reward = 0.0;
                state* nextState = NULL;

                random_search_resetInstance(random_search, crt2);
                action* optimalAction = random_search_planning(random_search, maxNbIterations);
                isTerminal = nextStateReward(crt2, optimalAction, &nextState, &reward);
                freeState(crt2);
                crt2 = nextState;
                averages[1] += reward;
                if(isTerminal < 0)
                    break;
            }
            random_search_resetInstance(random_search, crt1);

            printf("Random search: %uth set point processed\n", i + 1);

            for(j = 0; j < nbSteps; j++) {
                char isTerminal = 0;
                double reward = 0.0;
                state* nextState = NULL;

                uct_keepSubtree(uct);
                action* optimalAction = uct_planning(uct, maxNbIterations);
                isTerminal = nextStateReward(crt3, optimalAction, &nextState, &reward);
                freeState(crt3);
                crt3 = nextState;
                averages[2] += reward;
                if(isTerminal < 0)
                    break;
            }
            uct_resetInstance(uct, crt3);

            printf("Uct          : %uth set point processed\n", i + 1);

            for(j = 0; j < nbSteps; j++) {
                char isTerminal = 0;
                double reward = 0.0;
                state* nextState = NULL;

                uniform_keepSubtree(uniform);
                action* optimalAction = uniform_planning(uniform, maxNbIterations);
                isTerminal = nextStateReward(crt4, optimalAction, &nextState, &reward);
                freeState(crt4);
                crt4 = nextState;
                averages[3] += reward;
                if(isTerminal < 0)
                    break;
            }
            uniform_resetInstance(uniform, crt4);

            printf("Uniform      : %uth set point processed\n", i + 1);
            printf(">>>>>>>>>>>>>> %uth set point processed\n", i + 1);

        }

        fprintf(results, "%u,%.15f,%.15f,%.15f,%.15f\n", maxNbIterations, averages[0] / (double)nbSetPoints, averages[1] / (double)nbSetPoints, averages[2] / (double)nbSetPoints, averages[3] / (double)nbSetPoints);
        fflush(results);
        freeState(crt1);
        freeState(crt2);
        freeState(crt3);
        freeState(crt4);

        printf(">>>>>>>>>>>>>> %u depth done\n\n", crtDepth);

        maxNbIterations += pow(K, crtDepth+1);

    }

    fclose(results);

    arg_freetable(argtable, 7);

    free(setPoints);

    optimistic_uninitInstance(&optimistic);
    random_search_uninitInstance(&random_search);
    uct_uninitInstance(&uct);
    uniform_uninitInstance(&uniform);

    freeGenerativeModel();
    freeGenerativeModelParameters();

    return EXIT_SUCCESS;

}
Beispiel #27
0
/**
 * Executes Lyra2 based on the G function from Blake2b or BlaMka. This version supports salts and passwords
 * whose combined length is smaller than the size of the memory matrix, (i.e., (nRows x nCols x b) bits,
 * where "b" is the underlying sponge's bitrate). In this implementation, the "params" is composed by all 
 * integer parameters (treated as type "unsigned int") in the order they are provided, plus the value 
 * of nCols, (i.e., params = kLen || pwdlen || saltlen || timeCost || nRows || nCols).
 *
 * @param K The derived key to be output by the algorithm
 * @param kLen Desired key length
 * @param pwd User password
 * @param pwdlen Password length
 * @param salt Salt
 * @param saltlen Salt length
 * @param timeCost Parameter to determine the processing time (T)
 * @param nRows Number or rows of the memory matrix (R)
 * @param nCols Number of columns of the memory matrix (C)
 *
 * @return 0 if the key is generated correctly; -1 if there is an error (usually due to lack of memory for allocation)
 */
int LYRA2_multiThread(void *K, unsigned int kLen, const void *pwd, unsigned int pwdlen, const void *salt, unsigned int saltlen, unsigned int timeCost, unsigned int nRows, unsigned int nCols){

    //============================= Basic variables ============================//
    uint64_t i,j;        //auxiliary iteration counter
    //==========================================================================/

    //========== Initializing the Memory Matrix and pointers to it =============//
    //Allocates pointers to each row of the matrix
    __m128i **memMatrix = malloc(nRows * sizeof (uint64_t*));
    if (memMatrix == NULL) {
        return -1;
    }
    //Allocates pointers to each key
    unsigned char **pKeys = malloc(nPARALLEL * sizeof (unsigned char*));
    if (pKeys == NULL) {
        return -1;
    }

    if (nRows < 3)
      return -1;
    if (timeCost < 1)
      return -1;

#if _OPENMP <= 201107  //OpenMP 3.X or less 
    #pragma omp parallel num_threads(nPARALLEL) default(none) /*private(pwd)*/ shared(memMatrix,  pKeys, pwd, pwdlen, salt, saltlen, nRows, nCols, kLen, timeCost, nPARALLEL)
#endif // _OPENMP

#if _OPENMP > 201107  //OpenMP 4.0
    #pragma omp parallel proc_bind(spread) num_threads(nPARALLEL) default(none) /*private(pwd)*/ shared(memMatrix,  pKeys, pwd, pwdlen, salt, saltlen, nRows, nCols, kLen, timeCost, nPARALLEL)
#endif // _OPENMP
    {
        //============================= Basic threads variables ============================//
        int64_t gap = 1;                //Modifier to the step, assuming the values 1 or -1
        uint64_t step = 1;              //Visitation step (used during Setup and Wandering phases)
        uint64_t window = 2;            //Visitation window (used to define which rows can be revisited during Setup)
        uint64_t sync = 4;              //Synchronize counter
        uint64_t sqrt = 2;              //Square of window (i.e., square(window)), when a window is a square number;
                                        //otherwise, sqrt = 2*square(window/2) 
          

        uint64_t row0 = 3;              //row0: sequentially written during Setup; randomly picked during Wandering
        uint64_t prev0 = 2;             //prev0: stores the previous value of row0
        uint64_t rowP = 1;              //rowP: revisited during Setup, and then read [and written]; randomly picked during Wandering
        uint64_t prevP = 0;             //prevP: stores the previous value of rowP

        uint64_t threadNumber = 0;
        uint64_t iP;
        uint64_t jP;                     //Starts with threadNumber.
        uint64_t kP;
        uint64_t wCont;
        
        uint64_t sizeSlicedRows;
        uint64_t off0;
        uint64_t offP;
        //==========================================================================/

        //========================== BootStrapping Phase ==========================//
        // Size of each chunk that each thread will work with
        sizeSlicedRows = nRows/nPARALLEL;
        // Thread index:
        threadNumber = omp_get_thread_num();
        
        uint64_t sliceStart = threadNumber*sizeSlicedRows;
        uint64_t halfSlice = sizeSlicedRows/2;

        iP = (uint64_t) ((uint64_t) sizeSlicedRows * (uint64_t) ROW_LEN_BYTES);
        __m128i *threadSliceMatrix = malloc(iP);
        if (threadSliceMatrix == NULL) {
            printf("Error: unable to allocate memory (nRows too large?)\n");
            exit(EXIT_FAILURE);
        }
        //Places the pointers in the correct positions
        __m128i *ptrWord = threadSliceMatrix;
        for (kP = 0; kP < sizeSlicedRows; kP++) {
            memMatrix[threadNumber*sizeSlicedRows + kP] = ptrWord;
            ptrWord += ROW_LEN_INT128;
        }

        unsigned char *threadKey =  malloc(kLen);
        if (threadKey == NULL) {
            exit(EXIT_FAILURE);
        }

        //Places the pointers in the correct positions
        pKeys[threadNumber] = threadKey;
        
        //==========================================================================/

        //============= Padding (password + salt + params) with 10*1 ===============//

        //OBS.:The memory matrix will temporarily hold the password: not for saving memory,
        //but this ensures that the password copied locally will be overwritten as soon as possible

        //First, we clean enough blocks for the password, salt, params and padding
        //Change the ''8'' if different amounts of parameters were passed 
        uint64_t nBlocksInput = ((pwdlen + saltlen + 8 * sizeof (int)) / BLOCK_LEN_BLAKE2_SAFE_BYTES) + 1;
        byte *ptrByte = (byte*) threadSliceMatrix;
        memset(ptrByte, 0, nBlocksInput * BLOCK_LEN_BLAKE2_SAFE_BYTES);
        
        //Prepends the password
        memcpy(ptrByte, pwd, pwdlen);
        ptrByte += pwdlen;

        //Concatenates the salt
        memcpy(ptrByte, salt, saltlen);
        ptrByte += saltlen;
        
        //Concatenates the params: every integer passed as parameter, in the order they are provided by the interface        
        memcpy(ptrByte, &kLen, sizeof (int));
        ptrByte += sizeof (int);
        memcpy(ptrByte, &pwdlen, sizeof (int));
        ptrByte += sizeof (int);
        memcpy(ptrByte, &saltlen, sizeof (int));
        ptrByte += sizeof (int);
        memcpy(ptrByte, &timeCost, sizeof (int));
        ptrByte += sizeof (int);
        memcpy(ptrByte, &nRows, sizeof (int));
        ptrByte += sizeof (int);
        memcpy(ptrByte, &nCols, sizeof (int));
        ptrByte += sizeof (int);
        int p = nPARALLEL;
        memcpy(ptrByte, &p, sizeof (int));
        ptrByte += sizeof (int);
        memcpy(ptrByte, &threadNumber, sizeof (int));
        ptrByte += sizeof (int);// */

        //Now comes the padding
        *ptrByte = 0x80;                                                //first byte of padding: right after the password
        ptrByte = (byte*) threadSliceMatrix;                            //resets the pointer to the start of the memory matrix
        ptrByte += nBlocksInput * BLOCK_LEN_BLAKE2_SAFE_BYTES - 1;      //sets the pointer to the correct position: end of incomplete block
        *ptrByte ^= 0x01;                                               //last byte of padding: at the end of the last incomplete block
        
        //==========================================================================/        
        
        //============== Initializing the Sponge State =============/
        //Sponge state: 8 __m128i, BLOCK_LEN_INT128 words of them for the bitrate (b) and the remainder for the capacity (c)
        //Thread State
        __m128i *threadState = malloc(8 * sizeof (__m128i));
        if (threadState == NULL) {
            exit(EXIT_FAILURE);
        }
        initState(threadState);
        
        //==========================================================================/ 
                
        //============= Absorbing the input data with the sponge ===============//

        //Absorbing salt, password and params: this is the only place in which the block length is hard-coded to 512 bits, for compatibility with Blake2b and BlaMka
        ptrWord = threadSliceMatrix;
        for (kP = 0; kP < nBlocksInput; kP++) {
            absorbBlockBlake2Safe(threadState, ptrWord);        //absorbs each block of pad(pwd || salt || params)
            ptrWord += BLOCK_LEN_BLAKE2_SAFE_INT128;            //goes to next block of pad(pwd || salt || params)
        }
        
        //================================================================================/

        //================================ Setup Phase ==================================//
        //==Initializes a (nRows x nCols) memory matrix, it's cells having b bits each)==//
        
        //Initializes M[0]
        reducedSqueezeRow0(threadState, memMatrix[sliceStart]);               //The locally copied password is most likely overwritten here
        //Initializes M[1]
        reducedDuplexRow1and2(threadState, memMatrix[sliceStart], memMatrix[sliceStart+1]);
        //Initializes M[2]
        reducedDuplexRow1and2(threadState, memMatrix[sliceStart + 1], memMatrix[sliceStart + 2]);
        
        jP = threadNumber;

        //Filling Loop
        for (row0 = 3; row0 < sizeSlicedRows; row0++) {
            //Performs a reduced-round duplexing operation over "Mj[rowP][col] [+] Mi[prev0][col] [+] Mj[prevP][col]", filling Mi[row0] and updating Mj[rowP]
            //Mi[row0][N_COLS-1-col] = Mi[prev0][col] XOR rand;
            //Mj[rowP][col] = Mj[rowP][col] XOR rot(rand)                    rot(): right rotation by 'omega' bits (e.g., 1 or more words)
            reducedDuplexRowFilling(threadState, memMatrix[jP*sizeSlicedRows + rowP], memMatrix[sliceStart + prev0], memMatrix[jP*sizeSlicedRows + prevP], memMatrix[sliceStart + row0]);

            //Updates the "prev" indices: the rows more recently updated
            prev0 = row0;
            prevP = rowP;

            //updates the value of rowP: deterministically picked, with a variable step
            rowP = (rowP + step) & (window - 1);

            //Checks if all rows in the window where visited.
            if (rowP == 0) {
                window *= 2;                    //doubles the size of the re-visitation window
                step = sqrt + gap;              //changes the step: approximately doubles its value
                gap = -gap;                     //inverts the modifier to the step
                if (gap == -1){
                    sqrt *= 2;                  //Doubles sqrt every other iteration
                }
            } 
            //Synchronize threads and change the slices
            if (row0 == sync) {
                sync += sqrt/2;
                jP = (jP + 1) % nPARALLEL;
                #pragma omp barrier
            }
        }
        
        // Needs all matrix done before starting Wandering Phase.
        #pragma omp barrier
        
        //============================ Wandering Phase =============================//
        //=====Iteratively overwrites pseudorandom cells of the memory matrix=======//
        window = halfSlice;
        sync = sqrt;
        off0 = 0;
        offP = window;
        uint64_t offTemp;    
        
        //Visitation Loop
        for (wCont = 0; wCont < timeCost*sizeSlicedRows; wCont++){                
            //Selects a pseudorandom indices row0 and rowP 
            //------------------------------------------------------------------------------------------
            /*(USE THIS IF window IS A POWER OF 2)*/
            //row0  = off0 + (((uint64_t)(((__uint128_t *)threadState)[0])) & (window-1));
            //rowP = offP + (((uint64_t)(((__uint128_t *)threadState)[1])) & (window-1));
            /*(USE THIS FOR THE "GENERIC" CASE)*/
            row0 = off0 + (((uint64_t)(((__uint128_t *)threadState)[0])) % window);             //row0 = off0 + (lsw(rand) mod window)
            rowP = offP + (((uint64_t)(((__uint128_t *)threadState)[1])) % window);             //row1 = offP + (lsw(rot(rand)) mod window)

            //Selects a pseudorandom indices j0 (LSW(rot^2 (rand)) mod p)
            jP = ((uint64_t)(((__uint128_t *)threadState)[2])) % nPARALLEL;                     //jP = lsw(rot^2(rand)) mod nPARALLEL

            //Performs a reduced-round duplexing operation over "Mi[row0][col] [+] Mj[rowP][col] [+] Mi[prev0][col0]", updating Mi[row0]
            //Mi[row0][col] = Mi[row0][col] XOR rand;
            reducedDuplexRowWanderingParallel(threadState, memMatrix[sliceStart + row0], memMatrix[jP*sizeSlicedRows + rowP], memMatrix[sliceStart + prev0]);

            //update prev: they now point to the last rows ever updated
            prev0 = row0;
            
            //Synchronize threads and change the slices
            if (wCont == sync) { 
                sync += sqrt;
                offTemp = off0;
                off0 = offP;
                offP = offTemp;
                #pragma omp barrier
            }
        }
        #pragma omp barrier
        
        //==========================================================================/

        //============================ Wrap-up Phase ===============================//
        //========================= Output computation =============================//
        //Absorbs one last block of the memory matrix with the full-round sponge
        absorbColumn(threadState,  memMatrix[sliceStart + row0]);

        //Squeezes the key
        squeeze(threadState, threadKey, kLen);

        //========================= Freeing the thread memory =============================//
        free(threadSliceMatrix);

        //Wiping out the sponge's internal state before freeing it
        memset(threadState, 0, 8 * sizeof (__m128i));
        free(threadState);
    } // Parallelism End
    
    // XORs all Keys
    for (i = 1; i < nPARALLEL; i++) {
        for (j = 0; j < kLen; j++) {
            pKeys[0][j] ^= pKeys[i][j];
        }
    }

    // Returns in the correct variable
    memcpy(K, pKeys[0], kLen);


    //========================= Freeing the memory =============================//
    free(memMatrix);

    //Free each thread Key
    for (i = 0; i < nPARALLEL; i++) {
        free(pKeys[i]);
    }
    //Free the pointers to allKeys
    free(pKeys);
    
    //==========================================================================/

    return 0;
}
Beispiel #28
0
static void dumpLines( const uint_8 *input, uint length )
{
    const uint_8    *p;
    uint            opcode_base;
    uint            *opcode_lengths;
    uint            u;
    uint            file_index;
    const uint_8    *name;
    uint_32         dir_index;
    uint_32         mod_time;
    uint_32         file_length;
    uint_32         directory;
    uint_8          op_code;
    uint_8          op_len;
    uint_32         tmp;
    uint_16         tmp_seg;
    uint            line_range;
    int             line_base;
    int_32          itmp;
    int             default_is_stmt;
    state_info      state;
    uint            min_instr;
    uint_32         unit_length;
    const uint_8    *unit_base;

    p = input;
    while( p - input < length ) {
        unit_length = getU32( (uint_32 *)p );
        p += sizeof( uint_32 );
        unit_base = p;

        printf( "total_length: 0x%08lx (%u)\n", unit_length, unit_length );

        printf( "=== unit dump start ===\n" );
        dumpHex( unit_base - sizeof( uint_32 ), unit_length + sizeof (uint_32 ), 1 );
        printf( "=== unit dump end ===\n" );

        printf( "version: 0x%04x\n", getU16( (uint_16 *)p ) );
        p += sizeof( uint_16 );

        printf( "prologue_length: 0x%08lx (%u)\n", getU32( (uint_32 *)p ), getU32( (uint_32 *)p ) );
        p += sizeof( uint_32 );

        min_instr = *p;
        printf( "minimum_instruction_length: 0x%02x (%u)\n", min_instr, min_instr );
        p += 1;

        default_is_stmt = *p;
        printf( "default_is_stmt: 0x%02x (%u)\n", default_is_stmt, default_is_stmt );
        p += 1;

        line_base = *(int_8 *)p;
        printf( "line_base: 0x%02x (%d)\n", (unsigned char)line_base, line_base );
        p += 1;

        line_range = *(uint_8 *)p;
        printf( "line_range: 0x%02x (%u)\n", line_range, line_range );
        p += 1;

        opcode_base = *p;
        printf( "opcode_base: 0x%02x (%u)\n", opcode_base, opcode_base );
        p += 1;
        opcode_lengths = alloca( sizeof( uint ) * opcode_base );
        printf( "standard_opcode_lengths:\n" );
        for( u = 0; u < opcode_base - 1; ++u ) {
            opcode_lengths[u] = *p;
            ++p;
            printf( "%4u: %u\n", u + 1, opcode_lengths[u] );
        }

        printf( "-- current_offset = %08x\n", p - input );

        if( p - input >= length )
            return;

        printf( "-- start include paths --\n");
        file_index = 0;
        while( *p != 0 ) {
            ++file_index;
            name = p;
            p += strlen( (const char *)p ) + 1;
            printf( "path %u: '%s'\n", file_index, name );
            if( p - input >= length ) {
                return;
            }
        }
        printf( "-- end include paths --\n");
        p++;
        printf( "-- start files --\n");
        file_index = 0;
        while( *p != 0 ) {
            ++file_index;
            name = p;
            p += strlen( (const char *)p ) + 1;
            p = DecodeULEB128( p, &dir_index );
            p = DecodeULEB128( p, &mod_time );
            p = DecodeULEB128( p, &file_length );
            printf( "file %u: '%s' dir_index %08lx mod_time %08lx length %08lx\n",
                file_index, name, dir_index, mod_time, file_length );
            if( p - input >= length ) {
                return;
            }
        }
        printf( "-- end files --\n");
        p++;
        initState( &state, default_is_stmt );

        while( p - unit_base < unit_length ) {
            op_code = *p;
            ++p;
            if( op_code == 0 ) {
                printf( "EXTENDED 0x%02x: ", op_code );
                /* extended op_code */
                op_len = *p;
                ++p;
                printf( "len: %03d ", op_len );
                op_code = *p;
                ++p;
                switch( op_code ) {
                case DW_LNE_end_sequence:
                    printf( "END_SEQUENCE\n" );
                    state.end_sequence = 1;
                    dumpState( &state );
                    initState( &state, default_is_stmt );
                    break;
                case DW_LNE_set_address:
                    if( op_len == 3 ) {
                        tmp = getU16( (uint_16 *)p );
                        p += sizeof( uint_16 );
                    } else {
                        tmp = getU32( (uint_32 *)p );
                        p += sizeof( uint_32 );
                    }
#if 0   /* Why did they choose 6 byte here?  */
                    tmp_seg = getU16( (uint_16 *)p );
                    p += sizeof( uint_16 );
                    printf( "SET_ADDRESS %04x:%08lx\n", tmp_seg, tmp );
#else
                    tmp_seg = 0;    /* stop warning */
                    printf( "SET_ADDRESS %08lx\n", tmp );
#endif
                    break;
                case DW_LNE_WATCOM_set_segment_OLD:
                case DW_LNE_WATCOM_set_segment:
                    tmp_seg = getU16( (uint_16 *)p );
                    p += sizeof( uint_16 );
                    printf( "SET_ADDRESS_SEG %04x\n", tmp_seg );
                    break;
                case DW_LNE_define_file:
                    ++file_index;
                    name = p;
                    p += strlen( (const char *)p ) + 1;
                    p = DecodeULEB128( p, &directory );
                    p = DecodeULEB128( p, &mod_time );
                    p = DecodeULEB128( p, &file_length );
                    printf( "DEFINE_FILE %u: '%s' directory %ld mod_time %08lx length %08lx\n",
                        file_index, name, directory, mod_time, file_length );
                    break;
                default:
                    printf( "** unknown extended opcode: %02x - %u bytes\n", op_code, op_len );
                    printf( "** losing %u bytes\n", unit_length - ( p - unit_base ));

                    dumpHex( p-3, (unit_length - ( p - unit_base )) + 3, 1 );

                    p = unit_base + unit_length;
                    goto hacky;
//                    return;
                }
            } else if( op_code < opcode_base ) {
                printf( "%s", getStandardOp( op_code ) );
                switch( op_code ) {
                case DW_LNS_copy:
                    printf( "\n" );
                    dumpState( &state );
                    state.basic_block = 0;
                    break;
                case DW_LNS_advance_pc:
                    p = DecodeLEB128( p, &itmp );
                    printf( " %ld\n", itmp );
                    state.address += itmp * min_instr;
                    break;
                case DW_LNS_advance_line:
                    p = DecodeLEB128( p, &itmp );
                    printf( " %ld\n", itmp );
                    state.line += itmp;
                    break;
                case DW_LNS_set_file:
                    p = DecodeLEB128( p, &itmp );
                    printf( " %ld\n", itmp );
                    state.file = itmp;
                    break;
                case DW_LNS_set_column:
                    p = DecodeLEB128( p, &itmp );
                    printf( " %ld\n", itmp );
                    state.column = itmp;
                    break;
                case DW_LNS_negate_stmt:
                    printf( "\n" );
                    state.is_stmt = !state.is_stmt;
                    break;
                case DW_LNS_set_basic_block:
                    printf( "\n" );
                    state.basic_block = 1;
                    break;
                case DW_LNS_const_add_pc:
                    printf( "\n" );
                    state.address += ( ( 255 - opcode_base ) / line_range ) * min_instr;
                    break;
                case DW_LNS_fixed_advance_pc:
                    tmp = getU16( (uint_16 *)p );
                    p += sizeof( uint_16 );
                    printf( " %04x\n", tmp );
                    state.address += tmp;
                    break;
                default:
                    for( u = 0; u < opcode_lengths[op_code - 1]; ++u ) {
                        p = DecodeLEB128( p, &itmp );
                        printf( " %08lx", itmp );
                    }
                    printf( "\n" );
                }
            } else {
                printf( "SPECIAL 0x%02x:", op_code );
                op_code -= opcode_base;
                printf( " addr incr: %d  line incr: %d\n",
                    op_code / line_range,
                    line_base + op_code % line_range );
                state.line += line_base + op_code % line_range;
                state.address += ( op_code / line_range ) * min_instr;
                dumpState( &state );
                state.basic_block = 0;
            }
        }
hacky:
        printf( "-- current_offset = %08x\n", p - input );
    }
}
Beispiel #29
0
NpcScriptInterface::NpcScriptInterface() :
	LuaScriptInterface("Npc interface")
{
	m_libLoaded = false;
	initState();
}
Beispiel #30
0
const char * StrucViewItem::typeStr(void)
//---------------------------------------
{
    initState();
    return _type;
}