Exemplo n.º 1
0
uint32_t tpm_nv_write_value(uint32_t locality, tpm_nv_index_t index,
                            uint32_t offset, const uint8_t *data,
                            uint32_t data_size)
{
    uint32_t ret, in_size = 0, out_size = 0;

    if ( data == NULL )
        return TPM_BAD_PARAMETER;
    if ( data_size == 0 || data_size > TPM_NV_WRITE_VALUE_DATA_SIZE_MAX )
        return TPM_BAD_PARAMETER;

    /* copy index, offset and *data_size into buf in reversed byte order */
    reverse_copy(WRAPPER_IN_BUF, &index, sizeof(index));
    in_size += sizeof(index);
    reverse_copy(WRAPPER_IN_BUF + in_size, &offset, sizeof(offset));
    in_size += sizeof(offset);
    reverse_copy(WRAPPER_IN_BUF + in_size, &data_size, sizeof(data_size));
    in_size += sizeof(data_size);
    memcpy(WRAPPER_IN_BUF + in_size, data, data_size);
    in_size += data_size;

    ret = tpm_submit_cmd(locality, TPM_ORD_NV_WRITE_VALUE,
                         in_size, &out_size);

#ifdef TPM_TRACE
    printf("TPM: write nv %08x, offset %08x, %08x bytes, return = %08X\n",
           index, offset, data_size, ret);
#endif
    if ( ret != TPM_SUCCESS )
        printf("TPM: write nv %08x, offset %08x, %08x bytes, return = %08X\n",
               index, offset, data_size, ret);

    return ret;
}
Exemplo n.º 2
0
uint32_t tpm_nv_read_value(uint32_t locality, tpm_nv_index_t index,
                           uint32_t offset, uint8_t *data,
                           uint32_t *data_size)
{
    uint32_t ret, in_size = 0, out_size;

    if ( data == NULL || data_size == NULL )
        return TPM_BAD_PARAMETER;
    if ( *data_size == 0 )
        return TPM_BAD_PARAMETER;
    if ( *data_size > TPM_NV_READ_VALUE_DATA_SIZE_MAX )
        *data_size = TPM_NV_READ_VALUE_DATA_SIZE_MAX;

    /* copy the index, offset and *data_size into buf in reversed byte order */
    reverse_copy(WRAPPER_IN_BUF, &index, sizeof(index));
    in_size += sizeof(index);
    reverse_copy(WRAPPER_IN_BUF + in_size, &offset, sizeof(offset));
    in_size += sizeof(offset);
    reverse_copy(WRAPPER_IN_BUF + in_size, data_size, sizeof(*data_size));
    in_size += sizeof(*data_size);

    out_size = *data_size + sizeof(*data_size);
    ret = tpm_submit_cmd(locality, TPM_ORD_NV_READ_VALUE, in_size, &out_size);

#ifdef TPM_TRACE
    printf("TPM: read nv index %08x from offset %08x, return value = %08X\n",
           index, offset, ret);
#endif
    if ( ret != TPM_SUCCESS ) {
        printf("TPM: read nv index %08x offset %08x, return value = %08X\n",
               index, offset, ret);
        return ret;
    }

#ifdef TPM_TRACE
    {
        printf("TPM: ");
        print_hex(NULL, WRAPPER_OUT_BUF, out_size);
    }
#endif

    if ( out_size <= sizeof(*data_size) ) {
        *data_size = 0;
        return ret;
    }

    out_size -= sizeof(*data_size);
    reverse_copy(data_size, WRAPPER_OUT_BUF, sizeof(*data_size));
    *data_size = (*data_size > out_size) ? out_size : *data_size;
    if( *data_size > 0 )
        memcpy(data, WRAPPER_OUT_BUF + sizeof(*data_size), *data_size);

    return ret;
}
Exemplo n.º 3
0
void pure_numeric_algo(){
    cout<<endl<<"pure_numeric_algo :"<<endl;
    int ia[11] = {0, 1, 2, 3, 4, 5, 6,6,6, 7, 8 };
    vector<int> iv(ia,ia+11);	vector<int> iv2(ia+6,ia+8);	vector<int>::iterator itr;
    itr = adjacent_find(iv.begin(),iv.end(), equal_to<int>());	//找到相邻元素相等的第一个元素
    cout<<"adjacent_find: "<<*itr<<endl;
    cout<<"count: "<<count(iv.begin(),iv.end(), 6)<<endl;	//找到元素值等于6的个数
    cout<<"count_if: "<<count_if(iv.begin(),iv.end(), bind2nd(less<int>() , 7))<<endl;		//找到小于7的元素个数
    itr = find(iv.begin(),iv.end(), 4);				//找到元素等于4的第一个元素位置
    cout<<"find: "<<*itr<<endl;
    itr = find_if(iv.begin(),iv.end(), bind2nd(greater<int>() , 2));				//找到元素大于2的第一个元素位置
    cout<<"find_if: "<<*itr<<endl;
    itr = find_end(iv.begin(),iv.end(), iv2.begin(),iv2.end());				//找到iv序列中最后子序列匹配出现的位置
    cout<<"find_end: "<<*(itr+3)<<endl;
    itr = find_first_of(iv.begin(),iv.end(), iv2.begin(),iv2.end());			//找到iv序列中最先子序列匹配出现的位置
    cout<<"find_end: "<<*(itr+3)<<endl;
    remove(iv.begin(),iv.end(), 6);				//删除元素,向前移,但是容器size不变,后面会剩余数据
    cout<<"remove: "<<iv<<endl;
    vector<int> iv3(12,-1);
    remove_copy(iv.begin(),iv.end(), iv3.begin(), 6);	//删除元素,将数据拷贝到新容器,后面会剩余数据
    cout<<"remove_copy: "<<iv3<<endl;
    remove_if(iv.begin(),iv.end(), bind2nd(less<int>(), 6));	//删除小于6的元素,后面会剩余数据
    cout<<"remove_if: "<<iv<<endl;
    remove_copy_if(iv.begin(),iv.end(), iv3.begin(), bind2nd(less<int>(), 7));		//删除小于7的元素,并拷贝到新容器
    cout<<"remove_copy_if: "<<iv3<<endl;
    replace(iv.begin(),iv.end(), 6, 3);			//将所有元素值为6的改为3
    cout<<"replace: "<<iv<<endl;
    replace_copy(iv.begin(),iv.end(),iv3.begin(), 3, 5);			//将所有元素值为3的改为5,结果保存在新容器中
    cout<<"replace_copy: "<<iv3<<endl;
    replace_if(iv.begin(),iv.end(), bind2nd(less<int>(),5), 2);			//将所有元素值小于5的改为2
    cout<<"replace_if: "<<iv<<endl;
    replace_copy_if(iv.begin(),iv.end(),iv3.begin(), bind2nd(equal_to<int>(),8), 9);			//将所有元素值为8的改为9,结果保存在新容器中
    cout<<"replace_copy_if: "<<iv3<<endl;
    reverse(iv.begin(),iv.end());			cout<<"reverse: "<<iv<<endl;		//反转
    reverse_copy(iv.begin(),iv.end(),iv3.begin());		cout<<"reverse_copy: "<<iv3<<endl;	//反转,结果保存在新容器
    rotate(iv.begin(),iv.begin() + 4, iv.end());	cout<<"rotate: "<<iv<<endl;			//互换元素
    rotate_copy(iv.begin(),iv.begin() + 5,iv.end(),iv3.begin());		cout<<"rotate_copy: "<<iv3<<endl;	//互换元素,结果保存在新容器
    int ia2[] = {2, 8};		vector<int> iv4(ia2,ia2+2);
    cout<<"search:  "<<*search(iv.begin(),iv.end(),iv4.begin(),iv4.end())<<endl;		//查找子序列出现的第一次出现地点
    swap_ranges(iv4.begin(),iv4.end(),iv.begin());				//按区域交换
    cout<<"swap_ranges:  "<<iv<<endl<<iv4<<endl;
    transform(iv.begin(),iv.end(),iv.begin(),bind2nd(minus<int>(), 2));		//所有元素减2
    cout<<"transform:  "<<iv<<endl;
    transform(iv4.begin(),iv4.end(),iv.begin(),iv4.begin(),plus<int>());		//区间对应元素相加
    cout<<"transform:  "<<iv4<<endl;
    /************************************************************************/
    vector<int> iv5(ia,ia+11);	vector<int> iv6(ia+4,ia+8);	vector<int> iv7(15);
    cout<<"max_element:  "<<*max_element(iv5.begin(), iv5.end())<<endl;		//最大元素游标
    cout<<"min_element:  "<<*min_element(iv5.begin(), iv5.end())<<endl;
    cout<<"includes:  "<<includes(iv5.begin(),iv5.end(),iv6.begin(),iv6.end())<<endl;	//iv6中元素是不是都在iv5中,这两个必须排过序
    merge(iv5.begin(),iv5.end(),iv6.begin(),iv6.end(),iv7.begin());	//两个排序号的容器合并
    cout<<"merge:  "<<iv7<<endl;
    partition(iv7.begin(),iv7.end(),bind2nd(equal_to<int>(), 5));	//满足条件的放在左边,不满足条件的放在右边
    cout<<"partition:  "<<iv7<<endl;
    unique(iv5.begin(),iv5.end());				//去重,重复的元素放在后面
    cout<<"unique:  "<<iv5<<endl;
    unique_copy(iv5.begin(),iv5.end(),iv7.begin());				//去重,结果保存在新容器
    cout<<"unique_copy:  "<<iv7<<endl;
}
Exemplo n.º 4
0
void ReadSpill::fill_sca() {
  ChipSCA s;
  for (int i=0; i<int(m_chip.size()); ++i) {
    data_iter start = m_chip[i].begin, end = m_chip[i].end;
    //    for (data_iter i=start; i!=end; ++i) printf("%x ", *i); printf("\n");
    //    printf("end-start-1 = %f, chip = %x\n",double(end-start-1)/129., *(end-1));
    s.chip_id = *(end - 1);
    int nSCA = (end - start - 1) / 129; // chip id takes one word in the end, every SCA takes 64*2 (for ADC) + 1 (for BXID)
    //    if (end - start - 1 - 129 * nSCA == 1) printf("Chip ID is written twice: %x %x\n", *(end-2), *(end-1));
    for (int i=0; i<nSCA; ++i) {
      s.isca = nSCA - 1 - i; // last SCA is stored first
      reverse_copy(start + 128*i,      start + 128*i +  64, s.high.begin()); // copy uses ChipADC(unsigned short int d)
      reverse_copy(start + 128*i + 64, start + 128*i + 128, s.low.begin());  // reverse_copy since last channel comes first in data
      unsigned short int bxid = *(start + 128*nSCA + i); // last bxid is also first
      m_sca[bxid].push_back(s);
    }
  }
}
Exemplo n.º 5
0
 typename util::detail::algorithm_result<
     ExPolicy,
     hpx::util::tagged_pair<
         tag::in(typename traits::range_iterator<Rng>::type),
         tag::out(OutIter)
     >
 >::type
 reverse_copy(ExPolicy && policy, Rng && rng, OutIter dest_first)
 {
     return reverse_copy(std::forward<ExPolicy>(policy),
         boost::begin(rng), boost::end(rng), dest_first);
 }
Exemplo n.º 6
0
/** The Smith Waterman traceback algorithm function. Get result. */
static void smith_waterman_traceback(Result_t *result) {
	int i, j, idx, col, len, maxlen, gap_len;
	char acid1, acid2;
	char *reversed_markup; // revered markup

	col = seq2->length + 1;
	maxlen = seq1->length + seq2->length + 2; //the maximum length.
	reversed_markup = (char *) malloc(maxlen * sizeof(char));

	len = 0;
	result->score = trace_cell.value;
	result->identity = result->similarity = result->gaps = 0;

	i = trace_cell.row;
	j = trace_cell.col;
	while (idx = i * col + j, directions[idx] != 0) { 
		if (directions[idx] == 3) {
			for (gap_len = horizontal_gaps[idx]; gap_len > 0; --gap_len) {
				--j;
				reversed_markup[len++] = '2'; // Sequence #2.
				++result->gaps;
			}
		} else if (directions[idx] == 2) {
			for (gap_len = vertical_gaps[idx]; gap_len > 0; --gap_len) {
				--i;
				reversed_markup[len++] = '1'; // Sequence #1.
				++result->gaps;
			}
		} else if (directions[idx] == 1) {
			acid1 = seq1->acids[--i];
			acid2 = seq2->acids[--j];
			if (acid1 == acid2) {
				reversed_markup[len++] = '|';
				++result->identity;
				++result->similarity;
			} else if (get_score(acid1, acid2) > 0) {
				reversed_markup[len++] = ':';
				++result->similarity;
			} else {
				reversed_markup[len++] = '.';
			}
		}
	}

	result->start1 = i + 1;
	result->start2 = j + 1;
	result->length = len;
	result->markup = (char *) malloc(len * sizeof(char));
	reverse_copy(result->markup, reversed_markup, len);
}
Exemplo n.º 7
0
// Decode a base58-encoded string psz into byte vector vchRet
// returns true if decoding is successful
bool DecodeBase58(const char* psz, std::vector<unsigned char>& vchRet)
{
    CAutoBN_CTX pctx;
    vchRet.clear();
    CBigNum bn58 = 58;
    CBigNum bn = 0;
    CBigNum bnChar;
    while (isspace(*psz))
        psz++;

    // Convert big endian string to bignum
    for (const char* p = psz; *p; p++)
    {
        const char* p1 = strchr(pszBase58, *p);
        if (p1 == NULL)
        {
            while (isspace(*p))
                p++;
            if (*p != '\0')
                return false;
            break;
        }
        bnChar.setuint32((uint32_t)(p1 - pszBase58));
        if (!BN_mul(&bn, &bn, &bn58, pctx))
            throw bignum_error("DecodeBase58 : BN_mul failed");
        bn += bnChar;
    }

    // Get bignum as little endian data
    std::vector<unsigned char> vchTmp = bn.getvch();

    // Trim off sign byte if present
    if (vchTmp.size() >= 2 && vchTmp.end()[-1] == 0 && vchTmp.end()[-2] >= 0x80)
        vchTmp.erase(vchTmp.end()-1);

    // Restore leading zeros
    int nLeadingZeros = 0;
    for (const char* p = psz; *p == pszBase58[0]; p++)
        nLeadingZeros++;
    vchRet.assign(nLeadingZeros + vchTmp.size(), 0);

    // Convert little endian data to big endian
    reverse_copy(vchTmp.begin(), vchTmp.end(), vchRet.end() - vchTmp.size());
    return true;
}
Exemplo n.º 8
0
/*!
 * @brief An entry point of this program
 * @return exit-status
 */
int main(void) {
  static int  a[N];
  static int  b[N];
  static char buf[N];
  uint i;
  for (i = 0; i < N; i++) {
    int n;
    printf("整数を入力してください:a[%u] = ?\b", i);
    fgets(buf, sizeof(buf), stdin);
    DELETE_EOL(buf);
    n = str2int(buf);
    a[i] = n;
  }
  reverse_copy(b, a, N);
  for (i = 0; i < N; i++) {
    printf("b[%u] = %d\n", i, b[i]);
  }
  return EXIT_SUCCESS;
}
Exemplo n.º 9
0
//
// Запуск мультиблочной записи или мультиблочного чтения.
// page_num - номер начальной страницы
// read - если != 0, то запускается операция чтения, == 0 - запись
// В pr1 возвращается указатель на ответ от карты в считанных байтах
// 
static int
init_multiple_op(sdhc_spi_t *m, unsigned page_num, int read, uint8_t **pr1)
{
    int res;
    uint8_t *r1 = 0;
    
    memset(m->databuf, 0xFF, 16);
    if (read)
        m->databuf[0] = CMD_READ_MULTIPLE_BLOCK;
    else m->databuf[0] = CMD_WRITE_MULTIPLE_BLOCK;
    reverse_copy(&m->databuf[1], (uint8_t*)&page_num, 4);
    m->msg.word_count = 16;
    
    res = send_command(m, &r1);
    if (res != FLASH_ERR_OK) return res;

    if (*r1 & ERROR_MASK) return FLASH_ERR_IO;
    
    if (pr1) *pr1 = r1;

    return FLASH_ERR_OK;
}
Exemplo n.º 10
0
// Encode a byte sequence as a base58-encoded string
std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)
{
    CAutoBN_CTX pctx;
    CBigNum bn58 = 58;
    CBigNum bn0 = 0;

    // Convert big endian data to little endian
    // Extra zero at the end make sure bignum will interpret as a positive number
    std::vector<unsigned char> vchTmp(pend-pbegin+1, 0);
    reverse_copy(pbegin, pend, vchTmp.begin());

    // Convert little endian data to bignum
    CBigNum bn;
    bn.setvch(vchTmp);

    // Convert bignum to std::string
    std::string str;
    // Expected size increase from base58 conversion is approximately 137%
    // use 138% to be safe
    str.reserve((pend - pbegin) * 138 / 100 + 1);
    CBigNum dv;
    CBigNum rem;
    while (bn > bn0)
    {
        if (!BN_div(&dv, &rem, &bn, &bn58, pctx))
            throw bignum_error("EncodeBase58 : BN_div failed");
        bn = dv;
        unsigned int c = rem.getuint32();
        str += pszBase58[c];
    }

    // Leading zeroes encoded as base58 zeros
    for (const unsigned char* p = pbegin; p < pend && *p == 0; p++)
        str += pszBase58[0];

    // Convert little endian std::string to big endian
    reverse(str.begin(), str.end());
    return str;
}
Exemplo n.º 11
0
uint32_t tpm_pcr_reset(uint32_t locality, uint32_t pcr)
{
    uint32_t ret, in_size, out_size = 0;
    uint16_t size_of_select;
    tpm_pcr_selection_t pcr_sel = {0,{0,}};

    if ( pcr >= TPM_NR_PCRS || pcr < TPM_PCR_RESETABLE_MIN )
        return TPM_BAD_PARAMETER;

    /* the pcr_sel.pcr_select[size_of_select - 1] should not be 0 */
    size_of_select = pcr / 8 + 1;
    reverse_copy(&pcr_sel.size_of_select, &size_of_select,
                 sizeof(size_of_select));
    pcr_sel.pcr_select[pcr / 8] = 1 << (pcr % 8);

    in_size = sizeof(pcr_sel);
    memcpy(WRAPPER_IN_BUF, (void *)&pcr_sel, in_size);

    ret = tpm_submit_cmd(locality, TPM_ORD_PCR_RESET, in_size, &out_size);

    printf("TPM: Pcr %d reset, return value = %08X\n", pcr, ret);

    return ret;
}
Exemplo n.º 12
0
//
// Операция стирания произвольного числа страниц памяти.
// start_page - номер первой страницы, которую нужно стереть
// end_page - номер последней страницы для стирания
//
static int
sd_erase(flashif_t *flash, unsigned start_page, unsigned end_page)
{
    int res;
    sdhc_spi_t *m = (sdhc_spi_t *) flash;
    uint8_t *r1 = 0;
    
    mutex_lock(&flash->lock);
    
    // Карта может находиться в состоянии многоблочной операции,
    // в этом случае её нужно вернуть в нормальный режим
    if (m->state == SDHC_STATE_MULTIWRITE)
        stop_multiple_write(m);
    if (m->state == SDHC_STATE_MULTIREAD)
        stop_multiple_read(m);
    m->state = SDHC_STATE_IDLE;

    // Установка номера первой страницы
    m->msg.word_count = 16;
    memset(m->databuf, 0xFF, 16);
    m->databuf[0] = CMD_ERASE_WR_BLK_START_ADDR;
    reverse_copy(&m->databuf[1], (uint8_t*)&start_page, 4);
    
    res = send_command(m, &r1);
    if (res != FLASH_ERR_OK) {
        mutex_unlock(&flash->lock);
        return res;
    }
    if (*r1 & ERROR_MASK) {
        mutex_unlock(&flash->lock);
        return FLASH_ERR_IO;
    }
    
    // Установка номера последней страницы
    memset(m->databuf, 0xFF, 16);
    m->databuf[0] = CMD_ERASE_WR_BLK_END_ADDR;
    reverse_copy(&m->databuf[1], (uint8_t*)&end_page, 4);
    res = send_command(m, &r1);
    if (res != FLASH_ERR_OK) {
        mutex_unlock(&flash->lock);
        return res;
    }
    if (*r1 & ERROR_MASK) {
        mutex_unlock(&flash->lock);
        return FLASH_ERR_IO;
    }
    
    // Стирание
    memset(m->databuf, 0xFF, 16);
    m->databuf[0] = CMD_ERASE;
    m->msg.mode |= SPI_MODE_CS_HOLD;
    res = send_command(m, &r1);
    if (res != FLASH_ERR_OK) {
        m->msg.mode &= ~SPI_MODE_CS_HOLD;
        mutex_unlock(&flash->lock);
        return res;
    }
    if (*r1 & ERROR_MASK) {
        m->msg.mode &= ~SPI_MODE_CS_HOLD;
        mutex_unlock(&flash->lock);
        return FLASH_ERR_IO;
    }

    // Ожидание завершения стирания (снятия постоянного 0 с MISO)
    int cnt = 0;
    m->msg.word_count = 1;
    do {
        m->databuf[0] = 0xFF;
        if (spim_trx(m->spi, &m->msg) != SPI_ERR_OK) {
            m->msg.mode &= ~SPI_MODE_CS_HOLD;
            mutex_unlock(&flash->lock);
            return FLASH_ERR_IO;
        }
        cnt++;
    } while (m->databuf[0] == 0);
    
    m->msg.mode &= ~SPI_MODE_CS_HOLD;
    mutex_unlock(&flash->lock);
    return FLASH_ERR_OK;
}
Exemplo n.º 13
0
//
// Определение наличия подключенной карты и её параметров.
//
static int sd_connect(flashif_t *flash)
{
	int res;
	uint8_t *r1 = 0;
	
    sdhc_spi_t *m = (sdhc_spi_t *) flash;
    mutex_lock(&flash->lock);
    
    memset(m->databuf, 0xFF, sizeof(m->databuf));

    // Initial clock to activate SD controller
    m->msg.freq = 400000;
    m->msg.mode |= SPI_MODE_CS_HIGH | SPI_MODE_CS_HOLD;
    m->msg.tx_data = m->databuf;
    m->msg.rx_data = m->databuf;
    m->msg.word_count = 10;
    if (spim_trx(m->spi, &m->msg) != SPI_ERR_OK) {
        mutex_unlock(&flash->lock);
        return FLASH_ERR_IO;
    }

    // Switch SD to SPI mode
    m->databuf[0] = CMD_GO_IDLE_STATE;
    m->databuf[1] = 0x00;
    m->databuf[2] = 0x00;
    m->databuf[3] = 0x00;
    m->databuf[4] = 0x00;
    m->databuf[5] = 0x95;
    m->msg.mode &= ~(SPI_MODE_CS_HIGH | SPI_MODE_CS_HOLD);
    m->msg.word_count = 16; // cmd + max Ncr + r1 + 1byte spare
    res = send_command(m, &r1);
    if (res != FLASH_ERR_OK) {
        mutex_unlock(&flash->lock);
        return res;
    }
    if (*r1 != IN_IDLE_STATE) {
        mutex_unlock(&flash->lock);
        return FLASH_ERR_NOT_CONN;
    }
    
    // Checking SD version
    m->msg.word_count = 20;
    m->databuf[0] = CMD_SEND_IF_COND;
    m->databuf[1] = 0x00;
    m->databuf[2] = 0x00;
    m->databuf[3] = 0x01;
    m->databuf[4] = 0xAA;
    m->databuf[5] = 0x87;
    res = send_command(m, &r1);
    if (res != FLASH_ERR_OK) {
        mutex_unlock(&flash->lock);
        return res;
    }
    if (*(r1 + 4) != 0xAA)
    {
        mutex_unlock(&flash->lock);
        return FLASH_ERR_NOT_CONN;
    }

    if (*r1 != IN_IDLE_STATE) {
        mutex_unlock(&flash->lock);
        return FLASH_ERR_NOT_SUPP;
    }
    
    memset(m->databuf, 0xFF, 20);

    // Initialize SD card
    m->msg.word_count = 16;
    while (1) {
        m->databuf[0] = CMD_APP_CMD;
        m->databuf[1] = 0x00;
        m->databuf[2] = 0x00;
        m->databuf[3] = 0x00;
        m->databuf[4] = 0x00;
        m->databuf[5] = 0xFF;
		res = send_command(m, &r1);
		if (res != FLASH_ERR_OK) {
			mutex_unlock(&flash->lock);
			return res;
		}
		if (*r1 & ERROR_MASK) {
			mutex_unlock(&flash->lock);
			return FLASH_ERR_NOT_SUPP;
		}

        m->databuf[0] = ACMD_SD_SEND_OP_COND;
        m->databuf[1] = 0x40;
        m->databuf[2] = 0x00;
        m->databuf[3] = 0x00;
        m->databuf[4] = 0x00;
        m->databuf[5] = 0xFF;

		res = send_command(m, &r1);
		if (res != FLASH_ERR_OK) {
			mutex_unlock(&flash->lock);
			return res;
		}
		if (*r1 == SD_READY)
			break;
    }
    
    // Checking if the card is SDHC (or SDXC)
    m->msg.word_count = 20;
    m->databuf[0] = CMD_READ_OCR;
    m->databuf[1] = 0x00;
    m->databuf[2] = 0x00;
    m->databuf[3] = 0x00;
    m->databuf[4] = 0x00;
    m->databuf[5] = 0xFF;
    res = send_command(m, &r1);
    if (res != FLASH_ERR_OK) {
        mutex_unlock(&flash->lock);
        return res;
    }
    if (*r1 != SD_READY) {
        mutex_unlock(&flash->lock);
        return FLASH_ERR_BAD_ANSWER;
    }
    if (!(*(r1 + 1) & 0x40)) {
        mutex_unlock(&flash->lock);
        return FLASH_ERR_NOT_SUPP;
    }
    
    m->msg.freq = 25000000;
    
    // Read CSD for card parameters
    m->msg.word_count = 40;
    memset(m->databuf, 0xFF, 40);
	m->databuf[0] = CMD_SEND_CSD;
	m->databuf[1] = 0x00;
	m->databuf[2] = 0x00;
	m->databuf[3] = 0x00;
	m->databuf[4] = 0x00;
	res = send_command(m, &r1);
	if (res != FLASH_ERR_OK) {
		mutex_unlock(&flash->lock);
		return res;
	}
	if (*r1 != SD_READY) {
		mutex_unlock(&flash->lock);
		return FLASH_ERR_BAD_ANSWER;
	}
    
    ++r1;
    res = wait_data_token(m, &r1);
    if (res != FLASH_ERR_OK) return res;
    ++r1;
    
    csd_v2_t csd_v2;
    reverse_copy((uint8_t *) &csd_v2, r1, sizeof(csd_v2_t));
    flash->page_size = 512;
    flash->nb_pages_in_sector = 4 * 1024 * 1024 / 512;
    flash->nb_sectors = (csd_v2.c_size + 1) / 8;

    // Switching to High Speed mode
    memset(m->databuf, 0xFF, 16);
    m->msg.word_count = 16;
	m->databuf[0] = CMD_SWITCH_FUNC;
	m->databuf[1] = 0x80;
	m->databuf[4] = 0xF1;
	res = send_command(m, &r1);
	if (res != FLASH_ERR_OK) {
		mutex_unlock(&flash->lock);
		return res;
	}
	if (*r1 != SD_READY) {
		mutex_unlock(&flash->lock);
		return FLASH_ERR_BAD_ANSWER;
	}
    
    ++r1;
    res = wait_data_token(m, &r1);
    if (res != FLASH_ERR_OK) return res;
    
    int offset = 0;
    if (r1) offset = r1 - m->databuf + m->msg.word_count;
    
    m->msg.word_count = sizeof(m->databuf);
    memset(m->databuf, 0xFF, sizeof(m->databuf));
	if (spim_trx(m->spi, &m->msg) != SPI_ERR_OK) {
        mutex_unlock(&flash->lock);
        return FLASH_ERR_IO;
    }
    
    int high_speed = ((m->databuf[16 - offset] & 0xF) == 1);
    
    memset(m->databuf, 0xFF, sizeof(m->databuf));
	if (spim_trx(m->spi, &m->msg) != SPI_ERR_OK) {
        mutex_unlock(&flash->lock);
        return FLASH_ERR_IO;
    }

    // В случае, если удалось перейти в режим High Speed, увеличиваем
    // частоту передач в SPI до 50 Мгц.
    if (high_speed) m->msg.freq = 50000000;

    mutex_unlock(&flash->lock);
    return FLASH_ERR_OK;
}
Exemplo n.º 14
0
void do_copy(char **argv, int recurse, int preserve, char *username)
{
    int numsource, j, nrofargs;
    size_t len, rem;
    char *source_file, *destination_file, *tempstore, **rcp, *rcpstring;
    char **argvp;
    node_t *nodeptr;

    if (debug) {
	j = 0;
	if (username != NULL)
	    (void)printf("As User: %s\n", username);
	(void)printf("On nodes:\n");
	for (nodeptr = nodelink; nodeptr; nodeptr = nodeptr->next) {
	    if (!(j % 4) && j > 0)
		(void)printf("\n");
	    (void)printf("%s\t", nodeptr->name);
	    j++;
	}
    }
    if (*argv == (char *)NULL) {
	(void)fprintf(stderr, "Must specify at least one file to copy\n");
	exit(EXIT_FAILURE);
    }
    argvp = argv;
    len = strlen(*argvp) + 2;
    while (*++argvp != NULL) {
	    len += 1; /* space */
	    len += strlen(*argvp);
    }

    source_file = calloc(len, sizeof(char));
    rem = len;

    tempstore = NULL;
    strncpy(source_file, *argv, rem);
    rem -= strlen(*argv);
    numsource = 1;
    while (*++argv != NULL) {
	numsource++;
	if (tempstore != NULL) {
	    (void)strncat(source_file, " ", rem);
	    rem -= 1;
	    (void)strncat(source_file, tempstore, rem);
	    rem -= strlen(tempstore);
	}
	tempstore = *argv;
    }
    if (numsource == 1)
	destination_file = strdup(source_file);
    else
	destination_file = strdup(tempstore);

    if (bflag && numsource > 2) {
	fprintf(stderr, "Can only specify one file for reverse copy\n");
	bailout();
    }

    if (bflag && numsource == 1) {
	    free(destination_file);
	    destination_file = strdup(".");
    }
    
    if (debug)
	printf("\nDo Copy: %s %s\n", source_file, destination_file);

    rcp = parse_rcmd("RCP_CMD", "RCP_CMD_ARGS", &nrofargs);
    j = nrofargs;
    rcpstring = build_rshstring(rcp, nrofargs);
    if (recurse) {
	    strcat(rcpstring, " -r ");
	    nrofargs++;
    }
    if (preserve) {
	    strcat(rcpstring, " -p ");
	    nrofargs++;
    }

    if (bflag)
	    reverse_copy(rcpstring, username, source_file, destination_file);
    else if (concurrent)
	    paralell_copy(rcpstring, nrofargs + numsource, username,
		source_file, destination_file);
    else
	    serial_copy(rcpstring, username, source_file, destination_file);
    free(source_file);
    free(destination_file);
    for (nrofargs=0; nrofargs < j-2; nrofargs++) {
	    if (rcp[nrofargs] == NULL)
		break;
	    free(rcp[nrofargs]);
	}
    free(rcp);
}
Exemplo n.º 15
0
bool DecodeBase58(const char* psz, std::vector<unsigned char>& vchRet) {
    CAutoBN_CTX pctx;
    vchRet.clear();
    CBigNum bn58 = 58;
    CBigNum bn = 0;
    CBigNum bnChar;
    // Skip leading spaces.
    while (*psz && isspace(*psz))
        psz++;
    // Skip and count leading '1's.
    int zeroes = 0;
    while (*psz == '1') {
        zeroes++;
        psz++;
    }
    // Convert big endian string to bignum
    for (const char* p = psz; *p; p++)
    {
        const char* p1 = strchr(pszBase58, *p);
        if (p1 == NULL)
        {
            while (isspace(*p))
                p++;
            if (*p != '\0')
                return false;
            break;
        }
        bnChar.setulong(p1 - pszBase58);
        if (!BN_mul(&bn, &bn, &bn58, pctx))
            throw bignum_error("DecodeBase58 : BN_mul failed");
        bn += bnChar;
    }

     // Get bignum as little endian data
    std::vector<unsigned char> vchTmp = bn.getvch();

    // Trim off sign byte if present
    if (vchTmp.size() >= 2 && vchTmp.end()[-1] == 0 && vchTmp.end()[-2] >= 0x80)
        vchTmp.erase(vchTmp.end()-1);

    // Restore leading zeros
    int nLeadingZeros = 0;
    for (const char* p = psz; *p == pszBase58[0]; p++)
        nLeadingZeros++;
    vchRet.assign(nLeadingZeros + vchTmp.size(), 0);

    // Convert little endian data to big endian
    reverse_copy(vchTmp.begin(), vchTmp.end(), vchRet.end() - vchTmp.size());
    return true;
    // Allocate enough space in big-endian base256 representation.
    std::vector<unsigned char> b256(strlen(psz) * 733 / 1000 + 1); // log(58) / log(256), rounded up.
    // Process the characters.
    while (*psz && !isspace(*psz)) {
        // Decode base58 character
        const char *ch = strchr(pszBase58, *psz);
        if (ch == NULL)
            return false;
        // Apply "b256 = b256 * 58 + ch".
        int carry = ch - pszBase58;
        for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); it != b256.rend(); it++) {
            carry += 58 * (*it);
            *it = carry % 256;
            carry /= 256;
        }
        assert(carry == 0);
        psz++;
    }
    // Skip trailing spaces.
    while (isspace(*psz))
        psz++;
    if (*psz != 0)
        return false;
    // Skip leading zeroes in b256.
    std::vector<unsigned char>::iterator it = b256.begin();
    while (it != b256.end() && *it == 0)
        it++;
    // Copy result into output vector.
    vchRet.reserve(zeroes + (b256.end() - it));
    vchRet.assign(zeroes, 0x00);
    while (it != b256.end())
      vchRet.push_back(*(it++));
    return true;
}
Exemplo n.º 16
0
static void TestAlgorithms (void)
{
    static const int c_TestNumbers[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 11, 12, 13, 13, 14, 15, 16, 17, 18 };
    const int* first = c_TestNumbers;
    const int* last = first + VectorSize(c_TestNumbers);
    intvec_t v, buf;
    v.assign (first, last);
    PrintVector (v);

    cout << "swap(1,2)\n";
    swap (v[0], v[1]);
    PrintVector (v);
    v.assign (first, last);

    cout << "copy(0,8,9)\n";
    copy (v.begin(), v.begin() + 8, v.begin() + 9);
    PrintVector (v);
    v.assign (first, last);

    cout << "copy with back_inserter\n";
    v.clear();
    copy (first, last, back_inserter(v));
    PrintVector (v);
    v.assign (first, last);

    cout << "copy with inserter\n";
    v.clear();
    copy (first, first + 5, inserter(v, v.begin()));
    copy (first, first + 5, inserter(v, v.begin() + 3));
    PrintVector (v);
    v.assign (first, last);

    cout << "copy_n(0,8,9)\n";
    copy_n (v.begin(), 8, v.begin() + 9);
    PrintVector (v);
    v.assign (first, last);

    cout << "copy_if(is_even)\n";
    intvec_t v_even;
    copy_if (v, back_inserter(v_even), &is_even);
    PrintVector (v_even);
    v.assign (first, last);

    cout << "for_each(printint)\n{ ";
    for_each (v, &printint);
    cout << "}\n";

    cout << "for_each(reverse_iterator, printint)\n{ ";
    for_each (v.rbegin(), v.rend(), &printint);
    cout << "}\n";

    cout << "find(10)\n";
    cout.format ("10 found at offset %zd\n", abs_distance (v.begin(), find (v, 10)));

    cout << "count(13)\n";
    cout.format ("%zu values of 13, %zu values of 18\n", count(v,13), count(v,18));

    cout << "transform(sqr)\n";
    transform (v, &sqr);
    PrintVector (v);
    v.assign (first, last);

    cout << "replace(13,666)\n";
    replace (v, 13, 666);
    PrintVector (v);
    v.assign (first, last);

    cout << "fill(13)\n";
    fill (v, 13);
    PrintVector (v);
    v.assign (first, last);

    cout << "fill_n(5, 13)\n";
    fill_n (v.begin(), 5, 13);
    PrintVector (v);
    v.assign (first, last);

    cout << "fill 64083 uint8_t(0x41) ";
    TestBigFill<uint8_t> (64083, 0x41);
    cout << "fill 64083 uint16_t(0x4142) ";
    TestBigFill<uint16_t> (64083, 0x4142);
    cout << "fill 64083 uint32_t(0x41424344) ";
    TestBigFill<uint32_t> (64083, 0x41424344);
    cout << "fill 64083 float(0.4242) ";
    TestBigFill<float> (64083, 0x4242f);
#if HAVE_INT64_T
    cout << "fill 64083 uint64_t(0x4142434445464748) ";
    TestBigFill<uint64_t> (64083, UINT64_C(0x4142434445464748));
#else
    cout << "No 64bit types available on this platform\n";
#endif

    cout << "copy 64083 uint8_t(0x41) ";
    TestBigCopy<uint8_t> (64083, 0x41);
    cout << "copy 64083 uint16_t(0x4142) ";
    TestBigCopy<uint16_t> (64083, 0x4142);
    cout << "copy 64083 uint32_t(0x41424344) ";
    TestBigCopy<uint32_t> (64083, 0x41424344);
    cout << "copy 64083 float(0.4242) ";
    TestBigCopy<float> (64083, 0.4242f);
#if HAVE_INT64_T
    cout << "copy 64083 uint64_t(0x4142434445464748) ";
    TestBigCopy<uint64_t> (64083, UINT64_C(0x4142434445464748));
#else
    cout << "No 64bit types available on this platform\n";
#endif

    cout << "generate(genint)\n";
    generate (v, &genint);
    PrintVector (v);
    v.assign (first, last);

    cout << "rotate(4)\n";
    rotate (v, 7);
    rotate (v, -3);
    PrintVector (v);
    v.assign (first, last);

    cout << "merge with (3,5,10,11,11,14)\n";
    const int c_MergeWith[] = { 3,5,10,11,11,14 };
    intvec_t vmerged;
    merge (v.begin(), v.end(), VectorRange(c_MergeWith), back_inserter(vmerged));
    PrintVector (vmerged);
    v.assign (first, last);

    cout << "inplace_merge with (3,5,10,11,11,14)\n";
    v.insert (v.end(), VectorRange(c_MergeWith));
    inplace_merge (v.begin(), v.end() - VectorSize(c_MergeWith), v.end());
    PrintVector (v);
    v.assign (first, last);

    cout << "remove(13)\n";
    remove (v, 13);
    PrintVector (v);
    v.assign (first, last);

    cout << "remove (elements 3, 4, 6, 15, and 45)\n";
    vector<uoff_t> toRemove;
    toRemove.push_back (3);
    toRemove.push_back (4);
    toRemove.push_back (6);
    toRemove.push_back (15);
    toRemove.push_back (45);
    typedef index_iterate<intvec_t::iterator, vector<uoff_t>::iterator> riiter_t;
    riiter_t rfirst = index_iterator (v.begin(), toRemove.begin());
    riiter_t rlast = index_iterator (v.begin(), toRemove.end());
    remove (v, rfirst, rlast);
    PrintVector (v);
    v.assign (first, last);

    cout << "unique\n";
    unique (v);
    PrintVector (v);
    v.assign (first, last);

    cout << "reverse\n";
    reverse (v);
    PrintVector (v);
    v.assign (first, last);

    cout << "lower_bound(10)\n";
    PrintVector (v);
    cout.format ("10 begins at position %zd\n", abs_distance (v.begin(), lower_bound (v, 10)));
    v.assign (first, last);

    cout << "upper_bound(10)\n";
    PrintVector (v);
    cout.format ("10 ends at position %zd\n", abs_distance (v.begin(), upper_bound (v, 10)));
    v.assign (first, last);

    cout << "equal_range(10)\n";
    PrintVector (v);
    TestEqualRange (v);
    v.assign (first, last);

    cout << "sort\n";
    reverse (v);
    PrintVector (v);
    random_shuffle (v);
    sort (v);
    PrintVector (v);
    v.assign (first, last);

    cout << "stable_sort\n";
    reverse (v);
    PrintVector (v);
    random_shuffle (v);
    stable_sort (v);
    PrintVector (v);
    v.assign (first, last);

    cout << "is_sorted\n";
    random_shuffle (v);
    const bool bNotSorted = is_sorted (v.begin(), v.end());
    sort (v);
    const bool bSorted = is_sorted (v.begin(), v.end());
    cout << "unsorted=" << bNotSorted << ", sorted=" << bSorted << endl;
    v.assign (first, last);

    cout << "find_first_of\n";
    static const int c_FFO[] = { 10000, -34, 14, 27 };
    cout.format ("found 14 at position %zd\n", abs_distance (v.begin(), find_first_of (v.begin(), v.end(), VectorRange(c_FFO))));
    v.assign (first, last);

    static const int LC1[] = { 3, 1, 4, 1, 5, 9, 3 };
    static const int LC2[] = { 3, 1, 4, 2, 8, 5, 7 };
    static const int LC3[] = { 1, 2, 3, 4 };
    static const int LC4[] = { 1, 2, 3, 4, 5 };
    cout << "lexicographical_compare";
    cout << "\nLC1 < LC2 == " << lexicographical_compare (VectorRange(LC1), VectorRange(LC2));
    cout << "\nLC2 < LC2 == " << lexicographical_compare (VectorRange(LC2), VectorRange(LC2));
    cout << "\nLC3 < LC4 == " << lexicographical_compare (VectorRange(LC3), VectorRange(LC4));
    cout << "\nLC4 < LC1 == " << lexicographical_compare (VectorRange(LC4), VectorRange(LC1));
    cout << "\nLC1 < LC4 == " << lexicographical_compare (VectorRange(LC1), VectorRange(LC4));

    cout << "\nmax_element\n";
    cout.format ("max element is %d\n", *max_element (v.begin(), v.end()));
    v.assign (first, last);

    cout << "min_element\n";
    cout.format ("min element is %d\n", *min_element (v.begin(), v.end()));
    v.assign (first, last);

    cout << "partial_sort\n";
    reverse (v);
    partial_sort (v.begin(), v.iat(v.size() / 2), v.end());
    PrintVector (v);
    v.assign (first, last);

    cout << "partial_sort_copy\n";
    reverse (v);
    buf.resize (v.size());
    partial_sort_copy (v.begin(), v.end(), buf.begin(), buf.end());
    PrintVector (buf);
    v.assign (first, last);

    cout << "partition\n";
    partition (v.begin(), v.end(), &is_even);
    PrintVector (v);
    v.assign (first, last);

    cout << "stable_partition\n";
    stable_partition (v.begin(), v.end(), &is_even);
    PrintVector (v);
    v.assign (first, last);

    cout << "next_permutation\n";
    buf.resize (3);
    iota (buf.begin(), buf.end(), 1);
    PrintVector (buf);
    while (next_permutation (buf.begin(), buf.end()))
	PrintVector (buf);
    cout << "prev_permutation\n";
    reverse (buf);
    PrintVector (buf);
    while (prev_permutation (buf.begin(), buf.end()))
	PrintVector (buf);
    v.assign (first, last);

    cout << "reverse_copy\n";
    buf.resize (v.size());
    reverse_copy (v.begin(), v.end(), buf.begin());
    PrintVector (buf);
    v.assign (first, last);

    cout << "rotate_copy\n";
    buf.resize (v.size());
    rotate_copy (v.begin(), v.iat (v.size() / 3), v.end(), buf.begin());
    PrintVector (buf);
    v.assign (first, last);

    static const int c_Search1[] = { 5, 6, 7, 8, 9 }, c_Search2[] = { 10, 10, 11, 14 };
    cout << "search\n";
    cout.format ("{5,6,7,8,9} at %zd\n", abs_distance (v.begin(), search (v.begin(), v.end(), VectorRange(c_Search1))));
    cout.format ("{10,10,11,14} at %zd\n", abs_distance (v.begin(), search (v.begin(), v.end(), VectorRange(c_Search2))));
    cout << "find_end\n";
    cout.format ("{5,6,7,8,9} at %zd\n", abs_distance (v.begin(), find_end (v.begin(), v.end(), VectorRange(c_Search1))));
    cout.format ("{10,10,11,14} at %zd\n", abs_distance (v.begin(), find_end (v.begin(), v.end(), VectorRange(c_Search2))));
    cout << "search_n\n";
    cout.format ("{14} at %zd\n", abs_distance (v.begin(), search_n (v.begin(), v.end(), 1, 14)));
    cout.format ("{13,13} at %zd\n", abs_distance (v.begin(), search_n (v.begin(), v.end(), 2, 13)));
    cout.format ("{10,10,10} at %zd\n", abs_distance (v.begin(), search_n (v.begin(), v.end(), 3, 10)));
    v.assign (first, last);

    cout << "includes\n";
    static const int c_Includes[] = { 5, 14, 15, 18, 20 };
    cout << "includes=" << includes (v.begin(), v.end(), VectorRange(c_Includes)-1);
    cout << ", not includes=" << includes (v.begin(), v.end(), VectorRange(c_Includes));
    cout << endl;

    static const int c_Set1[] = { 1, 2, 3, 4, 5, 6 }, c_Set2[] = { 4, 4, 6, 7, 8 };
    intvec_t::iterator setEnd;
    cout << "set_difference\n";
    v.resize (4);
    setEnd = set_difference (VectorRange(c_Set1), VectorRange(c_Set2), v.begin());
    PrintVector (v);
    assert (setEnd == v.end());
    cout << "set_symmetric_difference\n";
    v.resize (7);
    setEnd = set_symmetric_difference (VectorRange(c_Set1), VectorRange(c_Set2), v.begin());
    PrintVector (v);
    assert (setEnd == v.end());
    cout << "set_intersection\n";
    v.resize (2);
    setEnd = set_intersection (VectorRange(c_Set1), VectorRange(c_Set2), v.begin());
    PrintVector (v);
    assert (setEnd == v.end());
    cout << "set_union\n";
    v.resize (9);
    setEnd = set_union (VectorRange(c_Set1), VectorRange(c_Set2), v.begin());
    PrintVector (v);
    assert (setEnd == v.end());
    v.assign (first, last);
}