Ejemplo n.º 1
0
/*
====================
Find
====================
*/
U32 EChunk::Find(const CHAR* name, const Vector2& st)
{
	GUARD(EChunk::Find);	

	CHECK(name);
	
	// searche the layer table
	for(U32 i = 0; i < mLayers.size(); i++)
	{
		if(mLayers[i].name == name && mLayers[i].st == st) return i;
	}

	// create the new layer
	Layer layer;
	layer.name = name;
	layer.st = st;
	layer.alpha.resize(U2P(ALPHA_STRIDE)*U2P(ALPHA_STRIDE), 0);
	layer.total = 0;

	// create the new primitive
	layer.primitive = GNEW(Primitive); CHECK(layer.primitive);
	layer.primitive->SetType(Primitive::PT_TRIANGLES);
	layer.primitive->SetVertexBuffer(mVBPtr.Ptr());
	layer.primitive->SetIndexBuffer(mIBPtr.Ptr());	
	layer.primitive->SetConstant("gWVP",GNEW(Constant(Matrix())));

	// get the color texture
	KeyPtr texture_key_ptr = Key::Find(name);
	if(texture_key_ptr == NULL)
	{
		const Image* image = Image::Load(GLoad(name)); CHECK(image);
		BaseTexture* base_texture = GNEW(Texture); CHECK(base_texture);
		base_texture->Load(image);
		texture_key_ptr = GNEW(Key(name, base_texture)); CHECK(texture_key_ptr);
	}
	mKeys.push_back(texture_key_ptr);
	layer.primitive->SetConstant("gColorTex",GNEW(Constant((BaseTexture*)texture_key_ptr->Ptr())));

	// set the scale st	
	layer.primitive->SetConstant("gScaleST",GNEW(Constant(Vector4(st[0],st[1],0,0))));	

	// set the alpha
	U32 width = U2P(ALPHA_STRIDE);
	U32 height = U2P(ALPHA_STRIDE);
	Image* image = GNEW(Image); CHECK(image);
	image->Width(width);
	image->Height(height);
	image->PixelFormat(PF_ALPHA);
	image->DataType(DT_UNSIGNED_BYTE);
	image->MipmapCount(1);
	image->Mipmap(0,&layer.alpha[0],width*height*sizeof(U8));		
	BaseTexture *alpha_texture = GNEW(Texture); CHECK(alpha_texture);
	alpha_texture->Load(image);
	layer.primitive->SetConstant("gAlphaTex",GNEW(Constant(alpha_texture)));
	layer.texture = alpha_texture;

	// load the shader
	layer.primitive->SetShader(dynamic_cast<Shader*>(mShaderKey->Ptr()), "layer");
	
	// add the layer to the table
	mLayers.push_back(layer);
	return mLayers.size() - 1;

	UNGUARD;
}
Ejemplo n.º 2
0
int Epoll_Watcher::end_loop(void) {
	GUARD(Mutex, mon, io_lock_);
	GUARD(Mutex, mon1, tq_lock_);
	end_flag_ = true;
	return 0;
}
Ejemplo n.º 3
0
int s2n_connection_set_fd(struct s2n_connection *conn, int fd)
{
    GUARD(s2n_connection_set_read_fd(conn, fd));
    GUARD(s2n_connection_set_write_fd(conn, fd));
    return 0;
}
Ejemplo n.º 4
0
static int s2n_set_cipher_and_cert_as_server(struct s2n_connection *conn, uint8_t * wire, uint32_t count, uint32_t cipher_suite_len)
{
    uint8_t renegotiation_info_scsv[S2N_TLS_CIPHER_SUITE_LEN] = { TLS_EMPTY_RENEGOTIATION_INFO_SCSV };
    struct s2n_cipher_suite *higher_vers_match = NULL;
    struct s2n_cert_chain_and_key *higher_vers_cert = NULL;

    /* RFC 7507 - If client is attempting to negotiate a TLS Version that is lower than the highest supported server
     * version, and the client cipher list contains TLS_FALLBACK_SCSV, then the server must abort the connection since
     * TLS_FALLBACK_SCSV should only be present when the client previously failed to negotiate a higher TLS version.
     */
    if (conn->client_protocol_version < s2n_highest_protocol_version) {
        uint8_t fallback_scsv[S2N_TLS_CIPHER_SUITE_LEN] = { TLS_FALLBACK_SCSV };
        if (s2n_wire_ciphers_contain(fallback_scsv, wire, count, cipher_suite_len)) {
            conn->closed = 1;
            S2N_ERROR(S2N_ERR_FALLBACK_DETECTED);
        }
    }

    /* RFC5746 Section 3.6: A server must check if TLS_EMPTY_RENEGOTIATION_INFO_SCSV is included */
    if (s2n_wire_ciphers_contain(renegotiation_info_scsv, wire, count, cipher_suite_len)) {
        conn->secure_renegotiation = 1;
    }

    const struct s2n_cipher_preferences *cipher_preferences;
    GUARD(s2n_connection_get_cipher_preferences(conn, &cipher_preferences));

    /* s2n supports only server order */
    for (int i = 0; i < cipher_preferences->count; i++) {
        conn->handshake_params.our_chain_and_key = NULL;
        const uint8_t *ours = cipher_preferences->suites[i]->iana_value;

        if (s2n_wire_ciphers_contain(ours, wire, count, cipher_suite_len)) {
            /* We have a match */
            struct s2n_cipher_suite *match = s2n_cipher_suite_from_wire(ours);

            /* If connection is for SSLv3, use SSLv3 version of suites */
            if (conn->client_protocol_version == S2N_SSLv3) {
                match = match->sslv3_cipher_suite;
            }

            /* Skip the suite if it is not compatible with any certificates */
            conn->handshake_params.our_chain_and_key = s2n_get_compatible_cert_chain_and_key(conn, match);
            if (!conn->handshake_params.our_chain_and_key) {
                continue;
            }

            /* Skip the suite if we don't have an available implementation */
            if (!match->available) {
                continue;
            }

            if (!s2n_kex_supported(match->key_exchange_alg, conn)) {
                continue;
            }

            /* Don't immediately choose a cipher the client shouldn't be able to support */
            if (conn->client_protocol_version < match->minimum_required_tls_version) {
                if (!higher_vers_match) {
                    higher_vers_match = match;
                    higher_vers_cert = conn->handshake_params.our_chain_and_key;
                }
                continue;
            }

            conn->secure.cipher_suite = match;
            return 0;
        }
    }

    /* Settle for a cipher with a higher required proto version, if it was set */
    if (higher_vers_match) {
        conn->secure.cipher_suite = higher_vers_match;
        conn->handshake_params.our_chain_and_key = higher_vers_cert;
        return 0;
    }

    S2N_ERROR(S2N_ERR_CIPHER_NOT_SUPPORTED);
}
Ejemplo n.º 5
0
static int s2n_drbg_bits(struct s2n_drbg *drbg, struct s2n_blob *out)
{
    struct s2n_blob value = {.data = drbg->v,.size = sizeof(drbg->v) };
    int block_aligned_size = out->size - (out->size % S2N_DRBG_BLOCK_SIZE);

    /* Per NIST SP800-90A 10.2.1.2: */
    for (int i = 0; i < block_aligned_size; i += S2N_DRBG_BLOCK_SIZE) {
        GUARD(s2n_increment_sequence_number(&value));
        GUARD(s2n_drbg_block_encrypt(drbg->ctx, drbg->v, out->data + i));
        drbg->bytes_used += S2N_DRBG_BLOCK_SIZE;
    }

    if (out->size <= block_aligned_size) {
        return 0;
    }

    uint8_t spare_block[S2N_DRBG_BLOCK_SIZE];
    GUARD(s2n_increment_sequence_number(&value));
    GUARD(s2n_drbg_block_encrypt(drbg->ctx, drbg->v, spare_block));
    drbg->bytes_used += S2N_DRBG_BLOCK_SIZE;

    memcpy_check(out->data + block_aligned_size, spare_block, out->size - block_aligned_size);

    return 0;
}

static int s2n_drbg_update(struct s2n_drbg *drbg, struct s2n_blob *provided_data)
{
    uint8_t temp[32];
    struct s2n_blob temp_blob = {.data = temp,.size = sizeof(temp) };

    eq_check(provided_data->size, sizeof(temp));

    GUARD(s2n_drbg_bits(drbg, &temp_blob));

    /* XOR in the provided data */
    for (int i = 0; i < provided_data->size; i++) {
        temp[i] ^= provided_data->data[i];
    }

    /* Update the key and value */
    GUARD_OSSL(EVP_EncryptInit_ex(drbg->ctx, EVP_aes_128_ecb(), NULL, temp, NULL), S2N_ERR_DRBG);

    memcpy_check(drbg->v, temp + S2N_DRBG_BLOCK_SIZE, S2N_DRBG_BLOCK_SIZE);

    return 0;
}

int s2n_drbg_seed(struct s2n_drbg *drbg, struct s2n_blob *ps)
{
    uint8_t seed[32];
    struct s2n_blob blob = {.data = seed,.size = sizeof(seed) };
    lte_check(ps->size, sizeof(seed));

    if (drbg->entropy_generator) {
        GUARD(drbg->entropy_generator(&blob));
    } else {
        GUARD(s2n_get_urandom_data(&blob));
    }

    for (int i = 0; i < ps->size; i++) {
        blob.data[i] ^= ps->data[i];
    }

    GUARD(s2n_drbg_update(drbg, &blob));

    drbg->bytes_used = 0;
    drbg->generation += 1;

    return 0;
}

int s2n_drbg_instantiate(struct s2n_drbg *drbg, struct s2n_blob *personalization_string)
{
    struct s2n_blob value = {.data = drbg->v,.size = sizeof(drbg->v) };
    uint8_t ps_prefix[32];
    struct s2n_blob ps = {.data = ps_prefix,.size = sizeof(ps_prefix) };

    /* Start off with zeroed data, per 10.2.1.3.1 item 4 */
    GUARD(s2n_blob_zero(&value));

    drbg->ctx = EVP_CIPHER_CTX_new();
    S2N_ERROR_IF(!drbg->ctx, S2N_ERR_DRBG);
    (void)EVP_CIPHER_CTX_init(drbg->ctx);

    /* Start off with zeroed key, per 10.2.1.3.1 item 5 */
    GUARD_OSSL(EVP_EncryptInit_ex(drbg->ctx, EVP_aes_128_ecb(), NULL, drbg->v, NULL), S2N_ERR_DRBG);

    /* Copy the personalization string */
    GUARD(s2n_blob_zero(&ps));

    memcpy_check(ps.data, personalization_string->data, MIN(ps.size, personalization_string->size));

    /* Seed / update the DRBG */
    GUARD(s2n_drbg_seed(drbg, &ps));

    /* After initial seeding, pivot to RDRAND if available and not overridden */
    if (drbg->entropy_generator == NULL && s2n_cpu_supports_rdrand()) {
        drbg->entropy_generator = s2n_get_rdrand_data;
    }
    return 0;
}

int s2n_drbg_generate(struct s2n_drbg *drbg, struct s2n_blob *blob)
{
    uint8_t all_zeros[32] = { 0 };
    struct s2n_blob zeros = {.data = all_zeros,.size = sizeof(all_zeros) };
    S2N_ERROR_IF(blob->size > S2N_DRBG_GENERATE_LIMIT, S2N_ERR_DRBG_REQUEST_SIZE);

    /* If either the entropy generator is set, for prediction resistance,
     * or if we reach the definitely-need-to-reseed limit, then reseed.
     */
    if (drbg->entropy_generator || drbg->bytes_used + blob->size + S2N_DRBG_BLOCK_SIZE >= S2N_DRBG_RESEED_LIMIT) {
        GUARD(s2n_drbg_seed(drbg, &zeros));
    }

    GUARD(s2n_drbg_bits(drbg, blob));
    GUARD(s2n_drbg_update(drbg, &zeros));

    return 0;
}

int s2n_drbg_wipe(struct s2n_drbg *drbg)
{
    struct s2n_blob state = {.data = (void *)drbg,.size = sizeof(struct s2n_drbg) };

    if (drbg->ctx) {
        GUARD_OSSL(EVP_CIPHER_CTX_cleanup(drbg->ctx), S2N_ERR_DRBG);

        EVP_CIPHER_CTX_free(drbg->ctx);
        drbg->ctx = NULL;
    }

    GUARD(s2n_blob_zero(&state));

    return 0;
}

int s2n_drbg_bytes_used(struct s2n_drbg *drbg)
{
    return drbg->bytes_used;
}
Ejemplo n.º 6
0
int s2n_server_cert_send(struct s2n_connection *conn)
{
    GUARD(s2n_send_cert_chain(&conn->handshake.io, conn->handshake_params.our_chain_and_key->cert_chain));
    return 0;
}
Ejemplo n.º 7
0
int s2n_prf_key_expansion(struct s2n_connection *conn)
{
    struct s2n_blob client_random = {.data = conn->secure.client_random,.size = sizeof(conn->secure.client_random) };
    struct s2n_blob server_random = {.data = conn->secure.server_random,.size = sizeof(conn->secure.server_random) };
    struct s2n_blob master_secret = {.data = conn->secure.master_secret,.size = sizeof(conn->secure.master_secret) };
    struct s2n_blob label, out;
    uint8_t key_expansion_label[] = "key expansion";
    uint8_t key_block[S2N_MAX_KEY_BLOCK_LEN];

    label.data = key_expansion_label;
    label.size = sizeof(key_expansion_label) - 1;
    out.data = key_block;
    out.size = sizeof(key_block);

    struct s2n_stuffer key_material;
    GUARD(s2n_prf(conn, &master_secret, &label, &server_random, &client_random, &out));
    GUARD(s2n_stuffer_init(&key_material, &out));
    GUARD(s2n_stuffer_write(&key_material, &out));

    GUARD(conn->secure.cipher_suite->cipher->init(&conn->secure.client_key));
    GUARD(conn->secure.cipher_suite->cipher->init(&conn->secure.server_key));

    /* What's our hmac algorithm? */
    s2n_hmac_algorithm hmac_alg = conn->secure.cipher_suite->hmac_alg;
    if (conn->actual_protocol_version == S2N_SSLv3) {
        if (hmac_alg == S2N_HMAC_SHA1) {
            hmac_alg = S2N_HMAC_SSLv3_SHA1;
        } else if (hmac_alg == S2N_HMAC_MD5) {
            hmac_alg = S2N_HMAC_SSLv3_MD5;
        } else {
            S2N_ERROR(S2N_ERR_HMAC_INVALID_ALGORITHM);
        }
    }

    /* Check that we have a valid MAC and key size */
    int mac_size;
    GUARD((mac_size = s2n_hmac_digest_size(hmac_alg)));

    /* Seed the client MAC */
    uint8_t *client_write_mac_key = s2n_stuffer_raw_read(&key_material, mac_size);
    notnull_check(client_write_mac_key);
    GUARD(s2n_hmac_init(&conn->secure.client_record_mac, hmac_alg, client_write_mac_key, mac_size));

    /* Seed the server MAC */
    uint8_t *server_write_mac_key = s2n_stuffer_raw_read(&key_material, mac_size);
    notnull_check(server_write_mac_key);
    GUARD(s2n_hmac_init(&conn->secure.server_record_mac, hmac_alg, server_write_mac_key, mac_size));

    /* Make the client key */
    struct s2n_blob client_key;
    client_key.size = conn->secure.cipher_suite->cipher->key_material_size;
    client_key.data = s2n_stuffer_raw_read(&key_material, client_key.size);
    notnull_check(client_key.data);
    if (conn->mode == S2N_CLIENT) {
        GUARD(conn->secure.cipher_suite->cipher->get_encryption_key(&conn->secure.client_key, &client_key));
    } else {
        GUARD(conn->secure.cipher_suite->cipher->get_decryption_key(&conn->secure.client_key, &client_key));
    }

    /* Make the server key */
    struct s2n_blob server_key;
    server_key.size = conn->secure.cipher_suite->cipher->key_material_size;
    server_key.data = s2n_stuffer_raw_read(&key_material, server_key.size);
    notnull_check(server_key.data);
    if (conn->mode == S2N_SERVER) {
        GUARD(conn->secure.cipher_suite->cipher->get_encryption_key(&conn->secure.server_key, &server_key));
    } else {
        GUARD(conn->secure.cipher_suite->cipher->get_decryption_key(&conn->secure.server_key, &server_key));
    }

    /* TLS >= 1.1 has no implicit IVs for non AEAD ciphers */
    if (conn->actual_protocol_version > S2N_TLS10 &&
        conn->secure.cipher_suite->cipher->type != S2N_AEAD) {
        return 0;
    }

    uint32_t implicit_iv_size = 0;
    switch(conn->secure.cipher_suite->cipher->type) {
        case S2N_AEAD:
            implicit_iv_size = conn->secure.cipher_suite->cipher->io.aead.fixed_iv_size;
            break;
        case S2N_CBC:
            implicit_iv_size = conn->secure.cipher_suite->cipher->io.cbc.block_size;
            break;
        /* No-op for stream ciphers */
        default:
            break;
    }

    struct s2n_blob client_implicit_iv = { .data = conn->secure.client_implicit_iv, .size = implicit_iv_size };
    struct s2n_blob server_implicit_iv = { .data = conn->secure.server_implicit_iv, .size = implicit_iv_size };
    GUARD(s2n_stuffer_read(&key_material, &client_implicit_iv));
    GUARD(s2n_stuffer_read(&key_material, &server_implicit_iv));

    return 0;
}
Ejemplo n.º 8
0
int s2n_connection_wipe(struct s2n_connection *conn)
{
    /* First make a copy of everything we'd like to save, which isn't very
     * much.
     */
    int mode = conn->mode;
    struct s2n_config *config = conn->config;
    struct s2n_stuffer alert_in;
    struct s2n_stuffer reader_alert_out;
    struct s2n_stuffer writer_alert_out;
    struct s2n_stuffer handshake_io;
    struct s2n_stuffer header_in;
    struct s2n_stuffer in;
    struct s2n_stuffer out;
    /* Session keys will be wiped. Preserve structs to avoid reallocation */
    struct s2n_session_key initial_client_key;
    struct s2n_session_key initial_server_key;
    struct s2n_session_key secure_client_key;
    struct s2n_session_key secure_server_key;

    /* Wipe all of the sensitive stuff */
    GUARD(s2n_connection_wipe_keys(conn));
    GUARD(s2n_stuffer_wipe(&conn->alert_in));
    GUARD(s2n_stuffer_wipe(&conn->reader_alert_out));
    GUARD(s2n_stuffer_wipe(&conn->writer_alert_out));
    GUARD(s2n_stuffer_wipe(&conn->handshake.io));
    GUARD(s2n_stuffer_wipe(&conn->header_in));
    GUARD(s2n_stuffer_wipe(&conn->in));
    GUARD(s2n_stuffer_wipe(&conn->out));

    /* Restore the socket option values */
    GUARD(s2n_socket_read_restore(conn));
    GUARD(s2n_socket_write_restore(conn));
    GUARD(s2n_free(&conn->status_response));

    /* Allocate or resize to their original sizes */
    GUARD(s2n_stuffer_resize(&conn->in, S2N_LARGE_FRAGMENT_LENGTH));

    /* Allocate memory for handling handshakes */
    GUARD(s2n_stuffer_resize(&conn->handshake.io, S2N_LARGE_RECORD_LENGTH));

    /* Clone the stuffers */
    /* ignore gcc 4.7 address warnings because dest is allocated on the stack */
    /* pragma gcc diagnostic was added in gcc 4.6 */
#if defined(__GNUC__) && GCC_VERSION >= 40600
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Waddress"
#endif
    memcpy_check(&alert_in, &conn->alert_in, sizeof(struct s2n_stuffer));
    memcpy_check(&reader_alert_out, &conn->reader_alert_out, sizeof(struct s2n_stuffer));
    memcpy_check(&writer_alert_out, &conn->writer_alert_out, sizeof(struct s2n_stuffer));
    memcpy_check(&handshake_io, &conn->handshake.io, sizeof(struct s2n_stuffer));
    memcpy_check(&header_in, &conn->header_in, sizeof(struct s2n_stuffer));
    memcpy_check(&in, &conn->in, sizeof(struct s2n_stuffer));
    memcpy_check(&out, &conn->out, sizeof(struct s2n_stuffer));
    memcpy_check(&initial_client_key, &conn->initial.client_key, sizeof(struct s2n_session_key));
    memcpy_check(&initial_server_key, &conn->initial.server_key, sizeof(struct s2n_session_key));
    memcpy_check(&secure_client_key, &conn->secure.client_key, sizeof(struct s2n_session_key));
    memcpy_check(&secure_server_key, &conn->secure.server_key, sizeof(struct s2n_session_key));
#if defined(__GNUC__) && GCC_VERSION >= 40600
#pragma GCC diagnostic pop
#endif

    /* Zero the whole connection structure */
    memset_check(conn, 0, sizeof(struct s2n_connection));

    conn->readfd = -1;
    conn->writefd = -1;
    conn->mode = mode;
    conn->config = config;
    conn->close_notify_queued = 0;
    conn->current_user_data_consumed = 0;
    conn->initial.cipher_suite = &s2n_null_cipher_suite;
    conn->secure.cipher_suite = &s2n_null_cipher_suite;
    conn->server = &conn->initial;
    conn->client = &conn->initial;
    conn->max_fragment_length = S2N_SMALL_FRAGMENT_LENGTH;
    conn->handshake.handshake_type = INITIAL;
    conn->handshake.message_number = 0;
    GUARD(s2n_hash_init(&conn->handshake.md5, S2N_HASH_MD5));
    GUARD(s2n_hash_init(&conn->handshake.sha1, S2N_HASH_SHA1));
    GUARD(s2n_hash_init(&conn->handshake.sha256, S2N_HASH_SHA256));
    GUARD(s2n_hash_init(&conn->handshake.sha384, S2N_HASH_SHA384));
    GUARD(s2n_hmac_init(&conn->client->client_record_mac, S2N_HMAC_NONE, NULL, 0));
    GUARD(s2n_hmac_init(&conn->server->server_record_mac, S2N_HMAC_NONE, NULL, 0));

    memcpy_check(&conn->alert_in, &alert_in, sizeof(struct s2n_stuffer));
    memcpy_check(&conn->reader_alert_out, &reader_alert_out, sizeof(struct s2n_stuffer));
    memcpy_check(&conn->writer_alert_out, &writer_alert_out, sizeof(struct s2n_stuffer));
    memcpy_check(&conn->handshake.io, &handshake_io, sizeof(struct s2n_stuffer));
    memcpy_check(&conn->header_in, &header_in, sizeof(struct s2n_stuffer));
    memcpy_check(&conn->in, &in, sizeof(struct s2n_stuffer));
    memcpy_check(&conn->out, &out, sizeof(struct s2n_stuffer));
    memcpy_check(&conn->initial.client_key, &initial_client_key, sizeof(struct s2n_session_key));
    memcpy_check(&conn->initial.server_key, &initial_server_key, sizeof(struct s2n_session_key));
    memcpy_check(&conn->secure.client_key, &secure_client_key, sizeof(struct s2n_session_key));
    memcpy_check(&conn->secure.server_key, &secure_server_key, sizeof(struct s2n_session_key));

    if (conn->mode == S2N_SERVER) {
        conn->server_protocol_version = s2n_highest_protocol_version;
        conn->client_protocol_version = s2n_unknown_protocol_version;
    }
    else {
        conn->server_protocol_version = s2n_unknown_protocol_version;
        conn->client_protocol_version = s2n_highest_protocol_version;
    }
    conn->actual_protocol_version = s2n_unknown_protocol_version;

    return 0;
}
Ejemplo n.º 9
0
UniformBufferMetaInfo::UniformBufferMetaInfo( GLint numMaxArrayElements, String bufferName, String arrayName,
        std::vector<String> memberStrings, Shader* queryShader)
    :
    mNumArrayElements(numMaxArrayElements),
    //mArrayName(arrayName),
    mMemberStrings(memberStrings),
    mRequiredBufferSize(0),
    mNumMemberElements(memberStrings.size() == 0 ? 1 : memberStrings.size() ),
    mBufferOffsets(0)
{
    LOG<<DEBUG_LOG_LEVEL<<bufferName<<"\n";
    GLuint shaderGLProgramHandle = queryShader->getGLProgramHandle();
    GLuint uniBlockIndex = GUARD( glGetUniformBlockIndex(shaderGLProgramHandle, bufferName.c_str()) );
    //query needed buffer size
    GUARD(
        glGetActiveUniformBlockiv(
            shaderGLProgramHandle,
            uniBlockIndex,
            GL_UNIFORM_BLOCK_DATA_SIZE,
            & mRequiredBufferSize
        )
    );

    //--------------------------------------------------------------------------------

    mBufferOffsets = new GLint*[mNumArrayElements];

//	const String memberStrings[] =
//		{
//		  "position","diffuseColor","specularColor","direction",
//		  "innerSpotCutOff_Radians","outerSpotCutOff_Radians","spotExponent","shadowMapLayer"
//		};

    const char** indexQuery_C_StringArray= new const char*[mNumMemberElements];
    String* indexQueryStringArray= new String[mNumMemberElements];
    GLuint* currentUniformIndices= new GLuint[mNumMemberElements];
    for(int arrayElementRunner=0; arrayElementRunner< mNumArrayElements; arrayElementRunner++)
    {
        String baseString =
            arrayName +
            String("[")
            + HelperFunctions::toString(arrayElementRunner)
            + String("]") ;


        mBufferOffsets[arrayElementRunner]= new GLint[mNumMemberElements];
        if(memberStrings.size() != 0)
        {
            //we have a structure as array elements; construct the GL referencation strings:
            for(int memberRunner=0; memberRunner< mNumMemberElements; memberRunner++)
            {
                indexQueryStringArray[memberRunner]= String(baseString+ String(".") + memberStrings[memberRunner]);
                indexQuery_C_StringArray[memberRunner]= indexQueryStringArray[memberRunner].c_str();
            }
        }
        else
        {
            //the array element constist of a single built-in type, i.e. the GL referencation strings
            //are a single string, beeing the base string:
            indexQuery_C_StringArray[0]= baseString.c_str();
        }

        //first, get indices of current lightsource members:
        GUARD(
            glGetUniformIndices(
                shaderGLProgramHandle,
                mNumMemberElements,
                indexQuery_C_StringArray,
                currentUniformIndices
            )
        );

        //second, get offset in buffer for those members, indentified by the queried indices:
        GUARD(
            glGetActiveUniformsiv(
                shaderGLProgramHandle,
                mNumMemberElements,
                currentUniformIndices,
                GL_UNIFORM_OFFSET,
                mBufferOffsets[arrayElementRunner]
            )
        );


//			for(int memberRunner=0; memberRunner< mNumMemberElements; memberRunner++)
//			{
//				LOG<<DEBUG_LOG_LEVEL << String(indexQuery_C_StringArray[memberRunner])<<" ;\n";
//				LOG<<DEBUG_LOG_LEVEL <<"uniform index: "<<  currentUniformIndices[memberRunner] <<" ;\n";
//				LOG<<DEBUG_LOG_LEVEL <<"uniform offset: "<<  mBufferOffsets[arrayElementRunner][memberRunner] <<" ;\n";
//				assert( "member should be active in shader, otherwise uniform buffer filling would turn out even more complicated :@"
//						&&  ( currentUniformIndices[memberRunner] != GL_INVALID_INDEX) );
//			}
    } //endfor
    delete[] indexQuery_C_StringArray;
    delete[] indexQueryStringArray;
    delete[] currentUniformIndices;
}
Ejemplo n.º 10
0
static int s2n_prf(struct s2n_connection *conn, struct s2n_blob *secret, struct s2n_blob *label, struct s2n_blob *seed_a, struct s2n_blob *seed_b, struct s2n_blob *out)
{
    if (conn->actual_protocol_version == S2N_SSLv3) {
        return s2n_sslv3_prf(&conn->prf_space, secret, seed_a, seed_b, out);
    }

    /* We zero the out blob because p_hash works by XOR'ing with the existing
     * buffer. This is a little convuloted but means we can avoid dynamic memory
     * allocation. When we call p_hash once (in the TLS1.2 case) it will produce
     * the right values. When we call it twice in the regular case, the two
     * outputs will be XORd just ass the TLS 1.0 and 1.1 RFCs require.
     */
    GUARD(s2n_blob_zero(out));

    if (conn->actual_protocol_version == S2N_TLS12) {
        return s2n_p_hash(&conn->prf_space, conn->secure.cipher_suite->tls12_prf_alg, secret, label, seed_a, seed_b, out);
    }

    struct s2n_blob half_secret = {.data = secret->data,.size = (secret->size + 1) / 2 };

    GUARD(s2n_p_hash(&conn->prf_space, S2N_HMAC_MD5, &half_secret, label, seed_a, seed_b, out));
    half_secret.data += secret->size - half_secret.size;
    GUARD(s2n_p_hash(&conn->prf_space, S2N_HMAC_SHA1, &half_secret, label, seed_a, seed_b, out));

    return 0;
}

int s2n_prf_master_secret(struct s2n_connection *conn, struct s2n_blob *premaster_secret)
{
    struct s2n_blob client_random, server_random, master_secret;
    struct s2n_blob label;
    uint8_t master_secret_label[] = "master secret";

    client_random.data = conn->secure.client_random;
    client_random.size = sizeof(conn->secure.client_random);
    server_random.data = conn->secure.server_random;
    server_random.size = sizeof(conn->secure.server_random);
    master_secret.data = conn->secure.master_secret;
    master_secret.size = sizeof(conn->secure.master_secret);
    label.data = master_secret_label;
    label.size = sizeof(master_secret_label) - 1;

    return s2n_prf(conn, premaster_secret, &label, &client_random, &server_random, &master_secret);
}

static int s2n_sslv3_finished(struct s2n_connection *conn, uint8_t prefix[4], struct s2n_hash_state *md5, struct s2n_hash_state *sha1, uint8_t *out)
{
    uint8_t xorpad1[48] =
        { 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
        0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36
    };
    uint8_t xorpad2[48] =
        { 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
        0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c
    };
    uint8_t *md5_digest = out;
    uint8_t *sha_digest = out + MD5_DIGEST_LENGTH;

    lte_check(MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH, sizeof(conn->handshake.client_finished));

    GUARD(s2n_hash_update(md5, prefix, 4));
    GUARD(s2n_hash_update(md5, conn->secure.master_secret, sizeof(conn->secure.master_secret)));
    GUARD(s2n_hash_update(md5, xorpad1, 48));
    GUARD(s2n_hash_digest(md5, md5_digest, MD5_DIGEST_LENGTH));
    GUARD(s2n_hash_reset(md5));
    GUARD(s2n_hash_update(md5, conn->secure.master_secret, sizeof(conn->secure.master_secret)));
    GUARD(s2n_hash_update(md5, xorpad2, 48));
    GUARD(s2n_hash_update(md5, md5_digest, MD5_DIGEST_LENGTH));
    GUARD(s2n_hash_digest(md5, md5_digest, MD5_DIGEST_LENGTH));
    GUARD(s2n_hash_reset(md5));

    GUARD(s2n_hash_update(sha1, prefix, 4));
    GUARD(s2n_hash_update(sha1, conn->secure.master_secret, sizeof(conn->secure.master_secret)));
    GUARD(s2n_hash_update(sha1, xorpad1, 40));
    GUARD(s2n_hash_digest(sha1, sha_digest, SHA_DIGEST_LENGTH));
    GUARD(s2n_hash_reset(sha1));
    GUARD(s2n_hash_update(sha1, conn->secure.master_secret, sizeof(conn->secure.master_secret)));
    GUARD(s2n_hash_update(sha1, xorpad2, 40));
    GUARD(s2n_hash_update(sha1, sha_digest, SHA_DIGEST_LENGTH));
    GUARD(s2n_hash_digest(sha1, sha_digest, SHA_DIGEST_LENGTH));
    GUARD(s2n_hash_reset(sha1));

    return 0;
}
Ejemplo n.º 11
0
static void Test_SingleProcess()
{
    LOG_POST("=== Single-process test ===");
    const CTimeout zero_timeout = CTimeout(0,0);

    LOG_POST("\n--- Test 1");
    // Name test
    {{
        try {
            CInterProcessLock lock("");
        } catch (CInterProcessLockException&) {}
        try {
            CInterProcessLock lock("relative/path");
        } catch (CInterProcessLockException&) {}
        {{
            CInterProcessLock lock("name");
            assert(lock.GetName() == "name");
#if defined(NCBI_OS_UNIX)
            assert(lock.GetSystemName() == "/var/tmp/name");
#elif defined(NCBI_OS_MSWIN)
            assert(lock.GetSystemName() == "name");
#endif
        }}
    }}

    // Fixed names are usually more appropriate, but here we don't
    // want independent tests to step on each other...
    string lockname = CFile::GetTmpName();

    CInterProcessLock lock1(lockname);
    CInterProcessLock lock2(lockname);
    CInterProcessLock lock3(lockname);

    LOG_POST("lock name = " << lock1.GetName());
    LOG_POST("lock system name = " << lock1.GetSystemName());

    LOG_POST("\n--- Test 2");
    // Direct CInterProcessLock usage
    {{
        lock1.Lock(/*infinite*/);
        try {
            lock2.Lock(zero_timeout);
            assert(0);
        }
        catch (CInterProcessLockException&) {}
        
        assert( !lock2.TryLock() );
        lock1.Unlock();
        lock2.Lock(/*infinite*/);
        assert( !lock3.TryLock() );
        lock2.Unlock();
        lock1.Lock(zero_timeout);
        lock1.Remove();
        // everything unlocked
    }}

    LOG_POST("\n--- Test 3");
    // CGuard usage
    {{
        {{
            CGuard<CInterProcessLock> GUARD(lock1);
            try {
                lock2.Lock(zero_timeout);
                assert(0);
            }
            catch (CInterProcessLockException&) {}
        }}
        lock2.Lock(zero_timeout);
        lock2.Remove();
        // everything unlocked
    }}

    LOG_POST("\n--- Test 4");
    // Reference count test
    {{
        assert( lock1.TryLock() );
        assert( lock1.TryLock() );
        assert( !lock2.TryLock() );
        assert( lock1.TryLock() );
        lock1.Unlock();
        lock1.Unlock();
        lock1.Unlock();
        try {
            lock1.Unlock();
            assert(0);
        }
        catch (CInterProcessLockException&) {}
        // everything unlocked
    }}
    // We don't need lock object anymore, remove it from the system
    lock1.Remove();
}
Ejemplo n.º 12
0
int s2n_config_free_cert_chain_and_key(struct s2n_config *config)
{
    struct s2n_blob b = {
        .data = (uint8_t *) config->cert_and_key_pairs,
        .size = sizeof(struct s2n_cert_chain_and_key)
    };

    /* If there were cert and key pairs set, walk the chain and free the certs */
    if (config->cert_and_key_pairs) {
        struct s2n_cert_chain *node = config->cert_and_key_pairs->head;
        while (node) {
            struct s2n_blob n = {
                .data = (uint8_t *)node,
                .size = sizeof(struct s2n_cert_chain)
            };
            /* Free the cert */
            GUARD(s2n_free(&node->cert));
            /* Advance to next */
            node = node->next;
            /* Free the node */
            GUARD(s2n_free(&n));
        }
        GUARD(s2n_rsa_private_key_free(&config->cert_and_key_pairs->private_key));
        GUARD(s2n_free(&config->cert_and_key_pairs->ocsp_status));
    }

    GUARD(s2n_free(&b));
    return 0;
}

int s2n_config_free_dhparams(struct s2n_config *config)
{
    struct s2n_blob b = {
        .data = (uint8_t *) config->dhparams,
        .size = sizeof(struct s2n_dh_params)
    };

    if (config->dhparams) {
        GUARD(s2n_dh_params_free(config->dhparams));
    }

    GUARD(s2n_free(&b));
    return 0;
}

int s2n_config_free(struct s2n_config *config)
{
    struct s2n_blob b = {.data = (uint8_t *) config,.size = sizeof(struct s2n_config) };

    GUARD(s2n_config_free_cert_chain_and_key(config));
    GUARD(s2n_config_free_dhparams(config));
    GUARD(s2n_free(&config->application_protocols));

    GUARD(s2n_free(&b));
    return 0;
}

int s2n_config_set_cipher_preferences(struct s2n_config *config, const char *version)
{
    for (int i = 0; selection[i].version != NULL; i++) {
        if (!strcasecmp(version, selection[i].version)) {
            config->cipher_preferences = selection[i].preferences;
            return 0;
        }
    }

    S2N_ERROR(S2N_ERR_INVALID_CIPHER_PREFERENCES);
}

int s2n_config_set_protocol_preferences(struct s2n_config *config, const char * const *protocols, int protocol_count)
{
    struct s2n_stuffer protocol_stuffer;

    GUARD(s2n_free(&config->application_protocols));

    if (protocols == NULL || protocol_count == 0) {
        /* NULL value indicates no prference, so nothing to do */
        return 0;
    }

    GUARD(s2n_stuffer_growable_alloc(&protocol_stuffer, 256));
    for (int i = 0; i < protocol_count; i++) {
        size_t length = strlen(protocols[i]);
        uint8_t protocol[255];

        if (length > 255 || (s2n_stuffer_data_available(&protocol_stuffer) + length + 1) > 65535) {
            return S2N_ERR_APPLICATION_PROTOCOL_TOO_LONG;
        }
        memcpy_check(protocol, protocols[i], length);
        GUARD(s2n_stuffer_write_uint8(&protocol_stuffer, length));
        GUARD(s2n_stuffer_write_bytes(&protocol_stuffer, protocol, length));
    }

    uint32_t size = s2n_stuffer_data_available(&protocol_stuffer);
    /* config->application_protocols blob now owns this data */
    config->application_protocols.size = size;
    config->application_protocols.data = s2n_stuffer_raw_read(&protocol_stuffer, size);
    notnull_check(config->application_protocols.data);

    return 0;
}

int s2n_config_set_status_request_type(struct s2n_config *config, s2n_status_request_type type)
{
    config->status_request_type = type;

    return 0;
}

int s2n_config_add_cert_chain_and_key_with_status(struct s2n_config *config,
        char *cert_chain_pem, char *private_key_pem, const uint8_t *status, uint32_t length)
{
    struct s2n_stuffer chain_in_stuffer, cert_out_stuffer, key_in_stuffer, key_out_stuffer;
    struct s2n_blob key_blob;
    struct s2n_blob mem;

    /* Allocate the memory for the chain and key struct */
    GUARD(s2n_alloc(&mem, sizeof(struct s2n_cert_chain_and_key)));
    config->cert_and_key_pairs = (struct s2n_cert_chain_and_key *)(void *)mem.data;
    config->cert_and_key_pairs->ocsp_status.data = NULL;
    config->cert_and_key_pairs->ocsp_status.size = 0;

    /* Put the private key pem in a stuffer */
    GUARD(s2n_stuffer_alloc_ro_from_string(&key_in_stuffer, private_key_pem));
    GUARD(s2n_stuffer_growable_alloc(&key_out_stuffer, strlen(private_key_pem)));

    /* Convert pem to asn1 and asn1 to the private key */
    GUARD(s2n_stuffer_rsa_private_key_from_pem(&key_in_stuffer, &key_out_stuffer));
    GUARD(s2n_stuffer_free(&key_in_stuffer));
    key_blob.size = s2n_stuffer_data_available(&key_out_stuffer);
    key_blob.data = s2n_stuffer_raw_read(&key_out_stuffer, key_blob.size);
    notnull_check(key_blob.data);
    GUARD(s2n_asn1der_to_rsa_private_key(&config->cert_and_key_pairs->private_key, &key_blob));
    GUARD(s2n_stuffer_free(&key_out_stuffer));

    /* Turn the chain into a stuffer */
    GUARD(s2n_stuffer_alloc_ro_from_string(&chain_in_stuffer, cert_chain_pem));
    GUARD(s2n_stuffer_growable_alloc(&cert_out_stuffer, 2048));

    struct s2n_cert_chain **insert = &config->cert_and_key_pairs->head;
    uint32_t chain_size = 0;
    do {
        struct s2n_cert_chain *new_node;

        if (s2n_stuffer_certificate_from_pem(&chain_in_stuffer, &cert_out_stuffer) < 0) {
            if (chain_size == 0) {
                S2N_ERROR(S2N_ERR_NO_CERTIFICATE_IN_PEM);
            }
            break;
        }

        GUARD(s2n_alloc(&mem, sizeof(struct s2n_cert_chain)));
        new_node = (struct s2n_cert_chain *)(void *)mem.data;

        GUARD(s2n_alloc(&new_node->cert, s2n_stuffer_data_available(&cert_out_stuffer)));
        GUARD(s2n_stuffer_read(&cert_out_stuffer, &new_node->cert));

        /* Additional 3 bytes for the length field in the protocol */
        chain_size += new_node->cert.size + 3;
        new_node->next = NULL;
        *insert = new_node;
        insert = &new_node->next;
    } while (s2n_stuffer_data_available(&chain_in_stuffer));

    GUARD(s2n_stuffer_free(&chain_in_stuffer));
    GUARD(s2n_stuffer_free(&cert_out_stuffer));

    config->cert_and_key_pairs->chain_size = chain_size;

    if (status && length > 0) {
        GUARD(s2n_alloc(&config->cert_and_key_pairs->ocsp_status, length));
        memcpy_check(config->cert_and_key_pairs->ocsp_status.data, status, length);
    }

    return 0;
}

int s2n_config_add_cert_chain_and_key(struct s2n_config *config, char *cert_chain_pem, char *private_key_pem)
{
    GUARD(s2n_config_add_cert_chain_and_key_with_status(config, cert_chain_pem, private_key_pem, NULL, 0));

    return 0;
}

int s2n_config_add_dhparams(struct s2n_config *config, char *dhparams_pem)
{
    struct s2n_stuffer dhparams_in_stuffer, dhparams_out_stuffer;
    struct s2n_blob dhparams_blob;
    struct s2n_blob mem;

    /* Allocate the memory for the chain and key struct */
    GUARD(s2n_alloc(&mem, sizeof(struct s2n_dh_params)));
    config->dhparams = (struct s2n_dh_params *)(void *)mem.data;

    GUARD(s2n_stuffer_alloc_ro_from_string(&dhparams_in_stuffer, dhparams_pem));
    GUARD(s2n_stuffer_growable_alloc(&dhparams_out_stuffer, strlen(dhparams_pem)));

    /* Convert pem to asn1 and asn1 to the private key */
    GUARD(s2n_stuffer_dhparams_from_pem(&dhparams_in_stuffer, &dhparams_out_stuffer));

    GUARD(s2n_stuffer_free(&dhparams_in_stuffer));

    dhparams_blob.size = s2n_stuffer_data_available(&dhparams_out_stuffer);
    dhparams_blob.data = s2n_stuffer_raw_read(&dhparams_out_stuffer, dhparams_blob.size);
    notnull_check(dhparams_blob.data);

    GUARD(s2n_pkcs3_to_dh_params(config->dhparams, &dhparams_blob));

    GUARD(s2n_free(&dhparams_blob));

    return 0;
}
 
int s2n_config_set_nanoseconds_since_epoch_callback(struct s2n_config *config, int (*nanoseconds_since_epoch)(void *, uint64_t *), void * data)
{
    notnull_check(nanoseconds_since_epoch);

    config->nanoseconds_since_epoch = nanoseconds_since_epoch;
    config->data_for_nanoseconds_since_epoch = data;

    return 0;
}

int s2n_config_set_cache_store_callback(struct s2n_config *config, int (*cache_store)(void *, const void *key, uint64_t key_size, const void *value, uint64_t value_size), void *data)
{
    notnull_check(cache_store);

    config->cache_store = cache_store;
    config->cache_store_data = data;

    return 0;
}
Ejemplo n.º 13
0
/*
====================
Save
====================
*/
VOID EChunk::Save(GFile& file)
{
	GUARD(EChunk::Save);

	// write the chunk header
	U32 header = MAKEFOURCC('G','C','H','K');
	file.Write(&header, sizeof(U32));

	// write the number of layers
	U32 num_layer = mLayers.size();
	file.Write(&num_layer, sizeof(U32));

	// write all of the layers
	if(mLayers.size() == 1)
	{
		Layer& layer = mLayers[0];

		// write the texture
		U32 name_len = layer.name.size();
		file.Write(&name_len, sizeof(U32));
		file.Write(layer.name.c_str(), name_len*sizeof(CHAR));
		file.Write(layer.st.ptr(), 2*sizeof(F32));

		// write the alpha
		U32 width = 1;
		file.Write(&width, sizeof(U32));
		U32 height = 1;
		file.Write(&height, sizeof(U32));
		U8 alpha = 127;
		file.Write(&alpha, sizeof(U8));
	}
	else
	{
		for(I32 k = 0; k < mLayers.size(); k++)
		{
			Layer& layer = mLayers[k];

			// write the texture
			U32 name_len = layer.name.size();
			file.Write(&name_len, sizeof(U32));
			file.Write(layer.name.c_str(), name_len*sizeof(CHAR));
			file.Write(layer.st.ptr(), 2*sizeof(F32));

			// write the alpha
			U32 width = U2P(ALPHA_STRIDE);
			file.Write(&width, sizeof(U32));
			U32 height = U2P(ALPHA_STRIDE);
			file.Write(&height, sizeof(U32));
			if(k==0)
			{
				std::vector<U8>data(width*height);
				for(U32 j = 0; j < height; j++)
				{
					for( U32 i = 0; i < width; i++)
					{
						U8& alpha = layer.alpha[i+j*width];
						U8& mask = mMask[i+j*width];
						if(mask == 0) data[i+j*width] = (U8)(((F32)alpha)/255.0f*127.0f);
						else data[i+j*width] = (U8)(((F32)alpha)/255.0f*127.0f)+128;
					}
				}
				file.Write(&data[0], width*height*sizeof(U8));
			}
			else
			{
				file.Write(&layer.alpha[0], width*height*sizeof(U8));
			}
		}
	}	

	UNGUARD;
}
Ejemplo n.º 14
0
bool BufferInterface::allocMem()throw(BufferException)
{
	if( mBufferInfo->isPingPongBuffer ||
		//don't trust the bufferInfo
		dynamic_cast<PingPongBuffer*>(this)
	)
	{
		throw(BufferException("Buffer::allocMem(): this routine may never be calles for ping pong buffers, as they are only managers"
				"for other buffers but having some own associated memory!"));
	}


	//assert that this routine is called only once per object:
	if(mCPU_Handle || mGraphicsBufferHandle || mComputeBufferHandle())
	{
		throw(BufferException("Buffer::allocMem(): some buffers already allocated"));
	}

	if( mBufferInfo->usageContexts & HOST_CONTEXT_TYPE_FLAG )
	{
		mCPU_Handle = malloc(mBufferInfo->bufferSizeInByte);
	}

	if(mBufferInfo->usageContexts & OPEN_GL_CONTEXT_TYPE_FLAG)
	{
		//ok, there is a need for an openGL buffer; maybe it will be shared with openCL,
		//but that doesn't matter for the GL buffer creation :)
		if( isDefaultBuffer() && (mBufferInfo->glBufferType == NO_GL_BUFFER_TYPE)	)
		{
			throw(BufferException("no gl buffer type specified for a non-texture or non-renderbuffer Buffer, although a gl usage context was requested"));
		}
		//no special treatment for texture types, as we use native GL-#defines

		GUARD(generateGL());
		//"direct" call of "bindGL()" here isn't dangerous, as the buffer is not shared (yet),
		//as it has just been created;
		GUARD(bindGL());
		GUARD(allocGL());
	}

	//ok, the GL stuff is allocated if it was requested; Now let's check for the "compute" world;
	if(mBufferInfo->usageContexts & OPEN_CL_CONTEXT_TYPE_FLAG)
	{
		if(mBufferInfo->usageContexts & OPEN_GL_CONTEXT_TYPE_FLAG)
		{
			//both CL and GL are requested, that means interop:
			//neither bind nor alloc necessary, just generating:
			GUARD(generateCLGL());

		}
		else
		{
			//a CL-only buffer is requested:
			//in OpenCL, alloc is done at the same time of generation; so, no allocCL() routine must be called
			GUARD(generateCL());
			//GUARD(allocCL()); <--bullshaat ;)
		}
	}


#if (FLEWNIT_TRACK_MEMORY || FLEWNIT_DO_PROFILING)
	//only track memory for non-pingpongs, as pingpongs only manage, but don't "own" own data store;
	if(! mBufferInfo->isPingPongBuffer)
	{
		registerBufferAllocation(mBufferInfo->usageContexts,mBufferInfo->bufferSizeInByte);
	}
#endif

	return true;

}
Ejemplo n.º 15
0
static int s2n_p_hash(union s2n_prf_working_space *ws, s2n_hmac_algorithm alg, struct s2n_blob *secret,
                      struct s2n_blob *label, struct s2n_blob *seed_a, struct s2n_blob *seed_b, struct s2n_blob *out)
{
    struct s2n_hmac_state *hmac = &ws->tls.hmac;
    uint32_t digest_size = s2n_hmac_digest_size(alg);

    /* First compute hmac(secret + A(0)) */
    GUARD(s2n_hmac_init(hmac, alg, secret->data, secret->size));
    GUARD(s2n_hmac_update(hmac, label->data, label->size));
    GUARD(s2n_hmac_update(hmac, seed_a->data, seed_a->size));

    if (seed_b) {
        GUARD(s2n_hmac_update(hmac, seed_b->data, seed_b->size));
    }
    GUARD(s2n_hmac_digest(hmac, ws->tls.digest0, digest_size));

    uint32_t outputlen = out->size;
    uint8_t *output = out->data;

    while (outputlen) {
        /* Now compute hmac(secret + A(N - 1) + seed) */
        GUARD(s2n_hmac_reset(hmac));
        GUARD(s2n_hmac_update(hmac, ws->tls.digest0, digest_size));

        /* Add the label + seed and compute this round's A */
        GUARD(s2n_hmac_update(hmac, label->data, label->size));
        GUARD(s2n_hmac_update(hmac, seed_a->data, seed_a->size));
        if (seed_b) {
            GUARD(s2n_hmac_update(hmac, seed_b->data, seed_b->size));
        }
        GUARD(s2n_hmac_digest(hmac, ws->tls.digest1, digest_size));

        uint32_t bytes_to_xor = MIN(outputlen, digest_size);

        for (int i = 0; i < bytes_to_xor; i++) {
            *output ^= ws->tls.digest1[i];
            output++;
            outputlen--;
        }

        /* Stash a digest of A(N), in A(N), for the next round */
        GUARD(s2n_hmac_reset(hmac));
        GUARD(s2n_hmac_update(hmac, ws->tls.digest0, digest_size));
        GUARD(s2n_hmac_digest(hmac, ws->tls.digest0, digest_size));
    }

    return 0;
}
Ejemplo n.º 16
0
const BufferInterface& BufferInterface::operator=(const BufferInterface& rhs) throw(BufferException)
{
	//the buffers must match exactly in all their meta-info in order to be securely copied
	//OpenGL and OpenCL are less restrictve than me, but in this case, I trade flexibility
	//for simplicity and robustness;
	if( (*this) == rhs )
	{
		if((mBufferInfo->usageContexts & HOST_CONTEXT_TYPE_FLAG) !=0)
		{
			memcpy(mCPU_Handle,rhs.getCPUBufferHandle(),mBufferInfo->bufferSizeInByte);
		}

		//GL
		if(
			( hasBufferInContext(OPEN_GL_CONTEXT_TYPE) && PARA_COMP_MANAGER->graphicsAreInControl() )
			||
			! (hasBufferInContext(OPEN_CL_CONTEXT_TYPE))
		)
		{
			//commented out the guard in case of driver bugs fu**ing up when doing too mush time-shared CL-GL-stuff
			//TODO uncomment when stable work is assured
			//if(isCLGLShared())
			{
				PARA_COMP_MANAGER->acquireSharedBuffersForGraphics();
			}
			//do a barrier in by all means to assure buffer integrity;
			PARA_COMP_MANAGER->barrierGraphics();

			GUARD(copyGLFrom(rhs.getGraphicsBufferHandle()));
			//return, as a shared buffer does need only copy via one context;
			return *this;
		}

		//CL
		if(
			( hasBufferInContext(OPEN_CL_CONTEXT_TYPE) && PARA_COMP_MANAGER->computeIsInControl() )
			||
			! (hasBufferInContext(OPEN_GL_CONTEXT_TYPE))
		)
		{
			//commented out the guard in case of driver bugs fu**ing up when doing too mush time-shared CL-GL-stuff
			//TODO uncomment when stable work is assured
			//if(isCLGLShared())
			{
				PARA_COMP_MANAGER->acquireSharedBuffersForCompute();
			}

			//do a barrier in by all means to assure buffer integrity;
			PARA_COMP_MANAGER->barrierCompute();
			GUARD(copyCLFrom(rhs.getComputeBufferHandle()));
			return *this;
		}

	}
	else
	{
		throw(BufferException("Buffer::operator= : Buffers not compatible"));
	}


	return *this;
}
Ejemplo n.º 17
0
int s2n_stuffer_read_uint8(struct s2n_stuffer *stuffer, uint8_t *u)
{
    GUARD(s2n_stuffer_read_bytes(stuffer, u, 1));

    return 0;
}
Ejemplo n.º 18
0
int main(int argc,char** argv){
	// openssl support
#ifdef _SSL
	initSSL();
	ctx=SSL_CTX_new(SSLv23_client_method());
	if(ctx==NULL){
		ERR_print_errors_fp(stdout);
		exit(-2);
	}
#endif

	if(argc!=2){
		printf("Usage:client ipv6addr\n");
		exit(-1);
	}
	setlocale(LC_ALL,"");
	char name[10];
	printf("输入昵称:\n");
	scanf("%6s",name);

	int sockfd,len;
	struct sockaddr_in6	dst;
	char buf[MAXBUF+1];
	char buf1[MAXBUF+1];

	sockfd=socket(AF_INET6,PROTOCOL,0);
	GUARD(sockfd);

	bzero(&dst,sizeof(dst));
	dst.sin6_family=AF_INET6;
	dst.sin6_port=htons(SERVERPORT);
	GUARD(inet_pton(AF_INET6,argv[1],&dst.sin6_addr));
	GUARD(connect(sockfd,(struct sockaddr *)&dst,sizeof(dst)));

	// ssl support
#ifdef _SSL
	sslfd=SSL_new(ctx);
	SSL_set_fd(sslfd,sockfd);
	if(SSL_connect(sslfd)==-1)
		ERR_print_errors_fp(stderr);
	else{
		printf("connected with %s encryption\n",SSL_get_cipher(sslfd));
		//ShowCerts(sslfd);
	}
#endif
	// ssl support bind over
	
	initscr();
	WINDOW *recvBd=subwin(stdscr,HEIGHT1+2,WIDTH+2,1,1);
	WINDOW *inputBd=subwin(stdscr,HEIGHT+2,WIDTH+2,15,1);
	recvWin=subwin(stdscr,HEIGHT1,WIDTH,2,2);
	inputWin=subwin(stdscr,HEIGHT,WIDTH,16,2);
	box(recvBd,HLINE,VLINE);
	box(inputBd,HLINE,VLINE);
	wprintw(recvBd,"接收");
	wprintw(inputBd,"发送");
	cbreak();
	keypad(stdscr,TRUE);
	start_color();
	scrollok(recvWin,1);
	scrollok(inputWin,1);
	refresh();

	bzero(buf,MAXBUF+1);
#ifndef _SSL
	len=recv(sockfd,buf,MAXBUF,0);
#else
	len=SSL_read(sslfd,buf,MAXBUF);
#endif
	wprintw(recvWin,"%s\n",buf);
	touchwin(recvWin);
	wrefresh(recvWin);

	pthread_t t_recv;
	if(pthread_create(&t_recv,NULL,recvThread,(void*)sockfd)<0){
		perror("create thread");
		exit(1);
	}

	while(1){
		bzero(buf,MAXBUF+1);
		wprintw(inputWin,"%6s > ",name);
		int key=wgetch(inputWin);
		if(key==ESCAPE){
			break;
		}
		wscanw(inputWin,"%s",buf);
		touchwin(inputWin);
		wrefresh(inputWin);

		sprintf(buf1,"[%6s]: %c%s\n",name,(char)key,buf);
#ifndef _SSL
		len=send(sockfd,buf1,strlen(buf1),0);
#else
		len=SSL_write(sslfd,buf1,strlen(buf1));
#endif
		if(len<0)
			continue;
	}
	close(sockfd);
	delwin(recvWin);
	delwin(inputWin);
	delwin(recvBd);
	delwin(inputBd);
	endwin();
#ifdef _SSL
	SSL_shutdown(sslfd);
	SSL_free(sslfd);
	SSL_CTX_free(ctx);
#endif
	return 0;
}
Ejemplo n.º 19
0
int s2n_stuffer_write_uint8(struct s2n_stuffer *stuffer, const uint8_t u)
{
    GUARD(s2n_stuffer_write_bytes(stuffer, &u, 1));

    return 0;
}
Ejemplo n.º 20
0
int main(int argc, char **argv)
{
    uint8_t u8; uint16_t u16; uint32_t u32;
    
    uint32_t stuffer_size = nondet_uint32();
	__CPROVER_assume(stuffer_size > 0);
	
	uint32_t entropy_size = nondet_uint32();
	__CPROVER_assume(entropy_size > 0);
	
	uint8_t entropy[entropy_size];
    struct s2n_stuffer stuffer;
	
    GUARD(s2n_stuffer_alloc(&stuffer, stuffer_size));

    struct s2n_blob in = {.data = entropy,.size = entropy_size};
    GUARD(s2n_stuffer_write(&stuffer, &in));

	GUARD(s2n_stuffer_wipe(&stuffer));
	while(nondet_bool()) {
        GUARD(s2n_stuffer_write_uint8(&stuffer, nondet_uint64()));
    }

    while(nondet_bool()) {
        GUARD(s2n_stuffer_read_uint8(&stuffer, &u8));
    }

    GUARD(s2n_stuffer_wipe(&stuffer));
    while(nondet_bool()) {
        GUARD(s2n_stuffer_write_uint16(&stuffer, nondet_uint64()));
    }

    while(nondet_bool()) {
        GUARD(s2n_stuffer_read_uint16(&stuffer, &u16));
    }

    GUARD(s2n_stuffer_wipe(&stuffer));
    while(nondet_bool()) {
        GUARD(s2n_stuffer_write_uint24(&stuffer, nondet_uint64()));
    }

    while(nondet_bool()) {
        GUARD(s2n_stuffer_read_uint24(&stuffer, &u32));
    }

    GUARD(s2n_stuffer_wipe(&stuffer));
    while(nondet_bool()) {
        GUARD(s2n_stuffer_write_uint32(&stuffer, nondet_uint64()));
    }

    while(nondet_bool()) {
        GUARD(s2n_stuffer_read_uint32(&stuffer, &u32));
    }

    GUARD(s2n_stuffer_free(&stuffer));
}
Ejemplo n.º 21
0
// [[register]]
SEXP unmelt(SEXP data, SEXP uniq_id, SEXP other_ind_, SEXP id_ind_, SEXP value_ind_) {

	// int id_ind = asInteger(id_ind_);
	int value_ind = asInteger(value_ind_);
	int* other_ind = INTEGER(other_ind_);
	int nRow = (int)(length(VECTOR_ELT(data, 0)) / length(uniq_id));
	int numprotect = 0;

	if (TYPEOF(uniq_id) != STRSXP) {
		GUARD(uniq_id = coerceVector(uniq_id, STRSXP));
	}

	int n_uniq = length(uniq_id);

	SEXP output;
	GUARD(output = allocVector(VECSXP, length(other_ind_) + length(uniq_id)));

	int n_other = length(other_ind_);

	// ensure that the unmelting process will go smoothly
#define HANDLE_CASE(RTYPE, CTYPE, ACCESSOR) \
		case RTYPE: { \
			CTYPE* tmp = ACCESSOR( VECTOR_ELT(data, other_ind[i]) ); \
			for (int j=0; j < nRow; ++j) { \
				for (int k=1; k < n_uniq; ++k) { \
					if (tmp[j] != tmp[j + nRow*k]) { \
						Rf_error("Mismatch in elements at indices %i and %i in vector %s", j+1, j + nRow*k+1, CHAR(STRING_ELT(getAttrib(data, R_NamesSymbol), other_ind[i]))); \
					} \
				} \
			} \
			break; \
		} \


	if (n_uniq > 1) {
		for (int i=0; i < n_other; ++i) {
			switch (TYPEOF(VECTOR_ELT(data, other_ind[i]))) {
			HANDLE_CASE(LGLSXP, int, LOGICAL);
			HANDLE_CASE(INTSXP, int, INTEGER);
			HANDLE_CASE(REALSXP, double, REAL);
			HANDLE_CASE(STRSXP, SEXP, STRING_PTR);
			default: Rf_error("Unhandled type %s", type2char(TYPEOF(VECTOR_ELT(data, other_ind[i]))));
			}
		}
	}

#undef HANDLE_CASE

	// copy in the 'other' variables first
#define COPY(RTYPE, CTYPE, ACCESSOR) { \
		PROTECT(tmp = allocVector(RTYPE, nRow)); \
		CTYPE* tmp_ptr = ACCESSOR(tmp); \
		CTYPE* data_ptr = ACCESSOR(VECTOR_ELT(data, other_ind[i])); \
		for (int i=0; i < nRow; ++i) { \
			tmp_ptr[i] = data_ptr[i]; \
		} \
		SET_VECTOR_ELT(output, i, tmp); \
		UNPROTECT(1); \
		break; \
		} \

	SEXP tmp;
	for (int i=0; i < n_other; ++i) {
		switch (TYPEOF(VECTOR_ELT(data, other_ind[i]))) {
		case LGLSXP: COPY(LGLSXP, int, LOGICAL);
		case INTSXP: COPY(INTSXP, int, INTEGER);
		case REALSXP: COPY(REALSXP, double, REAL);
		case STRSXP: COPY(STRSXP, SEXP, STRING_PTR);
		default: Rf_error("Unhandled SEXP type");
		}
	}

#undef COPY

#define COPY(RTYPE, CTYPE, ACCESSOR) { \
		PROTECT(tmp = allocVector(RTYPE, nRow)); \
		CTYPE* tmp_ptr = ACCESSOR(tmp); \
		CTYPE* data_ptr = ACCESSOR(VECTOR_ELT(data, value_ind)); \
		for (int j=0; j < nRow; ++j) { \
			tmp_ptr[j] = data_ptr[j + (i*nRow)]; \
		} \
		SET_VECTOR_ELT(output, i + n_other, tmp); \
		UNPROTECT(1); \
		break; \
		} \

	// copy the value
	int valuetype = TYPEOF(VECTOR_ELT(data, value_ind));
	for (int i=0; i < n_uniq; ++i) {
		switch (valuetype) {
		case LGLSXP: COPY(LGLSXP, int, LOGICAL);
		case INTSXP: COPY(INTSXP, int, INTEGER);
		case REALSXP: COPY(REALSXP, double, REAL);
		case STRSXP: COPY(STRSXP, SEXP, STRING_PTR);
		}
	}

	// set the names
	SEXP datanames = getAttrib(data, R_NamesSymbol);
	SEXP names;
	GUARD(names = allocVector(STRSXP, n_other + n_uniq));
	for (int i=0; i < n_other; ++i) {
		SET_STRING_ELT(names, i, STRING_ELT(datanames, i));
	}
	for (int i=0; i < n_uniq; ++i) {
		SET_STRING_ELT(names, n_other+i, STRING_ELT(uniq_id, i));
	}
	setAttrib(output, R_NamesSymbol, names);

	// set the class
	setAttrib(output, R_ClassSymbol, mkString("data.frame"));

	// set the rows
	SEXP rownames;
	GUARD( rownames=allocVector(INTSXP, nRow) );
	int* rownames_ptr = INTEGER(rownames);
	for (int i=0; i < nRow; ++i) {
		rownames_ptr[i] = i+1;
	}
	setAttrib(output, R_RowNamesSymbol, rownames);
	UNGUARD;
	return output;
}
Ejemplo n.º 22
0
int s2n_connection_wipe(struct s2n_connection *conn)
{
    /* First make a copy of everything we'd like to save, which isn't very
     * much.
     */
    int mode = conn->mode;
    struct s2n_config *config = conn->config;
    struct s2n_stuffer alert_in;
    struct s2n_stuffer reader_alert_out;
    struct s2n_stuffer writer_alert_out;
    struct s2n_stuffer handshake_io;
    struct s2n_stuffer header_in;
    struct s2n_stuffer in;
    struct s2n_stuffer out;

    /* Wipe all of the sensitive stuff */
    GUARD(s2n_connection_free_keys(conn));
    GUARD(s2n_stuffer_wipe(&conn->alert_in));
    GUARD(s2n_stuffer_wipe(&conn->reader_alert_out));
    GUARD(s2n_stuffer_wipe(&conn->writer_alert_out));
    GUARD(s2n_stuffer_wipe(&conn->handshake.io));
    GUARD(s2n_stuffer_wipe(&conn->header_in));
    GUARD(s2n_stuffer_wipe(&conn->in));
    GUARD(s2n_stuffer_wipe(&conn->out));

    /* Allocate or resize to their original sizes */
    GUARD(s2n_stuffer_resize(&conn->in, S2N_LARGE_FRAGMENT_LENGTH));

    /* Allocate memory for handling handshakes */
    GUARD(s2n_stuffer_resize(&conn->handshake.io, S2N_LARGE_RECORD_LENGTH));

    /* Clone the stuffers */
    /* ignore gcc 4.7 address warnings because dest is allocated on the stack */
    /* pragma gcc diagnostic was added in gcc 4.6 */
#if defined(__GNUC__) && GCC_VERSION >= 40600
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Waddress"
#endif
    memcpy_check(&alert_in, &conn->alert_in, sizeof(struct s2n_stuffer));
    memcpy_check(&reader_alert_out, &conn->reader_alert_out, sizeof(struct s2n_stuffer));
    memcpy_check(&writer_alert_out, &conn->writer_alert_out, sizeof(struct s2n_stuffer));
    memcpy_check(&handshake_io, &conn->handshake.io, sizeof(struct s2n_stuffer));
    memcpy_check(&header_in, &conn->header_in, sizeof(struct s2n_stuffer));
    memcpy_check(&in, &conn->in, sizeof(struct s2n_stuffer));
    memcpy_check(&out, &conn->out, sizeof(struct s2n_stuffer));
#if defined(__GNUC__) && GCC_VERSION >= 40600
#pragma GCC diagnostic pop
#endif

    /* Zero the whole connection structure */
    memset_check(conn, 0, sizeof(struct s2n_connection));

    conn->readfd = -1;
    conn->writefd = -1;
    conn->mode = mode;
    conn->config = config;
    conn->active.cipher_suite = &s2n_null_cipher_suite;
    conn->pending.cipher_suite = &s2n_null_cipher_suite;
    conn->server = &conn->active;
    conn->client = &conn->active;
    conn->max_fragment_length = S2N_SMALL_FRAGMENT_LENGTH;
    conn->handshake.state = CLIENT_HELLO;
    GUARD(s2n_hash_init(&conn->handshake.client_md5, S2N_HASH_MD5));
    GUARD(s2n_hash_init(&conn->handshake.client_sha1, S2N_HASH_SHA1));
    GUARD(s2n_hash_init(&conn->handshake.client_sha256, S2N_HASH_SHA256));
    GUARD(s2n_hash_init(&conn->handshake.server_md5, S2N_HASH_MD5));
    GUARD(s2n_hash_init(&conn->handshake.server_sha1, S2N_HASH_SHA1));
    GUARD(s2n_hash_init(&conn->handshake.server_sha256, S2N_HASH_SHA256));
    GUARD(s2n_hmac_init(&conn->client->client_record_mac, S2N_HMAC_NONE, NULL, 0));
    GUARD(s2n_hmac_init(&conn->server->server_record_mac, S2N_HMAC_NONE, NULL, 0));

    memcpy_check(&conn->alert_in, &alert_in, sizeof(struct s2n_stuffer));
    memcpy_check(&conn->reader_alert_out, &reader_alert_out, sizeof(struct s2n_stuffer));
    memcpy_check(&conn->writer_alert_out, &writer_alert_out, sizeof(struct s2n_stuffer));
    memcpy_check(&conn->handshake.io, &handshake_io, sizeof(struct s2n_stuffer));
    memcpy_check(&conn->header_in, &header_in, sizeof(struct s2n_stuffer));
    memcpy_check(&conn->in, &in, sizeof(struct s2n_stuffer));
    memcpy_check(&conn->out, &out, sizeof(struct s2n_stuffer));

    /* Set everything to the highest version at first */
    conn->server_protocol_version = s2n_highest_protocol_version;
    conn->client_protocol_version = s2n_highest_protocol_version;
    conn->actual_protocol_version = s2n_highest_protocol_version;

    return 0;
}
Ejemplo n.º 23
0
	/*
	====================
	build
	====================
	*/
	VOID Capsule::build()
	{
		GUARD(Capsule::build);

		// clear the old keys
		mKeys.clear();

		#define CAPSULE_SEGMENTS	20
		#define CAPSULE_ROWS		10

		std::vector<DVTN>vertexes;
		std::vector<U32>indexes;

		// create the capsule cylindrical body
		{
			const F32 angle_delta = 2.0f*PI/(F32)CAPSULE_SEGMENTS;
			const F32 texcoord_delta = 1.0f/(F32)CAPSULE_SEGMENTS;

			const F32 r = mRadius;
			const F32 h = mHeight;

			F32 base_z = -h*0.5f;
			F32 top_z = h*0.5f;

			F32 angle = 0.0f;
			F32 texcoord = 0.0f;

			for(U32 bodyi=0; bodyi<CAPSULE_SEGMENTS; ++bodyi,angle+=angle_delta,texcoord+=texcoord_delta)
			{
				F32 c = GMath::cos(angle);
				F32 s = GMath::sin(angle);

				DVTN v;
				v.normal[0]		= c;
				v.normal[1]		= s;
				v.normal[2]		= 0.0f;
				v.texcoord[0]	= texcoord;
				v.texcoord[1]	= 1.0f;
				v.point[0]		= c*r;
				v.point[1]		= s*r;
				v.point[2]		= top_z;
				vertexes.push_back(v);

				v.normal[0]		= c;
				v.normal[1]		= s;
				v.normal[2]		= 0.0f;
				v.texcoord[0]	= texcoord;
				v.texcoord[1]	= 0.0f;
				v.point[0]		= c*r;
				v.point[1]		= s*r;
				v.point[2]		= base_z;
				vertexes.push_back(v);
			}

			// do last point by hand to ensure no round off errors.
			DVTN v;
			v.normal[0]		= 1.0f;
			v.normal[1]		= 0.0f;
			v.normal[2]		= 0.0f;
			v.texcoord[0]	= 1.0f;
			v.texcoord[1]	= 1.0f;
			v.point[0]		= r;
			v.point[1]		= 0.0f;
			v.point[2]		= top_z;
			vertexes.push_back(v);

			v.normal[0]		= 1.0f;
			v.normal[1]		= 0.0f;
			v.normal[2]		= 0.0f;
			v.texcoord[0]	= 1.0f;
			v.texcoord[1]	= 0.0f;
			v.point[0]		= r;
			v.point[1]		= 0.0f;
			v.point[2]		= base_z;
			vertexes.push_back(v);

			// QUAD_STRIP
			U32 first = 0;
			U32 count = vertexes.size();
			for(U32 i=3, pos=first;i<count;i+=2,pos+=2)
			{
				indexes.push_back(pos);
				indexes.push_back(pos+1);
				indexes.push_back(pos+2);
				indexes.push_back(pos+1);
				indexes.push_back(pos+3);
				indexes.push_back(pos+2);
			}
		}

		// create the capsule top cap
		{
			U32 count = vertexes.size();

			F32 radius = mRadius;
			F32 z_offset = mHeight/2.0f;

			F32 l_delta = PI/(F32)CAPSULE_ROWS;
			F32 v_delta = 1.0f/(F32)CAPSULE_ROWS;			

			F32 angle_delta = PI*2.0f/(F32)CAPSULE_SEGMENTS;
			F32 texcoord_horz_delta = 1.0f/(F32)CAPSULE_SEGMENTS;

			F32 l_base=-PI*0.5f + (l_delta*(CAPSULE_ROWS/2));
			F32 r_base=(GMath::cos(l_base)*radius);
			F32 z_base=(GMath::sin(l_base)*radius);
			F32 v_base=(v_delta*(CAPSULE_ROWS/2));
			F32 n_z_base=(GMath::sin(l_base));
			F32 n_ratio_base=(GMath::cos(l_base));

			U32 row_begin = CAPSULE_ROWS/2;
			U32 row_end   = CAPSULE_ROWS;			

			for(U32 rowi=row_begin; rowi<row_end; ++rowi)
			{
				F32 l_top = l_base+l_delta;
				F32 r_top = GMath::cos(l_top)*radius;
				F32 z_top = GMath::sin(l_top)*radius;
				F32 v_top = v_base+v_delta;
				F32 n_z_top= GMath::sin(l_top);
				F32 n_ratio_top= GMath::cos(l_top);

				F32 angle = 0.0f;
				F32 texcoord = 0.0f;

				// The only difference between the font & back face loops is that the
				//  normals are inverted and the order of the vertex pairs is reversed.
				//  The code is mostly duplicated in order to hoist the back/front face 
				//  test out of the loop for efficiency
				for(U32 topi=0; topi<CAPSULE_SEGMENTS;++topi,angle+=angle_delta,texcoord+=texcoord_horz_delta)
				{
					F32 c = GMath::cos(angle);
					F32 s = GMath::sin(angle);

					DVTN v;
					v.normal[0]		= c*n_ratio_top;
					v.normal[1]		= s*n_ratio_top;
					v.normal[2]		= n_z_top;
					v.texcoord[0]	= texcoord;
					v.texcoord[1]	= v_top;
					v.point[0]		= c*r_top;
					v.point[1]		= s*r_top;
					v.point[2]		= z_top+z_offset;
					vertexes.push_back(v);

					v.normal[0]		= c*n_ratio_base;
					v.normal[1]		= s*n_ratio_base;
					v.normal[2]		= n_z_base;
					v.texcoord[0]	= texcoord;
					v.texcoord[1]	= v_base;
					v.point[0]		= c*r_base;
					v.point[1]		= s*r_base;
					v.point[2]		= z_base+z_offset;
					vertexes.push_back(v);
				}

				// do last point by hand to ensure no round off errors.
				DVTN v;
				v.normal[0]		= n_ratio_top;
				v.normal[1]		= 0.0f;
				v.normal[2]		= n_z_top;
				v.texcoord[0]	= 1.0f;
				v.texcoord[1]	= v_top;
				v.point[0]		= r_top;
				v.point[1]		= 0.0f;
				v.point[2]		= z_top+z_offset;
				vertexes.push_back(v);

				v.normal[0]		= n_ratio_base;
				v.normal[1]		= 0.0f;
				v.normal[2]		= n_z_base;
				v.texcoord[0]	= 1.0f;
				v.texcoord[1]	= v_base;
				v.point[0]		= r_base;
				v.point[1]		= 0.0f;
				v.point[2]		= z_base+z_offset;
				vertexes.push_back(v);

				l_base=l_top;
				r_base=r_top;
				z_base=z_top;
				v_base=v_top;
				n_z_base=n_z_top;
				n_ratio_base=n_ratio_top;
			}

			// QUAD_STRIP
			U32 first = count;
			count = vertexes.size() - count;
			for(U32 i=3, pos=first;i<count;i+=2,pos+=2)
			{
				indexes.push_back(pos);
				indexes.push_back(pos+1);
				indexes.push_back(pos+2);
				indexes.push_back(pos+1);
				indexes.push_back(pos+3);
				indexes.push_back(pos+2);
			}
		}

		// create the capsule bottom cap
		{
			U32 count = vertexes.size();

			F32 radius = mRadius;
			F32 z_offset = -mHeight/2.0f;

			F32 l_delta = PI/(F32)CAPSULE_ROWS;
			F32 v_delta = 1.0f/(F32)CAPSULE_ROWS;			

			F32 angle_delta = PI*2.0f/(F32)CAPSULE_SEGMENTS;
			F32 texcoord_horz_delta = 1.0f/(F32)CAPSULE_SEGMENTS;

			F32 l_base=-PI*0.5f;
			F32 r_base=0.0f;
			F32 z_base=-radius;
			F32 v_base=0.0f;
			F32 n_z_base=-1.0f;
			F32 n_ratio_base=0.0f;

			U32 row_begin = 0;
			U32 row_end   = CAPSULE_ROWS/2;			

			for(U32 rowi=row_begin; rowi<row_end; ++rowi)
			{
				F32 l_top = l_base+l_delta;
				F32 r_top = GMath::cos(l_top)*radius;
				F32 z_top = GMath::sin(l_top)*radius;
				F32 v_top = v_base+v_delta;
				F32 n_z_top= GMath::sin(l_top);
				F32 n_ratio_top= GMath::cos(l_top);

				F32 angle = 0.0f;
				F32 texcoord = 0.0f;

				// The only difference between the font & back face loops is that the
				//  normals are inverted and the order of the vertex pairs is reversed.
				//  The code is mostly duplicated in order to hoist the back/front face 
				//  test out of the loop for efficiency				
				for(U32 topi=0; topi<CAPSULE_SEGMENTS;++topi,angle+=angle_delta,texcoord+=texcoord_horz_delta)
				{
					F32 c = GMath::cos(angle);
					F32 s = GMath::sin(angle);

					DVTN v;
					v.normal[0]		= c*n_ratio_top;
					v.normal[1]		= s*n_ratio_top;
					v.normal[2]		= n_z_top;
					v.texcoord[0]	= texcoord;
					v.texcoord[1]	= v_top;
					v.point[0]		= c*r_top;
					v.point[1]		= s*r_top;
					v.point[2]		= z_top+z_offset;
					vertexes.push_back(v);

					v.normal[0]		= c*n_ratio_base;
					v.normal[1]		= s*n_ratio_base;
					v.normal[2]		= n_z_base;
					v.texcoord[0]	= texcoord;
					v.texcoord[1]	= v_base;
					v.point[0]		= c*r_base;
					v.point[1]		= s*r_base;
					v.point[2]		= z_base+z_offset;
					vertexes.push_back(v);
				}

				// do last point by hand to ensure no round off errors.
				DVTN v;
				v.normal[0]		= n_ratio_top;
				v.normal[1]		= 0.0f;
				v.normal[2]		= n_z_top;
				v.texcoord[0]	= 1.0f;
				v.texcoord[1]	= v_top;
				v.point[0]		= r_top;
				v.point[1]		= 0.0f;
				v.point[2]		= z_top+z_offset;
				vertexes.push_back(v);

				v.normal[0]		= n_ratio_base;
				v.normal[1]		= 0.0f;
				v.normal[2]		= n_z_base;
				v.texcoord[0]	= 1.0f;
				v.texcoord[1]	= v_base;
				v.point[0]		= r_base;
				v.point[1]		= 0.0f;
				v.point[2]		= z_base+z_offset;
				vertexes.push_back(v);

				l_base=l_top;
				r_base=r_top;
				z_base=z_top;
				v_base=v_top;
				n_z_base=n_z_top;
				n_ratio_base=n_ratio_top;
			}

			// QUAD_STRIP
			U32 first = count;
			count = vertexes.size() - count;
			for(U32 i=3, pos=first;i<count;i+=2,pos+=2)
			{
				indexes.push_back(pos);
				indexes.push_back(pos+1);
				indexes.push_back(pos+2);
				indexes.push_back(pos+1);
				indexes.push_back(pos+3);
				indexes.push_back(pos+2);
			}
		}

		// build the primitive
		mPrimitivePtr = GNEW(Primitive); CHECK(mPrimitivePtr);
		mPrimitivePtr->SetType(mType);

		// set the wvp
		Constant* wvp_constant_ptr = GNEW(Constant); CHECK(wvp_constant_ptr);
		wvp_constant_ptr->SetMatrix(Matrix());
		mPrimitivePtr->SetConstant("gWVP",wvp_constant_ptr);

		// set the color
		Constant* color_constant_ptr = GNEW(Constant); CHECK(color_constant_ptr);
		color_constant_ptr->SetVector(Vector4(0,0,0,0));
		mPrimitivePtr->SetConstant("gColor",color_constant_ptr);

		// set the shader
		Str key_name = "shader/color.xml";
		KeyPtr key_ptr = Key::Find(key_name.c_str());
		if(key_ptr == NULL)
		{
			Shader*shader = GNEW(Shader); CHECK(shader);
			shader->Load(GLoad(key_name.c_str()));
			key_ptr = GNEW(Key(key_name.c_str(), shader)); CHECK(key_ptr);
		}
		mKeys.push_back(key_ptr);
		mPrimitivePtr->SetShader(dynamic_cast<Shader*>(key_ptr->Ptr()), "p0");

		// build the vertex buffer
		VertexBufferPtr vb_ptr = GNEW(VertexBuffer); CHECK(vb_ptr);
		{
			GDataPtr vd_ptr = GNEW(GData); CHECK(vd_ptr);
			vd_ptr->Size(3*sizeof(U32) + 4*sizeof(U8) + vertexes.size()*sizeof(DVTN));
			U8*data_ptr = (U8*)vd_ptr->Ptr();
			*(U32*)data_ptr = MAKEFOURCC('G','V','B','O');
			data_ptr += sizeof(U32);
			*(U32*)data_ptr = vertexes.size();
			data_ptr += sizeof(U32);
			*(U32*)data_ptr = sizeof(DVTN); 
			data_ptr += sizeof(U32);
			*(U8*)data_ptr = 3;
			data_ptr += sizeof(U8);
			*(U8*)data_ptr = VertexBuffer::VT_3F;
			data_ptr += sizeof(U8);
			*(U8*)data_ptr = VertexBuffer::VT_2F;
			data_ptr += sizeof(U8);
			*(U8*)data_ptr = VertexBuffer::VT_3F;
			data_ptr += sizeof(U8);
			::memcpy(data_ptr, &vertexes[0], vertexes.size()*sizeof(DVTN));
			data_ptr += vertexes.size()*sizeof(DVTN);
			vb_ptr->Load(vd_ptr.Ptr());
		}
		mPrimitivePtr->SetVertexBuffer(vb_ptr.Ptr());

		// build the index
		IndexBufferPtr ib_ptr = GNEW(IndexBuffer); CHECK(ib_ptr);
		{
			GDataPtr id_ptr = GNEW(GData); CHECK(id_ptr);
			id_ptr->Size(3*sizeof(U32) + indexes.size()*sizeof(U32));
			U8*data_ptr = (U8*)id_ptr->Ptr();
			*(U32*)data_ptr = MAKEFOURCC('G','I','B','O');
			data_ptr += sizeof(U32);
			*(U32*)data_ptr = indexes.size(); 
			data_ptr += sizeof(U32);
			*(U32*)data_ptr = sizeof(U32); 
			data_ptr += sizeof(U32);
			::memcpy(data_ptr, &indexes[0], indexes.size()*sizeof(U32));
			data_ptr += indexes.size()*sizeof(U32);
			ib_ptr->Load(id_ptr.Ptr());
		}
		mPrimitivePtr->SetIndexBuffer(ib_ptr.Ptr());	

		// build the bounding box
		mBox.set(MAX_F32,MAX_F32,MAX_F32,MIN_F32,MIN_F32,MIN_F32);
		for(U32 i = 0; i < vertexes.size(); i++)mBox.expand(vertexes[i].point);
		mPrimitivePtr->SetBox(mBox);

		UNGUARD;
	}
Ejemplo n.º 24
0
int64_t s2n_public_random(int64_t max)
{
    uint64_t r;

    gt_check(max, 0);

    while(1) {
        struct s2n_blob blob = { .data = (void *) &r, sizeof(r) };
        GUARD(s2n_get_public_random_data(&blob));

        /* Imagine an int was one byte and UINT_MAX was 256. If the
         * caller asked for s2n_random(129, ...) we'd end up in
         * trouble. Each number in the range 0...127 would be twice
         * as likely as 128. That's because r == 0 % 129 -> 0, and
         * r == 129 % 129 -> 0, but only r == 128 returns 128,
         * r == 257 is out of range.
         *
         * To de-bias the dice, we discard values of r that are higher
         * that the highest multiple of 'max' an int can support. If
         * max is a uint, then in the worst case we discard 50% - 1 r's.
         * But since 'max' is an int and INT_MAX is <= UINT_MAX / 2,
         * in the worst case we discard 25% - 1 r's.
         */
        if (r < (UINT64_MAX - (UINT64_MAX % max))) {
            return r % max;
        }
    }

    return -1;
}

#if !defined(OPENSSL_IS_BORINGSSL) && !defined(OPENSSL_FIPS) && !defined(LIBRESSL_VERSION_NUMBER)

int s2n_openssl_compat_rand(unsigned char *buf, int num)
{
    struct s2n_blob out = {.data = buf, .size = num};

    if(s2n_get_private_random_data(&out) < 0) {
        return 0;
    }
    return 1;
}

int s2n_openssl_compat_status(void)
{
    return 1;
}

int s2n_openssl_compat_init(ENGINE *unused)
{
    return 1;
}

RAND_METHOD s2n_openssl_rand_method = {
    .seed = NULL,
    .bytes = s2n_openssl_compat_rand,
    .cleanup = NULL,
    .add = NULL,
    .pseudorand = s2n_openssl_compat_rand,
    .status = s2n_openssl_compat_status
};
#endif

int s2n_init(void)
{
    GUARD(s2n_mem_init());

    OPEN:
    entropy_fd = open(ENTROPY_SOURCE, O_RDONLY);
    if (entropy_fd == -1) {
        if (errno == EINTR) {
            goto OPEN;
        }
        S2N_ERROR(S2N_ERR_OPEN_RANDOM);
    }

#if defined(MAP_INHERIT_ZERO)
    zero_if_forked_ptr = mmap(NULL, sizeof(int), PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
    if (zero_if_forked_ptr == MAP_FAILED) {
        S2N_ERROR(S2N_ERR_OPEN_RANDOM);
    }

    if (minherit(zero_if_forked_ptr, sizeof(int), MAP_INHERIT_ZERO) == -1) {
        S2N_ERROR(S2N_ERR_OPEN_RANDOM);
    }
#else

    if (pthread_atfork(NULL, NULL, s2n_on_fork) != 0) {
        S2N_ERROR(S2N_ERR_OPEN_RANDOM);
    }
#endif

    GUARD(s2n_defend_if_forked());

#if !defined(OPENSSL_IS_BORINGSSL) && !defined(OPENSSL_FIPS) && !defined(LIBRESSL_VERSION_NUMBER)
    /* Create an engine */
    ENGINE *e = ENGINE_new();
    if (e == NULL ||
        ENGINE_set_id(e, "s2n") != 1 ||
        ENGINE_set_name(e, "s2n entropy generator") != 1 ||
        ENGINE_set_flags(e, ENGINE_FLAGS_NO_REGISTER_ALL) != 1 ||
        ENGINE_set_init_function(e, s2n_openssl_compat_init) != 1 ||
        ENGINE_set_RAND(e, &s2n_openssl_rand_method) != 1 ||
        ENGINE_add(e) != 1 ||
        ENGINE_free(e) != 1) {
        S2N_ERROR(S2N_ERR_OPEN_RANDOM);
    }

    /* Use that engine for rand() */
    e = ENGINE_by_id("s2n");
    if (e == NULL ||
        ENGINE_init(e) != 1 ||
        ENGINE_set_default(e, ENGINE_METHOD_RAND) != 1) {
        S2N_ERROR(S2N_ERR_OPEN_RANDOM);
    }

#endif

    return 0;
}
Ejemplo n.º 25
0
/*
====================
build
====================
*/
VOID Game::build()
{
    GUARD(Game::build);

    // build the color texture
    Image* image = GNEW(Image);
    CHECK(image);
    image->Width(256);
    image->Height(256);
    image->Depth(1);
    image->PixelFormat(PF_RGBA);
    image->DataType(DT_UNSIGNED_BYTE);
    mColorTexPtr = GNEW(Texture);
    CHECK(mColorTexPtr);
    mColorTexPtr->Load(image);

    // build the color rt
    mColorRTPtr = GNEW(Target(mColorTexPtr.Ptr()));
    CHECK(mColorRTPtr);

    // build the primitive
    mQuadPtr = GNEW(Primitive);
    CHECK(mQuadPtr);
    mQuadPtr->SetType(Primitive::PT_TRIANGLES);

    // set the wvp
    Constant* wvp_constant_ptr = GNEW(Constant);
    CHECK(wvp_constant_ptr);
    wvp_constant_ptr->SetMatrix(Matrix());
    mQuadPtr->SetConstant("gWVP",wvp_constant_ptr);

    // set the color texture
    Constant* texture_constant_ptr = GNEW(Constant);
    CHECK(texture_constant_ptr);
    texture_constant_ptr->SetTexture(mColorTexPtr.Ptr());
    mQuadPtr->SetConstant("gBaseTex",texture_constant_ptr);

    // set the shader
    Str shader_key_name = "shader/default.xml";
    KeyPtr shader_key_ptr = Key::Find(shader_key_name.c_str());
    if(shader_key_ptr == NULL)
    {
        Shader*shader = GNEW(Shader);
        CHECK(shader);
        shader->Load(GLoad(shader_key_name.c_str()));
        shader_key_ptr = GNEW(Key(shader_key_name.c_str(), shader));
        CHECK(shader_key_ptr);
    }
    mKeys.push_back(shader_key_ptr);
    mQuadPtr->SetShader(dynamic_cast<Shader*>(shader_key_ptr->Ptr()),"p0");

    // build the vertex buffer
    F32 x = 0.0f, y = 0.0f, w = 256, h = 256;
    DVT vertexes[] =
    {
        {x,		y,		0,		0,		0},
        {x+w,	y,		0,		1,		0},
        {x+w,	y+h,	0,		1,		1},
        {x,		y+h,	0,		0,		1},
    };
    VertexBufferPtr vb_ptr = GNEW(VertexBuffer);
    CHECK(vb_ptr);
    {
        GDataPtr vd_ptr = GNEW(GData);
        CHECK(vd_ptr);
        vd_ptr->Size(3*sizeof(U32) + 3*sizeof(U8) + sizeof(vertexes));
        U8*data_ptr = (U8*)vd_ptr->Ptr();
        *(U32*)data_ptr = MAKEFOURCC('G','V','B','O');
        data_ptr += sizeof(U32);
        *(U32*)data_ptr = sizeof(vertexes)/sizeof(DVT);
        data_ptr += sizeof(U32);
        *(U32*)data_ptr = sizeof(DVT);
        data_ptr += sizeof(U32);
        *(U8*)data_ptr = 2;
        data_ptr += sizeof(U8);
        *(U8*)data_ptr = VertexBuffer::VT_3F;
        data_ptr += sizeof(U8);
        *(U8*)data_ptr = VertexBuffer::VT_2F;
        data_ptr += sizeof(U8);
        ::memcpy(data_ptr, vertexes, sizeof(vertexes));
        data_ptr += sizeof(vertexes);
        vb_ptr->Load(vd_ptr.Ptr());
    }
    mQuadPtr->SetVertexBuffer(vb_ptr.Ptr());

    // build the index
    const U16 indexes[] = { 3, 0, 2, 2, 0, 1 };
    IndexBufferPtr ib_ptr = GNEW(IndexBuffer);
    CHECK(ib_ptr);
    {
        GDataPtr id_ptr = GNEW(GData);
        CHECK(id_ptr);
        id_ptr->Size(3*sizeof(U32) + sizeof(indexes));
        U8*data_ptr = (U8*)id_ptr->Ptr();
        *(U32*)data_ptr = MAKEFOURCC('G','I','B','O');
        data_ptr += sizeof(U32);
        *(U32*)data_ptr = sizeof(indexes)/sizeof(U16);
        data_ptr += sizeof(U32);
        *(U32*)data_ptr = sizeof(U16);
        data_ptr += sizeof(U32);
        ::memcpy(data_ptr, &indexes[0], sizeof(indexes));
        data_ptr += sizeof(indexes);
        ib_ptr->Load(id_ptr.Ptr());
    }
    mQuadPtr->SetIndexBuffer(ib_ptr.Ptr());

    // build the bounding box
    BoundingBox box;
    box.set(MAX_F32,MAX_F32,MAX_F32,MIN_F32,MIN_F32,MIN_F32);
    for(U32 i = 0; i < sizeof(vertexes)/sizeof(DVTN); i++)box.expand(vertexes[i].point);
    mQuadPtr->SetBox(box);

    UNGUARD;
}
Ejemplo n.º 26
0
int s2n_server_extensions_send(struct s2n_connection *conn, struct s2n_stuffer *out)
{
    uint16_t total_size = 0;

    uint8_t application_protocol_len = strlen(conn->application_protocol);

    if (application_protocol_len) {
        total_size += 7 + application_protocol_len;
    }
    if (s2n_server_can_send_ocsp(conn)) {
        total_size += 4;
    }
    if (conn->secure_renegotiation) {
        total_size += 5;
    }
    if (conn->secure.cipher_suite->key_exchange_alg->flags & S2N_KEY_EXCHANGE_ECC) {
        total_size += 6;
    }

    if (total_size == 0) {
        return 0;
    }

    GUARD(s2n_stuffer_write_uint16(out, total_size));

    /* Write the Supported Points Format extention.
     * RFC 4492 section 5.2 states that the absence of this extension in the Server Hello
     * is equivalent to allowing only the uncompressed point format. Let's send the
     * extension in case clients(Openssl 1.0.0) don't honor the implied behavior.
     */
    if (conn->secure.cipher_suite->key_exchange_alg->flags & S2N_KEY_EXCHANGE_ECC)  {
        GUARD(s2n_stuffer_write_uint16(out, TLS_EXTENSION_EC_POINT_FORMATS));
        /* Total extension length */
        GUARD(s2n_stuffer_write_uint16(out, 2));
        /* Format list length */
        GUARD(s2n_stuffer_write_uint8(out, 1));
        /* Only uncompressed format is supported. Interoperability shouldn't be an issue:
         * RFC 4492 Section 5.1.2: Implementations must support it for all of their curves.
         */
        GUARD(s2n_stuffer_write_uint8(out, TLS_EC_FORMAT_UNCOMPRESSED));
    }

    /* Write the renegotiation_info extension */
    if (conn->secure_renegotiation) {
        GUARD(s2n_stuffer_write_uint16(out, TLS_EXTENSION_RENEGOTIATION_INFO));
        /* renegotiation_info length */
        GUARD(s2n_stuffer_write_uint16(out, 1));
        /* renegotiated_connection length. Zero since we don't support renegotiation. */
        GUARD(s2n_stuffer_write_uint8(out, 0));
    }

    /* Write ALPN extension */
    if (application_protocol_len) {
        GUARD(s2n_stuffer_write_uint16(out, TLS_EXTENSION_ALPN));
        GUARD(s2n_stuffer_write_uint16(out, application_protocol_len + 3));
        GUARD(s2n_stuffer_write_uint16(out, application_protocol_len + 1));
        GUARD(s2n_stuffer_write_uint8(out, application_protocol_len));
        GUARD(s2n_stuffer_write_bytes(out, (uint8_t *) conn->application_protocol, application_protocol_len));
    }

    /* Write OCSP extension */
    if (s2n_server_can_send_ocsp(conn)) {
        GUARD(s2n_stuffer_write_uint16(out, TLS_EXTENSION_STATUS_REQUEST));
        GUARD(s2n_stuffer_write_uint16(out, 0));
    }

    return 0;
}
Ejemplo n.º 27
0
/*
====================
Load
====================
*/
VOID EChunk::Load(const VOID* data)
{
	GUARD(EChunk::Load);

	// build the vertex buffer
	mVBPtr = GNEW(VertexBuffer); CHECK(mVBPtr);
	{
		DVT vertexes[] = 
		{
			{0.0,			0.0,			0.0,	0.0,	1.0},
			{CHUNK_STRIDE,	0.0,			0.0,	1.0,	1.0},
			{CHUNK_STRIDE,	CHUNK_STRIDE,	0.0,	1.0,	0.0},
			{0.0,			CHUNK_STRIDE,	0.0,	0.0,	0.0},
		};

		GDataPtr vd_ptr = GNEW(GData); CHECK(vd_ptr);
		vd_ptr->Size(3*sizeof(U32) + 3*sizeof(U8) + sizeof(vertexes));
		U8*data_ptr = (U8*)vd_ptr->Ptr();
		*(U32*)data_ptr = MAKEFOURCC('G','V','B','O');
		data_ptr += sizeof(U32);
		*(U32*)data_ptr = sizeof(vertexes)/sizeof(DVT); 
		data_ptr += sizeof(U32);
		*(U32*)data_ptr = sizeof(DVT); 
		data_ptr += sizeof(U32);
		*(U8*)data_ptr = 2;
		data_ptr += sizeof(U8);
		*(U8*)data_ptr = VertexBuffer::VT_3F;
		data_ptr += sizeof(U8);
		*(U8*)data_ptr = VertexBuffer::VT_2F;
		data_ptr += sizeof(U8);
		::memcpy(data_ptr, vertexes, sizeof(vertexes));
		data_ptr += sizeof(vertexes);
		mVBPtr->Load(vd_ptr.Ptr());
	}		

	// build the index
	mIBPtr = GNEW(IndexBuffer); CHECK(mIBPtr);
	{
		const U16 indexes[] = { 3, 0, 2, 2, 0, 1 };
		GDataPtr id_ptr = GNEW(GData); CHECK(id_ptr);
		id_ptr->Size(3*sizeof(U32) + sizeof(indexes));
		U8*data_ptr = (U8*)id_ptr->Ptr();
		*(U32*)data_ptr = MAKEFOURCC('G','I','B','O');
		data_ptr += sizeof(U32);
		*(U32*)data_ptr = sizeof(indexes)/sizeof(U16); 
		data_ptr += sizeof(U32);
		*(U32*)data_ptr = sizeof(U16); 
		data_ptr += sizeof(U32);
		::memcpy(data_ptr, indexes, sizeof(indexes));
		data_ptr += sizeof(indexes);
		mIBPtr->Load(id_ptr.Ptr());
	}

	// build the shaders
	Str shader_name = "shader/chunk.xml";
	mShaderKey = Key::Find(shader_name.c_str());
	if(mShaderKey == NULL)
	{
		Shader*shader = GNEW(Shader); CHECK(shader);
		shader->Load(GLoad(shader_name.c_str()));
		mShaderKey = GNEW(Key(shader_name.c_str(), shader)); CHECK(mShaderKey);
	}

	// load the data
	U8*data_ptr = (U8*)data;

	// check the chunk header		
	CHECK(*(U32*)data_ptr == (MAKEFOURCC('G','C','H','K')));
	data_ptr += sizeof(U32);

	// get the layer
	U32 num_layer = *(U32*)data_ptr;
	data_ptr += sizeof(U32);
	for(U32 k = 0; k < num_layer; k++)
	{
		Layer layer;
		layer.total = 0;

		// get the primitive
		layer.primitive = GNEW(Primitive); CHECK(layer.primitive);
		layer.primitive->SetType(Primitive::PT_TRIANGLES);
		layer.primitive->SetVertexBuffer(mVBPtr.Ptr());
		layer.primitive->SetIndexBuffer(mIBPtr.Ptr());	
		layer.primitive->SetConstant("gWVP",GNEW(Constant(Matrix())));

		// get the color texture			
		Str texture_name;
		U32 len = *(U32*)data_ptr;
		data_ptr += sizeof(U32);
		texture_name.resize(len, 0);
		memcpy(&texture_name[0], data_ptr, len*sizeof(CHAR));
		data_ptr += len*sizeof(CHAR);
		KeyPtr texture_key_ptr = Key::Find(texture_name.c_str());
		if(texture_key_ptr == NULL)
		{
			const Image* image = Image::Load(GLoad(texture_name.c_str())); CHECK(image);
			BaseTexture* base_texture = GNEW(Texture); CHECK(base_texture);
			base_texture->Load(image);
			texture_key_ptr = GNEW(Key(texture_name.c_str(), base_texture)); CHECK(texture_key_ptr);
		}
		mKeys.push_back(texture_key_ptr);
		layer.primitive->SetConstant("gColorTex",GNEW(Constant((BaseTexture*)texture_key_ptr->Ptr())));
		layer.name = texture_name;

		// get the scale st
		F32 s = *(F32*)data_ptr;
		data_ptr += sizeof(F32);
		F32 t = *(F32*)data_ptr;
		data_ptr += sizeof(F32);
		layer.primitive->SetConstant("gScaleST",GNEW(Constant(Vector4(s,t,0,0))));
		layer.st.set(s, t);

		// get the alpha
		U32 width = *(U32*)data_ptr;
		data_ptr += sizeof(U32);
		U32 height = *(U32*)data_ptr;
		data_ptr += sizeof(U32);
		if(width==U2P(ALPHA_STRIDE) && height==U2P(ALPHA_STRIDE))
		{
			layer.alpha.resize(width*height*sizeof(U8));
			::memcpy(&layer.alpha[0], data_ptr, width*height*sizeof(U8));
			data_ptr += width*height*sizeof(U8);
		}
		else
		{
			U8 alpha = *(U8*)data_ptr;
			data_ptr += sizeof(U8);
			width = U2P(ALPHA_STRIDE);
			height = U2P(ALPHA_STRIDE);
			layer.alpha.resize(width*height*sizeof(U8),alpha);
		}
		if(k==0)
		{
			mMask.resize(width*height);
			for(U32 j = 0; j < height; j++)
			{
				for( U32 i = 0; i < width; i++)
				{
					U8& alpha = layer.alpha[i+j*width];
					U8& mask = mMask[i+j*width];
					if(alpha <= 127) 
					{
						alpha = (U8)((F32)alpha/127.0f*255.0f);
						mask = 0;
					}
					else 
					{
						alpha = (U8)((F32)(alpha-128)/127.0f*255.0f);
						mask = 1;
					}
					layer.total += alpha;
				}
			}
		}
		else
		{
			for(U32 j = 0; j < height; j++)
			{
				for( U32 i = 0; i < width; i++)
				{
					layer.total += layer.alpha[i+j*width];
				}
			}
		}
		BaseTexture *alpha_texture = GNEW(Texture); CHECK(alpha_texture);
		layer.primitive->SetConstant("gAlphaTex",GNEW(Constant(alpha_texture)));
		layer.texture = alpha_texture;

		// load the shader
		if(k==0) layer.primitive->SetShader(dynamic_cast<Shader*>(mShaderKey->Ptr()), "base");
		else layer.primitive->SetShader(dynamic_cast<Shader*>(mShaderKey->Ptr()), "layer");

		// add the layer to the table
		mLayers.push_back(layer);
	}

	// update the layer
	Update();

	UNGUARD;
}