Exemplo n.º 1
0
int main(int argc, char *argv[])
{
    int size = 1;
    int fd_mem;
    unsigned char data;
    unsigned short addr;
    char help[] = { "Input form ERROR!!!\n"
                    "RWfgpa r/w addr [val]\n"
                    "Example:\n"
                    "w 0x250 0xff\n"
                    "r 0x250\n"
                  };
    char option0[] = "r";
    char option1[] = "w";
    fd_mem = open("/dev/fpga", O_RDWR);
    if(fd_mem < 0) {
        printf("Cannot Open /dev/fpga.\n");
        return -1;
    }
    if (3 == argc && 0 == strcmp(option0, argv[1]))
    {
        printf("Reading FPGA ...\n");
        addr = str_to_hex(argv[2]);
        if (addr >= 0x1000)
        {
            printf("Read Addr. Error!\n");
            printf("%s\n", help);
            return 1;
        }
        lseek(fd_mem, addr, SEEK_SET);
        read(fd_mem, &data, size);
        printf("Val in 0x%x is 0x%x\n", addr, data);
        printf("Read Done!\n");
    }
    else if (4 == argc && 0 == strcmp(option1, argv[1]))
    {
        printf("Writing FPGA ...\n");
        data = str_to_hex(argv[3]);
        addr = str_to_hex(argv[2]);
        if (addr >= 0x1000)
        {
            printf("Addr. Error!\n");
            printf("%s\n", help);
            return 1;
        }
        lseek(fd_mem, addr, SEEK_SET);
        write(fd_mem, &data, size);
        printf("Write the val 0x%x to Addr. 0x%x\n", data, addr);
        printf("Write Done!\n");
    }
    else
        printf("%s\n", help);
    close(fd_mem);
    return 0;
}
Exemplo n.º 2
0
int main(int argc, char* argv[])
{
    int fd;
    unsigned int val = 0;
    unsigned short addr, data;
    char help[] = { "Input form ERROR!!!\n"
                    "Example:\n"
                    "w 0x250 0xff\n"
                    "r 0x251\n"
                  };
    char option0[] = "r";
    char option1[] = "w";
    fd = open("/dev/spidev0.4", O_RDWR);
    if (fd < 0)
    {
        printf("Can't open /dev/spidev1. \n");
        return -1;
    }
    if (3 == argc && 0 == strcmp(option0, argv[1]))
    {
//	printf("Reading Ad9361Reg ...\n");
        addr = str_to_hex(argv[2]);
        if (addr >= 0x3ff)
        {
            printf("Addr. Error!\n");
            printf("%s\n", help);
            return 1;
        }
        printf("Val in 0x%x is 0x%x\n", addr, Ad9361ReadReg(fd, addr));
//	printf("Val in 0x%x is %d\n", addr, Ad9361ReadReg(fd, addr));
//	printf("Read Done!\n");
    }
    else if (4 == argc && 0 == strcmp(option1, argv[1]))
    {
        printf("Writing Ad9361Reg ...\n");
        data = str_to_hex(argv[3]);
        addr = str_to_hex(argv[2]);
        if (addr >= 0x3ff)
        {
            printf("Addr. Error!\n");
            printf("%s\n", help);
            return 1;
        }
        Ad9361WriteReg(fd, addr, data);
        printf("Write the val 0x%x to Addr. 0x%x\n", data, addr);
        printf("Write Done!\n");
    }
    else
        printf("%s\n", help);
    return 0;
}
uint8_t is_macaddr(uint8_t * macstr, uint8_t * digitstr, uint8_t * mac)
{
	uint8_t tmp_mac[6];
	uint8_t tmp_hexstr[4];
	uint8_t i = 0;
	uint8_t len = strlen((char *)macstr);

	if(macstr[0] == 0 || len != 17) return 0;
	
	for( i = 0; i < 6; i++)
	{
		memcpy(tmp_hexstr, macstr+i*3, 3);
		if(tmp_hexstr[2] == 0 || strchr((char *)digitstr, tmp_hexstr[2]))
		{
			tmp_hexstr[2] = 0;
			if(is_hexstr(tmp_hexstr))
			{
				//sscanf(tmp_hexstr,"%x", &tmp_mac[i]);
				str_to_hex(tmp_hexstr, &tmp_mac[i]);
			}
			else
				return 0;
		}
		else
			return 0;
	}
	memcpy(mac, tmp_mac, sizeof(tmp_mac));
	return 1;
}
Exemplo n.º 4
0
jstring Java_com_hid_usbjni_UsbJni_UsbBulkWriteRead(JNIEnv *env, jobject obj, jstring content)
{
	int r;
	char scmd[1024] = {0}, rmsg[1024] = {0};
	unsigned char sbuf[1024], rbuf[1024];
	unsigned int slen, rlen = 0;
	INIT_RETURN_VALUE();

	strncpy(scmd, str, sizeof(scmd) - 1);
	r = str_to_hex(scmd, sbuf, sizeof(sbuf));
	if (r <= 0) {
		pdebug("str_to_hex error: r = %d\n", r);
		snprintf(rmsg, sizeof(rmsg), "str_to_hex error: ret = %d", r);
		r = -1;
		goto out;
	}
	slen = r;

	r = HID_write_read(NULL, sbuf, slen, rbuf, &rlen);
	if (r != 0) {
		snprintf(rmsg, sizeof(rmsg), "HID_write_read error: ret = %d", r);
		goto out;
	}

	if (NULL == hex_to_str(rbuf, rlen, rmsg, sizeof(rmsg))) {
		snprintf(rmsg, sizeof(rmsg), "hex_to_str error");
	}

	r = 0;
out:
	/* 通知虚拟机本地代码不再需要通过 str 访问 Java 字符串。 */
	(*env)->ReleaseStringUTFChars(env, content, (const char *)str);
	RETURN_VAL(r, rmsg);
}
Exemplo n.º 5
0
int  get_next_pattern(void)
{
    int         line_num = 1;
    uint8_t     *p;

	_au8ShaData = (uint8_t *)((uint32_t)_au8ShaData_pool | 0x80000000);

    while (get_line() == 0) {
        //sysprintf("LINE %d = %s\n", line_num, _pi8LineBuff);
        line_num++;

        if (_pi8LineBuff[0] == '#')
            continue;

        if (strncmp(_pi8LineBuff ,"Len", 3) == 0) {
            p = (uint8_t *)&_pi8LineBuff[3];
            while ((*p < '0') || (*p > '9'))
                p++;

            _i32DataLen = str_to_decimal(p);
            continue;
        }

        if (strncmp(_pi8LineBuff ,"Msg", 3) == 0) {
            p = (uint8_t *)&_pi8LineBuff[3];
            while (!is_hex_char(*p)) p++;
            str_to_hex(p, &_au8ShaData[0], 0);
            continue;
        }

        if (strncmp(_pi8LineBuff ,"MD", 2) == 0) {
            p = (uint8_t *)&_pi8LineBuff[2];
            while (!is_hex_char(*p)) p++;
            str_to_hex(p, &_au8ShaDigest[0], 1);
            return 0;
        }
    }
    return -1;
}
Exemplo n.º 6
0
static int print_str_on_hex(char *str, int len)
{
    char *buf = (char*)malloc((20 * len + 1) * sizeof(char));

    printf("print_str_on_hex.%s, %d\n", str, len);

    int iRes = str_to_hex(str, buf, len);
    if(0 == iRes){
        printf("print_str_on_hex:%s\n", buf);
    }
    free(buf);
    return 0;
}
Exemplo n.º 7
0
/*
 * crypt_sha_one() -
 *   return:
 *   thread_p(in):
 *   src(in): 
 *   src_len(in): 
 *   dest_len_p(out):
 * Note:
 */
int
crypt_sha_one (THREAD_ENTRY * thread_p, const char *src, int src_len, char **dest_p, int *dest_len_p)
{
  int hash_length;
  char *dest = NULL;
  char *dest_hex = NULL;
  int dest_len;
  int dest_hex_len;
  int error_status = NO_ERROR;

  assert (src != NULL);

  if (thread_p == NULL)
    {
      thread_p = thread_get_thread_entry_info ();
    }

  *dest_p = NULL;

  if (init_gcrypt () != NO_ERROR)
    {
      return ER_ENCRYPTION_LIB_FAILED;
    }

  hash_length = gcry_md_get_algo_dlen (GCRY_MD_SHA1);
  dest = (char *) db_private_alloc (thread_p, hash_length);
  if (dest == NULL)
    {
      error_status = ER_OUT_OF_VIRTUAL_MEMORY;
      goto exit_and_free;
    }

  dest_len = hash_length;
  gcry_md_hash_buffer (GCRY_MD_SHA1, dest, src, src_len);
  dest_hex = str_to_hex (thread_p, dest, dest_len, &dest_hex, &dest_hex_len);
  if (dest_hex == NULL)
    {
      error_status = ER_OUT_OF_VIRTUAL_MEMORY;
      goto exit_and_free;
    }

  *dest_p = dest_hex;
  *dest_len_p = dest_hex_len;

exit_and_free:
  if (dest != NULL)
    {
      db_private_free_and_init (thread_p, dest);
    }
  return error_status;
}
Exemplo n.º 8
0
void
AES_SetKey(AES_Struct *aes, const unsigned char *key, unsigned int key_len) {
	unsigned char hexkey[64];

	if (key_len != 16 && key_len != 24 && key_len != 32) {
		fprintf(stderr, "AES_SetKey: key must be 128, 192 or 256 bits.\n");
		abort();
	}

	str_to_hex(key, key_len, hexkey);

	makeKey(&aes->encrypt_key, DIR_ENCRYPT, key_len * 8, (char *) hexkey);
	makeKey(&aes->decrypt_key, DIR_DECRYPT, key_len * 8, (char *) hexkey);
	aes->key_gen = 1;
}
Exemplo n.º 9
0
int linux_thread_extra_info(struct target *target,
                            struct connection *connection, char *packet,
                            int packet_size)
{
    int64_t threadid = 0;
    struct linux_os *linux_os = (struct linux_os *)
                                target->rtos->rtos_specific_params;
    sscanf(packet, "qThreadExtraInfo,%" SCNx64, &threadid);
    /*LOG_INFO("lookup extra info for thread %" SCNx64, threadid);*/
    struct threads *temp = linux_os->thread_list;

    while (temp != NULL) {
        if (temp->threadid == threadid) {
            char *pid = " PID: ";
            char *pid_current = "*PID: ";
            char *name = "NAME: ";
            int str_size = strlen(pid) + strlen(name);
            char *tmp_str = (char *)calloc(1, str_size + 50);
            char *tmp_str_ptr = tmp_str;

            /*  discriminate cuurent task */
            if (temp->status == 3)
                tmp_str_ptr += sprintf(tmp_str_ptr, "%s",
                                       pid_current);
            else
                tmp_str_ptr += sprintf(tmp_str_ptr, "%s", pid);

            tmp_str_ptr +=
                sprintf(tmp_str_ptr, "%d", (int)temp->pid);
            tmp_str_ptr += sprintf(tmp_str_ptr, "%s", " | ");
            sprintf(tmp_str_ptr, "%s", name);
            sprintf(tmp_str_ptr, "%s", temp->name);
            char *hex_str =
                (char *)calloc(1, strlen(tmp_str) * 2 + 1);
            str_to_hex(hex_str, tmp_str);
            gdb_put_packet(connection, hex_str, strlen(hex_str));
            free(hex_str);
            free(tmp_str);
            return ERROR_OK;
        }

        temp = temp->next;
    }

    LOG_INFO("thread not found");
    return ERROR_OK;
}
Exemplo n.º 10
0
u32 str_to_u32(u8 *str, u32 len)
{  
    u32 tmp_index = 0;
    u32 tmp_value = 0;
	u32 tmp_tmp = 0;
    
    for(tmp_index = 0; tmp_index < len; tmp_index++,str++)
    {
       	tmp_tmp = str_to_hex(*str);
		if(tmp_tmp == -1)
		{
			return 0;
		}
        tmp_value = 16*tmp_value + tmp_tmp;
    }
    return tmp_value;

}
Exemplo n.º 11
0
static void on_read(void *arg)
{
    module_data_t *mod = arg;

    asc_timer_destroy(mod->timeout_timer);
    mod->timeout_timer = NULL;

    char *buffer = mod->buffer;

    int skip = mod->ts_len_in_buf;
    int r = asc_socket_recv(mod->sock, buffer + skip, HTTP_BUFFER_SIZE - skip);
    if(r <= 0)
    {
        on_close(mod);
        return;
    }
    r += mod->ts_len_in_buf;// Imagine that we've received more (+ previous part)

    int response = 0;

    parse_match_t m[4];

    // parse response
    if(mod->ready_state == 0)
    {
        if(!http_parse_response(buffer, m))
        {
            call_error(mod, "invalid response");
            on_close(mod);
            return;
        }

        lua_newtable(lua);
        response = lua_gettop(lua);

        lua_rawgeti(lua, LUA_REGISTRYINDEX, mod->__lua.oref);
        lua_pushvalue(lua, -2); // duplicate table
        lua_setfield(lua, -2, __response);
        lua_pop(lua, 1); // options

        lua_pushnumber(lua, atoi(&buffer[m[2].so]));
        lua_setfield(lua, response, __code);
        lua_pushlstring(lua, &buffer[m[3].so], m[3].eo - m[3].so);
        lua_setfield(lua, response, __message);

        skip = m[0].eo;
        mod->ready_state = 1;

        if(skip >= r)
        {
            lua_pop(lua, 1); // response
            return;
        }
    }

    // parse headers
    if(mod->ready_state == 1)
    {
        if(!response)
        {
            lua_rawgeti(lua, LUA_REGISTRYINDEX, mod->__lua.oref);
            lua_getfield(lua, -1, __response);
            lua_remove(lua, -2);
            response = lua_gettop(lua);
        }

        int headers_count = 0;
        lua_getfield(lua, response, __headers);
        if(lua_isnil(lua, -1))
        {
            lua_pop(lua, 1);
            lua_newtable(lua);
            lua_pushvalue(lua, -1);
            lua_setfield(lua, response, __headers);
        }
        else
        {
            headers_count = luaL_len(lua, -1);
        }
        const int headers = lua_gettop(lua);

        while(skip < r && http_parse_header(&buffer[skip], m))
        {
            const size_t so = m[1].so;
            const size_t length = m[1].eo - so;
            if(!length)
            {
                skip += m[0].eo;
                mod->ready_state = 2;
                break;
            }
            const char *header = &buffer[skip + so];

            if(!strncasecmp(header, __transfer_encoding, sizeof(__transfer_encoding) - 1))
            {
                const char *val = &header[sizeof(__transfer_encoding) - 1];
                if(!strncasecmp(val, __chunked, sizeof(__chunked) - 1))
                    mod->is_chunked = 1;
            }
            else if(!strncasecmp(header, __connection, sizeof(__connection) - 1))
            {
                const char *val = &header[sizeof(__connection) - 1];
                if(!strncasecmp(val, __close, sizeof(__close) - 1))
                    mod->is_close = 1;
                else if(!strncasecmp(val, __keep_alive, sizeof(__keep_alive) - 1))
                    mod->is_keep_alive = 1;
            }
            else if(!strncasecmp(header, __content_length, sizeof(__content_length) - 1))
            {
                const char *val = &header[sizeof(__content_length) - 1];
                mod->is_content_length = 1;
                mod->chunk_left = strtoul(val, NULL, 10);
            }

            ++headers_count;
            lua_pushnumber(lua, headers_count);
            lua_pushlstring(lua, header, length);
            lua_settable(lua, headers);
            skip += m[0].eo;
        }

        lua_pop(lua, 1); // headers

        if(mod->ready_state == 2)
        {
            get_lua_callback(mod);
            lua_rawgeti(lua, LUA_REGISTRYINDEX, mod->idx_self);
            lua_pushvalue(lua, response);
            lua_call(lua, 2, 0);

            lua_rawgeti(lua, LUA_REGISTRYINDEX, mod->__lua.oref);
            lua_pushnil(lua);
            lua_setfield(lua, -2, __response);
            lua_pop(lua, 1); // options
        }

        lua_pop(lua, 1); // response

        if(skip >= r)
            return;
    }

    // content
    if(mod->ready_state == 2)
    {
        /* Push to stream */
        if (mod->is_ts)
        {
            int pos = skip - mod->ts_len_in_buf;// buffer rewind
            while (r - pos >= TS_PACKET_SIZE)
            {
                module_stream_send(mod, (uint8_t*)&mod->buffer[pos]);
                pos += TS_PACKET_SIZE;
            }
            int left = r - pos;
            if (left > 0)
            {//there is something usefull in the end of buffer, move it to begin
                if (pos > 0) memmove(&mod->buffer[0], &mod->buffer[pos], left);
                mod->ts_len_in_buf = left;
            } else
            {//all data is processed
                mod->ts_len_in_buf = 0;
            }
        }

        // Transfer-Encoding: chunked
        else if(mod->is_chunked)
        {
            while(skip < r)
            {
                if(!mod->chunk_left)
                {
                    if(!http_parse_chunk(&buffer[skip], m))
                    {
                        call_error(mod, "invalid chunk");
                        on_close(mod);
                        return;
                    }

                    char cs_str[] = "00000000";
                    const size_t cs_size = m[1].eo - m[1].so;
                    const size_t cs_skip = 8 - cs_size;
                    memcpy(&cs_str[cs_skip], &buffer[skip], cs_size);

                    uint8_t cs_hex[4];
                    str_to_hex(cs_str, cs_hex, sizeof(cs_hex));
                    mod->chunk_left = (cs_hex[0] << 24)
                                    | (cs_hex[1] << 16)
                                    | (cs_hex[2] <<  8)
                                    | (cs_hex[3]      );
                    skip += m[0].eo;

                    if(!mod->chunk_left)
                    {
                        if(mod->is_keep_alive)
                        {
                            // keep-alive connection
                            get_lua_callback(mod);
                            lua_rawgeti(lua, LUA_REGISTRYINDEX, mod->idx_self);
                            lua_pushstring(lua, "");
                            lua_call(lua, 2, 0);
                        }
                        else
                        {
                            // close connection
                            on_close(mod);
                        }
                        return;
                    }
                }

                const size_t r_skip = r - skip;
                get_lua_callback(mod);
                lua_rawgeti(lua, LUA_REGISTRYINDEX, mod->idx_self);
                if(mod->chunk_left < r_skip)
                {
                    lua_pushlstring(lua, &buffer[skip], mod->chunk_left);
                    lua_call(lua, 2, 0);
                    skip += mod->chunk_left;
                    mod->chunk_left = 0;
                    if(buffer[skip] == '\r')
                        ++skip;
                    if(buffer[skip] == '\n')
                        ++skip;
                    else
                    {
                        call_error(mod, "invalid chunk");
                        on_close(mod);
                        return;
                    }
                }
                else
                {
                    lua_pushlstring(lua, &buffer[skip], r_skip);
                    lua_call(lua, 2, 0);
                    mod->chunk_left -= r_skip;
                    break;
                }
            }
        }

        // Content-Length
        else if(mod->is_content_length)
        {
            if(mod->chunk_left > 0)
            {
                const size_t r_skip = r - skip;
                get_lua_callback(mod);
                lua_rawgeti(lua, LUA_REGISTRYINDEX, mod->idx_self);
                if(mod->chunk_left > r_skip)
                {
                    lua_pushlstring(lua, &buffer[skip], r_skip);
                    lua_call(lua, 2, 0);
                    mod->chunk_left -= r_skip;
                }
                else
                {
                    lua_pushlstring(lua, &buffer[skip], mod->chunk_left);
                    lua_call(lua, 2, 0);
                    mod->chunk_left = 0;

                    if(mod->is_keep_alive)
                    {
                        // keep-alive connection
                        get_lua_callback(mod);
                        lua_rawgeti(lua, LUA_REGISTRYINDEX, mod->idx_self);
                        lua_pushstring(lua, "");
                        lua_call(lua, 2, 0);
                    }
                    else
                    {
                        // close connection
                        on_close(mod);
                    }
                    return;
                }
            }
        }

        // Stream
        else
        {
            get_lua_callback(mod);
            lua_rawgeti(lua, LUA_REGISTRYINDEX, mod->idx_self);
            lua_pushlstring(lua, &buffer[skip], r - skip);
            lua_call(lua, 2, 0);
        }
    }
} /* on_read */
Exemplo n.º 12
0
int main(int argc, char *argv[])
{

    u32 sig_id = 0;
    u32 head_len = 0;
    u32 data_len = 0;
    u32 buf_len = 0;
    u32 i = 0;
    u32 tmp_value_a = 0;
    u32 tmp_value_b = 0;

    s8 *data =  NULL;
    s8 *buf =  NULL;
    s8 *prt = NULL;
    u32 *tmp_u32_prt = NULL;
    
    
    s32 rtn_code = 0;
    s32 ret = 0;

    u32 type_count;
    s32 dev_type;

    u32 type_bits;
    u32 slot_max;
    struct ifm_board_info_s * slot_info;

    
    if (argc < 2)
    {
        printf("input parameter error\r\n");
        usage();
        return 0;
    }

    data = (s8 *)argv[1];
    data_len = (u32)strlen(data);
    
    sig_id = str_to_u32((u8 *)data,data_len);    
    
    head_len = sizeof(u32) * 3;
    
    if (2 == argc)
    {
        buf_len = head_len;
        buf = (s8 *)malloc(buf_len);
        if(NULL == buf)
        {
            printf("memory error\r\n");
            return 0;
        }
        memset(buf, 0x0, head_len);

        tmp_u32_prt = (u32 *)buf;

        *tmp_u32_prt = sig_id;
        tmp_u32_prt++; 
        *tmp_u32_prt = 0;
        tmp_u32_prt++;
        *tmp_u32_prt = 0;
    } 
    else
    {
        data = (s8 *)argv[2];
        data_len = (u32)strlen(data);
        if(data_len%2)
        {
            printf("input hex error1\r\n");
            usage();
            return 0;
        }

        buf_len = (data_len/2) + head_len;
        buf = (s8 *)malloc(buf_len);
        if(NULL == buf)
        {
            printf("memory error\r\n");
            return 0;
        }
        memset(buf, 0x0, buf_len);

        tmp_u32_prt = (u32 *)buf;

        *tmp_u32_prt = sig_id;
        tmp_u32_prt++;        
        *tmp_u32_prt = 1;
        tmp_u32_prt++;
        *tmp_u32_prt = data_len/2;

        prt = buf + head_len;

    
        for(i = 0; i < data_len - 1; i += 2, data += 2)
        {
            tmp_value_a = (u32)str_to_hex(*((s8 *)data));
            tmp_value_b = (u32)str_to_hex(*((s8 *)(data + 1)));
            tmp_value_b = tmp_value_a*16 + tmp_value_b;

            *prt =(u8)tmp_value_b;
            prt++;
        }
    }

    type_bits = BIT(UAG_BOARD) | BIT(IPS_BOARD);
    ret = ifm_get_board_count_by_type(type_bits, &type_count);
    if(ret)
    {
        return ret;
    }

    if (type_count == 0)
    {
        rtn_code = conplat_syscall(MODULEID_DCDM,DCDM_CMD_PCRE_TEST,(void *)buf,buf_len,&ret);
    }
    else
    {
        
        ret = ifm_get_slot_status(&slot_max, &slot_info);
        if(ret)
        {
            return ret;
        }

        for (i = 0; i < slot_max; i++)
        {
            dev_type = slot_info[i].slot_type;
            if(slot_info[i].is_available && (type_bits & BIT(dev_type)))
            {
                rtn_code = conplat_syscall(DPI_MODULEID_DCDM | dev_type,DCDM_CMD_PCRE_TEST,(void *)buf,buf_len,&ret);
            }
        }
    }
    
    if( (ERROR_SUCCESS != rtn_code) || (ERROR_SUCCESS != ret) )
    {
        printf("\r\ndcdmd_pcre_test failed!!\r\n");
    }
    else
    {
        printf("\r\ndcdmd_pcre_test succeed\r\n");
    }
    
    free(buf);
    return 0;    
}
Exemplo n.º 13
0
int parse_variable_format(query_var_t * var, char * format, const vars_container_t * vars_ctnr)
{
    char * pt = format;
    if(*pt != '(')	/* Offset + length without conditions */
    {
        if( (pt = strchr(format, ':')) )
            *pt = '\0';

        if(sscanf(format, "%hu", &var->offset) < 1)
            return FAIL;

        if(!pt)
        {   /* Offset only */
            var->length = 0;
            return OK;
        }

        format = pt + 1;
        if(sscanf(format, "%hu", &var->length) < 1)
            return FAIL;
    }
    else
    {   /* Condition found */
        while(format[0] == '(')
        {
            /* Searching last condition for this variable */
            dhcp_var_cond_t * condition;
            dhcp_var_cond_t ** last = &var->condition;
            while(*last)
                last = &(*last)->next_condition;
            condition = calloc(1, sizeof(dhcp_var_cond_t));
            CHECK_VALUE_CONF(condition, "Can't allocate memory for variable condition!", FAIL);
            *last = condition;

            /* Start parsing condition offset */
            ++format;
            if(*format == '$')
            {   /* Found offset variable */
                CHECK_VALUE_CONF( (pt = strchr(++format, '$')), "Unterminated variable name.", FAIL);
                *pt = '\0';
                condition->offset_var = get_var_by_name(format, vars_ctnr);
                if(!condition->offset_var)
                {
                    fprintf(stderr, "Undefined variable in condition offset: \"%s\"\n", format);
                    return FAIL;
                }
                *pt = '$';
            }
            else
            {
                if(sscanf(format, "%hu", &condition->offset) < 1)
                {
                    fprintf(stderr, "Invalid condition offset: \"%s\"\n", format);
                    return FAIL;
                }
            }

            /* Start parsing condition value */
            CHECK_VALUE_CONF( (pt = strchr(format, '=')), "Can't parse condition value.", FAIL);
            format = pt + 1;
            if(*format == '$')
            {   /* Found value variable */
                CHECK_VALUE_CONF( (pt = strchr(++format, '$')), "Unterminated variable value.", FAIL);
                *pt = '\0';
                condition->value_var = get_var_by_name(format, vars_ctnr);
                if(!condition->value_var)
                {
                    fprintf(stderr, "Undefined variable in condition value: \"%s\"\n", format);
                    return FAIL;
                }
                *pt = '$';
                CHECK_VALUE_CONF( (pt = strchr(format, ')')) ,
                                  "Error parsing condition: closed bracket not found.", FAIL);
                format = pt + 1;
            }
            else
            {   /* Check value length and store him if value is not variable */
                if(strncmp(format, "0x", strlen("0x")))
                {
                    fprintf(stderr, "Invalid condition value format: \"%s\"\n", format);
                    return FAIL;
                }
                format += strlen("0x");

                CHECK_VALUE_CONF( (pt = strchr(format, ')')) ,
                                  "Error parsing condition: closed bracket not found.", FAIL);

                if((pt - format) % 2)	/* Not even number of bytes format */
                {
                    *pt = '\0';
                    fprintf(stderr, "Odd number of chars for hex string: 0x%s\n", format);
                    return FAIL;
                }
                condition->size = (pt - format) / 2;	/* Size in bytes instead size in chars */

                condition->value = malloc(sizeof(condition->value[0]) * condition->size);
                CHECK_VALUE_CONF(condition->value, "Can't allocate memory for store condition value!", FAIL);

                if(!str_to_hex(condition->size, format, condition->value))
                {
                    fprintf(stderr, "Invalid condition value: \"%s\"\n", format);
                    return FAIL;
                }

                format = pt + 1;
            }

            /* Get 'if true' values */

            if(strncmp(format, "0x", strlen("0x")))
            {   /* This is not constant value. Get offset and length */
                if(sscanf(format, "%hu", &condition->true_offset) < 1)
                {
                    fprintf(stderr, "Invalid condition true offset: \"%s\"\n", format);
                    return FAIL;
                }

                if( !(pt = strchr(format, ':')) )
                {
                    fprintf(stderr, "Condition true length not found: \"%s\"\n", format);
                    return FAIL;
                }

                format = pt + 1;
                if(sscanf(format, "%hu", &condition->true_length) < 1)
                {
                    fprintf(stderr, "Invalid condition true length: \"%s\"\n", format);
                    return FAIL;
                }

                CHECK_VALUE_CONF( (pt = strchr(format, '|')), "'if false' condition ommited.", FAIL);

                format = pt + 1;
            }
            else
            {   /* Constant value from config */
                format += strlen("0x");
                CHECK_VALUE_CONF( (pt = strchr(format, '|')), "'if false' condition ommited.", FAIL);

                condition->true_length = pt - format;
                if(condition->true_length % 2)
                {
                    *pt = '\0';
                    fprintf(stderr, "Odd number of chars for hex string: 0x%s in true constant.\n", format);
                    return FAIL;
                }
                condition->true_length /= 2;
                condition->true_value = malloc(condition->true_length * sizeof(condition->true_value[0]));
                CHECK_VALUE_CONF(condition->true_value,
                                 "Can't allocate memory for store condition true value.", FAIL);

                if(!str_to_hex(condition->true_length, format, condition->true_value))
                {
                    fprintf(stderr, "Invalid condition true constant value: \"%s\"\n", format);
                    return FAIL;
                }
                format = pt + 1;
            }
            /* Get 'if false' values */

            if(format[0] == '(')	/* If false - go to next condition */
                continue;

            if(strlen(format) < 3)	/* 3 minimal length: "digit:digit" = 3 chars */
            {
                fprintf(stderr, "Invalid condition false format length - too short: \"%s\"\n", format);
                return FAIL;
            }

            if(strncmp(format, "0x", strlen("0x")))
            {
                if(sscanf(format, "%hu", &condition->false_offset) < 1)
                {
                    fprintf(stderr, "Invalid condition false offset: \"%s\"\n", format);
                    return FAIL;
                }

                if( !(pt = strchr(format, ':')) )
                {
                    fprintf(stderr, "Condition false length not found: \"%s\"\n", format);
                    return FAIL;
                }

                format = pt + 1;
                if(sscanf(format, "%hu", &condition->false_length) < 1)
                {
                    fprintf(stderr, "Invalid condition false length: \"%s\"\n", format);
                    return FAIL;
                }
            }
            else
            {   /* Constant value from config */
                format += strlen("0x");

                condition->false_length = strlen(format);
                if(condition->false_length % 2)
                {
                    fprintf(stderr, "Odd number of chars for hex string: 0x%s in false constant.\n", format);
                    return FAIL;
                }
                condition->false_length /= 2;
                condition->false_value = malloc(condition->false_length * sizeof(condition->false_value[0]));
                CHECK_VALUE_CONF(condition->false_value,
                                 "Can't allocate memory for store condition false value.", FAIL);

                if(!str_to_hex(condition->false_length, format, condition->false_value))
                {
                    fprintf(stderr, "Invalid condition false constant value: \"%s\"\n", format);
                    return FAIL;
                }
            }

            /* This was last condition */
            break;
        }

    }

    return OK;
}
Exemplo n.º 14
0
int gdb_thread_packet(struct connection *connection, char *packet, int packet_size)
{
	struct target *target = get_target_from_connection(connection);

	if (strstr(packet, "qThreadExtraInfo,"))
	{
		if ((target->rtos != NULL) && (target->rtos->thread_details != NULL) && (target->rtos->thread_count != 0))
		{
			threadid_t threadid = 0;
			int found = -1;
			sscanf(packet, "qThreadExtraInfo,%" SCNx64, &threadid );

			if ((target->rtos != NULL) && (target->rtos->thread_details
					!= NULL)) {
				int thread_num;
				for (thread_num = 0; thread_num
						< target->rtos->thread_count; thread_num++) {
					if (target->rtos->thread_details[thread_num].threadid
							== threadid) {
						if (target->rtos->thread_details[thread_num].exists) {
							found = thread_num;
						}
					}
				}
			}
			if (found == -1) {
				gdb_put_packet(connection, "E01", 3); // thread not found
				return ERROR_OK;
			}

			struct thread_detail* detail = &target->rtos->thread_details[found];

			int str_size = 0;
			if ( detail->display_str != NULL )
			{
				str_size += strlen(detail->display_str);
			}
			if ( detail->thread_name_str != NULL )
			{
				str_size += strlen(detail->thread_name_str);
			}
			if ( detail->extra_info_str != NULL )
			{
				str_size += strlen(detail->extra_info_str);
			}

			char * tmp_str = (char*) malloc( str_size + 7 );
			char*  tmp_str_ptr = tmp_str;

			if ( detail->display_str != NULL )
			{
				tmp_str_ptr += sprintf( tmp_str_ptr, "%s", detail->display_str );
			}
			if ( detail->thread_name_str != NULL )
			{
				if ( tmp_str_ptr != tmp_str )
				{
					tmp_str_ptr += sprintf( tmp_str_ptr, " : " );
				}
				tmp_str_ptr += sprintf( tmp_str_ptr, "%s", detail->thread_name_str );
			}
			if ( detail->extra_info_str != NULL )
			{
				if ( tmp_str_ptr != tmp_str )
				{
					tmp_str_ptr += sprintf( tmp_str_ptr, " : " );
				}
				tmp_str_ptr += sprintf( tmp_str_ptr, " : %s", detail->extra_info_str );
			}

			assert(strlen(tmp_str) ==
				(size_t) (tmp_str_ptr - tmp_str));

			char * hex_str = (char*) malloc( strlen(tmp_str)*2 +1 );
			str_to_hex( hex_str, tmp_str );

			gdb_put_packet(connection, hex_str, strlen(hex_str));
			free(hex_str);
			free(tmp_str);
			return ERROR_OK;

		}
		gdb_put_packet(connection, "", 0);
		return ERROR_OK;
	}
	else if (strstr(packet, "qSymbol"))
	{
		if ( target->rtos != NULL )
		{
			int next_symbol_num = -1;
			if (target->rtos->symbols == NULL)
			{
				target->rtos->type->get_symbol_list_to_lookup( &target->rtos->symbols );
			}
			if (0 == strcmp( "qSymbol::", packet ) )
			{
				// first query -
				next_symbol_num = 0;
			}
			else
			{
				int64_t value = 0;
				char * hex_name_str = malloc( strlen(packet));
				char * name_str;
				int symbol_num;

				char* found = strstr( packet, "qSymbol::" );
				if (0 == found )
				{
					sscanf(packet, "qSymbol:%" SCNx64 ":%s", &value, hex_name_str);
				}
				else
				{
					// No value returned by GDB - symbol was not found
					sscanf(packet, "qSymbol::%s", hex_name_str);
				}
				name_str = (char*) malloc( 1+ strlen(hex_name_str) / 2 );

				hex_to_str( name_str, hex_name_str );


				symbol_num = 0;
				while ( ( target->rtos->symbols[ symbol_num ].symbol_name != NULL ) && ( 0 != strcmp( target->rtos->symbols[ symbol_num ].symbol_name, name_str ) ) )
				{
					symbol_num++;
				}


				if ( target->rtos->symbols[ symbol_num ].symbol_name == NULL )
				{
					LOG_OUTPUT("ERROR: unknown symbol\r\n");
					gdb_put_packet(connection, "OK", 2);
					return ERROR_OK;
				}

				target->rtos->symbols[ symbol_num ].address = value;

				next_symbol_num = symbol_num+1;
				free( hex_name_str );
				free( name_str );

			}

			int symbols_done = 0;
			if ( target->rtos->symbols[ next_symbol_num ].symbol_name == NULL )
			{
				if ( ( target->rtos_auto_detect == false ) ||
					 ( 1 == target->rtos->type->detect_rtos( target ) ) )
				{
					// Found correct RTOS or not autodetecting
					if ( target->rtos_auto_detect == true )
					{
						LOG_OUTPUT( "Auto-detected RTOS: %s\r\n",target->rtos->type->name );
					}
					symbols_done = 1;
				}
				else
				{
					// Auto detecting RTOS and currently not found
					if( 1 != rtos_try_next( target ) )
					{
						// No more RTOS's to try
						symbols_done = 1;
					}
					else
					{
						next_symbol_num = 0;
						target->rtos->type->get_symbol_list_to_lookup( &target->rtos->symbols );
					}

				}
			}


			if ( symbols_done == 1 )
			{
				target->rtos_auto_detect = false;
				target->rtos->type->create( target );
				target->rtos->type->update_threads(target->rtos);
				// No more symbols needed
				gdb_put_packet(connection, "OK", 2);
				return ERROR_OK;

			}
			else
			{
				char* symname = target->rtos->symbols[ next_symbol_num ].symbol_name;
				char qsymstr[] = "qSymbol:";
				char * opstring = (char*)malloc(sizeof(qsymstr)+strlen(symname)*2+1);
				char * posptr = opstring;
				posptr += sprintf( posptr, "%s", qsymstr );
				str_to_hex( posptr, symname );
				gdb_put_packet(connection, opstring, strlen(opstring));
				free(opstring);
				return ERROR_OK;
			}

		}
		gdb_put_packet(connection, "OK", 2);
		return ERROR_OK;
	}
	else if (strstr(packet, "qfThreadInfo"))
	{
		int i;
		if ( ( target->rtos != NULL ) && ( target->rtos->thread_count != 0 ) )
		{

			char* out_str = (char*) malloc(17 * target->rtos->thread_count + 5);
			char* tmp_str = out_str;
			tmp_str += sprintf(tmp_str, "m");
			for (i = 0; i < target->rtos->thread_count; i++) {
				if (i != 0) {
					tmp_str += sprintf(tmp_str, ",");
				}
				tmp_str += sprintf(tmp_str, "%016" PRIx64,
						target->rtos->thread_details[i].threadid);
			}
			tmp_str[0] = 0;
			gdb_put_packet(connection, out_str, strlen(out_str));
		}
		else
		{
			gdb_put_packet(connection, "", 0);
		}

		return ERROR_OK;
	}
	else if (strstr(packet, "qsThreadInfo"))
	{
		gdb_put_packet(connection, "l", 1);
		return ERROR_OK;
	}
	else if (strstr(packet, "qAttached"))
	{
		gdb_put_packet(connection, "1", 1);
		return ERROR_OK;
	}
	else if (strstr(packet, "qOffsets"))
	{
		char offsets[] = "Text=0;Data=0;Bss=0";
		gdb_put_packet(connection, offsets, sizeof(offsets)-1);
		return ERROR_OK;
	}
	else if (strstr(packet, "qC"))
	{
		if( target->rtos!=NULL )
		{
			char buffer[15];
			int size;
			size = snprintf(buffer, 15, "QC%08X", (int)target->rtos->current_thread);
			gdb_put_packet(connection, buffer, size);
		}
		else
		{
			gdb_put_packet(connection, "QC0", 3);
		}
		return ERROR_OK;
	}
	else if ( packet[0] == 'T' ) // Is thread alive?
	{
		threadid_t threadid;
		int found = -1;
		sscanf(packet, "T%" SCNx64, &threadid);
		if ((target->rtos != NULL) && (target->rtos->thread_details
				!= NULL)) {
			int thread_num;
			for (thread_num = 0; thread_num
					< target->rtos->thread_count; thread_num++) {
				if (target->rtos->thread_details[thread_num].threadid
						== threadid) {
					if (target->rtos->thread_details[thread_num].exists) {
						found = thread_num;
					}
				}
			}
		}
		if (found != -1) {
			gdb_put_packet(connection, "OK", 2); // thread alive
		} else {
			gdb_put_packet(connection, "E01", 3); // thread not found
		}
		return ERROR_OK;
	}
	else if ( packet[0] == 'H') // Set current thread ( 'c' for step and continue, 'g' for all other operations )
	{
		if (packet[1] == 'g')
		{
			sscanf(packet, "Hg%16" SCNx64, &current_threadid);
		}
		gdb_put_packet(connection, "OK", 2);
		return ERROR_OK;
	}

	return GDB_THREAD_PACKET_NOT_CONSUMED;
}
Exemplo n.º 15
0
void parse_options(int argc, char **argv, cmd_args *args)
{
    static char *usage = "NAME                                                 \n"
                         "       percolation - 2D site percolation             \n"  
                         "                                                     \n"
                         "SYNOPSIS                                             \n"
                         "       percolation [OPTION]...                       \n"
                         "                                                     \n"
                         "DESCRIPTION                                          \n"
                         "       -w, --width                                   \n"
                         "           grid width                                \n"
                         "                                                     \n"
                         "       -h, --height                                  \n"
                         "           grid height                               \n"
                         "                                                     \n"
                         "       -p, --probability                             \n"
                         "           site vacancy probability                  \n"
                         "                                                     \n"
                         "       -o, --output                                  \n"
                         "           output image file (either png or svg)     \n"
                         "                                                     \n"
                         "       -s, --size                                    \n"
                         "           maximum image size                        \n"
                         "                                                     \n"
                         "       -c, --color                                   \n"
                         "           color for the full sites in form '#rrggbb'\n"
                         "           or as a lookup table index                \n"                         
                         "                                                     \n"
                         "       -l, --list-colors                             \n"
                         "           dispalys a list of predefined colors and  \n"
                         "           their indexes (an argument for -c option) \n"
                         "                                                     \n"
                         "       -r, --recursive                               \n"
                         "           enable recursive flow propagation         \n"
                         "                                                     \n"  
                         "       -O, --no-output                               \n" 
                         "           disable image output                      \n" 
                         "                                                     \n"                        
                         "       --help                                        \n"
                         "           display this help and exit                \n" 
                         "                                                     \n"
                         "AUTHOR                                               \n"  
                         "       Written by Taras Kuzyo                        \n"                         
                         "                                                     \n";

    
    static const struct option long_opts[] = {
                        { "width",       required_argument, NULL, 'w' }, 
                        { "height",      required_argument, NULL, 'h' },    
                        { "probability", required_argument, NULL, 'p' },
                        { "output",      required_argument, NULL, 'o' },       
                        { "size",        required_argument, NULL, 's' },
                        { "color",       required_argument, NULL, 'c' },
                        { "list-colors", no_argument,       NULL, 'l' },
                        { "recursive",   no_argument,       NULL, 'r' },
                        { "no-output",   no_argument,       NULL, 'O' },
                        { "help",        no_argument,       NULL,  0  },
                        {  NULL,         no_argument,       NULL,  0  }  };
            
    char *options = "w:h:p:p:o:s:c:lrO";

    int opt = 0;
    int long_index = 0;
    
    /* minimal values for some arguments */
    const int min_width = 2, min_height = 2, min_size = 64;
    /* flags indicating option invocation */
    int width_flag = 0, height_flag = 0, prob_flag = 0;
    
    /* default values for the arguments */
    int recursive_flag = 0;
    int img_output = 1;
    int width = 0, height = 0;
    double prob = 0.0, size = 800.0;    
    char filename[STR_BUF_SIZE] = "";
    int color = COLOR_PAD;
    
    
    /* print usage if no args */
    if (argc == 1)
    {
        printf("%s", usage);
        exit(0);
    }
    
    /* process options */
    while ((opt = getopt_long(argc, argv, options, long_opts, &long_index)) != -1)
    {
        switch (opt)
        {
            case 'w':
                width_flag = 1;
                width = atoi(optarg);
                break;
                
            case 'h':
                height_flag = 1;
                height = atoi(optarg);
                break;
                
            case 'p':
                prob_flag = 1;
                prob = atof(optarg);
                break;
            
            case 's':
                /* image maximum size 
                   (either width of height) in px */
                size = atof(optarg);
                break;
                
            case 'o':
                /* set custum output filename */
                strcpy(filename, optarg);
                break;
                
            case 'c':
                /* try converting from hex representation
                   use simple integer conversion if failed */
                if ( ! str_to_hex(optarg, &color) )
                    color = COLOR_PAD + atoi(optarg);
                break;
                
            case 'l':
                /* list colors indexes available */
                colormap_show();
                exit(0);
                break;
                
            case 'r':
                recursive_flag = 1;
                break;
                
            case 'O':
                img_output = 0;
                break;
                
            case 0:
                printf("%s", usage);
                exit(0);
                break;
                        
            case '?':
                exit(1);
                break;
                
            default:
                printf("%s: unknown option '%s'\n", argv[0], optarg);
                exit(1);
                break;
        }
    }
    /* check if required arguments were passed */
    if (!width_flag)
    {
        printf("%s: missing '-w' option\n", argv[0]);
        exit(1);
    }
    if (!height_flag)
    {
        printf("%s: missing '-h' option\n", argv[0]);
        exit(1);
    }
    if (!prob_flag)
    {
        printf("%s: missing '-p' option\n", argv[0]);
        exit(1);
    }
    /* check probability range */
    if (prob < 0.0 || prob > 1.0)
    {
        printf("%s: invalid probability value: %g\n", argv[0], prob);
        exit(1);
    }
    /* check if color index is valid */
    if (color < 0 || color - COLOR_PAD >= NUM_COLORS)
    {
        printf("%s: unknown color code: %x\n", argv[0], (int)(color));
        exit(1);
    }
    
    size   = (size   < min_size  ) ? min_size   : size;
    width  = (width  < min_width ) ? min_width  : width;
    height = (height < min_height) ? min_height : height;
    
    /* set default image filename */
    if (strlen(filename) == 0)
        snprintf(filename, STR_BUF_SIZE, "output_%d_%d_%g.png", width, height, prob);
        
    args->width      = width;
    args->height     = height;
    args->prob       = prob;
    args->size       = size;
    args->color      = color;
    args->img_output = img_output;
    args->recursive  = recursive_flag;
    strcpy(args->filename, filename);
}
Exemplo n.º 16
0
/*
 * crypt_sha_two() -
 *   return:
 *   thread_p(in):
 *   src(in):
 *   src_len(in):
 *   need_hash_len(in):
 *   dest_p(out)
 *   dest_len_p(out):
 * Note:
 */
int
crypt_sha_two (THREAD_ENTRY * thread_p, const char *src, int src_len, int need_hash_len, char **dest_p, int *dest_len_p)
{
  int hash_length;
  int algo;
  char *dest = NULL;
  int dest_len;
  char *dest_hex = NULL;
  int dest_hex_len;
  int error_status = NO_ERROR;

  assert (src != NULL);

  if (thread_p == NULL)
    {
      thread_p = thread_get_thread_entry_info ();
    }

  *dest_p = NULL;

  switch (need_hash_len)
    {
    case 0:
    case 256:
      algo = GCRY_MD_SHA256;
      break;
    case 224:
      algo = GCRY_MD_SHA224;
      break;
    case 384:
      algo = GCRY_MD_SHA384;
      break;
    case 512:
      algo = GCRY_MD_SHA512;
      break;
    default:
      return NO_ERROR;
    }

  if (init_gcrypt () != NO_ERROR)
    {
      return ER_ENCRYPTION_LIB_FAILED;
    }

  hash_length = gcry_md_get_algo_dlen (algo);
  dest_len = hash_length;
  dest = (char *) db_private_alloc (thread_p, hash_length);
  if (dest == NULL)
    {
      error_status = ER_OUT_OF_VIRTUAL_MEMORY;
      goto exit_and_free;
    }

  gcry_md_hash_buffer (algo, dest, src, src_len);
  dest_hex = str_to_hex (thread_p, dest, dest_len, &dest_hex, &dest_hex_len);
  if (dest_hex == NULL)
    {
      error_status = ER_OUT_OF_VIRTUAL_MEMORY;
      goto exit_and_free;
    }

  *dest_p = dest_hex;
  *dest_len_p = dest_hex_len;

exit_and_free:
  if (dest != NULL)
    {
      db_private_free_and_init (thread_p, dest);
    }
  return error_status;
}