Ejemplo n.º 1
0
/*! \fn static void md5_transform(u32 *hash, u32 const *in)
 *  \ingroup IFX_MD5_FUNCTIONS
 *  \brief main interface to md5 hardware   
 *  \param hash current hash value  
 *  \param in 64-byte block of input  
*/                                 
static void md5_transform(struct md5_ctx *mctx, u32 *hash, u32 const *in)
{
    int i;
    volatile struct deu_hash_t *hashs = (struct deu_hash_t *) HASH_START;
    unsigned long flag;

    CRTCL_SECT_START;

    if (mctx->started) { 
        hashs->D1R = endian_swap(*((u32 *) hash + 0));
    	hashs->D2R = endian_swap(*((u32 *) hash + 1));
        hashs->D3R = endian_swap(*((u32 *) hash + 2));
        hashs->D4R = endian_swap(*((u32 *) hash + 3));
    }

    for (i = 0; i < 16; i++) {
        hashs->MR = endian_swap(in[i]);
//	printk("in[%d]: %08x\n", i, endian_swap(in[i]));
    };

    //wait for processing
    while (hashs->controlr.BSY) {
        // this will not take long
    }

    *((u32 *) hash + 0) = endian_swap (hashs->D1R);
    *((u32 *) hash + 1) = endian_swap (hashs->D2R);
    *((u32 *) hash + 2) = endian_swap (hashs->D3R);
    *((u32 *) hash + 3) = endian_swap (hashs->D4R);

    mctx->started = 1; 

    CRTCL_SECT_END;
}
Ejemplo n.º 2
0
void memory_dump_state(memory_t* memory) {
  printf("Non-zero memory:\n");
  for (uint32_t i = 0; i <= (memory->size - 4); i += 4) {
    uint32_t value = memory_read(memory, i);
    if (value) {
      printf("0x%08x: 0x%08x\n", i, endian_swap(value));
    }
  }
}
Ejemplo n.º 3
0
/*! \fn static void md5_final(struct crypto_tfm *tfm, u8 *out)
 *  \ingroup IFX_MD5_FUNCTIONS
 *  \brief compute final md5 value   
 *  \param tfm linux crypto algo transform  
 *  \param out final md5 output value  
*/                                 
static int md5_final(struct shash_desc *desc, u8 *out)
{
    struct md5_ctx *mctx = shash_desc_ctx(desc);
    const unsigned int offset = mctx->byte_count & 0x3f;
    char *p = (char *)mctx->block + offset;
    int padding = 56 - (offset + 1);
    volatile struct deu_hash_t *hashs = (struct deu_hash_t *) HASH_START;
    unsigned long flag;

    *p++ = 0x80;
    if (padding < 0) {
        memset(p, 0x00, padding + sizeof (u64));
        md5_transform_helper(mctx);
        p = (char *)mctx->block;
        padding = 56;
    }

    memset(p, 0, padding);
    mctx->block[14] = endian_swap(mctx->byte_count << 3);
    mctx->block[15] = endian_swap(mctx->byte_count >> 29);

#if 0
    le32_to_cpu_array(mctx->block, (sizeof(mctx->block) -
                      sizeof(u64)) / sizeof(u32));
#endif

    md5_transform(mctx, mctx->hash, mctx->block);                                                 

    CRTCL_SECT_START;

    *((u32 *) out + 0) = endian_swap (hashs->D1R);
    *((u32 *) out + 1) = endian_swap (hashs->D2R);
    *((u32 *) out + 2) = endian_swap (hashs->D3R);
    *((u32 *) out + 3) = endian_swap (hashs->D4R);

    CRTCL_SECT_END;

    // Wipe context
    memset(mctx, 0, sizeof(*mctx));

    return 0;
}
Ejemplo n.º 4
0
int read_pwm(uint16_t *pwm_signal_ptr){
	unsigned char  DataBuf[PWM_BYTES];

	// Poll Ardupilot for 8 bytes of data (4 channels)
	if(PWM_BYTES != cyg_i2c_rx(&ATMEGA328_PWM, &DataBuf[0], PWM_BYTES)){
		fprintf(stderr,"\n read_pwm: PWM_BYTES bytes not read");
		return 0;
	}
	endian_swap(&DataBuf[0],0,PWM_BYTES); // swap bytes
	memcpy(pwm_signal_ptr,&DataBuf,PWM_BYTES); // copy to uint16_t array

	return 1;
}
Ejemplo n.º 5
0
void fitstable_endian_flip_row_data(fitstable_t* table, void* data) {
	int i;
	char* cursor;
	if (!need_endian_flip())
		return;
	cursor = data;
	for (i=0; i<ncols(table); i++) {
		int j;
		fitscol_t* col = getcol(table, i);
		for (j=0; j<col->arraysize; j++) {
			endian_swap(cursor, col->fitssize);
			cursor += col->fitssize;
		}
	}
}
Ejemplo n.º 6
0
Uint16 FileAccess::get_word() {
	ERR_FAIL_COND_V(!f,0);

	ERR_FAIL_COND_V( !(current_mode&READ ) , 0 );

	Uint8 aux_byte1=get_byte();
	Uint8 aux_byte2=get_byte();
	
	endian_swap(aux_byte1,aux_byte2);

	Uint16 ret=aux_byte2;
	ret<<=8;
	ret|=aux_byte1;

	return ret;
}
Ejemplo n.º 7
0
Uint32 FileAccess::get_dword() {
	ERR_FAIL_COND_V(!f,0);

	ERR_FAIL_COND_V( !(current_mode&READ ) , 0 );

	Uint16 aux_word1 = get_word();
	Uint16 aux_word2 = get_word();

	endian_swap(aux_word1,aux_word2);
	
	Uint32 ret=aux_word2;
	ret<<=16;
	ret|=aux_word1;
	
	return ret;

}
Ejemplo n.º 8
0
/** Read 1 float/double based on precision, swap bytes if big endian. */
int Traj_GmxTrX::read_real( float& fval ) {
    double dval;
    switch (precision_) {
    case sizeof(float):
        if (file_.Read( &fval, precision_ ) != precision_) return 1;
        if (isBigEndian_) endian_swap( &fval, 1 );
        break;
    case sizeof(double):
        if (file_.Read( &dval, precision_ ) != precision_) return 1;
        if (isBigEndian_) endian_swap8( &dval, 1 );
        fval = (float)dval;
        break;
    default:
        return 1;
    }
    return 0;
}
Ejemplo n.º 9
0
/** \return true if TRR/TRJ file. Determine endianness. */
bool Traj_GmxTrX::IsTRX(CpptrajFile& infile) {
    int magic;
    if ( infile.Read( &magic, 4 ) != 4 ) return 1;
    if (magic != Magic_) {
        // See if this is big endian
        endian_swap( &magic, 1 );
        if (magic != Magic_)
            return false;
        else
            isBigEndian_ = true;
    } else
        isBigEndian_ = false;
    // TODO: At this point file is trX, but not sure how best to differentiate
    // between TRR and TRJ. For now do it based on extension. Default TRR.
    if      (infile.Filename().Ext() == ".trr") format_ = TRR;
    else if (infile.Filename().Ext() == ".trj") format_ = TRJ;
    else format_ = TRR;
    return true;
}
Ejemplo n.º 10
0
/** Read array of size natom3 with set precision. Swap endianness if
  * necessary. Since GROMACS units are nm, convert to Ang.
  */
int Traj_GmxTrX::ReadAtomVector( double* Dout, int size ) {
    switch (precision_) {
    case sizeof(float):
        if (file_.Read( farray_, size ) != size) return 1;
        if (isBigEndian_) endian_swap(farray_, natom3_);
        for (int i = 0; i < natom3_; ++i)
            Dout[i] = (double)(farray_[i] * 10.0); // FIXME: Legit for velocities?
        break;
    case sizeof(double):
        if (file_.Read( Dout, size ) != size) return 1;
        if (isBigEndian_) endian_swap8(Dout, natom3_);
        for (int i = 0; i < natom3_; ++i)
            Dout[i] *= 10.0; // FIXME: Legit for velocities?
        break;
    default:
        return 1;
    }
    return 0;
}
Ejemplo n.º 11
0
/**
  * \param boxOut Double array of length 6 containing {X Y Z alpha beta gamma}
  */
int Traj_GmxTrX::ReadBox(double* boxOut) {
    // xyz is an array of length 9 containing X{xyz} Y{xyz} Z{xyz}.
    double xyz[9];
    float f_boxIn[9];
    switch (precision_) {
    case sizeof(float):
        if (file_.Read( f_boxIn, box_size_ ) != box_size_) return 1;
        if (isBigEndian_) endian_swap( f_boxIn, 9 );
        for (int i = 0; i < 9; ++i)
            xyz[i] = (double)f_boxIn[i];
        break;
    case sizeof(double):
        if (file_.Read( xyz, box_size_ ) != box_size_) return 1;
        if (isBigEndian_) endian_swap8( xyz, 9 );
        break;
    default:
        return 1;
    }
    // Calculate box lengths
    // NOTE: GROMACS units are nm
    boxOut[0] = sqrt((xyz[0]*xyz[0] + xyz[1]*xyz[1] + xyz[2]*xyz[2])) * 10.0;
    boxOut[1] = sqrt((xyz[3]*xyz[3] + xyz[4]*xyz[4] + xyz[5]*xyz[5])) * 10.0;
    boxOut[2] = sqrt((xyz[6]*xyz[6] + xyz[7]*xyz[7] + xyz[8]*xyz[8])) * 10.0;
    //mprintf("DEBUG:\tTRX Box Lengths: %f %f %f\n", boxOut[0], boxOut[1], boxOut[2]);
    if (boxOut[0] <= 0.0 || boxOut[1] <= 0.0 || boxOut[2] <= 0.0) {
        // Use zero-length box size and set angles to 90
        // TODO: This will cause box detection to fail in Trajin. Set to max(X,Y,Z)?
        boxOut[0] = boxOut[1] = boxOut[2] = 0.0;
        boxOut[3] = boxOut[4] = boxOut[5] = 90.0;
    } else {
        // Get angles between x+y(gamma), x+z(beta), and y+z(alpha)
        boxOut[5] = acos( (xyz[0]*xyz[3] + xyz[1]*xyz[4] + xyz[2]*xyz[5]) *
                          100.0 / (boxOut[0]* boxOut[1]) ) * 90.0/Constants::PIOVER2;
        boxOut[4] = acos( (xyz[0]*xyz[6] + xyz[1]*xyz[7] + xyz[2]*xyz[8]) *
                          100.0 / (boxOut[0]* boxOut[2]) ) * 90.0/Constants::PIOVER2;
        boxOut[3] = acos( (xyz[3]*xyz[6] + xyz[4]*xyz[7] + xyz[5]*xyz[8]) *
                          100.0 / (boxOut[1]* boxOut[2]) ) * 90.0/Constants::PIOVER2;
    }
    //mprintf("DEBUG:\tTRX Box Angles: %f %f %f\n", boxOut[3], boxOut[4], boxOut[5]);
    return 0;
}
Ejemplo n.º 12
0
/** Read 1 integer, swap bytes if big endian. */
int Traj_GmxTrX::read_int( int& ival ) {
    // ASSUMING 4 byte integers
    if ( file_.Read( &ival, 4 ) != 4 ) return 1;
    if (isBigEndian_) endian_swap( &ival, 1 );
    return 0;
}
Ejemplo n.º 13
0
static void parse_gps( struct gps *gpsData_ptr ){
	double old_GPS_TOW;
    double sig_X, sig_Y, sig_Z, sig_VX, sig_VY, sig_VZ;
    uint8_t finesteering_ok, solution_ok;
       
    MATRIX ecef_mat = mat_creat(3,1,ZERO_MATRIX);
    MATRIX lla_mat = mat_creat(3,1,ZERO_MATRIX);
    MATRIX ned_mat = mat_creat(3,1,ZERO_MATRIX);
    
    switch(localBuffer[5]*256 + localBuffer[4] ){

    case 241: // parse BESTXYZ
    
        endian_swap(localBuffer,14,2);     // GPS Week No
        endian_swap(localBuffer,16,4);     // GPS_TOW
        endian_swap(localBuffer,28,4);     // Solution Status
        endian_swap(localBuffer,28+8,8);   // X
        endian_swap(localBuffer,28+16,8);  // Y
        endian_swap(localBuffer,28+24,8);  // Z
        endian_swap(localBuffer,28+32,4);  // stdevXe
        endian_swap(localBuffer,28+36,4);  // stdevYe
        endian_swap(localBuffer,28+40,4);  // stdevZe
        endian_swap(localBuffer,28+52,8);  // Vx
        endian_swap(localBuffer,28+60,8);  // Vy
        endian_swap(localBuffer,28+68,8);  // Vz
        endian_swap(localBuffer,28+76,4);  // stdevVx
        endian_swap(localBuffer,28+80,4);  // stdevVy
        endian_swap(localBuffer,28+84,4);  // stdevVz
        
        gpsData_ptr->GPS_week = *((uint16_t *)(&localBuffer[14]));
        gpsData_ptr->satVisible = (uint16_t)(localBuffer[28+105]);
        
        old_GPS_TOW = gpsData_ptr->GPS_TOW;
		gpsData_ptr->GPS_TOW =  (double) *((uint32_t *)(&localBuffer[16])) / 1000.0;
        
        // convert positions from ECEF to LLA
        gpsData_ptr->Xe = *((double *)(&localBuffer[28+8]));
        gpsData_ptr->Ye = *((double *)(&localBuffer[28+16]));
        gpsData_ptr->Ze = *((double *)(&localBuffer[28+24]));
        
        ecef_mat[0][0] = gpsData_ptr->Xe;
        ecef_mat[1][0] = gpsData_ptr->Ye;
        ecef_mat[2][0] = gpsData_ptr->Ze;
		
		if(sqrt(gpsData_ptr->Xe*gpsData_ptr->Xe + gpsData_ptr->Ye*gpsData_ptr->Ye + gpsData_ptr->Ze*gpsData_ptr->Ze) < 1e-3) {
			lla_mat[0][0] = 0.0;
			lla_mat[1][0] = 0.0;
			lla_mat[2][0] = 0.0;
		} else {
			lla_mat = ecef2lla(ecef_mat,lla_mat);
		}
        
        gpsData_ptr->lat = lla_mat[0][0]*R2D;
        gpsData_ptr->lon = lla_mat[1][0]*R2D;
        gpsData_ptr->alt = lla_mat[2][0];
        
        // convert velocities from ECEF to NED
        gpsData_ptr->Ue = *((double *)(&localBuffer[28+52]));
        gpsData_ptr->Ve = *((double *)(&localBuffer[28+60]));
        gpsData_ptr->We = *((double *)(&localBuffer[28+68]));
        
        ecef_mat[0][0] = gpsData_ptr->Ue;
        ecef_mat[1][0] = gpsData_ptr->Ve;
        ecef_mat[2][0] = gpsData_ptr->We;
        
        ned_mat = ecef2ned(ecef_mat,ned_mat,lla_mat);
        
        gpsData_ptr->vn = ned_mat[0][0];
        gpsData_ptr->ve = ned_mat[1][0];
        gpsData_ptr->vd = ned_mat[2][0];
        
        // convert stdev position from ECEF to NED
        sig_X = (double) *((float *)(&localBuffer[28+32]));
        sig_Y = (double) *((float *)(&localBuffer[28+36]));
        sig_Z = (double) *((float *)(&localBuffer[28+40]));
        
        ecef_mat[0][0] = sig_X;
        ecef_mat[1][0] = sig_Y;
        ecef_mat[2][0] = sig_Z;
        
        ned_mat = ecef2ned(ecef_mat,ned_mat,lla_mat);
        
        gpsData_ptr->sig_N = ned_mat[0][0];
        gpsData_ptr->sig_E = ned_mat[1][0];
        gpsData_ptr->sig_D = ned_mat[2][0];
        
        // convert stdev velocities from ECEF to NED
        sig_VX = (double) *((float *)(&localBuffer[28+76]));
        sig_VY = (double) *((float *)(&localBuffer[28+80]));
        sig_VZ = (double) *((float *)(&localBuffer[28+84]));
        
        ecef_mat[0][0] = sig_VX;
        ecef_mat[1][0] = sig_VY;
        ecef_mat[2][0] = sig_VZ;
        
        ned_mat = ecef2ned(ecef_mat,ned_mat,lla_mat);
        
        gpsData_ptr->sig_vn = ned_mat[0][0];
        gpsData_ptr->sig_ve = ned_mat[1][0];
        gpsData_ptr->sig_vd = ned_mat[2][0];
		
		//fprintf(stderr,"Stat:%d \n",(*((uint32_t *)(&localBuffer[28]))));
        //fprintf(stderr,"Time:%d \n",(*((uint8_t *)(&localBuffer[13]))));
		
		//endian_swap(localBuffer,20,4);
		//fprintf(stderr,"Rx:%08X \n",(*((uint32_t *)(&localBuffer[20]))));
		
        solution_ok = ((*((uint32_t *)(&localBuffer[28]))) == 0);
        //finesteering_ok = ( (*((uint8_t *)(&localBuffer[13]))) == 160 ) || ( (*((uint8_t *)(&localBuffer[13]))) == 170 ) || ( (*((uint8_t *)(&localBuffer[13]))) == 180 );
		finesteering_ok=1;
        if(solution_ok & finesteering_ok) {
            if(fabs(gpsData_ptr->GPS_TOW - old_GPS_TOW) > 1e-3) {
                // Check that this is a new data (no GPS outage)
                gpsData_ptr->navValid = 0; // Light the GPS LOCK in Ground Station
                gpsData_ptr->newData = 1;  // Execute measurement update
            }
			else gpsData_ptr->navValid = 1; // Turn off the GPS LOCK light in Ground station
        }								   // Also, no measurement update will occur since newData is not set to 1
        else gpsData_ptr->navValid = 1; // Turn off the GPS LOCK light in Ground station
                                        // Also, no measurement update will occur since newData is not set to 1
        
        break;
    }
	mat_free(ecef_mat);
	mat_free(lla_mat);
	mat_free(ned_mat);
}
Ejemplo n.º 14
0
/** Header is 256 4-byte words. Integer unless otherwise noted. First 56 words are:
  *    0-2: columns, rows, sections (fastest changing to slowest)
  *      3: mode: 0 = envelope stored as signed bytes (from -128 lowest to 127 highest)
  *               1 = Image     stored as Integer*2
  *               2 = Image     stored as Reals
  *               3 = Transform stored as Complex Integer*2
  *               4 = Transform stored as Complex Reals
  *               5 == 0
  *    4-6: Column, row, and section offsets
  *    7-9: Intervals along X, Y, Z
  *  10-15: float; 3x cell lengths (Ang) and 3x cell angles (deg)
  *  16-18: Map of which axes correspond to cols, rows, sections (1,2,3 = x,y,z)
  *  19-21: float; Min, max, and mean density
  *  22-24: Space group, bytes used for storing symm ops, flag for skew transform
  *         If skew flag != 0, skew transformation is from standard orthogonal
  *         coordinate frame (as used for atoms) to orthogonal map frame, as:
  *             Xo(map) = S * (Xo(atoms) - t)
  *  25-33: Skew matrix 'S' (in order S11, S12, S13, S21 etc)
  *  34-36: Skew translation 't'
  *  37-51: For future use and can be skipped.
  *     52: char; 'MAP '
  *     53: char; machine stamp for determining endianness
  *     54: float; RMS deviation of map from mean
  *     55: Number of labels
  */
int DataIO_CCP4::ReadData(FileName const& fname,
                          DataSetList& datasetlist, std::string const& dsname)
{
    CpptrajFile infile;
    if (infile.OpenRead( fname )) return 1;
    // Read first 56 words of the header into a buffer.
    headerbyte buffer;
    if (infile.Read(buffer.i, 224*sizeof(unsigned char)) < 1) {
        mprinterr("Error: Could not buffer CCP4 header.\n");
        return 1;
    }
    if (debug_ > 0)
        mprintf("DEBUG: MAP= '%c %c %c %c'  MACHST= '%x %x %x %x'\n",
                buffer.c[208], buffer.c[209], buffer.c[210], buffer.c[211],
                buffer.c[212], buffer.c[213], buffer.c[214], buffer.c[215]);
    // SANITY CHECK
    if (!MapCharsValid(buffer.c + 208)) {
        mprinterr("Error: CCP4 file missing 'MAP ' string at word 53\n");
        return 1;
    }
    // Check endianess
    bool isBigEndian = (buffer.c[212] == 0x11 && buffer.c[213] == 0x11 &&
                        buffer.c[214] == 0x00 && buffer.c[215] == 0x00);
    if (!isBigEndian) {
        if (debug_ > 0) mprintf("DEBUG: Little endian.\n");
        // SANITY CHECK
        if ( !(buffer.c[212] == 0x44 && buffer.c[213] == 0x41 &&
                buffer.c[214] == 0x00 && buffer.c[215] == 0x00) )
            mprintf("Warning: Invalid machine stamp: %x %x %x %x : assuming little endian.\n",
                    buffer.c[212], buffer.c[213], buffer.c[214], buffer.c[215]);
    } else {
        if (debug_ > 0) mprintf("DEBUG: Big endian.\n");
        // Perform endian swapping on header if necessary
        endian_swap(buffer.i, 56);
    }

    // Print DEBUG info
    if (debug_ > 0) {
        mprintf("DEBUG: Columns=%i  Rows=%i  Sections=%i\n", buffer.i[0], buffer.i[1], buffer.i[2]);
        mprintf("DEBUG: Mode=%i\n", buffer.i[3]);
        mprintf("DEBUG: Offsets: C=%i  R=%i  S=%i\n", buffer.i[4], buffer.i[5], buffer.i[6]);
        mprintf("DEBUG: NXYZ={ %i %i %i }\n", buffer.i[7], buffer.i[8], buffer.i[9]);
        mprintf("DEBUG: Box XYZ={ %f %f %f }  ABG={ %f %f %f }\n",
                buffer.f[10], buffer.f[11], buffer.f[12],
                buffer.f[13], buffer.f[14], buffer.f[15]);
        mprintf("DEBUG: Map: ColAxis=%i  RowAxis=%i  SecAxis=%i\n",
                buffer.i[16], buffer.i[17], buffer.i[18]);
        mprintf("DEBUG: SpaceGroup#=%i  SymmOpBytes=%i  SkewFlag=%i\n",
                buffer.i[22], buffer.i[23], buffer.i[24]);
        const int* MSKEW = buffer.i + 25;
        mprintf("DEBUG: Skew matrix: %i %i %i\n"
                "                    %i %i %i\n"
                "                    %i %i %i\n", MSKEW[0], MSKEW[1], MSKEW[2], MSKEW[3],
                MSKEW[4], MSKEW[5], MSKEW[6], MSKEW[7], MSKEW[8]);
        const int* TSKEW = buffer.i + 34;
        mprintf("DEBUG: Skew translation: %i %i %i\n", TSKEW[0], TSKEW[1], TSKEW[2]);
        mprintf("DEBUG: Nlabels=%i\n", buffer.i[55]);
    }
    // Check input data. Only support mode 2 for now.
    if (buffer.i[3] != 2) {
        mprinterr("Error: Mode %i; currently only mode 2 for CCP4 files is supported.\n", buffer.i[3]);
        return 1;
    }
    // Check offsets.
    if (buffer.i[4] != 0 || buffer.i[5] != 0 || buffer.i[6] != 0)
        mprintf("Warning: Non-zero offsets present. This is not yet supported and will be ignored.\n");
    // Check that mapping is col=x row=y section=z
    if (buffer.i[16] != 1 || buffer.i[17] != 2 || buffer.i[18] != 3) {
        mprinterr("Error: Currently only support cols=X, rows=Y, sections=Z\n");
        return 1;
    }
    if (buffer.i[24] != 0) {
        mprintf("Warning: Skew information present but not yet supported and will be ignored.\n");
        return 1;
    }

    // Read 10 80 character text labels
    char Labels[801];
    Labels[800] = '\0';
    infile.Read( Labels, 200*wSize );
    mprintf("\t%s\n", Labels);
    // Symmetry records: operators separated by * and grouped into 'lines' of 80 characters
    int NsymmRecords = buffer.i[23] / 80;
    if (NsymmRecords > 0) {
        char symBuffer[81];
        mprintf("\t%i symmetry records.\n", NsymmRecords);
        for (int ib = 0; ib != NsymmRecords; ib++) {
            infile.Gets( symBuffer, 80 );
            mprintf("\t%s\n", symBuffer);
        }
    }

    // Add grid data set. Default to float for now.
    DataSet* gridDS = datasetlist.AddSet( DataSet::GRID_FLT, dsname, "GRID" );
    if (gridDS == 0) return 1;
    DataSet_GridFlt& grid = static_cast<DataSet_GridFlt&>( *gridDS );
    // Allocate grid from dims and spacing. FIXME OK to assume zero origin?
    if (grid.Allocate_N_O_Box( buffer.i[7], buffer.i[8], buffer.i[9],
                               Vec3(0.0), Box(buffer.f + 10) ) != 0)
    {
        mprinterr("Error: Could not allocate grid.\n");
        return 1;
    }
    // FIXME: Grids are currently indexed so Z is fastest changing.
    //        Should be able to change indexing in grid DataSet.
    size_t mapSize = buffer.i[7] * buffer.i[8] * buffer.i[9];
    mprintf("\tCCP4 map has %zu elements\n", mapSize);
    mprintf("\tDensity: Min=%f  Max=%f  Mean=%f  RMS=%f\n",
            buffer.f[19], buffer.f[20], buffer.f[21], buffer.f[54]);
    std::vector<float> mapbuffer( mapSize );
    int mapBytes = mapSize * wSize;
    int numRead = infile.Read( &mapbuffer[0], mapBytes );
    if (numRead < 1) {
        mprinterr("Error: Could not read CCP4 map data.\n");
        return 1;
    } else if (numRead < mapBytes)
        mprintf("Warning: Expected %i bytes, read only %i bytes\n", mapBytes, numRead);
    if (isBigEndian) endian_swap(&mapbuffer[0], mapSize);

    // FIXME: Place data into grid DataSet with correct ordering.
    int gidx = 0;
    int NXY = buffer.i[7] * buffer.i[8];
    for (int ix = 0; ix != buffer.i[7]; ix++)
        for (int iy = 0; iy != buffer.i[8]; iy++)
            for (int iz = 0; iz != buffer.i[9]; iz++) {
                int midx = (iz * NXY) + (iy * buffer.i[7]) + ix;
                grid[gidx++] = mapbuffer[midx];
            }

    infile.CloseFile();
    return 0;
}
Ejemplo n.º 15
0
// How to handle static variables with multiple sensors?  objects? add to gpspacket?
int read_gps(struct gps *gpsData_ptr)
{
	cyg_io_handle_t port_handle;
	cyg_serial_buf_info_t buff_info;
	unsigned int len = sizeof (buff_info);

	// get serial port handle
	cyg_io_lookup( gpsData_ptr->portName, &port_handle );
	
	cyg_io_get_config (port_handle, CYG_IO_GET_CONFIG_SERIAL_BUFFER_INFO,\
			&buff_info, &len);
	unsigned int bytesInBuffer = buff_info.rx_count;
	unsigned int bytesReadThisCall = 0;
	unsigned short msgPayloadSize = 0, bytesToRead = 0, bytesRead = 0;
    unsigned long CRC_computed, CRC_read;
	int j, status =0;
	
	// Initialization of persistent local buffer
	if (gpsData_ptr->localBuffer == NULL)
	{
		gpsData_ptr->localBuffer = (unsigned char*) malloc (1024 * sizeof (unsigned char));
	}

	// First check if there are any bytes in the serial buffer, return if none
	if( bytesInBuffer == 0 )
		return -1;

	// Get localBuffer stored in gps packet. This is to keep the following code readable
	localBuffer = gpsData_ptr->localBuffer;
	bytesInLocalBuffer= gpsData_ptr->bytesInLocalBuffer;
	readState = gpsData_ptr->readState;

	while (bytesReadThisCall < bytesInBuffer){

        switch (readState){
            case 0: //Look for packet header bytes
                // Read in up to 3 bytes to the first open location in the local buffer
                //fprintf(stderr,"bytesInLocalBuffer is %d\n",bytesInLocalBuffer);
                
                bytesRead = read(gpsData_ptr->port,&localBuffer[bytesInLocalBuffer],3-bytesInLocalBuffer);
                
                //fprintf(stderr,"The first three bytes are %0X %0X %0X\n",localBuffer[0],localBuffer[1],localBuffer[2]);    
                //fprintf(stderr,"bytesRead is %d\n",bytesRead);
                //fprintf(stderr,"Read %d bytes, The first three bytes are %0X %0X %0X\n", bytesRead,localBuffer[0],localBuffer[1],localBuffer[2]);    
                
                bytesReadThisCall += bytesRead; // keep track of bytes read during this call
                
                if (localBuffer[0] == 0xAA){ // Check for first header byte
                    bytesInLocalBuffer = 1;
                    //fprintf(stderr, "case 0, 0xAA header type \n");
                    if (localBuffer[1] == 0x44){ // Check for second header byte
                        bytesInLocalBuffer = 2;
                        if (localBuffer[2] == 0x12){ // Check for third header byte
                            bytesInLocalBuffer = 3;
                            readState++;
                        }
                    }
                }
                else {
                    gpsData_ptr->err_type = noPacketHeader;
                }
                break;	// end case 0
                
            case 1: // Look for block ID and data length
                // Read 28 Header Bytes
                bytesToRead = 28 - bytesInLocalBuffer;
                
                // Read in bytes to the last location in the local buffer
                bytesRead = read(gpsData_ptr->port,&localBuffer[bytesInLocalBuffer],bytesToRead);
                bytesInLocalBuffer += bytesRead; // keep track of bytes in local buffer
                bytesReadThisCall += bytesRead;  // keep track of bytes read during this call
                
                if (bytesRead == bytesToRead){
                    readState++;
                    //fprintf (stderr,"<GPS>: Got msgID: %d and Data Length: %d\n", localBuffer[5]*256 + localBuffer[4], localBuffer[9]*256 + localBuffer[8]);
                    //printf ("<GPS>: localBuffer[0] = %02X localBuffer[1] = %02X localBuffer[2] = %02X localBuffer[3] = %02X localBuffer[4] = %02X localBuffer[5] = %02X \n", localBuffer[0], localBuffer[1], localBuffer[2], localBuffer[3], localBuffer[4], localBuffer[5]);
                }
                else{
                    gpsData_ptr->err_type = incompletePacket;
                }
                break;  // end case 1
        
            case 2: //Read payload
                // Find message payload size
                msgPayloadSize = localBuffer[9]*256 + localBuffer[8]; // data is in little endian format
                
                // Error checking on payload size. If size is bigger than expected, dump packet
                if(msgPayloadSize > GPS_MAX_MSG_SIZE){			
                    gpsData_ptr->err_type = incompletePacket;
                    reset_localBuffer();
                }
                
                // Find how many bytes need to be read for the total message (Sync (3)  + Remaining Header (25) + Payload - bytes already read )
                bytesToRead = msgPayloadSize + 28 - bytesInLocalBuffer;
                
                //printf("bytesInLocalBuffer is %d bytesToRead is %d \n",bytesInLocalBuffer,bytesToRead);
                
                // Read in the remainder of the message to the local buffer, starting at the first empty location
                bytesRead = read (gpsData_ptr->port, &localBuffer[bytesInLocalBuffer], bytesToRead);
                bytesInLocalBuffer += bytesRead; // keep track of bytes in local buffer
                bytesReadThisCall += bytesRead; // keep track of bytes read during this call
                
                if (bytesRead == bytesToRead){
                    //printf ("<GPS>: Got complete message! Tried for %d, got %d\n",bytesToRead,bytesRead);
					readState++;
				}
				else {
					gpsData_ptr->err_type = incompletePacket;
				}
				
				break; // end case 2
				
			case 3: // read CRC bytes (4 bytes)
				bytesToRead = 4;
				bytesRead = read (gpsData_ptr->port, &localBuffer[bytesInLocalBuffer], bytesToRead);
				bytesInLocalBuffer += bytesRead;
				bytesReadThisCall += bytesRead;
					
				if(bytesRead == bytesToRead) {
					// CRC verification
					CRC_computed = CalculateBlockCRC32(bytesInLocalBuffer-4,localBuffer);
					endian_swap(localBuffer,140,4);
					CRC_read = *(uint32_t *) (localBuffer+140);
                    if (CRC_computed == CRC_read) {
                        gpsData_ptr->err_type = data_valid;
						parse_gps(gpsData_ptr);
                        //fprintf (stderr,"<GPS t = %9.3lf>: Success!\n",gpsData_ptr->GPS_TOW);
                    }
                    else{ 
						send_status("GPS CRC ERR");
                        //fprintf (stderr,"<GPS>: Checksum mismatch!\n");
						/* ============= DEBUG CHECKSUM ERROR ================
						fprintf (stderr,"<GPS %d>: Checksum mismatch! Buffer: %02X%02X%02X%02X Read: %08lX Computed: %08lX\n",localBuffer[5]*256 + localBuffer[4],localBuffer[140],localBuffer[141],localBuffer[142],localBuffer[143],CRC_read,CRC_computed);
                        fprintf (stderr,"Hex: \n");
                            for (j = 0; j < bytesInLocalBuffer; j++) {
                                fprintf(stderr,"%02X ",localBuffer[j]);
                                if(j%8==7) 
                                    fprintf(stderr,"\n");
                            }
						*/
						gpsData_ptr->err_type = checksum_err;
                    }
                    
                    reset_localBuffer();
                }
                else{
                    //printf ("\n<GPS>: Didn't get complete message. Tried for %d, got %d",bytesToRead,bytesRead);
                    gpsData_ptr->err_type= incompletePacket;
                    
                    status = 0;									
                }
                break;	// end case 3
                
                default:
                    reset_localBuffer();
                    printf ("\n<GPS>: Why are you here?");
                    status = 0;
                break; // end default
        
        } // end switch (readState)

    } // end while (bytesReadThisCall < bytesInBuffer)	

    // Store local buffer in gps packet
    gpsData_ptr->localBuffer = localBuffer;
    gpsData_ptr->bytesInLocalBuffer = bytesInLocalBuffer;
    gpsData_ptr->readState = readState;
    
    return status;
}
Ejemplo n.º 16
0
    IANAParser::IANAParser(std::unique_ptr<char[]>fileblock)
    {
	unsigned int fb_index = 0;
	TZHead tzh = *reinterpret_cast<TZHead*>(&fileblock[fb_index]);
	static constexpr int ttinfo_size = 6; //struct TTInfo gets padded
	last_year = 2037; //Constrained by 32-bit time_t.
	int transition_size = 4; // length of a transition time in the file

	auto time_count = *(endian_swap(reinterpret_cast<uint32_t*>(tzh.timecnt)));
	auto type_count = *(endian_swap(reinterpret_cast<uint32_t*>(tzh.typecnt)));
	auto char_count = *(endian_swap(reinterpret_cast<uint32_t*>(tzh.charcnt)));
	auto isgmt_count = *(endian_swap(reinterpret_cast<uint32_t*>(tzh.ttisgmtcnt)));
	auto isstd_count = *(endian_swap(reinterpret_cast<uint32_t*>(tzh.ttisstdcnt)));
	auto leap_count = *(endian_swap(reinterpret_cast<uint32_t*>(tzh.leapcnt)));
	if ((tzh.version == '2' || tzh.version == '3') && sizeof(time_t) == sizeof(int64_t))
	{
	    fb_index = (sizeof(tzh) +
			(sizeof(uint32_t) + sizeof(uint8_t)) * time_count +
			ttinfo_size * type_count +
			sizeof(char) * char_count +
			sizeof(uint8_t) * isgmt_count +
			sizeof(uint8_t) * isstd_count +
			2 * sizeof(uint32_t) * leap_count);

	    //This might change at some point in the probably very
	    //distant future.
	    tzh = *reinterpret_cast<TZHead*>(&fileblock[fb_index]);
	    last_year = 2499;
	    time_count = *(endian_swap(reinterpret_cast<uint32_t*>(tzh.timecnt)));
	    type_count = *(endian_swap(reinterpret_cast<uint32_t*>(tzh.typecnt)));
	    char_count = *(endian_swap(reinterpret_cast<uint32_t*>(tzh.charcnt)));
	    isgmt_count = *(endian_swap(reinterpret_cast<uint32_t*>(tzh.ttisgmtcnt)));
	    isstd_count = *(endian_swap(reinterpret_cast<uint32_t*>(tzh.ttisstdcnt)));
	    leap_count = *(endian_swap(reinterpret_cast<uint32_t*>(tzh.leapcnt)));
	    transition_size = 8;
	}
	fb_index += sizeof(tzh);
	auto start_index = fb_index;
	auto info_index_zero = start_index + time_count * transition_size;
	for(uint32_t index = 0; index < time_count; ++index)
	{
	    fb_index = start_index + index * transition_size;
	    auto info_index = info_index_zero + index;
	    if (transition_size  == 4)
	    {
		transitions.push_back(
		    {*(endian_swap(reinterpret_cast<int32_t*>(&fileblock[fb_index]))),
			    static_cast<uint8_t>(fileblock[info_index])});
	    }
	    else
	    {
		transitions.push_back(
		    {*(endian_swap(reinterpret_cast<int64_t*>(&fileblock[fb_index]))),
			    static_cast<uint8_t>(fileblock[info_index])});
	    }
	}

	//Add in the tzinfo indexes consumed in the previous loop
	start_index = info_index_zero + time_count;
	//Can't use sizeof(TZInfo) because it's padded out to 8 bytes.
	static const size_t tzinfo_size = 6;
	auto abbrev = start_index + type_count * tzinfo_size;
	auto std_dist = abbrev + char_count;
	auto gmt_dist = std_dist + type_count;
	for(uint32_t index = 0; index < type_count; ++index)
	{
	    fb_index = start_index + index * tzinfo_size;
	    TTInfo info = *reinterpret_cast<TTInfo*>(&fileblock[fb_index]);
	    endian_swap(&info.gmtoff);
	    tzinfo.push_back(
		{info, &fileblock[abbrev + info.abbrind],
			fileblock[std_dist + index] != '\0',
			fileblock[gmt_dist + index] != '\0'});
	}

    }
Ejemplo n.º 17
0
static void parse_gps( struct gps *gpsData_ptr ){
	double old_GPS_TOW;
	// parse msg ID 
	switch(localBuffer[5]*256 + localBuffer[4] ){

	case 1: // parse msg 1 

		// Swap byte order first
		endian_swap(localBuffer, 10, 2);
		endian_swap(localBuffer, 12, 8);
		endian_swap(localBuffer, 20, 8);
		endian_swap(localBuffer, 28, 8);
		endian_swap(localBuffer, 36, 4);
		endian_swap(localBuffer, 40, 4);
		endian_swap(localBuffer, 44, 4);
		endian_swap(localBuffer, 48, 4);
		endian_swap(localBuffer, 52, 4);
		endian_swap(localBuffer, 56, 2);
		endian_swap(localBuffer, 58, 2);
		
		// Cast bytes into appropriate datatypes
		gpsData_ptr->satVisible = (uint16_t)(localBuffer[9]);
		gpsData_ptr->GPS_week = *((uint16_t *)(&localBuffer[10]));
		
		old_GPS_TOW = gpsData_ptr->GPS_TOW;
		gpsData_ptr->GPS_TOW = *((double *)(&localBuffer[12]));
		
		gpsData_ptr->lat = *((double *)(&localBuffer[20]));
		gpsData_ptr->lon = *((double *)(&localBuffer[28]));
		gpsData_ptr->alt = (double)(*((float *)(&localBuffer[36])));
		gpsData_ptr->vn = (double)(*((float *)(&localBuffer[40])));
		gpsData_ptr->ve = (double)(*((float *)(&localBuffer[44])));
		gpsData_ptr->vd = (double)(*((float *)(&localBuffer[48]))) * -1;
		gpsData_ptr ->courseOverGround = atan2(gpsData_ptr->ve,gpsData_ptr->vn);
		gpsData_ptr ->speedOverGround = sqrt(gpsData_ptr->vn*gpsData_ptr->vn + gpsData_ptr->ve*gpsData_ptr->ve);
		

		// Checking for GPS lock and outages

		// First, we check that the GPS receiver is outputting some form of GPS data
		// Second, we check that the GPS data is fine-steered
		// Third, we check that the GPS data is distinct from the previous data point

		// All three conditions must be satisfied for GPS lock and GPS new data.
		
		// When there is no new GPS information, GPS_TOW sent by the receiver is the old TOW
		// The new data flag is not set if the GPS is not new, when prevents measurement updates

		
		if((*((uint16_t *)(&localBuffer[56]))) != 0) {
			// Check internal navigation mode sent by the receiver.
			// Crescent: 0 means no fix. (SirfIII: 0 means fix, not relevant here)
			// Added 1e-5 to GPW_TOW in order to deal with numerical issue in floor() function in C
			if(fabs(gpsData_ptr->GPS_TOW - floor(gpsData_ptr->GPS_TOW+1e-5)) < 1e-3) {
				// GPS TOW needs to be fine-steered to a whole number of TOW.
				if(fabs(gpsData_ptr->GPS_TOW - old_GPS_TOW) > 1e-3) {
					// Check that this is a new data (no GPS outage)
					gpsData_ptr->navValid = 0; // Light the GPS LOCK in Ground Station
					gpsData_ptr->newData = 1;  // Execute measurement update
				}
				else {
			        gpsData_ptr->navValid = 1; // Turn off the GPS LOCK light in Ground station
				}
			}								   // Also, no measurement update will occur since newData is not set to 1
			else {
			    gpsData_ptr->navValid = 1; // Turn off the GPS LOCK light in Ground station
			}
		}								   // Also, no measurement update will occur since newData is not set to 1 
		else {
			gpsData_ptr->navValid = 1; // Turn off the GPS LOCK light in Ground station
		}							   // Also, no measurement update will occur since newData is not set to 1
		break;
	
	}

}
Ejemplo n.º 18
0
/*! \fn void md5_hmac_final(struct crypto_tfm *tfm, u8 *out)
 *  \ingroup IFX_MD5_HMAC_FUNCTIONS
 *  \brief compute final md5 hmac value   
 *  \param tfm linux crypto algo transform  
 *  \param out final md5 hmac output value  
*/                                 
static int md5_hmac_final(struct shash_desc *desc, u8 *out)
{
    struct md5_hmac_ctx *mctx = crypto_shash_ctx(desc->tfm);
    const unsigned int offset = mctx->byte_count & 0x3f;
    char *p = (char *)mctx->block + offset;
    int padding = 56 - (offset + 1);
    volatile struct deu_hash_t *hashs = (struct deu_hash_t *) HASH_START;
    unsigned long flag;
    int i = 0;
    int dbn;
    u32 *in = &temp[0];


    *p++ = 0x80;
    if (padding < 0) {
        memset(p, 0x00, padding + sizeof (u64));
        md5_hmac_transform(desc, mctx->block);
        p = (char *)mctx->block;
        padding = 56;
    }

    memset(p, 0, padding);
    mctx->block[14] = endian_swap((mctx->byte_count + 64) << 3); // need to add 512 bit of the IPAD operation 
    mctx->block[15] = 0x00000000;

    md5_hmac_transform(desc, mctx->block);

    CRTCL_SECT_START;

    //printk("\ndbn = %d\n", mctx->dbn); 
    hashs->DBN = mctx->dbn;
    asm("sync");
    
    *IFX_HASH_CON = 0x0703002D; //khs, go, init, ndc, endi, kyue, hmen, md5 	

    //wait for processing
    while (hashs->controlr.BSY) {
        // this will not take long
    }

    for (dbn = 0; dbn < mctx->dbn; dbn++)
    {
        for (i = 0; i < 16; i++) {
            hashs->MR = in[i];
        };

        hashs->controlr.GO = 1;
        asm("sync");

        //wait for processing
        while (hashs->controlr.BSY) {
           // this will not take long
        }
    
        in += 16;
}


#if 1
    //wait for digest ready
    while (! hashs->controlr.DGRY) {
        // this will not take long
    }
#endif

    *((u32 *) out + 0) = hashs->D1R;
    *((u32 *) out + 1) = hashs->D2R;
    *((u32 *) out + 2) = hashs->D3R;
    *((u32 *) out + 3) = hashs->D4R;
    *((u32 *) out + 4) = hashs->D5R;

    /* reset the context after we finish with the hash */
    mctx->byte_count = 0;
    memset(&mctx->hash[0], 0, sizeof(MD5_HASH_WORDS));
    memset(&mctx->block[0], 0, sizeof(MD5_BLOCK_WORDS));
    memset(&temp[0], 0, MD5_HMAC_DBN_TEMP_SIZE);

    CRTCL_SECT_END;


   return 0;
}
Ejemplo n.º 19
0
/////////////////////////////////////////////////////////////////////////
/// Run
/// @description
///     This is the main communication engine.
///
/// @I/O
///     At every timestep, a message is sent to FPGA via TCP socket connection,
///     then a message is retrieved from FPGA via the same connection.
///     On the FPGA side, it's the reverse order -- receive and then send.
///     Both DGI and FPGA sides' receive function will block until a message
///     arrives, creating a synchronous, lock-step communication between DGI
///     and FPGA. In this sense, how frequently send and receive get executed
///     by CRtdsAdapter is dependent on how fast FPGA runs.
///
/// @Error_Handling
///     Throws an exception if reading from or writing to the socket fails
///
/// @pre
///     Connection with FPGA is established.
///
/// @post
///     All values in the cmdTable is written to a buffer and sent to FPGA.
///     All values in the stateTable is rewritten with value received
///     from FPGA.
///
/// @limitations
///     Synchronous commnunication
//////////////////////////////////////////////////////////////////////////
void CRtdsAdapter::Run()
{
    Logger.Trace << __PRETTY_FUNCTION__ << std::endl;
    //TIMESTEP is used by deadline_timer.async_wait at the end of Run().  
    //We keep TIMESTEP very small as we actually do not care if we wait at all.
    //We simply need to use deadline_timer.async_wait to pass control back
    //to io_service, so it can schedule Run() with other callback functions 
    //under its watch.
    const int TIMESTEP = 1; //in microseconds. NEEDS MORE TESTING TO SET CORRECTLY

    //**********************************
    //* Always send data to FPGA first *
    //**********************************
    {
        boost::shared_lock<boost::shared_mutex> lockRead(m_cmdTable.m_mutex);
        Logger.Debug << "Obtained mutex as reader" << std::endl;
        //read from cmdTable
        memcpy(m_txBuffer, m_cmdTable.m_data, m_txBufSize);
        Logger.Debug << "Released reader mutex" << std::endl;
    }// the scope is needed for mutex to auto release

    // FPGA will send values in big-endian byte order
    // If host machine is in little-endian byte order, convert to big-endian
#if __BYTE_ORDER == __LITTLE_ENDIAN

    for (int i = 0; i < m_txCount; i++)
    {
        //should be 4 bytes in float.
        endian_swap((char *) &m_txBuffer[4 * i], sizeof (float));
    }

#endif

    // send to FPGA
    try
    {
        boost::asio::write(m_socket,
                boost::asio::buffer(m_txBuffer, m_txBufSize));
    }
    catch (std::exception & e)
    {
        std::stringstream ss;
        ss << "Send to FPGA failed for the following reason: " << e.what();
        throw std::runtime_error(ss.str());
    }

    //*******************************
    //* Receive data from FPGA next *
    //*******************************
    try
    {
        boost::asio::read(m_socket,
                boost::asio::buffer(m_rxBuffer, m_rxBufSize));
    }
    catch (std::exception & e)
    {
        std::stringstream ss;
        ss << "Receive from FPGA failed for the following reason" << e.what();
        throw std::runtime_error(ss.str());
    }

    // FPGA will send values in big-endian byte order
    // If host machine is in little-endian byte order, convert to little-endian
#if __BYTE_ORDER == __LITTLE_ENDIAN

    for (int j = 0; j < m_rxCount; j++)
    {
        endian_swap((char *) &m_rxBuffer[4 * j], sizeof (float));
    }

#endif
    {
        boost::unique_lock<boost::shared_mutex> lockWrite(m_stateTable.m_mutex);
        Logger.Debug << "Client_RTDS - obtained mutex as writer" << std::endl;

        //write to stateTable
        memcpy(m_stateTable.m_data, m_rxBuffer, m_rxBufSize);

        Logger.Debug << "Client_RTDS - released writer mutex" << std::endl;
    } //scope is needed for mutex to auto release

    //Start the timer; on timeout, this function is called again
    m_GlobalTimer.expires_from_now(boost::posix_time::microseconds(TIMESTEP));
    m_GlobalTimer.async_wait(boost::bind(&CRtdsAdapter::Run, this));
}
Ejemplo n.º 20
0
 void Utility::network_to_host_uint32(boost::uint32_t& x) {
     // TODO: replace this with real code
     endian_swap(x);
 }
Ejemplo n.º 21
0
bool __SseSearch(unsigned int *round1State, unsigned char *round1Block2, unsigned __int32 *round2State, unsigned char *round2Block1, unsigned __int32 *nonce_, sseCheckFunc check)
{
    // starting nonce
    unsigned int nonce = 0;

    // vector containing input round1 state
    __m128i round1State_m128i[8];
    for (int i = 0; i < 8; i++)
        round1State_m128i[i] = _mm_set1_epi32(round1State[i]);

    // vector containing input round 1 block 2, contains the nonce field
    __m128i round1Block2_m128i[16];
    for (int i = 0; i < 16; i++)
        round1Block2_m128i[i] = _mm_set1_epi32(((unsigned __int32*)round1Block2)[i]);

    // vector containing input round 2 state, initialized
    __m128i round2State_m128i[8];
    for (int i = 0; i < 8; i++)
        round2State_m128i[i] = _mm_set1_epi32(round2State[i]);

    // vector containing round 2 block, to which the state from round 1 should be output
    __m128i round2Block1_m128i[16];
    for (int i = 0; i < 16; i++)
        round2Block1_m128i[i] = _mm_set1_epi32(((unsigned __int32*)round2Block1)[i]);

    // vector containing the final output from round 2
    __m128i round2State2_m128i[8];

    // initial nonce vector
    __m128i nonce_inc_m128i = _mm_set_epi32(0, 1, 2, 3);

    for (;;)
    {
        // set nonce in blocks
        round1Block2_m128i[3] = _mm_add_epi32(_mm_set1_epi32(nonce), nonce_inc_m128i);

        // transform variable second half of block using saved state from first block, into pre-padded round 2 block (end of first hash)
        sha256_transform(round1State_m128i, round1Block2_m128i, round2Block1_m128i);

        // transform round 2 block into round 2 state (second hash)
        sha256_transform(round2State_m128i, round2Block1_m128i, round2State2_m128i);

        // isolate 0x00000000, segment to uint64 for easier testing
        __m128i p = _mm_cmpeq_epi32(round2State2_m128i[7], _mm_setzero_si128());
        unsigned __int64 *p64 = (unsigned __int64*)&p;

        // one of the two sides of the vector has values
        if ((p64[0] != 0) | (p64[1] != 0))
        {
            // first result
            if (_mm_extract_epi16(p, 0) != 0)
            {
                *nonce_ = endian_swap(nonce + 3);
                return true;
            }

            // second result
            if (_mm_extract_epi16(p, 2) != 0)
            {
                *nonce_ = endian_swap(nonce + 2);
                return true;
            }

            // third result
            if (_mm_extract_epi16(p, 4) != 0)
            {
                *nonce_ = endian_swap(nonce + 1);
                return true;
            }

            // fourth result
            if (_mm_extract_epi16(p, 6) != 0)
            {
                *nonce_ = endian_swap(nonce + 0);
                return true;
            }
        }

        // report progress, or check overflow
        if ((nonce += 4) % 65536 == 0)
            if (!check(65536) || nonce < 4)
                break;
    }

    return false;
}
Ejemplo n.º 22
0
int main(int argc, char *argv[]) {
    int argchar;
    char* infn = NULL;
    char* outfn = NULL;
    anbool tostdout = FALSE;
    FILE* fin = NULL;
    FILE* fout = NULL;
    il* exts;
    il* sizes;
    int i;
    char* progname = argv[0];
    int Next;
    anqfits_t* anq;

    exts = il_new(16);
    sizes = il_new(16);

    while ((argchar = getopt (argc, argv, OPTIONS)) != -1)
        switch (argchar) {
        case 'e':
            il_append(exts, atoi(optarg));
            break;
        case 's':
            il_append(sizes, atoi(optarg));
            break;
        case 'i':
            infn = optarg;
            break;
        case 'o':
            outfn = optarg;
            break;
        case '?':
        case 'h':
            printHelp(progname);
            return 0;
        default:
            return -1;
        }

    log_init(LOG_MSG);

    if (!infn || !outfn || !il_size(exts) || (il_size(exts) != il_size(sizes))) {
        printHelp(progname);
        exit(-1);
    }

    if (infn) {
        fin = fopen(infn, "rb");
        if (!fin) {
            SYSERROR("Failed to open input file %s", infn);
            exit(-1);
        }
    }
    
    anq = anqfits_open(infn);
    if (!anq) {
        ERROR("Failed to open input file %s", infn);
        exit(-1);
    }
    Next = anqfits_n_ext(anq);
    if (Next == -1) {
        ERROR("Couldn't determine how many extensions are in file %s", infn);
        exit(-1);
    } else {
        logverb("File %s contains %i FITS extensions.\n", infn, Next);
    }

    for (i=0; i<il_size(exts); i++) {
        int e = il_get(exts, i);
        int s = il_get(sizes, i);
        if (e < 0 || e >= Next) {
            logerr("Extension %i is not valid: must be in [%i, %i]\n", e, 0, Next);
            exit(-1);
        }
        if (s != 2 && s != 4 && s != 8) {
            logerr("Invalid byte size %i: must be 2, 4, or 8.\n", s);
            exit(-1);
        }
    }

    if (!strcmp(outfn, "-"))
        tostdout = TRUE;

    if (tostdout)
        fout = stdout;
    else {
        fout = fopen(outfn, "wb");
        if (!fout) {
            SYSERROR("Failed to open output file %s", outfn);
            exit(-1);
        }
    }

    for (i=0; i<Next; i++) {
        int hdrstart, hdrlen, datastart, datalen;
        int ind;
        int size;
        ind = il_index_of(exts, i);
        if (ind == -1) {
            size = 0;
        } else {
            size = il_get(sizes, ind);
        }

        hdrstart = anqfits_header_start(anq, i);
        hdrlen   = anqfits_header_size (anq, i);
        datastart = anqfits_data_start(anq, i);
        datalen   = anqfits_data_size (anq, i);

        if (hdrlen) {
            if (pipe_file_offset(fin, hdrstart, hdrlen, fout)) {
                ERROR("Failed to write header for extension %i", i);
                exit(-1);
            }
        }
        if (!datalen)
            continue;

        if (size) {
            int Nitems = datalen / size;
            int j;
            char buf[size];
            logmsg("Extension %i: flipping words of length %i bytes.\n", i, size);
            for (j=0; j<Nitems; j++) {
                if (fread(buf, size, 1, fin) != 1) {
                    SYSERROR("Failed to read data element %i from extension %i", j, i);
                    exit(-1);
                }
                endian_swap(buf, size);
                if (fwrite(buf, size, 1, fout) != 1) {
                    SYSERROR("Failed to write data element %i to extension %i", j, i);
                    exit(-1);
                }
            }
        } else {
            logmsg("Extension %i: copying verbatim.\n", i);
            // passthrough
            if (pipe_file_offset(fin, datastart, datalen, fout)) {
                ERROR("Failed to write data for extension %i", i);
                exit(-1);
            }
        }
    }
    fclose(fin);
    anqfits_close(anq);
    if (!tostdout)
        fclose(fout);
    il_free(exts);
    il_free(sizes);
    return 0;
}