コード例 #1
0
ファイル: dcrypt-gnutls.c プロジェクト: bdraco/core
static
void dcrypt_gnutls_ctx_sym_set_key_iv_random(struct dcrypt_context_symmetric *ctx)
{
	if(ctx->key.data != NULL) p_free(ctx->pool, ctx->key.data);
	if(ctx->iv.data != NULL) p_free(ctx->pool, ctx->iv.data);
	ctx->key.data = p_malloc(ctx->pool, gnutls_cipher_get_key_size(ctx->cipher));
	random_fill(ctx->key.data, gnutls_cipher_get_key_size(ctx->cipher));
	ctx->key.size = gnutls_cipher_get_key_size(ctx->cipher);
	ctx->iv.data = p_malloc(ctx->pool, gnutls_cipher_get_iv_size(ctx->cipher));
	random_fill(ctx->iv.data, gnutls_cipher_get_iv_size(ctx->cipher));
	ctx->iv.size = gnutls_cipher_get_iv_size(ctx->cipher);
}
コード例 #2
0
ファイル: StreamTest.cpp プロジェクト: Cue/skia
static void test_buffer(skiatest::Reporter* reporter) {
    SkRandom rand;
    SkAutoMalloc am(MAX_SIZE * 2);
    char* storage = (char*)am.get();
    char* storage2 = storage + MAX_SIZE;

    random_fill(rand, storage, MAX_SIZE);

    for (int sizeTimes = 0; sizeTimes < 100; sizeTimes++) {
        int size = rand.nextU() % MAX_SIZE;
        if (size == 0) {
            size = MAX_SIZE;
        }
        for (int times = 0; times < 100; times++) {
            int bufferSize = 1 + (rand.nextU() & 0xFFFF);
            SkMemoryStream mstream(storage, size);
            SkBufferStream bstream(&mstream, bufferSize);

            int bytesRead = 0;
            while (bytesRead < size) {
                int s = 17 + (rand.nextU() & 0xFFFF);
                int ss = bstream.read(storage2, s);
                REPORTER_ASSERT(reporter, ss > 0 && ss <= s);
                REPORTER_ASSERT(reporter, bytesRead + ss <= size);
                REPORTER_ASSERT(reporter,
                                memcmp(storage + bytesRead, storage2, ss) == 0);
                bytesRead += ss;
            }
            REPORTER_ASSERT(reporter, bytesRead == size);
        }
    }
}
コード例 #3
0
ファイル: main.c プロジェクト: softman11/my_quick_sort
int main()
{



	random_fill(0,0x7fffffff,6,list0,list1,list2,list3,list4,list5);
    //random_fill(0,N,6,list0,list1,list2,list3,list4,list5);
    test_sort(list0,0,N-1,"my quick_sort_0",quick_sort_0);

    test_sort(list1,0,N-1,"my quick_sort_1",quick_sort_1);

    test_sort(list2,0,N-1,"other_quick_sort_0",other_quick_sort_0);
    test_sort(list3,0,N-1,"other eq_sort",eq_sort);
   // test_sort(list3,0,N-1,"clib_quick_sort",clib_quick_sort);

	test_sort1(list4,0,N-1,"other bq_sort",bq_sort);

	test_sort1(list5,0,N-1,"my quick_sort_2",quick_sort_2);



    return 0;


}
コード例 #4
0
ファイル: mech-digest-md5.c プロジェクト: bsmr-dovecot/core
static string_t *get_digest_challenge(struct digest_auth_request *request)
{
	const struct auth_settings *set = request->auth_request.set;
	buffer_t buf;
	string_t *str;
	const char *const *tmp;
	unsigned char nonce[16];
	unsigned char nonce_base64[MAX_BASE64_ENCODED_SIZE(sizeof(nonce))+1];
	int i;
	bool first_qop;

	/*
	   realm="hostname" (multiple allowed)
	   nonce="randomized data, at least 64bit"
	   qop="auth,auth-int,auth-conf"
	   maxbuf=number (with auth-int, auth-conf, defaults to 64k)
	   charset="utf-8" (iso-8859-1 if it doesn't exist)
	   algorithm="md5-sess"
	   cipher="3des,des,rc4-40,rc4,rc4-56" (with auth-conf)
	*/

	/* get 128bit of random data as nonce */
	random_fill(nonce, sizeof(nonce));

	buffer_create_from_data(&buf, nonce_base64, sizeof(nonce_base64));
	base64_encode(nonce, sizeof(nonce), &buf);
	buffer_append_c(&buf, '\0');
	request->nonce = p_strdup(request->pool, buf.data);

	str = t_str_new(256);
	if (*set->realms_arr == NULL) {
		/* If no realms are given, at least Cyrus SASL client defaults
		   to destination host name */
		str_append(str, "realm=\"\",");
	} else {
		for (tmp = set->realms_arr; *tmp != NULL; tmp++)
			str_printfa(str, "realm=\"%s\",", *tmp);
	}

	str_printfa(str, "nonce=\"%s\",", request->nonce);

	str_append(str, "qop=\""); first_qop = TRUE;
	for (i = 0; i < QOP_COUNT; i++) {
		if (request->qop & (1 << i)) {
			if (first_qop)
				first_qop = FALSE;
			else
				str_append_c(str, ',');
			str_append(str, qop_names[i]);
		}
	}
	str_append(str, "\",");

	str_append(str, "charset=\"utf-8\","
		   "algorithm=\"md5-sess\"");
	return str;
}
コード例 #5
0
ファイル: mcp56.c プロジェクト: ctz/cryptopals
static void oracle(const byteblock *prefix, const byteblock *secret, byteblock *out)
{
  uint8_t key[16];
  random_fill(key, sizeof key);
  
  out->len = prefix->len + secret->len;
  
  memcpy(out->buf, prefix->buf, prefix->len);
  memcpy(out->buf + prefix->len, secret->buf, secret->len);
  
  rc4(key, sizeof key, out->buf, out->len);
}
コード例 #6
0
ファイル: randgen.c プロジェクト: apoikos/pkg-dovecot
void random_init(void)
{
    unsigned int seed;

    if (RAND_status() == 0) {
        i_fatal("Random generator not initialized: "
                "Install egd on /var/run/egd-pool");
    }

    random_fill(&seed, sizeof(seed));
    rand_set_seed(seed);
}
コード例 #7
0
ファイル: init.c プロジェクト: chch1028/rtems
static void
block_rw_write (int fd, char *out, size_t pos, size_t size)
{
  ssize_t n;

  random_fill (out + pos, size);

  block_rw_lseek (fd, pos);

  n = write (fd, out + pos, size);
  rtems_test_assert (n == (ssize_t) size);
}
コード例 #8
0
ファイル: init.c プロジェクト: chch1028/rtems
static void
block_rw_write_cont (int fd, char *out, size_t *pos, size_t size)
{
  ssize_t n;

  random_fill (out + *pos, size);

  n = write (fd, out + *pos, size);
  rtems_test_assert (n == (ssize_t) size);

  *pos += size;
}
コード例 #9
0
ファイル: password-scheme.c プロジェクト: bdraco/core
const char *password_generate_salt(size_t len)
{
	unsigned int i;
	char *salt;

	salt = t_malloc_no0(len + 1);
	random_fill(salt, len);
	for (i = 0; i < len; i++)
		salt[i] = salt_chars[salt[i] % (sizeof(salt_chars)-1)];
	salt[len] = '\0';
	return salt;
}
コード例 #10
0
ファイル: test-stream.c プロジェクト: bdraco/core
static
void test_write_read_v2(void)
{
	test_begin("test_write_read_v2");
	unsigned char payload[IO_BLOCK_SIZE*10];
	const unsigned char *ptr;
	size_t pos = 0, siz;
	random_fill(payload, IO_BLOCK_SIZE*10);

	buffer_t *buf = buffer_create_dynamic(default_pool, sizeof(payload));
	struct ostream *os = o_stream_create_buffer(buf);
	struct ostream *os_2 = o_stream_create_encrypt(os, "aes-256-gcm-sha256", test_v1_kp.pub, IO_STREAM_ENC_INTEGRITY_AEAD);
	o_stream_nsend(os_2, payload, sizeof(payload));
	test_assert(o_stream_finish(os_2) > 0);
	if (os_2->stream_errno != 0)
		i_debug("error: %s", o_stream_get_error(os_2));

	o_stream_unref(&os);
	o_stream_unref(&os_2);

	struct istream *is = test_istream_create_data(buf->data, buf->used);
	/* test regression where read fails due to incorrect behaviour
	   when buffer is full before going to decrypt code */
	i_stream_set_max_buffer_size(is, 8192);
	i_stream_read(is);
	struct istream *is_2 = i_stream_create_decrypt(is, test_v1_kp.priv);

	size_t offset = 0;
	test_istream_set_size(is, 0);
	test_istream_set_allow_eof(is, FALSE);
	while(i_stream_read_data(is_2, &ptr, &siz, 0)>=0) {
		if (offset == buf->used)
			test_istream_set_allow_eof(is, TRUE);
		else
			test_istream_set_size(is, ++offset);

		test_assert_idx(pos + siz <= sizeof(payload), pos);
		if (pos + siz > sizeof(payload)) break;
		test_assert_idx(siz == 0 || memcmp(ptr, payload + pos, siz) == 0, pos);
		i_stream_skip(is_2, siz); pos += siz;
	}

	test_assert(is_2->stream_errno == 0);
	if (is_2->stream_errno != 0)
		i_debug("error: %s", i_stream_get_error(is_2));

	i_stream_unref(&is);
	i_stream_unref(&is_2);
	buffer_free(&buf);

	test_end();
}
コード例 #11
0
ファイル: mech-cram-md5.c プロジェクト: jwm/dovecot-notmuch
static const char *get_cram_challenge(void)
{
    unsigned char buf[17];
    size_t i;

    random_fill(buf, sizeof(buf)-1);

    for (i = 0; i < sizeof(buf)-1; i++)
        buf[i] = (buf[i] % 10) + '0';
    buf[sizeof(buf)-1] = '\0';

    return t_strdup_printf("<%s.%s@%s>", (const char *)buf,
                           dec2str(ioloop_time), my_hostname);
}
コード例 #12
0
ファイル: test-stream.c プロジェクト: bdraco/core
static
void test_write_read_v1_short(void)
{
	test_begin("test_write_read_v1_short");
	unsigned char payload[1];
	const unsigned char *ptr;
	size_t pos = 0, siz;
	random_fill(payload, 1);

	buffer_t *buf = buffer_create_dynamic(default_pool, 64);
	struct ostream *os = o_stream_create_buffer(buf);
	struct ostream *os_2 = o_stream_create_encrypt(os, "<unused>", test_v2_kp.pub, IO_STREAM_ENC_VERSION_1);
	o_stream_nsend(os_2, payload, sizeof(payload));

	if (os_2->stream_errno != 0)
		i_debug("error: %s", o_stream_get_error(os_2));

	test_assert(os_2->stream_errno == 0);
	test_assert(o_stream_finish(os_2) > 0);
	test_assert(os_2->stream_errno == 0);

	o_stream_unref(&os);
	o_stream_unref(&os_2);

	struct istream *is = test_istream_create_data(buf->data, buf->used);
	struct istream *is_2 = i_stream_create_decrypt(is, test_v2_kp.priv);

	size_t offset = 0;
	test_istream_set_allow_eof(is, FALSE);
	test_istream_set_size(is, 0);
	while(i_stream_read_data(is_2, &ptr, &siz, 0)>=0) {
		if (offset == buf->used)
			test_istream_set_allow_eof(is, TRUE);
		else
			test_istream_set_size(is, ++offset);

		test_assert_idx(pos + siz <= sizeof(payload), pos);
		if (siz > sizeof(payload) || pos + siz > sizeof(payload)) break;
		test_assert_idx(siz == 0 || memcmp(ptr, payload + pos, siz) == 0, pos);
		i_stream_skip(is_2, siz); pos += siz;
	}

	test_assert(is_2->stream_errno == 0);

	i_stream_unref(&is);
	i_stream_unref(&is_2);
	buffer_free(&buf);

	test_end();
}
コード例 #13
0
ファイル: auth-token.c プロジェクト: LTD-Beget/dovecot
void auth_token_init(void)
{
	const char *secret_path =
		t_strconcat(global_auth_settings->base_dir, "/",
			    AUTH_TOKEN_SECRET_FNAME, NULL);

	if (auth_token_read_secret(secret_path, auth_token_secret) < 0) {
		random_fill(auth_token_secret, sizeof(auth_token_secret));

		if (auth_token_write_secret(secret_path, auth_token_secret) < 0) {
			i_error("Failed to write auth token secret file; "
				"returned tokens will be invalid once auth restarts");
		}
	}
}
コード例 #14
0
ファイル: test_add_sssaa.c プロジェクト: krisk0/razin
int main()
{
    int i;
    for(i=10; i--;)
    {
        random_fill(A,size,i);
        slow_way(R0,A,size/2);
        fast_way(R1,A,size/2);
        if( (R0[0] != R1[0]) || (R0[1] != R1[1]) || (R0[2] != R1[2]) )
            assert(0);
        fazt_way(R2,A,size/2);
        if( (R0[0] != R2[0]) || (R0[1] != R2[1]) || (R0[2] != R2[2]) )
            assert(0);
    }
    printf("Test passed\n");
}
コード例 #15
0
ファイル: vogl_mem.cpp プロジェクト: Nicky-D/vogl
void vogl_tracked_free(const char *pFile_line, void *p)
{
    if (!p)
        return;

    if (reinterpret_cast<ptr_bits_t>(p) & (VOGL_MIN_ALLOC_ALIGNMENT - 1))
    {
        vogl_mem_error("vogl_free: bad ptr", pFile_line);
        return;
    }

#if VOGL_SCRUB_FREED_MEMORY
    random_fill(p, msize_block(p, pFile_line));
#endif

    free_block(p, pFile_line);
}
コード例 #16
0
void auth_client_connection_create(struct auth *auth, int fd,
				   bool login_requests, bool token_auth)
{
	static unsigned int connect_uid_counter = 0;
	struct auth_client_connection *conn;
	const char *mechanisms;
	string_t *str;

	conn = i_new(struct auth_client_connection, 1);
	conn->auth = auth;
	conn->refcount = 1;
	conn->connect_uid = ++connect_uid_counter;
	conn->login_requests = login_requests;
	conn->token_auth = token_auth;
	random_fill(conn->cookie, sizeof(conn->cookie));

	conn->fd = fd;
	conn->input = i_stream_create_fd(fd, AUTH_CLIENT_MAX_LINE_LENGTH);
	conn->output = o_stream_create_fd(fd, (size_t)-1);
	o_stream_set_no_error_handling(conn->output, TRUE);
	o_stream_set_flush_callback(conn->output, auth_client_output, conn);
	conn->io = io_add(fd, IO_READ, auth_client_input, conn);

	DLLIST_PREPEND(&auth_client_connections, conn);

	if (token_auth) {
		mechanisms = t_strconcat("MECH\t",
			mech_dovecot_token.mech_name, "\n", NULL);
	} else {
		mechanisms = str_c(auth->reg->handshake);
	}

	str = t_str_new(128);
	str_printfa(str, "VERSION\t%u\t%u\n%sSPID\t%s\nCUID\t%u\nCOOKIE\t",
                    AUTH_CLIENT_PROTOCOL_MAJOR_VERSION,
                    AUTH_CLIENT_PROTOCOL_MINOR_VERSION,
		    mechanisms, my_pid, conn->connect_uid);
	binary_to_hex_append(str, conn->cookie, sizeof(conn->cookie));
	str_append(str, "\nDONE\n");

	if (o_stream_send(conn->output, str_data(str), str_len(str)) < 0)
		auth_client_disconnected(&conn);
}
コード例 #17
0
ファイル: svd.cpp プロジェクト: YannCobigo/viennacl-dev
void time_svd(std::size_t sz1, std::size_t sz2)
{

  std::vector<ScalarType> in(sz1 * sz2);
  random_fill(in);

  viennacl::matrix<ScalarType> Ai(sz1, sz2), QL(sz1, sz1), QR(sz2, sz2);
  viennacl::fast_copy(&in[0], &in[0] + in.size(), Ai);


  Timer timer;
  timer.start();

  viennacl::linalg::svd(Ai, QL, QR);
  viennacl::backend::finish();
  double time_spend = timer.get();

  printf("[%dx%d] time = %.6f\n", static_cast<int>(sz1), static_cast<int>(sz2), time_spend);
}
コード例 #18
0
ファイル: fundamental.c プロジェクト: fmardini/strings_trees
int main(int argc, char **argv) {
  int len = 10;
  if (argc > 1)
    len = atoi(argv[1]);
  if (len < 10) len = 10;
  char *t = malloc(len + 1);
  if (len == 10)
    memcpy(t, "aabaaabcaab", 10);
  else
    random_fill(t, len);
  t[len] = '\0';
  int *z;

  fundamental(t, len, &z);
  inspect(z, len);
  inspect_c(t, len);
  free(z);

  return 0;
}
コード例 #19
0
ファイル: ch11ex08.c プロジェクト: j-angus/cpama
/********************************************************
 * main: implement find_largest() function
 ********************************************************/
int main(void)
{
	PRINT_FILE_INFO

	int *lrg_ptr; /* stores index to largest element within a[] */
	int a[MAX];

	random_fill(MAX, a, MAX);

	for(int i = 0; i < MAX; ++i)
		printf("a[%d]: %d\n%s", i, a[i], i == MAX -1 ? "\n" : "");

	lrg_ptr = find_largest(a, MAX);
	printf("*lrg_ptr:\t %02d\n\n", *lrg_ptr);

	printf("lrg_ptr: %ld, &a[0]: %ld, a: %ld\n", lrg_ptr, &a[0], a);
	printf("lrg_ptr - &a[0]: %02ld\n", lrg_ptr - &a[0]);
	printf("lrg_ptr - a[0]:\t %02ld\n", lrg_ptr - a);

	return 0;
}
コード例 #20
0
ファイル: randgen.c プロジェクト: apoikos/pkg-dovecot
void random_init(void)
{
    unsigned int seed;

    if (init_refcount++ > 0)
        return;

    urandom_fd = open(DEV_URANDOM_PATH, O_RDONLY);
    if (urandom_fd == -1) {
        if (errno == ENOENT) {
            i_fatal(DEV_URANDOM_PATH" doesn't exist, "
                    "currently we require it");
        } else {
            i_fatal("Can't open "DEV_URANDOM_PATH": %m");
        }
    }

    random_fill(&seed, sizeof(seed));
    rand_set_seed(seed);

    fd_close_on_exec(urandom_fd, TRUE);
}
コード例 #21
0
ファイル: vogl_mem.cpp プロジェクト: Nicky-D/vogl
void *vogl_tracked_malloc(const char *pFile_line, size_t size, size_t *pActual_size)
{
    size = (size + sizeof(uint32) - 1U) & ~(sizeof(uint32) - 1U);
    if (!size)
        size = sizeof(uint32);

    if (size > VOGL_MAX_POSSIBLE_HEAP_BLOCK_SIZE)
    {
        vogl_mem_error("vogl_malloc: size too big", pFile_line);
        return NULL;
    }

    uint8 *p_new = (uint8 *)malloc_block(size, pFile_line);

    VOGL_ASSERT((reinterpret_cast<ptr_bits_t>(p_new) & (VOGL_MIN_ALLOC_ALIGNMENT - 1)) == 0);

    if (!p_new)
    {
        vogl_mem_error("vogl_malloc: out of memory", pFile_line);
        return NULL;
    }

    if (pActual_size)
    {
        *pActual_size = msize_block(p_new, pFile_line);

        if ((size) && (*pActual_size >= static_cast<uint64_t>(size) * 16U))
        {
            // I've seen this happen with glibc's absolutely terrible debug heap crap, best to let the caller know that shit is going to die
            fprintf(stderr, "%s: malloc_usable_size may be misbehaving! Requested %zu bytes, but the usable size is reported as %zu bytes.\n", __FUNCTION__, size, *pActual_size);
        }
    }

#if VOGL_RAND_FILL_ALLLOCATED_MEMORY
    random_fill(p_new, size);
#endif

    return p_new;
}
コード例 #22
0
ファイル: imap-urlauth.c プロジェクト: Distrotech/dovecot
int imap_urlauth_fetch_parsed(struct imap_urlauth_context *uctx,
			      struct imap_url *url,
			      struct imap_msgpart_url **mpurl_r,
			      enum mail_error *error_code_r,
			      const char **error_r)
{
	struct mail_user *user = uctx->user;
	struct imap_msgpart_url *mpurl;
	struct mailbox *box;
	const char *error;
	unsigned char mailbox_key[IMAP_URLAUTH_KEY_LEN];
	int ret;

	*mpurl_r = NULL;
	*error_r = NULL;
	*error_code_r = MAIL_ERROR_NONE;

	/* check urlauth mechanism, access, userid and authority */
	if (!imap_urlauth_check(uctx, url, FALSE, error_r)) {
		*error_code_r = MAIL_ERROR_PARAMS;
		return 0;
	}

	/* validate target user */
	if (user->anonymous || strcmp(url->userid, user->username) != 0) {
		*error_r = t_strdup_printf("Not permitted to fetch URLAUTH for user %s",
					   url->userid);
		*error_code_r = MAIL_ERROR_PARAMS;
		return 0;
	}

	/* validate mailbox */
	if ((ret = imap_msgpart_url_create(user, url, &mpurl, &error)) < 0) {
		*error_r = t_strdup_printf("Invalid URLAUTH: %s", error);
		*error_code_r = MAIL_ERROR_PARAMS;
		return ret;
	}

	if ((ret = imap_msgpart_url_open_mailbox(mpurl, &box, error_code_r,
						 &error)) < 0) {
		*error_r = "Internal server error";
		imap_msgpart_url_free(&mpurl);
		return -1;
	}

	if (ret == 0) {
		/* RFC says: `If the mailbox cannot be identified, an
		   authorization token is calculated on the rump URL, using
		   random "plausible" keys (selected by the server) as needed,
		   before returning a validation failure. This prevents timing
		   attacks aimed at identifying mailbox names.' */
		random_fill(mailbox_key, sizeof(mailbox_key));
		(void)imap_urlauth_internal_verify(url->uauth_rumpurl,
			mailbox_key, url->uauth_token, url->uauth_token_size);

		*error_r = t_strdup_printf("Invalid URLAUTH: %s", error);
		imap_msgpart_url_free(&mpurl);
		return 0;
	}

	/* obtain mailbox key */
	ret = imap_urlauth_backend_get_mailbox_key(box, FALSE, mailbox_key,
						   error_r, error_code_r);
	if (ret < 0) {
		imap_msgpart_url_free(&mpurl);
		return -1;
	}

	if (ret == 0 ||
	    !imap_urlauth_internal_verify(url->uauth_rumpurl, mailbox_key,
					  url->uauth_token,
					  url->uauth_token_size)) {
		*error_r = "URLAUTH verification failed";
		*error_code_r = MAIL_ERROR_PERM;
		imap_msgpart_url_free(&mpurl);
		ret = 0;
	} else {
		ret = 1;
	}

	safe_memset(mailbox_key, 0, sizeof(mailbox_key));
	*mpurl_r = mpurl;
	return ret;
}
コード例 #23
0
ファイル: wrap-binary.98.c プロジェクト: Deewiant/mushspace
int main(int argc, char **argv) {
   tap_n((3+5)*4 + (2+5)*2 + (2+5));

   if (argc > 1) {
      long s = atol(argv[1]);
      init_by_array((uint32_t*)&s, sizeof s / sizeof(uint32_t));
   } else {
      time_t s = time(NULL);
      init_by_array((uint32_t*)&s, sizeof s / sizeof(uint32_t));
   }

   void *data = malloc(DATA_LEN);
   random_fill(data, DATA_LEN);

   const size_t codepoints = DATA_LEN * CHAR_BIT / 21;

   const mushcell pos = MUSHCELL_MAX - WRAP_AFTER;
   mushcoords beg = MUSHCOORDS(pos,pos,pos), end;

   void *space_buf = malloc(mushspace_sizeof);
   mushspace *space;

   bool ok;
   mushbounds bounds, expected_loose, expected_tight;

   size_t spaces_beg, spaces_end;

   codepoint_reader cp_reader;

#define BOUNDS_CHECK \
   mushspace_get_loose_bounds(space, &bounds); \
   \
   tap_leqcos(bounds.beg, expected_loose.beg, \
              "get_loose_bounds reports appropriate beg", \
              "get_loose_bounds reports too large beg"); \
   tap_geqcos(bounds.end, expected_loose.end, \
              "get_loose_bounds reports appropriate end", \
              "get_loose_bounds reports too small end"); \
   \
   ok = mushspace_get_tight_bounds(space, &bounds); \
   tap_bool(ok, "get_tight_bounds says that the space is nonempty", \
                "get_tight_bounds says that the space is empty"); \
   \
   tap_eqcos(bounds.beg, expected_tight.beg, \
             "get_tight_bounds reports correct beg", \
             "get_tight_bounds reports incorrect beg"); \
   tap_eqcos(bounds.end, expected_tight.end, \
             "get_tight_bounds reports correct end", \
             "get_tight_bounds reports incorrect end"); \

#define LOAD_STRING(suf, T, ENCODER, BLOWUP, FOREACH_CP) \
   space = mushspace_init(space_buf, NULL); \
   if (!space) { \
      tap_not_ok("init returned null"); \
      tap_skip_remaining("init failed"); \
      return 1; \
   } \
   tap_ok("init succeeded"); \
   \
   T *encoded_data##suf = (T*)data; \
   size_t encoded_len##suf = DATA_LEN / sizeof *encoded_data##suf; \
   if (BLOWUP) { \
      encoded_data##suf = \
         malloc((codepoints * BLOWUP) * sizeof *encoded_data##suf); \
      encoded_len##suf = ENCODER(data, encoded_data##suf, codepoints); \
   } \
   \
   mushspace_load_string##suf( \
      space, encoded_data##suf, encoded_len##suf, &end, beg, true); \
   \
   if (BLOWUP) \
      free(encoded_data##suf); \
   \
   size_t ii##suf = 0; \
   mushcell cp##suf; \
   \
   spaces_beg = 0; \
   spaces_end = 0; \
   \
   FOREACH_CP(suf) { \
      if (ii##suf <= WRAP_AFTER) { \
         if (cp##suf == ' ') \
            ++spaces_end; \
         else \
            spaces_end = 0; \
         continue; \
      } \
      if (cp##suf == ' ') \
         ++spaces_beg; \
      else \
         break; \
   } \
   \
   expected_loose.beg = expected_tight.beg = \
      MUSHCOORDS(MUSHCELL_MIN, beg.y, beg.z); \
   expected_loose.end = expected_tight.end = \
      MUSHCOORDS(MUSHCELL_MAX, beg.y, beg.z); \
   \
   expected_loose.beg.x = expected_tight.beg.x += spaces_beg; \
   expected_loose.end.x = expected_tight.end.x -= spaces_end; \
   \
   tap_eqcos(end, expected_tight.end, \
             "load_string" #suf " reports correct end", \
             "load_string" #suf " reports incorrect end"); \
   \
   ok = true; \
   FOREACH_CP(suf) { \
      mushcell gc = \
         mushspace_get(space, mushcoords_add(beg, MUSHCOORDS(ii##suf,0,0))); \
      if (gc == cp##suf) \
         continue; \
      ok = false; \
      tap_not_ok("get doesn't match data given to load_string" #suf); \
      printf("  ---\n" \
             "  failed index: %zu\n" \
             "  expected: %" MUSHCELL_PRIx "\n" \
             "  got: %" MUSHCELL_PRIx "\n" \
             "  ...\n", \
             ii##suf, cp##suf, gc); \
      break; \
   } \
   if (ok) \
      tap_ok("get matches data given to load_string" #suf); \
   \
   BOUNDS_CHECK; \
   mushspace_free(space);

#define DIRECT_FOREACH_CP(s) \
   ii##s = 0; \
   for (; ii##s < encoded_len##s && (cp##s = encoded_data##s[ii##s], true); \
        ++ii##s)

#define READER_FOREACH_CP(s) \
   cp_reader = make_codepoint_reader(data, codepoints); \
   for (ii##s = 0; (cp##s = next_codepoint(&cp_reader)) != UINT32_MAX; ++ii##s)

   LOAD_STRING(, unsigned char,  dummy, 0,        DIRECT_FOREACH_CP);
   LOAD_STRING(_cell,  mushcell, dummy, 0,        DIRECT_FOREACH_CP);
   LOAD_STRING(_utf8,  uint8_t,  encode_utf8,  4, READER_FOREACH_CP);
   LOAD_STRING(_utf16, uint16_t, encode_utf16, 2, READER_FOREACH_CP);

   const mushcell *data_cell       = (const mushcell*)data;
   const size_t    data_cell_count = DATA_LEN / sizeof *data_cell;

   spaces_beg = 0;
   spaces_end = 0;

   for (size_t i = WRAP_AFTER+1; i < data_cell_count && data_cell[i++] == ' ';)
      ++spaces_beg;
   for (size_t i = WRAP_AFTER+1; i-- > 0 && data_cell[i] == ' ';)
      ++spaces_end;

   expected_loose.beg = expected_tight.beg =
      MUSHCOORDS(MUSHCELL_MIN, beg.y, beg.z);
   expected_loose.end = expected_tight.end =
      MUSHCOORDS(MUSHCELL_MAX, beg.y, beg.z);
   expected_loose.beg.x = expected_tight.beg.x += spaces_beg;
   expected_loose.end.x = expected_tight.end.x -= spaces_beg;

#define PUT(FOREACH_CELL, S) \
   space = mushspace_init(space_buf, NULL); \
   if (!space) { \
      tap_not_ok("init returned null"); \
      tap_skip_remaining("init failed"); \
      return 1; \
   } \
   tap_ok("init succeeded"); \
   FOREACH_CELL { \
      mushspace_put(space, mushcoords_add(beg, MUSHCOORDS(i, 0, 0)), \
                           data_cell[i]); \
   } \
   \
   ok = true; \
   for (size_t i = 0; i < data_cell_count; ++i) { \
      mushcell dc = data_cell[i], \
               gc = mushspace_get(space, \
                                  mushcoords_add(beg, MUSHCOORDS(i, 0, 0))); \
      if (gc == dc) \
         continue; \
      ok = false; \
      tap_not_ok("get doesn't match what was put" S); \
      printf("  ---\n" \
             "  failed index: %zu\n" \
             "  expected: %" MUSHCELL_PRIx "\n" \
             "  got: %" MUSHCELL_PRIx "\n" \
             "  ...\n", \
             i, dc, gc); \
      break; \
   } \
   if (ok) \
      tap_ok("get matches what was put" S); \
   \
   BOUNDS_CHECK;

#define FORWARD for (size_t i = 0; i < data_cell_count; ++i)
#define REVERSE for (size_t i = data_cell_count; i--;)
   PUT(FORWARD, " (forward order)");
   mushspace_free(space);
   PUT(REVERSE, " (reverse order)");

   if (!ok) {
      tap_skip_remaining("won't copy bad space");
      return 1;
   }

   void *space_buf2 = malloc(mushspace_sizeof);

   mushspace *space2 = mushspace_copy(space_buf2, space, NULL);
   mushspace_free(space);
   free(space_buf);

   space = space2;

   if (!space) {
      tap_not_ok("copy returned null");
      tap_skip_remaining("copy failed");
      return 1;
   }
   tap_ok("copy succeeded");

   ok = true;
   for (size_t i = 0; i < DATA_LEN / sizeof *data_cell; ++i) {
      mushcell dc = data_cell[i],
               gc = mushspace_get(space,
                                  mushcoords_add(beg, MUSHCOORDS(i, 0, 0)));
      if (gc == dc)
         continue;
      ok = false;
      tap_not_ok("get in copy doesn't match data");
      printf("  ---\n"
             "  failed index: %zu\n"
             "  expected: %" MUSHCELL_PRIx "\n"
             "  got: %" MUSHCELL_PRIx "\n"
             "  ...\n",
             i, dc, gc);
      break;
   }
   if (ok)
      tap_ok("get in copy matched data");

   BOUNDS_CHECK;

   free(data);
   mushspace_free(space);
   free(space_buf2);
}
コード例 #24
0
ファイル: ostream-encrypt.c プロジェクト: manuelm/dovecot
static
int o_stream_encrypt_keydata_create_v2(struct encrypt_ostream *stream, const char *malg)
{
	const struct hash_method *hash = hash_method_lookup(malg);
	const char *error;
	size_t tagsize;
	const unsigned char *ptr;
	size_t kl;
	unsigned int val;

	buffer_t *keydata, *res;

	if (hash == NULL) {
		io_stream_set_error(&stream->ostream.iostream,
			"Encryption init error: Hash algorithm '%s' not supported", malg);
		return -1;
	}

	/* key data length for internal use */
	if ((stream->flags & IO_STREAM_ENC_INTEGRITY_HMAC) == IO_STREAM_ENC_INTEGRITY_HMAC) {
		tagsize = IOSTREAM_TAG_SIZE; 
	} else if ((stream->flags & IO_STREAM_ENC_INTEGRITY_AEAD) == IO_STREAM_ENC_INTEGRITY_AEAD) {
		tagsize = IOSTREAM_TAG_SIZE;
	} else {
		/* do not include MAC */
		tagsize = 0;
	}

	/* generate keydata length of random data for key/iv/mac */
	kl = dcrypt_ctx_sym_get_key_length(stream->ctx_sym) + dcrypt_ctx_sym_get_iv_length(stream->ctx_sym) + tagsize;
	keydata = buffer_create_dynamic(pool_datastack_create(), kl);
	random_fill(buffer_append_space_unsafe(keydata, kl), kl);
	buffer_set_used_size(keydata, kl);
	ptr = keydata->data;

	res = buffer_create_dynamic(default_pool, 256);

	/* store number of public key(s) */
	buffer_append(res, "\1", 1); /* one key for now */

	/* we can do multiple keys at this point, but do it only once now */
	if (o_stream_encrypt_key_for_pubkey_v2(stream, malg, ptr, kl, stream->pub, res) != 0) {
		buffer_free(&res);
		return -1;
	}

	/* create hash of the key data */
	unsigned char hctx[hash->context_size];
	unsigned char hres[hash->digest_size];
	hash->init(hctx);
	hash->loop(hctx, ptr, kl);
	hash->result(hctx, hres);

	for(int i = 1; i < 2049; i++) {
		uint32_t i_msb = htonl(i);

		hash->init(hctx);
		hash->loop(hctx, hres, sizeof(hres));
		hash->loop(hctx, &i_msb, sizeof(i_msb));
		hash->result(hctx, hres);
	}

	/* store key data hash */
	val = htonl(sizeof(hres));
	buffer_append(res, &val, 4);
	buffer_append(res, hres, sizeof(hres));

	/* pick up key data that goes into stream */
	stream->key_data_len = res->used;
	stream->key_data = buffer_free_without_data(&res);

	/* prime contexts */
	dcrypt_ctx_sym_set_key(stream->ctx_sym, ptr, dcrypt_ctx_sym_get_key_length(stream->ctx_sym));
	ptr += dcrypt_ctx_sym_get_key_length(stream->ctx_sym);
	dcrypt_ctx_sym_set_iv(stream->ctx_sym, ptr, dcrypt_ctx_sym_get_iv_length(stream->ctx_sym));
	ptr += dcrypt_ctx_sym_get_iv_length(stream->ctx_sym);

	if ((stream->flags & IO_STREAM_ENC_INTEGRITY_HMAC) == IO_STREAM_ENC_INTEGRITY_HMAC) {
		dcrypt_ctx_hmac_set_key(stream->ctx_mac, ptr, tagsize);
		dcrypt_ctx_hmac_init(stream->ctx_mac, &error);
	} else if ((stream->flags & IO_STREAM_ENC_INTEGRITY_AEAD) == IO_STREAM_ENC_INTEGRITY_AEAD) {
		dcrypt_ctx_sym_set_aad(stream->ctx_sym, ptr, tagsize);
	}

	/* clear out private key data */
	safe_memset(buffer_get_modifiable_data(keydata, 0), 0, keydata->used);

	if (!dcrypt_ctx_sym_init(stream->ctx_sym, &error)) {
		io_stream_set_error(&stream->ostream.iostream, "Encryption init error: %s", error);
		return -1;
	}
	return 0;
}
コード例 #25
0
ファイル: find_minimum.c プロジェクト: kaizenoh/book-source
int main() {
  cl_int status;
  srand(time(NULL));

  cl_platform_id platform;
  CHECK_STATUS(clGetPlatformIDs(1, &platform, NULL));

  cl_device_id device;
  CHECK_STATUS(clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, NULL));

  cl_context context = clCreateContext(NULL, 1, &device, NULL, NULL, &status);
  CHECK_STATUS(status);

  cl_command_queue queue = clCreateCommandQueue(context, device, 0, &status);
  CHECK_STATUS(status);

  char* source = read_source("find_minimum.cl");
  cl_program program = clCreateProgramWithSource(context, 1,
    (const char**)&source, NULL, NULL);
  CHECK_STATUS(status);
  free(source);

  CHECK_STATUS(clBuildProgram(program, 0, NULL, NULL, NULL, NULL));

  cl_kernel kernel = clCreateKernel(program, "find_minimum", &status);
  CHECK_STATUS(status);

  cl_float values[NUM_VALUES];
  random_fill(values, NUM_VALUES);

  cl_mem valuesBuffer = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
    sizeof(cl_float) * NUM_VALUES, values, &status);
  CHECK_STATUS(status);
  cl_mem resultBuffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY,
    sizeof(cl_float), NULL, &status);
  CHECK_STATUS(status);

  CHECK_STATUS(clSetKernelArg(kernel, 0, sizeof(cl_mem), &valuesBuffer));
  CHECK_STATUS(clSetKernelArg(kernel, 1, sizeof(cl_mem), &resultBuffer));
// START:allocatelocal
  CHECK_STATUS(clSetKernelArg(kernel, 2, sizeof(cl_float) * NUM_VALUES, NULL));
// END:allocatelocal

  size_t work_units[] = {NUM_VALUES};
  CHECK_STATUS(clEnqueueNDRangeKernel(queue, kernel, 1, NULL, work_units, 
    work_units, 0, NULL, NULL));

  cl_float result;
  CHECK_STATUS(clEnqueueReadBuffer(queue, resultBuffer, CL_TRUE, 0, sizeof(cl_float),
    &result, 0, NULL, NULL));

  CHECK_STATUS(clReleaseMemObject(resultBuffer));
  CHECK_STATUS(clReleaseMemObject(valuesBuffer));
  CHECK_STATUS(clReleaseKernel(kernel));
  CHECK_STATUS(clReleaseProgram(program));
  CHECK_STATUS(clReleaseCommandQueue(queue));
  CHECK_STATUS(clReleaseContext(context));

// START:sequential
  cl_float acc = FLT_MAX;
  for (int i = 0; i < NUM_VALUES; ++i)
    acc = fmin(acc, values[i]);
// END:sequential

  if (acc != result)
    fprintf(stderr, "Error: %f != %f", acc, result);

  return 0;
}
コード例 #26
0
ファイル: ECIES.cpp プロジェクト: BobWay/rippled
Blob encryptECIES (const openssl::ec_key& secretKey, const openssl::ec_key& publicKey, Blob const& plaintext)
{

    ECIES_ENC_IV_TYPE iv;
    random_fill (iv.begin (), ECIES_ENC_BLK_SIZE);

    ECIES_ENC_KEY_TYPE secret;
    ECIES_HMAC_KEY_TYPE hmacKey;

    getECIESSecret (secretKey, publicKey, secret, hmacKey);
    ECIES_HMAC_TYPE hmac = makeHMAC (hmacKey, plaintext);
    hmacKey.zero ();

    EVP_CIPHER_CTX ctx;
    EVP_CIPHER_CTX_init (&ctx);

    if (EVP_EncryptInit_ex (&ctx, ECIES_ENC_ALGO, nullptr, secret.begin (), iv.begin ()) != 1)
    {
        EVP_CIPHER_CTX_cleanup (&ctx);
        secret.zero ();
        throw std::runtime_error ("init cipher ctx");
    }

    secret.zero ();

    Blob out (plaintext.size () + ECIES_HMAC_SIZE + ECIES_ENC_KEY_SIZE + ECIES_ENC_BLK_SIZE, 0);
    int len = 0, bytesWritten;

    // output IV
    memcpy (& (out.front ()), iv.begin (), ECIES_ENC_BLK_SIZE);
    len = ECIES_ENC_BLK_SIZE;

    // Encrypt/output HMAC
    bytesWritten = out.capacity () - len;
    assert (bytesWritten > 0);

    if (EVP_EncryptUpdate (&ctx, & (out.front ()) + len, &bytesWritten, hmac.begin (), ECIES_HMAC_SIZE) < 0)
    {
        EVP_CIPHER_CTX_cleanup (&ctx);
        throw std::runtime_error ("");
    }

    len += bytesWritten;

    // encrypt/output plaintext
    bytesWritten = out.capacity () - len;
    assert (bytesWritten > 0);

    if (EVP_EncryptUpdate (&ctx, & (out.front ()) + len, &bytesWritten, & (plaintext.front ()), plaintext.size ()) < 0)
    {
        EVP_CIPHER_CTX_cleanup (&ctx);
        throw std::runtime_error ("");
    }

    len += bytesWritten;

    // finalize
    bytesWritten = out.capacity () - len;

    if (EVP_EncryptFinal_ex (&ctx, & (out.front ()) + len, &bytesWritten) < 0)
    {
        EVP_CIPHER_CTX_cleanup (&ctx);
        throw std::runtime_error ("encryption error");
    }

    len += bytesWritten;

    // Output contains: IV, encrypted HMAC, encrypted data, encrypted padding
    assert (len <= (plaintext.size () + ECIES_HMAC_SIZE + (2 * ECIES_ENC_BLK_SIZE)));
    assert (len >= (plaintext.size () + ECIES_HMAC_SIZE + ECIES_ENC_BLK_SIZE)); // IV, HMAC, data
    out.resize (len);
    EVP_CIPHER_CTX_cleanup (&ctx);
    return out;
}
コード例 #27
0
ファイル: wrap-textual.98.c プロジェクト: Deewiant/mushspace
int main(int argc, char **argv) {
   // We don't check bounds here: we'd end up essentially duplicating the logic
   // from load_string, and there's little point in that.
   tap_n(2*4 + 2*2 + 2);

   if (argc > 1) {
      long s = atol(argv[1]);
      init_by_array((uint32_t*)&s, sizeof s / sizeof(uint32_t));
   } else {
      time_t s = time(NULL);
      init_by_array((uint32_t*)&s, sizeof s / sizeof(uint32_t));
   }

   void *data = malloc(DATA_LEN);
   random_fill(data, DATA_LEN);

   const size_t codepoints = DATA_LEN * CHAR_BIT / 21;

   mushcoords beg = MUSHCOORDS(MUSHCELL_MAX-WRAP_AFTER,
                               MUSHCELL_MAX-WRAP_AFTER,
                               MUSHCELL_MAX-WRAP_AFTER),
              end;

   void *space_buf = malloc(mushspace_sizeof);
   mushspace *space;

   bool ok;

   codepoint_reader cp_reader;

   mushcoords pos, pos_next;
   bool cr;

#define POS_INIT \
   pos_next = beg; \
   cr = false;

#define CP_POS(cp) \
   pos = pos_next; \
   switch (cp) { \
   default: \
      if (MUSHSPACE_DIM > 1 && cr) { \
         cr = false; \
         pos = MUSHCOORDS(beg.x, pos.y + 1, pos.z); \
      } \
      pos_next = MUSHCOORDS(pos.x + 1, pos.y, pos.z); \
      break; \
   case '\r': \
      if (MUSHSPACE_DIM > 1) { \
         if (cr) \
            pos_next = pos = MUSHCOORDS(beg.x, pos.y + 1, pos.z); \
         cr = true; \
      } \
      continue; \
   case '\n': \
      if (MUSHSPACE_DIM > 1) { \
         cr = false; \
         pos_next = pos = MUSHCOORDS(beg.x, pos.y + 1, pos.z); \
      } \
      continue; \
   case '\f': \
      if (MUSHSPACE_DIM > 2) { \
         cr = false; \
         pos_next = pos = MUSHCOORDS(beg.x, beg.y, pos.z + 1); \
      } else if (cr) { \
         cr = false; \
         pos_next = pos = MUSHCOORDS(beg.x, pos.y + 1, pos.z); \
      } \
      continue; \
   }

#define LOAD_STRING(suf, T, ENCODER, BLOWUP, FOREACH_CP) \
   space = mushspace_init(space_buf, NULL); \
   if (!space) { \
      tap_not_ok("init returned null"); \
      tap_skip_remaining("init failed"); \
      return 1; \
   } \
   tap_ok("init succeeded"); \
   \
   T *encoded_data##suf = (T*)data; \
   size_t encoded_len##suf = DATA_LEN / sizeof *encoded_data##suf; \
   if (BLOWUP) { \
      encoded_data##suf = \
         malloc((codepoints * BLOWUP) * sizeof *encoded_data##suf); \
      encoded_len##suf = ENCODER(data, encoded_data##suf, codepoints); \
   } \
   \
   mushspace_load_string##suf( \
      space, encoded_data##suf, encoded_len##suf, &end, beg, false); \
   \
   if (BLOWUP) \
      free(encoded_data##suf); \
   \
   ok = true; \
   POS_INIT; \
   FOREACH_CP(suf) { \
      CP_POS(cp##suf); \
      mushcell gc = mushspace_get(space, pos); \
      if (gc == cp##suf) \
         continue; \
      ok = false; \
      tap_not_ok("get doesn't match data given to load_string" #suf); \
      printf("  ---\n" \
             "  expected: %" MUSHCELL_PRIx "\n" \
             "  got: %" MUSHCELL_PRIx "\n" \
             "  failed index: %zu\n", \
             cp##suf, gc, ii##suf); \
      printf("  failed pos relative to min: ("); \
      for (uint8_t i = 0; i < MUSHSPACE_DIM; ++i) \
         printf(" %" MUSHCELL_PRId, mushcell_sub(pos.v[i], MUSHCELL_MIN)); \
      printf(" )\n" \
             "  ...\n"); \
      break; \
   } \
   if (ok) \
      tap_ok("get matches data given to load_string" #suf); \
   \
   mushspace_free(space);

#define DIRECT_FOREACH_CP(s) \
   mushcell cp##s; \
   size_t ii##s = 0; \
   for (; ii##s < encoded_len##s && (cp##s = encoded_data##s[ii##s], true); \
        ++ii##s)

#define READER_FOREACH_CP(s) \
   cp_reader = make_codepoint_reader(data, codepoints); \
   size_t ii##s = 0; \
   for (mushcell cp##s; (cp##s = next_codepoint(&cp_reader)) != UINT32_MAX; \
        ++ii##s)

   LOAD_STRING(, unsigned char,  dummy, 0,        DIRECT_FOREACH_CP);
   LOAD_STRING(_cell,  mushcell, dummy, 0,        DIRECT_FOREACH_CP);
   LOAD_STRING(_utf8,  uint8_t,  encode_utf8,  4, READER_FOREACH_CP);
   LOAD_STRING(_utf16, uint16_t, encode_utf16, 2, READER_FOREACH_CP);

   const mushcell *data_cell       = (const mushcell*)data;
   const size_t    data_cell_count = DATA_LEN / sizeof *data_cell;

   mushcoords *saved_pos = malloc(data_cell_count * sizeof *saved_pos);

#define PUT(FOREACH_CELL, S, GET_POS, SAVE_POS) \
   space = mushspace_init(space_buf, NULL); \
   if (!space) { \
      tap_not_ok("init returned null"); \
      tap_skip_remaining("init failed"); \
      free(saved_pos); \
      return 1; \
   } \
   tap_ok("init succeeded"); \
   POS_INIT; \
   FOREACH_CELL { \
      GET_POS(data_cell[i]); \
      if (SAVE_POS) \
         saved_pos[i] = pos; \
      mushspace_put(space, pos, data_cell[i]); \
   } \
   \
   ok = true; \
   POS_INIT; \
   for (size_t i = 0; i < data_cell_count; ++i) { \
      mushcell dc = data_cell[i]; \
      GET_POS(dc); \
      mushcell gc = mushspace_get(space, pos); \
      if (gc == dc) \
         continue; \
      ok = false; \
      tap_not_ok("get doesn't match what was put" S); \
      printf("  ---\n" \
             "  failed index: %zu\n" \
             "  expected: %" MUSHCELL_PRIx "\n" \
             "  got: %" MUSHCELL_PRIx "\n", \
             i, dc, gc); \
      printf("  failed pos relative to min: ("); \
      for (uint8_t j = 0; j < MUSHSPACE_DIM; ++j) \
         printf(" %" MUSHCELL_PRId, mushcell_sub(pos.v[j], MUSHCELL_MIN)); \
      printf(" )\n" \
             "  ...\n"); \
      break; \
   } \
   if (ok) \
      tap_ok("get matches what was put" S);

#define FORWARD for (size_t i = 0; i < data_cell_count; ++i)
#define REVERSE for (size_t i = data_cell_count; i--;)

#define SAVED_POS(_) pos = saved_pos[i];

   PUT(FORWARD, " (forward order)", CP_POS, true);
   mushspace_free(space);
   PUT(REVERSE, " (reverse order)", SAVED_POS, false);
   free(saved_pos);

   if (!ok) {
      tap_skip_remaining("won't copy bad space");
      return 1;
   }

   void *space_buf2 = malloc(mushspace_sizeof);

   mushspace *space2 = mushspace_copy(space_buf2, space, NULL);
   mushspace_free(space);
   free(space_buf);

   space = space2;

   if (!space) {
      tap_not_ok("copy returned null");
      tap_skip_remaining("copy failed");
      return 1;
   }
   tap_ok("copy succeeded");

   ok = true;
   POS_INIT;
   for (size_t i = 0; i < DATA_LEN / sizeof *data_cell; ++i) {
      mushcell dc = data_cell[i];
      CP_POS(dc);
      mushcell gc = mushspace_get(space, pos);
      if (gc == dc)
         continue;
      ok = false;
      tap_not_ok("get in copy doesn't match data");
      printf("  ---\n"
             "  failed index: %zu\n"
             "  expected: %" MUSHCELL_PRIx "\n"
             "  got: %" MUSHCELL_PRIx "\n",
             i, dc, gc);
      printf("  failed pos relative to min: (");
      for (uint8_t j = 0; j < MUSHSPACE_DIM; ++j)
         printf(" %" MUSHCELL_PRId, mushcell_sub(pos.v[j], MUSHCELL_MIN)); \
      printf(" )\n"
             "  ...\n");
      break;
   }
   if (ok)
      tap_ok("get in copy matched data");

   free(data);
   mushspace_free(space);
   free(space_buf2);
}
コード例 #28
0
ファイル: vogl_mem.cpp プロジェクト: Nicky-D/vogl
void *vogl_tracked_realloc(const char *pFile_line, void *p, size_t size, size_t *pActual_size)
{
    if ((ptr_bits_t)p & (VOGL_MIN_ALLOC_ALIGNMENT - 1))
    {
        vogl_mem_error("vogl_realloc: bad ptr", pFile_line);
        return NULL;
    }

    if (size > VOGL_MAX_POSSIBLE_HEAP_BLOCK_SIZE)
    {
        vogl_mem_error("vogl_realloc: size too big!", pFile_line);
        return NULL;
    }

    if ((size) && (size < sizeof(uint32)))
        size = sizeof(uint32);

#if VOGL_RAND_FILL_ALLLOCATED_MEMORY || VOGL_SCRUB_FREED_MEMORY
    size_t orig_size = p ? msize_block(p, pFile_line) : 0;

#if VOGL_SCRUB_FREED_MEMORY
    if ((orig_size) && (!size))
        random_fill(p, orig_size);
#endif
#endif

    void *p_new = realloc_block(p, size, pFile_line);

    VOGL_ASSERT((reinterpret_cast<ptr_bits_t>(p_new) & (VOGL_MIN_ALLOC_ALIGNMENT - 1)) == 0);

    if (pActual_size)
    {
        *pActual_size = 0;

        if (size)
        {
            if (p_new)
                *pActual_size = msize_block(p_new, pFile_line);
            else if (p)
                *pActual_size = msize_block(p, pFile_line);

            if (*pActual_size >= static_cast<uint64_t>(size) * 16U)
            {
                // I've seen this happen with glibc's absolutely terrible debug heap crap, best to let the caller know that shit is going to die
                fprintf(stderr, "%s: malloc_usable_size may be misbehaving! Requested %zu bytes, but the usable size is reported as %zu bytes.\n", __FUNCTION__, size, *pActual_size);
            }
        }
    }

#if VOGL_RAND_FILL_ALLLOCATED_MEMORY
    if ((size) && (p_new))
    {
        size_t new_size = msize_block(p_new, pFile_line);

        if (new_size > orig_size)
            random_fill(static_cast<uint8 *>(p_new) + orig_size, new_size - orig_size);
    }
#endif

    return p_new;
}
コード例 #29
0
int main() {
  cl_int status;

  cl_platform_id platform;
  CHECK_STATUS(clGetPlatformIDs(1, &platform, NULL));

  cl_device_id device;
  CHECK_STATUS(clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, NULL));

  cl_context context = clCreateContext(NULL, 1, &device, NULL, NULL, &status);
  CHECK_STATUS(status);

  cl_command_queue queue = clCreateCommandQueue(context, device, 0, &status);
  CHECK_STATUS(status);

  char* source = read_source("multiply_arrays.cl");
  cl_program program = clCreateProgramWithSource(context, 1,
    (const char**)&source, NULL, NULL);
  CHECK_STATUS(status);
  free(source);

  CHECK_STATUS(clBuildProgram(program, 0, NULL, NULL, NULL, NULL));

  cl_kernel kernel = clCreateKernel(program, "multiply_arrays", &status);
  CHECK_STATUS(status);

  cl_float a[1024], b[1024];
  random_fill(a, 1024);
  random_fill(b, 1024);

  cl_mem inputA = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
    sizeof(cl_float) * 1024, a, &status);
  CHECK_STATUS(status);
  cl_mem inputB = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
    sizeof(cl_float) * 1024, b, &status);
  CHECK_STATUS(status);
  cl_mem output = clCreateBuffer(context, CL_MEM_WRITE_ONLY,
    sizeof(cl_float) * 1024, NULL, &status);
  CHECK_STATUS(status);

  CHECK_STATUS(clSetKernelArg(kernel, 0, sizeof(cl_mem), &inputA));
  CHECK_STATUS(clSetKernelArg(kernel, 1, sizeof(cl_mem), &inputB));
  CHECK_STATUS(clSetKernelArg(kernel, 2, sizeof(cl_mem), &output));

  size_t work_units = 1024;
  CHECK_STATUS(clEnqueueNDRangeKernel(queue, kernel, 1, NULL, &work_units, NULL, 0, NULL, NULL));

  cl_float results[1024];
  CHECK_STATUS(clEnqueueReadBuffer(queue, output, CL_TRUE, 0, sizeof(cl_float) * 1024,
    results, 0, NULL, NULL));

  CHECK_STATUS(clReleaseMemObject(inputA));
  CHECK_STATUS(clReleaseMemObject(inputB));
  CHECK_STATUS(clReleaseMemObject(output));
  CHECK_STATUS(clReleaseKernel(kernel));
  CHECK_STATUS(clReleaseProgram(program));
  CHECK_STATUS(clReleaseCommandQueue(queue));
  CHECK_STATUS(clReleaseContext(context));

  for (int i = 0; i < 1024; ++i) {
    printf("%f * %f = %f\n", a[i], b[i], results[i]);
  }

  return 0;
}
コード例 #30
0
ファイル: main.c プロジェクト: DaniilAnichin/9_file_work
int start_run()
{
    FILE* work_file;

    char *start_menu[] = {
        "Create file;\n",
        "Open file;\n",
        "Read file;\n",
        "Delete file;\n",
        "Exit program;\n",
    };

    char menu_symb[] = "0";
    char random = '\0';
    char path[PATH_LEN + 1];
    char full_path[FPATH_LEN + 1];

    int fill_number = 0;
    int menu_count = 0;
    int incorrect_choice = 1;
    int exit = 0;

    do
    {
        incorrect_choice = 1;

        system("clear");
        for(menu_count = 0; menu_count < 5; menu_count++)
            printf("%d) %s", menu_count + 1, start_menu[menu_count]);

        printf("Input the number of menu item:\n");
        while(incorrect_choice)
        {
            menu_symb[0] = getche();
            if(!strpbrk(menu_symb, "12345"))
                printf("Unknown value: %c; repeat the choice\n", menu_symb[0]);
            else
                incorrect_choice = 0;
        }

        switch(menu_symb[0])
        {
        case '1':
        {
            puts("Input the name of the file to create:");
            puts("(If you wish inner directories, "
                 "type them with '/' separator;");
            puts("Further this path may be appended "
                 "to executable's base dir)");
            string_input(stdin, PATH_LEN, path, 0);
            getcwd(full_path, FPATH_LEN + 1);
            strcat(full_path, "/");
            strcat(full_path, path);

            work_file = file_create(full_path);
            if(work_file)
            {
                incorrect_choice = 1;

                puts("Do you want to fill the file with random values?[Y/N]");
                while(incorrect_choice)
                {
                    random = getche();
                    if(!strpbrk(&random, "ynYN"))
                        printf("Unknown value: %c; repeat the choice\n",
                               random);
                    else
                        incorrect_choice = 0;
                }
                if(random == 'y' || random == 'Y')
                {
                    puts("Input the number of items to create:");
                    fill_number = integer_input(1, 200);
                    random_fill(work_file, fill_number);
                }

                file_run(work_file);
            }
        }
            break;
        case '2':
        {
            puts("Input the name of the file to open & operate with:");
            string_input(stdin, PATH_LEN, path, 0);
            getcwd(full_path, FPATH_LEN + 1);
            strcat(full_path, "/");
            strcat(full_path, path);

            if(!file_exist(full_path))
                alert("\tNo such file or directory;");
            else
            {
                work_file = file_open(full_path);
                if(work_file)
                    file_run(work_file);
            }
        }
            break;
        case '3':
        {
            puts("Input the name of the file to read:");
            string_input(stdin, PATH_LEN, path, 0);
            getcwd(full_path, FPATH_LEN + 1);
            strcat(full_path, "/");
            strcat(full_path, path);

            if(!file_exist(full_path))
                alert("\tNo such file or directory;");
            else
            {
                work_file = file_open(full_path);
                if(work_file)
                    file_read(work_file);
            }
        }
            break;
        case '4':
        {
            puts("Input the name of the file to delete:");
            string_input(stdin, PATH_LEN, path, 0);
            getcwd(full_path, FPATH_LEN + 1);
            strcat(full_path, "/");
            strcat(full_path, path);

            if(!file_exist(full_path))
                alert("\tNo such file or directory;");
            else
                if(remove(full_path))
                    alert("\tUnable to delete this file;");
        }
            break;
        case '5':
        {
            printf("Good luck;\n");
            exit = 1;
        }
            break;
        }
    }while(!exit);

    return menu_symb[0] - '0';
}