repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
robot-dreams/secp256k1-zkp
src/modules/musig/tests_impl.h
/********************************************************************** * Copyright (c) 2018 <NAME> * * Distributed under the MIT software license, see the accompanying * * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ #ifndef _SECP256K1_MODULE_MUSIG_TESTS_ #define _SECP256K1_MODULE_MUSIG_TESTS_ #include "secp256k1_musig.h" int secp256k1_xonly_pubkey_create(secp256k1_xonly_pubkey *pk, const unsigned char *seckey) { int ret; secp256k1_keypair keypair; ret = secp256k1_keypair_create(ctx, &keypair, seckey); ret &= secp256k1_keypair_xonly_pub(ctx, pk, NULL, &keypair); return ret; } /* Just a simple (non-adaptor, non-tweaked) 2-of-2 MuSig combine, sign, verify * test. */ void musig_simple_test(secp256k1_scratch_space *scratch) { unsigned char sk[2][32]; secp256k1_musig_session session[2]; secp256k1_musig_session_signer_data signer0[2]; secp256k1_musig_session_signer_data signer1[2]; unsigned char nonce_commitment[2][32]; unsigned char msg[32]; secp256k1_xonly_pubkey combined_pk; secp256k1_musig_pre_session pre_session; unsigned char session_id[2][32]; secp256k1_xonly_pubkey pk[2]; const secp256k1_xonly_pubkey *pk_ptr[2]; const unsigned char *ncs[2]; unsigned char public_nonce[3][32]; secp256k1_musig_partial_signature partial_sig[2]; unsigned char final_sig[64]; secp256k1_testrand256(session_id[0]); secp256k1_testrand256(session_id[1]); secp256k1_testrand256(sk[0]); secp256k1_testrand256(sk[1]); secp256k1_testrand256(msg); pk_ptr[0] = &pk[0]; pk_ptr[1] = &pk[1]; CHECK(secp256k1_xonly_pubkey_create(&pk[0], sk[0]) == 1); CHECK(secp256k1_xonly_pubkey_create(&pk[1], sk[1]) == 1); CHECK(secp256k1_musig_pubkey_combine(ctx, scratch, &combined_pk, &pre_session, pk_ptr, 2) == 1); CHECK(secp256k1_musig_session_init(ctx, &session[1], signer1, nonce_commitment[1], session_id[1], msg, &combined_pk, &pre_session, 2, sk[1]) == 1); CHECK(secp256k1_musig_session_init(ctx, &session[0], signer0, nonce_commitment[0], session_id[0], msg, &combined_pk, &pre_session, 2, sk[0]) == 1); ncs[0] = nonce_commitment[0]; ncs[1] = nonce_commitment[1]; CHECK(secp256k1_musig_session_get_public_nonce(ctx, &session[0], signer0, public_nonce[0], ncs, 2, NULL) == 1); CHECK(secp256k1_musig_session_get_public_nonce(ctx, &session[1], signer1, public_nonce[1], ncs, 2, NULL) == 1); CHECK(secp256k1_musig_set_nonce(ctx, &signer0[0], public_nonce[0]) == 1); CHECK(secp256k1_musig_set_nonce(ctx, &signer0[1], public_nonce[1]) == 1); CHECK(secp256k1_musig_set_nonce(ctx, &signer1[0], public_nonce[0]) == 1); CHECK(secp256k1_musig_set_nonce(ctx, &signer1[1], public_nonce[1]) == 1); CHECK(secp256k1_musig_session_combine_nonces(ctx, &session[0], signer0, 2, NULL, NULL) == 1); CHECK(secp256k1_musig_session_combine_nonces(ctx, &session[1], signer1, 2, NULL, NULL) == 1); CHECK(secp256k1_musig_partial_sign(ctx, &session[0], &partial_sig[0]) == 1); CHECK(secp256k1_musig_partial_sig_verify(ctx, &session[0], &signer0[0], &partial_sig[0], &pk[0]) == 1); CHECK(secp256k1_musig_partial_sign(ctx, &session[1], &partial_sig[1]) == 1); CHECK(secp256k1_musig_partial_sig_verify(ctx, &session[0], &signer0[1], &partial_sig[1], &pk[1]) == 1); CHECK(secp256k1_musig_partial_sig_verify(ctx, &session[1], &signer1[1], &partial_sig[1], &pk[1]) == 1); CHECK(secp256k1_musig_partial_sig_combine(ctx, &session[0], final_sig, partial_sig, 2) == 1); CHECK(secp256k1_schnorrsig_verify(ctx, final_sig, msg, sizeof(msg), &combined_pk) == 1); } void musig_api_tests(secp256k1_scratch_space *scratch) { secp256k1_scratch_space *scratch_small; secp256k1_musig_session session[2]; secp256k1_musig_session session_uninitialized; secp256k1_musig_session verifier_session; secp256k1_musig_session_signer_data signer0[2]; secp256k1_musig_session_signer_data signer1[2]; secp256k1_musig_session_signer_data verifier_signer_data[2]; secp256k1_musig_partial_signature partial_sig[2]; secp256k1_musig_partial_signature partial_sig_adapted[2]; secp256k1_musig_partial_signature partial_sig_overflow; unsigned char final_sig[64]; unsigned char final_sig_cmp[64]; unsigned char buf[32]; unsigned char sk[2][32]; unsigned char ones[32]; unsigned char session_id[2][32]; unsigned char nonce_commitment[2][32]; int combined_nonce_parity; const unsigned char *ncs[2]; unsigned char msg[32]; secp256k1_xonly_pubkey combined_pk; secp256k1_musig_pre_session pre_session; secp256k1_musig_pre_session pre_session_uninitialized; secp256k1_xonly_pubkey pk[2]; const secp256k1_xonly_pubkey *pk_ptr[2]; secp256k1_xonly_pubkey invalid_pk; const secp256k1_xonly_pubkey *invalid_pk_ptr2[2]; const secp256k1_xonly_pubkey *invalid_pk_ptr3[3]; unsigned char tweak[32]; unsigned char sec_adaptor[32]; unsigned char sec_adaptor1[32]; secp256k1_pubkey adaptor; int i; /** setup **/ secp256k1_context *none = secp256k1_context_create(SECP256K1_CONTEXT_NONE); secp256k1_context *sign = secp256k1_context_create(SECP256K1_CONTEXT_SIGN); secp256k1_context *vrfy = secp256k1_context_create(SECP256K1_CONTEXT_VERIFY); int ecount; secp256k1_context_set_error_callback(none, counting_illegal_callback_fn, &ecount); secp256k1_context_set_error_callback(sign, counting_illegal_callback_fn, &ecount); secp256k1_context_set_error_callback(vrfy, counting_illegal_callback_fn, &ecount); secp256k1_context_set_illegal_callback(none, counting_illegal_callback_fn, &ecount); secp256k1_context_set_illegal_callback(sign, counting_illegal_callback_fn, &ecount); secp256k1_context_set_illegal_callback(vrfy, counting_illegal_callback_fn, &ecount); memset(ones, 0xff, 32); /* Simulate structs being uninitialized by setting it to 0s. We don't want * to produce undefined behavior by actually providing uninitialized * structs. */ memset(&pre_session_uninitialized, 0, sizeof(pre_session_uninitialized)); memset(&session_uninitialized, 0, sizeof(session_uninitialized)); memset(&invalid_pk, 0, sizeof(invalid_pk)); secp256k1_testrand256(session_id[0]); secp256k1_testrand256(session_id[1]); secp256k1_testrand256(sk[0]); secp256k1_testrand256(sk[1]); secp256k1_testrand256(msg); secp256k1_testrand256(sec_adaptor); secp256k1_testrand256(tweak); pk_ptr[0] = &pk[0]; pk_ptr[1] = &pk[1]; CHECK(secp256k1_xonly_pubkey_create(&pk[0], sk[0]) == 1); CHECK(secp256k1_xonly_pubkey_create(&pk[1], sk[1]) == 1); CHECK(secp256k1_ec_pubkey_create(ctx, &adaptor, sec_adaptor) == 1); for (i = 0; i < 2; i++) { invalid_pk_ptr2[i] = &invalid_pk; invalid_pk_ptr3[i] = &pk[i]; } /* invalid_pk_ptr3 has two valid, one invalid pk, which is important to test * musig_pubkeys_combine */ invalid_pk_ptr3[2] = &invalid_pk; /** main test body **/ /* Key combination */ ecount = 0; CHECK(secp256k1_musig_pubkey_combine(none, scratch, &combined_pk, &pre_session, pk_ptr, 2) == 1); CHECK(secp256k1_musig_pubkey_combine(sign, scratch, &combined_pk, &pre_session, pk_ptr, 2) == 1); CHECK(secp256k1_musig_pubkey_combine(vrfy, scratch, &combined_pk, &pre_session, pk_ptr, 2) == 1); /* pubkey_combine does not require a scratch space */ CHECK(secp256k1_musig_pubkey_combine(vrfy, NULL, &combined_pk, &pre_session, pk_ptr, 2) == 1); /* A small scratch space works too, but will result in using an ineffecient algorithm */ scratch_small = secp256k1_scratch_space_create(ctx, 1); CHECK(secp256k1_musig_pubkey_combine(vrfy, scratch_small, &combined_pk, &pre_session, pk_ptr, 2) == 1); secp256k1_scratch_space_destroy(ctx, scratch_small); CHECK(secp256k1_musig_pubkey_combine(vrfy, scratch, NULL, &pre_session, pk_ptr, 2) == 0); CHECK(ecount == 1); CHECK(secp256k1_musig_pubkey_combine(vrfy, scratch, &combined_pk, NULL, pk_ptr, 2) == 1); CHECK(ecount == 1); CHECK(secp256k1_musig_pubkey_combine(vrfy, scratch, &combined_pk, &pre_session, NULL, 2) == 0); CHECK(ecount == 2); CHECK(secp256k1_musig_pubkey_combine(vrfy, scratch, &combined_pk, &pre_session, invalid_pk_ptr2, 2) == 0); CHECK(ecount == 3); CHECK(secp256k1_musig_pubkey_combine(vrfy, scratch, &combined_pk, &pre_session, invalid_pk_ptr3, 3) == 0); CHECK(ecount == 4); CHECK(secp256k1_musig_pubkey_combine(vrfy, scratch, &combined_pk, &pre_session, pk_ptr, 0) == 0); CHECK(ecount == 5); CHECK(secp256k1_musig_pubkey_combine(vrfy, scratch, &combined_pk, &pre_session, NULL, 0) == 0); CHECK(ecount == 6); CHECK(secp256k1_musig_pubkey_combine(vrfy, scratch, &combined_pk, &pre_session, pk_ptr, 2) == 1); CHECK(secp256k1_musig_pubkey_combine(vrfy, scratch, &combined_pk, &pre_session, pk_ptr, 2) == 1); CHECK(secp256k1_musig_pubkey_combine(vrfy, scratch, &combined_pk, &pre_session, pk_ptr, 2) == 1); /** Tweaking */ ecount = 0; { secp256k1_xonly_pubkey tmp_internal_pk = combined_pk; secp256k1_pubkey tmp_output_pk; secp256k1_musig_pre_session tmp_pre_session = pre_session; CHECK(secp256k1_musig_pubkey_tweak_add(ctx, &tmp_pre_session, &tmp_output_pk, &tmp_internal_pk, tweak) == 1); /* Reset pre_session */ tmp_pre_session = pre_session; CHECK(secp256k1_musig_pubkey_tweak_add(none, &tmp_pre_session, &tmp_output_pk, &tmp_internal_pk, tweak) == 1); tmp_pre_session = pre_session; CHECK(secp256k1_musig_pubkey_tweak_add(sign, &tmp_pre_session, &tmp_output_pk, &tmp_internal_pk, tweak) == 1); tmp_pre_session = pre_session; CHECK(secp256k1_musig_pubkey_tweak_add(vrfy, &tmp_pre_session, &tmp_output_pk, &tmp_internal_pk, tweak) == 1); tmp_pre_session = pre_session; CHECK(secp256k1_musig_pubkey_tweak_add(vrfy, NULL, &tmp_output_pk, &tmp_internal_pk, tweak) == 0); CHECK(ecount == 1); /* Uninitialized pre_session */ CHECK(secp256k1_musig_pubkey_tweak_add(vrfy, &pre_session_uninitialized, &tmp_output_pk, &tmp_internal_pk, tweak) == 0); CHECK(ecount == 2); /* Using the same pre_session twice does not work */ CHECK(secp256k1_musig_pubkey_tweak_add(vrfy, &tmp_pre_session, &tmp_output_pk, &tmp_internal_pk, tweak) == 1); CHECK(secp256k1_musig_pubkey_tweak_add(vrfy, &tmp_pre_session, &tmp_output_pk, &tmp_internal_pk, tweak) == 0); CHECK(ecount == 3); tmp_pre_session = pre_session; CHECK(secp256k1_musig_pubkey_tweak_add(vrfy, &tmp_pre_session, NULL, &tmp_internal_pk, tweak) == 0); CHECK(ecount == 4); CHECK(secp256k1_musig_pubkey_tweak_add(vrfy, &tmp_pre_session, &tmp_output_pk, NULL, tweak) == 0); CHECK(ecount == 5); CHECK(secp256k1_musig_pubkey_tweak_add(vrfy, &tmp_pre_session, &tmp_output_pk, &tmp_internal_pk, NULL) == 0); CHECK(ecount == 6); CHECK(secp256k1_musig_pubkey_tweak_add(vrfy, &tmp_pre_session, &tmp_output_pk, &tmp_internal_pk, ones) == 0); CHECK(ecount == 6); } /** Session creation **/ ecount = 0; CHECK(secp256k1_musig_session_init(none, &session[0], signer0, nonce_commitment[0], session_id[0], msg, &combined_pk, &pre_session, 2, sk[0]) == 0); CHECK(ecount == 1); CHECK(secp256k1_musig_session_init(vrfy, &session[0], signer0, nonce_commitment[0], session_id[0], msg, &combined_pk, &pre_session, 2, sk[0]) == 0); CHECK(ecount == 2); CHECK(secp256k1_musig_session_init(sign, &session[0], signer0, nonce_commitment[0], session_id[0], msg, &combined_pk, &pre_session, 2, sk[0]) == 1); CHECK(ecount == 2); CHECK(secp256k1_musig_session_init(sign, NULL, signer0, nonce_commitment[0], session_id[0], msg, &combined_pk, &pre_session, 2, sk[0]) == 0); CHECK(ecount == 3); CHECK(secp256k1_musig_session_init(sign, &session[0], NULL, nonce_commitment[0], session_id[0], msg, &combined_pk, &pre_session, 2, sk[0]) == 0); CHECK(ecount == 4); CHECK(secp256k1_musig_session_init(sign, &session[0], signer0, NULL, session_id[0], msg, &combined_pk, &pre_session, 2, sk[0]) == 0); CHECK(ecount == 5); CHECK(secp256k1_musig_session_init(sign, &session[0], signer0, nonce_commitment[0], NULL, msg, &combined_pk, &pre_session, 2, sk[0]) == 0); CHECK(ecount == 6); CHECK(secp256k1_musig_session_init(sign, &session[0], signer0, nonce_commitment[0], session_id[0], NULL, &combined_pk, &pre_session, 2, sk[0]) == 1); CHECK(ecount == 6); CHECK(secp256k1_musig_session_init(sign, &session[0], signer0, nonce_commitment[0], session_id[0], msg, NULL, &pre_session, 2, sk[0]) == 0); CHECK(ecount == 7); CHECK(secp256k1_musig_session_init(sign, &session[0], signer0, nonce_commitment[0], session_id[0], msg, &combined_pk, NULL, 2, sk[0]) == 0); CHECK(ecount == 8); /* Uninitialized pre_session */ CHECK(secp256k1_musig_session_init(sign, &session[0], signer0, nonce_commitment[0], session_id[0], msg, &combined_pk, &pre_session_uninitialized, 2, sk[0]) == 0); CHECK(ecount == 9); CHECK(secp256k1_musig_session_init(sign, &session[0], signer0, nonce_commitment[0], session_id[0], msg, &combined_pk, &pre_session, 0, sk[0]) == 0); CHECK(ecount == 10); /* If more than UINT32_MAX fits in a size_t, test that session_init * rejects n_signers that high. */ if (SIZE_MAX > UINT32_MAX) { CHECK(secp256k1_musig_session_init(sign, &session[0], signer0, nonce_commitment[0], session_id[0], msg, &combined_pk, &pre_session, ((size_t) UINT32_MAX) + 2, sk[0]) == 0); CHECK(ecount == 11); } else { ecount = 11; } CHECK(secp256k1_musig_session_init(sign, &session[0], signer0, nonce_commitment[0], session_id[0], msg, &combined_pk, &pre_session, 2, NULL) == 0); CHECK(ecount == 12); /* secret key overflows */ CHECK(secp256k1_musig_session_init(sign, &session[0], signer0, nonce_commitment[0], session_id[0], msg, &combined_pk, &pre_session, 2, ones) == 0); CHECK(ecount == 12); CHECK(secp256k1_musig_session_init(sign, &session[0], signer0, nonce_commitment[0], session_id[0], msg, &combined_pk, &pre_session, 2, sk[0]) == 1); CHECK(secp256k1_musig_session_init(sign, &session[1], signer1, nonce_commitment[1], session_id[1], msg, &combined_pk, &pre_session, 2, sk[1]) == 1); ncs[0] = nonce_commitment[0]; ncs[1] = nonce_commitment[1]; ecount = 0; CHECK(secp256k1_musig_session_init_verifier(none, &verifier_session, verifier_signer_data, msg, &combined_pk, &pre_session, ncs, 2) == 1); CHECK(ecount == 0); CHECK(secp256k1_musig_session_init_verifier(none, NULL, verifier_signer_data, msg, &combined_pk, &pre_session, ncs, 2) == 0); CHECK(ecount == 1); CHECK(secp256k1_musig_session_init_verifier(none, &verifier_session, verifier_signer_data, NULL, &combined_pk, &pre_session, ncs, 2) == 0); CHECK(ecount == 2); CHECK(secp256k1_musig_session_init_verifier(none, &verifier_session, verifier_signer_data, msg, NULL, &pre_session, ncs, 2) == 0); CHECK(ecount == 3); CHECK(secp256k1_musig_session_init_verifier(none, &verifier_session, verifier_signer_data, msg, &combined_pk, NULL, ncs, 2) == 0); CHECK(ecount == 4); CHECK(secp256k1_musig_session_init_verifier(none, &verifier_session, verifier_signer_data, msg, &combined_pk, &pre_session, NULL, 2) == 0); CHECK(ecount == 5); CHECK(secp256k1_musig_session_init_verifier(none, &verifier_session, verifier_signer_data, msg, &combined_pk, &pre_session, ncs, 0) == 0); CHECK(ecount == 6); if (SIZE_MAX > UINT32_MAX) { CHECK(secp256k1_musig_session_init_verifier(none, &verifier_session, verifier_signer_data, msg, &combined_pk, &pre_session, ncs, ((size_t) UINT32_MAX) + 2) == 0); CHECK(ecount == 7); } else { ecount = 7; } CHECK(secp256k1_musig_session_init_verifier(none, &verifier_session, verifier_signer_data, msg, &combined_pk, &pre_session, ncs, 2) == 1); /** Signing step 0 -- exchange nonce commitments */ ecount = 0; { unsigned char nonce[32]; secp256k1_musig_session session_0_tmp; memcpy(&session_0_tmp, &session[0], sizeof(session_0_tmp)); /* Can obtain public nonce after commitments have been exchanged; still can't sign */ CHECK(secp256k1_musig_session_get_public_nonce(none, &session_0_tmp, signer0, nonce, ncs, 2, NULL) == 1); CHECK(secp256k1_musig_partial_sign(none, &session_0_tmp, &partial_sig[0]) == 0); CHECK(ecount == 1); } /** Signing step 1 -- exchange nonces */ ecount = 0; { unsigned char public_nonce[3][32]; secp256k1_musig_session session_0_tmp; memcpy(&session_0_tmp, &session[0], sizeof(session_0_tmp)); CHECK(secp256k1_musig_session_get_public_nonce(none, &session_0_tmp, signer0, public_nonce[0], ncs, 2, NULL) == 1); CHECK(ecount == 0); /* Reset session */ memcpy(&session_0_tmp, &session[0], sizeof(session_0_tmp)); CHECK(secp256k1_musig_session_get_public_nonce(none, NULL, signer0, public_nonce[0], ncs, 2, NULL) == 0); CHECK(ecount == 1); /* uninitialized session */ CHECK(secp256k1_musig_session_get_public_nonce(none, &session_uninitialized, signer0, public_nonce[0], ncs, 2, NULL) == 0); CHECK(ecount == 2); CHECK(secp256k1_musig_session_get_public_nonce(none, &session_0_tmp, NULL, public_nonce[0], ncs, 2, NULL) == 0); CHECK(ecount == 3); CHECK(secp256k1_musig_session_get_public_nonce(none, &session_0_tmp, signer0, NULL, ncs, 2, NULL) == 0); CHECK(ecount == 4); CHECK(secp256k1_musig_session_get_public_nonce(none, &session_0_tmp, signer0, public_nonce[0], NULL, 2, NULL) == 0); CHECK(ecount == 5); /* Number of commitments and number of signers are different */ CHECK(secp256k1_musig_session_get_public_nonce(none, &session_0_tmp, signer0, public_nonce[0], ncs, 1, NULL) == 0); CHECK(ecount == 6); CHECK(secp256k1_musig_session_get_public_nonce(none, &session[0], signer0, public_nonce[0], ncs, 2, NULL) == 1); CHECK(secp256k1_musig_session_get_public_nonce(none, &session[1], signer1, public_nonce[1], ncs, 2, NULL) == 1); CHECK(secp256k1_musig_set_nonce(none, &signer0[0], public_nonce[0]) == 1); CHECK(secp256k1_musig_set_nonce(none, &signer0[1], public_nonce[0]) == 0); CHECK(secp256k1_musig_set_nonce(none, &signer0[1], public_nonce[1]) == 1); CHECK(secp256k1_musig_set_nonce(none, &signer0[1], public_nonce[1]) == 1); CHECK(ecount == 6); CHECK(secp256k1_musig_set_nonce(none, NULL, public_nonce[0]) == 0); CHECK(ecount == 7); CHECK(secp256k1_musig_set_nonce(none, &signer1[0], NULL) == 0); CHECK(ecount == 8); CHECK(secp256k1_musig_set_nonce(none, &signer1[0], public_nonce[0]) == 1); CHECK(secp256k1_musig_set_nonce(none, &signer1[1], public_nonce[1]) == 1); CHECK(secp256k1_musig_set_nonce(none, &verifier_signer_data[0], public_nonce[0]) == 1); CHECK(secp256k1_musig_set_nonce(none, &verifier_signer_data[1], public_nonce[1]) == 1); ecount = 0; memcpy(&session_0_tmp, &session[0], sizeof(session_0_tmp)); CHECK(secp256k1_musig_session_combine_nonces(none, &session_0_tmp, signer0, 2, &combined_nonce_parity, &adaptor) == 1); memcpy(&session_0_tmp, &session[0], sizeof(session_0_tmp)); CHECK(secp256k1_musig_session_combine_nonces(none, NULL, signer0, 2, &combined_nonce_parity, &adaptor) == 0); CHECK(ecount == 1); /* Uninitialized session */ CHECK(secp256k1_musig_session_combine_nonces(none, &session_uninitialized, signer0, 2, &combined_nonce_parity, &adaptor) == 0); CHECK(ecount == 2); CHECK(secp256k1_musig_session_combine_nonces(none, &session_0_tmp, NULL, 2, &combined_nonce_parity, &adaptor) == 0); CHECK(ecount == 3); /* Number of signers differs from number during intialization */ CHECK(secp256k1_musig_session_combine_nonces(none, &session_0_tmp, signer0, 1, &combined_nonce_parity, &adaptor) == 0); CHECK(ecount == 4); CHECK(secp256k1_musig_session_combine_nonces(none, &session_0_tmp, signer0, 2, NULL, &adaptor) == 1); CHECK(ecount == 4); memcpy(&session_0_tmp, &session[0], sizeof(session_0_tmp)); CHECK(secp256k1_musig_session_combine_nonces(none, &session_0_tmp, signer0, 2, &combined_nonce_parity, NULL) == 1); CHECK(secp256k1_musig_session_combine_nonces(none, &session[0], signer0, 2, &combined_nonce_parity, &adaptor) == 1); CHECK(secp256k1_musig_session_combine_nonces(none, &session[1], signer0, 2, &combined_nonce_parity, &adaptor) == 1); CHECK(secp256k1_musig_session_combine_nonces(none, &verifier_session, verifier_signer_data, 2, &combined_nonce_parity, &adaptor) == 1); } /** Signing step 2 -- partial signatures */ ecount = 0; CHECK(secp256k1_musig_partial_sign(none, &session[0], &partial_sig[0]) == 1); CHECK(ecount == 0); CHECK(secp256k1_musig_partial_sign(none, NULL, &partial_sig[0]) == 0); CHECK(ecount == 1); /* Uninitialized session */ CHECK(secp256k1_musig_partial_sign(none, &session_uninitialized, &partial_sig[0]) == 0); CHECK(ecount == 2); CHECK(secp256k1_musig_partial_sign(none, &session[0], NULL) == 0); CHECK(ecount == 3); CHECK(secp256k1_musig_partial_sign(none, &session[0], &partial_sig[0]) == 1); CHECK(secp256k1_musig_partial_sign(none, &session[1], &partial_sig[1]) == 1); /* observer can't sign */ CHECK(secp256k1_musig_partial_sign(none, &verifier_session, &partial_sig[2]) == 0); CHECK(ecount == 4); ecount = 0; CHECK(secp256k1_musig_partial_signature_serialize(none, buf, &partial_sig[0]) == 1); CHECK(secp256k1_musig_partial_signature_serialize(none, NULL, &partial_sig[0]) == 0); CHECK(ecount == 1); CHECK(secp256k1_musig_partial_signature_serialize(none, buf, NULL) == 0); CHECK(ecount == 2); CHECK(secp256k1_musig_partial_signature_parse(none, &partial_sig[0], buf) == 1); CHECK(secp256k1_musig_partial_signature_parse(none, NULL, buf) == 0); CHECK(ecount == 3); CHECK(secp256k1_musig_partial_signature_parse(none, &partial_sig[0], NULL) == 0); CHECK(ecount == 4); CHECK(secp256k1_musig_partial_signature_parse(none, &partial_sig_overflow, ones) == 1); /** Partial signature verification */ ecount = 0; CHECK(secp256k1_musig_partial_sig_verify(none, &session[0], &signer0[0], &partial_sig[0], &pk[0]) == 1); CHECK(secp256k1_musig_partial_sig_verify(sign, &session[0], &signer0[0], &partial_sig[0], &pk[0]) == 1); CHECK(secp256k1_musig_partial_sig_verify(vrfy, &session[0], &signer0[0], &partial_sig[0], &pk[0]) == 1); CHECK(secp256k1_musig_partial_sig_verify(vrfy, &session[0], &signer0[0], &partial_sig[1], &pk[0]) == 0); CHECK(secp256k1_musig_partial_sig_verify(vrfy, NULL, &signer0[0], &partial_sig[0], &pk[0]) == 0); CHECK(ecount == 1); /* Unitialized session */ CHECK(secp256k1_musig_partial_sig_verify(vrfy, &session_uninitialized, &signer0[0], &partial_sig[0], &pk[0]) == 0); CHECK(ecount == 2); CHECK(secp256k1_musig_partial_sig_verify(vrfy, &session[0], NULL, &partial_sig[0], &pk[0]) == 0); CHECK(ecount == 3); CHECK(secp256k1_musig_partial_sig_verify(vrfy, &session[0], &signer0[0], NULL, &pk[0]) == 0); CHECK(ecount == 4); CHECK(secp256k1_musig_partial_sig_verify(vrfy, &session[0], &signer0[0], &partial_sig_overflow, &pk[0]) == 0); CHECK(ecount == 4); CHECK(secp256k1_musig_partial_sig_verify(vrfy, &session[0], &signer0[0], &partial_sig[0], NULL) == 0); CHECK(ecount == 5); CHECK(secp256k1_musig_partial_sig_verify(vrfy, &session[0], &signer0[0], &partial_sig[0], &pk[0]) == 1); CHECK(secp256k1_musig_partial_sig_verify(vrfy, &session[1], &signer1[0], &partial_sig[0], &pk[0]) == 1); CHECK(secp256k1_musig_partial_sig_verify(vrfy, &session[0], &signer0[1], &partial_sig[1], &pk[1]) == 1); CHECK(secp256k1_musig_partial_sig_verify(vrfy, &session[1], &signer1[1], &partial_sig[1], &pk[1]) == 1); CHECK(secp256k1_musig_partial_sig_verify(vrfy, &verifier_session, &verifier_signer_data[0], &partial_sig[0], &pk[0]) == 1); CHECK(secp256k1_musig_partial_sig_verify(vrfy, &verifier_session, &verifier_signer_data[1], &partial_sig[1], &pk[1]) == 1); CHECK(ecount == 5); /** Adaptor signature verification */ memcpy(&partial_sig_adapted[1], &partial_sig[1], sizeof(partial_sig_adapted[1])); ecount = 0; CHECK(secp256k1_musig_partial_sig_adapt(none, &partial_sig_adapted[0], &partial_sig[0], sec_adaptor, combined_nonce_parity) == 1); CHECK(secp256k1_musig_partial_sig_adapt(none, NULL, &partial_sig[0], sec_adaptor, 0) == 0); CHECK(ecount == 1); CHECK(secp256k1_musig_partial_sig_adapt(none, &partial_sig_adapted[0], NULL, sec_adaptor, 0) == 0); CHECK(ecount == 2); CHECK(secp256k1_musig_partial_sig_adapt(none, &partial_sig_adapted[0], &partial_sig_overflow, sec_adaptor, combined_nonce_parity) == 0); CHECK(ecount == 2); CHECK(secp256k1_musig_partial_sig_adapt(none, &partial_sig_adapted[0], &partial_sig[0], NULL, 0) == 0); CHECK(ecount == 3); CHECK(secp256k1_musig_partial_sig_adapt(none, &partial_sig_adapted[0], &partial_sig[0], ones, combined_nonce_parity) == 0); CHECK(ecount == 3); /** Signing combining and verification */ ecount = 0; CHECK(secp256k1_musig_partial_sig_combine(none, &session[0], final_sig, partial_sig_adapted, 2) == 1); CHECK(secp256k1_musig_partial_sig_combine(none, &session[0], final_sig_cmp, partial_sig_adapted, 2) == 1); CHECK(memcmp(final_sig, final_sig_cmp, sizeof(final_sig)) == 0); CHECK(secp256k1_musig_partial_sig_combine(none, &session[0], final_sig_cmp, partial_sig_adapted, 2) == 1); CHECK(memcmp(final_sig, final_sig_cmp, sizeof(final_sig)) == 0); CHECK(secp256k1_musig_partial_sig_combine(none, NULL, final_sig, partial_sig_adapted, 2) == 0); CHECK(ecount == 1); /* Unitialized session */ CHECK(secp256k1_musig_partial_sig_combine(none, &session_uninitialized, final_sig, partial_sig_adapted, 2) == 0); CHECK(ecount == 2); CHECK(secp256k1_musig_partial_sig_combine(none, &session[0], NULL, partial_sig_adapted, 2) == 0); CHECK(ecount == 3); CHECK(secp256k1_musig_partial_sig_combine(none, &session[0], final_sig, NULL, 2) == 0); CHECK(ecount == 4); { secp256k1_musig_partial_signature partial_sig_tmp[2]; partial_sig_tmp[0] = partial_sig_adapted[0]; partial_sig_tmp[1] = partial_sig_overflow; CHECK(secp256k1_musig_partial_sig_combine(none, &session[0], final_sig, partial_sig_tmp, 2) == 0); } CHECK(ecount == 4); /* Wrong number of partial sigs */ CHECK(secp256k1_musig_partial_sig_combine(none, &session[0], final_sig, partial_sig_adapted, 1) == 0); CHECK(ecount == 4); CHECK(secp256k1_musig_partial_sig_combine(none, &session[0], final_sig, partial_sig_adapted, 2) == 1); CHECK(ecount == 4); CHECK(secp256k1_schnorrsig_verify(vrfy, final_sig, msg, sizeof(msg), &combined_pk) == 1); /** Secret adaptor can be extracted from signature */ ecount = 0; CHECK(secp256k1_musig_extract_secret_adaptor(none, sec_adaptor1, final_sig, partial_sig, 2, combined_nonce_parity) == 1); CHECK(memcmp(sec_adaptor, sec_adaptor1, 32) == 0); CHECK(secp256k1_musig_extract_secret_adaptor(none, NULL, final_sig, partial_sig, 2, 0) == 0); CHECK(ecount == 1); CHECK(secp256k1_musig_extract_secret_adaptor(none, sec_adaptor1, NULL, partial_sig, 2, 0) == 0); CHECK(ecount == 2); { unsigned char final_sig_tmp[64]; memcpy(final_sig_tmp, final_sig, sizeof(final_sig_tmp)); memcpy(&final_sig_tmp[32], ones, 32); CHECK(secp256k1_musig_extract_secret_adaptor(none, sec_adaptor1, final_sig_tmp, partial_sig, 2, combined_nonce_parity) == 0); } CHECK(ecount == 2); CHECK(secp256k1_musig_extract_secret_adaptor(none, sec_adaptor1, final_sig, NULL, 2, 0) == 0); CHECK(ecount == 3); { secp256k1_musig_partial_signature partial_sig_tmp[2]; partial_sig_tmp[0] = partial_sig[0]; partial_sig_tmp[1] = partial_sig_overflow; CHECK(secp256k1_musig_extract_secret_adaptor(none, sec_adaptor1, final_sig, partial_sig_tmp, 2, combined_nonce_parity) == 0); } CHECK(ecount == 3); CHECK(secp256k1_musig_extract_secret_adaptor(none, sec_adaptor1, final_sig, partial_sig, 0, 0) == 1); CHECK(secp256k1_musig_extract_secret_adaptor(none, sec_adaptor1, final_sig, partial_sig, 2, 1) == 1); /** cleanup **/ memset(&session, 0, sizeof(session)); secp256k1_context_destroy(none); secp256k1_context_destroy(sign); secp256k1_context_destroy(vrfy); } /* Initializes two sessions, one use the given parameters (session_id, * nonce_commitments, etc.) except that `session_tmp` uses new signers with different * public keys. The point of this test is to call `musig_session_get_public_nonce` * with signers from `session_tmp` who have different public keys than the correct * ones and return the resulting messagehash. This should not result in a different * messagehash because the public keys of the signers are only used during session * initialization. */ void musig_state_machine_diff_signer_msghash_test(unsigned char *msghash, secp256k1_xonly_pubkey *pks, secp256k1_xonly_pubkey *combined_pk, secp256k1_musig_pre_session *pre_session, const unsigned char * const *nonce_commitments, unsigned char *msg, unsigned char *nonce_other, unsigned char *sk, unsigned char *session_id) { secp256k1_musig_session session; secp256k1_musig_session session_tmp; unsigned char nonce_commitment[32]; secp256k1_musig_session_signer_data signers[2]; secp256k1_musig_session_signer_data signers_tmp[2]; unsigned char sk_dummy[32]; secp256k1_xonly_pubkey pks_tmp[2]; const secp256k1_xonly_pubkey *pks_tmp_ptr[2]; secp256k1_xonly_pubkey combined_pk_tmp; secp256k1_musig_pre_session pre_session_tmp; unsigned char nonce[32]; /* Set up signers with different public keys */ secp256k1_testrand256(sk_dummy); pks_tmp[0] = pks[0]; CHECK(secp256k1_xonly_pubkey_create(&pks_tmp[1], sk_dummy) == 1); pks_tmp_ptr[0] = &pks_tmp[0]; pks_tmp_ptr[1] = &pks_tmp[1]; CHECK(secp256k1_musig_pubkey_combine(ctx, NULL, &combined_pk_tmp, &pre_session_tmp, pks_tmp_ptr, 2) == 1); CHECK(secp256k1_musig_session_init(ctx, &session_tmp, signers_tmp, nonce_commitment, session_id, msg, &combined_pk_tmp, &pre_session_tmp, 2, sk_dummy) == 1); CHECK(secp256k1_musig_session_init(ctx, &session, signers, nonce_commitment, session_id, msg, combined_pk, pre_session, 2, sk) == 1); CHECK(memcmp(nonce_commitment, nonce_commitments[1], 32) == 0); /* Call get_public_nonce with different signers than the signers the session was * initialized with. */ CHECK(secp256k1_musig_session_get_public_nonce(ctx, &session_tmp, signers, nonce, nonce_commitments, 2, NULL) == 1); CHECK(secp256k1_musig_session_get_public_nonce(ctx, &session, signers_tmp, nonce, nonce_commitments, 2, NULL) == 1); CHECK(secp256k1_musig_set_nonce(ctx, &signers[0], nonce_other) == 1); CHECK(secp256k1_musig_set_nonce(ctx, &signers[1], nonce) == 1); CHECK(secp256k1_musig_session_combine_nonces(ctx, &session, signers, 2, NULL, NULL) == 1); secp256k1_musig_compute_messagehash(ctx, msghash, &session); } /* Creates a new session (with a different session id) and tries to use that session * to combine nonces with given signers_other. This should fail, because the nonce * commitments of signers_other do not match the nonce commitments the new session * was initialized with. If do_test is 0, the correct signers are being used and * therefore the function should return 1. */ int musig_state_machine_diff_signers_combine_nonce_test(secp256k1_xonly_pubkey *combined_pk, secp256k1_musig_pre_session *pre_session, unsigned char *nonce_commitment_other, unsigned char *nonce_other, unsigned char *msg, unsigned char *sk, secp256k1_musig_session_signer_data *signers_other, int do_test) { secp256k1_musig_session session; secp256k1_musig_session_signer_data signers[2]; secp256k1_musig_session_signer_data *signers_to_use; unsigned char nonce_commitment[32]; unsigned char session_id[32]; unsigned char nonce[32]; const unsigned char *ncs[2]; /* Initialize new signers */ secp256k1_testrand256(session_id); CHECK(secp256k1_musig_session_init(ctx, &session, signers, nonce_commitment, session_id, msg, combined_pk, pre_session, 2, sk) == 1); ncs[0] = nonce_commitment_other; ncs[1] = nonce_commitment; CHECK(secp256k1_musig_session_get_public_nonce(ctx, &session, signers, nonce, ncs, 2, NULL) == 1); CHECK(secp256k1_musig_set_nonce(ctx, &signers[0], nonce_other) == 1); CHECK(secp256k1_musig_set_nonce(ctx, &signers[1], nonce) == 1); CHECK(secp256k1_musig_set_nonce(ctx, &signers[1], nonce) == 1); secp256k1_musig_session_combine_nonces(ctx, &session, signers_other, 2, NULL, NULL); if (do_test) { signers_to_use = signers_other; } else { signers_to_use = signers; } return secp256k1_musig_session_combine_nonces(ctx, &session, signers_to_use, 2, NULL, NULL); } /* Initializaes a session with the given session_id, signers, pk, msg etc. * parameters but without a message. Will test that the message must be * provided with `get_public_nonce`. */ void musig_state_machine_late_msg_test(secp256k1_xonly_pubkey *pks, secp256k1_xonly_pubkey *combined_pk, secp256k1_musig_pre_session *pre_session, unsigned char *nonce_commitment_other, unsigned char *nonce_other, unsigned char *sk, unsigned char *session_id, unsigned char *msg) { /* Create context for testing ARG_CHECKs by setting an illegal_callback. */ secp256k1_context *ctx_tmp = secp256k1_context_create(SECP256K1_CONTEXT_NONE); int ecount = 0; secp256k1_musig_session session; secp256k1_musig_session_signer_data signers[2]; unsigned char nonce_commitment[32]; const unsigned char *ncs[2]; unsigned char nonce[32]; secp256k1_musig_partial_signature partial_sig; secp256k1_context_set_illegal_callback(ctx_tmp, counting_illegal_callback_fn, &ecount); CHECK(secp256k1_musig_session_init(ctx, &session, signers, nonce_commitment, session_id, NULL, combined_pk, pre_session, 2, sk) == 1); ncs[0] = nonce_commitment_other; ncs[1] = nonce_commitment; /* Trying to get the nonce without providing a message fails. */ CHECK(ecount == 0); CHECK(secp256k1_musig_session_get_public_nonce(ctx_tmp, &session, signers, nonce, ncs, 2, NULL) == 0); CHECK(ecount == 1); /* Providing a message should make get_public_nonce succeed. */ CHECK(secp256k1_musig_session_get_public_nonce(ctx, &session, signers, nonce, ncs, 2, msg) == 1); /* Trying to set the message again fails. */ CHECK(ecount == 1); CHECK(secp256k1_musig_session_get_public_nonce(ctx_tmp, &session, signers, nonce, ncs, 2, msg) == 0); CHECK(ecount == 2); /* Check that it's working */ CHECK(secp256k1_musig_set_nonce(ctx, &signers[0], nonce_other) == 1); CHECK(secp256k1_musig_set_nonce(ctx, &signers[1], nonce) == 1); CHECK(secp256k1_musig_session_combine_nonces(ctx, &session, signers, 2, NULL, NULL) == 1); CHECK(secp256k1_musig_partial_sign(ctx, &session, &partial_sig)); CHECK(secp256k1_musig_partial_sig_verify(ctx, &session, &signers[1], &partial_sig, &pks[1])); secp256k1_context_destroy(ctx_tmp); } void musig_state_machine_tests(secp256k1_scratch_space *scratch) { secp256k1_context *ctx_tmp = secp256k1_context_create(SECP256K1_CONTEXT_VERIFY | SECP256K1_CONTEXT_VERIFY); size_t i; secp256k1_musig_session session[2]; secp256k1_musig_session_signer_data signers0[2]; secp256k1_musig_session_signer_data signers1[2]; unsigned char nonce_commitment[2][32]; unsigned char session_id[2][32]; unsigned char msg[32]; unsigned char sk[2][32]; secp256k1_xonly_pubkey pk[2]; const secp256k1_xonly_pubkey *pk_ptr[2]; secp256k1_xonly_pubkey combined_pk; secp256k1_musig_pre_session pre_session; unsigned char nonce[2][32]; const unsigned char *ncs[2]; secp256k1_musig_partial_signature partial_sig[2]; unsigned char sig[64]; unsigned char msghash1[32]; unsigned char msghash2[32]; int ecount; secp256k1_context_set_illegal_callback(ctx_tmp, counting_illegal_callback_fn, &ecount); ecount = 0; /* Run state machine with the same objects twice to test that it's allowed to * reinitialize session and session_signer_data. */ for (i = 0; i < 2; i++) { /* Setup */ secp256k1_testrand256(session_id[0]); secp256k1_testrand256(session_id[1]); secp256k1_testrand256(sk[0]); secp256k1_testrand256(sk[1]); secp256k1_testrand256(msg); pk_ptr[0] = &pk[0]; pk_ptr[1] = &pk[1]; CHECK(secp256k1_xonly_pubkey_create(&pk[0], sk[0]) == 1); CHECK(secp256k1_xonly_pubkey_create(&pk[1], sk[1]) == 1); CHECK(secp256k1_musig_pubkey_combine(ctx, scratch, &combined_pk, &pre_session, pk_ptr, 2) == 1); CHECK(secp256k1_musig_session_init(ctx, &session[0], signers0, nonce_commitment[0], session_id[0], msg, &combined_pk, &pre_session, 2, sk[0]) == 1); CHECK(secp256k1_musig_session_init(ctx, &session[1], signers1, nonce_commitment[1], session_id[1], msg, &combined_pk, &pre_session, 2, sk[1]) == 1); /* Can't combine nonces unless we're through round 1 already */ ecount = 0; CHECK(secp256k1_musig_session_combine_nonces(ctx_tmp, &session[0], signers0, 2, NULL, NULL) == 0); CHECK(ecount == 1); /* Set nonce commitments */ ncs[0] = nonce_commitment[0]; ncs[1] = nonce_commitment[1]; CHECK(secp256k1_musig_session_get_public_nonce(ctx, &session[0], signers0, nonce[0], ncs, 2, NULL) == 1); /* Calling the function again is not okay */ ecount = 0; CHECK(secp256k1_musig_session_get_public_nonce(ctx_tmp, &session[0], signers0, nonce[0], ncs, 2, NULL) == 0); CHECK(ecount == 1); /* Get nonce for signer 1 */ CHECK(secp256k1_musig_session_get_public_nonce(ctx, &session[1], signers1, nonce[1], ncs, 2, NULL) == 1); /* Set nonces */ CHECK(secp256k1_musig_set_nonce(ctx, &signers0[0], nonce[0]) == 1); /* Can't set nonce that doesn't match nonce commitment */ CHECK(secp256k1_musig_set_nonce(ctx, &signers0[1], nonce[0]) == 0); /* Set correct nonce */ CHECK(secp256k1_musig_set_nonce(ctx, &signers0[1], nonce[1]) == 1); /* Combine nonces */ CHECK(secp256k1_musig_session_combine_nonces(ctx, &session[0], signers0, 2, NULL, NULL) == 1); /* Not everyone is present from signer 1's view */ CHECK(secp256k1_musig_session_combine_nonces(ctx, &session[1], signers1, 2, NULL, NULL) == 0); /* Make everyone present */ CHECK(secp256k1_musig_set_nonce(ctx, &signers1[0], nonce[0]) == 1); CHECK(secp256k1_musig_set_nonce(ctx, &signers1[1], nonce[1]) == 1); /* Can't combine nonces from signers of a different session */ CHECK(musig_state_machine_diff_signers_combine_nonce_test(&combined_pk, &pre_session, nonce_commitment[0], nonce[0], msg, sk[1], signers1, 1) == 0); CHECK(musig_state_machine_diff_signers_combine_nonce_test(&combined_pk, &pre_session, nonce_commitment[0], nonce[0], msg, sk[1], signers1, 0) == 1); /* Partially sign */ CHECK(secp256k1_musig_partial_sign(ctx, &session[0], &partial_sig[0]) == 1); /* Can't verify, sign or combine signatures until nonce is combined */ ecount = 0; CHECK(secp256k1_musig_partial_sig_verify(ctx_tmp, &session[1], &signers1[0], &partial_sig[0], &pk[0]) == 0); CHECK(ecount == 1); CHECK(secp256k1_musig_partial_sign(ctx_tmp, &session[1], &partial_sig[1]) == 0); CHECK(ecount == 2); memset(&partial_sig[1], 0, sizeof(partial_sig[1])); CHECK(secp256k1_musig_partial_sig_combine(ctx_tmp, &session[1], sig, partial_sig, 2) == 0); CHECK(ecount == 3); CHECK(secp256k1_musig_session_combine_nonces(ctx, &session[1], signers1, 2, NULL, NULL) == 1); CHECK(secp256k1_musig_partial_sig_verify(ctx, &session[1], &signers1[0], &partial_sig[0], &pk[0]) == 1); /* messagehash should be the same as a session whose get_public_nonce was called * with different signers (i.e. they diff in public keys). This is because the * public keys of the signers is set in stone when initializing the session. */ secp256k1_musig_compute_messagehash(ctx, msghash1, &session[1]); musig_state_machine_diff_signer_msghash_test(msghash2, pk, &combined_pk, &pre_session, ncs, msg, nonce[0], sk[1], session_id[1]); CHECK(memcmp(msghash1, msghash2, 32) == 0); CHECK(secp256k1_musig_partial_sign(ctx, &session[1], &partial_sig[1]) == 1); CHECK(secp256k1_musig_partial_sig_verify(ctx, &session[1], &signers1[1], &partial_sig[1], &pk[1]) == 1); /* Wrong signature */ CHECK(secp256k1_musig_partial_sig_verify(ctx, &session[1], &signers1[1], &partial_sig[0], &pk[1]) == 0); /* Can't get the public nonce until msg is set */ musig_state_machine_late_msg_test(pk, &combined_pk, &pre_session, nonce_commitment[0], nonce[0], sk[1], session_id[1], msg); } secp256k1_context_destroy(ctx_tmp); } void scriptless_atomic_swap(secp256k1_scratch_space *scratch) { /* Throughout this test "a" and "b" refer to two hypothetical blockchains, * while the indices 0 and 1 refer to the two signers. Here signer 0 is * sending a-coins to signer 1, while signer 1 is sending b-coins to signer * 0. Signer 0 produces the adaptor signatures. */ unsigned char final_sig_a[64]; unsigned char final_sig_b[64]; secp256k1_musig_partial_signature partial_sig_a[2]; secp256k1_musig_partial_signature partial_sig_b_adapted[2]; secp256k1_musig_partial_signature partial_sig_b[2]; unsigned char sec_adaptor[32]; unsigned char sec_adaptor_extracted[32]; secp256k1_pubkey pub_adaptor; unsigned char seckey_a[2][32]; unsigned char seckey_b[2][32]; secp256k1_xonly_pubkey pk_a[2]; const secp256k1_xonly_pubkey *pk_a_ptr[2]; secp256k1_xonly_pubkey pk_b[2]; const secp256k1_xonly_pubkey *pk_b_ptr[2]; secp256k1_musig_pre_session pre_session_a; secp256k1_musig_pre_session pre_session_b; secp256k1_xonly_pubkey combined_pk_a; secp256k1_xonly_pubkey combined_pk_b; secp256k1_musig_session musig_session_a[2]; secp256k1_musig_session musig_session_b[2]; unsigned char noncommit_a[2][32]; unsigned char noncommit_b[2][32]; const unsigned char *noncommit_a_ptr[2]; const unsigned char *noncommit_b_ptr[2]; unsigned char pubnon_a[2][32]; unsigned char pubnon_b[2][32]; int combined_nonce_parity_a; int combined_nonce_parity_b; secp256k1_musig_session_signer_data data_a[2]; secp256k1_musig_session_signer_data data_b[2]; const unsigned char seed[32] = "still tired of choosing seeds..."; const unsigned char msg32_a[32] = "this is the message blockchain a"; const unsigned char msg32_b[32] = "this is the message blockchain b"; /* Step 1: key setup */ secp256k1_testrand256(seckey_a[0]); secp256k1_testrand256(seckey_a[1]); secp256k1_testrand256(seckey_b[0]); secp256k1_testrand256(seckey_b[1]); secp256k1_testrand256(sec_adaptor); pk_a_ptr[0] = &pk_a[0]; pk_a_ptr[1] = &pk_a[1]; pk_b_ptr[0] = &pk_b[0]; pk_b_ptr[1] = &pk_b[1]; CHECK(secp256k1_xonly_pubkey_create(&pk_a[0], seckey_a[0])); CHECK(secp256k1_xonly_pubkey_create(&pk_a[1], seckey_a[1])); CHECK(secp256k1_xonly_pubkey_create(&pk_b[0], seckey_b[0])); CHECK(secp256k1_xonly_pubkey_create(&pk_b[1], seckey_b[1])); CHECK(secp256k1_ec_pubkey_create(ctx, &pub_adaptor, sec_adaptor)); CHECK(secp256k1_musig_pubkey_combine(ctx, scratch, &combined_pk_a, &pre_session_a, pk_a_ptr, 2)); CHECK(secp256k1_musig_pubkey_combine(ctx, scratch, &combined_pk_b, &pre_session_b, pk_b_ptr, 2)); CHECK(secp256k1_musig_session_init(ctx, &musig_session_a[0], data_a, noncommit_a[0], seed, msg32_a, &combined_pk_a, &pre_session_a, 2, seckey_a[0])); CHECK(secp256k1_musig_session_init(ctx, &musig_session_a[1], data_a, noncommit_a[1], seed, msg32_a, &combined_pk_a, &pre_session_a, 2, seckey_a[1])); noncommit_a_ptr[0] = noncommit_a[0]; noncommit_a_ptr[1] = noncommit_a[1]; CHECK(secp256k1_musig_session_init(ctx, &musig_session_b[0], data_b, noncommit_b[0], seed, msg32_b, &combined_pk_b, &pre_session_b, 2, seckey_b[0])); CHECK(secp256k1_musig_session_init(ctx, &musig_session_b[1], data_b, noncommit_b[1], seed, msg32_b, &combined_pk_b, &pre_session_b, 2, seckey_b[1])); noncommit_b_ptr[0] = noncommit_b[0]; noncommit_b_ptr[1] = noncommit_b[1]; /* Step 2: Exchange nonces */ CHECK(secp256k1_musig_session_get_public_nonce(ctx, &musig_session_a[0], data_a, pubnon_a[0], noncommit_a_ptr, 2, NULL)); CHECK(secp256k1_musig_session_get_public_nonce(ctx, &musig_session_a[1], data_a, pubnon_a[1], noncommit_a_ptr, 2, NULL)); CHECK(secp256k1_musig_session_get_public_nonce(ctx, &musig_session_b[0], data_b, pubnon_b[0], noncommit_b_ptr, 2, NULL)); CHECK(secp256k1_musig_session_get_public_nonce(ctx, &musig_session_b[1], data_b, pubnon_b[1], noncommit_b_ptr, 2, NULL)); CHECK(secp256k1_musig_set_nonce(ctx, &data_a[0], pubnon_a[0])); CHECK(secp256k1_musig_set_nonce(ctx, &data_a[1], pubnon_a[1])); CHECK(secp256k1_musig_set_nonce(ctx, &data_b[0], pubnon_b[0])); CHECK(secp256k1_musig_set_nonce(ctx, &data_b[1], pubnon_b[1])); CHECK(secp256k1_musig_session_combine_nonces(ctx, &musig_session_a[0], data_a, 2, &combined_nonce_parity_a, &pub_adaptor)); CHECK(secp256k1_musig_session_combine_nonces(ctx, &musig_session_a[1], data_a, 2, NULL, &pub_adaptor)); CHECK(secp256k1_musig_session_combine_nonces(ctx, &musig_session_b[0], data_b, 2, &combined_nonce_parity_b, &pub_adaptor)); CHECK(secp256k1_musig_session_combine_nonces(ctx, &musig_session_b[1], data_b, 2, NULL, &pub_adaptor)); /* Step 3: Signer 0 produces partial signatures for both chains. */ CHECK(secp256k1_musig_partial_sign(ctx, &musig_session_a[0], &partial_sig_a[0])); CHECK(secp256k1_musig_partial_sign(ctx, &musig_session_b[0], &partial_sig_b[0])); /* Step 4: Signer 1 receives partial signatures, verifies them and creates a * partial signature to send B-coins to signer 0. */ CHECK(secp256k1_musig_partial_sig_verify(ctx, &musig_session_a[1], data_a, &partial_sig_a[0], &pk_a[0]) == 1); CHECK(secp256k1_musig_partial_sig_verify(ctx, &musig_session_b[1], data_b, &partial_sig_b[0], &pk_b[0]) == 1); CHECK(secp256k1_musig_partial_sign(ctx, &musig_session_b[1], &partial_sig_b[1])); /* Step 5: Signer 0 adapts its own partial signature and combines it with the * partial signature from signer 1. This results in a complete signature which * is broadcasted by signer 0 to take B-coins. */ CHECK(secp256k1_musig_partial_sig_adapt(ctx, &partial_sig_b_adapted[0], &partial_sig_b[0], sec_adaptor, combined_nonce_parity_b)); memcpy(&partial_sig_b_adapted[1], &partial_sig_b[1], sizeof(partial_sig_b_adapted[1])); CHECK(secp256k1_musig_partial_sig_combine(ctx, &musig_session_b[0], final_sig_b, partial_sig_b_adapted, 2) == 1); CHECK(secp256k1_schnorrsig_verify(ctx, final_sig_b, msg32_b, sizeof(msg32_b), &combined_pk_b) == 1); /* Step 6: Signer 1 extracts adaptor from the published signature, applies it to * other partial signature, and takes A-coins. */ CHECK(secp256k1_musig_extract_secret_adaptor(ctx, sec_adaptor_extracted, final_sig_b, partial_sig_b, 2, combined_nonce_parity_b) == 1); CHECK(memcmp(sec_adaptor_extracted, sec_adaptor, sizeof(sec_adaptor)) == 0); /* in real life we couldn't check this, of course */ CHECK(secp256k1_musig_partial_sig_adapt(ctx, &partial_sig_a[0], &partial_sig_a[0], sec_adaptor_extracted, combined_nonce_parity_a)); CHECK(secp256k1_musig_partial_sign(ctx, &musig_session_a[1], &partial_sig_a[1])); CHECK(secp256k1_musig_partial_sig_combine(ctx, &musig_session_a[1], final_sig_a, partial_sig_a, 2) == 1); CHECK(secp256k1_schnorrsig_verify(ctx, final_sig_a, msg32_a, sizeof(msg32_a), &combined_pk_a) == 1); } void sha256_tag_test_internal(secp256k1_sha256 *sha_tagged, unsigned char *tag, size_t taglen) { secp256k1_sha256 sha; unsigned char buf[32]; unsigned char buf2[32]; size_t i; secp256k1_sha256_initialize(&sha); secp256k1_sha256_write(&sha, tag, taglen); secp256k1_sha256_finalize(&sha, buf); /* buf = SHA256("KeyAgg coefficient") */ secp256k1_sha256_initialize(&sha); secp256k1_sha256_write(&sha, buf, 32); secp256k1_sha256_write(&sha, buf, 32); /* Is buffer fully consumed? */ CHECK((sha.bytes & 0x3F) == 0); /* Compare with tagged SHA */ for (i = 0; i < 8; i++) { CHECK(sha_tagged->s[i] == sha.s[i]); } secp256k1_sha256_write(&sha, buf, 32); secp256k1_sha256_write(sha_tagged, buf, 32); secp256k1_sha256_finalize(&sha, buf); secp256k1_sha256_finalize(sha_tagged, buf2); CHECK(memcmp(buf, buf2, 32) == 0); } /* Checks that the initialized tagged hashes initialized have the expected * state. */ void sha256_tag_test(void) { secp256k1_sha256 sha_tagged; { char tag[11] = "KeyAgg list"; secp256k1_musig_keyagglist_sha256(&sha_tagged); sha256_tag_test_internal(&sha_tagged, (unsigned char*)tag, sizeof(tag)); } { char tag[18] = "KeyAgg coefficient"; secp256k1_musig_keyaggcoef_sha256(&sha_tagged); sha256_tag_test_internal(&sha_tagged, (unsigned char*)tag, sizeof(tag)); } } /* Attempts to create a signature for the combined public key using given secret * keys and pre_session. */ void musig_tweak_test_helper(const secp256k1_xonly_pubkey* combined_pubkey, const unsigned char *sk0, const unsigned char *sk1, secp256k1_musig_pre_session *pre_session) { secp256k1_musig_session session[2]; secp256k1_musig_session_signer_data signers0[2]; secp256k1_musig_session_signer_data signers1[2]; secp256k1_xonly_pubkey pk[2]; unsigned char session_id[2][32]; unsigned char msg[32]; unsigned char nonce_commitment[2][32]; unsigned char nonce[2][32]; const unsigned char *ncs[2]; secp256k1_musig_partial_signature partial_sig[2]; unsigned char final_sig[64]; secp256k1_testrand256(session_id[0]); secp256k1_testrand256(session_id[1]); secp256k1_testrand256(msg); CHECK(secp256k1_xonly_pubkey_create(&pk[0], sk0) == 1); CHECK(secp256k1_xonly_pubkey_create(&pk[1], sk1) == 1); CHECK(secp256k1_musig_session_init(ctx, &session[0], signers0, nonce_commitment[0], session_id[0], msg, combined_pubkey, pre_session, 2, sk0) == 1); CHECK(secp256k1_musig_session_init(ctx, &session[1], signers1, nonce_commitment[1], session_id[1], msg, combined_pubkey, pre_session, 2, sk1) == 1); /* Set nonce commitments */ ncs[0] = nonce_commitment[0]; ncs[1] = nonce_commitment[1]; CHECK(secp256k1_musig_session_get_public_nonce(ctx, &session[0], signers0, nonce[0], ncs, 2, NULL) == 1); CHECK(secp256k1_musig_session_get_public_nonce(ctx, &session[1], signers1, nonce[1], ncs, 2, NULL) == 1); /* Set nonces */ CHECK(secp256k1_musig_set_nonce(ctx, &signers0[0], nonce[0]) == 1); CHECK(secp256k1_musig_set_nonce(ctx, &signers0[1], nonce[1]) == 1); CHECK(secp256k1_musig_set_nonce(ctx, &signers1[0], nonce[0]) == 1); CHECK(secp256k1_musig_set_nonce(ctx, &signers1[1], nonce[1]) == 1); CHECK(secp256k1_musig_session_combine_nonces(ctx, &session[0], signers0, 2, NULL, NULL) == 1); CHECK(secp256k1_musig_session_combine_nonces(ctx, &session[1], signers1, 2, NULL, NULL) == 1); CHECK(secp256k1_musig_partial_sign(ctx, &session[0], &partial_sig[0]) == 1); CHECK(secp256k1_musig_partial_sign(ctx, &session[1], &partial_sig[1]) == 1); CHECK(secp256k1_musig_partial_sig_verify(ctx, &session[0], &signers0[1], &partial_sig[1], &pk[1]) == 1); CHECK(secp256k1_musig_partial_sig_verify(ctx, &session[1], &signers1[0], &partial_sig[0], &pk[0]) == 1); CHECK(secp256k1_musig_partial_sig_combine(ctx, &session[0], final_sig, partial_sig, 2)); CHECK(secp256k1_schnorrsig_verify(ctx, final_sig, msg, sizeof(msg), combined_pubkey) == 1); } /* In this test we create a combined public key P and a commitment Q = P + * hash(P, contract)*G. Then we test that we can sign for both public keys. In * order to sign for Q we use the tweak32 argument of partial_sig_combine. */ void musig_tweak_test(secp256k1_scratch_space *scratch) { unsigned char sk[2][32]; secp256k1_xonly_pubkey pk[2]; const secp256k1_xonly_pubkey *pk_ptr[2]; secp256k1_musig_pre_session pre_session_P; secp256k1_musig_pre_session pre_session_Q; secp256k1_xonly_pubkey P; unsigned char P_serialized[32]; secp256k1_pubkey Q; int Q_parity; secp256k1_xonly_pubkey Q_xonly; unsigned char Q_serialized[32]; secp256k1_sha256 sha; unsigned char contract[32]; unsigned char ec_commit_tweak[32]; /* Setup */ secp256k1_testrand256(sk[0]); secp256k1_testrand256(sk[1]); secp256k1_testrand256(contract); pk_ptr[0] = &pk[0]; pk_ptr[1] = &pk[1]; CHECK(secp256k1_xonly_pubkey_create(&pk[0], sk[0]) == 1); CHECK(secp256k1_xonly_pubkey_create(&pk[1], sk[1]) == 1); CHECK(secp256k1_musig_pubkey_combine(ctx, scratch, &P, &pre_session_P, pk_ptr, 2) == 1); CHECK(secp256k1_xonly_pubkey_serialize(ctx, P_serialized, &P) == 1); secp256k1_sha256_initialize(&sha); secp256k1_sha256_write(&sha, P_serialized, 32); secp256k1_sha256_write(&sha, contract, 32); secp256k1_sha256_finalize(&sha, ec_commit_tweak); pre_session_Q = pre_session_P; CHECK(secp256k1_musig_pubkey_tweak_add(ctx, &pre_session_Q, &Q, &P, ec_commit_tweak) == 1); CHECK(secp256k1_xonly_pubkey_from_pubkey(ctx, &Q_xonly, &Q_parity, &Q)); CHECK(secp256k1_xonly_pubkey_serialize(ctx, Q_serialized, &Q_xonly)); /* Check that musig_pubkey_tweak_add produces same result as * xonly_pubkey_tweak_add. */ CHECK(secp256k1_xonly_pubkey_tweak_add_check(ctx, Q_serialized, Q_parity, &P, ec_commit_tweak) == 1); /* Test signing for P */ musig_tweak_test_helper(&P, sk[0], sk[1], &pre_session_P); /* Test signing for Q */ musig_tweak_test_helper(&Q_xonly, sk[0], sk[1], &pre_session_Q); } void musig_test_vectors_helper(unsigned char pk_ser[][32], int n_pks, const unsigned char *combined_pk_expected, int has_second_pk, int second_pk_idx) { secp256k1_xonly_pubkey *pk = malloc(n_pks * sizeof(*pk)); const secp256k1_xonly_pubkey **pk_ptr = malloc(n_pks * sizeof(*pk_ptr)); secp256k1_xonly_pubkey combined_pk; unsigned char combined_pk_ser[32]; secp256k1_musig_pre_session pre_session; secp256k1_fe second_pk_x; int i; for (i = 0; i < n_pks; i++) { CHECK(secp256k1_xonly_pubkey_parse(ctx, &pk[i], pk_ser[i])); pk_ptr[i] = &pk[i]; } CHECK(secp256k1_musig_pubkey_combine(ctx, NULL, &combined_pk, &pre_session, pk_ptr, n_pks) == 1); CHECK(secp256k1_fe_set_b32(&second_pk_x, pre_session.second_pk)); CHECK(secp256k1_fe_is_zero(&second_pk_x) == !has_second_pk); if (!secp256k1_fe_is_zero(&second_pk_x)) { CHECK(secp256k1_memcmp_var(&pk_ser[second_pk_idx], &pre_session.second_pk, sizeof(pk_ser[second_pk_idx])) == 0); } CHECK(secp256k1_xonly_pubkey_serialize(ctx, combined_pk_ser, &combined_pk)); /* TODO: remove when test vectors are not expected to change anymore */ /* int k, l; */ /* printf("const unsigned char combined_pk_expected[32] = {\n"); */ /* for (k = 0; k < 4; k++) { */ /* printf(" "); */ /* for (l = 0; l < 8; l++) { */ /* printf("0x%02X, ", combined_pk_ser[k*8+l]); */ /* } */ /* printf("\n"); */ /* } */ /* printf("};\n"); */ CHECK(secp256k1_memcmp_var(combined_pk_ser, combined_pk_expected, sizeof(combined_pk_ser)) == 0); free(pk); free(pk_ptr); } void musig_test_vectors(void) { size_t i; unsigned char pk_ser_tmp[4][32]; unsigned char pk_ser[3][32] = { /* X1 */ { 0xF9, 0x30, 0x8A, 0x01, 0x92, 0x58, 0xC3, 0x10, 0x49, 0x34, 0x4F, 0x85, 0xF8, 0x9D, 0x52, 0x29, 0xB5, 0x31, 0xC8, 0x45, 0x83, 0x6F, 0x99, 0xB0, 0x86, 0x01, 0xF1, 0x13, 0xBC, 0xE0, 0x36, 0xF9 }, /* X2 */ { 0xDF, 0xF1, 0xD7, 0x7F, 0x2A, 0x67, 0x1C, 0x5F, 0x36, 0x18, 0x37, 0x26, 0xDB, 0x23, 0x41, 0xBE, 0x58, 0xFE, 0xAE, 0x1D, 0xA2, 0xDE, 0xCE, 0xD8, 0x43, 0x24, 0x0F, 0x7B, 0x50, 0x2B, 0xA6, 0x59 }, /* X3 */ { 0x35, 0x90, 0xA9, 0x4E, 0x76, 0x8F, 0x8E, 0x18, 0x15, 0xC2, 0xF2, 0x4B, 0x4D, 0x80, 0xA8, 0xE3, 0x14, 0x93, 0x16, 0xC3, 0x51, 0x8C, 0xE7, 0xB7, 0xAD, 0x33, 0x83, 0x68, 0xD0, 0x38, 0xCA, 0x66 } }; const unsigned char combined_pk_expected[4][32] = { { /* 0 */ 0xE5, 0x83, 0x01, 0x40, 0x51, 0x21, 0x95, 0xD7, 0x4C, 0x83, 0x07, 0xE3, 0x96, 0x37, 0xCB, 0xE5, 0xFB, 0x73, 0x0E, 0xBE, 0xAB, 0x80, 0xEC, 0x51, 0x4C, 0xF8, 0x8A, 0x87, 0x7C, 0xEE, 0xEE, 0x0B, }, { /* 1 */ 0xD7, 0x0C, 0xD6, 0x9A, 0x26, 0x47, 0xF7, 0x39, 0x09, 0x73, 0xDF, 0x48, 0xCB, 0xFA, 0x2C, 0xCC, 0x40, 0x7B, 0x8B, 0x2D, 0x60, 0xB0, 0x8C, 0x5F, 0x16, 0x41, 0x18, 0x5C, 0x79, 0x98, 0xA2, 0x90, }, { /* 2 */ 0x81, 0xA8, 0xB0, 0x93, 0x91, 0x2C, 0x9E, 0x48, 0x14, 0x08, 0xD0, 0x97, 0x76, 0xCE, 0xFB, 0x48, 0xAE, 0xB8, 0xB6, 0x54, 0x81, 0xB6, 0xBA, 0xAF, 0xB3, 0xC5, 0x81, 0x01, 0x06, 0x71, 0x7B, 0xEB, }, { /* 3 */ 0x2E, 0xB1, 0x88, 0x51, 0x88, 0x7E, 0x7B, 0xDC, 0x5E, 0x83, 0x0E, 0x89, 0xB1, 0x9D, 0xDB, 0xC2, 0x80, 0x78, 0xF1, 0xFA, 0x88, 0xAA, 0xD0, 0xAD, 0x01, 0xCA, 0x06, 0xFE, 0x4F, 0x80, 0x21, 0x0B, }, }; for (i = 0; i < sizeof(combined_pk_expected)/sizeof(combined_pk_expected[0]); i++) { size_t n_pks; int has_second_pk; int second_pk_idx; switch (i) { case 0: /* [X1, X2, X3] */ n_pks = 3; memcpy(pk_ser_tmp[0], pk_ser[0], sizeof(pk_ser_tmp[0])); memcpy(pk_ser_tmp[1], pk_ser[1], sizeof(pk_ser_tmp[1])); memcpy(pk_ser_tmp[2], pk_ser[2], sizeof(pk_ser_tmp[2])); has_second_pk = 1; second_pk_idx = 1; break; case 1: /* [X3, X2, X1] */ n_pks = 3; memcpy(pk_ser_tmp[2], pk_ser[0], sizeof(pk_ser_tmp[0])); memcpy(pk_ser_tmp[1], pk_ser[1], sizeof(pk_ser_tmp[1])); memcpy(pk_ser_tmp[0], pk_ser[2], sizeof(pk_ser_tmp[2])); has_second_pk = 1; second_pk_idx = 1; break; case 2: /* [X1, X1, X1] */ n_pks = 3; memcpy(pk_ser_tmp[0], pk_ser[0], sizeof(pk_ser_tmp[0])); memcpy(pk_ser_tmp[1], pk_ser[0], sizeof(pk_ser_tmp[1])); memcpy(pk_ser_tmp[2], pk_ser[0], sizeof(pk_ser_tmp[2])); has_second_pk = 0; second_pk_idx = 0; /* unchecked */ break; case 3: /* [X1, X1, X2, X2] */ n_pks = 4; memcpy(pk_ser_tmp[0], pk_ser[0], sizeof(pk_ser_tmp[0])); memcpy(pk_ser_tmp[1], pk_ser[0], sizeof(pk_ser_tmp[1])); memcpy(pk_ser_tmp[2], pk_ser[1], sizeof(pk_ser_tmp[2])); memcpy(pk_ser_tmp[3], pk_ser[1], sizeof(pk_ser_tmp[3])); has_second_pk = 1; second_pk_idx = 2; /* second_pk_idx = 3 is equally valid */ break; default: CHECK(0); } musig_test_vectors_helper(pk_ser_tmp, n_pks, combined_pk_expected[i], has_second_pk, second_pk_idx); } } void run_musig_tests(void) { int i; secp256k1_scratch_space *scratch = secp256k1_scratch_space_create(ctx, 1024 * 1024); for (i = 0; i < count; i++) { musig_simple_test(scratch); } musig_api_tests(scratch); musig_state_machine_tests(scratch); for (i = 0; i < count; i++) { /* Run multiple times to ensure that pk and nonce have different y * parities */ scriptless_atomic_swap(scratch); musig_tweak_test(scratch); } sha256_tag_test(); musig_test_vectors(); secp256k1_scratch_space_destroy(ctx, scratch); } #endif
nvh/DataSourceable
DataSourceable/DataSourceable.h
<filename>DataSourceable/DataSourceable.h<gh_stars>10-100 // // DataSourceable.h // DataSourceable // // Created by <NAME> on 13/10/15. // Copyright © 2015 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> //! Project version number for DataSourceable. FOUNDATION_EXPORT double DataSourceableVersionNumber; //! Project version string for DataSourceable. FOUNDATION_EXPORT const unsigned char DataSourceableVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <DataSourceable/PublicHeader.h>
EverydayStep/ESAlbumManager
ESAlbumManager/ESAlbumManager/ESAlbumManager.h
// // ESAlbumManager.h // ESAlbumManager // // Created by codeLocker on 2017/7/26. // Copyright © 2017年 codeLocker. All rights reserved. // #import <Foundation/Foundation.h> #import <Photos/Photos.h> @interface ESAlbumManager : NSObject /** 相册当前访问权限 @return 访问权限 */ + (PHAuthorizationStatus)authorizationState; /** 相册授权 @param accept 授权 @param decline 拒绝 */ + (void)authorization:(void(^)(void))accept decline:(void(^)(void))decline; /** 取消资源请求 @param requestID 请求ID */ //+ (void)cancelImageRequest:(PHImageRequestID)requestID; /** 开始缓存 @param assets 资源文件 @param targetSize 目标尺寸 @param contentMode 内容模式 @param options 条件 */ //+ (void)startCachingAssets:(NSArray<PHAsset *> *)assets targetSize:(CGSize)targetSize contentMode:(PHImageContentMode)contentMode options:(PHImageRequestOptions *)options; /** 停止缓存 @param assets 资源文件 @param targetSize 目标尺寸 @param contentMode 内容模式 @param options 条件 */ //+ (void)stopCachingAssets:(NSArray<PHAsset *> *)assets targetSize:(CGSize)targetSize contentMode:(PHImageContentMode)contentMode options:(PHImageRequestOptions *)options; /** 停止所有缓存 */ //+ (void)stopCachingAllAssets; /** 请求管理器 @return 管理器 */ //+ (PHCachingImageManager *)assetCachingManager; @end
EverydayStep/ESAlbumManager
ESAlbumManager/ESAlbumManager/ESAlbumManager+ESVideo.h
<reponame>EverydayStep/ESAlbumManager // // ESAlbumManager+ESVideo.h // ESAlbumManager // // Created by codeLocker on 2017/7/27. // Copyright © 2017年 codeLocker. All rights reserved. // #import "ESAlbumManager.h" @interface ESAlbumManager (ESVideo) #pragma mark - Image /** 获取视屏的缩略图 @param asset 资源文件 @param targetSize 缩略图的尺寸 @param isSync 是否线程同步执行 @param isHightQuality 是否获取高质量图片,isSync=YES 情况下只有高质量图片 @param isCache 是否需要缓存(缓存大量图片会造成大量内存占用) @param resultHandler 回调处理 @return requestID */ //+ (PHImageRequestID)videoThumbnailForAsset:(PHAsset *)asset targetSize:(CGSize)targetSize isSync:(BOOL)isSync isHightQuality:(BOOL)isHightQuality isCache:(BOOL)isCache resultHandler:(void (^)(UIImage *result, NSDictionary *info))resultHandler; /** 获取视屏的预览图 @param asset 资源文件 @param isSync 是否线程同步执行 @param isCache 是否需要缓存(缓存大量图片会造成大量内存占用) @param resultHandler 回调处理 @return requestID */ //+ (PHImageRequestID)videoPreviewForAsset:(PHAsset *)asset isSync:(BOOL)isSync isCache:(BOOL)isCache resultHandler:(void (^)(UIImage *result, NSDictionary *info))resultHandler; /** 获取playerItem 视频 @param asset 资源文件 @param options 条件 @param resultHandler 回调处理 @return requestID */ //+ (PHImageRequestID)videoPlayerItemForAsset:(PHAsset *)asset options:(PHVideoRequestOptions *)options resultHandler:(void (^)(AVPlayerItem *playerItem, NSDictionary *info))resultHandler; /** 导出视频 @param asset 资源文件 @param options 条件 @param exportPreset 导出格式 AVAssetExportPresetLowQuality AVAssetExportPresetMediumQuality AVAssetExportPresetHighestQuality AVAssetExportPreset640x480 AVAssetExportPreset1280x720 @param resultHandler 回调处理 @return requestID */ //+ (PHImageRequestID)videoExportSessionForVideo:(PHAsset *)asset options:(PHVideoRequestOptions *)options exportPreset:(NSString *)exportPreset resultHandler:(void (^)(AVAssetExportSession *exportSession, NSDictionary *info))resultHandler; /** 导出AVAsset @param asset AVAsset @param options 条件 @param resultHandler 回调处理 @return requestID */ //+ (PHImageRequestID)videoAVAssetForVideo:(PHAsset *)asset options:(PHVideoRequestOptions *)options resultHandler:(void (^)(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info))resultHandler; @end
EverydayStep/ESAlbumManager
ESAlbumManager/ESAlbumManager/ESAlbumManager+ESAsset.h
<filename>ESAlbumManager/ESAlbumManager/ESAlbumManager+ESAsset.h // // ESAlbumManager+ESAsset.h // ESAlbumManager // // Created by codeLocker on 2017/7/27. // Copyright © 2017年 codeLocker. All rights reserved. // #import "ESAlbumManager.h" @interface ESAlbumManager (ESAsset) #pragma mmark - Query Asset /** 查询照片库中资源 @param options 查询条件 无条件传nil @return 查询结果 */ + (PHFetchResult<PHAsset *> *)assetsWithOptions:(PHFetchOptions *)options; /** 查询照片库中资源 @param mediaType 查询的类型 @param options 查询条件 无条件传nil @return 查询结果 */ + (PHFetchResult<PHAsset *> *)assetsWithMediaType:(PHAssetMediaType)mediaType options:(PHFetchOptions *)options; /** 查询相册中的资源 @param assetCollection 相册 @param mediaType PHAsset的资源类型 @return 查询结果 */ + (PHFetchResult<PHAsset *> *)assetsInAssetCollection:(PHAssetCollection *)assetCollection mediaType:(PHAssetMediaType)mediaType; /** 查询相册中的资源 @param assetCollection 相册 @param options 查询条件 无条件传nil @return 查询结果 */ + (PHFetchResult<PHAsset *> *)assetsInAssetCollection:(PHAssetCollection *)assetCollection options:(PHFetchOptions *)options; /** 查询照片库资源 @param identifiers 查询的id @param options 查询条件 无条件传nil @return 查询结果 */ + (PHFetchResult<PHAsset *> *)assetsWithLocalIdentifiers:(NSArray<NSString *> *)identifiers options:(PHFetchOptions *)options; /** 查询相册关键资源 @param assetCollection 相册 @param options 查询条件 无条件传nil @return 查询结果 */ + (PHFetchResult<PHAsset *> *)keyAssetsInAssetCollection:(PHAssetCollection *)assetCollection options:(PHFetchOptions *)options; /** 查询照片库资源 @param burstIdentifier burstIdentifier 查询burstID @param options 查询条件 无条件传nil @return 查询结果 */ + (PHFetchResult<PHAsset *> *)assetsWithBurstIdentifier:(NSString *)burstIdentifier options:(PHFetchOptions *)options; /** 查询照片库资源 @param assetURLs 资源的URL @param options 查询条件 无条件传nil @return 查询结果 */ + (PHFetchResult<PHAsset *> *)assetsWithALAssetURLs:(NSArray<NSURL *> *)assetURLs options:(PHFetchOptions *)options; #pragma mark - 保存照片 /** 保存图片 @param image UIImage @param collection 目标相册 @param success 成功回调 @param fail 失败回调 */ //+ (void)saveImage:(UIImage *)image toCollection:(PHAssetCollection *)collection success:(void(^)(void))success fail:(void(^)(NSError *error))fail; ///** // 保存图片 // // @param fileURL UIImage // @param collection 目标相册 // @param success 成功回调 // @param fail 失败回调 // */ //+ (void)saveImageAtFileURL:(NSURL *)fileURL toCollection:(PHAssetCollection *)collection success:(void(^)(void))success fail:(void(^)(NSError *error))fail; // //#pragma mark - 保存 Video ///** // 保存视频 // // @param fileURL 视频路径 // @param collection 目标相册 // @param success 成功回调 // @param fail 失败回调 // */ //+ (void)saveVideoAtFileURL:(NSURL *)fileURL toCollection:(PHAssetCollection *)collection success:(void(^)(void))success fail:(void(^)(NSError *error))fail; // //#pragma mark - 保存 Asset ///** // 保存Asset // // @param fileURL 资源路径 // @param type 资源类型 // @param collection 目标相册 // @param options 条件 // @param success 成功回调 // @param fail 失败回调 // */ //+ (void)saveAssetAtFileURL:(NSURL *)fileURL type:(PHAssetResourceType)type toCollection:(PHAssetCollection *)collection options:(PHAssetResourceCreationOptions *)options success:(void(^)(void))success fail:(void(^)(NSError *error))fail; // ///** // 保存Asset // // @param data 资源data // @param type 资源类型 // @param collection 目标相册 // @param options 条件 // @param success 成功回调 // @param fail 失败回调 // */ //+ (void)saveAssetWithData:(NSData *)data type:(PHAssetResourceType)type toCollection:(PHAssetCollection *)collection options:(PHAssetResourceCreationOptions *)options success:(void(^)(void))success fail:(void(^)(NSError *error))fail; // //#pragma mark - 删除 Asset ///** // 删除PHAsset // // @param asset PHAsset // @param success 成功回调 // @param fail 失败回到 // */ //+ (void)deleteAsset:(PHAsset *)asset success:(void(^)(void))success fail:(void(^)(NSError *error))fail; @end
EverydayStep/ESAlbumManager
ESAlbumManager/ESAlbumManager/ESAlbumManager+ESImage.h
// // ESAlbumManager+ESImage.h // ESAlbumManager // // Created by codeLocker on 2017/7/27. // Copyright © 2017年 codeLocker. All rights reserved. // #import "ESAlbumManager.h" @interface ESAlbumManager (ESImage) #pragma mark - 缩略图 /** 获取图片做略图 @param asset 资源文件 @param targetSize 缩略图的尺寸 @param isSync 是否线程同步执行 @param isHightQuality 是否获取高质量图片,isSync=YES 情况下只有高质量图片 @param isCache 是否需要缓存(缓存大量图片会造成大量内存占用) @param resultHandler 回调处理 @return requestID */ //+ (PHImageRequestID)imageThumbnailForAsset:(PHAsset *)asset targetSize:(CGSize)targetSize isSync:(BOOL)isSync isHightQuality:(BOOL)isHightQuality isCache:(BOOL)isCache resultHandler:(void (^)(UIImage *result, NSDictionary *info))resultHandler; /** 获取图片原图 @param asset 资源文件 @param isSync 是否线程同步执行 @param isCache 是否需要缓存(缓存大量图片会造成大量内存占用) @param resultHandler 回调处理 @return requestID */ //+ (PHImageRequestID)imageOriginForAsset:(PHAsset *)asset isSync:(BOOL)isSync isCache:(BOOL)isCache resultHandler:(void (^)(UIImage *result, NSDictionary *info))resultHandler; /** 获取预览图 @param asset 资源文件 @param isSync 是否线程同步执行 @param isCache 是否需要缓存(缓存大量图片会造成大量内存占用) @param resultHandler 回调处理 @return requestID */ //+ (PHImageRequestID)imagePreviewForAsset:(PHAsset *)asset isSync:(BOOL)isSync isCache:(BOOL)isCache resultHandler:(void (^)(UIImage *result, NSDictionary *info))resultHandler; /** 获取图片 @param asset 资源文件 @param targetSize 目标尺寸 @param isHightQuality 是否获取高质量图片,isSync=YES 情况下只有高质量图片 @param isCache 是否需要缓存(缓存大量图片会造成大量内存占用) @param contentMode 图片模式 @param options 条件 @param resultHandler 回调处理 @return requestID */ //+ (PHImageRequestID)imageForAsset:(PHAsset *)asset targetSize:(CGSize)targetSize isHightQuality:(BOOL)isHightQuality isCache:(BOOL)isCache contentMode:(PHImageContentMode)contentMode options:(PHImageRequestOptions *)options resultHandler:(void (^)(UIImage *result, NSDictionary *info))resultHandler; /** 获取图片Data @param asset 资源文件 @param options 条件 @param resultHandler 回调处理 @return requestID */ //+ (PHImageRequestID)imageDataForAsset:(PHAsset *)asset options:(PHImageRequestOptions *)options resultHandler:(void(^)(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info))resultHandler; @end
EverydayStep/ESAlbumManager
ESAlbumManager/ESAlbumManager/ESAlbumManager+ESCollection.h
// // ESAlbumManager+ESCollection.h // ESAlbumManager // // Created by codeLocker on 2017/7/27. // Copyright © 2017年 codeLocker. All rights reserved. // #import "ESAlbumManager.h" @interface ESAlbumManager (ESCollection) #pragma mark - 用户创建相册 /** 查询用户创建的标题为title的相册 @param title 相册标题 @return 用户创建的相册 */ + (PHFetchResult<PHCollection *>*)userAssetCollectionsWithTitle:(NSString *)title; /** 查询用户创建的相册 @param options 查询条件 无条件传nil @return 用户创建的相册 */ + (PHFetchResult<PHCollection *>*)userAssetCollectionsWithOptions:(PHFetchOptions *)options; #pragma mark - 系统相册 /** 查询相册 @param type 相册组类型 @param subtype 相册类型 @param options 查询条件 无条件传nil @return 查询结果 */ + (PHFetchResult<PHAssetCollection *>*)assetCollectionsWithType:(PHAssetCollectionType)type subtype:(PHAssetCollectionSubtype)subtype options:(PHFetchOptions *)options; /** 查询相册 @param identifiers 相册的ID @param options 查询条件 无条件传nil @return 查询结果 */ + (PHFetchResult<PHAssetCollection *> *)assetCollectionsWithLocalIdentifiers:(NSArray<NSString *> *)identifiers options:(PHFetchOptions *)options; #pragma mark - 创建相册 /** 创建相册 @param title 相册标题 @param success 创建成功 @param fail 创建失败 */ //+ (void)createAssetCollectionWithTitle:(NSString *)title success:(void(^)(void))success fail:(void(^)(NSError *error))fail; // //#pragma mark - 删除相册 ///** // 删除相册 // // @param assetCollections 待删除的相册 // @param success 删除成功 // @param fail 删除失败 // */ //+ (void)deleteAssetCollections:(NSArray *)assetCollections success:(void(^)(void))success fail:(void(^)(NSError *error))fail; @end
EverydayStep/ESAlbumManager
ESAlbumManager/ESImageCell.h
<gh_stars>0 // // ESImageCell.h // ESAlbumManager // // Created by codeLocker on 2017/7/27. // Copyright © 2017年 codeLocker. All rights reserved. // #import <UIKit/UIKit.h> @interface ESImageCell : UICollectionViewCell @property (nonatomic, strong) UIImageView *imageView; @end
godlikezack/ScanQRCode
ScanQRCode/Lib/QRCodeViewController.h
<filename>ScanQRCode/Lib/QRCodeViewController.h<gh_stars>0 // // QRCodeViewController.h // ScanQRCode // // Created by zack on 2016/11/16. // Copyright © 2016年 HF. All rights reserved. // #import <UIKit/UIKit.h> @class QRCodeViewController; @protocol QRCodeViewControllerDelegate <NSObject> /** * 读取到结果时会调用下面的代理方法 * * @param reader 扫描二维码控制器 * @param result 扫描结果 */ - (void)reader:(QRCodeViewController *)reader didScanResult:(NSString *)result; @end @interface QRCodeViewController : UIViewController @property (nonatomic, weak) id<QRCodeViewControllerDelegate> delegate; /** * 设置扫描二维码完成后回调的block * * @param completionBlock 完成block */ - (void)setCompletionWithBlock:(void (^) (NSString *resultAsString))completionBlock; @end
dionrhys/JAMasterServer
src/NetAdr.h
<reponame>dionrhys/JAMasterServer #ifndef _NETADR_H #define _NETADR_H /** * Possible host address types. */ enum NetAdrType { ADR_BAD, ADR_IP, ADR_IP6 }; /** * Structure to uniquely identify a remote/local host. * * @warning Please remember that UDP packets are totally insecure and can * be faked to appear to originate from any address/port! */ class NetAdr { public: NetAdr(); NetAdr(unsigned long ipv4_address, unsigned short port); NetAdr(unsigned char ipv6_address[16], unsigned short port); NetAdrType GetType(); // These are identical to the constructors above void ChangeTo(); void ChangeTo(unsigned long ipv4_address, unsigned short port); void ChangeTo(unsigned char ipv6_address[16], unsigned short port); unsigned long GetIPv4Address(); unsigned char const *GetIPv6Address(); unsigned short GetPort(); bool CompareWith(NetAdr *other); void ToString(char *buffer, int length); void ToSockaddr(struct sockaddr_storage *saddr); private: NetAdrType m_type; // addr and port are stored as HOST order here! union { unsigned long ip; unsigned char ip6[16]; } m_addr; unsigned short m_port; }; #endif // !_NETADR_H
dionrhys/JAMasterServer
src/config.h
<gh_stars>1-10 #ifndef _CONFIG_H #define _CONFIG_H #include "jams_local.h" typedef enum { OPT_BOOL, OPT_INT, OPT_FLOAT, OPT_STRING, // All parsed strings are malloc'd } optionType_t; typedef struct { char *name; char *defaultValue; void *ptr; optionType_t type; } option_t; /** * All of JAMasterServer's configuration options go in the table below. */ static const option_t jamsOptions[] = { /** * Listening address * * @remark Empty string means any interface. */ {"hostname", "", &jams.config.hostname, OPT_STRING}, /** * Listening port */ {"port", "29060", &jams.config.port, OPT_INT}, /** * Rcon password * * @remark Empty string means rcon is disabled. */ {"rconPassword", "", &jams.config.rconPassword, OPT_STRING}, /** * Server heartbeat timeout (in seconds) * * A server will be de-registered if no successfully-challenged heartbeat * is received within this time. * * @remark Set this option to 0 to make servers stay forever. * (Not recommended) */ {"serverTimeout", "300", &jams.config.svTimeout, OPT_INT}, /** * Minimum wait time between heartbeats (in seconds) * * A server will be de-registered if it gave us a heartbeat before this * time (flood protection). * * @remark Set this option to 0 to disable flood protection. * @todo Think of better flood protection than just de-registering a * server... */ {"floodDelay", "60", &jams.config.floodDelay, OPT_INT}, /** * Server challenge response timeout (in seconds) * * A server will be de-registered if it didn't reply to a getstatus request * within this time (servers send a heartbeat when they shutdown). * * @remark Set this value the same as svTimeout if you don't want to assume * that a server sent a shutdown heartbeat. */ {"challengeTimeout", "10", &jams.config.challengeTimeout, OPT_INT}, /** * Flag to make the master server "daemonize" itself. * * @note Not supported for Windows. (Might make it a Windows Service later) */ {"daemonize", "false", &jams.config.daemonize, OPT_BOOL}, /** * Logging to a file is enabled when this flag is set to true. * Use the logFile option to specify the log file to use. */ {"useLogFile", "false", &jams.config.useLogFile, OPT_BOOL}, /** * File to use for logging output. * * @remark Typical value for Unix: "/var/log/jams.log" * Typical value for Windows: "./jams.log" */ {"logFile", "", &jams.config.logFile, OPT_STRING}, /** * Logging to a syslog daemon is enabled when this flag is set to true. * * @remark This option only applies on Unix. */ {"useSyslog", "false", &jams.config.useSyslog, OPT_BOOL}, /** * Specify the lock file to use to ensure only one instance is running. * * @remark Typical value for Unix: "/var/run/jams.pid" * Typical value for Windows: "./jams.pid" */ {"lockFile", "", &jams.config.lockFile, OPT_STRING}, {NULL} }; bool JAMS_LoadConfig(char *filename); #endif // !_CONFIG_H
dionrhys/JAMasterServer
src/InfoString.h
#ifndef _INFOSTRING_H #define _INFOSTRING_H #include "jams_local.h" class InfoString { public: static const size_t MAX_INFO_STRING = 1024; static const size_t MAX_INFO_KEY = 1024; static const size_t MAX_INFO_VALUE = 1024; InfoString(char *initialString); void GetValue(const char *key, char *buffer, size_t length); //void SetValue(const char *key, const char *value); //void RemoveKey(const char *key); private: char m_string[MAX_INFO_STRING]; }; #endif // !_INFOSTRING_H
dionrhys/JAMasterServer
src/rcon.h
<gh_stars>1-10 // JAMS RCON Command System // <3 Q3 /** * stop * Gracefully shutdown the server remotely * * Usage: * stop * * WARNING: You won't get it back up with rcon again :P */ /** * restart * Gracefully restart the server remotely * * Usage: * restart */ /** * kick * Kick a server from our server list * * Usage: * kick <server ip> - Kick all registered servers using this IP * (Note: Servers can exist on different ports) * * kick <server ip:port> - Kick the registered server using this IP/Port * (Guaranteed to be only one server) * * kick all - Kick ALL the currently registered servers off the list! * * This command supports wildcard IP address matches (192.168.*.*) */ /** * ban * Ban a server from our server list * * Usage: * ban <server ip> - Ban any server from this IP from registering * (Note: Servers can exist on different ports) * * ban <server ip:port> - Ban the server at this IP/Port from registering * (Guaranteed to be only one server) * * This command supports wildcard IP address matches (192.168.*.*) */ /** * status * Get a brief status of the server * * Usage: * status * * Example response: * Servers online: XXX * */ /** * listservers * List pages of registered servers * * Usage: * list [page number] - Responds with a single page of registered servers * If no page number is given, page 1 is shown * (Pages contain <listserversPageCount> servers each) * * list * - Show every single registered server * (WARNING: Will generate a lot of UDP traffic!) * * Example response: * # Address Port Timeout * ---- --------------- ----- ------- * 0 192.168.127.12 8 7s * 10 9.87.6.543 1056 11s * 20 54.321.978.6 135 254s * ... * 300 1192.168.127.12 5000 36s * 4000 172.16.31.10 29070 104s * --- Page 1/1 --------------------- */ /** * showgraph * Print an ASCII art graph :') of the registered server count * over a day in 30 minute intervals * * Usage: * showgraph * * Example response: * 600 | * 570 | * 540 | * 510 | * 480 | _________ * 450 | _____| | * 420 | | |_ * 390 | __| |___ * 360 | _| | * 330 | | |__ * 300 | | | * 270 | | | * 240 | | | _ * 210 | _| |__|_ * 180 | | | * 150 | | | * 120 | ___ _| |__ * 90 | | |_| |__ * 60 | __| |__ * 30 |_____| |__ * 0 |________________________________________________ * ^^^^^|^^^^^|^^^^^|^^^^^|^^^^^|^^^^^|^^^^^|^^^^^| * 18 21 00 03 06 09 12 15 */
dionrhys/JAMasterServer
src/platform.h
#ifndef _SYS_PUBLIC_H #define _SYS_PUBLIC_H #include "jams_local.h" // OS-dependent functions // Initialise OS-dependent stuff // Return non-zero for error int Sys_Init(void); typedef enum { _PRINT_NONE, PRINT_ERROR, PRINT_WARNING, PRINT_NORMAL, // Normal, Warning and Error logged/printed by default PRINT_VERBOSE, PRINT_DEBUG, _PRINT_ALL } printLevel_t; // Print function with different print levels void Error( const char *fmt, ... ); void PrintWarning( const char *fmt, ... ); void Print( const char *fmt, ... ); void PrintVerbose( const char *fmt, ... ); void PrintDebug( const char *fmt, ... ); void Sys_Printf( printLevel_t level, const char *message ); #endif // !_SYS_PUBLIC_H
dionrhys/JAMasterServer
src/Command.h
/************************************************** * * [ JAMasterServer by Didz ] * * Copyright (c) 2011, <NAME> * All Rights Reserved. * * Stand-Alone Command Tokenizer - Header * * Heavily ported from Q3, should match JKA. * You can spawn as many of these as you wish. * **************************************************/ #ifndef _COMMAND_H #define _COMMAND_H //#define MAX_STRING_CHARS 1024 // max length of a string passed to Cmd_TokenizeString #define MAX_STRING_TOKENS 1024 // max tokens resulting from Cmd_TokenizeString //#define MAX_TOKEN_CHARS 1024 // max length of an individual token //#define MAX_INFO_STRING 1024 //#define MAX_INFO_KEY 1024 //#define MAX_INFO_VALUE 1024 #define BIG_INFO_STRING 8192 // used for system info key only //#define BIG_INFO_KEY 8192 //#define BIG_INFO_VALUE 8192 class Command { public: Command(); ~Command(); void TokenizeString( const char *text_in ); int Argc( void ); char *Argv( int arg ); char *Cmd(); char *ConcatArgs( int arg ); private: int m_argc; char *m_argv[MAX_STRING_TOKENS]; // points into cmd_tokenized char m_tokenized[BIG_INFO_STRING+MAX_STRING_TOKENS]; // will have 0 bytes inserted char m_cmd[BIG_INFO_STRING]; // the original command we received (no token processing) char m_tempArgs[BIG_INFO_STRING]; // for ConcatArgs }; #endif // !_COMMAND_H
dionrhys/JAMasterServer
src/cJSON.h
/* JSON framework for C Copyright (c) 2010 Lourens "BobaFett" Elzinga Based on cJSON by <NAME> Changes: * Cleaned up code formatting to make it much more readable * Renamed print to serialize * Serializer now uses a stringbuilder instead of a tremendous amount of mallocs * Added usage of dynamic arrays and hashtables to drastically speed up lookup times for arrays and objects * JSON Type #defines are now internal * Array and Object functions now contain sanity checks (to ensure an array/object is being used) * cJSON struct is now internal, and is typedef'd as void * Replaced all instances of sprintf by snprintf to remove the risk of overflows (#defined as sprintf_s for windows compiles) * Added functions to obtain item values as a specific type (with default value in case of an error or incompatible type) * Added functions to determine the type of an item * Removed 'references'. They are unsafe and not very useful. * Added item duplication * Added new create functions (for booleans and integers) * The string serializer now supports unprintable characters ( < ANSI 32 without \x equivalent ) * Deleting linked nodes is no longer possible * Added a safe version of cJSON_Delete which also clears the pointer if deleting was successful * Added function to insert items in arrays * Added function to swap 2 items in arrays * Added functions to clear arrays and objects * Added extended lookup, to allow retreival of deeply nested items in 1 call * Implemented iterator functions to iterate over objects (and arrays) * The parser now uses a stream buffer to track the current position * Errors during parsing now produce a proper error instead of silently failing * Fixed memory leaks in parser * The parser supports C-style comments (both single-line and block comments) * The string parser and serializer is now properly UTF-8 aware, and will encode and decode characters properly (non-ANSI chars are converted to '?') * The parser now supports memory pooling, which dramatically increases parse and free time (at the cost of the result being read-only) */ #ifndef cJSON__h #define cJSON__h #include <stdlib.h> #ifdef __cplusplus extern "C" { #endif #ifndef __cJSON_INTERNAL typedef void cJSON; typedef void cJSONStream; #endif typedef struct cJSON_Hooks { void *(*malloc_fn)(size_t sz); void *(*realloc_fn)(void *ptr, size_t sz); void (*free_fn)(void *ptr); } cJSON_Hooks; // Supply malloc, realloc and free functions to cJSON extern void cJSON_InitHooks(cJSON_Hooks* hooks); // Supply a block of JSON, and this returns a cJSON object you can interrogate. Call cJSON_Delete when finished. // cJSON_ParsePooled utilizes a memory pool. This makes the parsing and freeing much faster, but also makes the structure read-only. extern cJSON *cJSON_Parse(const char *data, char *error, size_t errorlen); extern cJSON *cJSON_ParsePooled(const char *data, char *error, size_t errorlen); // Serialize a cJSON entity to text for transfer/storage. Optionally with formatting to make it more human-readable. Free the const char* when finished. extern const char *cJSON_Serialize(cJSON *item, int format); // Delete a cJSON entity and all subentities. extern void cJSON_Delete(cJSON *c); // Delete a cJSON entity and all subentities, and clear the pointer to it as well (if successful) extern void cJSON_SafeDelete(cJSON **c); // Returns the number of items in an arry (or object). extern int cJSON_GetArraySize(cJSON *arry); // Retrieve item number "item" from arry "arry". Returns NULL if unsuccessful. extern cJSON *cJSON_GetArrayItem(cJSON *arry, int item); // Get item "string" from object. Case insensitive. extern cJSON *cJSON_GetObjectItem(cJSON *object, const char *string); // Extended Item Lookup. // Allows complex nested lookups // // Format example: // sub[5].myvar // [2] // test.sub[24].something[4].var extern cJSON *cJSON_Lookup(cJSON *item, const char *path); // Iterator functions // Example usage: // // for (item = cJSON_GetFirstItem(object); item; item = cJSON_GetNextItem(item)) { ... } // extern cJSON *cJSON_GetFirstItem(cJSON *object); extern cJSON *cJSON_GetNextItem(cJSON *item); // Returns the key of an item (only valid for items that are part of an object) extern const char * cJSON_GetItemKey(cJSON *item); // Duplicate a cJSON item and all subentities extern cJSON *cJSON_DuplicateItem(cJSON *item); // These calls create a cJSON item of the appropriate type. extern cJSON *cJSON_CreateNull(); extern cJSON *cJSON_CreateTrue(); extern cJSON *cJSON_CreateFalse(); extern cJSON *cJSON_CreateBoolean(int boolean); extern cJSON *cJSON_CreateNumber(double num); extern cJSON *cJSON_CreateInteger(int num); extern cJSON *cJSON_CreateString(const char *string); extern cJSON *cJSON_CreateArray(); extern cJSON *cJSON_CreateObject(); // These utilities create an array of count items. extern cJSON *cJSON_CreateIntArray(int count, int *number); extern cJSON *cJSON_CreateFloatArray(int count, float *numbers); extern cJSON *cJSON_CreateDoubleArray(int count, double *numbers); extern cJSON *cJSON_CreateStringArray(int count, const char **strings); // Same as above, but uses varargs instead of arrays extern cJSON *cJSON_CreateIntArrayv(int count, ...); extern cJSON *cJSON_CreateFloatArrayv(int count, ...); extern cJSON *cJSON_CreateDoubleArrayv(int count, ...); extern cJSON *cJSON_CreateStringArrayv(int count, ...); // Read an array and store the values. extern int cJSON_ReadIntArray(cJSON *arry, int count, int *number); extern int cJSON_ReadFloatArray(cJSON *arry, int count, float *numbers); extern int cJSON_ReadDoubleArray(cJSON *arry, int count, double *numbers); extern int cJSON_ReadStringArray(cJSON *arry, int count, const char **strings); // Same as above, but uses varargs instead of arrays extern int cJSON_ReadIntArrayv(cJSON *arry, int count, ...); extern int cJSON_ReadFloatArrayv(cJSON *arry, int count, ...); extern int cJSON_ReadDoubleArrayv(cJSON *arry, int count, ...); extern int cJSON_ReadStringArrayv(cJSON *arry, int count, ...); // Append item to the specified array/object. extern void cJSON_AddItemToArray(cJSON *arry, cJSON *item); extern void cJSON_InsertItemInArray(cJSON *arry, cJSON *item, int before); extern void cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item); // Remove/Detatch items from Arrays/Objects. extern cJSON *cJSON_DetachItemFromArray(cJSON *arry, int which); extern void cJSON_DeleteItemFromArray(cJSON *arry, int which); extern cJSON *cJSON_DetachItemFromObject(cJSON *object, const char *string); extern void cJSON_DeleteItemFromObject(cJSON *object, const char *string); // Clear all items from Arrays/Objects extern void cJSON_ClearItemsFromObject(cJSON *object); extern void cJSON_ClearItemsFromArray(cJSON *arry); // Update array items. extern void cJSON_ReplaceItemInArray(cJSON *arry, int which, cJSON *newitem); extern void cJSON_SwapItemsInArray(cJSON *arry, int item1, int item2); extern void cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem); // Convenience functions: Add item to object #define cJSON_AddNullToObject(object, name) cJSON_AddItemToObject(object, name, cJSON_CreateNull()) #define cJSON_AddTrueToObject(object, name) cJSON_AddItemToObject(object, name, cJSON_CreateTrue()) #define cJSON_AddFalseToObject(object, name) cJSON_AddItemToObject(object, name, cJSON_CreateFalse()) #define cJSON_AddBooleanToObject(object, name, b) cJSON_AddItemToObject(object, name, cJSON_CreateBoolean(b)) #define cJSON_AddIntegerToObject(object, name, i) cJSON_AddItemToObject(object, name, cJSON_CreateInteger(i)) #define cJSON_AddNumberToObject(object, name, n) cJSON_AddItemToObject(object, name, cJSON_CreateNumber(n)) #define cJSON_AddStringToObject(object, name, s) cJSON_AddItemToObject(object, name, cJSON_CreateString(s)) // Convenience functions: Add item to array #define cJSON_AddNullToArray(arry) cJSON_AddItemToArray(arry, cJSON_CreateNull()) #define cJSON_AddTrueToArray(arry) cJSON_AddItemToArray(arry, cJSON_CreateTrue()) #define cJSON_AddFalseToArray(arry) cJSON_AddItemToArray(arry, cJSON_CreateFalse()) #define cJSON_AddBooleanToArray(arry, b) cJSON_AddItemToArray(arry, cJSON_CreateBoolean(b)) #define cJSON_AddIntegerToArray(arry, i) cJSON_AddItemToArray(arry, cJSON_CreateInteger(i)) #define cJSON_AddNumberToArray(arry, n) cJSON_AddItemToArray(arry, cJSON_CreateNumber(n)) #define cJSON_AddStringToArray(arry, s) cJSON_AddItemToArray(arry, cJSON_CreateString(s)) // Value types extern int cJSON_IsNULL(cJSON *item); extern int cJSON_IsTrue(cJSON *item); extern int cJSON_IsFalse(cJSON *item); extern int cJSON_IsBoolean(cJSON *item); extern int cJSON_IsNumber(cJSON *item); extern int cJSON_IsString(cJSON *item); extern int cJSON_IsArray(cJSON *item); extern int cJSON_IsObject(cJSON *item); // Returns whether or not the cJSON entity is linked (part of an array or object). // Linked items cannot be deleted directly. Delete the array/object they're part of to delete them. extern int cJSON_IsLinked(cJSON *item); // Retrive values. If something goes wrong (wrong type, etc) the return value will be 0. extern int cJSON_ToBoolean(cJSON *item); extern double cJSON_ToNumber(cJSON *item); extern int cJSON_ToInteger(cJSON *item); extern const char * cJSON_ToString(cJSON *item); // Retreive values with default value (if they're of a wrong type or nonexistant) extern int cJSON_ToBooleanOpt(cJSON *item, int defval); extern double cJSON_ToNumberOpt(cJSON *item, double defval); extern int cJSON_ToIntegerOpt(cJSON *item, int defval); extern const char * cJSON_ToStringOpt(cJSON *item, const char *defval); // Retrive values directly. No type checking or default values. extern int cJSON_ToBooleanRaw(cJSON *item); extern double cJSON_ToNumberRaw(cJSON *item); extern int cJSON_ToIntegerRaw(cJSON *item); extern const char * cJSON_ToStringRaw(cJSON *item); // Set values (and change types) of cJSON entities extern void cJSON_SetStringValue(cJSON *item, const char *value); extern void cJSON_SetNumberValue(cJSON *item, double number); extern void cJSON_SetIntegerValue(cJSON *item, int integer); extern void cJSON_SetBooleanValue(cJSON *item, int boolean); extern void cJSON_SetNULLValue(cJSON *item); // JSON Stream Writer API extern cJSONStream *cJSON_Stream_New(int maxDepth, int formatted, size_t bufferInitSize, size_t bufferBlockSize); extern const char *cJSON_Stream_Finalize(cJSONStream *stream); extern void cJSON_Stream_WriteNull(cJSONStream *stream, const char *key); extern void cJSON_Stream_WriteTrue(cJSONStream *stream, const char *key); extern void cJSON_Stream_WriteFalse(cJSONStream *stream, const char *key); extern void cJSON_Stream_WriteBoolean(cJSONStream *stream, const char *key, int boolean); extern void cJSON_Stream_WriteString(cJSONStream *stream, const char *key, const char *string); extern void cJSON_Stream_WriteInteger(cJSONStream *stream, const char *key, int value); extern void cJSON_Stream_WriteNumber(cJSONStream *stream, const char *key, double value); extern void cJSON_Stream_BeginArray(cJSONStream *stream, const char *key); extern void cJSON_Stream_BeginObject(cJSONStream *stream, const char *key); extern void cJSON_Stream_EndBlock(cJSONStream *stream); #ifdef __cplusplus } #endif #endif
dionrhys/JAMasterServer
src/oob_cmds.h
<gh_stars>1-10 #ifndef _OOBCMDS_H #define _OOBCMDS_H #include "jams_local.h" void JAMS_Heartbeat(Command *cmd, NetAdr *from, Q3OobMsg *msg); void JAMS_StatusResponse(Command *cmd, NetAdr *from, Q3OobMsg *msg); void JAMS_GetServers(Command *cmd, NetAdr *from, Q3OobMsg *msg); #endif
dionrhys/JAMasterServer
src/Server.h
#ifndef _SERVER_H #define _SERVER_H #include "jams_local.h" // * Servers should be stored in the heap with chunked/adjustive allocation // (allocate more or less depending on traffic, needs some throttling of course) // * Server spaces should be allocated in chunks of 256/512/1024? // * A maximum amount of server spaces should be set? (16384/32768/65536?) // * Heartbeat challenges should be stored in a cyclic buffer of certain max size // Server entries typedef struct { bool inuse; NetAdr adr; time_t expireTime; // Timestamp of expiry int challenge; // Challenge key: master --> server --> master //char heartbeatIdent[64]; // Should be QuakeArena-1 for JKA int protocol; // JKA 1.01 is 26 } SVEntry; typedef struct { bool inuse; NetAdr adr; time_t expireTime; // Timestamp of expiry int challenge; // Challenge key: master --> server --> master } SVChallenge; /* * To register a server in the master server, the server must send a heartbeat packet first. * The master server will then send a getstatus request to the server with a random challenge number. * The server should then reply to the master server with a statusResponse packet. * If the statusResponse packet was received to the master server in a timely manner and the * challenge matches, the server is now registered on the master server. */ SVChallenge *SV_GetChallengeByNetAdr(NetAdr *adr, bool createIfNoMatch); SVEntry *SV_GetServerEntryByNetAdr(NetAdr *adr, bool createIfNoMatch); #endif
dionrhys/JAMasterServer
src/net.h
#ifndef _NET_H #define _NET_H #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #include <WinSock2.h> #include <WS2tcpip.h> #include <IPHlpApi.h> #pragma comment(lib, "Ws2_32.lib") #endif #ifdef __linux__ #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <netinet/in.h> #include <arpa/inet.h> #include <errno.h> #include <unistd.h> #include <fcntl.h> #endif //#include "NetAdr.h" //#include "Q3OobMsg.h" #if 0 /// NetAdrType - Possible host address types enum NetAdrType { ADR_BAD, //ADR_LOCAL, ADR_IP, ADR_IP6 }; /// NetAdr - Structure to uniquely identify a remote/local host // ** Please remember that UDP packets are totally insecure and can // ** be faked to appear to originate from any address/port! typedef struct { NetAdrType type; // addr and port are stored as HOST order here! union { unsigned long ip; unsigned char ip6[16]; } addr; unsigned short port; } NetAdr; #endif void NET_Init(const char *hostname, short port); void NET_Shutdown(); void NET_Frame(); void NET_SendPacket(NetAdr *to, const char *data, size_t length); void NET_HandlePacket(NetAdr *from, Q3OobMsg *msg); void NET_SendOobMsgf(NetAdr *to, const char *fmt, ...); #endif // !_NET_H
dionrhys/JAMasterServer
src/Q3OobMsg.h
<reponame>dionrhys/JAMasterServer<gh_stars>1-10 // todo comments // Q3OobMsg class for reading/writing Q3 oob messages #ifndef _Q3OOBMSG_H #define _Q3OOBMSG_H #include "jams_local.h" class Q3OobMsg { public: Q3OobMsg(char *data, size_t length); ~Q3OobMsg(); // General Methods size_t GetSize(); void SetSize(size_t newSize); size_t GetMaxSize(); size_t GetReadCount(); char *GetData(); bool Seek(int bytesToSeek); // Reading Methods char ReadByte(); //int16 ReadShort(); //int32 ReadLong(); //int64 ReadLongLong(); char *ReadStringLine(); // Writing Methods //void WriteBytes(uint8 *data, size_t length); private: char *m_data; size_t m_maxSize; size_t m_size; size_t m_readCount; char m_tempString[1024]; // for ReadStringLine }; #endif
dionrhys/JAMasterServer
src/utils.h
#ifndef _UTILS_H #define _UTILS_H // strncpy with guaranteed trailing zero void Strncpyz(char *dest, const char *src, size_t destsize); // strcat with guaranteed trailing zero void Strcat(char *dest, const char *src, size_t destsize); // Compare two strings case-sensitive int Strcmp(const char *s1, const char *s2); // Compare two strings case-sensitive up to 'count' characters int Strncmp(const char *s1, const char *s2, size_t count); // Compare two strings case-insensitive int Stricmp(const char *s1, const char *s2); // Compare two strings case-insensitive up to 'count' characters int Strnicmp(const char *s1, const char *s2, size_t count); #endif // !_UTILS_H
dionrhys/JAMasterServer
src/jams_local.h
<reponame>dionrhys/JAMasterServer<gh_stars>1-10 #ifndef _JAMS_LOCAL_H #define _JAMS_LOCAL_H /** * Notes * * - On Windows, the window title should show current registered servers :) * - On *nix, handle signals to shutdown the server gracefully * - On Windows, use a control handler to shutdown * - Colour console output on both platforms * - Windows version is made for MSVC, Linux build is made for gcc * (I personally can't help you if you use other tools) * - Both 32-bit and 64-bit architectures are supported * - TODO: Support daemonising on all platforms * - TODO: Support logging (console, file, syslog, etc.) * * Signals (based on Polipo's handling) * SIGHUP Shutdown gracefully * SIGTERM Shutdown gracefully * SIGINT Shutdown gracefully * SIGUSR1 Write memory to disk (don't discard), reopen log file, reload configuration * SIGUSR2 Write memory to disk (discard from memory), reopen log file, reload configuration */ #define JAMS_NAME "JAMasterServer" #define JAMS_VERSION "r1" #if defined(_WIN32) // OS-dependent libraries/includes #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <winsock2.h> // Confound this warning, it drives me to insomnia // http://msdn.microsoft.com/en-us/library/ttcz0bys.aspx #ifdef _DEBUG #pragma warning(disable:4996) #endif // Define the OS and Arch identifier (only needed for diagnostics/info) #ifdef _WIN64 #define JAMS_OS "win64" #if defined(_M_X64) #define JAMS_ARCH "x64" #elif defined(_M_IA64) #define JAMS_ARCH "Itanium" #else #define JAMS_ARCH "UnknownArch" #endif #else // We already know _WIN32 is defined #define JAMS_OS "win32" #if defined(_M_IX86) /*_X86_*/ #define JAMS_ARCH "x86" #else #define JAMS_ARCH "UnknownArch" #endif #endif // _WIN64 // Define debug marker for info #ifdef _DEBUG #define JAMS_DEBUGBUILD "debug" // JAMS_DEUGBUILD can be treated as a pointer (0/NULL if not debug) #else #define JAMS_DEBUGBUILD 0 #endif // _DEBUG #elif defined(__linux__) // OS-dependent libraries/includes #include <sys/types.h> #include <unistd.h> /* Need to define OS and Arch identifiers for Linux systems, I have no clue how to do that... */ #define JAMS_OS "linux" #define JAMS_ARCH "UnknownArch" #endif // Standard Libraries #include <stdlib.h> #include <stdio.h> #include <string.h> #include <time.h> #include <stdarg.h> #include <assert.h> #include <string> int JAMS_Main(void); //int JAMS_LoadConfig(void); // TODO: Sort this mess.. #include "cJSON.h" #include "Command.h" #include "InfoString.h" #include "NetAdr.h" #include "Q3OobMsg.h" #include "net.h" // depends on NetAdr and Q3OobMsg #include "oob_cmds.h" #include "platform.h" #include "rcon.h" #include "Server.h" #include "utils.h" //================================================== // Common Code //================================================== // JAMS default configuration values #define JAMS_DEFAULT_CONFIG "jams.json" #define JAMS_DEFAULT_SVTIMEOUT 300 #define JAMS_DEFAULT_PORT 29060 //#define JAMS_DEFAULT_FLOODDELAY (JAMS_DEFAULT_SVTIMEOUT-30) #define JAMS_DEFAULT_FLOODDELAY 60 // More lenient, allows people who are testing server setups // to close/start servers and see changes promptly #define JAMS_DEFAULT_CHALLENGETIMEOUT 10 typedef struct { /*** OPTIONS **************************************/ // Configuration filename to read/write (malloced - not yet!) //char *configFilename; char configFilename[256]; // Listening port short port; // Listening address (empty string = any interface) char hostname[256]; // Rcon password (empty string = rcon disabled) // Limited to 255 characters for consistency with JKA char rconPassword[256]; // Server heartbeat timeout (in seconds) // The server will be de-registered if no heartbeat is received within // this time int svTimeout; // Minimum wait time between heartbeats (in seconds) // The server will be de-registered if it gave us a heartbeat before this // time (flood protection) int floodDelay; // Server challenge response timeout (in seconds) // The server will be de-registered after a heartbeat if it didn't // respond with this time (servers send a heartbeat when they shutdown) int challengeTimeout; /**************************************************/ SVEntry servers[16834]; // fixed-size array used for testing! Implement properly later. int nextChallenge; SVChallenge challenges[1024]; /** * Structure to hold all the configuration options after loading. * See config.h for the actual table of configuration options. */ struct { std::string hostname; int port; std::string rconPassword; int svTimeout; int floodDelay; int challengeTimeout; bool daemonize; bool useLogFile; std::string logFile; bool useSyslog; std::string lockFile; } config; } jamsLocal_t; extern jamsLocal_t jams; #include "config.h" #endif
hexiaole1994/llvm-frontend-pl0e
pl0e-jit.h
#ifndef LLVM_EXECUTIONENGINE_ORC_PL0JIT_H #define LLVM_EXECUTIONENGINE_ORC_PL0JIT_H #include "llvm/ADT/STLExtras.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/Mangler.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Support/DynamicLibrary.h" #include "llvm/Support/raw_ostream.h" #include "llvm/ExecutionEngine/JITSymbol.h" #include "llvm/ExecutionEngine/SectionMemoryManager.h" #include "llvm/ExecutionEngine/RTDyldMemoryManager.h" #include "llvm/ExecutionEngine/ExecutionEngine.h" #include "llvm/ExecutionEngine/Orc/LambdaResolver.h" #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h" #include "llvm/ExecutionEngine/Orc/CompileUtils.h" #include "llvm/ExecutionEngine/Orc/IRCompileLayer.h" #include <memory> #include <string> #include <vector> #include <algorithm> namespace llvm { namespace orc { class Pl0JIT { private: std::unique_ptr<TargetMachine> TM; const DataLayout DL; RTDyldObjectLinkingLayer ObjectLayer; IRCompileLayer<decltype(ObjectLayer),SimpleCompiler> CompileLayer; public: using ModuleHandle = decltype(CompileLayer)::ModuleHandleT; Pl0JIT():TM(EngineBuilder().selectTarget()),DL(TM->createDataLayout()),ObjectLayer([](){return std::make_shared<SectionMemoryManager>();}),CompileLayer(ObjectLayer,SimpleCompiler(*TM)) { llvm::sys::DynamicLibrary::LoadLibraryPermanently(nullptr); } TargetMachine& getTargetMachine(){ return *TM;} ModuleHandle addModule(std::unique_ptr<Module> M) { auto Resolver = createLambdaResolver( [&](const std::string& Name) { auto Sym = CompileLayer.findSymbol(Name,false); if(!Sym) return JITSymbol(nullptr); return Sym; } , [](const std::string& Name) { auto SymAddr = RTDyldMemoryManager::getSymbolAddressInProcess(Name); if(!SymAddr) return JITSymbol(nullptr); return JITSymbol(SymAddr,JITSymbolFlags::Exported); } ); return cantFail(CompileLayer.addModule(std::move(M),std::move(Resolver))); } JITSymbol findSymbol(const std::string Name) { std::string MangledName; raw_string_ostream MangledNameStream(MangledName); Mangler::getNameWithPrefix(MangledNameStream,Name,DL); return CompileLayer.findSymbol(MangledNameStream.str(),true); } JITTargetAddress getSymbolAddress(const std::string Name) { return cantFail(findSymbol(Name).getAddress()); } void removeModule(ModuleHandle H) { cantFail(CompileLayer.removeModule(H)); } }; }//end of namespace orc }//end of namespace llvm #endif
hexiaole1994/llvm-frontend-pl0e
pl0e-lib.c
<reponame>hexiaole1994/llvm-frontend-pl0e //===------------------------------------------------===// // The library for running the generated object file // Usage: see readme file for details //===-----------------------------------------------===// #include <stdio.h> #include <math.h> void putf(double val) { printf("%lf",val); } void puti(int val) { printf("%d",val); } void getf(double* var) { scanf("%lf",var); } void geti(int* var) { scanf("%d",var); } void putch(char c) { printf("%c",c); } int getrem(int a,int b) { return a%b; }
atbj505/WebSocket
Socket/Socket/RYWebSocketManager.h
<filename>Socket/Socket/RYWebSocketManager.h // // RYWebSocketManager.h // Socket // // Created by Robert on 2017/3/11. // Copyright © 2017年 Robert. All rights reserved. // #import <Foundation/Foundation.h> @interface RYWebSocketManager : NSObject + (instancetype)shareInstance; - (void)connect; - (void)disConnect; - (void)sendMsg:(NSString *)msg; - (void)ping; @end
atbj505/WebSocket
Socket/Socket/RYSocketManager.h
<reponame>atbj505/WebSocket<gh_stars>0 // // RYSocketManager.h // Socket // // Created by Robert on 2017/1/11. // Copyright © 2017年 Robert. All rights reserved. // #import <Foundation/Foundation.h> @interface RYSocketManager : NSObject + (instancetype)shareInstance; - (void)connect; - (void)disConnect; - (void)sendMsg:(NSString *)msg; @end
atbj505/WebSocket
Socket/Socket/ViewController.h
<gh_stars>0 // // ViewController.h // Socket // // Created by Robert on 2017/1/11. // Copyright © 2017年 Robert. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end
dvdmuckle/musikcube
src/musikcube/cursespp/Colors.h
////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2017 musikcube team // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the author nor the names of other contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////////// #pragma once #include "curses_config.h" #define CURSESPP_DEFAULT_COLOR -1LL #define CURSESPP_SELECTED_LIST_ITEM 1 #define CURSESPP_HIGHLIGHTED_LIST_ITEM 2 #define CURSESPP_HIGHLIGHTED_ERROR_LIST_ITEM 3 #define CURSESPP_HIGHLIGHTED_SELECTED_LIST_ITEM 4 #define CURSESPP_LIST_ITEM_HEADER 5 #define CURSESPP_LIST_ITEM_HIGHLIGHTED_HEADER 6 #define CURSESPP_DEFAULT_CONTENT_COLOR 7 #define CURSESPP_DEFAULT_FRAME_COLOR 8 #define CURSESPP_FOCUSED_FRAME_COLOR 9 #define CURSESPP_TEXT_DEFAULT 10 #define CURSESPP_TEXT_DISABLED 11 #define CURSESPP_TEXT_FOCUSED 12 #define CURSESPP_TEXT_ACTIVE 13 #define CURSESPP_TEXT_WARNING 14 #define CURSESPP_TEXT_ERROR 15 #define CURSESPP_TEXT_HIDDEN 16 #define CURSESPP_BUTTON_NORMAL 17 #define CURSESPP_BUTTON_HIGHLIGHTED 18 #define CURSESPP_SHORTCUT_ROW_NORMAL 19 #define CURSESPP_SHORTCUT_ROW_FOCUSED 20 #define CURSESPP_OVERLAY_FRAME 21 #define CURSESPP_OVERLAY_CONTENT 22 #define CURSESPP_OVERLAY_INPUT_FRAME 23 #define CURSESPP_OVERLAY_TEXT_FOCUSED 24 #define CURSESPP_BANNER 25 #define CURSESPP_FOOTER 26 namespace cursespp { class Colors { private: Colors(); public: enum Mode { RGB, Palette, Basic }; enum BgType { Theme, Inherit, }; static void Init(Mode mode = Mode::Basic, BgType bgType = BgType::Theme); static void SetTheme(const std::string& fn); }; }
dvdmuckle/musikcube
src/core/sdk/ISchema.h
<filename>src/core/sdk/ISchema.h ////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2017 musikcube team // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the author nor the names of other contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////////// #pragma once #include <stddef.h> #include <float.h> #include <climits> #include <vector> #include <memory> #include <string> #include <cstring> namespace musik { namespace core { namespace sdk { class ISchema { public: enum class Type { Bool, Int, Double, String, Enum }; struct Entry { Type type; const char* name; }; struct BoolEntry { Entry entry; bool defaultValue; }; struct IntEntry { Entry entry; int minValue; int maxValue; int defaultValue; }; struct DoubleEntry { Entry entry; double minValue; double maxValue; int precision; double defaultValue; }; struct StringEntry { Entry entry; const char* defaultValue; }; struct EnumEntry { Entry entry; size_t count; const char** values; const char* defaultValue; }; virtual void Release() = 0; virtual size_t Count() = 0; virtual const Entry* At(size_t index) = 0; }; template <typename T = ISchema> class TSchema: public ISchema { public: virtual ~TSchema() { for (auto it : this->entries) { switch (it->type) { case Type::String: { StringEntry* entry = reinterpret_cast<StringEntry*>(it); FreeString(entry->defaultValue); break; } case Type::Enum: { EnumEntry* entry = reinterpret_cast<EnumEntry*>(it); FreeString(entry->defaultValue); FreeStringList(entry->values, entry->count); break; } default: break; } FreeString(it->name); delete it; } } virtual void Release() override { delete this; } virtual size_t Count() override { return entries.size(); } virtual const Entry* At(size_t index) override { return entries[index]; } TSchema& AddBool(const std::string& name, bool defaultValue) { auto entry = new BoolEntry(); entry->entry.type = ISchema::Type::Bool; entry->entry.name = AllocString(name); entry->defaultValue = defaultValue; entries.push_back(reinterpret_cast<Entry*>(entry)); return *this; } TSchema& AddInt( const std::string& name, int defaultValue, int min = INT_MIN, int max = INT_MAX) { auto entry = new IntEntry(); entry->entry.type = ISchema::Type::Int; entry->entry.name = AllocString(name); entry->defaultValue = defaultValue; entry->minValue = min; entry->maxValue = max; entries.push_back(reinterpret_cast<Entry*>(entry)); return *this; } TSchema& AddDouble( const std::string& name, double defaultValue, int precision = 2, double min = DBL_MIN, double max = DBL_MAX) { auto entry = new DoubleEntry(); entry->entry.type = ISchema::Type::Double; entry->entry.name = AllocString(name); entry->defaultValue = defaultValue; entry->precision = precision; entry->minValue = min; entry->maxValue = max; entries.push_back(reinterpret_cast<Entry*>(entry)); return *this; } TSchema& AddString(const std::string& name, const std::string& defaultValue) { auto entry = new StringEntry(); entry->entry.type = ISchema::Type::String; entry->entry.name = AllocString(name); entry->defaultValue = AllocString(defaultValue); entries.push_back(reinterpret_cast<Entry*>(entry)); return *this; } TSchema& AddEnum( const std::string& name, const std::vector<std::string>&& values, const std::string& defaultValue) { auto entry = new EnumEntry(); entry->entry.type = ISchema::Type::Enum; entry->entry.name = AllocString(name); entry->defaultValue = AllocString(defaultValue); entry->count = values.size(); entry->values = AllocStringList(values); entries.push_back(reinterpret_cast<Entry*>(entry)); return *this; } private: const char** AllocStringList(const std::vector<std::string>& values) { const char** result = new const char*[values.size()]; for (size_t i = 0; i < values.size(); i++) { result[i] = AllocString(values[i]); } return result; } void FreeStringList(const char** values, size_t count) { for (size_t i = 0; i < count; i++) { FreeString(values[i]); } delete[] values; } const char* AllocString(const std::string& str) { char* result = new char[str.size() + 1]; #ifdef WIN32 strncpy_s(result, str.size() + 1, str.c_str(), str.size()); #else strncpy(result, str.c_str(), str.size()); #endif result[str.size()] = 0; return result; } void FreeString(const char* str) { delete[] str; } std::vector<Entry*> entries; }; } } }
dvdmuckle/musikcube
src/musikcube/app/version.h
<filename>src/musikcube/app/version.h #pragma once #include <string> #define VERSION_MAJOR 0 #define VERSION_MINOR 51 #define VERSION_PATCH 0 #define VERSION "0.51.0" namespace musik { namespace cube { static inline std::string userAgent() { #ifdef WIN32 static const std::string PLATFORM = "win32"; #elif defined __APPLE__ static const std::string PLATFORM = "macos"; #else static const std::string PLATFORM = "linux"; #endif return "musikcube " + std::to_string(VERSION_MAJOR) + "." + std::to_string(VERSION_MINOR) + "." + std::to_string(VERSION_PATCH) + "(" + PLATFORM + ")"; } } }
dvdmuckle/musikcube
src/core/sdk/HttpClient.h
////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2017 musikcube team // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the author nor the names of other contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////////// #include <curl/curl.h> #include <thread> #include <mutex> #include <unordered_map> #include <set> #include "constants.h" namespace musik { namespace core { namespace sdk { template <typename T> class HttpClient: public std::enable_shared_from_this<HttpClient<T>> { public: enum class Thread { Current, Background }; enum class HttpMethod { Get, Post }; using HttpHeaders = std::unordered_map<std::string, std::string>; using Callback = std::function<void(HttpClient<T>* caller, int, CURLcode)>; using DecoratorCallback = std::function<void(CURL*)>; using HeaderCallback = std::function<void(std::string, std::string)>; using CanceledCallback = std::function<void(HttpClient<T>* caller)>; static std::shared_ptr<HttpClient<T>> Create(T&& stream) { return std::shared_ptr<HttpClient<T>>(new HttpClient<T>(std::move(stream))); } ~HttpClient(); HttpClient<T>& Url(const std::string& url); HttpClient<T>& Header(const std::string& key, const std::string& value); HttpClient<T>& Headers(HeaderCallback headersCb); HttpClient<T>& Decorator(DecoratorCallback decoratorCb); HttpClient<T>& Canceled(CanceledCallback canceledCb); HttpClient<T>& Mode(Thread mode); HttpClient<T>& PostBody(const std::string& postBody); HttpClient<T>& Method(HttpMethod mode); HttpClient<T>& UserAgent(const std::string& userAgent); const T& Stream() const { return this->ostream; } const HttpHeaders& ResponseHeaders() const { return this->responseHeaders; } const HttpHeaders& RequestHeaders() const { return this->requestHeaders; } const std::string& Url() const { return this->url; } HttpClient<T>& Run(Callback callback = Callback()); void Wait(); void Cancel(); private: HttpClient(T&& stream); static size_t CurlWriteCallback(char *ptr, size_t size, size_t nmemb, void *userdata); static int CurlTransferCallback(void *ptr, curl_off_t downTotal, curl_off_t downNow, curl_off_t upTotal, curl_off_t upNow); static size_t CurlHeaderCallback(char *buffer, size_t size, size_t nitems, void *userdata); static std::string DefaultUserAgent(); static void ReplaceAll(std::string& input, const std::string& find, const std::string& replace); static std::string Trim(const std::string &str); void RunOnCurrentThread(Callback callback); std::mutex mutex; std::shared_ptr<std::thread> thread; T ostream; std::string url; std::string postBody; std::string userAgent; HttpHeaders requestHeaders, responseHeaders; HeaderCallback headersCb; DecoratorCallback decoratorCb; CanceledCallback canceledCallback; bool cancel; Thread mode{ Thread::Background }; HttpMethod method{ HttpMethod::Get }; CURL* curl; static std::mutex instanceMutex; static std::set<std::shared_ptr<HttpClient<T>>> instances; }; template <typename T> std::mutex HttpClient<T>::instanceMutex; template <typename T> std::set<std::shared_ptr<HttpClient<T>>> HttpClient<T>::instances; template <typename T> std::string HttpClient<T>::DefaultUserAgent() { #ifdef WIN32 static const std::string PLATFORM = "win32"; #elif defined __APPLE__ static const std::string PLATFORM = "macos"; #else static const std::string PLATFORM = "linux"; #endif return "musikcore sdk " + std::to_string(SdkVersion) + "." + "(" + PLATFORM + ")"; } template <typename T> size_t HttpClient<T>::CurlWriteCallback(char *ptr, size_t size, size_t nmemb, void *userdata) { if (ptr && userdata) { HttpClient* context = static_cast<HttpClient*>(userdata); if (context->cancel) { return 0; /* aborts */ } context->ostream.write(ptr, size * nmemb); } return size * nmemb; } template <typename T> int HttpClient<T>::CurlTransferCallback( void *ptr, curl_off_t downTotal, curl_off_t downNow, curl_off_t upTotal, curl_off_t upNow) { HttpClient* context = static_cast<HttpClient*>(ptr); if (context->cancel) { return -1; /* kill the stream */ } return 0; /* ok! */ } template <typename T> /* copied from Common.h for SDK usage. */ void HttpClient<T>::ReplaceAll(std::string& input, const std::string& find, const std::string& replace) { size_t pos = input.find(find); while (pos != std::string::npos) { input.replace(pos, find.size(), replace); pos = input.find(find, pos + replace.size()); } } template <typename T> std::string HttpClient<T>::Trim(const std::string &str) { std::string s(str); s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); return s; } template <typename T> size_t HttpClient<T>::CurlHeaderCallback(char *buffer, size_t size, size_t nitems, void *userdata) { HttpClient* stream = static_cast<HttpClient*>(userdata); std::string header(buffer, size * nitems); ReplaceAll(header, "\r\n", ""); size_t splitAt = header.find_first_of(":"); if (splitAt != std::string::npos) { std::string key = Trim(header.substr(0, splitAt)); std::string value = Trim(header.substr(splitAt + 1)); stream->responseHeaders[key] = value; if (stream->headersCb) { stream->headersCb(key, value); } } return size * nitems; } template <typename T> HttpClient<T>::HttpClient(T&& stream) { this->curl = nullptr; this->cancel = false; std::swap(this->ostream, stream); } template <typename T> HttpClient<T>::~HttpClient() { std::unique_lock<std::mutex> lock(this->mutex); if (this->curl) { curl_easy_cleanup(this->curl); } if (this->thread && this->thread->joinable()) { this->cancel = true; this->thread->join(); } } template <typename T> HttpClient<T>& HttpClient<T>::Run(Callback callback) { std::unique_lock<std::mutex> lock(this->mutex); if (this->thread) { throw std::runtime_error("already started"); } this->curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_HEADER, 0); curl_easy_setopt(curl, CURLOPT_HTTPGET, 1); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(curl, CURLOPT_AUTOREFERER, 1); curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1); curl_easy_setopt(curl, CURLOPT_USERAGENT, DefaultUserAgent().c_str()); curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0); curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0); curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 3000); curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, 7500); curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 500); if (this->decoratorCb) { this->decoratorCb(this->curl); } curl_easy_setopt(curl, CURLOPT_WRITEDATA, this); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &CurlWriteCallback); curl_easy_setopt(curl, CURLOPT_XFERINFODATA, this); curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, &CurlTransferCallback); curl_easy_setopt(curl, CURLOPT_HEADERDATA, this); curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, &CurlHeaderCallback); #if 0 curl_easy_setopt(curl, CURLOPT_PROXY, "http://localhost"); curl_easy_setopt(curl, CURLOPT_PROXYPORT, 8080); #endif if (this->requestHeaders.size()) { struct curl_slist* slist = nullptr; for (auto it : this->requestHeaders) { std::string header = it.first + ": " + it.second; slist = curl_slist_append(slist, header.c_str()); } curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist); } if (this->method == HttpMethod::Post) { curl_easy_setopt(curl, CURLOPT_POST, 1L); if (this->postBody.size()) { curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS, this->postBody.c_str()); } } if (mode == Thread::Background) { std::unique_lock<std::mutex> lock(instanceMutex); instances.insert(this->shared_from_this()); this->thread.reset(new std::thread([callback, this] { this->RunOnCurrentThread(callback); })); } else { this->RunOnCurrentThread(callback); } return *this; } template <typename T> void HttpClient<T>::RunOnCurrentThread(Callback callback) { CURLcode curlCode = curl_easy_perform(this->curl); if (this->cancel) { if (this->canceledCallback) { this->canceledCallback(this); } } int httpStatus = 0; curl_easy_getinfo(this->curl, CURLINFO_RESPONSE_CODE, &httpStatus); if (callback) { callback(this, httpStatus, curlCode); } if (this->thread) { this->thread->detach(); this->thread.reset(); } { std::unique_lock<std::mutex> lock(instanceMutex); instances.erase(instances.find(this->shared_from_this())); } } template <typename T> void HttpClient<T>::Wait() { std::unique_lock<std::mutex> lock(this->mutex); if (this->thread && this->thread->joinable()) { this->thread->join(); } } template <typename T> HttpClient<T>& HttpClient<T>::Url(const std::string& url) { this->url = url; return *this; } template <typename T> HttpClient<T>& HttpClient<T>::PostBody(const std::string& postBody) { this->postBody = postBody; return *this; } template <typename T> HttpClient<T>& HttpClient<T>::Mode(Thread mode) { this->mode = mode; return *this; } template <typename T> HttpClient<T>& HttpClient<T>::Method(HttpMethod method) { this->method = method; return *this; } template <typename T> HttpClient<T>& HttpClient<T>::UserAgent(const std::string& userAgent) { this->userAgent = userAgent; return *this; } template <typename T> HttpClient<T>& HttpClient<T>::Header(const std::string& key, const std::string& value) { this->requestHeaders[key] = value; return *this; } template <typename T> HttpClient<T>& HttpClient<T>::Headers(HeaderCallback headersCb) { this->headersCb = headersCb; return *this; } template <typename T> HttpClient<T>& HttpClient<T>::Decorator(DecoratorCallback decoratorCb) { this->decoratorCb = decoratorCb; return *this; } template <typename T> HttpClient<T>& HttpClient<T>::Canceled(CanceledCallback canceledCb) { this->canceledCb = canceledCb; return *this; } template <typename T> void HttpClient<T>::Cancel() { std::unique_lock<std::mutex> lock(this->mutex); if (this->thread) { this->cancel = true; if (this->thread->joinable()) { this->thread->join(); } } } } } }
dvdmuckle/musikcube
src/musikcube/app/layout/MainLayout.h
<gh_stars>0 ////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2017 musikcube team // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the author nor the names of other contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////////// #pragma once #include <cursespp/App.h> #include <cursespp/LayoutBase.h> #include <cursespp/TextInput.h> #include <cursespp/TextLabel.h> #include <cursespp/ShortcutsWindow.h> #include <cursespp/IViewRoot.h> #include <core/audio/PlaybackService.h> #include <core/support/Preferences.h> #include <core/library/ILibrary.h> #include <core/runtime/IMessageTarget.h> #include <core/audio/MasterTransport.h> #include "ITopLevelLayout.h" #include <sigslot/sigslot.h> namespace musik { namespace cube { class MainLayout : public cursespp::LayoutBase, public cursespp::IViewRoot, #if (__clang_major__ == 7 && __clang_minor__ == 3) public std::enable_shared_from_this<MainLayout>, #endif public sigslot::has_slots<> { public: MainLayout( cursespp::App& app, musik::core::audio::PlaybackService& playback, musik::core::ILibraryPtr library); virtual ~MainLayout(); void Start(); void Stop(); virtual bool KeyPress(const std::string& key) override; virtual void OnLayout() override; virtual cursespp::IWindowPtr GetFocus() override; virtual cursespp::IWindowPtr FocusNext() override; virtual cursespp::IWindowPtr FocusPrev() override; virtual void ResizeToViewport() override; virtual void ProcessMessage(musik::core::runtime::IMessage &message) override; void SetMainLayout(std::shared_ptr<cursespp::LayoutBase> layout); private: void OnIndexerStarted(); void OnIndexerProgress(int count); void OnIndexerFinished(int count); void Initialize(); void RunUpdateCheck(); void EnableDemoModeIfNecessary(); cursespp::IWindowPtr BlurShortcuts(); void FocusShortcuts(); std::shared_ptr<musik::core::Preferences> prefs; std::shared_ptr<cursespp::ShortcutsWindow> shortcuts; std::shared_ptr<cursespp::LayoutBase> layout; std::shared_ptr<cursespp::TextLabel> syncing; std::shared_ptr<cursespp::LayoutBase> consoleLayout; std::shared_ptr<cursespp::LayoutBase> libraryLayout; std::shared_ptr<cursespp::LayoutBase> settingsLayout; std::shared_ptr<cursespp::LayoutBase> hotkeysLayout; std::shared_ptr<cursespp::TextLabel> hotkey; musik::core::ILibraryPtr library; cursespp::IWindowPtr lastFocus; ITopLevelLayout* topLevelLayout; bool shortcutsFocused; int syncUpdateCount; }; } }
ipasimulator/libobjc2
asmconstants.h
#ifdef __LP64__ #define DTABLE_OFFSET 64 #define SMALLOBJ_BITS 3 #define SHIFT_OFFSET 0 #define DATA_OFFSET 8 #define SLOT_OFFSET 32 #else #define DTABLE_OFFSET 32 #define SMALLOBJ_BITS 1 #define SHIFT_OFFSET 0 #define DATA_OFFSET 8 #define SLOT_OFFSET 16 #endif #define SMALLOBJ_MASK ((1<<SMALLOBJ_BITS) - 1)
ipasimulator/libobjc2
lock.h
<filename>lock.h<gh_stars>1-10 /** * libobjc requires recursive mutexes. These are delegated to the underlying * threading implementation. This file contains a VERY thin wrapper over the * Windows and POSIX mutex APIs. */ #ifndef __LIBOBJC_LOCK_H_INCLUDED__ #define __LIBOBJC_LOCK_H_INCLUDED__ #ifdef WIN32 #define BOOL _WINBOOL # include <windows.h> #undef BOOL typedef CRITICAL_SECTION mutex_t; # define INIT_LOCK(x) InitializeCriticalSection(&(x)) # define LOCK(x) EnterCriticalSection(x) # define UNLOCK(x) LeaveCriticalSection(x) # define DESTROY_LOCK(x) DeleteCriticalSection(x) #else # include <pthread.h> typedef pthread_mutex_t mutex_t; // If this pthread implementation has a static initializer for recursive // mutexes, use that, otherwise fall back to the portable version # ifdef PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP # define INIT_LOCK(x) x = (pthread_mutex_t)PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP # elif defined(PTHREAD_RECURSIVE_MUTEX_INITIALIZER) # define INIT_LOCK(x) x = (pthread_mutex_t)PTHREAD_RECURSIVE_MUTEX_INITIALIZER # else # define INIT_LOCK(x) init_recursive_mutex(&(x)) static inline void init_recursive_mutex(pthread_mutex_t *x) { pthread_mutexattr_t recursiveAttributes; pthread_mutexattr_init(&recursiveAttributes); pthread_mutexattr_settype(&recursiveAttributes, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(x, &recursiveAttributes); pthread_mutexattr_destroy(&recursiveAttributes); } # endif # define LOCK(x) pthread_mutex_lock(x) # define UNLOCK(x) pthread_mutex_unlock(x) # define DESTROY_LOCK(x) pthread_mutex_destroy(x) #endif __attribute__((unused)) static void objc_release_lock(void *x) { mutex_t *lock = *(mutex_t**)x; UNLOCK(lock); } /** * Acquires the lock and automatically releases it at the end of the current * scope. */ #define LOCK_FOR_SCOPE(lock) \ __attribute__((cleanup(objc_release_lock)))\ __attribute__((unused)) mutex_t *lock_pointer = lock;\ LOCK(lock) /** * The global runtime mutex. */ extern mutex_t runtime_mutex; #define LOCK_RUNTIME() LOCK(&runtime_mutex) #define UNLOCK_RUNTIME() UNLOCK(&runtime_mutex) #define LOCK_RUNTIME_FOR_SCOPE() LOCK_FOR_SCOPE(&runtime_mutex) #endif // __LIBOBJC_LOCK_H_INCLUDED__
ipasimulator/libobjc2
loader.c
#include <stdlib.h> #include <assert.h> #include "objc/runtime.h" #include "objc/objc-auto.h" #include "objc/objc-arc.h" #include "lock.h" #include "loader.h" #include "visibility.h" #ifdef ENABLE_GC #include <gc/gc.h> #endif #include <stdio.h> /** * Runtime lock. This is exposed in */ PRIVATE mutex_t runtime_mutex; LEGACY void *__objc_runtime_mutex = &runtime_mutex; void init_alias_table(void); void init_arc(void); void init_class_tables(void); void init_dispatch_tables(void); void init_gc(void); void init_protocol_table(void); void init_selector_tables(void); void init_trampolines(void); void objc_send_load_message(Class class); void log_selector_memory_usage(void); static void log_memory_stats(void) { log_selector_memory_usage(); } /* Number of threads that are alive. */ int __objc_runtime_threads_alive = 1; /* !T:MUTEX */ // libdispatch hooks for registering threads __attribute__((weak)) void (*dispatch_begin_thread_4GC)(void); __attribute__((weak)) void (*dispatch_end_thread_4GC)(void); __attribute__((weak)) void *(*_dispatch_begin_NSAutoReleasePool)(void); __attribute__((weak)) void (*_dispatch_end_NSAutoReleasePool)(void *); void __objc_load_module(struct objc_module_abi_8 *module) { static BOOL first_run = YES; // Check that this module uses an ABI version that we recognise. // In future, we should pass the ABI version to the class / category load // functions so that we can change various structures more easily. assert(objc_check_abi_version(module)); if (first_run) { #if ENABLE_GC init_gc(); #endif // Create the main runtime lock. This is not safe in theory, but in // practice the first time that this function is called will be in the // loader, from the main thread. Future loaders may run concurrently, // but that is likely to break the semantics of a lot of languages, so // we don't have to worry about it for a long time. // // The only case when this can potentially go badly wrong is when a // pure-C main() function spawns two threads which then, concurrently, // call dlopen() or equivalent, and the platform's implementation of // this does not perform any synchronization. INIT_LOCK(runtime_mutex); // Create the various tables that the runtime needs. init_selector_tables(); init_protocol_table(); init_class_tables(); init_dispatch_tables(); init_alias_table(); init_arc(); init_trampolines(); first_run = NO; if (dispatch_begin_thread_4GC != 0) { dispatch_begin_thread_4GC = objc_registerThreadWithCollector; } if (dispatch_end_thread_4GC != 0) { dispatch_end_thread_4GC = objc_unregisterThreadWithCollector; } if (_dispatch_begin_NSAutoReleasePool != 0) { _dispatch_begin_NSAutoReleasePool = objc_autoreleasePoolPush; } if (_dispatch_end_NSAutoReleasePool != 0) { _dispatch_end_NSAutoReleasePool = objc_autoreleasePoolPop; } } // The runtime mutex is held for the entire duration of a load. It does // not need to be acquired or released in any of the called load functions. LOCK_RUNTIME_FOR_SCOPE(); struct objc_symbol_table_abi_8 *symbols = module->symbol_table; // Register all of the selectors used in this module. if (symbols->selectors) { if (module->version < 11) { // the module has the old selector format objc_register_selector_array8(symbols->selectors, symbols->selector_count); } else { objc_register_selector_array(symbols->selectors, symbols->selector_count); } } unsigned short defs = 0; // Load the classes from this module for (unsigned short i=0 ; i<symbols->class_count ; i++) { objc_load_class(symbols->definitions[defs++]); } // Load the categories from this module for (unsigned short i=0 ; i<symbols->category_count; i++) { objc_try_load_category(symbols->definitions[defs++]); } // Load the static instances struct objc_static_instance_list **statics = (void*)symbols->definitions[defs]; while (NULL != statics && NULL != *statics) { objc_init_statics(*(statics++)); } // Load categories and statics that were deferred. objc_load_buffered_categories(); objc_init_buffered_statics(); } void __objc_resolve_module(struct objc_module_abi_8 *module) { LOCK_RUNTIME_FOR_SCOPE(); // Fix up the class links for loaded classes. objc_resolve_class_links(); if (NULL != module) { struct objc_symbol_table_abi_8 *symbols = module->symbol_table; unsigned int category_start = symbols->class_count; for (unsigned short i=0 ; i<symbols->category_count; i++) { struct objc_category *cat = (struct objc_category*) symbols->definitions[category_start++]; Class class = (Class)objc_getClass(cat->class_name); if ((Nil != class) && objc_test_class_flag(class, objc_class_flag_resolved)) { objc_send_load_message(class); } } } } #ifdef WINOBJC // WinObjC breaks loading into two deterministic stages: class registration // and class resolution. The original GNUstep ABI as implemented in Clang // emits calls to __objc_exec_class into the user static init section, // interleaving them with other static initializers and subjecting them to // static initialization ordering issues. +load can therefore be called on one class // when another class's module hasn't even been registered. // The WinObjC ABI preferentially emits objc_module_abi_8*s into a binary section // that's then registered and resolved (in that order) once on load. // // For backwards compatibility, however, it must support __objc_exec_class-based registration. // To do so, this code batches all executed modules into a linked list for future resolution. // This ensures that +load is only called after all referenced classes have completed // registration and dtable installation. static struct objc_module_abi_8 *legacy_module_head; static void __objc_push_legacy_module(struct objc_module_abi_8 *module) { LOCK_RUNTIME_FOR_SCOPE(); // repurpose module->name for an intrusive linked list; this is just like // unresolved_class_{next,prev} in class_table.c module->name = (char*)legacy_module_head; legacy_module_head = module; } void __objc_resolve_legacy_modules(void) { LOCK_RUNTIME_FOR_SCOPE(); struct objc_module_abi_8 *module = legacy_module_head; legacy_module_head = NULL; for(; module; module = (struct objc_module_abi_8 *)module->name) { __objc_resolve_module(module); } } #endif void __objc_exec_class(struct objc_module_abi_8 *module) { __objc_load_module(module); #ifdef WINOBJC __objc_push_legacy_module(module); #else __objc_resolve_module(module); #endif }
ipasimulator/libobjc2
dtable.c
<reponame>ipasimulator/libobjc2<gh_stars>1-10 #define __BSD_VISIBLE 1 #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <errno.h> #include "objc/runtime.h" #include "objc/hooks.h" #include "sarray2.h" #include "selector.h" #include "class.h" #include "lock.h" #include "method_list.h" #include "slot_pool.h" #include "dtable.h" #include "visibility.h" #include "asmconstants.h" _Static_assert(__builtin_offsetof(struct objc_class, dtable) == DTABLE_OFFSET, "Incorrect dtable offset for assembly"); _Static_assert(__builtin_offsetof(SparseArray, shift) == SHIFT_OFFSET, "Incorrect shift offset for assembly"); _Static_assert(__builtin_offsetof(SparseArray, data) == DATA_OFFSET, "Incorrect data offset for assembly"); _Static_assert(__builtin_offsetof(struct objc_slot, method) == SLOT_OFFSET, "Incorrect slot offset for assembly"); PRIVATE dtable_t uninstalled_dtable; #if defined(WITH_TRACING) && defined (__x86_64) PRIVATE dtable_t tracing_dtable; #endif #ifndef ENOTSUP # define ENOTSUP -1 #endif /** Head of the list of temporary dtables. Protected by initialize_lock. */ PRIVATE InitializingDtable *temporary_dtables; /** Lock used to protect the temporary dtables list. */ PRIVATE mutex_t initialize_lock; /** The size of the largest dtable. This is a sparse array shift value, so is * 2^x in increments of 8. */ static uint32_t dtable_depth = 8; struct objc_slot* objc_get_slot(Class cls, SEL selector); /** * Returns YES if the class implements a method for the specified selector, NO * otherwise. */ static BOOL ownsMethod(Class cls, SEL sel) { struct objc_slot *slot = objc_get_slot(cls, sel); if ((NULL != slot) && (slot->owner == cls)) { return YES; } return NO; } /** * Checks whether the class implements memory management methods, and whether * they are safe to use with ARC. */ static void checkARCAccessors(Class cls) { static SEL retain, release, autorelease, isARC; if (NULL == retain) { retain = sel_registerName("retain"); release = sel_registerName("release"); autorelease = sel_registerName("autorelease"); isARC = sel_registerName("_ARCCompliantRetainRelease"); } struct objc_slot *slot = objc_get_slot(cls, retain); if ((NULL != slot) && !ownsMethod(slot->owner, isARC)) { objc_clear_class_flag(cls, objc_class_flag_fast_arc); return; } slot = objc_get_slot(cls, release); if ((NULL != slot) && !ownsMethod(slot->owner, isARC)) { objc_clear_class_flag(cls, objc_class_flag_fast_arc); return; } slot = objc_get_slot(cls, autorelease); if ((NULL != slot) && !ownsMethod(slot->owner, isARC)) { objc_clear_class_flag(cls, objc_class_flag_fast_arc); return; } objc_set_class_flag(cls, objc_class_flag_fast_arc); } PRIVATE void checkARCAccessorsSlow(Class cls) { if (cls->dtable != uninstalled_dtable) { return; } static SEL retain, release, autorelease, isARC; if (NULL == retain) { retain = sel_registerName("retain"); release = sel_registerName("release"); autorelease = sel_registerName("autorelease"); isARC = sel_registerName("_ARCCompliantRetainRelease"); } if (cls->super_class != Nil) { checkARCAccessorsSlow(cls->super_class); } BOOL superIsFast = objc_test_class_flag(cls, objc_class_flag_fast_arc); BOOL selfImplementsRetainRelease = NO; for (struct objc_method_list *l=cls->methods ; l != NULL ; l= l->next) { for (int i=0 ; i<l->count ; i++) { SEL s = l->methods[i].selector; if (sel_isEqual(s, retain) || sel_isEqual(s, release) || sel_isEqual(s, autorelease)) { selfImplementsRetainRelease = YES; } else if (sel_isEqual(s, isARC)) { objc_set_class_flag(cls, objc_class_flag_fast_arc); return; } } } if (superIsFast && ! selfImplementsRetainRelease) { objc_set_class_flag(cls, objc_class_flag_fast_arc); } } static void collectMethodsForMethodListToSparseArray( struct objc_method_list *list, SparseArray *sarray, BOOL recurse) { if (recurse && (NULL != list->next)) { collectMethodsForMethodListToSparseArray(list->next, sarray, YES); } for (unsigned i=0 ; i<list->count ; i++) { SparseArrayInsert(sarray, list->methods[i].selector->index, (void*)&list->methods[i]); } } #ifdef __OBJC_LOW_MEMORY__ struct objc_dtable { struct cache_line { uint32_t idx; uint32_t version; struct objc_slot *slot; } cache[8]; mutex_t lock; struct objc_slot **slots; int slot_count; int slot_size; Class cls; }; static void update_dtable(dtable_t dtable); PRIVATE void init_dispatch_tables () { INIT_LOCK(initialize_lock); } Class class_getSuperclass(Class); PRIVATE dtable_t create_dtable_for_class(Class class, dtable_t root_dtable) { // Don't create a dtable for a class that already has one if (classHasDtable(class)) { return dtable_for_class(class); } LOCK_RUNTIME_FOR_SCOPE(); // Make sure that another thread didn't create the dtable while we were // waiting on the lock. if (classHasDtable(class)) { return dtable_for_class(class); } // Allocate the dtable dtable_t dtable = calloc(1, sizeof(struct objc_dtable)); dtable->cls = class; INIT_LOCK(dtable->lock); // Initialise it update_dtable(dtable); return dtable; } PRIVATE void objc_resize_dtables(uint32_t newSize) { if (1<<dtable_depth > newSize) { return; } dtable_depth <<= 1; } #define HASH_UID(uid) ((uid >> 2) & 7) static struct objc_slot* check_cache(dtable_t dtable, uint32_t uid) { int i = HASH_UID(uid); volatile struct cache_line *cache = &dtable->cache[i]; int32_t initial_idx = cache->idx; if (initial_idx != uid) { return NULL; } struct objc_slot *slot; int32_t idx; int32_t version; do { initial_idx = cache->idx; version = cache->version; slot = cache->slot; __sync_synchronize(); idx = cache->idx; } while (idx != initial_idx); return (idx == uid) && (slot->version == version) ? slot : NULL; } static struct objc_slot *find_slot(uint32_t uid, struct objc_slot **slots, int slot_count) { if (slot_count == 0) { return NULL; } int idx = slot_count >> 1; struct objc_slot *slot = slots[idx]; if (slot_count == 1) { if (slot->selector->index == uid) { return slot; } return NULL; } if (slot->selector->index > uid) { return find_slot(uid, slots, idx); } if (slot->selector->index < uid) { return find_slot(uid, slots+idx, slot_count - idx); } if (slot->selector->index == uid) { return slot; } return NULL; } static int slot_cmp(const void *l, const void *r) { return (*(struct objc_slot**)l)->selector->index - (*(struct objc_slot**)r)->selector->index; } static void insert_slot(dtable_t dtable, struct objc_slot *slot, uint32_t idx) { if (dtable->slot_size == dtable->slot_count) { dtable->slot_size += 16; dtable->slots = realloc(dtable->slots, dtable->slot_size * sizeof(struct objc_slot)); assert(NULL != dtable->slots && "Out of memory!"); } dtable->slots[dtable->slot_count++] = slot; } static void add_slot_to_dtable(SEL sel, dtable_t dtable, uint32_t old_slot_count, struct objc_method *m, Class cls) { uint32_t idx = sel->index; struct objc_slot *s = find_slot(idx, dtable->slots, old_slot_count); if (NULL != s) { s->method = m->imp; s->version++; } else { struct objc_slot *slot = new_slot_for_method_in_class(m, cls); slot->selector = sel; insert_slot(dtable, slot, idx); if (Nil != cls->super_class) { slot = objc_dtable_lookup(dtable_for_class(cls->super_class), idx); if (NULL != slot) { slot->version++; } } } } static void update_dtable(dtable_t dtable) { Class cls = dtable->cls; if (NULL == cls->methods) { return; } SparseArray *methods = SparseArrayNewWithDepth(dtable_depth); collectMethodsForMethodListToSparseArray((void*)cls->methods, methods, YES); if (NULL == dtable->slots) { dtable->slots = calloc(sizeof(struct objc_slot), 16); dtable->slot_size = 16; } uint32_t old_slot_count = dtable->slot_count; struct objc_method *m; uint32_t idx = 0; while ((m = SparseArrayNext(methods, &idx))) { add_slot_to_dtable(m->selector, dtable, old_slot_count, m, cls); #ifdef TYPE_DEPENDENT_DISPATCH add_slot_to_dtable(sel_getUntyped(m->selector), dtable, old_slot_count, m, cls); #endif } mergesort(dtable->slots, dtable->slot_count, sizeof(struct objc_slot*), slot_cmp); SparseArrayDestroy(methods); } PRIVATE void objc_update_dtable_for_class(Class cls) { dtable_t dtable = dtable_for_class(cls); // Be lazy about constructing the slot list - don't do it unless we actually // need to access it if ((NULL == dtable) || (NULL == dtable->slots)) { return; } LOCK_FOR_SCOPE(&dtable->lock); update_dtable(dtable); } PRIVATE void add_method_list_to_class(Class cls, struct objc_method_list *list) { objc_update_dtable_for_class(cls); } PRIVATE struct objc_slot* objc_dtable_lookup(dtable_t dtable, uint32_t uid) { if (NULL == dtable) { return NULL; } struct objc_slot *slot = check_cache(dtable, uid); if (NULL != slot) { return slot; } LOCK_FOR_SCOPE(&dtable->lock); if (NULL == dtable->slots) { update_dtable(dtable); } slot = find_slot(uid, dtable->slots, dtable->slot_count); if (NULL != slot) { int i = HASH_UID(uid); volatile struct cache_line *cache = &dtable->cache[i]; // Simplified multiword atomic exchange. First we write a value that // is an invalid but recognisable UID and then a memory barrier. Then // we complete the update and set the index pointer if and only if // there have been no other modifications in the meantime cache->idx = -uid; __sync_synchronize(); cache->version = slot->version; cache->slot = slot; __sync_bool_compare_and_swap(&cache->idx, -uid, uid); return slot; } if (NULL != dtable->cls->super_class) { return objc_dtable_lookup(dtable_for_class(dtable->cls->super_class), uid); } return NULL; } PRIVATE dtable_t objc_copy_dtable_for_class(dtable_t old, Class cls) { dtable_t dtable = calloc(1, sizeof(struct objc_dtable)); dtable->cls = cls; INIT_LOCK(dtable->lock); return dtable; } PRIVATE void free_dtable(dtable_t dtable) { if (NULL != dtable->slots) { free(dtable->slots); } DESTROY_LOCK(&dtable->lock); free(dtable); } #else PRIVATE void init_dispatch_tables () { INIT_LOCK(initialize_lock); uninstalled_dtable = SparseArrayNewWithDepth(dtable_depth); #if defined(WITH_TRACING) && defined (__x86_64) tracing_dtable = SparseArrayNewWithDepth(dtable_depth); #endif } #if defined(WITH_TRACING) && defined (__x86_64) static int init; static void free_thread_stack(void* x) { free(*(void**)x); } static pthread_key_t thread_stack_key; static void alloc_thread_stack(void) { pthread_key_create(&thread_stack_key, free_thread_stack); init = 1; } PRIVATE void* pushTraceReturnStack(void) { static pthread_once_t once_control = PTHREAD_ONCE_INIT; if (!init) { pthread_once(&once_control, alloc_thread_stack); } void **stack = pthread_getspecific(thread_stack_key); if (stack == 0) { stack = malloc(4096*sizeof(void*)); } pthread_setspecific(thread_stack_key, stack + 5); return stack; } PRIVATE void* popTraceReturnStack(void) { void **stack = pthread_getspecific(thread_stack_key); stack -= 5; pthread_setspecific(thread_stack_key, stack); return stack; } #endif int objc_registerTracingHook(SEL aSel, objc_tracing_hook aHook) { #if defined(WITH_TRACING) && defined (__x86_64) // If this is an untyped selector, register it for every typed variant if (sel_getType_np(aSel) == 0) { SEL buffer[16]; SEL *overflow = 0; int count = sel_copyTypedSelectors_np(sel_getName(aSel), buffer, 16); if (count > 16) { overflow = calloc(count, sizeof(SEL)); sel_copyTypedSelectors_np(sel_getName(aSel), buffer, 16); for (int i=0 ; i<count ; i++) { SparseArrayInsert(tracing_dtable, overflow[i]->index, aHook); } free(overflow); } else { for (int i=0 ; i<count ; i++) { SparseArrayInsert(tracing_dtable, buffer[i]->index, aHook); } } } SparseArrayInsert(tracing_dtable, aSel->index, aHook); return 0; #else return ENOTSUP; #endif } static BOOL installMethodInDtable(Class class, Class owner, SparseArray *dtable, struct objc_method *method, BOOL replaceExisting) { ASSERT(uninstalled_dtable != dtable); uint32_t sel_id = method->selector->index; struct objc_slot *slot = SparseArrayLookup(dtable, sel_id); if (NULL != slot) { // If this method is the one already installed, pretend to install it again. if (slot->method == method->imp) { return NO; } // If the existing slot is for this class, we can just replace the // implementation. We don't need to bump the version; this operation // updates cached slots, it doesn't invalidate them. if (slot->owner == owner) { // Don't replace methods if we're not meant to (if they're from // later in a method list, for example) if (!replaceExisting) { return NO; } slot->method = method->imp; return YES; } // Check whether the owner of this method is a subclass of the one that // owns this method. If it is, then we don't want to install this // method irrespective of other cases, because it has been overridden. for (Class installedFor = slot->owner ; Nil != installedFor ; installedFor = installedFor->super_class) { if (installedFor == owner) { return NO; } } } struct objc_slot *oldSlot = slot; slot = new_slot_for_method_in_class((void*)method, owner); SparseArrayInsert(dtable, sel_id, slot); // In TDD mode, we also register the first typed method that we // encounter as the untyped version. #ifdef TYPE_DEPENDENT_DISPATCH SparseArrayInsert(dtable, get_untyped_idx(method->selector), slot); #endif // Invalidate the old slot, if there is one. if (NULL != oldSlot) { oldSlot->version++; } return YES; } static void installMethodsInClass(Class cls, Class owner, SparseArray *methods, BOOL replaceExisting) { SparseArray *dtable = dtable_for_class(cls); assert(uninstalled_dtable != dtable); uint32_t idx = 0; struct objc_method *m; while ((m = SparseArrayNext(methods, &idx))) { if (!installMethodInDtable(cls, owner, dtable, m, replaceExisting)) { // Remove this method from the list, if it wasn't actually installed SparseArrayInsert(methods, idx, 0); } } } static void mergeMethodsFromSuperclass(Class super, Class cls, SparseArray *methods) { for (struct objc_class *subclass=cls->subclass_list ; Nil != subclass ; subclass = subclass->sibling_class) { // Don't bother updating dtables for subclasses that haven't been // initialized yet if (!classHasDtable(subclass)) { continue; } // Create a new (copy-on-write) array to pass down to children SparseArray *newMethods = SparseArrayCopy(methods); // Install all of these methods except ones that are overridden in the // subclass. All of the methods that we are updating were added in a // superclass, so we don't replace versions registered to the subclass. installMethodsInClass(subclass, super, newMethods, YES); // Recursively add the methods to the subclass's subclasses. mergeMethodsFromSuperclass(super, subclass, newMethods); SparseArrayDestroy(newMethods); } } Class class_getSuperclass(Class); PRIVATE void objc_update_dtable_for_class(Class cls) { // Only update real dtables if (!classHasDtable(cls)) { return; } LOCK_RUNTIME_FOR_SCOPE(); SparseArray *methods = SparseArrayNewWithDepth(dtable_depth); collectMethodsForMethodListToSparseArray((void*)cls->methods, methods, YES); installMethodsInClass(cls, cls, methods, YES); // Methods now contains only the new methods for this class. mergeMethodsFromSuperclass(cls, cls, methods); SparseArrayDestroy(methods); checkARCAccessors(cls); } PRIVATE void add_method_list_to_class(Class cls, struct objc_method_list *list) { // Only update real dtables if (!classHasDtable(cls)) { return; } LOCK_RUNTIME_FOR_SCOPE(); SparseArray *methods = SparseArrayNewWithDepth(dtable_depth); collectMethodsForMethodListToSparseArray(list, methods, NO); installMethodsInClass(cls, cls, methods, YES); // Methods now contains only the new methods for this class. mergeMethodsFromSuperclass(cls, cls, methods); SparseArrayDestroy(methods); checkARCAccessors(cls); } PRIVATE dtable_t create_dtable_for_class(Class class, dtable_t root_dtable) { // Don't create a dtable for a class that already has one if (classHasDtable(class)) { return dtable_for_class(class); } LOCK_RUNTIME_FOR_SCOPE(); // Make sure that another thread didn't create the dtable while we were // waiting on the lock. if (classHasDtable(class)) { return dtable_for_class(class); } Class super = class_getSuperclass(class); dtable_t dtable; if (Nil == super) { dtable = SparseArrayNewWithDepth(dtable_depth); } else { dtable_t super_dtable = dtable_for_class(super); if (super_dtable == uninstalled_dtable) { if (super->isa == class) { super_dtable = root_dtable; } else { abort(); } } dtable = SparseArrayCopy(super_dtable); } // When constructing the initial dtable for a class, we iterate along the // method list in forward-traversal order. The first method that we // encounter is always the one that we want to keep, so we instruct // installMethodInDtable() not to replace methods that are already // associated with this class. struct objc_method_list *list = (void*)class->methods; while (NULL != list) { for (unsigned i=0 ; i<list->count ; i++) { installMethodInDtable(class, class, dtable, &list->methods[i], NO); } list = list->next; } return dtable; } Class class_table_next(void **e); PRIVATE void objc_resize_dtables(uint32_t newSize) { // If dtables already have enough space to store all registered selectors, do nothing if (1<<dtable_depth > newSize) { return; } LOCK_RUNTIME_FOR_SCOPE(); if (1<<dtable_depth > newSize) { return; } dtable_depth += 8; uint32_t oldShift = uninstalled_dtable->shift; dtable_t old_uninstalled_dtable = uninstalled_dtable; uninstalled_dtable = SparseArrayExpandingArray(uninstalled_dtable, dtable_depth); #if defined(WITH_TRACING) && defined (__x86_64) tracing_dtable = SparseArrayExpandingArray(tracing_dtable, dtable_depth); #endif { LOCK_FOR_SCOPE(&initialize_lock); for (InitializingDtable *buffer = temporary_dtables ; NULL != buffer ; buffer = buffer->next) { buffer->dtable = SparseArrayExpandingArray(buffer->dtable, dtable_depth); } } // Resize all existing dtables void *e = NULL; struct objc_class *next; while ((next = class_table_next(&e))) { if (next->dtable == old_uninstalled_dtable) { next->dtable = uninstalled_dtable; next->isa->dtable = uninstalled_dtable; continue; } if (NULL != next->dtable && ((SparseArray*)next->dtable)->shift == oldShift) { next->dtable = SparseArrayExpandingArray((void*)next->dtable, dtable_depth); next->isa->dtable = SparseArrayExpandingArray((void*)next->isa->dtable, dtable_depth); } } } PRIVATE dtable_t objc_copy_dtable_for_class(dtable_t old, Class cls) { return SparseArrayCopy(old); } PRIVATE void free_dtable(dtable_t dtable) { SparseArrayDestroy(dtable); } #endif // __OBJC_LOW_MEMORY__ LEGACY void update_dispatch_table_for_class(Class cls) { static BOOL warned = NO; if (!warned) { fprintf(stderr, "Warning: Calling deprecated private ObjC runtime function %s\n", __func__); warned = YES; } objc_update_dtable_for_class(cls); } void objc_resolve_class(Class); __attribute__((unused)) static void objc_release_object_lock(id *x) { objc_sync_exit(*x); } /** * Macro that is equivalent to @synchronize, for use in C code. */ #define LOCK_OBJECT_FOR_SCOPE(obj) \ __attribute__((cleanup(objc_release_object_lock)))\ __attribute__((unused)) id lock_object_pointer = obj;\ objc_sync_enter(obj); /** * Remove a buffer from an entry in the initializing dtables list. This is * called as a cleanup to ensure that it runs even if +initialize throws an * exception. */ static void remove_dtable(InitializingDtable* meta_buffer) { LOCK(&initialize_lock); InitializingDtable *buffer = meta_buffer->next; // Install the dtable: meta_buffer->class->dtable = meta_buffer->dtable; buffer->class->dtable = buffer->dtable; // Remove the look-aside buffer entry. if (temporary_dtables == meta_buffer) { temporary_dtables = buffer->next; } else { InitializingDtable *prev = temporary_dtables; while (prev->next->class != meta_buffer->class) { prev = prev->next; } prev->next = buffer->next; } UNLOCK(&initialize_lock); } /** * Send a +initialize message to the receiver, if required. */ PRIVATE void objc_send_initialize(id object) { Class class = classForObject(object); // If the first message is sent to an instance (weird, but possible and // likely for things like NSConstantString, make sure +initialize goes to // the class not the metaclass. if (objc_test_class_flag(class, objc_class_flag_meta)) { class = (Class)object; } Class meta = class->isa; // Make sure that the class is resolved. objc_resolve_class(class); // Make sure that the superclass is initialized first. if (Nil != class->super_class) { objc_send_initialize((id)class->super_class); } // Superclass +initialize might possibly send a message to this class, in // which case this method would be called again. See NSObject and // NSAutoreleasePool +initialize interaction in GNUstep. if (objc_test_class_flag(class, objc_class_flag_initialized)) { // We know that initialization has started because the flag is set. // Check that it's finished by grabbing the class lock. This will be // released once the class has been fully initialized objc_sync_enter((id)meta); objc_sync_exit((id)meta); assert(dtable_for_class(class) != uninstalled_dtable); return; } // Lock the runtime while we're creating dtables and before we acquire any // other locks. This prevents a lock-order reversal when // dtable_for_class is called from something holding the runtime lock while // we're still holding the initialize lock. We should ensure that we never // acquire the runtime lock after acquiring the initialize lock. LOCK_RUNTIME(); LOCK_OBJECT_FOR_SCOPE((id)meta); LOCK(&initialize_lock); if (objc_test_class_flag(class, objc_class_flag_initialized)) { UNLOCK(&initialize_lock); UNLOCK_RUNTIME(); return; } BOOL skipMeta = objc_test_class_flag(meta, objc_class_flag_initialized); // Set the initialized flag on both this class and its metaclass, to make // sure that +initialize is only ever sent once. objc_set_class_flag(class, objc_class_flag_initialized); objc_set_class_flag(meta, objc_class_flag_initialized); dtable_t class_dtable = create_dtable_for_class(class, uninstalled_dtable); dtable_t dtable = skipMeta ? 0 : create_dtable_for_class(meta, class_dtable); // Now we've finished doing things that may acquire the runtime lock, so we // can hold onto the initialise lock to make anything doing // dtable_for_class block until we've finished updating temporary dtable // lists. // If another thread holds the runtime lock, it can now proceed until it // gets into a dtable_for_class call, and then block there waiting for us // to finish setting up the temporary dtable. UNLOCK_RUNTIME(); static SEL initializeSel = 0; if (0 == initializeSel) { initializeSel = sel_registerName("initialize"); } struct objc_slot *initializeSlot = skipMeta ? 0 : objc_dtable_lookup(dtable, initializeSel->index); // If there's no initialize method, then don't bother installing and // removing the initialize dtable, just install both dtables correctly now if (0 == initializeSlot) { if (!skipMeta) { meta->dtable = dtable; } class->dtable = class_dtable; checkARCAccessors(class); UNLOCK(&initialize_lock); return; } // Create an entry in the dtable look-aside buffer for this. When sending // a message to this class in future, the lookup function will check this // buffer if the receiver's dtable is not installed, and block if // attempting to send a message to this class. InitializingDtable buffer = { class, class_dtable, temporary_dtables }; __attribute__((cleanup(remove_dtable))) InitializingDtable meta_buffer = { meta, dtable, &buffer }; temporary_dtables = &meta_buffer; // We now release the initialize lock. We'll reacquire it later when we do // the cleanup, but at this point we allow other threads to get the // temporary dtable and call +initialize in other threads. UNLOCK(&initialize_lock); // We still hold the class lock at this point. dtable_for_class will block // there after acquiring the temporary dtable. checkARCAccessors(class); // Store the buffer in the temporary dtables list. Note that it is safe to // insert it into a global list, even though it's a temporary variable, // because we will clean it up after this function. initializeSlot->method((id)class, initializeSel); }
ipasimulator/libobjc2
selector.h
#ifndef OBJC_SELECTOR_H_INCLUDED #define OBJC_SELECTOR_H_INCLUDED /** * Structure used to store the types for a selector. This allows for a quick * test to see whether a selector is polymorphic and allows enumeration of all * type encodings for a given selector. * * This is <= the size of an objc_selector, so we can allocate them from the * objc_selector pool. * * Note: For ABI v10, we can probably do something a bit more sensible here and * make selectors into a linked list. */ struct sel_type_list { const char *value; struct sel_type_list *next; }; /** * Structure used to store selectors in the list. This is the selctor from abi version 8. */ struct objc_selector8 { union { /** * The name of this selector. Used for unregistered selectors. */ const char *name; /** * The index of this selector in the selector table. When a selector * is registered with the runtime, its name is replaced by an index * uniquely identifying this selector. The index is used for dispatch. */ uintptr_t index; }; /** * The Objective-C type encoding of the message identified by this selector. */ const char * types; }; /** * Structure used to store selectors in the list. */ struct objc_selector { union { /** * The name of this selector. Used for unregistered selectors. */ const char *name; /** * The index of this selector in the selector table. When a selector * is registered with the runtime, its name is replaced by an index * uniquely identifying this selector. The index is used for dispatch. */ uintptr_t index; }; /** * The Objective-C type encoding of the message identified by this selector. */ const char * types; /** * Hash value for this selector (calculated from its name and type) */ _Atomic uint32_t hash; }; /** * Returns the untyped variant of a selector. */ __attribute__((unused)) static uint32_t get_untyped_idx(SEL aSel) { SEL untyped = sel_registerTypedName_np(sel_getName(aSel), 0); return untyped->index; } __attribute__((unused)) static SEL sel_getUntyped(SEL aSel) { return sel_registerTypedName_np(sel_getName(aSel), 0); } /** * Returns whether a selector is mapped. */ BOOL isSelRegistered(SEL sel); /** * Registers the selector. This selector may be returned later, so it must not * be freed. */ SEL objc_register_selector(SEL aSel); /** * SELECTOR() macro to work around the fact that GCC hard-codes the type of * selectors. This is functionally equivalent to @selector(), but it ensures * that the selector has the type that the runtime uses for selectors. */ #ifdef __clang__ #define SELECTOR(x) @selector(x) #else #define SELECTOR(x) (SEL)@selector(x) #endif #endif // OBJC_SELECTOR_H_INCLUDED
ipasimulator/libobjc2
msvc/block_to_imp_winobjc.c
<filename>msvc/block_to_imp_winobjc.c #include "objc/runtime.h" #include "../visibility.h" /* These are stub implementations of the block->imp->block API functions. * Until we can emit the block trampolines at build time (like iOS appears to), * we'll have to live without these functions. */ IMP imp_implementationWithBlock(void *block) { return NULL; } void *imp_getBlock(IMP anImp) { return NULL; } BOOL imp_removeBlock(IMP anImp) { return NO; } char *block_copyIMPTypeEncoding_np(void*block) { return NULL; } PRIVATE void init_trampolines(void) { }
ipasimulator/libobjc2
msvc/debug_constants.h
<reponame>ipasimulator/libobjc2 #ifndef DBG_SKIP // The line number 0xF00F00 (here in decimal) is a signal to the debugger that the following line should be skipped. #define DBG_SKIP 15732480 #endif #ifndef DBG_FOLLOW // The line number 0xFEEFEE (in decimal below) signals to the debugger that the line should be skipped, but its jump targets should not be. #define DBG_FOLLOW 16707566 #endif
ipasimulator/libobjc2
class_table.c
#include "objc/runtime.h" #include "objc/hooks.h" #include "objc/developer.h" #include "alias.h" #include "class.h" #include "method_list.h" #include "selector.h" #include "lock.h" #include "ivar.h" #include "dtable.h" #include "visibility.h" #include <stdlib.h> #include <assert.h> void objc_register_selectors_from_class(Class class); void objc_init_protocols(struct objc_protocol_list *protos); void objc_compute_ivar_offsets(Class class); //////////////////////////////////////////////////////////////////////////////// // +load method hash table //////////////////////////////////////////////////////////////////////////////// static int imp_compare(const void *i1, void *i2) { return i1 == i2; } static int32_t imp_hash(const void *imp) { return (int32_t)(((uintptr_t)imp) >> 4); } #define MAP_TABLE_NAME load_messages #define MAP_TABLE_COMPARE_FUNCTION imp_compare #define MAP_TABLE_HASH_KEY imp_hash #define MAP_TABLE_HASH_VALUE imp_hash #include "hash_table.h" static load_messages_table *load_table; SEL loadSel; PRIVATE void objc_init_load_messages_table(void) { load_messages_initialize(&load_table, 4096); loadSel = sel_registerName("load"); } PRIVATE void objc_send_load_message(Class class) { Class meta = class->isa; for (struct objc_method_list *l=meta->methods ; NULL!=l ; l=l->next) { for (int i=0 ; i<l->count ; i++) { Method m = &l->methods[i]; if (sel_isEqual(m->selector, loadSel)) { if (load_messages_table_get(load_table, m->imp) == 0) { m->imp((id)class, loadSel); load_messages_insert(load_table, m->imp); } } } } } // Get the functions for string hashing #include "string_hash.h" static int class_compare(const char *name, const Class class) { return string_compare(name, class->name); } static int class_hash(const Class class) { return string_hash(class->name); } #define MAP_TABLE_NAME class_table_internal #define MAP_TABLE_COMPARE_FUNCTION class_compare #define MAP_TABLE_HASH_KEY string_hash #define MAP_TABLE_HASH_VALUE class_hash // This defines the maximum number of classes that the runtime supports. /* #define MAP_TABLE_STATIC_SIZE 2048 #define MAP_TABLE_STATIC_NAME class_table */ #include "hash_table.h" static class_table_internal_table *class_table; #define unresolved_class_next subclass_list #define unresolved_class_prev sibling_class /** * Linked list using the subclass_list pointer in unresolved classes. */ static Class unresolved_class_list; static enum objc_developer_mode_np mode; void objc_setDeveloperMode_np(enum objc_developer_mode_np newMode) { mode = newMode; } //////////////////////////////////////////////////////////////////////////////// // Class table manipulation //////////////////////////////////////////////////////////////////////////////// PRIVATE Class zombie_class; PRIVATE void class_table_insert(Class class) { if (!objc_test_class_flag(class, objc_class_flag_resolved)) { if (Nil != unresolved_class_list) { unresolved_class_list->unresolved_class_prev = class; } class->unresolved_class_next = unresolved_class_list; unresolved_class_list = class; } if ((0 == zombie_class) && (strcmp("NSZombie", class->name) == 0)) { zombie_class = class; } class_table_internal_insert(class_table, class); } PRIVATE Class class_table_get_safe(const char *class_name) { if (NULL == class_name) { return Nil; } return class_table_internal_table_get(class_table, class_name); } PRIVATE Class class_table_next(void **e) { return class_table_internal_next(class_table, (struct class_table_internal_table_enumerator**)e); } PRIVATE void init_class_tables(void) { class_table_internal_initialize(&class_table, 4096); objc_init_load_messages_table(); } //////////////////////////////////////////////////////////////////////////////// // Loader functions //////////////////////////////////////////////////////////////////////////////// PRIVATE BOOL objc_resolve_class(Class cls) { // Skip this if the class is already resolved. if (objc_test_class_flag(cls, objc_class_flag_resolved)) { return YES; } // We can only resolve the class if its superclass is resolved. if (cls->super_class) { Class super = (Class)objc_getClass((char*)cls->super_class); if (Nil == super) { return NO; } if (!objc_test_class_flag(super, objc_class_flag_resolved)) { if (!objc_resolve_class(super)) { return NO; } } } // Remove the class from the unresolved class list if (Nil == cls->unresolved_class_prev) { unresolved_class_list = cls->unresolved_class_next; } else { cls->unresolved_class_prev->unresolved_class_next = cls->unresolved_class_next; } if (Nil != cls->unresolved_class_next) { cls->unresolved_class_next->unresolved_class_prev = cls->unresolved_class_prev; } cls->unresolved_class_prev = Nil; cls->unresolved_class_next = Nil; // The superclass for the metaclass. This is the metaclass for the // superclass if one exists, otherwise it is the root class itself Class superMeta = Nil; // The metaclass for the metaclass. This is always the root class's // metaclass. Class metaMeta = Nil; // Resolve the superclass pointer if (NULL == cls->super_class) { superMeta = cls; metaMeta = cls->isa; } else { // Resolve the superclass if it isn't already resolved Class super = (Class)objc_getClass((char*)cls->super_class); if (!objc_test_class_flag(super, objc_class_flag_resolved)) { objc_resolve_class(super); } superMeta = super->isa; // Set the superclass pointer for the class and the superclass cls->super_class = super; do { metaMeta = super->isa; super = super->super_class; } while (Nil != super); } Class meta = cls->isa; // Make the root class the superclass of the metaclass (e.g. NSObject is // the superclass of all metaclasses in classes that inherit from NSObject) meta->super_class = superMeta; meta->isa = metaMeta; // Don't register root classes as children of anything if (Nil != cls->super_class) { // Set up the class links cls->sibling_class = cls->super_class->subclass_list; cls->super_class->subclass_list = cls; } // Set up the metaclass links meta->sibling_class = superMeta->subclass_list; superMeta->subclass_list = meta; // Mark this class (and its metaclass) as resolved objc_set_class_flag(cls, objc_class_flag_resolved); objc_set_class_flag(cls->isa, objc_class_flag_resolved); // Fix up the ivar offsets objc_compute_ivar_offsets(cls); // Send the +load message, if required if (!objc_test_class_flag(cls, objc_class_flag_user_created)) { objc_send_load_message(cls); } if (_objc_load_callback) { _objc_load_callback(cls, 0); } return YES; } PRIVATE void objc_resolve_class_links(void) { LOCK_RUNTIME_FOR_SCOPE(); BOOL resolvedClass; do { Class class = unresolved_class_list; resolvedClass = NO; while ((Nil != class)) { Class next = class->unresolved_class_next; objc_resolve_class(class); if (resolvedClass || objc_test_class_flag(class, objc_class_flag_resolved)) { resolvedClass = YES; } class = next; } } while (resolvedClass); } void __objc_resolve_class_links(void) { static BOOL warned = NO; if (!warned) { fprintf(stderr, "Warning: Calling deprecated private ObjC runtime function %s\n", __func__); warned = YES; } objc_resolve_class_links(); } static void reload_class(struct objc_class *class, struct objc_class *old) { const char *superclassName = (char*)class->super_class; class->super_class = class_table_get_safe(superclassName); // Checking the instance sizes are equal here is a quick-and-dirty test. // It's not actually needed, because we're testing the ivars are at the // same locations next, but it lets us skip those tests if the total size // is different. BOOL equalLayouts = (class->super_class == old->super_class) && (class->instance_size == old->instance_size); // If either of the classes has an empty ivar list, then the other one must too. if ((NULL == class->ivars) || (NULL == old->ivars)) { equalLayouts &= (class->ivars == old->ivars); } else { // If the class sizes are the same, ensure that the ivars have the same // types, names, and offsets. Note: Renaming an ivar is treated as a // conflict because name changes are often accompanied by semantic // changes. For example, an object ivar at offset 16 goes from being // called 'delegate' to being called 'view' - we almost certainly don't // want methods that expect to be working with the delegate ivar to // work with the view ivar now! for (int i=0 ; equalLayouts && (i<old->ivars->count) ; i++) { struct objc_ivar *oldIvar = &old->ivars->ivar_list[i]; struct objc_ivar *newIvar = &class->ivars->ivar_list[i]; equalLayouts &= strcmp(oldIvar->name, newIvar->name) == 0; equalLayouts &= strcmp(oldIvar->type, newIvar->type) == 0; equalLayouts &= (oldIvar->offset == newIvar->offset); } } // If the layouts are equal, then we can simply tack the class's method // list on to the front of the old class and update the dtable. if (equalLayouts) { class->methods->next = old->methods; old->methods = class->methods; objc_update_dtable_for_class(old); return; } // If we get to here, then we are adding a new class. This is where things // start to get a bit tricky... // Ideally, we'd want to capture the subclass list here. Unfortunately, // this is not possible because the subclass will contain methods that // refer to ivars in the superclass. // // We can't use the non-fragile ABI's offset facility easily, because we'd // have to have two (or more) offsets for the same ivar. This gets messy // very quickly. Ideally, we'd want every class to include ivar offsets // for every single (public) ivar in its superclasses. These could then be // updated by copies of the class. Defining a development ABI is something // to consider for a future release. class->subclass_list = NULL; // Replace the old class with this one in the class table. New lookups for // this class will now return this class. class_table_internal_table_set(class_table, (void*)class->name, class); // Register all of the selectors used by this class and its metaclass objc_register_selectors_from_class(class); objc_register_selectors_from_class(class->isa); // Set the uninstalled dtable. The compiler could do this as well. class->dtable = uninstalled_dtable; class->isa->dtable = uninstalled_dtable; // If this is a root class, make the class into the metaclass's superclass. // This means that all instance methods will be available to the class. if (NULL == superclassName) { class->isa->super_class = class; } if (class->protocols) { objc_init_protocols(class->protocols); } } /** * Loads a class. This function assumes that the runtime mutex is locked. */ PRIVATE void objc_load_class(struct objc_class *class) { struct objc_class *existingClass = class_table_get_safe(class->name); if (Nil != existingClass) { if (objc_developer_mode_developer != mode) { fprintf(stderr, "Loading two versions of %s. The class that will be used is undefined\n", class->name); return; } reload_class(class, existingClass); return; } // The compiler initialises the super class pointer to the name of the // superclass, not the superclass pointer. // Note: With the new ABI, the class pointer is public. We could, // therefore, directly reference the superclass from the compiler and make // the linker resolve it. This should be done in the GCC-incompatible ABI. const char *superclassName = (char*)class->super_class; // Work around a bug in some versions of GCC that don't initialize the // class structure correctly. class->subclass_list = NULL; // Insert the class into the class table class_table_insert(class); // Register all of the selectors used by this class and its metaclass objc_register_selectors_from_class(class); objc_register_selectors_from_class(class->isa); // Set the uninstalled dtable. The compiler could do this as well. class->dtable = uninstalled_dtable; class->isa->dtable = uninstalled_dtable; // If this is a root class, make the class into the metaclass's superclass. // This means that all instance methods will be available to the class. if (NULL == superclassName) { class->isa->super_class = class; } if (class->protocols) { objc_init_protocols(class->protocols); } } PRIVATE Class SmallObjectClasses[7]; BOOL objc_registerSmallObjectClass_np(Class class, uintptr_t mask) { if ((mask & OBJC_SMALL_OBJECT_MASK) != mask) { return NO; } if (sizeof(void*) == 4) { if (Nil == SmallObjectClasses[0]) { SmallObjectClasses[0] = class; return YES; } return NO; } if (Nil != SmallObjectClasses[mask]) { return NO; } SmallObjectClasses[mask] = class; return YES; } //////////////////////////////////////////////////////////////////////////////// // Public API //////////////////////////////////////////////////////////////////////////////// int objc_getClassList(Class *buffer, int bufferLen) { if (buffer == NULL || bufferLen == 0) { return class_table->table_used; } int count = 0; struct class_table_internal_table_enumerator *e = NULL; Class next; while (count < bufferLen && (next = class_table_internal_next(class_table, &e))) { buffer[count++] = next; } return count; } Class *objc_copyClassList(unsigned int *outCount) { int count = class_table->table_used; Class *buffer = calloc(sizeof(Class), count); if (NULL != outCount) { *outCount = count; } objc_getClassList(buffer, count); return buffer; } Class class_getSuperclass(Class cls) { if (Nil == cls) { return Nil; } if (!objc_test_class_flag(cls, objc_class_flag_resolved)) { objc_resolve_class(cls); } return cls->super_class; } id objc_getClass(const char *name) { id class = (id)class_table_get_safe(name); if (nil != class) { return class; } // Second chance lookup via @compatibilty_alias: class = (id)alias_getClass(name); if (nil != class) { return class; } // Third chance lookup via the hook: if (0 != _objc_lookup_class) { class = (id)_objc_lookup_class(name); } return class; } id objc_lookUpClass(const char *name) { return (id)class_table_get_safe(name); } id objc_getMetaClass(const char *name) { Class cls = (Class)objc_getClass(name); return cls == Nil ? nil : (id)cls->isa; } // Legacy interface compatibility id objc_get_class(const char *name) { return objc_getClass(name); } id objc_lookup_class(const char *name) { return objc_getClass(name); } id objc_get_meta_class(const char *name) { return objc_getMetaClass(name); } Class objc_next_class(void **enum_state) { return class_table_next ( enum_state); } Class class_pose_as(Class impostor, Class super_class) { fprintf(stderr, "Class posing is no longer supported.\n"); fprintf(stderr, "Please use class_replaceMethod() instead.\n"); abort(); }
saulogatti/UX
Sample Code/ObjcSampleCode/UXSDKOCSample/Oficial5/Model/UI/Botao/ButtonOn.h
<gh_stars>0 // // ButtonOn.h // DJI O-SDK // // Created by <NAME> on 29/08/18. // Copyright © 2018 DJI. All rights reserved. // #import <UIKit/UIKit.h> @interface ButtonOn : UIButton @property (nonatomic, assign) BOOL inverterCorDePress; @end
saulogatti/UX
Sample Code/ObjcSampleCode/UXSDKOCSample/Oficial5/Model/UI/Botao/ButtonOff.h
// // ButtonOff.h // DJI O-SDK // // Created by <NAME> on 29/08/18. // Copyright © 2018 DJI. All rights reserved. // #import <UIKit/UIKit.h> @interface ButtonOff : UIButton @property (nonatomic, assign) BOOL inverterCorDePress; @end
saulogatti/UX
Sample Code/ObjcSampleCode/UXSDKOCSample/Oficial5/Utils/Protocols/StatusProtocol.h
// // StatusProtocol.h // DJI O-SDK // // Created by <NAME> on 30/08/18. // Copyright © 2018 DJI. All rights reserved. // #import <Foundation/Foundation.h> @protocol IStatusProtocolDelegate <NSObject> @optional - (void) changeStatus:(BOOL) status; @end
saulogatti/UX
Sample Code/ObjcSampleCode/UXSDKOCSample/Oficial5/New Group/MOSJSONDynamicController.h
// // MOSJSONDynamicController.h // MOS // // // Copyright © 2016 DJI. All rights reserved. // #import <UIKit/UIKit.h> #import "AppDelegate.h" #import "MOSSection.h" @interface MOSJSONDynamicController : UITableViewController { NSMutableDictionary * _dicCell; } @property (weak, nonatomic) AppDelegate *appDelegate; @property (weak, nonatomic) MOSSection *section; @end
saulogatti/UX
Framework/DJIUXSDK.framework/Headers/DUXColorWaveformWidget.h
// // DUXColorWaveformWidget.h // DJIUXSDK // // Created by <NAME> on 5/7/18. // Copyright © 2018 DJI. All rights reserved. // #import <DJIUXSDK/DJIUXSDK.h> @class DUXFPVViewController; /** * Display: * Widget to display color waveform of live video. */ @interface DUXColorWaveformWidget : DUXWidget /** * Class method to check if color waveform is supported by current camera. * * @return A boolean value to check if color waveform is supported by current camera. */ + (BOOL) isSupported; - (instancetype) initWithFPVViewController:(DUXFPVViewController *)fpvViewController; @end
saulogatti/UX
Sample Code/ObjcSampleCode/UXSDKOCSample/Oficial5/Model/Objetos/TimerCommand.h
<filename>Sample Code/ObjcSampleCode/UXSDKOCSample/Oficial5/Model/Objetos/TimerCommand.h // // TimerCommand.h // UXSDKOCSample // // Created by <NAME> on 03/01/19. // Copyright © 2019 DJI. All rights reserved. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface TimerCommand : NSObject @property (nonatomic, assign) NSInteger timeOn; @property (nonatomic, assign) NSInteger timeOff; @property (nonatomic, assign) NSInteger valve; @property (nonatomic, assign) BOOL executeOn; @property (nonatomic, assign) BOOL executado; @property (nonatomic, assign) BOOL executandoOff; @property (nonatomic, assign) u_int16_t comando; @end NS_ASSUME_NONNULL_END
saulogatti/UX
Sample Code/ObjcSampleCode/UXSDKOCSample/Oficial5/Model/UI/MOSDynamicTableViewCell.h
<reponame>saulogatti/UX // // MOSDynamicTableViewCell.h // MOS // // // Copyright © 2016 DJI. All rights reserved. // #import <UIKit/UIKit.h> @class MOSAction; typedef void (^MOSGoActionBlock)(NSNumber *cmdId, NSArray *arguments); @interface MOSDynamicTableViewCell : UITableViewCell @property (weak, nonatomic) IBOutlet UILabel *commandLabel; @property (weak, nonatomic) IBOutlet UILabel *commandInformation; @property (weak, nonatomic) IBOutlet UILabel *cmdIdLabel; @property (weak, nonatomic) IBOutlet UILabel *commandResultLabel; @property (weak, nonatomic) IBOutlet UIButton *btOff; @property (weak, nonatomic) IBOutlet UIButton *btOn; @property (weak, nonatomic) IBOutlet UILabel *lbStatus; @property (nonatomic, assign) NSInteger timerCommandOff; @property (nonatomic, assign) NSInteger timerCommandOn; @property (strong, nonatomic) MOSGoActionBlock goAction; - (IBAction)go:(id)sender; - (void)populateWithActionModel:(MOSAction *)actionModel; -(void)changeStatus:(BOOL) value; - (void) executeTimer; - (void) pause; @end
saulogatti/UX
Sample Code/ObjcSampleCode/UXSDKOCSample/Oficial5/Utils/Suporte.h
<reponame>saulogatti/UX // // Suporte.h // UXSDKOCSample // // Created by <NAME> on 02/01/19. // Copyright © 2019 DJI. All rights reserved. // @import UIKit; NS_ASSUME_NONNULL_BEGIN @interface Suporte : NSObject @property (nonatomic, strong) NSMutableDictionary * listTimer; @property (nonatomic, assign) NSInteger valveExecute; + (UIViewController*) getTopMostViewController; + (Suporte*) getInstancia; @end NS_ASSUME_NONNULL_END
saulogatti/UX
Sample Code/ObjcSampleCode/UXSDKOCSample/AppDelegate.h
<gh_stars>0 // // AppDelegate.h // UXSDKOCSample // // Created by DJI on 14/4/2017. // Copyright © 2017 DJI. All rights reserved. // #import <UIKit/UIKit.h> @class MOSModel; @class MOSProductCommunicationManager; @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @property (strong, nonatomic) MOSModel *model; @property (strong, nonatomic) MOSProductCommunicationManager *productCommunicationManager; @end
saulogatti/UX
Sample Code/ObjcSampleCode/UXSDKOCSample/Oficial5/New Group/MOSMainTabViewController.h
// // MOSMainTabViewController.h // MOS // // // Copyright © 2016 DJI. All rights reserved. // #import <UIKit/UIKit.h> #import "AppDelegate.h" @interface MOSMainTabViewController : UITabBarController @property (weak, nonatomic) AppDelegate *appDelegate; @end
saulogatti/UX
Sample Code/ObjcSampleCode/UXSDKOCSample/Oficial5/Network/GerenciadorTimer.h
// // GerenciadorTimer.h // UXSDKOCSample // // Created by <NAME> on 28/01/19. // Copyright © 2019 DJI. All rights reserved. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface GerenciadorTimer : NSObject + (GerenciadorTimer *)getInstancia; - (void) play; - (void) pause; - (void) restart; @end NS_ASSUME_NONNULL_END
saulogatti/UX
Sample Code/ObjcSampleCode/UXSDKOCSample/Oficial5/New Group/ConfigTimerTableViewController.h
<gh_stars>0 // // ConfigTimerTableViewController.h // UXSDKOCSample // // Created by <NAME> on 03/01/19. // Copyright © 2019 DJI. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface ConfigTimerTableViewController : UITableViewController<UITextFieldDelegate> @end NS_ASSUME_NONNULL_END
saulogatti/UX
Sample Code/ObjcSampleCode/UXSDKOCSample/Oficial5/Model/UI/Botao/Botao.h
// // Botao.h // UXSDKOCSample // // Created by <NAME> on 07/11/18. // Copyright © 2018 DJI. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface Botao : UIButton @end NS_ASSUME_NONNULL_END
saulogatti/UX
Sample Code/ObjcSampleCode/UXSDKOCSample/Oficial5/Utils/Enum.h
// // Enum.m // DJI O-SDK // // Created by <NAME> on 25/08/18. // Copyright © 2018 DJI. All rights reserved. // @import UIKit; typedef enum { ValvulaUmAberta = 11, ValvulaUmFechada = 10, ValvulaDoisAberta = 21, ValvulaDoisFechada = 20, ValvulaTresAberta = 31, ValvulaTresFechada = 30, ValvulaQuatroAberta = 41, ValvulaQuatroFechada = 40, ValvulaCincoAberta = 51, ValvulaCincoFechada = 50 } RETURN_SERVER;
saulogatti/UX
Sample Code/ObjcSampleCode/UXSDKOCSample/Oficial5/Model/MOSSection.h
// // MOSSection.h // MOS // // // Copyright © 2016 DJI. All rights reserved. // #import <Foundation/Foundation.h> @class MOSAction; @interface MOSSection : NSObject @property (strong, nonatomic) NSString *name; @property (strong, nonatomic) NSMutableArray <MOSAction *> *actions; - (instancetype)initWithName:(NSString *)sectionName andJSONContent:(NSArray *)jsonContent; - (NSMutableArray <MOSAction *> *)actionsInJsonArray:(NSArray *)jsonArray; @end
saulogatti/UX
Sample Code/ObjcSampleCode/UXSDKOCSample/Oficial5/New Group/MOSLogConsoleViewController.h
// // MOSLogConsoleViewController.h // MOS // // // Copyright © 2016 DJI. All rights reserved. // #import <UIKit/UIKit.h> #import "AppDelegate.h" @interface MOSLogConsoleViewController : UIViewController @property (weak, nonatomic) AppDelegate *appDelegate; @property (weak, nonatomic) IBOutlet UITextView *logView; - (IBAction)actionClearLogs:(id)sender; - (void)updateLogView; @end
saulogatti/UX
Sample Code/ObjcSampleCode/UXSDKOCSample/Oficial5/Network/MOSProductCommunicationManager.h
<gh_stars>0 // // MOSProductCommunicationManager.h // MOS // // // Copyright © 2016 DJI. All rights reserved. // #import <Foundation/Foundation.h> @import DJISDK; @class AppDelegate; NS_ASSUME_NONNULL_BEGIN typedef void (^MOSAckBlock)(NSData *data, NSError * _Nullable error); @interface MOSProductCommunicationManager : NSObject <DJISDKManagerDelegate, DJIFlightControllerDelegate> { NSTimer * _timerRetry; NSData * _dataRetry; } @property (weak, nonatomic) AppDelegate *appDelegate; @property (weak, nonatomic) DJIBaseProduct *connectedProduct; @property (strong, nonatomic) NSMutableDictionary *sentCmds; /*********************************************************************************/ #pragma mark - OnBoardSDK Communication /*********************************************************************************/ - (NSString *)commandIDStringKeyFromData:(NSData *)data; - (void)sendData:(NSData *)data withCompletion:(void (^)(NSError * _Nullable error))completion andAckBlock:(MOSAckBlock)ackBlock; @end NS_ASSUME_NONNULL_END
saulogatti/UX
Sample Code/ObjcSampleCode/UXSDKOCSample/Oficial5/Model/MOSModel.h
// // MOSModel.h // MOS // // // Copyright © 2016 DJI. All rights reserved. // #import <Foundation/Foundation.h> @class MOSSection; typedef void(^MOSModelLogChangedBlock)(); @interface MOSModel : NSObject /*********************************************************************************/ #pragma mark - JSON-Based UI /*********************************************************************************/ @property (strong, nonatomic) NSMutableArray <MOSSection *> *jsonSections; // Loads the config.json file. - (void)loadConfiguration; /*********************************************************************************/ #pragma mark - Logs /*********************************************************************************/ @property (strong, nonatomic) NSMutableArray <NSDictionary *> *logs; @property (strong, nonatomic) MOSModelLogChangedBlock logChangedBlock; - (void)addLog:(NSString *)newLogEntry; @end
saulogatti/UX
Framework/DJIUXSDK.framework/Headers/DUXStorageCapacityChecklistItem.h
// // DUXStorageCapacityChecklistItem.h // DJIUXSDK // // Copyright © 2016 DJI. All rights reserved. // #import <DJIUXSDK/DUXPreflightChecklistItem.h> /** * Preflight checklist item that reports the storage remaining for photo and video * capture. This item will always report ready to fly. */ @interface DUXStorageCapacityChecklistItem : DUXPreflightChecklistItem @property NSInteger sdSpaceLeftInMB; @property NSInteger ssdSpaceLeftInMB; @property (nonatomic) NSUInteger preferredCameraIndex; @end
saulogatti/UX
Sample Code/ObjcSampleCode/UXSDKOCSample/Oficial5/Utils/ColorSuporte.h
// // ColorSuporte.h // DJI O-SDK // // Created by <NAME> on 29/08/18. // Copyright © 2018 DJI. All rights reserved. // #import <UIKit/UIKit.h> @interface ColorSuporte : NSObject + (UIColor*) ColorDefaultButtonOn; + (UIColor*) ColorDefaultButtonOff; @end
saulogatti/UX
Sample Code/ObjcSampleCode/UXSDKOCSample/Oficial5/New Group/CronometroViewController.h
<gh_stars>0 // // CronometroViewController.h // UXSDKOCSample // // Created by <NAME> on 29/11/18. // Copyright © 2018 DJI. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface CronometroViewController : UIViewController @end NS_ASSUME_NONNULL_END
saulogatti/UX
Sample Code/ObjcSampleCode/UXSDKOCSample/Oficial5/Model/MOSAction.h
<reponame>saulogatti/UX // // MOSAction.h // MOS // // // Copyright © 2016 DJI. All rights reserved. // #import <Foundation/Foundation.h> @interface MOSAction : NSObject @property (strong, nonatomic) NSString *key; @property (strong, nonatomic) NSString *label; @property (strong, nonatomic) NSString *information; @property (strong, nonatomic) NSNumber *cmdIDOn; @property (strong, nonatomic) NSNumber *cmdIDOff; @property BOOL acks; // Acknowledgment - (instancetype)initWithJsonDictionary:(NSDictionary *)jsonDictionary; @end
rrainey/DSKY-matic
src/test/alarm-panel-test.c
<reponame>rrainey/DSKY-matic #include <fcntl.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> #include <stdio.h> #include <unistd.h> #include <stdint.h> #include <time.h> #include <sys/ioctl.h> #include "linux/i2c-dev.h" /** * seven bit device address (binary): 011 1000 */ #define I2C_ALARM_PANEL_ADDRESS 0x38 /** * seven bit device address (binary): 011 1001 */ #define I2C_KEYBOARD_ADDRESS 0x39 #define LAMP(x) (0x8000>>x) #define LAMP_UPLINK_ACTY LAMP(0) #define LAMP_NO_ATT LAMP(1) #define LAMP_STBY LAMP(2) #define LAMP_KEY_REL LAMP(3) #define LAMP_OPR_ERR LAMP(4) #define LAMP_TEMP LAMP(7) #define LAMP_GIMBAL_LOCK LAMP(8) #define LAMP_PROG LAMP(9) #define LAMP_RESTART LAMP(10) #define LAMP_TRACKER LAMP(11) #define LAMP_ALT LAMP(12) #define LAMP_VEL LAMP(13) const char *key_name[] = { NULL, // entry 0 does not correspond to an S-key. "STBY", "KEY REL", "ENTR", "VERB", "NOUN", "CLR", "(minus)", "0", "(plus)", "1", "2", "3", "4", "5", "6", "7", "8", "9", "RESET" }; bool setLamps(int fd, unsigned int state) { char buf[2]; bool status = true; buf[0] = (state >> 8) & 0xff; buf[1] = (state & 0xff); if(write(fd, buf, 2) != 2) { status = false; } return status; } bool checkKeyEvent( int fd_key, unsigned long *millis, unsigned char *s_id, unsigned char *state) { unsigned char buf[6]; *millis = 0; *s_id = 0; *state = 0; bool status = false; if( read(fd_key, buf, 6) == 6 ) { *millis = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3]; //fprintf(stderr, "%ul\n", *millis); *s_id = buf[4]; *state = buf[5]; status = true; } return status; } int main(int argc, char *argv[]) { int fd; int fd_key; bool reported = false; bool reported2 = false; struct timespec _500ms; _500ms.tv_sec = 0; //_500ms.tv_nsec = 5000000L; _500ms.tv_nsec = 500 * 1000000L; fd = open("/dev/i2c-1", O_RDWR); if(fd < 0) { fprintf(stderr, "Error opening device\n"); exit(EXIT_FAILURE); } if(ioctl(fd, I2C_SLAVE, I2C_ALARM_PANEL_ADDRESS) < 0) { fprintf(stderr, "Error setting slave address\n"); close(fd); exit(EXIT_FAILURE); } fd_key = open("/dev/i2c-1", O_RDWR); if(fd_key < 0) { fprintf(stderr, "Error opening device\n"); exit(EXIT_FAILURE); } if(ioctl(fd_key, I2C_SLAVE, I2C_KEYBOARD_ADDRESS) < 0) { fprintf(stderr, "Error setting slave address\n"); close(fd_key); exit(EXIT_FAILURE); } unsigned short lamp = 0x8000; while (1) { if (!setLamps(fd, lamp)) { if (!reported) { reported = true; fprintf(stderr, "Error writing (1)\n"); } //close(fd); // exit(EXIT_FAILURE); } unsigned long millis; unsigned char s_id = 1; unsigned char state; while ( s_id > 0) { if (checkKeyEvent(fd_key, &millis, &s_id, &state) ) { if (s_id > 0) { printf("%s %s\n", key_name[s_id], state ? "down" : "up"); } } else { if (!reported2) { reported2 = true; printf ("error on keyboard poll\n"); } } } nanosleep(&_500ms, NULL); lamp = lamp >> 1; if (lamp == 0x0002) { lamp = 0x8000; } } close(fd); close(fd_key); exit(EXIT_SUCCESS); }
rrainey/DSKY-matic
src/yaDSKY2/DSKYmaticIF.h
/* * DSKY-matic driver interface for Raspberry Pi OS * * Copyright (c) 2020, <NAME> * * This file is part of the DSKY-matic project. All software in that project * is release via the GPL v2 license. See src/SOFTWARE-LICENSE.txt. Hardware and * artistic elements are covered by a separate CC-BY-SA license. * * DSKY-matic is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * DSKY-matic is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with DSKY-matic; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef DSKYMATICIF_H #define DSKYMATICIF_H /** * seven bit device address (binary): 011 1000 */ #define I2C_ALARM_PANEL_ADDRESS 0x38 /** * seven bit device address (binary): 011 1001 */ #define I2C_KEYBOARD_ADDRESS 0x39 #define LAMP(x) (0x8000>>x) #define LAMP_UPLINK_ACTY LAMP(0) #define LAMP_NO_ATT LAMP(1) #define LAMP_STBY LAMP(2) #define LAMP_KEY_REL LAMP(3) #define LAMP_OPR_ERR LAMP(4) #define LAMP_TEMP LAMP(7) #define LAMP_GIMBAL_LOCK LAMP(8) #define LAMP_PROG LAMP(9) #define LAMP_RESTART LAMP(10) #define LAMP_TRACKER LAMP(11) #define LAMP_ALT LAMP(12) #define LAMP_VEL LAMP(13) /* * DSKY EL Display serial protocol * as implemented in <NAME>'s EL Display Project * * Ben's DSKY_driver_V4seg driver firmware implements a subset of the full DSKY display driver functionality. * Notably, non-digit display values are supported by the DSKY, but not by this protocol * (see https://www.ibiblio.org/apollo/developer.html). * Sometime I may update the driver to implement the full protocol. * * The EL Display is controlled by sending a 26-character packet to the EL Display via the USB * serial interface: * * [PPNNVV+11111+22222+33333D * * 0 ASCII Left Brace "[" packet "start character" * 1-2 Prog digits (PP) * 3-4 Noun digits (NN) * 5-6 Verb digits (VV) * 7-12 top line +/-DDDDD * 13-18 middle line +/-DDDDD * 19-24 bottom line +/-DDDDD * 25 various discrete segments (values below) * * If the upper bit of any digit is set, the remaining bits are set/reset based on the * SEGMENT_ values below. If the upper bit is zero, then the character is interpreted * as an ASCII digit and the segments are set accordingly */ #define DIGIT_RAW_SEGMENT_CONTROL 0x80 /* * Raw segment bit defnitions recognized by DSKY EL Driver when the high-order bit * corresponding to the digit is set to "1" (DIGIT_RAW_SEGMENT_CONTROL) * a-g are traditional industry-standard seven-segment names. MIT used E, A, M, N, K, F, U as * names for the same segments. * * see https://github.com/rrainey/DSKY_EL_replica/blob/master/firmware%20-%20Arduino/DSKY_driver_V4seg/DSKY_driver_V4seg.ino */ #define SEGMENT_a 0x01 #define SEGMENT_b 0x02 #define SEGMENT_c 0x04 #define SEGMENT_d 0x08 #define SEGMENT_e 0x10 #define SEGMENT_f 0x20 #define SEGMENT_g 0x40 // Discrete visual sgements (trailing byte, (#25) in the communications protocol) // a=COMP ACTY, b=PROG, c=VERB, d=NOUN, e=upper line, f=middle line, g=lower line #define EL_SEGMENT_COMP_ACTY 0x01 #define EL_SEGMENT_PROG 0x02 #define EL_SEGMENT_VERB 0x04 #define EL_SEGMENT_NOUN 0x08 #define EL_SEGMENT_UPPER 0x10 #define EL_SEGMENT_MIDDLE 0x20 #define EL_SEGMENT_LOWER 0x40 // Sign digit definitions #define EL_SEGMENT_SIGN_MINUS SEGMENT_a #define EL_SEGMENT_SIGN_PLUS_TOP SEGMENT_b #define EL_SEGMENT_SIGN_PLUS_BOTTOM SEGMENT_g /* * End of DSKY EL Display serial protocol definitions */ class DSKYmaticIF { private: int fdAlarm; int fdELDisplay; int fdKeyboard; // Values received from Channel 010 (octal) output operations // Represents the EL Display state and some of the alarm/warning lamps unsigned short ch010Values[13]; // Channel commands are translated into equivalent EL Driver segment // directives that will generate the appropriate outputs. Those values are // saved here unsigned char prog[2]; unsigned char noun[2]; unsigned char verb[2]; unsigned char upper[5]; unsigned char middle[5]; unsigned char lower[5]; // EL Driver-compatible sign directived for each digit row; // Ben's EL Driver defines uses these segments when under raw control: // a = minus segment, b,g = "plus" segments. " ", "-", & "+" will // also work, but we'll use the direct segment control in this interface // for consistency. unsigned char s1placeholder, s2placeholder, s3placeholder; // cached alarm panel lamp states unsigned short lampState; // "Dirty" flags are set when a change is detected that will require updating the // appropriate display hardware. A "dirty" flag is reset after an update is transmitted. bool lampStateDirty; bool elDisplayStateDirty; /* * Experimental: track number of relays tripped each cycle to be able to render * appropriate sound effects. This is tracked today, but remains to be * fully implemented. */ int relayTripCount; bool compActyLamp; /** * Flash NOUN/VERB digits when commanded by the AGC * @see updateFlashingState */ bool flashNounVerb; /** * Some display elements flash at 1.5 CPS. * When "false", these elements should be inhibited. * @see updateFlashingState */ bool flashState; /** * Some display elements flash at 1.5 CPS. * Track wall clock time remaining to next on/off transition * @see updateFlashingState */ int flashCountdown_ms; bool reported2; public: DSKYmaticIF(); /** * Call exactly once to open connections to DSKY-matic Alarm, Keyboard, and EL Display */ int initialize(); /** * Transmits current display state to the EL Display board */ void updateELDisplay(); /** * Transmits current alarm panel state to the Alarm Panel */ void updateAlarmStatusPanel(); /** * Poll Keyboard and generate appropriate AGC Input Channel events. */ void checkKeyboard(); /** * Some displays/lamps on the DSKY flash at 1.5 CPS; to synchronize this flashing across * modules, we must track the passing of time manually. updateFlashingState must be called * periodically to keep allow this function to operate properly. * @param elapsed_ms elapsed wall clock time since last call */ void updateFlashingState(int elapsed_ms); /** * Called when AGC Channel events are passed to the application. * yaAGC sends these as UDP packets to this application. */ void processIncomingChannel(int channel, int value, int uBit); private: /* * Update Alarm panel driver via I2C interface */ bool sendLampState(unsigned int state); /* * Poll keyboard via I2C interface to determine if a key has been pressed or released * * @parm millis relative time of the event measured by the keyboards internal clock * @param s_id key code * @param state 0 == key release event, 1 == key press event */ bool checkKeyEvent( unsigned long *millis, unsigned char *s_id, unsigned char *state); /** * Handle channel output potentially altering a lamp relay. Mark the lamp driver for update if * the new value is different than the current state. */ void setLampState(int value, unsigned short channelBit, unsigned short driverBit); /** * Housekeeping to track changes in a specific EL Display digit. * Detects when a change actually occurs so that we can limit sending to the harware to * only when the display changed. */ void updateIfDigitChanged(unsigned char &oldValue, unsigned short channelValue); /** * Housekeeping to track changes in a specific EL Display sign segment */ void updateIfPlusSignChanged(unsigned char &oldValue, unsigned short channelValue); /** * Housekeeping to track changes in a specific EL Display sign segment */ void updateIfMinusSignChanged(unsigned char &oldValue, unsigned short channelValue); /** * Count number of bits changing in a value. Used to count the number of relays that are * changing state when a digit or lamp changes -- track this in order to be able to generate * relay clicking sound effects. * @param oldVal original value * @param newVal new value * @return tally of the number of changed bits */ unsigned short countChangedBits(unsigned short oldVal, unsigned short newVal); void outputKeycode (int keycode); void outputPro (int OffOn); /* * Translate DSKY segment code bits to EL Driver equivalent value; */ unsigned short mapBitsToELDriver(int bits); }; #endif
rrainey/DSKY-matic
src/yaDSKY2/ChannelQueue.h
/* * DSKY-matic driver interface for Raspberry Pi OS * * Copyright (c) 2020, <NAME> * * This file is part of the DSKY-matic project. All software in that project * is release via the GPL v2 license. See src/SOFTWARE-LICENSE.txt. Hardware and * artistic elements are covered by a separate CC-BY-SA license. * * DSKY-matic is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * DSKY-matic is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with DSKY-matic; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <list> class ChannelIOOperation { public: ChannelIOOperation( unsigned short usChannel, unsigned short usValue, unsigned short usMask = 077777 ) { m_usChannel = usChannel; m_usValue = usValue; m_usMask = usMask; } unsigned short m_usChannel; unsigned short m_usValue; unsigned short m_usMask; }; typedef std::list<ChannelIOOperation> ChannelIOList; extern ChannelIOList g_AGCChannelOutputQueue; extern ChannelIOList g_AGCChannelInputQueue; // Channel definitions from Delco Electronics, Apollo 15 CM SOFTWARE Manual // Colossus 3 (ARTEMIS 72) Software Description /** * CHANNEL WORD BIT NUMBERS */ #define BIT16 0100000 #define BIT15 040000 #define BIT14 020000 #define BIT13 010000 #define BIT12 004000 #define BIT11 002000 #define BIT10 001000 #define BIT9 000400 #define BIT8 000200 #define BIT7 000100 #define BIT6 000040 #define BIT5 000020 #define BIT4 000010 #define BIT3 000004 #define BIT2 000002 #define BIT1 000001 // see https://www.ibiblio.org/apollo/developer.html #define CH010_OPERATION_MASK (15<<11) #define CH010_OPERATION_M1M2 (11<<11) #define CH010_OPERATION_V1V2 (10<<11) #define CH010_OPERATION_N1N2 (9<<11) #define CH010_OPERATION_DIGIT11 (8<<11) #define CH010_OPERATION_DIGIT1213 (7<<11) //1+ in BIT11 #define CH010_OPERATION_DIGIT1415 (6<<11) //1- in BIT11 #define CH010_OPERATION_DIGIT2122 (5<<11) //2+ in BIT11 #define CH010_OPERATION_DIGIT2324 (4<<11) //2- in BIT11 #define CH010_OPERATION_DIGIT2531 (3<<11) #define CH010_OPERATION_DIGIT3233 (2<<11) //3+ in BIT11 #define CH010_OPERATION_DIGIT3435 (1<<11) //3- in BIT11 #define CH010_OPERATION_LAMPS (12<<11) #define CH010_PRIO_DISP_LAMP BIT1 #define CH010_NO_DAP_LAMP BIT2 #define CH010_VEL_LAMP BIT3 #define CH010_NO_ATT_LAMP BIT4 #define CH010_ALT_LAMP BIT5 #define CH010_GIMBAL_LOCK_LAMP BIT6 #define CH010_TRACKER_LAMP BIT8 #define CH010_PROG_LAMP BIT9 #define CH010_CCCCC_VALUE(x) (((x) & (0x1F << 5)>> 5) #define CH010_DDDDD_VALUE(x) ((x) & 0x1F) /* * From https://www.ibiblio.org/apollo/Documents/agc_programming_info.pdf */ #define CH011_ISS_WARNING 0x001 #define CH011_COMP_ACTY_LAMP 0x002 #define CH011_UPLINK_ACTY_LAMP 0x004 #define CH011_TEMP_CAUTION 0x008 #define CH011_KEYBOARD_RELEASE_LAMP 0x010 // flashes at 1.5 CPS #define CH011_FLASH_VERB_NOUN_LAMPS 0x020 // flashes at 1.5 CPS see https://www.ibiblio.org/apollo/Documents/acelectroniclmma00acel_0.pdf #define CH011_OPER_ERROR_LAMP 0x040 // flashes at 1.5 CPS /** * S-IVB Separate, Abort; 0 = TRUE */ #define CH030_SIVB_SEPARATE_ABORT BIT4 /** * LIFTOFF DISCRETE, 0 = TRUE */ #define CH030_LIFTOFF BIT5 /** * GUIDANCE REFERENCE RELEASE, 0 = TRUE */ #define CH030_GRR BIT6 /** * IMU Operate; 0 = TRUE */ #define CH030_IMU_OPERATE BIT9 /** * Spacecraft control of Saturn L/V; 1 = IU Control, 0 = S/C Control */ #define CH030_SC_CONTROL BIT10 /** * ISS Turn on Request; 0 = TRUE */ #define CH030_ISS_TURN_ON_REQUEST BIT14 /** * ISS Temp in limits; 0 = TRUE */ #define CH030_ISS_TEMP_IN_LIMITS BIT15
jarvanh/HyperFT
Prj-Linux/LandmarkTracking.h
#ifndef ZEUSEESFACETRACKING_H #define ZEUSEESFACETRACKING_H //#include <opencv2/opencv.hpp> //#include <thread> #include "mtcnn.h" #include "time.h" #include "colotracker.h" cv::Rect boundingRect(const std::vector<cv::Point>& pts) { if (pts.size() > 1) { int xmin = pts[0].x; int ymin = pts[0].y; int xmax = pts[0].x; int ymax = pts[0].y; for (int i = 1; i < pts.size(); i++) { if (pts[i].x < xmin) xmin = pts[i].x; if (pts[i].y < ymin) ymin = pts[i].y; if (pts[i].x > xmax) xmax = pts[i].x; if (pts[i].y > ymax) ymax = pts[i].y; } return cv::Rect(xmin, ymin, xmax - xmin, ymax - ymin); } } //typedef int T; //T i = 1; class Face { public: Face(int instance_id, Shape::Rect<float> rect) { face_id = instance_id; face_location = rect; isCanShow = false; //追踪一次后待框稳定后即可显示 } Face() { isCanShow = false; //追踪一次后待框稳定后即可显示 } Bbox faceBbox; int face_id = -1; long frameId = 0; int ptr_num = 0; Shape::Rect<float> face_location; bool isCanShow; cv::Mat frame_face_prev; static cv::Rect SquarePadding(cv::Rect facebox, int margin_rows, int margin_cols, bool max) { int c_x = facebox.x + facebox.width / 2; int c_y = facebox.y + facebox.height / 2; int large = 0; if (max) large = std::max(facebox.height, facebox.width) / 2; else large = min(facebox.height, facebox.width) / 2; cv::Rect rectNot(c_x - large, c_y - large, c_x + large, c_y + large); rectNot.x = std::max(0, rectNot.x); rectNot.y = std::max(0, rectNot.y); rectNot.height = min(rectNot.height, margin_rows - 1); rectNot.width = min(rectNot.width, margin_cols - 1); if (rectNot.height - rectNot.y != rectNot.width - rectNot.x) return SquarePadding(cv::Rect(rectNot.x, rectNot.y, rectNot.width - rectNot.x, rectNot.height - rectNot.y), margin_rows, margin_cols, false); return cv::Rect(rectNot.x, rectNot.y, rectNot.width - rectNot.x, rectNot.height - rectNot.y); } static cv::Rect SquarePadding(cv::Rect facebox, int padding) { int c_x = facebox.x - padding; int c_y = facebox.y - padding; return cv::Rect(facebox.x - padding, facebox.y - padding, facebox.width + padding * 2, facebox.height + padding * 2);; } static double getDistance(cv::Point x, cv::Point y) { return sqrt((x.x - y.x) * (x.x - y.x) + (x.y - y.y) * (x.y - y.y)); } vector<vector<cv::Point> > faceSequence; vector<vector<float>> attitudeSequence; }; class FaceTracking { public: FaceTracking(string modelPath) { this->detector = new MTCNN(modelPath); downSimpilingFactor = 1; faceMinSize = 70; this->detector->SetMinFace(faceMinSize); detection_Time = -1; } ~FaceTracking() { delete this->detector; } void detecting(cv::Mat* image) { ncnn::Mat ncnn_img = ncnn::Mat::from_pixels(image->data, ncnn::Mat::PIXEL_BGR2RGB, image->cols, image->rows); std::vector<Bbox> finalBbox; if(isMaxFace) detector->detectMaxFace(ncnn_img, finalBbox); else detector->detect(ncnn_img, finalBbox); const int num_box = finalBbox.size(); std::vector<cv::Rect> bbox; bbox.resize(num_box); candidateFaces_lock = 1; for (int i = 0; i < num_box; i++) { bbox[i] = cv::Rect(finalBbox[i].x1, finalBbox[i].y1, finalBbox[i].x2 - finalBbox[i].x1 + 1, finalBbox[i].y2 - finalBbox[i].y1 + 1); bbox[i] = Face::SquarePadding(bbox[i], image->rows, image->cols, true); Shape::Rect<float> f_rect(bbox[i].x / static_cast<float>(image->cols), bbox[i].y / static_cast<float>(image->rows), bbox[i].width / static_cast<float>(image->cols), bbox[i].height / static_cast<float>(image->rows) ); std::shared_ptr<Face> face(new Face(trackingID, f_rect)); (*image)(bbox[i]).copyTo(face->frame_face_prev); trackingID = trackingID + 1; candidateFaces.push_back(*face); } candidateFaces_lock = 0; } void Init(cv::Mat& image) { ImageHighDP = image; cv::Size lowDpSize(ImageHighDP.cols / downSimpilingFactor, ImageHighDP.rows / downSimpilingFactor); cv::resize(image, ImageLowDP, lowDpSize); trackingID = 0; detection_Interval = 200; //detect faces every 200 ms detecting(&image); stabilization = false; UI_height = image.rows; UI_width = image.cols; lastImage =image.clone(); MF_Tracker.init(image); } void doingLandmark_onet(cv::Mat& face, Bbox& faceBbox, int zeroadd_x, int zeroadd_y, int stable_state = 0) { ncnn::Mat in = ncnn::Mat::from_pixels_resize(face.data, ncnn::Mat::PIXEL_BGR, face.cols, face.rows, 48, 48); faceBbox = detector->onet(in, zeroadd_x, zeroadd_y, face.cols, face.rows); } void tracking_corrfilter(const cv::Mat& frame, const cv::Mat& model, cv::Rect& trackBox, float scale) { trackBox.x /= scale; trackBox.y /= scale; trackBox.height /= scale; trackBox.width /= scale; int zeroadd_x = 0; int zeroadd_y = 0; cv::Mat frame_; cv::Mat model_; cv::resize(frame, frame_, cv::Size(), 1 / scale, 1 / scale); cv::resize(model, model_, cv::Size(), 1 / scale, 1 / scale); cv::Mat gray; cvtColor(frame_, gray, cv::COLOR_RGB2GRAY); cv::Mat gray_model; cvtColor(model_, gray_model, cv::COLOR_RGB2GRAY); cv::Rect searchWindow; searchWindow.width = trackBox.width * 3; searchWindow.height = trackBox.height * 3; searchWindow.x = trackBox.x + trackBox.width * 0.5 - searchWindow.width * 0.5; searchWindow.y = trackBox.y + trackBox.height * 0.5 - searchWindow.height * 0.5; searchWindow &= cv::Rect(0, 0, frame_.cols, frame_.rows); cv::Mat similarity; matchTemplate(gray(searchWindow), gray_model, similarity, cv::TM_CCOEFF_NORMED); double mag_r; cv::Point point; minMaxLoc(similarity, 0, &mag_r, 0, &point); trackBox.x = point.x + searchWindow.x; trackBox.y = point.y + searchWindow.y; trackBox.x *= scale; trackBox.y *= scale; trackBox.height *= scale; trackBox.width *= scale; } bool tracking(cv::Mat& image, Face& face) { cv::Rect faceROI = face.face_location.convert_cv_rect(image.rows, image.cols); cv::Mat faceROI_Image; double t = (double)getTickCount();//开始时间 //tracking_corrfilter(image, face.frame_face_prev, faceROI, tpm_scale); faceROI =MF_Tracker.track(image,lastImage,faceROI.x,faceROI.y,faceROI.x+faceROI.width,faceROI.y+faceROI.height); t = (double)getTickCount() - t;//代码运行时间=结束时间-开始时间 //printf("互相关匹配时间= %gms\n", t*1000. / getTickFrequency());//转换时间单位并输出代码运行时间 printf("光流时间= %gms\n", t*1000. / getTickFrequency());//转换时间单位并输出代码运行时间 //lastImage = image; image(faceROI).copyTo(faceROI_Image); cv::Rect bdbox; doingLandmark_onet(faceROI_Image, face.faceBbox, faceROI.x, faceROI.y, face.frameId > 1); bdbox.x = face.faceBbox.x1; bdbox.y = face.faceBbox.y1; bdbox.width = face.faceBbox.x2 - face.faceBbox.x1; bdbox.height = face.faceBbox.y2 - face.faceBbox.y1; bdbox = Face::SquarePadding(bdbox, static_cast<int>(bdbox.height * -0.05)); bdbox = Face::SquarePadding(bdbox, image.rows, image.cols, 1); Shape::Rect<float> boxfloat(bdbox.x / static_cast<float>(image.cols), bdbox.y / static_cast<float>(image.rows), bdbox.width / static_cast<float>(image.cols), bdbox.height / static_cast<float>(image.rows)); face.faceBbox.x1 = bdbox.x; face.faceBbox.y1 = bdbox.y; face.faceBbox.x2 = bdbox.x + bdbox.width; face.faceBbox.y2 = bdbox.y + bdbox.height; face.face_location = boxfloat; faceROI = face.face_location.convert_cv_rect(image.rows, image.cols); image(faceROI).copyTo(face.frame_face_prev); face.frameId += 1; ncnn::Mat rnet_data = ncnn::Mat::from_pixels_resize(faceROI_Image.data, ncnn::Mat::PIXEL_BGR2RGB, faceROI_Image.cols, faceROI_Image.rows, 24, 24); float sim = detector->rnet(rnet_data); face.isCanShow = true; if (sim > 0.9) { //stablize float diff_x = 0; float diff_y = 0; return true; } return false; } void setMask(cv::Mat& image, cv::Rect& rect_mask) { int height = image.rows; int width = image.cols; cv::Mat subImage = image(rect_mask); subImage.setTo(0); } void update(cv::Mat& image) { ImageHighDP = image; //std::cout << trackingFace.size() << std::endl; if (candidateFaces.size() > 0 && !candidateFaces_lock) { for (int i = 0; i < candidateFaces.size(); i++) { trackingFace.push_back(candidateFaces[i]); } candidateFaces.clear(); } for (vector<Face>::iterator iter = trackingFace.begin(); iter != trackingFace.end();) { if (!tracking(image, *iter)) { iter = trackingFace.erase(iter); //追踪失败 则删除此人脸 } else { iter++; } } if (trackingFace.size() <= 0) { detection_Interval = 200; } else { detection_Interval = 1000; } if (detection_Time < 0) { detection_Time = (double)cv::getTickCount(); } else { double diff = (double)(cv::getTickCount() - detection_Time) * 1000 / cv::getTickFrequency(); if (diff > detection_Interval) { cv::Size lowDpSize(ImageHighDP.cols / downSimpilingFactor, ImageHighDP.rows / downSimpilingFactor); cv::resize(image, ImageLowDP, lowDpSize); //set Mask to protect the tracking face not to be detected. for (auto& face : trackingFace) { Shape::Rect<float> rect = face.face_location; cv::Rect rect1 = rect.convert_cv_rect(ImageLowDP.rows, ImageLowDP.cols); setMask(ImageLowDP, rect1); } detection_Time = (double)cv::getTickCount(); // do detection in thread detecting(&ImageLowDP); } } } vector<Face> trackingFace; //跟踪中的人脸 int UI_width; int UI_height; private: cv::Mat lastImage; int isLostDetection; int isTracking; int isDetection; cv::Mat ImageHighDP; cv::Mat ImageLowDP; int downSimpilingFactor; int faceMinSize; MTCNN* detector; ColorTracker MF_Tracker; vector<Face> candidateFaces; // 将检测到的人脸放入此列队 待跟踪的人脸 bool candidateFaces_lock; double detection_Time; double detection_Interval; int trackingID; bool stabilization; int tpm_scale = 2; bool isMaxFace = true; }; #endif //ZEUSEESFACETRACKING_H
jarvanh/HyperFT
Prj-Win/3rd/ncnn/include/modelbin.h
<filename>Prj-Win/3rd/ncnn/include/modelbin.h // Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #ifndef NCNN_MODELBIN_H #define NCNN_MODELBIN_H #include <stdio.h> #include "mat.h" #include "platform.h" namespace ncnn { class Net; class ModelBin { public: // element type // 0 = auto // 1 = float32 // 2 = float16 // 3 = int8 // load vec virtual Mat load(int w, int type) const = 0; // load image virtual Mat load(int w, int h, int type) const; // load dim virtual Mat load(int w, int h, int c, int type) const; }; #if NCNN_STDIO class ModelBinFromStdio : public ModelBin { public: // construct from file ModelBinFromStdio(FILE* binfp); virtual Mat load(int w, int type) const; protected: FILE* binfp; }; #endif // NCNN_STDIO class ModelBinFromMemory : public ModelBin { public: // construct from external memory ModelBinFromMemory(const unsigned char*& mem); virtual Mat load(int w, int type) const; protected: const unsigned char*& mem; }; class ModelBinFromMatArray : public ModelBin { public: // construct from weight blob array ModelBinFromMatArray(const Mat* weights); virtual Mat load(int w, int type) const; protected: mutable const Mat* weights; }; } // namespace ncnn #endif // NCNN_MODELBIN_H
jarvanh/HyperFT
Prj-Linux/colotracker.h
#ifndef COLOTRACKER_H #define COLOTRACKER_H //#include "cv.h" //#include "highgui.h" #include "opencv/cv.h" #include "opencv/highgui.h" #include <iostream> using namespace std; using namespace cv; class ColorTracker { private: double bbox_x; double bbox_y; double bbox_width; double bbox_height; double xmean = 0; double ymean = 0; float median; int npoints = 64; // Number of feature points int pcount; // Number of passed points that finally track //IplImage *frame; //IplImage *frame1_1C = NULL,*frame2_1C = NULL; cv::Mat frame; cv::Mat frame1_1C,frame2_1C; int winsize = 5; CvPoint pta,ptb; // Init methods double euclid_dist(const Point2f* point1, const Point2f* point2); void pairwise_dist(const Point2f* features, double *edist, int npoin); void ncc_filter(cv::Mat frame1, cv::Mat frame2, Point2f *prev_feat, Point2f *curr_feat, int npoin, int method, cv::Mat rec0, cv::Mat rec1, cv::Mat res, int *ncc_pass); void fb_filter(const Point2f* prev_features, const Point2f* backward_features, const Point2f* curr_feat, int *fb_pass, const int npoin); void bbox_move(const Point2f* prev_feat, const Point2f* curr_feat, const int npoin,double &xmean, double &ymean); public: cv::Rect FirstRect; cv::Mat FirstMat; void init(cv::Mat & img); bool lost =false; //frame-to-frame object tracking cv::Rect track(cv::Mat & img,cv::Mat before,double x1, double y1, double x2, double y2); inline cv::Rect track(cv::Mat & img,cv::Mat before) { return track(img,before,bbox_x, bbox_y,bbox_x+bbox_width, bbox_y+bbox_height); } }; #endif // COLOTRACKER_H
jarvanh/HyperFT
Prj-Android/app/src/main/cpp/LandmarkTracking.h
#ifndef ZEUSEESFACETRACKING_H #define ZEUSEESFACETRACKING_H #include <opencv2/opencv.hpp> #include <thread> #include "mtcnn.h" #include "time.h" #include <android/log.h> namespace Shape{ template <typename T> class Rect{ public: Rect(){} Rect(T x,T y,T w,T h) { this->x = x; this->y = y; this->width = w; height = h; } T x; T y; T width; T height; cv::Rect convert_cv_rect(int _height,int _width) { cv::Rect Rect_(static_cast<int>(x*_width),static_cast<int>(y*_height), static_cast<int>(width*_width),static_cast<int>(height*_height)); return Rect_; } }; } #define WITH_ATT 0 static int HeadPosePointIndexs[] = {94,59,27,20,69,45,50}; int *estimateHeadPosePointIndexs = HeadPosePointIndexs; static float estimateHeadPose2dArray[] = { -0.208764,-0.140359,0.458815,0.106082,0.00859783,-0.0866249,-0.443304,-0.00551231,-0.0697294, -0.157724,-0.173532,0.16253,0.0935172,-0.0280447,0.016427,-0.162489,-0.0468956,-0.102772, 0.126487,-0.164141,0.184245,0.101047,0.0104349,-0.0243688,-0.183127,0.0267416,0.117526, 0.201744,-0.051405,0.498323,0.0341851,-0.0126043,0.0578142,-0.490372,0.0244975,0.0670094, 0.0244522,-0.211899,-1.73645,0.0873952,0.00189387,0.0850161,1.72599,0.00521321,0.0315345, -0.122839,0.405878,0.28964,-0.23045,0.0212364,-0.0533548,-0.290354,0.0718529,-0.176586, 0.136662,0.335455,0.142905,-0.191773,-0.00149495,0.00509046,-0.156346,-0.0759126,0.133053, -0.0393198,0.307292,0.185202,-0.446933,-0.0789959,0.29604,-0.190589,-0.407886,0.0269739, -0.00319206,0.141906,0.143748,-0.194121,-0.0809829,0.0443648,-0.157001,-0.0928255,0.0334674, -0.0155408,-0.145267,-0.146458,0.205672,-0.111508,0.0481617,0.142516,-0.0820573,0.0329081, -0.0520549,-0.329935,-0.231104,0.451872,-0.140248,0.294419,0.223746,-0.381816,0.0223632, 0.176198,-0.00558382,0.0509544,0.0258391,0.050704,-1.10825,-0.0198969,1.1124,0.189531, -0.0352285,0.163014,0.0842186,-0.24742,0.199899,0.228204,-0.0721214,-0.0561584,-0.157876, -0.0308544,-0.131422,-0.0865534,0.205083,0.161144,0.197055,0.0733392,-0.0916629,-0.147355, 0.527424,-0.0592165,0.0150818,0.0603236,0.640014,-0.0714241,-0.0199933,-0.261328,0.891053}; cv::Mat estimateHeadPoseMat = cv::Mat(15,9,CV_32FC1,estimateHeadPose2dArray); static float estimateHeadPose2dArray2[] = { 0.139791,27.4028,7.02636, -2.48207,9.59384,6.03758, 1.27402,10.4795,6.20801, 1.17406,29.1886,1.67768, 0.306761,-103.832,5.66238, 4.78663,17.8726,-15.3623, -5.20016,9.29488,-11.2495, -25.1704,10.8649,-29.4877, -5.62572,9.0871,-12.0982, -5.19707,-8.25251,13.3965, -23.6643,-13.1348,29.4322, 67.239,0.666896,1.84304, -2.83223,4.56333,-15.885, -4.74948,-3.79454,12.7986, -16.1,1.47175,4.03941 }; cv::Mat estimateHeadPoseMat2 = cv::Mat(15,3,CV_32FC1,estimateHeadPose2dArray2); void EstimateHeadPose(std::vector<cv::Point> &current_shape, cv::Vec3d &eav){ if(current_shape.empty()) return; static const int samplePdim = 7; float miny = 10000000000.0f; float maxy = 0.0f; float sumx = 0.0f; float sumy = 0.0f; for(int i=0; i<samplePdim; i++){ sumx += current_shape[i].x; float y = current_shape[i].y; sumy += y; if(miny > y) miny = y; if(maxy < y) maxy = y; } float dist = maxy - miny; sumx = sumx/samplePdim; sumy = sumy/samplePdim; static cv::Mat tmp(1, 2*samplePdim+1, CV_32FC1); for(int i=0; i<samplePdim; i++){ tmp.at<float>(i) = (current_shape[estimateHeadPosePointIndexs[i]].x - sumx)/dist; tmp.at<float>(i+samplePdim) = (current_shape[estimateHeadPosePointIndexs[i]].y-sumy)/dist; } tmp.at<float>(2*samplePdim) = 1.0f; cv::Mat predict = tmp*estimateHeadPoseMat2; eav[0] = predict.at<float>(0); eav[1] = predict.at<float>(1); eav[2] = predict.at<float>(2); return; } cv::Rect boundingRect(const std::vector<cv::Point> &pts){ if(pts.size()>1) { int xmin = pts[0].x; int ymin = pts[0].y; int xmax = pts[0].x; int ymax = pts[0].y; for(int i = 1 ; i < pts.size(); i ++) { if(pts[i].x<xmin) xmin = pts[i].x; if(pts[i].y<ymin) ymin = pts[i].y; if(pts[i].x>xmax) xmax= pts[i].x; if(pts[i].y>ymax) ymax= pts[i].y; } return cv::Rect(xmin,ymin,xmax-xmin,ymax-ymin); } } //typedef int T; //T i = 1; class Face{ public: Face(int instance_id,Shape::Rect<float> rect){ face_id = instance_id; landmark = std::shared_ptr<vector<cv::Point> >(new vector<cv::Point>(106)); // landmark_prev = std::shared_ptr<vector<cv::Point> >(new vector<cv::Point>(106)); face_location = rect; isCanShow = false; //追踪一次后待框稳定后即可显示 for(int i = 0 ; i < 106;i++) { (*landmark)[i].x = -1; (*landmark)[i].y = -1; } } Face(){ landmark = std::shared_ptr<vector<cv::Point> >(new vector<cv::Point>(106)); isCanShow = false; //追踪一次后待框稳定后即可显示 } std::shared_ptr<vector<cv::Point> > landmark; int landmark_prev[212]; int face_id = -1; long frameId = 0 ; int ptr_num = 0; int ptr_eye_state = 0; Shape::Rect<float> face_location; bool isCanShow; bool stateMonth; bool stateEye; bool stateRise; bool stateShake; double eulerAngle[3]; bool state_left[20] = {false}; bool state_right[20] = {false}; cv::Mat frame_face_prev; static cv::Rect SquarePadding(cv::Rect facebox,int margin_rows,int margin_cols,bool max) { int c_x = facebox.x + facebox.width/2; int c_y = facebox.y + facebox.height/2; int large = 0 ; if(max) large = std::max(facebox.height,facebox.width)/2; else large = std::min(facebox.height,facebox.width)/2; cv::Rect rectNot(c_x-large,c_y-large,c_x+large,c_y+large); rectNot.x = std::max(0,rectNot.x); rectNot.y = std::max(0,rectNot.y); rectNot.height= std::min(rectNot.height,margin_rows-1); rectNot.width = std::min(rectNot.width,margin_cols-1); if(rectNot.height-rectNot.y!=rectNot.width-rectNot.x) return SquarePadding(cv::Rect(rectNot.x,rectNot.y,rectNot.width-rectNot.x,rectNot.height - rectNot.y),margin_rows,margin_cols,false); return cv::Rect(rectNot.x,rectNot.y,rectNot.width-rectNot.x,rectNot.height - rectNot.y); } static cv::Rect SquarePadding(cv::Rect facebox,int padding) { int c_x = facebox.x - padding; int c_y = facebox.y - padding; return cv::Rect(facebox.x-padding,facebox.y-padding,facebox.width+padding*2,facebox.height+ padding*2);; } static double getDistance(cv::Point x,cv::Point y) { return sqrt((x.x - y.x)*(x.x - y.x)+(x.y - y.y)*(x.y - y.y)); } vector<vector<cv::Point> > faceSequence; vector<vector<float>> attitudeSequence; }; class FaceTracking{ public: FaceTracking(string modelPath) { this->detector =new MTCNN (modelPath); downSimpilingFactor = 1; faceMinSize = 70; this->detector->SetMinFace(faceMinSize); detection_Time = -1; } ~FaceTracking(){ delete this->detector; } void detecting(cv::Mat *image) { ncnn::Mat ncnn_img = ncnn::Mat::from_pixels(image->data, ncnn::Mat::PIXEL_BGR2RGB, image->cols, image->rows); std::vector<Bbox> finalBbox; detector->detect(ncnn_img, finalBbox); const int num_box = finalBbox.size(); std::vector<cv::Rect> bbox; bbox.resize(num_box); candidateFaces_lock = 1; for (int i = 0; i < num_box; i++) { bbox[i] = cv::Rect(finalBbox[i].x1, finalBbox[i].y1, finalBbox[i].x2 - finalBbox[i].x1 + 1, finalBbox[i].y2 - finalBbox[i].y1 + 1); bbox[i] = Face::SquarePadding(bbox[i],image->rows,image->cols,true); Shape::Rect<float> f_rect(bbox[i].x/ static_cast<float>(image->cols), bbox[i].y/ static_cast<float>(image->rows), bbox[i].width/ static_cast<float>(image->cols), bbox[i].height/ static_cast<float>(image->rows) ); std::shared_ptr<Face> face(new Face(trackingID,f_rect)); (*image)(bbox[i]).copyTo(face->frame_face_prev ); trackingID = trackingID+1; candidateFaces.push_back(*face); } candidateFaces_lock = 0 ; } void Init(cv::Mat &image){ ImageHighDP = image; cv::Size lowDpSize(ImageHighDP.cols/downSimpilingFactor,ImageHighDP.rows/downSimpilingFactor); cv::resize(image,ImageLowDP,lowDpSize); trackingID = 0 ; detection_Interval = 350; //detect faces every 200 ms detecting(&image); stabilization = 0; UI_height = image.rows; UI_width= image.cols; } void doingLandmark_onet(cv::Mat &face,std::vector<cv::Point> &pts,int zeroadd_x ,int zeroadd_y,int stable_state =0 ) { ncnn::Mat in = ncnn::Mat::from_pixels_resize(face.data, ncnn::Mat::PIXEL_BGR, face.cols, face.rows, 48, 48); const float mean_vals[3] = {127.5f, 127.5f, 127.5f}; const float norm_vals[3] = {1.0 / 127.5, 1.0 / 127.5, 1.0 / 127.5}; in.substract_mean_normalize(mean_vals, norm_vals); ncnn::Extractor Onet= detector->Onet.create_extractor(); Onet.set_num_threads(2); Onet.input("data", in); ncnn::Mat out; Onet.extract("conv6-2", out); __android_log_print(ANDROID_LOG_ERROR,"landmark","conv6-2 output %f %f %f %f",out[0],out[1],out[2],out[3]); for (int j = 0; j < 2; j++) { int x = 0 ; int y= 0 ; if (j == 0) { x = static_cast<int>(out[j * 2 + 0] * face.cols) + zeroadd_x; y = static_cast<int>(out[j * 2 + 1] * face.rows) + zeroadd_y; } else{ x = static_cast<int>(out[j * 2 + 0] * face.cols) +face.cols+ zeroadd_x; y = static_cast<int>(out[j * 2 + 1] * face.rows) +face.rows+ zeroadd_y; } __android_log_print(ANDROID_LOG_ERROR,"landmark","landmark %d %d",x,y); cv::Point p(x, y); pts[j] = p; } //for (int j = 0; j < 5; j++) { // int x = 0 ; // int y= 0 ; // x = static_cast<int>(out[j + 0] * face.cols) + zeroadd_x; // y = static_cast<int>(out[j + 5] * face.rows) + zeroadd_y; // // __android_log_print(ANDROID_LOG_ERROR,"landmark","landmark %d %d",x,y); // cv::Point p(x, y); // pts[j] = p; //} } void doingLandmark_112(cv::Mat &face,std::vector<cv::Point> &pts,int zeroadd_x ,int zeroadd_y,int stable_state =0 ) { //ncnn::Mat in = ncnn::Mat::from_pixels_resize(face.data, ncnn::Mat::PIXEL_BGR, face.cols, face.rows, 80, 80); ncnn::Mat in = ncnn::Mat::from_pixels_resize(face.data, ncnn::Mat::PIXEL_BGR, face.cols, face.rows, 112, 112); const float mean_vals[3] = {127.5f, 127.5f, 127.5f}; const float norm_vals[3] = {1.0 / 127.5, 1.0 / 127.5, 1.0 / 127.5}; in.substract_mean_normalize(mean_vals, norm_vals); ncnn::Extractor frNet = net_landmark_.create_extractor(); frNet.set_num_threads(2); // frNet.set_light_mode(true); frNet.input("data", in); ncnn::Mat out; frNet.extract("prelu1", out); __android_log_print(ANDROID_LOG_ERROR,"ncnn","h:%d w:%d c:%d",out.h,out.w,out.c); for (int j = 0; j < 106; j++) { int x = static_cast<int>(out[j * 2 + 0] * face.cols)+zeroadd_x; int y = static_cast<int>(out[j * 2 + 1] * face.rows)+zeroadd_y; cv::Point p(x, y); pts[j] = p; } } void tracking_corrfilter(const cv::Mat &frame, const cv::Mat &model, cv::Rect &trackBox,float scale ) { trackBox.x/=scale; trackBox.y/=scale; trackBox.height/=scale; trackBox.width/=scale; int zeroadd_x = 0; int zeroadd_y = 0; cv::Mat frame_; cv::Mat model_; cv::resize(frame,frame_,cv::Size(),1/scale,1/scale); cv::resize(model,model_,cv::Size(),1/scale,1/scale); cv::Mat gray; cvtColor(frame_, gray, CV_RGB2GRAY); cv::Mat gray_model; cvtColor(model_, gray_model, CV_RGB2GRAY); cv::Rect searchWindow; searchWindow.width = trackBox.width * 3; searchWindow.height = trackBox.height * 3; searchWindow.x = trackBox.x + trackBox.width * 0.5 - searchWindow.width * 0.5; searchWindow.y = trackBox.y + trackBox.height * 0.5 - searchWindow.height * 0.5; searchWindow &= cv::Rect(0, 0, frame_.cols, frame_.rows); cv::Mat similarity; matchTemplate(gray(searchWindow), gray_model, similarity, CV_TM_CCOEFF_NORMED); double mag_r; cv::Point point; minMaxLoc(similarity, 0, &mag_r, 0, &point); trackBox.x = point.x + searchWindow.x; trackBox.y = point.y + searchWindow.y; trackBox.x*=scale; trackBox.y*=scale; trackBox.height*=scale; trackBox.width*=scale; } bool tracking( cv::Mat &image, Face &face) { cv::Rect faceROI = face.face_location.convert_cv_rect(image.rows,image.cols); cv::Mat faceROI_Image; tracking_corrfilter(image,face.frame_face_prev,faceROI,2); image(faceROI).copyTo(faceROI_Image); clock_t start_time = clock(); (*face.landmark).resize(2); doingLandmark_onet(faceROI_Image,*face.landmark,faceROI.x,faceROI.y,face.frameId>1); //doingLandmark_112(faceROI_Image,*face.landmark,faceROI.x,faceROI.y,face.frameId>1); clock_t finish_time = clock(); double total_time = (double) (finish_time - start_time) / CLOCKS_PER_SEC; cv::Rect bdbox((*face.landmark)[0].x,(*face.landmark)[0].y,(*face.landmark)[1].x-(*face.landmark)[0].x,(*face.landmark)[1].y-(*face.landmark)[0].y); // cv::Rect bdbox = cv::boundingRect((*face.landmark)); // bdbox = Face::SquarePadding(bdbox, static_cast<int>(bdbox.height*0.55)); bdbox = Face::SquarePadding(bdbox, static_cast<int>(bdbox.height*-0.05)); bdbox = Face::SquarePadding(bdbox,image.rows,image.cols,1); Shape::Rect<float> boxfloat(bdbox.x/ static_cast<float>(image.cols), bdbox.y/ static_cast<float>(image.rows), bdbox.width/ static_cast<float>(image.cols), bdbox.height/ static_cast<float>(image.rows)); // face.face_location.height = boxfloat.height; // face.face_location.width= boxfloat.width; // face.face_location.x= (faceROI.x*0.5 +bdbox.x*0.5)/static_cast<float>(image.cols); // face.face_location.y = (faceROI.y*0.5 + bdbox.y*0.5)/static_cast<float>(image.rows); face.face_location= boxfloat; faceROI = face.face_location.convert_cv_rect(image.rows,image.cols); image(faceROI).copyTo(face.frame_face_prev); face.frameId+=1; ncnn::Extractor Rnet= detector->Rnet.create_extractor(); const float mean_vals[3] = {127.5, 127.5, 127.5}; const float norm_vals[3] = {0.0078125, 0.0078125, 0.0078125}; ncnn::Mat rnet_data= ncnn::Mat::from_pixels_resize(faceROI_Image.data, ncnn::Mat::PIXEL_BGR2RGB, faceROI_Image.cols, faceROI_Image.rows, 24, 24); rnet_data.substract_mean_normalize(mean_vals,norm_vals); Rnet.input("data", rnet_data); ncnn::Mat out_origin; Rnet.extract("prob1", out_origin); face.isCanShow = true; if(out_origin[1]>0.1){ //stablize float diff_x = 0 ; float diff_y = 0 ; return true; } return false; } void setMask(cv::Mat &image,cv::Rect &rect_mask) { int height = image.rows; int width = image.cols; cv::Mat subImage = image(rect_mask); subImage.setTo(0); } void update( cv::Mat &image) { ImageHighDP = image; std::cout<<trackingFace.size()<<std::endl; if(candidateFaces.size()>0 && !candidateFaces_lock) { for(int i = 0 ; i < candidateFaces.size() ; i++) { trackingFace.push_back(candidateFaces[i]); } candidateFaces.clear(); } for(vector<Face>::iterator iter = trackingFace.begin();iter != trackingFace.end();) { if(!tracking(image,*iter)) { iter = trackingFace.erase(iter); //追踪失败 则删除此人脸 } else{ iter++; } } if(detection_Time < 0 ) { detection_Time = (double)cvGetTickCount(); } else{ double diff= (double)cvGetTickCount() - detection_Time ; diff /=(cvGetTickFrequency()*1000); if(diff>detection_Interval ) { cv::Size lowDpSize(ImageHighDP.cols/downSimpilingFactor,ImageHighDP.rows/downSimpilingFactor); cv::resize(image,ImageLowDP,lowDpSize); //set Mask to protect the tracking face not to be detected. for( auto &face:trackingFace) { Shape::Rect<float> rect = face.face_location; cv::Rect rect1 = rect.convert_cv_rect(ImageLowDP.rows,ImageLowDP.cols); setMask(ImageLowDP,rect1); } detection_Time = (double)cvGetTickCount(); // do detection in thread detecting(&ImageLowDP); } } } vector<Face> trackingFace; //跟踪中的人脸 int UI_width; int UI_height; private: // float template_face[]; // 姿态角估计 int isLostDetection; int isTracking; int isDetection; cv::Mat ImageHighDP; cv::Mat ImageLowDP; int downSimpilingFactor; int faceMinSize; MTCNN *detector; vector<Face> candidateFaces; // 将检测到的人脸放入此列队 待跟踪的人脸 bool candidateFaces_lock; double detection_Time; double detection_Interval; ncnn::Net net_landmark_; ncnn::Net net_eye_classifier; float stable_factor_stage1 = 0.2f; float stable_factor_stage2 = 2.0f; int trackingID; bool stabilization; }; #endif //ZEUSEESFACETRACKING_H
cmkcoin/cmkcore
src/qt/forms/ui_darksendconfig.h
/******************************************************************************** ** Form generated from reading UI file 'darksendconfig.ui' ** ** Created by: Qt User Interface Compiler version 5.5.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_DARKSENDCONFIG_H #define UI_DARKSENDCONFIG_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QDialog> #include <QtWidgets/QFrame> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QPushButton> QT_BEGIN_NAMESPACE class Ui_DarksendConfig { public: QPushButton *buttonBasic; QPushButton *buttonHigh; QPushButton *buttonMax; QLabel *label; QLabel *label_2; QLabel *label_3; QLabel *label_4; QLabel *label_6; QLabel *label_7; QLabel *label_8; QLabel *label_9; QFrame *line; QFrame *line_2; void setupUi(QDialog *DarksendConfig) { if (DarksendConfig->objectName().isEmpty()) DarksendConfig->setObjectName(QStringLiteral("DarksendConfig")); DarksendConfig->resize(630, 307); buttonBasic = new QPushButton(DarksendConfig); buttonBasic->setObjectName(QStringLiteral("buttonBasic")); buttonBasic->setGeometry(QRect(20, 70, 151, 27)); buttonHigh = new QPushButton(DarksendConfig); buttonHigh->setObjectName(QStringLiteral("buttonHigh")); buttonHigh->setGeometry(QRect(20, 140, 151, 27)); buttonMax = new QPushButton(DarksendConfig); buttonMax->setObjectName(QStringLiteral("buttonMax")); buttonMax->setGeometry(QRect(20, 210, 151, 27)); label = new QLabel(DarksendConfig); label->setObjectName(QStringLiteral("label")); label->setGeometry(QRect(30, 20, 571, 31)); label_2 = new QLabel(DarksendConfig); label_2->setObjectName(QStringLiteral("label_2")); label_2->setGeometry(QRect(190, 70, 421, 21)); label_3 = new QLabel(DarksendConfig); label_3->setObjectName(QStringLiteral("label_3")); label_3->setGeometry(QRect(190, 140, 411, 21)); label_4 = new QLabel(DarksendConfig); label_4->setObjectName(QStringLiteral("label_4")); label_4->setGeometry(QRect(190, 210, 421, 21)); label_6 = new QLabel(DarksendConfig); label_6->setObjectName(QStringLiteral("label_6")); label_6->setGeometry(QRect(40, 100, 561, 21)); label_7 = new QLabel(DarksendConfig); label_7->setObjectName(QStringLiteral("label_7")); label_7->setGeometry(QRect(40, 170, 561, 21)); label_8 = new QLabel(DarksendConfig); label_8->setObjectName(QStringLiteral("label_8")); label_8->setGeometry(QRect(40, 240, 561, 21)); label_9 = new QLabel(DarksendConfig); label_9->setObjectName(QStringLiteral("label_9")); label_9->setGeometry(QRect(40, 260, 561, 21)); line = new QFrame(DarksendConfig); line->setObjectName(QStringLiteral("line")); line->setGeometry(QRect(10, 120, 601, 16)); line->setFrameShape(QFrame::HLine); line->setFrameShadow(QFrame::Sunken); line_2 = new QFrame(DarksendConfig); line_2->setObjectName(QStringLiteral("line_2")); line_2->setGeometry(QRect(10, 190, 601, 16)); line_2->setFrameShape(QFrame::HLine); line_2->setFrameShadow(QFrame::Sunken); retranslateUi(DarksendConfig); QMetaObject::connectSlotsByName(DarksendConfig); } // setupUi void retranslateUi(QDialog *DarksendConfig) { DarksendConfig->setWindowTitle(QApplication::translate("DarksendConfig", "Configure PrivateSend", 0)); buttonBasic->setText(QApplication::translate("DarksendConfig", "Basic Privacy", 0)); buttonHigh->setText(QApplication::translate("DarksendConfig", "High Privacy", 0)); buttonMax->setText(QApplication::translate("DarksendConfig", "Maximum Privacy", 0)); label->setText(QApplication::translate("DarksendConfig", "Please select a privacy level.", 0)); label_2->setText(QApplication::translate("DarksendConfig", "Use 2 separate masternodes to mix funds up to 1000 CMK", 0)); label_3->setText(QApplication::translate("DarksendConfig", "Use 8 separate masternodes to mix funds up to 1000 CMK", 0)); label_4->setText(QApplication::translate("DarksendConfig", "Use 16 separate masternodes", 0)); label_6->setText(QApplication::translate("DarksendConfig", "This option is the quickest and will cost about ~0.025 CMK to anonymize 1000 CMK", 0)); label_7->setText(QApplication::translate("DarksendConfig", "This option is moderately fast and will cost about 0.05 CMK to anonymize 1000 CMK", 0)); label_8->setText(QApplication::translate("DarksendConfig", "This is the slowest and most secure option. Using maximum anonymity will cost", 0)); label_9->setText(QApplication::translate("DarksendConfig", "0.1 CMK per 1000 CMK you anonymize.", 0)); } // retranslateUi }; namespace Ui { class DarksendConfig: public Ui_DarksendConfig {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_DARKSENDCONFIG_H
davidebreso/etherdfs-client
src/etherdfs.c
<filename>src/etherdfs.c /* * EtherDFS - a network drive for DOS running over raw ethernet * http://etherdfs.sourceforge.net * * Copyright (C) 2017, 2018 <NAME> * Copyright (c) 2020 <NAME> * Copyright (C) 2021 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include <i86.h> /* union INTPACK */ // #include <stdio.h> /* for printf */ #include "version.h" /* program & protocol version */ #include "dosstruc.h" /* definitions of structures used by DOS */ #include "globals.h" /* global variables used by etherdfs */ #include "chint.h" /* store_newds(newds) */ /* this function obviously does nothing - but I need it because it is a * 'low-water' mark for the end of my resident code (so I know how much memory * exactly I can trim when going TSR) */ static void begtextend(void) { } unsigned short residentcs; /* segment of resident code */ /* registers a packet driver handle to use on subsequent calls */ static int pktdrv_accesstype(void) { unsigned char cflag = 0; _asm { mov ax, 201h /* AH=subfunction access_type(), AL=if_class=1(eth) */ mov bx, 0ffffh /* if_type = 0xffff means 'all' */ mov dl, 0 /* if_number: 0 (first interface) */ /* ES:DI points to the receiving routine */ mov es, residentcs /* write segment of pktdrv_recv into es */ mov di, offset pktdrv_recv /* DS:SI should point to the ethertype value in network byte order */ push ds /* save DS */ mov ds, cs:glob_newds /* Set DS to resident data area */ mov si, offset glob_pktdrv_sndbuff + 12 /* DS:SI points to packet type specification */ mov cx, 2 /* typelen (ethertype is 16 bits) */ mov cflag, 1 /* pre-set the cflag variable to failure */ /* int to variable vector is a mess, so I have fetched its vector myself * and pushf + cli + call far it now to simulate a regular int */ pushf cli call dword ptr glob_pktdrv_pktcall /* get CF state - reset cflag if CF clear, and get pkthandle from AX */ jc badluck /* Jump if Carry */ mov word ptr [glob_data + GLOB_DATOFF_PKTHANDLE], ax /* Pkt handle should be in AX */ mov cflag, 0 badluck: pop ds /* restore DS */ } if (cflag != 0) return(-1); return(0); } /* get my own MAC addr. target MUST point to a space of at least 6 chars */ static void pktdrv_getaddr(unsigned char *dst) { _asm { mov ah, 6 /* subfunction: get_addr() */ mov bx, word ptr [glob_data + GLOB_DATOFF_PKTHANDLE]; /* handle */ push ds /* write segment of dst into es */ pop es mov di, dst /* offset of dst (in small mem model dst IS an offset) */ mov cx, 6 /* expected length (ethernet = 6 bytes) */ /* int to variable vector is a mess, so I have fetched its vector myself * and pushf + cli + call far it now to simulate a regular int */ pushf cli call dword ptr glob_pktdrv_pktcall } } static int pktdrv_init(unsigned short pktintparam, int nocksum) { unsigned short far *intvect = (unsigned short far *)MK_FP(0, pktintparam << 2); unsigned short pktdrvfuncoffs = *intvect; unsigned short pktdrvfuncseg = *(intvect+1); unsigned short rseg = 0, roff = 0; char far *pktdrvfunc = (char far *)MK_FP(pktdrvfuncseg, pktdrvfuncoffs); int i; char sig[8]; /* preload sig with "PKT DRVR" -- I could it just as well with * char sig[] = "PKT DRVR", but I want to avoid this landing in * my DATA segment so it doesn't pollute the TSR memory space. */ sig[0] = 'P'; sig[1] = 'K'; sig[2] = 'T'; sig[3] = ' '; sig[4] = 'D'; sig[5] = 'R'; sig[6] = 'V'; sig[7] = 'R'; /* set my ethertype to 0xF5ED (EDF5 in network byte order) */ glob_pktdrv_sndbuff[12] = 0xED; glob_pktdrv_sndbuff[13] = 0xF5; /* set protover and CKSUM flag in send buffer (I won't touch it again) */ if (nocksum == 0) { glob_pktdrv_sndbuff[56] = PROTOVER | 128; /* protocol version */ } else { glob_pktdrv_sndbuff[56] = PROTOVER; /* protocol version */ } pktdrvfunc += 3; /* skip three bytes of executable code */ for (i = 0; i < 8; i++) if (sig[i] != pktdrvfunc[i]) return(-1); glob_data.pktint = pktintparam; /* fetch the vector of the pktdrv interrupt and save it for later */ _asm { mov ah, 35h /* AH=GetVect */ mov al, byte ptr [glob_data] + GLOB_DATOFF_PKTINT; /* AL=int number */ push es /* save ES and BX (will be overwritten) */ push bx int 21h mov rseg, es mov roff, bx pop bx pop es } glob_pktdrv_pktcall = rseg; glob_pktdrv_pktcall <<= 16; glob_pktdrv_pktcall |= roff; return(pktdrv_accesstype()); } static void pktdrv_free() { _asm { mov ah, 3 mov bx, word ptr [glob_data + GLOB_DATOFF_PKTHANDLE] /* int to variable vector is a mess, so I have fetched its vector myself * and pushf + cli + call far it now to simulate a regular int */ pushf cli call dword ptr glob_pktdrv_pktcall } /* if (regs.x.cflag != 0) return(-1); return(0);*/ } static struct sdastruct far *getsda(void) { /* DOS 3.0+ - GET ADDRESS OF SDA (Swappable Data Area) * AX = 5D06h * * CF set on error (AX=error code) * DS:SI -> sda pointer */ unsigned short rds = 0, rsi = 0; _asm { mov ax, 5d06h push ds push si int 21h mov bx, ds mov cx, si pop si pop ds mov rds, bx mov rsi, cx } return(MK_FP(rds, rsi)); } /* returns the CDS struct for drive. requires DOS 4+ */ static struct cdsstruct far *getcds(unsigned int drive) { /* static to preserve state: only do init once */ static unsigned char far *dir; static int ok = -1; static unsigned char lastdrv; /* init of never inited yet */ if (ok == -1) { /* DOS 3.x+ required - no CDS in earlier versions */ ok = 1; /* offsets of CDS and lastdrv in the List of Lists depends on the DOS version: * DOS < 3 no CDS at all * DOS 3.0 lastdrv at 1Bh, CDS pointer at 17h * DOS 3.1+ lastdrv at 21h, CDS pointer at 16h */ /* fetch lastdrv and CDS through a little bit of inline assembly */ _asm { push si /* SI needs to be preserved */ /* get the List of Lists into ES:BX */ mov ah, 52h int 21h /* get the LASTDRIVE value */ mov si, 21h /* 21h for DOS 3.1+, 1Bh on DOS 3.0 */ mov ah, byte ptr es:[bx+si] mov lastdrv, ah /* get the CDS */ mov si, 16h /* 16h for DOS 3.1+, 17h on DOS 3.0 */ les bx, es:[bx+si] mov word ptr dir+2, es mov word ptr dir, bx /* restore the original SI value*/ pop si } /* some OSes (at least OS/2) set the CDS pointer to FFFF:FFFF */ if (dir == (unsigned char far *) -1l) ok = 0; } /* end of static initialization */ if (ok == 0) return(NULL); if (drive > lastdrv) return(NULL); /* return the CDS array entry for drive - note that currdir_size depends on * DOS version: 0x51 on DOS 3.x, and 0x58 on DOS 4+ */ return((struct cdsstruct __far *)((unsigned char __far *)dir + (drive * 0x58 /*currdir_size*/))); } /******* end of CDS-related stuff *******/ /* primitive message output used instead of printf() to limit memory usage * and binary size */ static void outmsg(char *s); #pragma aux outmsg = \ "mov ah, 9h" /* DOS 1+ - WRITE STRING TO STANDARD OUTPUT \ * DS:DX -> '$'-terminated string \ * small memory model: no need to set DS, 's' is an offset */ \ "int 21h" \ parm [dx] modify exact [ah] nomemory; /* zero out an object of l bytes */ static void zerobytes(void *obj, unsigned short l) { unsigned char *o = obj; while (l-- != 0) { *o = 0; o++; } } /* expects a hex string of exactly two chars "XX" and returns its value, or -1 * if invalid */ static int hexpair2int(char *hx) { unsigned char h[2]; unsigned short i; /* translate hx[] to numeric values and validate */ for (i = 0; i < 2; i++) { if ((hx[i] >= 'A') && (hx[i] <= 'F')) { h[i] = hx[i] - ('A' - 10); } else if ((hx[i] >= 'a') && (hx[i] <= 'f')) { h[i] = hx[i] - ('a' - 10); } else if ((hx[i] >= '0') && (hx[i] <= '9')) { h[i] = hx[i] - '0'; } else { /* invalid */ return(-1); } } /* compute the end result and return it */ i = h[0]; i <<= 4; i |= h[1]; return(i); } /* translates an ASCII MAC address into a 6-bytes binary string */ static int string2mac(unsigned char *d, char *mac) { int i, v; /* is it exactly 17 chars long? */ for (i = 0; mac[i] != 0; i++); if (i != 17) return(-1); /* are nibble pairs separated by colons? */ for (i = 2; i < 16; i += 3) if (mac[i] != ':') return(-1); /* translate each byte to its numeric value */ for (i = 0; i < 16; i += 3) { v = hexpair2int(mac + i); if (v < 0) return(-1); *d = v; d++; } return(0); } #define ARGFL_QUIET 1 #define ARGFL_AUTO 2 #define ARGFL_UNLOAD 4 #define ARGFL_NOCKSUM 8 #define ARGFL_LOADHIGH 16 /* a structure used to pass and decode arguments between main() and parseargv() */ struct argstruct { int argc; /* original argc */ char **argv; /* original argv */ unsigned short pktint; /* custom packet driver interrupt */ unsigned char flags; /* ARGFL_QUIET, ARGFL_AUTO, ARGFL_UNLOAD, ARGFL_CKSUM, ARGFL_LOADHIGH */ }; /* parses (and applies) command-line arguments. returns 0 on success, * non-zero otherwise */ static int parseargv(struct argstruct *args) { int i, drivemapflag = 0, gotmac = 0; /* iterate through arguments, if any */ for (i = 1; i < args->argc; i++) { char opt; char *arg; /* is it a drive mapping, like "c-x"? */ if ((args->argv[i][0] >= 'A') && (args->argv[i][1] == '-') && (args->argv[i][2] >= 'A') && (args->argv[i][3] == 0)) { unsigned char ldrv, rdrv; rdrv = DRIVETONUM(args->argv[i][0]); ldrv = DRIVETONUM(args->argv[i][2]); if ((ldrv > 25) || (rdrv > 25)) return(-2); if (glob_data.ldrv[ldrv] != 0xff) return(-2); glob_data.ldrv[ldrv] = rdrv; drivemapflag = 1; continue; } /* not a drive mapping -> is it an option? */ if (args->argv[i][0] == '/') { if (args->argv[i][1] == 0) return(-3); opt = args->argv[i][1]; /* fetch option's argument, if any */ if (args->argv[i][2] == 0) { /* single option */ arg = NULL; } else if (args->argv[i][2] == '=') { /* trailing argument */ arg = args->argv[i] + 3; } else { return(-3); } /* normalize the option char to lower case */ if ((opt >= 'A') && (opt <= 'Z')) opt += ('a' - 'A'); /* what is the option about? */ switch (opt) { case 'q': if (arg != NULL) return(-4); args->flags |= ARGFL_QUIET; break; case 'p': if (arg == NULL) return(-4); /* I expect an exactly 2-characters string */ if ((arg[0] == 0) || (arg[1] == 0) || (arg[2] != 0)) return(-1); if ((args->pktint = hexpair2int(arg)) < 1) return(-4); break; case 'n': /* disable CKSUM */ if (arg != NULL) return(-4); args->flags |= ARGFL_NOCKSUM; break; case 'u': /* unload EtherDFS */ if (arg != NULL) return(-4); args->flags |= ARGFL_UNLOAD; break; case 'h': /* load TSR high */ if (arg != NULL) return(-4); args->flags |= ARGFL_LOADHIGH; break; default: /* invalid parameter */ return(-5); } continue; } /* not a drive mapping nor an option -> so it's a MAC addr perhaps? */ if (gotmac != 0) return(-1); /* fail if got a MAC already */ /* read the srv mac address, unless it's "::" (auto) */ if ((args->argv[i][0] == ':') && (args->argv[i][1] == ':') && (args->argv[i][2] == 0)) { args->flags |= ARGFL_AUTO; } else { if (string2mac(GLOB_RMAC, args->argv[i]) != 0) return(-1); } gotmac = 1; } /* fail if MAC+unload or mapping+unload */ if (args->flags & ARGFL_UNLOAD) { if ((gotmac != 0) || (drivemapflag != 0)) return(-1); return(0); } /* did I get at least one drive mapping? and a MAC? */ if ((drivemapflag == 0) || (gotmac == 0)) return(-6); return(0); } /* translates an unsigned byte into a 2-characters string containing its hex * representation. s needs to be at least 3 bytes long. */ static void byte2hex(char *s, unsigned char b) { char h[16]; unsigned short i; /* pre-compute h[] with a string 0..F -- I could do the same thing easily * with h[] = "0123456789ABCDEF", but then this would land inside the DATA * segment, while I want to keep it in stack to avoid polluting the TSR's * memory space */ for (i = 0; i < 10; i++) h[i] = '0' + i; for (; i < 16; i++) h[i] = ('A' - 10) + i; /* */ s[0] = h[b >> 4]; s[1] = h[b & 15]; s[2] = 0; } /* allocates sz paragraphs in upper memory and returns the segment to allocated memory * or 0 on error. */ __declspec(naked) static unsigned short allocseg(unsigned short sz) { /* ask DOS for memory */ _asm { /* set strategy to 'last fit' */ mov ax, 5800h /* DOS 2.11+ - GET OR SET MEMORY ALLOCATION STRATEGY * al = 0 means 'get allocation strategy' */ int 21h /* now current strategy is in ax */ push ax /* push current strategy to stack */ mov ax, 5802h /* al = 2 means 'get UMB Link Status'*/ int 21h /* now current link status is in ax */ push ax /* push UMB Link Status to stack */ mov ax, 5803h /* al = 3 means 'Set UMB Link Status' */ mov bx, 1 /* 1 means 'include upper memory' */ int 21h mov ax, 5801h /* al = 1 means 'set strategy' */ mov bx, 0041h /* 41h means 'upper best fit' */ int 21h /* do the allocation now */ mov ah, 48h /* alloc memory (DOS 2+) */ mov bx, dx /* number of paragraphs to allocate */ mov dx, 0 /* pre-set res to failure (0) */ int 21h /* returns allocated segment in AX */ /* check CF */ jc failed mov dx, ax /* set res to actual result */ failed: /* set link status back to its initial setting */ mov ax, 5803h pop bx /* pop UMB Link Status from stack */ int 21h /* set strategy back to its initial setting */ mov ax, 5801h pop bx /* pop current strategy from stack */ int 21h ret } } #pragma aux allocseg parm [dx] value [dx] modify exact [ax bx cl dx] nomemory; /* free segment previously allocated through allocseg() */ static void freeseg(unsigned short segm) { _asm { mov ah, 49h /* free memory (DOS 2+) */ mov es, segm /* put segment to free into ES */ int 21h } } /* scans the 2Fh interrupt for some available 'multiplex id' in the range * C0..FF. also checks for EtherDFS presence at the same time. returns: * - the available id if found * - the id of the already-present etherdfs instance * - 0 if no available id found * presentflag set to 0 if no etherdfs found loaded, non-zero otherwise. */ static unsigned char findfreemultiplex(unsigned char *presentflag) { unsigned char id = 0, freeid = 0, pflag = 0; _asm { mov id, 0C0h /* start scanning at C0h */ checkid: xor al, al /* subfunction is 'installation check' (00h) */ mov ah, id int 2Fh /* is it free? (AL == 0) */ test al, al jnz notfree /* not free - is it me perhaps? */ mov freeid, ah /* it's free - remember it, I may use it myself soon */ jmp checknextid notfree: /* is it me? (AL=FF + BX=4D86 CX=7E1 [MV 2017]) */ cmp al, 0ffh jne checknextid cmp bx, 4d86h jne checknextid cmp cx, 7e1h jne checknextid /* if here, then it's me... */ mov ah, id mov freeid, ah mov pflag, 1 jmp gameover checknextid: /* if not me, then check next id */ inc id jnz checkid /* if id is zero, then all range has been covered (C0..FF) */ gameover: } *presentflag = pflag; return(freeid); } /* Compute the size of resident memory needed by the program, in 16 btyes * paragraphs. How to compute the number of paragraphs? Simple: look at * the memory map and note down the size of the RESDATA segment (that's * where I store all TSR data) and of the BEGTEXT segment (that's where I * store all TSR routines). * Then: (sizeof(RESDATA) + sizeof(BEGTEXT) + sizeof(PSP) + 15) / 16 * PSP is 256 bytes of course. And +15 is needed to avoid truncating the * last (partially used) paragraph. */ static unsigned short get_residentsize() { unsigned short res = 0; _asm { push ax /* save AX */ mov ax, offset begtextend /* AX = offset of resident code end */ add ax, 256 /* add size of PSP (256 bytes) */ add ax, 15 /* add 15 to avoid truncating last paragraph */ mov cl, 4 /* convert bytes to number of 16-bytes paragraphs */ shr ax, cl /* the 8086/8088 CPU supports only a 1-bit version * of SHR so I use the reg,CL method */ /* Add size of RESDATA (in paragraphs) by subtracting CS and DS */ add ax, seg begtextend /* add code segment */ sub ax, seg glob_data /* subtract data segment */ mov res, ax /* set res to actual result */ pop ax /* restore AX */ } return(res); } /* Compute the segment of the upper memory code */ static unsigned short get_upperds(unsigned short upperseg) { unsigned short res = 0; _asm { push ax /* save AX */ /* Compute size of RESDATA (in paragraphs) by subtracting CS and DS */ mov ax, seg begtextend /* AX is code segment */ sub ax, seg glob_data /* subtract data segment */ add ax, 16 /* add size of PSP (256 bytes, 16 paragraphs) */ add ax, upperseg /* Add the upper base segment (points at PSP) */ mov res, ax /* set res to actual result */ pop ax /* restore AX */ } return(res); } static unsigned char umb_ident[8] = "ETHERDFS"; int main(int argc, char **argv) { struct argstruct args; struct cdsstruct far *cds; unsigned char tmpflag = 0; int i; unsigned short upperseg; /* segment of upper memory block to load high */ unsigned short residentsize = get_residentsize(); unsigned short old_pspseg; /* PSP of low memory portion of the program */ char buff[20]; unsigned char far *mcbfptr; /* set all drive mappings as 'unused' */ for (i = 0; i < 26; i++) glob_data.ldrv[i] = 0xff; /* parse command-line arguments */ zerobytes(&args, sizeof(args)); args.argc = argc; args.argv = argv; if (parseargv(&args) != 0) { #include "msg/help.c" return(1); } /* check DOS version - I require DOS 5.0+ */ _asm { mov ax, 3306h int 21h mov tmpflag, bl inc al /* if AL was 0xFF ("unsupported function"), it is 0 now */ jnz done mov tmpflag, 0 /* if AL is 0 (hence was 0xFF), set dosver to 0 */ done: } if (tmpflag < 5) { /* tmpflag contains DOS version or 0 for 'unknown' */ #include "msg/unsupdos.c" return(1); } /* look whether or not it's ok to install a network redirector at int 2F */ _asm { mov tmpflag, 0 mov ax, 1100h int 2Fh dec ax /* if AX was set to 1 (ie. "not ok to install"), it's zero now */ jnz goodtogo mov tmpflag, 1 goodtogo: } if (tmpflag != 0) { #include "msg/noredir.c" return(1); } /* is it all about unloading myself? */ if ((args.flags & ARGFL_UNLOAD) != 0) { unsigned char etherdfsid, pktint; unsigned short myseg, myoff, myhandle; unsigned long pktdrvcall; struct tsrshareddata far *tsrdata; unsigned char far *int2fptr; /* am I loaded at all? */ etherdfsid = findfreemultiplex(&tmpflag); if (tmpflag == 0) { /* not loaded, cannot unload */ #include "msg/notload.c" return(1); } /* am I still at the top of the int 2Fh chain? */ _asm { /* save BX and ES */ push bx push es /* fetch int vector */ mov ax, 352Fh /* AH=35h 'GetVect' for int 2Fh */ int 21h mov myseg, es mov myoff, bx /* restore BX and ES */ pop es pop bx } /* The interrupt handler's signature appears at offset INTSIG_OFF * The value is set by the Makefile and depends on the optimisation settings * and may change at each source code modification. */ int2fptr = (unsigned char far *)MK_FP(myseg, myoff) + INTSIG_OFF; /* look for the "MVet" signature */ /* DEBUG: print signature */ /* for(i=0; i < 4; ++i) { buff[i] = int2fptr[i]; } buff[4] = '\r'; buff[5] = '\n'; buff[6] = '$'; outmsg(buff); */ if ((int2fptr[0] != 'M') || (int2fptr[1] != 'V') || (int2fptr[2] != 'e') || (int2fptr[3] != 't')) { #include "msg/othertsr.c"; return(1); } /* get the ptr to TSR's data */ _asm { push bx pushf mov ah, etherdfsid mov al, 1 mov cx, 4D86h mov myseg, 0ffffh int 2Fh /* AX should be 0, and BX:CX contains the address */ test ax, ax jnz fail mov myseg, bx mov myoff, cx fail: popf pop bx } if (myseg == 0xffffu) { #include "msg/tsrcomfa.c" return(1); } // printf("TSR shared data at %04X:%04X\n", myseg, myoff); tsrdata = MK_FP(myseg, myoff); /* restore previous int 2f handler (under DS:DX, AH=25h, INT 21h)*/ myseg = tsrdata->prev_2f_handler_seg; myoff = tsrdata->prev_2f_handler_off; _asm { /* save DS */ push ds /* set DS:DX */ mov ax, myseg push ax pop ds mov dx, myoff /* call INT 21h,25h for int 2Fh */ mov ax, 252Fh int 21h /* restore DS */ pop ds } /* get the address of the packet driver routine */ pktint = tsrdata->pktint; _asm { /* save BX and ES */ push bx push es /* fetch int vector */ mov ah, 35h /* AH=35h 'GetVect' */ mov al, pktint /* interrupt */ int 21h mov myseg, es mov myoff, bx /* restore BX and ES */ pop es pop bx } pktdrvcall = myseg; pktdrvcall <<= 16; pktdrvcall |= myoff; /* unregister packet driver */ myhandle = tsrdata->pkthandle; _asm { /* save AX */ push ax /* prepare the release_type() call */ mov ah, 3 /* release_type() */ mov bx, myhandle /* call the pktdrv int */ /* int to variable vector is a mess, so I have fetched its vector myself * and pushf + cli + call far it now to simulate a regular int */ pushf cli call dword ptr pktdrvcall /* restore AX */ pop ax } /* set all mapped drives as 'not available' */ for (i = 0; i < 26; i++) { if (tsrdata->ldrv[i] == 0xff) continue; cds = getcds(i); if (cds != NULL) cds->flags = 0; } /* free TSR's resident seg and its PSP */ // printf("Free TSR's resident memory at %04X\n", tsrdata->pspseg); freeseg(tsrdata->pspseg); /* all done */ if ((args.flags & ARGFL_QUIET) == 0) { #include "msg/unloaded.c" } return(0); } /* remember current int 2f handler, we might over-write it soon (also I * use it to see if I'm already loaded) */ _asm { mov ax, 352fh; /* AH=GetVect AL=2F */ push es /* save ES and BX (will be overwritten) */ push bx int 21h mov word ptr [glob_data + GLOB_DATOFF_PREV2FHANDLERSEG], es mov word ptr [glob_data + GLOB_DATOFF_PREV2FHANDLEROFF], bx pop bx pop es } /* is the TSR installed already? */ glob_multiplexid = findfreemultiplex(&tmpflag); if (tmpflag != 0) { /* already loaded */ #include "msg/alrload.c" return(1); } else if (glob_multiplexid == 0) { /* no free multiplex id found */ #include "msg/nomultpx.c" return(1); } /* if any of the to-be-mapped drives is already active, fail */ for (i = 0; i < 26; i++) { if (glob_data.ldrv[i] == 0xff) continue; cds = getcds(i); if (cds == NULL) { #include "msg/mapfail.c" return(1); } if (cds->flags != 0) { #include "msg/drvactiv.c" return(1); } } /* remember the SDA address (will be useful later) */ glob_sdaptr = getsda(); /* Save resident data segment inside resident code segment. */ glob_newds = (FP_SEG((void far *)&glob_data)); // printf("Saved resident data segment at %04X\n", glob_newds); /* Save resident code segment. */ residentcs = (FP_SEG((void far *)&inthandler)); // printf("Saved resident code segment at %04X\n", residentcs); /* init the packet driver interface */ glob_data.pktint = 0; if (args.pktint == 0) { /* detect first packet driver within int 60h..80h */ for (i = 0x60; i <= 0x80; i++) { if (pktdrv_init(i, args.flags & ARGFL_NOCKSUM) == 0) break; } } else { /* use the pktdrvr interrupt passed through command line */ pktdrv_init(args.pktint, args.flags & ARGFL_NOCKSUM); } /* has it succeeded? */ if (glob_data.pktint == 0) { #include "msg/pktdfail.c" return(1); } pktdrv_getaddr(GLOB_LMAC); /* should I auto-discover the server? */ if ((args.flags & ARGFL_AUTO) != 0) { unsigned short *ax; unsigned char *answer; /* set (temporarily) glob_rmac to broadcast */ for (i = 0; i < 6; i++) GLOB_RMAC[i] = 0xff; for (i = 0; glob_data.ldrv[i] == 0xff; i++); /* find first mapped disk */ /* send a discovery frame that will update glob_rmac */ if (sendquery(AL_DISKSPACE, i, 0, &answer, &ax, 1) != 6) { #include "msg/nosrvfnd.c" pktdrv_free(); /* free the pkt drv and quit */ return(1); } } /* set all drives as being 'network' drives (also add the PHYSICAL bit, * otherwise MS-DOS 6.0 will ignore the drive) */ for (i = 0; i < 26; i++) { if (glob_data.ldrv[i] == 0xff) continue; cds = getcds(i); cds->flags = CDSFLAG_NET | CDSFLAG_PHY; /* set 'current path' to root, to avoid inheriting any garbage */ cds->current_path[0] = 'A' + i; cds->current_path[1] = ':'; cds->current_path[2] = '\\'; cds->current_path[3] = 0; } /* get the segment of the PSP (might come handy later) */ _asm { mov ah, 62h /* get current PSP address */ int 21h /* returns the segment of PSP in BX */ mov word ptr [glob_data + GLOB_DATOFF_PSPSEG], bx /* copy PSP segment to glob_pspseg */ } // printf("PSP segment at %04X\n", glob_data.pspseg); // printf("RESDATA segment at %04X\n", FP_SEG((void far *)&glob_data)); // printf("BEGTEXT segment at %04X\n", FP_SEG((void far *)inthandler)); /* do I have to load myself high? */ if ((args.flags & ARGFL_LOADHIGH) != 0) { /* allocate a new segment in the upper memory area to use for resident code and data */ upperseg = allocseg(residentsize); if (upperseg == 0) { /* Upper memory allocation error, load in conventional memory */ #include "msg/memfail.c" args.flags &= ~ARGFL_LOADHIGH; } else { // printf("Upper segment at %04X\n", upperseg); /* New resident data segment is upperseg + sizeof(PSP) in paragraphs * PSP is 256 bytes (16 paragraphs). */ glob_newds = upperseg + 16; // printf("Upper resident data segment at %04X\n", glob_newds); /* Get upper resident code segment */ residentcs = get_upperds(upperseg); // printf("Upper resident code segment at %04X\n", residentcs); /* Set name of the block owner in the MCB * The Memory Control Block is 1 paragraph below upperseg * At offset 8 in MCB should be the name of block owner. */ mcbfptr = (unsigned char far *)MK_FP(upperseg -1, 8); // printf("Upper MCB signature at %04X:%04X\n", FP_SEG(mcbfptr), FP_OFF(mcbfptr)); for(i = 0; i < 8; i++) { mcbfptr[i] = umb_ident[i]; } /* Set saved PSP segment to the upper memory block */ old_pspseg = glob_data.pspseg; glob_data.pspseg = upperseg; // printf("Upper PSP segment at %04X\n", glob_data.pspseg); /* copy resident code and data into the upper memory segment */ _asm { /* save registers on the stack */ push ds push es push ax push cx push si push di pushf /* copy the memory block */ mov ax, residentsize /* ax is number of paragraphs to copy */ mov cl, 3 /* convert paragraphs to number of words */ shl ax, cl /* the 8086/8088 CPU supports only a 1-bit version */ /* of SHR so I use the reg,CL method */ mov cx, ax /* CX is number of words to copy */ xor si, si /* si = 0*/ xor di, di /* di = 0 */ cld /* clear direction flag (increment si/di) */ mov ax, old_pspseg /* load ds with low memory PSP segment */ mov ds, ax mov es, upperseg /* load es with upperseg */ rep movsw /* execute copy DS:SI -> ES:DI */ /* restore registers */ popf pop di pop si pop cx pop ax pop es pop ds } /* Free the packet driver */ pktdrv_free(); /* Set new packet driver handle to upper memory */ if(pktdrv_accesstype() != 0) { /* Relocation of packet driver failed. * Set all mapped drives as 'not available' */ for (i = 0; i < 26; i++) { if (glob_data.ldrv[i] == 0xff) continue; cds = getcds(i); if (cds != NULL) cds->flags = 0; } /* Release upper memory block */ freeseg(upperseg); #include "msg/relfail.c" return(1); } } } if ((args.flags & ARGFL_QUIET) == 0) { #include "msg/instlled.c" for (i = 0; i < 6; i++) { byte2hex(buff + i + i + i, GLOB_LMAC[i]); } for (i = 2; i < 16; i += 3) buff[i] = ':'; buff[17] = '$'; outmsg(buff); #include "msg/pktdrvat.c" byte2hex(buff, glob_data.pktint); buff[2] = ')'; buff[3] = '\r'; buff[4] = '\n'; buff[5] = '$'; outmsg(buff); for (i = 0; i < 26; i++) { int z; if (glob_data.ldrv[i] == 0xff) continue; buff[0] = ' '; buff[1] = 'A' + i; buff[2] = ':'; buff[3] = ' '; buff[4] = '-'; buff[5] = '>'; buff[6] = ' '; buff[7] = '['; buff[8] = 'A' + glob_data.ldrv[i]; buff[9] = ':'; buff[10] = ']'; buff[11] = ' '; buff[12] = 'o'; buff[13] = 'n'; buff[14] = ' '; buff[15] = '$'; outmsg(buff); for (z = 0; z < 6; z++) { byte2hex(buff + z + z + z, GLOB_RMAC[z]); } for (z = 2; z < 16; z += 3) buff[z] = ':'; buff[17] = '\r'; buff[18] = '\n'; buff[19] = '$'; outmsg(buff); } } /* free the environment (env segment is at offset 2C of the PSP) */ // printf("Free the environment.\n"); _asm { mov es, word ptr [glob_data + GLOB_DATOFF_PSPSEG] /* load ES with PSP's segment */ mov es, es:[2Ch] /* get segment of the env block */ mov ah, 49h /* free memory (DOS 2+) */ int 21h } /* set up the TSR (INT 2F catching) */ // printf("Set up the TSR at %04X:%04X\n", residentcs, inthandler); _asm { cli mov ax, 252fh /* AH=set interrupt vector AL=2F */ push ds /* preserve DS */ push residentcs /* set DS to the resident code segment, */ pop ds /* that is provide the int handler's segment */ mov dx, offset inthandler /* int handler's offset */ int 21h pop ds /* restore DS to previous value */ sti } // printf("Turn self into a TSR keeping %d paragraphs of memory\n", residentsize); /* If the TSR is loaded high, set the PSP to upper memory and deallocate low memory */ if ((args.flags & ARGFL_LOADHIGH) != 0) { /* Set new PSP to upper memory */ // printf("Set new PSP to upper memory.\n"); _asm { mov bx, upperseg /* BX = new process PSP segment address */ mov ah, 50h /* INT 21,50 - Set Current Process ID */ int 21h } /* Deallocate the whole low memory of the program */ freeseg(old_pspseg); } /* When loading the TSR high, the following code actually run in deallocated memory * but luckily it is not overwritten yet by DOS. */ /* Turn self into a TSR and free memory I won't need any more. That is, I * free all the libc startup code and my init functions by passing the * number of paragraphs to keep resident to INT 21h, AH=31h. How to compute * the number of paragraphs? Simple: look at the memory map and note down * the size of the RESDATA segment (that's where I store all TSR data) and of * the BEGTEXT segment (that's where I store all TSR routines). * Then: (sizeof(RESDATA) + sizeof(BEGTEXT) + sizeof(PSP) + 15) / 16 * PSP is 256 bytes of course. And +15 is needed to avoid truncating the * last (partially used) paragraph. */ _asm { mov ax, 3100h /* AH=31 'terminate+stay resident', AL=0 exit code */ mov dx, residentsize /* DX = size of resident memory (in paragraphs) */ int 21h } return(0); /* never reached, but compiler complains if not present */ }
davidebreso/etherdfs-client
src/version.h
/* program version and date */ #define PVER "0.9.3.1" #define PDATE "2017,2018" #define MODATE "2020" #define DBDATE "2021,2022" /* protocol version */ #define PROTOVER 2
davidebreso/etherdfs-client
src/chint.h
/* this is a copy of the _chain_intr() function, borrowed as-is from the * source code of OpenWatcom 1.9 (bld/clib/intel/a/chint086.asm) * the reason I'm doing this is to have it inside my own code segment, so I * can use it from within the TSR after dropping all libc */ /* original declaration: _WCRTLINK extern void _chain_intr( void (_WCINTERRUPT _DOSFAR *__handler)() ); */ #ifndef chint_h_sentinel #define chint_h_sentinel _WCRTLINK extern void _mvchain_intr(void far *__handler); extern unsigned short far glob_newds; #endif
davidebreso/etherdfs-client
src/globals.h
<gh_stars>1-10 /* * This file is part of the etherdfs project. * http://etherdfs.sourceforge.net * * Copyright (C) 2017 <NAME> * Copyright (C) 2021 <NAME> * * Contains all global variables used by etherdfs. */ #ifndef GLOBALS_SENTINEL #define GLOBALS_SENTINEL /* set DEBUGLEVEL to 0, 1 or 2 to turn on debug mode with desired verbosity */ #define DEBUGLEVEL 0 /* define the maximum size of a frame, as sent or received by etherdfs. * example: value 1084 accomodates payloads up to 1024 bytes +all headers */ #define FRAMESIZE 1090 /* define NULL, for readability of the code */ #ifndef NULL #define NULL (void *)0 #endif /* define boolean constants */ #ifndef TRUE #define TRUE 1 #define FALSE 0 #endif /* required size (in bytes) of the stack for the interrupt handler routine. * Packet drivers tend to require a stack of several hundreds bytes at least * 1K should be safe... */ #define NEWSTACKSZ 1024 /* a few globals useful only for debug messages */ #if DEBUGLEVEL > 0 static unsigned short dbg_xpos = 0; static unsigned short far *dbg_VGA = (unsigned short far *)(0xB8000000l); static unsigned char dbg_hexc[16] = "0123456789ABCDEF"; #define dbg_startoffset 80*16 #endif /* translates a drive letter (either upper- or lower-case) into a number (A=0, * B=1, C=2, etc) */ #define DRIVETONUM(x) (((x) >= 'a') && ((x) <= 'z')?x-'a':x-'A') /* all the calls I support are in the range AL=0..2Eh - the list below serves * as a convenience to compare AL (subfunction) values */ enum AL_SUBFUNCTIONS { AL_INSTALLCHK = 0x00, AL_RMDIR = 0x01, AL_MKDIR = 0x03, AL_CHDIR = 0x05, AL_CLSFIL = 0x06, AL_CMMTFIL = 0x07, AL_READFIL = 0x08, AL_WRITEFIL = 0x09, AL_LOCKFIL = 0x0A, AL_UNLOCKFIL = 0x0B, AL_DISKSPACE = 0x0C, AL_SETATTR = 0x0E, AL_GETATTR = 0x0F, AL_RENAME = 0x11, AL_DELETE = 0x13, AL_OPEN = 0x16, AL_CREATE = 0x17, AL_FINDFIRST = 0x1B, AL_FINDNEXT = 0x1C, AL_SKFMEND = 0x21, AL_UNKNOWN_2D = 0x2D, AL_SPOPNFIL = 0x2E, AL_UNKNOWN = 0xFF }; /* whenever the tsrshareddata structure changes, offsets below MUST be * adjusted (these are required by assembly routines) */ #define GLOB_DATOFF_PREV2FHANDLERSEG 0 #define GLOB_DATOFF_PREV2FHANDLEROFF 2 #define GLOB_DATOFF_PSPSEG 4 #define GLOB_DATOFF_PKTHANDLE 6 #define GLOB_DATOFF_PKTINT 8 struct tsrshareddata { /*offs*/ /* 0 */ unsigned short prev_2f_handler_seg; /* seg:off of the previous 2F handler */ /* 2 */ unsigned short prev_2f_handler_off; /* (so I can call it for all queries */ /* that do not relate to my drive */ /* 4 */ unsigned short pspseg; /* segment of the program's PSP block */ /* 6 */ unsigned short pkthandle; /* handler returned by the packet driver */ /* 8 */ unsigned char pktint; /* software interrupt of the packet driver */ unsigned char ldrv[26]; /* local to remote drives mappings (0=A:, 1=B, etc */ }; extern struct tsrshareddata glob_data; /* global variables related to packet driver management and handling frames */ extern unsigned char glob_pktdrv_sndbuff[FRAMESIZE]; /* this not only is my send-frame buffer, but I also use it to store permanently lmac, rmac, ethertype and PROTOVER at proper places */ extern unsigned long glob_pktdrv_pktcall; /* vector address of the pktdrv interrupt */ /* a few definitions for data that points to my sending buffer */ #define GLOB_LMAC (glob_pktdrv_sndbuff + 6) /* local MAC address */ #define GLOB_RMAC (glob_pktdrv_sndbuff) /* remote MAC address */ extern struct sdastruct far *glob_sdaptr; /* pointer to DOS SDA (set by main() at * * startup, used later by process2f() */ /* the INT 2F "multiplex id" registerd by EtherDFS */ extern unsigned char glob_multiplexid; //*************// //* Functions *// //*************// extern void __declspec(naked) far pktdrv_recv(void); extern unsigned short sendquery(unsigned char query, unsigned char drive, unsigned short bufflen, unsigned char **replyptr, unsigned short **replyax, unsigned int updatermac); extern void __interrupt __far inthandler(union INTPACK r); #endif
davidebreso/etherdfs-client
src/dosstruc.h
<reponame>davidebreso/etherdfs-client /* * This file is part of the etherdfs project. * http://etherdfs.sourceforge.net * * Copyright (C) 2017 <NAME> * * Contains definitions of DOS structures used by etherdfs. */ #ifndef DOSSTRUCTS_SENTINEL #define DOSSTRUCTS_SENTINEL /* make sure structs are packed tightly (required since that's how DOS packs its CDS) */ #pragma pack(1) /* CDS (current directory structure), as used by DOS 4+ */ #define CDSFLAG_SUB 0x1000u /* SUBST drive */ #define CDSFLAG_JOI 0x2000u /* JOINed drive */ #define CDSFLAG_PHY 0x4000u /* Physical drive */ #define CDSFLAG_NET 0x8000u /* Network drive */ struct cdsstruct { unsigned char current_path[67]; /* current path */ unsigned short flags; /* indicates whether the drive is physical, networked, substed or joined*/ unsigned char far *dpb; /* a pointer to the Drive Parameter Block */ union { struct { /* used for local disks */ unsigned short start_cluster; unsigned long unknown; } LOCAL; struct { /* used for network disks */ unsigned long redirifs_record_ptr; unsigned short parameter; } NET; } u; unsigned short backslash_offset; /* offset in current_path of '\' (always 2, unless it's a SUBST drive) */ /* DOS 4 and newer have 7 extra bytes here */ unsigned char f2[7]; }; /* 88 bytes total */ /* called 'srchrec' in phantom.c */ struct sdbstruct { unsigned char drv_lett; unsigned char srch_tmpl[11]; unsigned char srch_attr; unsigned short dir_entry; unsigned short par_clstr; unsigned char f1[4]; }; struct foundfilestruct { unsigned char fname[11]; unsigned char fattr; /* (1=RO 2=HID 4=SYS 8=VOL 16=DIR 32=ARCH 64=DEVICE) */ unsigned char f1[10]; unsigned short time_lstupd; /* 16 bits: hhhhhmmm mmmsssss */ unsigned short date_lstupd; /* 16 bits: YYYYYYYM MMMDDDDD */ unsigned short start_clstr; /* (optional) */ unsigned long fsize; }; /* * Pointers to SDA fields. Layout: * DOS4+ DOS 3, DR-DOS * DTA ptr 0Ch 0Ch * First filename buffer 9Eh 92h * Search data block (SDB) 19Eh 192h * Dir entry for found file 1B3h 1A7h * Search attributes 24Dh 23Ah * File access/sharing mode 24Eh 23Bh * Ptr to current CDS 282h 26Ch * Extended open mode 2E1h Not supported * * The struct below is matching FreeDOS and MS-DOS 4+ */ struct sdastruct { unsigned char f0[12]; unsigned char far *curr_dta; unsigned char f1[32]; unsigned char dd; unsigned char mm; unsigned short yy_1980; unsigned char f2[106]; unsigned char fn1[128]; unsigned char fn2[128]; struct sdbstruct sdb; struct foundfilestruct found_file; struct cdsstruct drive_cdscopy; /* 88 bytes total */ unsigned char fcb_fn1[11]; unsigned char f3; unsigned char fcb_fn2[11]; unsigned char f4[11]; unsigned char srch_attr; unsigned char open_mode; unsigned char f5[51]; unsigned char far *drive_cdsptr; unsigned char f6[12]; unsigned short fn1_csofs; unsigned short fn2_csofs; unsigned char f7[71]; unsigned short spop_act; unsigned short spop_attr; unsigned short spop_mode; unsigned char f8[29]; struct { unsigned char drv_lett; unsigned char srch_tmpl[11]; unsigned char srch_attr; unsigned short dir_entry; unsigned short par_clstr; unsigned char f1[4]; } ren_srcfile; struct { unsigned char fname[11]; unsigned char fattr; /* (1=RO 2=HID 4=SYS 8=VOL 16=DIR 32=ARCH 64=DEVICE) */ unsigned char f1[10]; unsigned short time_lstupd; /* 16 bits: hhhhhmmm mmmsssss */ unsigned short date_lstupd; /* 16 bits: YYYYYYYM MMMDDDDD */ unsigned short start_clstr; /* (optional) */ unsigned long fsize; } ren_file; }; /* DOS System File Table entry - ALL DOS VERSIONS * Some of the fields below are defined by the redirector, and differ * from the SFT normally found under DOS */ struct sftstruct { unsigned int handle_count; /* count of handles referring to this file */ unsigned int open_mode; /* open mode, bit 15 set if opened via FCB */ unsigned char file_attr; /* file attributes */ unsigned int dev_info_word; /* device info word */ unsigned char far *dev_drvr_ptr; /* ??? */ unsigned int start_sector; /* starting cluster of file */ unsigned long file_time; /* file date and time */ unsigned long file_size; /* file length */ unsigned long file_pos; /* current file position */ unsigned int rel_sector; unsigned int abs_sector; unsigned int dir_sector; unsigned char dir_entry_no; char file_name[11]; }; #endif
davidebreso/etherdfs-client
src/resident.c
<filename>src/resident.c /* * EtherDFS - a network drive for DOS running over raw ethernet * http://etherdfs.sourceforge.net * * Copyright (C) 2017, 2018 <NAME> * Copyright (c) 2020 <NAME> * Copyright (C) 2021 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include <i86.h> /* union INTPACK */ /* all the resident code goes to segment 'BEGTEXT' */ #pragma code_seg(BEGTEXT, CODE) /* all the resident data goes to segment 'RESDATA' of special class 'RDATA' */ #pragma data_seg(RESDATA, RDATA) #include "dosstruc.h" /* definitions of structures used by DOS */ #include "globals.h" /* global variables used by etherdfs */ #include "chint.h" /* _mvchain_intr() */ struct tsrshareddata glob_data; /* global variables related to packet driver management and handling frames */ unsigned char glob_pktdrv_recvbuff[FRAMESIZE]; signed short volatile glob_pktdrv_recvbufflen; /* length of the frame in buffer, 0 means "free", and neg value means "awaiting" */ unsigned char glob_pktdrv_sndbuff[FRAMESIZE]; /* this not only is my send-frame buffer, but I also use it to store permanently lmac, rmac, ethertype and PROTOVER at proper places */ unsigned long glob_pktdrv_pktcall; /* vector address of the pktdrv interrupt */ unsigned char glob_reqdrv; /* the requested drive, set by the INT 2F * * handler and read by process2f() */ unsigned short glob_reqstkword; /* WORD saved from the stack (used by SETATTR) */ struct sdastruct far *glob_sdaptr; /* pointer to DOS SDA (set by main() at * * startup, used later by process2f() */ /* seg:off addresses of the old (DOS) stack */ unsigned short glob_oldstack_seg; unsigned short glob_oldstack_off; /* the INT 2F "multiplex id" registerd by EtherDFS */ unsigned char glob_multiplexid; /* an INTPACK structure used to store registers as set when INT2F is called */ union INTPACK glob_intregs; /* copies len bytes from *src to *dst */ static void __declspec(naked) copybytes(void far *dst, void far *src, unsigned int len) { _asm { /* Save registers and flags into the stack */ push ds pushf cld /* clear direction flag (increment si/di) */ mov ds, dx /* load segment of source */ shr cx, 1 /* number of words to copy */ rep movsw /* copy CX words from DS:SI -> ES:DI */ adc cx, cx /* see if 1 more byte to copy */ rep movsb /* do repeat copy */ /* restore flags and registers */ popf pop ds ret } } #pragma aux copybytes parm [es di] [dx si] [cx] modify exact [cx di si] nomemory; static unsigned short __declspec(naked) mystrlen(void far *s) { _asm { /* Save registers and flags into the stack */ pushf cld /* clear direction flag (increment si/di) */ mov al, 0 /* Zero terminator */ mov cx, 0xFFFF /* CX count string length */ repne scasb /* scan string to find zero terminator */ neg cx /* string length is (-CX - 2) */ dec cx dec cx /* restore flags and registers */ popf ret } } #pragma aux mystrlen parm [es di] value [cx] modify exact [ax cx di] nomemory; /* returns -1 if the NULL-terminated s string contains any wildcard (?, *) * character. otherwise returns the length of the string. */ static int __declspec(naked) len_if_no_wildcards(char far *s) { _asm { /* Save registers and flags into the stack */ push ds pushf cld /* clear direction flag (increment si/di) */ mov ds, cx /* load segment of string */ xor cx, cx /* CX = 0 */ next: lodsb /* load byte at DS:SI into AL */ test al,al /* is zero? */ jz end /* return string length */ inc cx /* it is a character, increment cx */ cmp al,'?' /* is '?' ? */ je wildcard cmp al, '*' /* is '*' ? */ jne next /* if not, continue with next char */ wildcard: mov cx, -1 end: /* restore flags and registers */ popf pop ds ret } } #pragma aux len_if_no_wildcards parm [cx si] value [cx] modify exact [al cx si] nomemory; /* computes a BSD checksum of l bytes at dataptr location */ __declspec(naked) static unsigned short bsdsum(unsigned char *dataptr, unsigned short l) { _asm { cld /* clear direction flag */ xor bx, bx /* bx will hold the result */ xor ax, ax iterate: lodsb /* load a byte from DS:SI into AL and INC SI */ ror bx, 1 add bx, ax dec cx /* DEC CX + JNZ could be replaced by a single LOOP */ jnz iterate /* instruction, but DEC+JNZ is 3x faster (on 8086) */ ret } } /* Must be [si] [cx] and NOT [si cx] */ #pragma aux bsdsum parm [si] [cx] value [bx] modify exact [ax bx cx si] nomemory; /* this function is called two times by the packet driver. One time for * telling that a packet is incoming, and how big it is, so the application * can prepare a buffer for it and hand it back to the packet driver. the * second call is just to let know that the frame has been copied into the * buffer. This is a naked function - I don't need the compiler to get into * the way when dealing with packet driver callbacks. * IMPORTANT: this function must take care to modify ONLY the registers * ES and DI - packet drivers can be easily confused should anything else * be modified. */ void __declspec(naked) far pktdrv_recv(void) { _asm { // jmp skip // SIG db 'pktr' // skip: /* save DS and flags to stack */ push ds /* save old ds (I will change it) */ push bx /* save bx (I use it as a temporary register) */ pushf /* save flags */ /* set my custom DS (saved in CS:glob_newds) */ mov bx, cs:glob_newds mov ds, bx /* handle the call */ cmp ax, 0 jne secondcall /* if ax != 0, then packet driver just filled my buffer */ /* first call: the packet driver needs a buffer of CX bytes */ cmp cx, FRAMESIZE /* is cx > FRAMESIZE ? (unsigned) */ ja nobufferavail /* it is too small (that's what she said!) */ /* see if buffer not filled already... */ cmp glob_pktdrv_recvbufflen, 0 /* is bufflen > 0 ? (signed) */ jg nobufferavail /* if signed > 0, then we are busy already */ /* buffer is available, set its seg:off in es:di */ mov es,bx /* set es:di to recvbuff */ mov di, offset glob_pktdrv_recvbuff /* set bufferlen to expected len and switch it to neg until data comes */ mov glob_pktdrv_recvbufflen, cx neg glob_pktdrv_recvbufflen /* restore flags, bx and ds, then return */ jmp restoreandret nobufferavail: /* no buffer available, or it's too small -> fail */ /* zero out es and di - this tells the packet driver 'sorry no can do' */ xor di,di push di pop es /* restore flags, bx and ds, then return */ jmp restoreandret secondcall: /* second call: I've just got data in buff */ /* I switch back bufflen to positive so the app can see that something is there now */ neg glob_pktdrv_recvbufflen /* restore flags, bx and ds, then return */ restoreandret: popf /* restore flags */ pop bx /* restore bx */ pop ds /* restore ds */ retf } } /* this table makes it easy to figure out if I want a subfunction or not */ unsigned char supportedfunctions[0x2F] = { AL_INSTALLCHK, /* 0x00 */ AL_RMDIR, /* 0x01 */ AL_UNKNOWN, /* 0x02 */ AL_MKDIR, /* 0x03 */ AL_UNKNOWN, /* 0x04 */ AL_CHDIR, /* 0x05 */ AL_CLSFIL, /* 0x06 */ AL_CMMTFIL, /* 0x07 */ AL_READFIL, /* 0x08 */ AL_WRITEFIL, /* 0x09 */ AL_LOCKFIL, /* 0x0A */ AL_UNLOCKFIL, /* 0x0B */ AL_DISKSPACE, /* 0x0C */ AL_UNKNOWN, /* 0x0D */ AL_SETATTR, /* 0x0E */ AL_GETATTR, /* 0x0F */ AL_UNKNOWN, /* 0x10 */ AL_RENAME, /* 0x11 */ AL_UNKNOWN, /* 0x12 */ AL_DELETE, /* 0x13 */ AL_UNKNOWN, /* 0x14 */ AL_UNKNOWN, /* 0x15 */ AL_OPEN, /* 0x16 */ AL_CREATE, /* 0x17 */ AL_UNKNOWN, /* 0x18 */ AL_UNKNOWN, /* 0x19 */ AL_UNKNOWN, /* 0x1A */ AL_FINDFIRST, /* 0x1B */ AL_FINDNEXT, /* 0x1C */ AL_UNKNOWN, /* 0x1D */ AL_UNKNOWN, /* 0x1E */ AL_UNKNOWN, /* 0x1F */ AL_UNKNOWN, /* 0x20 */ AL_SKFMEND, /* 0x21 */ AL_UNKNOWN, /* 0x22 */ AL_UNKNOWN, /* 0x23 */ AL_UNKNOWN, /* 0x24 */ AL_UNKNOWN, /* 0x25 */ AL_UNKNOWN, /* 0x26 */ AL_UNKNOWN, /* 0x27 */ AL_UNKNOWN, /* 0x28 */ AL_UNKNOWN, /* 0x29 */ AL_UNKNOWN, /* 0x2A */ AL_UNKNOWN, /* 0x2B */ AL_UNKNOWN, /* 0x2C */ AL_UNKNOWN_2D, /* 0x2D */ AL_SPOPNFIL /* 0x2E */ }; /* an INTPACK struct contains following items: regs.w.gs regs.w.fs regs.w.es regs.w.ds regs.w.di regs.w.si regs.w.bp regs.w.sp regs.w.bx regs.w.dx regs.w.cx regs.w.ax regs.w.ip regs.w.cs regs.w.flags (AND with INTR_CF to fetch the CF flag - INTR_CF is defined as 0x0001) regs.h.bl regs.h.bh regs.h.dl regs.h.dh regs.h.cl regs.h.ch regs.h.al regs.h.ah */ /* sends query out, as found in glob_pktdrv_sndbuff, and awaits for an answer. * this function returns the length of replyptr, or 0xFFFF on error. */ unsigned short sendquery(unsigned char query, unsigned char drive, unsigned short bufflen, unsigned char **replyptr, unsigned short **replyax, unsigned int updatermac) { static unsigned char seq; unsigned short count; unsigned char t; unsigned char volatile far *rtc = (unsigned char far *)0x46C; /* this points to a char, while the rtc timer is a word - but I care only about the lowest 8 bits. Be warned that this location won't increment while interrupts are disabled! */ /* resolve remote drive - no need to validate it, it has been validated * already by inthandler() */ drive = glob_data.ldrv[drive]; /* bufflen provides payload's length, but I prefer knowing the frame's len */ bufflen += 60; /* if query too long then quit */ if (bufflen > sizeof(glob_pktdrv_sndbuff)) { return(0); } /* inc seq */ seq++; /* I do not fill in ethernet headers (src mac, dst mac, ethertype), nor * PROTOVER, since all these have been inited already at transient time */ /* padding (38 bytes) */ ((unsigned short *)glob_pktdrv_sndbuff)[26] = bufflen; /* total frame len */ glob_pktdrv_sndbuff[57] = seq; /* seq number */ glob_pktdrv_sndbuff[58] = drive; glob_pktdrv_sndbuff[59] = query; /* AL value (query) */ if (glob_pktdrv_sndbuff[56] & 128) { /* if CKSUM enabled, compute it */ /* fill in the BSD checksum at offset 54 */ ((unsigned short *)glob_pktdrv_sndbuff)[27] = bsdsum(glob_pktdrv_sndbuff + 56, bufflen - 56); } /* I do not copy anything more into glob_pktdrv_sndbuff - the caller is * expected to have already copied all relevant data into glob_pktdrv_sndbuff+60 * copybytes((unsigned char far *)glob_pktdrv_sndbuff + 60, (unsigned char far *)buff, bufflen); */ /* send the query frame and wait for an answer for about 100ms. then, resend * the query again and again, up to 5 times. the RTC clock at 0x46C is used * as a timing reference. */ glob_pktdrv_recvbufflen = 0; /* mark the receiving buffer empty */ for (count = 5; count != 0; count--) { /* faster than count=0; count<5; count++ */ /* send the query frame out */ _asm { /* save registers */ push ax push cx push dx /* may be changed by the packet driver (set to errno) */ push si pushf /* must be last register pushed (expected by 'call') */ /* */ mov ah, 4h /* SendPkt */ mov cx, bufflen mov si, offset glob_pktdrv_sndbuff /* DS:SI points to buff, I do not modify DS because the buffer should already be in my data segment (small memory model) */ /* int to variable vector is a mess, so I have fetched its vector myself * and pushf + cli + call far it now to simulate a regular int */ /* pushf -- already on the stack */ cli call dword ptr glob_pktdrv_pktcall /* restore registers (but not pushf, already restored by call) */ pop si pop dx pop cx pop ax } /* wait for (and validate) the answer frame */ t = *rtc; for (;;) { int i; if ((t != *rtc) && (t+1 != *rtc) && (*rtc != 0)) { break; /* timeout, retry */ } if (glob_pktdrv_recvbufflen < 1) continue; /* I've got something! */ /* is the frame long enough for me to care? */ if (glob_pktdrv_recvbufflen < 60) goto ignoreframe; /* is it for me? (correct src mac & dst mac) */ for (i = 0; i < 6; i++) { if (glob_pktdrv_recvbuff[i] != GLOB_LMAC[i]) goto ignoreframe; if ((updatermac == 0) && (glob_pktdrv_recvbuff[i+6] != GLOB_RMAC[i])) goto ignoreframe; } /* is the ethertype and seq what I expect? */ if ((((unsigned short *)glob_pktdrv_recvbuff)[6] != 0xF5EDu) || (glob_pktdrv_recvbuff[57] != seq)) goto ignoreframe; /* validate frame length (if provided) */ if (((unsigned short *)glob_pktdrv_recvbuff)[26] > glob_pktdrv_recvbufflen) { /* frame appears to be truncated */ goto ignoreframe; } if (((unsigned short *)glob_pktdrv_recvbuff)[26] < 60) { /* malformed frame */ goto ignoreframe; } glob_pktdrv_recvbufflen = ((unsigned short *)glob_pktdrv_recvbuff)[26]; /* if CKSUM enabled, check it on received frame */ if (glob_pktdrv_sndbuff[56] & 128) { /* is the cksum ok? */ if (bsdsum(glob_pktdrv_recvbuff + 56, glob_pktdrv_recvbufflen - 56) != (((unsigned short *)glob_pktdrv_recvbuff)[27])) { /* DEBUG - prints a '!' on screen on cksum error */ /*{ unsigned short far *v = (unsigned short far *)0xB8000000l; v[0] = 0x4000 | '!'; }*/ goto ignoreframe; } } /* return buffer (without headers and seq) */ *replyptr = glob_pktdrv_recvbuff + 60; *replyax = (unsigned short *)(glob_pktdrv_recvbuff + 58); /* update glob_rmac if needed, then return */ if (updatermac != 0) copybytes(GLOB_RMAC, glob_pktdrv_recvbuff + 6, 6); return(glob_pktdrv_recvbufflen - 60); ignoreframe: /* ignore this frame and wait for the next one */ glob_pktdrv_recvbufflen = 0; /* mark the buffer empty */ } } return(0xFFFFu); /* return error */ } /* reset CF (set on error only) and AX (expected to contain the error code, * I might set it later) - I assume a success */ #define SUCCESSFLAG glob_intregs.w.ax = 0; glob_intregs.w.flags &= ~(INTR_CF); #define FAILFLAG(x) {glob_intregs.w.ax = x; glob_intregs.w.flags |= INTR_CF;} /* this function contains the logic behind INT 2F processing */ void process2f(void) { #if DEBUGLEVEL > 0 char far *dbg_msg = NULL; #endif short i; unsigned char *answer; unsigned char *buff; /* pointer to the "query arguments" part of glob_pktdrv_sndbuff */ unsigned char subfunction; unsigned short *ax; /* used to collect the resulting value of AX */ buff = glob_pktdrv_sndbuff + 60; /* DEBUG output (RED) */ #if DEBUGLEVEL > 0 dbg_xpos &= 511; dbg_VGA[dbg_startoffset + dbg_xpos++] = 0x4e00 | ' '; dbg_VGA[dbg_startoffset + dbg_xpos++] = 0x4e00 | (dbg_hexc[(glob_intregs.h.al >> 4) & 0xf]); dbg_VGA[dbg_startoffset + dbg_xpos++] = 0x4e00 | (dbg_hexc[glob_intregs.h.al & 0xf]); dbg_VGA[dbg_startoffset + dbg_xpos++] = 0x4e00 | ' '; #endif /* remember the AL register (0x2F subfunction id) */ subfunction = glob_intregs.h.al; /* if we got here, then the call is definitely for us. set AX and CF to */ /* 'success' (being a natural optimist I assume success) */ SUCCESSFLAG; /* look what function is called exactly and process it */ switch (subfunction) { case AL_RMDIR: /*** 01h: RMDIR ******************************************/ /* RMDIR is like MKDIR, but I need to check if dir is not current first */ for (i = 0; glob_sdaptr->fn1[i] != 0; i++) { if (glob_sdaptr->fn1[i] != glob_sdaptr->drive_cdsptr[i]) goto proceedasmkdir; } FAILFLAG(16); /* err 16 = "attempted to remove current directory" */ break; proceedasmkdir: case AL_MKDIR: /*** 03h: MKDIR ******************************************/ i = mystrlen(glob_sdaptr->fn1); /* fn1 must be at least 2 bytes long */ if (i < 2) { FAILFLAG(3); /* "path not found" */ break; } /* copy fn1 to buff (but skip drive part) */ i -= 2; copybytes(buff, glob_sdaptr->fn1 + 2, i); /* send query providing fn1 */ if (sendquery(subfunction, glob_reqdrv, i, &answer, &ax, 0) == 0) { glob_intregs.w.ax = *ax; if (*ax != 0) glob_intregs.w.flags |= INTR_CF; } else { FAILFLAG(2); } break; case AL_CHDIR: /*** 05h: CHDIR ******************************************/ /* The INT 2Fh/1105h redirector callback is executed by DOS when * changing directories. The Phantom authors (and RBIL contributors) * clearly thought that it was the redirector's job to update the CDS, * but in fact the callback is only meant to validate that the target * directory exists; DOS subsequently updates the CDS. */ /* fn1 must be at least 2 bytes long */ i = mystrlen(glob_sdaptr->fn1); if (i < 2) { FAILFLAG(3); /* "path not found" */ break; } /* copy fn1 to buff (but skip the drive: part) */ i -= 2; copybytes(buff, glob_sdaptr->fn1 + 2, i); /* send query providing fn1 */ if (sendquery(AL_CHDIR, glob_reqdrv, i, &answer, &ax, 0) == 0) { glob_intregs.w.ax = *ax; if (*ax != 0) glob_intregs.w.flags |= INTR_CF; } else { FAILFLAG(3); /* "path not found" */ } break; case AL_CLSFIL: /*** 06h: CLSFIL ****************************************/ /* my only job is to decrement the SFT's handle count (which I didn't * have to increment during OPENFILE since DOS does it... talk about * consistency. I also inform the server about this, just so it knows */ /* ES:DI points to the SFT */ { struct sftstruct far *sftptr = MK_FP(glob_intregs.x.es, glob_intregs.x.di); if (sftptr->handle_count > 0) sftptr->handle_count--; ((unsigned short *)buff)[0] = sftptr->start_sector; if (sendquery(AL_CLSFIL, glob_reqdrv, 2, &answer, &ax, 0) == 0) { if (*ax != 0) FAILFLAG(*ax); } } break; case AL_CMMTFIL: /*** 07h: CMMTFIL **************************************/ /* I have nothing to do here */ break; case AL_READFIL: /*** 08h: READFIL **************************************/ { /* ES:DI points to the SFT (whose file_pos needs to be updated) */ /* CX = number of bytes to read (to be updated with number of bytes actually read) */ /* SDA DTA = read buffer */ struct sftstruct far *sftptr = MK_FP(glob_intregs.x.es, glob_intregs.x.di); unsigned short totreadlen; /* is the file open for write-only? */ if (sftptr->open_mode & 1) { FAILFLAG(5); /* "access denied" */ break; } /* return immediately if the caller wants to read 0 bytes */ if (glob_intregs.x.cx == 0) break; /* do multiple read operations so chunks can fit in my eth frames */ totreadlen = 0; for (;;) { int chunklen, len; if ((glob_intregs.x.cx - totreadlen) < (FRAMESIZE - 60)) { chunklen = glob_intregs.x.cx - totreadlen; } else { chunklen = FRAMESIZE - 60; } /* query is OOOOSSLL (offset, start sector, length to read) */ ((unsigned long *)buff)[0] = sftptr->file_pos + totreadlen; ((unsigned short *)buff)[2] = sftptr->start_sector; ((unsigned short *)buff)[3] = chunklen; len = sendquery(AL_READFIL, glob_reqdrv, 8, &answer, &ax, 0); if (len == 0xFFFFu) { /* network error */ FAILFLAG(2); break; } else if (*ax != 0) { /* backend error */ FAILFLAG(*ax); break; } else { /* success */ copybytes(glob_sdaptr->curr_dta + totreadlen, answer, len); totreadlen += len; if ((len < chunklen) || (totreadlen == glob_intregs.x.cx)) { /* EOF - update SFT and break out */ sftptr->file_pos += totreadlen; glob_intregs.x.cx = totreadlen; break; } } } } break; case AL_WRITEFIL: /*** 09h: WRITEFIL ************************************/ { /* ES:DI points to the SFT (whose file_pos needs to be updated) */ /* CX = number of bytes to write (to be updated with number of bytes actually written) */ /* SDA DTA = read buffer */ struct sftstruct far *sftptr = MK_FP(glob_intregs.x.es, glob_intregs.x.di); unsigned short more, bytesleft, chunklen, written = 0; /* is the file open for read-only? */ if ((sftptr->open_mode & 3) == 0) { FAILFLAG(5); /* "access denied" */ break; } /* TODO FIXME I should update the file's time in the SFT here */ /* do multiple write operations so chunks can fit in my eth frames */ bytesleft = glob_intregs.x.cx; /* BUGFIX: WRITEFIL can be used to truncate a file to the current * file position by writing zero bytes. */ more = TRUE; while (more) { unsigned short len; chunklen = bytesleft; if (chunklen > FRAMESIZE - 66) chunklen = FRAMESIZE - 66; /* query is OOOOSS (file offset, start sector/fileid) */ ((unsigned long *)buff)[0] = sftptr->file_pos; ((unsigned short *)buff)[2] = sftptr->start_sector; copybytes(buff + 6, glob_sdaptr->curr_dta + written, chunklen); len = sendquery(AL_WRITEFIL, glob_reqdrv, chunklen + 6, &answer, &ax, 0); if (len == 0xFFFFu) { /* network error */ FAILFLAG(2); break; } else if ((*ax != 0) || (len != 2)) { /* backend error */ FAILFLAG(*ax); break; } else { /* success - write amount of bytes written into CX and update SFT */ len = ((unsigned short *)answer)[0]; written += len; bytesleft -= len; /* Set more to TRUE if there are other chunks to write */ more = (bytesleft > 0 ? TRUE: FALSE); glob_intregs.x.cx = written; sftptr->file_pos += len; if (sftptr->file_pos > sftptr->file_size) sftptr->file_size = sftptr->file_pos; if (len != chunklen) break; /* something bad happened on the other side */ } } } break; case AL_LOCKFIL: /*** 0Ah: LOCKFIL **************************************/ { struct sftstruct far *sftptr = MK_FP(glob_intregs.x.es, glob_intregs.x.di); ((unsigned short *)buff)[0] = glob_intregs.x.cx; ((unsigned short *)buff)[1] = sftptr->start_sector; if (glob_intregs.h.bl > 1) FAILFLAG(2); /* BL should be either 0 (lock) or 1 (unlock) */ /* copy 8*CX bytes from DS:DX to buff+4 (parameters block) */ copybytes(buff + 4, MK_FP(glob_intregs.x.ds, glob_intregs.x.dx), glob_intregs.x.cx << 3); if (sendquery(AL_LOCKFIL + glob_intregs.h.bl, glob_reqdrv, (glob_intregs.x.cx << 3) + 4, &answer, &ax, 0) != 0) { FAILFLAG(2); } } break; case AL_UNLOCKFIL: /*** 0Bh: UNLOCKFIL **********************************/ /* Nothing here - this isn't supposed to be used by DOS 4+ */ FAILFLAG(2); break; case AL_DISKSPACE: /*** 0Ch: get disk information ***********************/ if (sendquery(AL_DISKSPACE, glob_reqdrv, 0, &answer, &ax, 0) == 6) { glob_intregs.w.ax = *ax; /* sectors per cluster */ glob_intregs.w.bx = ((unsigned short *)answer)[0]; /* total clusters */ glob_intregs.w.cx = ((unsigned short *)answer)[1]; /* bytes per sector */ glob_intregs.w.dx = ((unsigned short *)answer)[2]; /* num of available clusters */ } else { FAILFLAG(2); } break; case AL_SETATTR: /*** 0Eh: SETATTR **************************************/ /* sdaptr->fn1 -> file to set attributes for stack word -> new attributes (stack must not be changed!) */ /* fn1 must be at least 2 characters long */ i = mystrlen(glob_sdaptr->fn1); if (i < 2) { FAILFLAG(2); break; } /* */ buff[0] = glob_reqstkword; /* copy fn1 to buff (but without the drive part) */ copybytes(buff + 1, glob_sdaptr->fn1 + 2, i - 2); #if DEBUGLEVEL > 0 dbg_VGA[dbg_startoffset + dbg_xpos++] = 0x1000 | dbg_hexc[(glob_reqstkword >> 4) & 15]; dbg_VGA[dbg_startoffset + dbg_xpos++] = 0x1000 | dbg_hexc[glob_reqstkword & 15]; #endif i = sendquery(AL_SETATTR, glob_reqdrv, i - 1, &answer, &ax, 0); if (i != 0) { FAILFLAG(2); } else if (*ax != 0) { FAILFLAG(*ax); } break; case AL_GETATTR: /*** 0Fh: GETATTR **************************************/ i = mystrlen(glob_sdaptr->fn1); if (i < 2) { FAILFLAG(2); break; } i -= 2; copybytes(buff, glob_sdaptr->fn1 + 2, i); i = sendquery(AL_GETATTR, glob_reqdrv, i, &answer, &ax, 0); if ((unsigned short)i == 0xffffu) { FAILFLAG(2); } else if ((i != 9) || (*ax != 0)) { FAILFLAG(*ax); } else { /* all good */ /* CX = timestamp * DX = datestamp * BX:DI = fsize * AX = attr * NOTE: Undocumented DOS talks only about setting AX, no fsize, time * and date, these are documented in RBIL and used by SHSUCDX */ glob_intregs.w.cx = ((unsigned short *)answer)[0]; /* time */ glob_intregs.w.dx = ((unsigned short *)answer)[1]; /* date */ glob_intregs.w.bx = ((unsigned short *)answer)[3]; /* fsize hi word */ glob_intregs.w.di = ((unsigned short *)answer)[2]; /* fsize lo word */ glob_intregs.w.ax = answer[8]; /* file attribs */ } break; case AL_RENAME: /*** 11h: RENAME ****************************************/ /* sdaptr->fn1 = old name * sdaptr->fn2 = new name */ /* is the operation for the SAME drive? */ if (glob_sdaptr->fn1[0] != glob_sdaptr->fn2[0]) { FAILFLAG(2); break; } /* prepare the query (LSSS...DDD...) */ i = mystrlen(glob_sdaptr->fn1); if (i < 2) { FAILFLAG(2); break; } i -= 2; /* trim out the drive: part (C:\FILE --> \FILE) */ buff[0] = i; copybytes(buff + 1, glob_sdaptr->fn1 + 2, i); i = len_if_no_wildcards(glob_sdaptr->fn2); if (i < 2) { FAILFLAG(3); break; } i -= 2; /* trim out the drive: part (C:\FILE --> \FILE) */ copybytes(buff + 1 + buff[0], glob_sdaptr->fn2 + 2, i); /* send the query out */ i = sendquery(AL_RENAME, glob_reqdrv, 1 + buff[0] + i, &answer, &ax, 0); if (i != 0) { FAILFLAG(2); } else if (*ax != 0) { FAILFLAG(*ax); } break; case AL_DELETE: /*** 13h: DELETE ****************************************/ #if DEBUGLEVEL > 0 dbg_msg = glob_sdaptr->fn1; #endif /* compute length of fn1 and copy it to buff (w/o the 'drive:' part) */ i = mystrlen(glob_sdaptr->fn1); if (i < 2) { FAILFLAG(2); break; } i -= 2; copybytes(buff, glob_sdaptr->fn1 + 2, i); /* send query */ i = sendquery(AL_DELETE, glob_reqdrv, i, &answer, &ax, 0); if ((unsigned short)i == 0xffffu) { FAILFLAG(2); } else if ((i != 0) || (*ax != 0)) { FAILFLAG(*ax); } break; case AL_OPEN: /*** 16h: OPEN ********************************************/ case AL_CREATE: /*** 17h: CREATE ****************************************/ case AL_SPOPNFIL: /*** 2Eh: SPOPNFIL ************************************/ #if DEBUGLEVEL > 0 dbg_msg = glob_sdaptr->fn1; #endif /* fail if fn1 contains any wildcard, otherwise get len of fn1 */ i = len_if_no_wildcards(glob_sdaptr->fn1); if (i < 2) { FAILFLAG(3); break; } i -= 2; /* prepare and send query (SSCCMMfff...) */ ((unsigned short *)buff)[0] = glob_reqstkword; /* WORD from the stack */ ((unsigned short *)buff)[1] = glob_sdaptr->spop_act; /* action code (SPOP only) */ ((unsigned short *)buff)[2] = glob_sdaptr->spop_mode; /* open mode (SPOP only) */ copybytes(buff + 6, glob_sdaptr->fn1 + 2, i); i = sendquery(subfunction, glob_reqdrv, i + 6, &answer, &ax, 0); if ((unsigned short)i == 0xffffu) { FAILFLAG(2); } else if ((i != 25) || (*ax != 0)) { FAILFLAG(*ax); } else { /* ES:DI contains an uninitialized SFT */ struct sftstruct far *sftptr = MK_FP(glob_intregs.x.es, glob_intregs.x.di); /* special treatment for SPOP, (set open_mode and return CX, too) */ if (subfunction == AL_SPOPNFIL) { glob_intregs.w.cx = ((unsigned short *)answer)[11]; } if (sftptr->open_mode & 0x8000) { /* if bit 15 is set, then it's a "FCB open", and requires the internal DOS "Set FCB Owner" function to be called */ /* TODO FIXME set_sft_owner() */ #if DEBUGLEVEL > 0 dbg_VGA[25*80] = 0x1700 | '$'; #endif } sftptr->file_attr = answer[0]; sftptr->dev_info_word = 0x8040 | glob_reqdrv; /* mark device as network & unwritten drive */ sftptr->dev_drvr_ptr = NULL; sftptr->start_sector = ((unsigned short *)answer)[10]; sftptr->file_time = ((unsigned long *)answer)[3]; sftptr->file_size = ((unsigned long *)answer)[4]; sftptr->file_pos = 0; sftptr->open_mode &= 0xff00u; sftptr->open_mode |= answer[24]; sftptr->rel_sector = 0xffff; sftptr->abs_sector = 0xffff; sftptr->dir_sector = 0; sftptr->dir_entry_no = 0xff; /* why such value? no idea, PHANTOM.C uses that, too */ copybytes(sftptr->file_name, answer + 1, 11); } break; case AL_FINDFIRST: /*** 1Bh: FINDFIRST **********************************/ case AL_FINDNEXT: /*** 1Ch: FINDNEXT ***********************************/ { /* AX = 111Bh SS = DS = DOS DS [DTA] = uninitialized 21-byte findfirst search data (see #01626 at INT 21/AH=4Eh) SDA first filename pointer (FN1, 9Eh) -> fully-qualified search template SDA CDS pointer -> current directory structure for drive with file SDA search attribute = attribute mask for search Return: CF set on error AX = DOS error code (see #01680 at INT 21/AH=59h/BX=0000h) -> http://www.ctyme.com/intr/rb-3012.htm CF clear if successful [DTA] = updated findfirst search data (bit 7 of first byte must be set) [DTA+15h] = standard directory entry for file (see #01352) FindNext is the same, but only DTA should be used to fetch search params */ struct sdbstruct far *dta; #if DEBUGLEVEL > 0 dbg_msg = glob_sdaptr->fn1; #endif /* prepare the query buffer (i must provide query's length) */ if (subfunction == AL_FINDFIRST) { dta = (struct sdbstruct far *)(glob_sdaptr->curr_dta); /* FindFirst needs to fetch search arguments from SDA */ buff[0] = glob_sdaptr->srch_attr; /* file attributes to look for */ /* copy fn1 (w/o drive) to buff */ for (i = 2; glob_sdaptr->fn1[i] != 0; i++) buff[i-1] = glob_sdaptr->fn1[i]; i--; /* adjust i because its one too much otherwise */ } else { /* FindNext needs to fetch search arguments from DTA (es:di) */ dta = MK_FP(glob_intregs.x.es, glob_intregs.x.di); ((unsigned short *)buff)[0] = dta->par_clstr; ((unsigned short *)buff)[1] = dta->dir_entry; buff[4] = dta->srch_attr; /* copy search template to buff */ for (i = 0; i < 11; i++) buff[i+5] = dta->srch_tmpl[i]; i += 5; /* i must provide the exact query's length */ } /* send query to remote peer and wait for answer */ i = sendquery(subfunction, glob_reqdrv, i, &answer, &ax, 0); if (i == 0xffffu) { if (subfunction == AL_FINDFIRST) { FAILFLAG(2); /* a failed findfirst returns error 2 (file not found) */ } else { FAILFLAG(18); /* a failed findnext returns error 18 (no more files) */ } break; } else if ((*ax != 0) || (i != 24)) { FAILFLAG(*ax); break; } /* fill in the directory entry 'found_file' (32 bytes) * 00h unsigned char fname[11] * 0Bh unsigned char fattr (1=RO 2=HID 4=SYS 8=VOL 16=DIR 32=ARCH 64=DEV) * 0Ch unsigned char f1[10] * 16h unsigned short time_lstupd * 18h unsigned short date_lstupd * 1Ah unsigned short start_clstr *optional* * 1Ch unsigned long fsize */ copybytes(glob_sdaptr->found_file.fname, answer+1, 11); /* found file name */ glob_sdaptr->found_file.fattr = answer[0]; /* found file attributes */ glob_sdaptr->found_file.time_lstupd = ((unsigned short *)answer)[6]; /* time (word) */ glob_sdaptr->found_file.date_lstupd = ((unsigned short *)answer)[7]; /* date (word) */ glob_sdaptr->found_file.start_clstr = 0; /* start cluster (I don't care) */ glob_sdaptr->found_file.fsize = ((unsigned long *)answer)[4]; /* fsize (word) */ /* put things into DTA so I can understand where I left should FindNext * be called - this shall be a valid FindFirst structure (21 bytes): * 00h unsigned char drive letter (7bits, MSB must be set for remote drives) * 01h unsigned char search_tmpl[11] * 0Ch unsigned char search_attr (1=RO 2=HID 4=SYS 8=VOL 16=DIR 32=ARCH 64=DEV) * 0Dh unsigned short entry_count_within_directory * 0Fh unsigned short cluster number of start of parent directory * 11h unsigned char reserved[4] * -- RBIL says: [DTA+15h] = standard directory entry for file * 15h 11-bytes (FCB-style) filename+ext ("FILE0000TXT") * 20h unsigned char attr. of file found (1=RO 2=HID 4=SYS 8=VOL 16=DIR 32=ARCH 64=DEV) * 21h 10-bytes reserved * 2Bh unsigned short file time * 2Dh unsigned short file date * 2Fh unsigned short cluster * 31h unsigned long file size */ /* init some stuff only on FindFirst (FindNext contains valid values already) */ if (subfunction == AL_FINDFIRST) { dta->drv_lett = glob_reqdrv | 128; /* bit 7 set means 'network drive' */ copybytes(dta->srch_tmpl, glob_sdaptr->fcb_fn1, 11); dta->srch_attr = glob_sdaptr->srch_attr; } dta->par_clstr = ((unsigned short *)answer)[10]; dta->dir_entry = ((unsigned short *)answer)[11]; /* then 32 bytes as in the found_file record */ copybytes(dta + 0x15, &(glob_sdaptr->found_file), 32); } break; case AL_SKFMEND: /*** 21h: SKFMEND **************************************/ { struct sftstruct far *sftptr = MK_FP(glob_intregs.x.es, glob_intregs.x.di); ((unsigned short *)buff)[0] = glob_intregs.x.dx; ((unsigned short *)buff)[1] = glob_intregs.x.cx; ((unsigned short *)buff)[2] = sftptr->start_sector; /* send query to remote peer and wait for answer */ i = sendquery(AL_SKFMEND, glob_reqdrv, 6, &answer, &ax, 0); if (i == 0xffffu) { FAILFLAG(2); } else if ((*ax != 0) || (i != 4)) { FAILFLAG(*ax); } else { /* put new position into DX:AX */ glob_intregs.w.ax = ((unsigned short *)answer)[0]; glob_intregs.w.dx = ((unsigned short *)answer)[1]; } break; } case AL_UNKNOWN_2D: /*** 2Dh: UNKNOWN_2D ********************************/ /* this is only called in MS-DOS v4.01, its purpose is unknown. MSCDEX * returns AX=2 there, and so do I. */ glob_intregs.w.ax = 2; break; } /* DEBUG */ #if DEBUGLEVEL > 0 while ((dbg_msg != NULL) && (*dbg_msg != 0)) dbg_VGA[dbg_startoffset + dbg_xpos++] = 0x4f00 | *(dbg_msg++); #endif } /**** Allocate space for the Interrupt handler stack */ static unsigned char newstack[NEWSTACKSZ]; /* this function is hooked on INT 2Fh */ void __interrupt __far inthandler(union INTPACK r) { /* insert a static code signature so I can reliably patch myself later, * this will also contain the DS segment to use and actually set it */ _asm { jmp SKIPTSRSIG TSRSIG db 'MVet' SKIPTSRSIG: /* save AX */ push ax /* set my custom DS (saved in CS:glob_newds) */ mov ax, cs:glob_newds mov ds, ax /* save one word from the stack (might be used by SETATTR later) * The original stack should be at SS:BP+30 */ mov ax, ss:[BP+30] mov glob_reqstkword, ax /* uncomment the debug code below to insert a stack's dump into snd eth * frame - debugging ONLY! */ /* mov ax, ss:[BP] mov word ptr [glob_pktdrv_sndbuff+16], ax mov ax, ss:[BP+2] mov word ptr [glob_pktdrv_sndbuff+18], ax mov ax, ss:[BP+4] mov word ptr [glob_pktdrv_sndbuff+20], ax mov ax, ss:[BP+6] mov word ptr [glob_pktdrv_sndbuff+22], ax mov ax, ss:[BP+8] mov word ptr [glob_pktdrv_sndbuff+24], ax mov ax, ss:[BP+10] mov word ptr [glob_pktdrv_sndbuff+26], ax mov ax, ss:[BP+12] mov word ptr [glob_pktdrv_sndbuff+28], ax mov ax, ss:[BP+14] mov word ptr [glob_pktdrv_sndbuff+30], ax mov ax, ss:[BP+16] mov word ptr [glob_pktdrv_sndbuff+32], ax mov ax, ss:[BP+18] mov word ptr [glob_pktdrv_sndbuff+34], ax mov ax, ss:[BP+20] mov word ptr [glob_pktdrv_sndbuff+36], ax mov ax, ss:[BP+22] mov word ptr [glob_pktdrv_sndbuff+38], ax */ /* restore AX */ pop ax } /* DEBUG output (BLUE) */ #if DEBUGLEVEL > 1 dbg_VGA[dbg_startoffset + dbg_xpos++] = 0x1e00 | (dbg_hexc[(r.h.ah >> 4) & 0xf]); dbg_VGA[dbg_startoffset + dbg_xpos++] = 0x1e00 | (dbg_hexc[r.h.ah & 0xf]); dbg_VGA[dbg_startoffset + dbg_xpos++] = 0x1e00 | (dbg_hexc[(r.h.al >> 4) & 0xf]); dbg_VGA[dbg_startoffset + dbg_xpos++] = 0x1e00 | (dbg_hexc[r.h.al & 0xf]); dbg_VGA[dbg_startoffset + dbg_xpos++] = 0; #endif /* is it a multiplex call for me? */ if (r.h.ah == glob_multiplexid) { if (r.h.al == 0) { /* install check */ r.h.al = 0xff; /* 'installed' */ r.w.bx = 0x4d86; /* MV */ r.w.cx = 0x7e1; /* 2017 */ return; } if ((r.h.al == 1) && (r.x.cx == 0x4d86)) { /* get shared data ptr (AX=0, ptr under BX:CX) */ _asm { push ds pop glob_reqstkword } r.w.ax = 0; /* zero out AX */ r.w.bx = glob_reqstkword; /* ptr returned at BX:CX */ r.w.cx = FP_OFF(&glob_data); return; } } /* if not related to a redirector function (AH=11h), or the function is * an 'install check' (0), or the function is over our scope (2Eh), or it's * an otherwise unsupported function (as pointed out by supportedfunctions), * then call the previous INT 2F handler immediately */ if ((r.h.ah != 0x11) || (r.h.al == AL_INSTALLCHK) || (r.h.al > 0x2E) || (supportedfunctions[r.h.al] == AL_UNKNOWN)) goto CHAINTOPREVHANDLER; /* DEBUG output (GREEN) */ #if DEBUGLEVEL > 0 dbg_VGA[dbg_startoffset + dbg_xpos++] = 0x2e00 | (dbg_hexc[(r.h.al >> 4) & 0xf]); dbg_VGA[dbg_startoffset + dbg_xpos++] = 0x2e00 | (dbg_hexc[r.h.al & 0xf]); dbg_VGA[dbg_startoffset + dbg_xpos++] = 0; #endif /* determine whether or not the query is meant for a drive I control, * and if not - chain to the previous INT 2F handler */ if (((r.h.al >= AL_CLSFIL) && (r.h.al <= AL_UNLOCKFIL)) || (r.h.al == AL_SKFMEND) || (r.h.al == AL_UNKNOWN_2D)) { /* ES:DI points to the SFT: if the bottom 6 bits of the device information * word in the SFT are > last drive, then it relates to files not associated * with drives, such as LAN Manager named pipes. */ struct sftstruct far *sft = MK_FP(r.w.es, r.w.di); glob_reqdrv = sft->dev_info_word & 0x3F; } else { switch (r.h.al) { case AL_FINDNEXT: glob_reqdrv = glob_sdaptr->sdb.drv_lett & 0x1F; break; case AL_SETATTR: case AL_GETATTR: case AL_DELETE: case AL_OPEN: case AL_CREATE: case AL_SPOPNFIL: case AL_MKDIR: case AL_RMDIR: case AL_CHDIR: case AL_RENAME: /* check sda.fn1 for drive */ glob_reqdrv = DRIVETONUM(glob_sdaptr->fn1[0]); break; default: /* otherwise check out the CDS (at ES:DI) */ { struct cdsstruct far *cds = MK_FP(r.w.es, r.w.di); glob_reqdrv = DRIVETONUM(cds->current_path[0]); #if DEBUGLEVEL > 0 /* DEBUG output (ORANGE) */ dbg_VGA[dbg_startoffset + dbg_xpos++] = 0x6e00 | ('A' + glob_reqdrv); dbg_VGA[dbg_startoffset + dbg_xpos++] = 0x6e00 | ':'; #endif } break; } } /* validate drive */ if ((glob_reqdrv > 25) || (glob_data.ldrv[glob_reqdrv] == 0xff)) { goto CHAINTOPREVHANDLER; } /* This should not be necessary. DOS usually generates an FCB-style name in * the appropriate SDA area. However, in the case of user input such as * 'CD ..' or 'DIR ..' it leaves the fcb area all spaces, hence the need to * normalize the fcb area every time. */ if (r.h.al != AL_DISKSPACE) { unsigned short i; unsigned char far *path = glob_sdaptr->fn1; /* fast forward 'path' to first character of the filename */ for (i = 0;; i++) { if (glob_sdaptr->fn1[i] == '\\') path = glob_sdaptr->fn1 + i + 1; if (glob_sdaptr->fn1[i] == 0) break; } /* clear out fcb_fn1 by filling it with spaces */ for (i = 0; i < 11; i++) glob_sdaptr->fcb_fn1[i] = ' '; /* copy 'path' into fcb_name using the fcb syntax ("FILE TXT") */ for (i = 0; *path != 0; path++) { if (*path == '.') { i = 8; } else { glob_sdaptr->fcb_fn1[i++] = *path; } } } /* copy interrupt registers into glob_intregs so the int handler can access them without using any stack */ copybytes(&glob_intregs, &r, sizeof(union INTPACK)); /* set stack to my custom memory */ _asm { cli /* make sure to disable interrupts, so nobody gets in the way while I'm fiddling with the stack */ mov glob_oldstack_seg, SS mov glob_oldstack_off, SP /* set SS to DS */ mov ax, ds mov ss, ax /* set SP to the end of the new stack (-2) */ mov sp, offset newstack + NEWSTACKSZ - 2 sti } /* call the actual INT 2F processing function */ process2f(); /* switch stack back */ _asm { cli mov SS, glob_oldstack_seg mov SP, glob_oldstack_off sti } /* copy all registers back so watcom will set them as required 'for real' */ copybytes(&r, &glob_intregs, sizeof(union INTPACK)); return; /* hand control to the previous INT 2F handler */ CHAINTOPREVHANDLER: _mvchain_intr(MK_FP(glob_data.prev_2f_handler_seg, glob_data.prev_2f_handler_off)); } /*********************** HERE ENDS THE RESIDENT PART ***********************/
davidebreso/etherdfs-client
src/genmsg.c
<filename>src/genmsg.c /* * This file is part of the EtherDFS project. * http://etherdfs.sourceforge.net * * Copyright (C) 2017 <NAME>, 2021 <NAME> * * genmsg generates C files that contain assembly for outputting to screen * every string that etherdfs might need to output. * * The assembly part is based on this model: * * push ds ; save all to-be-modified registers on the stack * push dx * push ax * call getip ; skip the binary content below (it's my string!) * S000 db 84,104,101,32,114,101,113,117,101,115,116,101,100,32,100,114 * S001 db 105,118,101,32,108,101,116,116,101,114,32,105,115,32,97,'$' * getip: * pop dx ; "read" the address following the CALL from the stack * push cs ; load DS with the value of CS (that's where my data is) * pop ds * mov ah,9h ; set AH=9 (DOS function "print string") * int 21h * pop ax ; restore registers to their previous values * pop dx * pop ds */ #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include "version.h" void genmsg(char *fname, char *msg) { unsigned short i; FILE *fd; fd = fopen(fname, "wb"); fprintf(fd, "/* %s: THIS FILE IS AUTO-GENERATED BY GENMSG.C -- DO NOT MODIFY! */\r\n", fname); fprintf(fd, "_asm {\r\n"); fprintf(fd, " push ds\r\n"); fprintf(fd, " push dx\r\n"); fprintf(fd, " push ax\r\n"); fprintf(fd, " call getip"); /* */ for (i = 0; msg[i] != 0; i++) { if ((i & 15) == 0) { fprintf(fd, "\r\n S%03X db ", i >> 4); } else { fprintf(fd, ","); } fprintf(fd, "%u", msg[i]); } fprintf(fd, ",'$'\r\n"); /* close definition */ fprintf(fd, " getip:\r\n"); fprintf(fd, " pop dx\r\n"); fprintf(fd, " push cs\r\n"); fprintf(fd, " pop ds\r\n"); fprintf(fd, " mov ah,9h\r\n"); fprintf(fd, " int 21h\r\n"); fprintf(fd, " pop ax\r\n"); fprintf(fd, " pop dx\r\n"); fprintf(fd, " pop ds\r\n"); fprintf(fd, "};\r\n"); fclose(fd); } int main(void) { struct stat st = {0}; if (stat("msg", &st) == -1) { mkdir("msg", 0755); } genmsg("msg/help.c", "EtherDFS v" PVER "\r\n" " Copyright (C) " PDATE " <NAME>\r\n" " Copyright (C) " MODATE " <NAME>\r\n" " Copyright (C) " DBDATE " <NAME>\r\n" "A network drive for DOS, running over raw ethernet\r\n" "\r\n" "Usage: etherdfs SRVMAC rdrv-ldrv [rdrv2-ldrv2 ...] [options]\r\n" " etherdfs /u\r\n" "\r\n" "Options:\r\n" " /p=XX use packet driver at interrupt XX (autodetect otherwise)\r\n" " /n disable EtherDFS checksums\r\n" " /q quiet mode (print nothing if loaded/unloaded successfully)\r\n" " /h install EtherDFS in upper memory\r\n" " /u unload EtherDFS from memory\r\n" "\r\n" "Use '::' as SRVMAC for server auto-discovery.\r\n" "\r\n" "Examples: etherdfs 6d:4f:4a:4d:49:52 C-F /q\r\n" " etherdfs :: C-X D-Y E-Z /p=6F\r\n" ); genmsg("msg/unsupdos.c", "Unsupported DOS version! EtherDFS requires MS-DOS 5+.\r\n"); genmsg("msg/noredir.c", "Redirector installation has been forbidden either by DOS or another process.\r\n"); genmsg("msg/alrload.c", "EtherDFS is already installed and cannot be loaded twice.\r\n"); genmsg("msg/notload.c", "EtherDFS is not loaded, so it cannot be unloaded.\r\n"); genmsg("msg/tsrcomfa.c", "Communication with the TSR failed.\r\n"); genmsg("msg/nomultpx.c", "Failed to find an available INT 2F multiplex id.\r\nYou may have loaded too many TSRs already.\r\n"); genmsg("msg/othertsr.c", "EtherDFS cannot be unloaded because another TSR hooked its interrupt handler.\r\n"); genmsg("msg/unloaded.c", "EtherDFS unloaded successfully.\r\n"); genmsg("msg/mapfail.c", "Unable to activate the local drive mapping. You are either using an\r\n" "unsupported operating system, or your LASTDRIVE directive does not permit\r\n" "to define the requested drive letter (try LASTDRIVE=Z in your CONFIG.SYS).\r\n" ); genmsg("msg/drvactiv.c", "The requested local drive letter is already in use. Please choose another\r\n" "drive letter.\r\n" ); genmsg("msg/memfail.c", "Upper memory alloc error, loading TSR in conventional memory.\r\n"); genmsg("msg/relfail.c", "Relocation to upper memory failed.\r\n"); genmsg("msg/pktdfail.c", "Packet driver initialization failed.\r\n"); genmsg("msg/nosrvfnd.c", "No EtherSRV server found on the LAN (not for requested drive at least).\r\n"); genmsg("msg/instlled.c", "EtherDFS v" PVER " installed (local MAC "); genmsg("msg/pktdrvat.c", ", pktdrvr at INT "); return(0); }
ppiecuch/gd_imagetools
register_types.h
void register_gd_imagetools_types(); void unregister_gd_imagetools_types();
ppiecuch/gd_imagetools
classes/image_blender.h
<reponame>ppiecuch/gd_imagetools #ifndef GODOT_IMAGE_BLENDER_H #define GODOT_IMAGE_BLENDER_H #include "core/image.h" class ImageBlender : public Reference { GDCLASS(ImageBlender, Reference); protected: static void _bind_methods(); public: enum BlendEquation { FUNC_ADD, FUNC_SUBTRACT, FUNC_REVERSE_SUBTRACT, FUNC_MIN, FUNC_MAX }; enum BlendFactor { FACTOR_ZERO, FACTOR_ONE, FACTOR_SRC_COLOR, FACTOR_ONE_MINUS_SRC_COLOR, FACTOR_DST_COLOR, FACTOR_ONE_MINUS_DST_COLOR, FACTOR_SRC_ALPHA, FACTOR_ONE_MINUS_SRC_ALPHA, FACTOR_DST_ALPHA, FACTOR_ONE_MINUS_DST_ALPHA, FACTOR_DST_ALPHA_TIMES_ONE_MINUS_SRC_ALPHA }; private: BlendEquation rgb_equation = FUNC_ADD; BlendEquation alpha_equation = FUNC_ADD; BlendFactor rgb_src_factor = FACTOR_SRC_ALPHA; BlendFactor rgb_dst_factor = FACTOR_DST_ALPHA_TIMES_ONE_MINUS_SRC_ALPHA; BlendFactor alpha_src_factor = FACTOR_ONE; BlendFactor alpha_dst_factor = FACTOR_ONE_MINUS_SRC_ALPHA; Color calculate_factor(const Color &p_src, const Color &p_dst, BlendFactor p_factor) const; Color calculate_rgb_src_factor(const Color &p_src, const Color &p_dst) const { return calculate_factor(p_src, p_dst, rgb_src_factor); }; Color calculate_rgb_dst_factor(const Color &p_src, const Color &p_dst) const { return calculate_factor(p_src, p_dst, rgb_dst_factor); }; Color calculate_alpha_src_factor(const Color &p_src, const Color &p_dst) const { return calculate_factor(p_src, p_dst, alpha_src_factor); }; Color calculate_alpha_dst_factor(const Color &p_src, const Color &p_dst) const { return calculate_factor(p_src, p_dst, alpha_dst_factor); }; Color blend_colors(const Color &p_src, const Color &p_dst) const; public: void blend_rect(const Ref<Image> p_src, const Rect2 &p_src_rect, Ref<Image> p_dst, const Point2 &p_dst_pos) const; void set_rgb_equation(BlendEquation p_equation) { rgb_equation = p_equation; }; void set_alpha_equation(BlendEquation p_equation) { alpha_equation = p_equation; }; void set_rgb_src_factor(BlendFactor p_factor) { rgb_src_factor = p_factor; }; void set_rgb_dst_factor(BlendFactor p_factor) { rgb_dst_factor = p_factor; }; void set_alpha_src_factor(BlendFactor p_factor) { alpha_src_factor = p_factor; }; void set_alpha_dst_factor(BlendFactor p_factor) { alpha_dst_factor = p_factor; }; BlendEquation get_rgb_equation() const { return rgb_equation; }; BlendEquation get_alpha_equation() const { return alpha_equation; }; BlendFactor get_rgb_src_factor() const { return rgb_src_factor; }; BlendFactor get_rgb_dst_factor() const { return rgb_dst_factor; }; BlendFactor get_alpha_src_factor() const { return alpha_src_factor; }; BlendFactor get_alpha_dst_factor() const { return alpha_dst_factor; }; }; VARIANT_ENUM_CAST(ImageBlender::BlendEquation); VARIANT_ENUM_CAST(ImageBlender::BlendFactor); #endif // GODOT_IMAGE_BLENDER_H
TangZhiZhen/libva
va/va_enc_av1.h
<gh_stars>0 /* * Copyright (c) 2021 Intel Corporation. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sub license, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial portions * of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. * IN NO EVENT SHALL INTEL AND/OR ITS SUPPLIERS BE LIABLE FOR * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * \file va_enc_av1.h * \brief AV1 encoding API * * This file contains the \ref api_enc_av1 "AV1 encoding API". * */ #ifndef VA_ENC_AV1_H #define VA_ENC_AV1_H #ifdef __cplusplus extern "C" { #endif #include <stdint.h> /** * \defgroup api_enc_av1 AV1 encoding API * * This AV1 encoding API supports 8-bit/10bit 420 format only. * * @{ */ /** \brief Attribute value for VAConfigAttribEncAV1. * * This attribute decribes the supported features of an AV1 * encoder configuration. * * All of the field values in this attribute are VA_FEATURE_* values, * indicating support for the corresponding feature. * */ typedef union _VAConfigAttribValEncAV1 { struct { /** * \brief Use 128x128 superblock. * * Allows setting use_128x128_superblock in the SPS. */ uint32_t support_128x128_superblock : 2; /** * \brief Intra filter. * Allows setting enable_filter_intra in the SPS. */ uint32_t support_filter_intra : 2; /** * \brief Intra edge filter. * Allows setting enable_intra_edge_filter in the SPS. */ uint32_t support_intra_edge_filter : 2; /** * \brief Interintra compound. * Allows setting enable_interintra_compound in the SPS. */ uint32_t support_interintra_compound : 2; /** * \brief Masked compound. * Allows setting enable_masked_compound in the SPS. */ uint32_t support_masked_compound : 2; /** * \brief Warped motion. * Allows setting enable_warped_motion in the SPS. */ uint32_t support_warped_motion : 2; /** * \brief Palette mode. * Allows setting palette_mode in the PPS. */ uint32_t support_palette_mode : 2; /** * \brief Dual filter. * Allows setting enable_dual_filter in the SPS. */ uint32_t support_dual_filter : 2; /** * \brief Jnt compound. * Allows setting enable_jnt_comp in the SPS. */ uint32_t support_jnt_comp : 2; /** * \brief Refrence frame mvs. * Allows setting enable_ref_frame_mvs in the SPS. */ uint32_t support_ref_frame_mvs : 2; /** * \brief Super resolution. * Allows setting enable_superres in the SPS. */ uint32_t support_superres : 2; /** * \brief Restoration. * Allows setting enable_restoration in the SPS. */ uint32_t support_restoration : 2; /** * \brief Allow intraBC. * Allows setting allow_intrabc in the PPS. */ uint32_t support_allow_intrabc : 2; /** * \brief Cdef channel strength. * Allows setting cdef_y_strengths and cdef_uv_strengths in PPS. */ uint32_t support_cdef_channel_strength : 2; /** \brief Reserved bits for future, must be zero. */ uint32_t reserved : 4; } bits; uint32_t value; } VAConfigAttribValEncAV1; /** \brief Attribute value for VAConfigAttribEncAV1Ext1. */ typedef union _VAConfigAttribValEncAV1Ext1 { struct { /** * \brief Fields indicate which types of interpolation filter are supported. * (interpolation_filter & 0x01) == 1: eight_tap filter is supported, 0: not. * (interpolation_filter & 0x02) == 1: eight_tap_smooth filter is supported, 0: not. * (interpolation_filter & 0x04) == 1: eight_sharp filter is supported, 0: not. * (interpolation_filter & 0x08) == 1: bilinear filter is supported, 0: not. * (interpolation_filter & 0x10) == 1: switchable filter is supported, 0: not. */ uint32_t interpolation_filter : 5; /** * \brief Min segmentId block size accepted. * Application need to send seg_id_block_size in PPS equal or larger than this value. */ uint32_t min_segid_block_size_accepted : 8; /** * \brief Type of segment feature supported. * (segment_feature_support & 0x01) == 1: SEG_LVL_ALT_Q is supported, 0: not. * (segment_feature_support & 0x02) == 1: SEG_LVL_ALT_LF_Y_V is supported, 0: not. * (segment_feature_support & 0x04) == 1: SEG_LVL_ALT_LF_Y_H is supported, 0: not. * (segment_feature_support & 0x08) == 1: SEG_LVL_ALT_LF_U is supported, 0: not. * (segment_feature_support & 0x10) == 1: SEG_LVL_ALT_LF_V is supported, 0: not. * (segment_feature_support & 0x20) == 1: SEG_LVL_REF_FRAME is supported, 0: not. * (segment_feature_support & 0x40) == 1: SEG_LVL_SKIP is supported, 0: not. * (segment_feature_support & 0x80) == 1: SEG_LVL_GLOBALMV is supported, 0: not. */ uint32_t segment_feature_support : 8; /** \brief Reserved bits for future, must be zero. */ uint32_t reserved : 11; } bits; uint32_t value; } VAConfigAttribValEncAV1Ext1; /** \brief Attribute value for VAConfigAttribEncAV1Ext2. */ typedef union _VAConfigAttribValEncAV1Ext2 { struct { /** * \brief Tile size bytes minus1. * Specify the number of bytes needed to code tile size supported. * This value need to be set in frame header obu. */ uint32_t tile_size_bytes_minus1 : 2; /** * \brief Tile size bytes minus1. * Specify the fixed number of bytes needed to code syntax obu_size. */ uint32_t obu_size_bytes_minus1 : 2; /** * \brief tx_mode supported. * (tx_mode_support & 0x01) == 1: ONLY_4X4 is supported, 0: not. * (tx_mode_support & 0x02) == 1: TX_MODE_LARGEST is supported, 0: not. * (tx_mode_support & 0x04) == 1: TX_MODE_SELECT is supported, 0: not. */ uint32_t tx_mode_support : 3; /** * \brief Max tile num minus1. * Specify the max number of tile supported by driver. */ uint32_t max_tile_num_minus1 : 13; /** \brief Reserved bits for future, must be zero. */ uint32_t reserved : 12; } bits; uint32_t value; } VAConfigAttribValEncAV1Ext2; /** * \brief Packed header types specific to AV1 encoding. * * Types of packed headers generally used for AV1 encoding. * */ typedef enum { /** * \brief Packed Sequence Parameter Set (SPS). * * The corresponding packed header data buffer shall contain the * complete sequence_header_obu() syntax element. * */ VAEncPackedHeaderAV1_SPS = VAEncPackedHeaderSequence, /** * \brief Packed Picture Parameter Set (PPS). * * The corresponding packed header data buffer shall contain the * complete frame_header_obu() syntax element. * */ VAEncPackedHeaderAV1_PPS = VAEncPackedHeaderPicture, } VAEncPackedHeaderTypeAV1; /** * \brief AV1 Encoding Sequence Parameter Buffer Structure. * * This structure conveys sequence level parameters. * */ typedef struct _VAEncSequenceParameterBufferAV1 { /** \brief AV1 profile setting. * value range [0..2]. */ uint8_t seq_profile; /** \brief Level Setting of current operation point. * value range [0..23]. */ uint8_t seq_level_idx; /** \brief Tier Setting of current operation point. * value range [0..1]. */ uint8_t seq_tier; uint8_t reserved8b; /** \brief Period between intra_only frames. */ uint32_t intra_period; /** \brief Period between I/P frames. * For hierarchical structure, this is the anchor frame distance. */ uint32_t ip_period; /* \brief RC related fields. RC modes are set with VAConfigAttribRateControl. */ /* For AV1, CBR implies HRD conformance and VBR implies no HRD conformance. */ /** * \brief Initial bitrate set for this sequence in CBR or VBR modes. * * This field represents the initial bitrate value for CBR mode or * initial max bitrate value for VBR mode in this sequence. * i.e. if the encoder pipeline was created with a #VAConfigAttribRateControl * attribute set to either \ref VA_RC_CBR or \ref VA_RC_VBR. * * The bitrate can be modified later on through * #VAEncMiscParameterRateControl buffers. */ uint32_t bits_per_second; union { struct { /** \brief Still picture encoding, no inter frame referencing. */ uint32_t still_picture : 1; /** \brief Force using 128x128 or 64x64 Supper block */ uint32_t use_128x128_superblock : 1; /** \brief Corresponds to AV1 syntax element of the same name. */ uint32_t enable_filter_intra : 1; /** \brief Corresponds to AV1 syntax element of the same name. */ uint32_t enable_intra_edge_filter : 1; /** \brief Corresponds to AV1 syntax element of the same name. */ uint32_t enable_interintra_compound : 1; /** \brief Corresponds to AV1 syntax element of the same name. */ uint32_t enable_masked_compound : 1; /** \brief Corresponds to AV1 syntax element of the same name. */ uint32_t enable_warped_motion : 1; /** \brief Corresponds to AV1 syntax element of the same name. */ uint32_t enable_dual_filter : 1; /** \brief Corresponds to AV1 syntax element of the same name. */ uint32_t enable_order_hint : 1; /** \brief Corresponds to AV1 syntax element of the same name. */ uint32_t enable_jnt_comp : 1; /** \brief Corresponds to AV1 syntax element of the same name. */ uint32_t enable_ref_frame_mvs : 1; /** \brief Corresponds to AV1 syntax element of the same name. */ uint32_t enable_superres : 1; /** \brief Corresponds to AV1 syntax element of the same name. */ uint32_t enable_cdef : 1; /** \brief Corresponds to AV1 syntax element of the same name. */ uint32_t enable_restoration : 1; /** \brief Sepcify number of bits for every channel(Y, U or V). */ uint32_t bit_depth_minus8 : 3; /** \brief Corresponds to AV1 syntax element of the same name. */ uint32_t subsampling_x : 1; /** \brief Corresponds to AV1 syntax element of the same name. */ uint32_t subsampling_y : 1; /** \brief Reserved bytes for future use, must be zero. */ uint32_t reserved_bits : 13; } bits; uint32_t value; } seq_fields; /** \brief Corresponds to AV1 syntax element of the same name. * value range [0..7]. */ uint8_t order_hint_bits_minus_1; /** \brief Reserved bytes for future use, must be zero */ uint32_t va_reserved[VA_PADDING_HIGH]; } VAEncSequenceParameterBufferAV1; #define VA_AV1_MAX_SEGMENTS 8 #define VA_AV1_SEG_LVL_MAX 8 /** * \brief Segment parameters */ typedef struct _VAEncSegParamAV1 { union { struct { /** \brief Indicates if segmentation is enabled in the current frame. * If disabled, all the below parameters in the structure should * be set to 0, and ignored by driver. */ uint8_t segmentation_enabled : 1; /** * When segmentation_enabled equals 1 and segment_number > 0, * this parameter equals 1 indicates the segmentation map may * come from application, and that "Segment map data buffer" * should be provided with populated segment_id. If equals 0, * segmentation map should be inherited from a reference frame * (specified by \c primary_ref_frame). When segmentation_enabled or * segment_number equals 0, this parameter should be set to 0 * and ignored by driver. */ uint8_t segmentation_update_map : 1; /** * When segmentation_update_map equals 1, this parameter equaling 1 * indicates segment id per block will be determined either from * reference frame or from app. Equaling 0 means segment id per block * will come from app. When segmentation_temporal_update equals 0, * this parameter should be set to 0 and ignored by driver. */ uint8_t segmentation_temporal_update : 1; /** \brief Reserved bytes for future use, must be zero. */ uint8_t reserved : 5; } bits; uint8_t value; } seg_flags; /** * If segmentation_enabled equals 1, this parameter indicates * the number of segments conveyed through VAAPI. In this case, * if segment_number equals 0, it will force the driver to determine * how many segments would be created as well as the segmentation map * to be generated. Also the driver shall write the segmentation_params() * syntax in the uncompressed header at \c bit_offset_segmentation (back-annotation). * In application, the rest parameters in this structure should be all * set to 0 and ignored by driver. And app should NOT send the * "Segment map data buffer". In packed uncompressed header * bitstream, app should write syntax element segmentation_enabled * as 0 and segmentation_params() should be only 1-bit-long. * If segment_number > 0, and segmentation_update_map = 1, app should provide * the "Segment map data buffer" and populate the rest of the * current data structure. And that underline encoder would honor * the segmentation parameters feature_data[0..segment_number-1][] * and feature_mask[0..segment_number-1], etc. * Value range [0..8]. */ uint8_t segment_number; /** \brief segment parameters. * feature_data[][] is equivalent to variable FeatureData[][] in spec, * which is after clip3() operation. * Clip3(x, y, z) = (z<x)? x : ((z > y)? y : z); * The limit is defined in Segmentation_Feature_Max[ SEG_LVL_MAX ] = { * 255, MAX_LOOP_FILTER, MAX_LOOP_FILTER, MAX_LOOP_FILTER, * MAX_LOOP_FILTER, 7, 0, 0 } */ int16_t feature_data[VA_AV1_MAX_SEGMENTS][VA_AV1_SEG_LVL_MAX]; /** \brief Bit field to indicate each feature is enabled or not per * segment_id. Each bit is the feature_id. */ uint8_t feature_mask[VA_AV1_MAX_SEGMENTS]; /** \brief Reserved bytes for future use, must be zero. */ uint32_t va_reserved[VA_PADDING_LOW]; } VAEncSegParamAV1; /** * \brief Segment map data buffer. * * This buffer is optional depending on the value of av1_segments.segmentation_enabled. * If av1_segments.segmentation_enabled in the picture parameters equals 1, * and RateControlMethod is not CQP and this surface is not provided by App, * the encoder will determine the per block segmentation map. In this case, * App should not provide the segmentation parameter data structure * in frame header as well. If av1_segments.segmentation_enabled equals 1 * and the segmentation map buffer is provided, app should embed the * segmentation info in frame header, populate the VAEncSegParamAV1 structure with * #VAEncMacroblockMapBufferType and the driver as well as the underline encoder * should honor what is given by the app. */ typedef struct _VAEncSegMapBufferAV1 { /** \brief Segment map data size. */ uint32_t segmentMapDataSize; /** * \brief Segment map. * Size of this map is indicated by \ref segmentMapDataSize and each element * in this map contains the segment id of a particular block. * The element is indexed by raster scan order. * The value of each entry should be in the range [0..7], inclusive. */ uint8_t *pSegmentMap; } VAEncSegMapBufferAV1; typedef enum { /** \brief Identity transformation, 0-parameter. */ VAAV1EncTransformationIdentity = 0, /** \brief Translational motion, 2-parameter. */ VAAV1EncTransformationTranslation = 1, /** \brief Simplified affine with rotation + zoom only, 4-parameter. */ VAAV1EncTransformationRotzoom = 2, /** \brief Affine, 6-parameter. */ VAAV1EncTransformationAffine = 3, /** \brief Transformation count. */ VAAV1EncTransformationCount } VAEncTransformationTypeAV1; typedef struct _VAEncWarpedMotionParamsAV1{ /** \brief Specify the type of warped motion. */ VAEncTransformationTypeAV1 wmtype; /** \brief Specify warp motion parameters. * wm.wmmat[] corresponds to gm_params[][] in spec. * Details in AV1 spec section 5.9.24 or refer to libaom code * https://aomedia.googlesource.com/aom/+/refs/heads/master/av1/decoder/decodeframe.c. */ int32_t wmmat[8]; /** \brief Valid or invalid on affine set. */ uint8_t invalid; /** \brief Reserved bytes for future use, must be zero. */ uint32_t va_reserved[VA_PADDING_LOW]; } VAEncWarpedMotionParamsAV1; /** * \brief Reference frame control. * * Suggest which frame to be used as reference along with preferred search order. * * search_idx#: index into ref_frame_idx[] to indicate that frame will be included * in the reference list if value in range [1..7]. Invalid when value is 0. * The order of the search_idx# indicates the preferred search order. * */ typedef union { struct { /** * \brief Value used as index into ref_frame_idx[] to indicate that frame * will be included in the reference list. * valid value range: [1..7], invalid when value is 0. */ uint32_t search_idx0 : 3; /** * \brief Value used as index into ref_frame_idx[] to indicate that frame * will be included in the reference list. * valid value range: [1..7], invalid when value is 0. */ uint32_t search_idx1 : 3; /** * \brief Value used as index into ref_frame_idx[] to indicate that frame * will be included in the reference list. * valid value range: [1..7], invalid when value is 0. */ uint32_t search_idx2 : 3; /** * \brief Value used as index into ref_frame_idx[] to indicate that frame * will be included in the reference list. * valid value range: [1..7], invalid when value is 0. */ uint32_t search_idx3 : 3; /** * \brief Value used as index into ref_frame_idx[] to indicate that frame * will be included in the reference list. * valid value range: [1..7], invalid when value is 0. */ uint32_t search_idx4 : 3; /** * \brief Value used as index into ref_frame_idx[] to indicate that frame * will be included in the reference list. * valid value range: [1..7], invalid when value is 0. */ uint32_t search_idx5 : 3; /** * \brief Value used as index into ref_frame_idx[] to indicate that frame * will be included in the reference list. * valid value range: [1..7], invalid when value is 0. */ uint32_t search_idx6 : 3; /** \brief Reserved bytes for future use, must be zero. */ uint32_t Reserved : 11; } fields; uint32_t value; } VARefFrameCtrlAV1; /** * \brief AV1 Encoding Picture Parameter Buffer Structure. * * This structure conveys picture level parameters. * */ typedef struct _VAEncPictureParameterBufferAV1 { /** \brief AV1 encoder may support SupRes and dynamic scaling function. * For SupRes, underline encoder is responsible to do downscaling. * For dynamic scaling, app should provide the scaled raw source. */ /** \brief Raw source frame width in pixels. */ uint16_t frame_width_minus_1; /** \brief Raw source frame height in pixels. */ uint16_t frame_height_minus_1; /** \brief Surface to store reconstructed frame, not used for enc only case. */ VASurfaceID reconstructed_frame; /** \brief Buffer to store coded data. */ VABufferID coded_buf; /** \brief Reference frame buffers. * Each entry of the array specifies the surface index of the picture * that is referred by current picture or will be referred by any future * picture. The valid entries take value from 0 to 127, inclusive. * Non-valid entries, those do not point to pictures which are referred * by current picture or future pictures, should take value 0xFF. * Other values are not allowed. * * Application should update this array based on the refreshing * information expected. */ VASurfaceID reference_frames[8]; /** \brief Reference index list. * Contains a list of indices into refernce_frames[]. * Indice with refernce frames range: [LAST_FRAME - LAST_FRAME, * LAST2_FRAME - LAST_FRAME, ..., ALTREF2_FRAME - LAST_FRAME]. * #define LAST_FRAME 1 * #define LAST2_FRAME 2 * #define LAST3_FRAME 3 * #define GOLDEN_FRAME 4 * #define BWDREF_FRAME 5 * #define ALTREF_FRAME 6 * #define ALTREF2_FRAME 7 * value range [0..7]. */ uint8_t ref_frame_idx[7]; uint8_t reserved8bits0; /** \brief primary reference frame. * Index into reference_frames[] * segment id map, context table, etc. come from the reference * frame pointed by this index. * value range [0..7]. */ uint8_t primary_ref_frame; /** \brief Corresponds to AV1 syntax element of the same name. */ uint8_t order_hint; /** \brief Corresponds to AV1 syntax element of the same name. */ uint8_t refresh_frame_flags; uint8_t reserved8bits1; /** \brief Suggest which frames to be used as references. * see struct #VARefFrameCtrl for details. */ VARefFrameCtrlAV1 ref_frame_ctrl_l0; VARefFrameCtrlAV1 ref_frame_ctrl_l1; union { struct { /** \brief frame type. * 0: key_frame. * 1: inter_frame. * 2: intra_only frame. * 3: switch_frame (app needs to set error_resilient_mode = 1, * refresh_frame_flags, etc approperately.). */ uint32_t frame_type : 2; /** \brief Corresponds to AV1 syntax element of the same name. */ uint32_t error_resilient_mode : 1; /** \brief Corresponds to AV1 syntax element of the same name. */ uint32_t disable_cdf_update : 1; /** \brief Corresponds to AV1 syntax element of the same name. */ uint32_t use_superres : 1; /** \brief Corresponds to AV1 syntax element of the same name. */ uint32_t allow_high_precision_mv : 1; /** \brief Corresponds to AV1 syntax element of the same name. */ uint32_t use_ref_frame_mvs : 1; /** \brief Corresponds to AV1 syntax element of the same name. */ uint32_t disable_frame_end_update_cdf : 1; /** \brief Corresponds to AV1 syntax element of the same name. */ uint32_t reduced_tx_set : 1; /** \brief For single tile group, app may choose to use one frame obu * to replace one frame header obu + one tile group obu. * Invalid if num_tile_groups_minus1 > 0. */ uint32_t enable_frame_obu : 1; /** \brief Indicate the current frame will be used as a long term reference. */ uint32_t long_term_reference : 1; /** \brief If the encoded frame will not be referred by other frames, * its recon may not be generated in order to save memory bandwidth. */ uint32_t disable_frame_recon : 1; /** \brief Corresponds to AV1 syntax element of the same name. */ uint32_t allow_intrabc : 1; /** \brief Equal to 1 indicates that intra blocks may use palette encoding. * Otherwise disable palette encoding. */ uint32_t palette_mode_enable : 1; /** \brief Reserved bytes for future use, must be zero. */ uint32_t reserved : 18; } bits; uint32_t value; } picture_flags; /** \brief Block size for each Segment ID in Segment Map. * 0: 16x16 block size, default value; * 1: 32x32 block size; * 2: 64x64 block size; * 3: 8x8 block size. */ uint8_t seg_id_block_size; /** \brief Number of tile groups minus 1. * value range [0..255]. */ uint8_t num_tile_groups_minus1; /** \brief Temporal id of the frame.*/ uint8_t temporal_id; /** \brief Deblock filter parameters. * value range [0..63]. */ uint8_t filter_level[2]; uint8_t filter_level_u; uint8_t filter_level_v; union { struct { /** \brief Sharpness level for deblock filter. * value range [0..7]. */ uint8_t sharpness_level : 3; uint8_t mode_ref_delta_enabled : 1; uint8_t mode_ref_delta_update : 1; /** \brief Reserved bytes for future use, must be zero. */ uint8_t reserved : 3; } bits; uint8_t value; } loop_filter_flags; /** \brief Super resolution scale denominator. * value range [9..16]. */ uint8_t superres_scale_denominator; /** \brief Corresponds to AV1 syntax element of the same name. */ uint8_t interpolation_filter; /** \brief Loop filter ref deltas. * value range [-63..63]. */ int8_t ref_deltas[8]; /** \brief Loop filter mode deltas. * value range [-63..63]. */ int8_t mode_deltas[2]; /** \brief Quantization params. */ uint8_t base_qindex; int8_t y_dc_delta_q; int8_t u_dc_delta_q; int8_t u_ac_delta_q; int8_t v_dc_delta_q; int8_t v_ac_delta_q; /** \brief Min value for base q index for BRC. * value range [1..255]. */ uint8_t min_base_qindex; /** \brief Max value for base q index for BRC. * value range [1..255]. */ uint8_t max_base_qindex; /** \brief Quantization matrix. */ union { struct { /** \brief Corresponds to AV1 syntax element of the same name. */ uint16_t using_qmatrix : 1; /** \brief Following parameters only valid when using_qmatrix == 1. */ uint16_t qm_y : 4; /** \brief Corresponds to AV1 syntax element of the same name. */ uint16_t qm_u : 4; /** \brief Corresponds to AV1 syntax element of the same name. */ uint16_t qm_v : 4; /** \brief Reserved bytes for future use, must be zero. */ uint16_t reserved : 3; } bits; uint16_t value; } qmatrix_flags; uint16_t reserved16bits1; union { struct { /** \brief Specify whether quantizer index delta values are present. * value range [0..1]. */ uint32_t delta_q_present : 1; /** \brief Corresponds to AV1 syntax element of the same name. * value range [0..3]. */ uint32_t delta_q_res : 2; /** \brief Specify whether loop filter delta values are present. * value range [0..1]. */ uint32_t delta_lf_present : 1; /** \brief Corresponds to AV1 syntax element of the same name. * value range [0..3]. */ uint32_t delta_lf_res : 2; /** \brief Corresponds to AV1 syntax element of the same name. * value range [0..1]. */ uint32_t delta_lf_multi : 1; /** \brief Corresponds to AV1 syntax element of the same name. * 0: ONLY_4X4; * 1: TX_MODE_LARGEST; * 2: TX_MODE_SELECT; * 3: Invalid. */ uint32_t tx_mode : 2; /** \brief Indicates whether to use single or compound reference prediction. * 0: SINGLE_REFERENCE; * 1: COMPOUND_REFERENCE; * 2: REFERENCE_MODE_SELECT. * 3: Invalid. * * Value 2 means driver make decision to use single reference or compound reference. */ uint32_t reference_mode : 2; /** \brief Corresponds to AV1 syntax element of the same name. * value range [0..1]. */ uint32_t skip_mode_present : 1; /** \brief Reserved bytes for future use, must be zero. */ uint32_t reserved : 20; } bits; uint32_t value; } mode_control_flags; /** \brief Segmentation parameters. */ VAEncSegParamAV1 segments; /** \brief Number of tile columns. */ uint8_t tile_cols; /** \brief Number of tile rows. */ uint8_t tile_rows; uint16_t reserved16bits2; /** \brief The last tile column or row size needs to be derived. */ uint16_t width_in_sbs_minus_1[63]; uint16_t height_in_sbs_minus_1[63]; /** \brief specify which tile to use for the CDF update. * value range [0..127]*/ uint16_t context_update_tile_id; /** \brief Corresponds to AV1 syntax element of the same name. * value range [0..3]. */ uint8_t cdef_damping_minus_3; /** \brief Corresponds to AV1 syntax element of the same name. * value range [0..3]. */ uint8_t cdef_bits; /** \brief CDEF Y strengths. * value range [0..63]*/ uint8_t cdef_y_strengths[8]; /** \brief CDEF UV strengths. * value range [0..63]*/ uint8_t cdef_uv_strengths[8]; union { struct { /** \brief Restoration type for Y frame. * value range [0..3]. */ uint16_t yframe_restoration_type : 2; /** \brief Restoration type for Cb frame. * value range [0..3]. */ uint16_t cbframe_restoration_type : 2; /** \brief Restoration type for Cr frame. * value range [0..3]. */ uint16_t crframe_restoration_type : 2; /** \brief Corresponds to AV1 syntax element of the same name. * value range [0..2]. */ uint16_t lr_unit_shift : 2; /** \brief Corresponds to AV1 syntax element of the same name. * value range [0..1]. */ uint16_t lr_uv_shift : 1; /** \brief Reserved bytes for future use, must be zero. */ uint16_t reserved : 7; } bits; uint16_t value; } loop_restoration_flags; /** \brief Global motion. */ VAEncWarpedMotionParamsAV1 wm[7]; /** * Offset in bits for syntax base_q_idx in packed frame header bit stream * from the start of the packed header data. * In BRC mode, this parameter should be set and driver will update base_q_idx in * uncompressed header according to this offset. * In CQP mode, this parameter should be set to 0 and ignored by driver. */ uint32_t bit_offset_qindex; /** * Offset in bits for syntax segmentation_enabled of frame header OBU * in packed frame header bit stream from the start of the packed header data. * Valid only in auto segmentation mode. Other than that, this parameter * should be set to 0 and ignored by driver. */ uint32_t bit_offset_segmentation; /** * Offset in bits for syntax loop_filter_params() in packed frame * header bit stream from the start of the packed header data. * In BRC mode, this parameter should be set and driver will update filter params * in packed frame header according to this offset. * In CQP mode, this parameter should be set to 0 and ignored by driver. */ uint32_t bit_offset_loopfilter_params; /** * In BRC mode, underline encoder should generate the approperiate * CDEF values and write back into uncompressed header. And app * should provide default CDEF values in packed header. This parameter * should point to the starting bit of cdef_params() syntax structure * in packed header. * In CQP mode, this parameter should be set to 0 and ignored by driver. */ uint32_t bit_offset_cdef_params; /** * In BRC mode, this parameter indicates the actual bit usage of * cdef_params() syntax structure in packed uncompressed header. * In CQP mode, this parameter should be set to 0 and ignored by driver. */ uint32_t size_in_bits_cdef_params; /** * Offset in bytes for syntax obu_size of frame header OBU in packed * frame header bit stream from the start of the packed header. The frame * header OBU size depends on the encoded tile sizes. It applies to both * Frame Header OBU and Frame OBU if obu_size needs to be updated by * underline encoder. Otherwise, app can set it to 0 and ignored by driver. * * In BRC mode, obu_size needs to be updated and this parameter should be set. * In CQP mode, this parameter should be set to 0 and ignored by driver. */ uint32_t byte_offset_frame_hdr_obu_size; /** * Frame header OBU bit stream size in bits. The frame header obu packed bit * stream contains an obu header, a 4-byte long obu_size field, frame_header_obu() * syntax chain, and a trailing bit if not inside a frame obu. If \c enable_frame_obu == 1, * the value should include and up to the last bit of frame_header_obu() and * excluding the bits generated by byte_alignment(). If \c enable_frame_obu == 0, * the value should include and up to the trailing bit at the end of the frame * header obu. The size will be used by encoder to calculate the final frame * header size after bit shifting due to auto segmentation. * In CQP mode, this parameter should be set to 0 and ignored by driver. */ uint32_t size_in_bits_frame_hdr_obu; /** \brief Tile Group OBU header */ union { struct { /** \brief Corresponds to AV1 syntax element of the same name. * value range [0..1]. */ uint8_t obu_extension_flag : 1; /** \brief Corresponds to AV1 syntax element of the same name. * value range [0..1]. */ uint8_t obu_has_size_field : 1; /** \brief Corresponds to AV1 syntax element of the same name. * value range [0..7]. */ uint8_t temporal_id : 3; /** \brief Corresponds to AV1 syntax element of the same name. * value range [0..2]. */ uint8_t spatial_id : 2; /** \brief Reserved bytes for future use, must be zero. */ uint8_t reserved : 1; } bits; uint8_t value; } tile_group_obu_hdr_info; /** \brief The number of frames skipped prior to the current frame. * It includes only the skipped frames that were not counted before. * App may generate the "show_existing_frame" short frame header OBUs * and send to driver with the next frame. Default value 0. */ uint8_t number_skip_frames; uint16_t reserved16bits3; /** \brief Indicates the application forced frame size change in bytes. * When the value is positive, the frame size is reduced. Otherwise, the frame * size increases. The parameter can be used when application skips frames with * setting of NumSkipFrames. And application can also use it for other scenarios * such as inserting "show_existing_frame" at very end of the sequence. */ int32_t skip_frames_reduced_size; /** \brief Reserved bytes for future use, must be zero. */ uint32_t va_reserved[VA_PADDING_HIGH]; } VAEncPictureParameterBufferAV1; /** * \brief Tile Group Buffer. */ typedef struct _VAEncTileGroupBufferAV1 { /** \brief Tile group start location. * The position of the first tile in current tile group * in raster scan order across the frame. * value range [0..127]. */ uint8_t tg_start; /** \brief Tile group end location. * The position of the last tile in current tile group * in raster scan order across the frame. * value range [0..127]. */ uint8_t tg_end; /** \brief Reserved bytes for future use, must be zero. */ uint32_t va_reserved[VA_PADDING_LOW]; } VAEncTileGroupBufferAV1; /**@}*/ #ifdef __cplusplus } #endif #endif /* VA_ENC_AV1_H */
xiaohaichun/paddle-mobile
src/operators/kernel/central-arm-func/batchnorm_arm_func.h
<gh_stars>1-10 /* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifdef BATCHNORM_OP #pragma once #include <cmath> #include "operators/op_param.h" namespace paddle_mobile { namespace operators { template <typename P> void BatchnormCompute(const BatchNormParam<CPU> &param) { const Tensor *input_x = param.InputX(); auto input_x_ptr = input_x->data<float>(); const auto &x_dims = input_x->dims(); const int N = x_dims[0]; const int C = x_dims[1]; const int H = x_dims[2]; const int W = x_dims[3]; const int stride0 = C * H * W; const int stride1 = H * W; const int stride2 = W; Tensor *out = param.OutputY(); auto out_ptr = out->mutable_data<float>(); const float epsilon = param.Epsilon(); const Tensor *mean = param.InputMean(); const Tensor *variance = param.InputVariance(); const Tensor *scale = param.InputScale(); const Tensor *bias = param.InputBias(); auto mean_ptr = mean->data<float>(); auto variance_ptr = variance->data<float>(); auto scale_ptr = scale->data<float>(); auto bias_ptr = bias->data<float>(); // Tensor inv_std; // auto inv_std_ptr = inv_std.mutable_data<float>(make_ddim({C})); PADDLE_MOBILE_ENFORCE(C == variance->numel(), "C must equal to variance.numel()"); int HXW = H * W; #if __ARM_NEON #if __aarch64__ float *inv_std_ptr = new float[C]; for (int i = 0; i < C; i++) { inv_std_ptr[i] = 1 / static_cast<float>(pow((variance_ptr[i] + epsilon), 0.5)); } Tensor new_scale; auto new_scale_ptr = new_scale.mutable_data<float>(framework::make_ddim({C})); Tensor new_bias; auto new_bias_ptr = new_bias.mutable_data<float>(framework::make_ddim({C})); /// ((x - est_mean) * (inv_var) * scale + bias equal to /// (x * inv_var * scale) + (bias - est_mean * inv_var * scale) for (int i = 0; i < C; i++) { new_scale_ptr[i] = inv_std_ptr[i] * scale_ptr[i]; new_bias_ptr[i] = bias_ptr[i] - mean_ptr[i] * inv_std_ptr[i] * scale_ptr[i]; { for (int n = 0; n < N; n++) { for (int h = 0; h < H; h++) { int tmp_index = n * stride0 + i * stride1 + h * stride2; for (int w = 0; w < W; w++) { int index = tmp_index + w; out_ptr[index] = input_x_ptr[index] * new_scale_ptr[i] + new_bias_ptr[i]; } } } } } delete[] inv_std_ptr; #else if (HXW > 32) { int NXC = N * C; float *inv_std_ptr = new float[NXC * 4]; float *volatile new_scale_ptr = new float[NXC * 4]; float *volatile new_bias_ptr = new float[NXC * 4]; /// std = (var + epsilon).sqrt(); /// inv_std = 1 / std; for (int i = 0; i < C * 4; i += 4) { int index = i / 4; inv_std_ptr[i] = 1 / static_cast<float>(pow((variance_ptr[index] + epsilon), 0.5)); inv_std_ptr[i + 1] = inv_std_ptr[i]; inv_std_ptr[i + 2] = inv_std_ptr[i]; inv_std_ptr[i + 3] = inv_std_ptr[i]; new_scale_ptr[i] = inv_std_ptr[i] * scale_ptr[index]; new_scale_ptr[i + 1] = new_scale_ptr[i]; new_scale_ptr[i + 2] = new_scale_ptr[i]; new_scale_ptr[i + 3] = new_scale_ptr[i]; new_bias_ptr[i] = bias_ptr[index] - mean_ptr[index] * inv_std_ptr[i] * scale_ptr[index]; new_bias_ptr[i + 1] = new_bias_ptr[i]; new_bias_ptr[i + 2] = new_bias_ptr[i]; new_bias_ptr[i + 3] = new_bias_ptr[i]; } for (int j = C * 4; j < NXC * 4; ++j) { new_scale_ptr[j] = new_scale_ptr[j - C * 4]; new_bias_ptr[j] = new_bias_ptr[j - C * 4]; } asm volatile( "subs %[N], %[N], #1 \n\t" "blt end_n_%= \n\t" "loop_n_%=: \n\t" "subs %[C], %[C], #1 \n\t" "blt end_c_%= \n\t" "loop_c_%=: \n\t" "vld1.32 {q9}, [%[new_scale_ptr]]! \n\t" "vld1.32 {q10}, [%[new_bias_ptr]]! \n\t" "mov r6, %[HXW] \n\t" "subs r6, r6, #32 \n\t" "blt end_hw_%= \n\t" "loop_hw_%=: \n\t" "vld1.32 {q1, q2}, [%[input_x_ptr]]! \n\t" "vld1.32 {q3, q4}, [%[input_x_ptr]]! \n\t" "vld1.32 {q5, q6}, [%[input_x_ptr]]! \n\t" "vld1.32 {q7, q8}, [%[input_x_ptr]]! \n\t" "vmul.f32 q1, q1, q9 \n\t" "vmul.f32 q2, q2, q9 \n\t" "vmul.f32 q3, q3, q9 \n\t" "vmul.f32 q4, q4, q9 \n\t" "vmul.f32 q5, q5, q9 \n\t" "vmul.f32 q6, q6, q9 \n\t" "vmul.f32 q7, q7, q9 \n\t" "vmul.f32 q8, q8, q9 \n\t" "vadd.f32 q1, q1, q10 \n\t" "vadd.f32 q2, q2, q10 \n\t" "vadd.f32 q3, q3, q10 \n\t" "vadd.f32 q4, q4, q10 \n\t" "vadd.f32 q5, q5, q10 \n\t" "vadd.f32 q6, q6, q10 \n\t" "vadd.f32 q7, q7, q10 \n\t" "vadd.f32 q8, q8, q10 \n\t" "vst1.32 {q1, q2}, [%[out_ptr]]! \n\t" "vst1.32 {q3, q4}, [%[out_ptr]]! \n\t" "vst1.32 {q5, q6}, [%[out_ptr]]! \n\t" "vst1.32 {q7, q8}, [%[out_ptr]]! \n\t" "subs r6, r6, #32 \n\t" "bge loop_hw_%= \n\t" "end_hw_%=: \n\t" "cmp r6, #0 \n\t" "bge end_remainder_%= \n\t" "mov r5, #4 \n\t" "mul r6, r6, r5 \n\t" "add %[input_x_ptr], %[input_x_ptr], r6 \n\t" "vld1.32 {q1, q2}, [%[input_x_ptr]]! \n\t" "vld1.32 {q3, q4}, [%[input_x_ptr]]! \n\t" "vld1.32 {q5, q6}, [%[input_x_ptr]]! \n\t" "vld1.32 {q7, q8}, [%[input_x_ptr]]! \n\t" "vmul.f32 q1, q1, q9 \n\t" "vmul.f32 q2, q2, q9 \n\t" "vmul.f32 q3, q3, q9 \n\t" "vmul.f32 q4, q4, q9 \n\t" "vmul.f32 q5, q5, q9 \n\t" "vmul.f32 q6, q6, q9 \n\t" "vmul.f32 q7, q7, q9 \n\t" "vmul.f32 q8, q8, q9 \n\t" "vadd.f32 q1, q1, q10 \n\t" "vadd.f32 q2, q2, q10 \n\t" "vadd.f32 q3, q3, q10 \n\t" "vadd.f32 q4, q4, q10 \n\t" "vadd.f32 q5, q5, q10 \n\t" "vadd.f32 q6, q6, q10 \n\t" "vadd.f32 q7, q7, q10 \n\t" "vadd.f32 q8, q8, q10 \n\t" "add %[out_ptr], %[out_ptr], r6 \n\t" "vst1.32 {q1, q2}, [%[out_ptr]]! \n\t" "vst1.32 {q3, q4}, [%[out_ptr]]! \n\t" "vst1.32 {q5, q6}, [%[out_ptr]]! \n\t" "vst1.32 {q7, q8}, [%[out_ptr]]! \n\t" "end_remainder_%=: \n\t" "subs %[C], %[C], #1 \n\t" "bge loop_c_%= \n\t" "end_c_%=: \n\t" "subs %[N], %[N], #1 \n\t" "bge loop_n_%= \n\t" "end_n_%=: \n\t" : : [input_x_ptr] "r"(input_x_ptr), [out_ptr] "r"(out_ptr), [new_scale_ptr] "r"(new_scale_ptr), [new_bias_ptr] "r"(new_bias_ptr), [N] "r"(N), [C] "r"(C), [HXW] "r"(HXW) : "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "r5", "r6"); delete[] inv_std_ptr; delete[] new_scale_ptr; delete[] new_bias_ptr; } else { float *inv_std_ptr = new float[C]; for (int i = 0; i < C; i++) { inv_std_ptr[i] = 1 / static_cast<float>(pow((variance_ptr[i] + epsilon), 0.5)); } Tensor new_scale; auto new_scale_ptr = new_scale.mutable_data<float>(framework::make_ddim({C})); Tensor new_bias; auto new_bias_ptr = new_bias.mutable_data<float>(framework::make_ddim({C})); /// ((x - est_mean) * (inv_var) * scale + bias equal to /// (x * inv_var * scale) + (bias - est_mean * inv_var * scale) for (int i = 0; i < C; i++) { new_scale_ptr[i] = inv_std_ptr[i] * scale_ptr[i]; new_bias_ptr[i] = bias_ptr[i] - mean_ptr[i] * inv_std_ptr[i] * scale_ptr[i]; { for (int n = 0; n < N; n++) { for (int h = 0; h < H; h++) { int tmp_index = n * stride0 + i * stride1 + h * stride2; for (int w = 0; w < W; w++) { int index = tmp_index + w; out_ptr[index] = input_x_ptr[index] * new_scale_ptr[i] + new_bias_ptr[i]; } } } } } delete[] inv_std_ptr; } #endif #else float *inv_std_ptr = new float[C]; for (int i = 0; i < C; i++) { inv_std_ptr[i] = 1 / static_cast<float>(pow((variance_ptr[i] + epsilon), 0.5)); } Tensor new_scale; auto new_scale_ptr = new_scale.mutable_data<float>(framework::make_ddim({C})); Tensor new_bias; auto new_bias_ptr = new_bias.mutable_data<float>(framework::make_ddim({C})); /// ((x - est_mean) * (inv_var) * scale + bias equal to /// (x * inv_var * scale) + (bias - est_mean * inv_var * scale) for (int i = 0; i < C; i++) { new_scale_ptr[i] = inv_std_ptr[i] * scale_ptr[i]; new_bias_ptr[i] = bias_ptr[i] - mean_ptr[i] * inv_std_ptr[i] * scale_ptr[i]; { for (int n = 0; n < N; n++) { for (int h = 0; h < H; h++) { int tmp_index = n * stride0 + i * stride1 + h * stride2; for (int w = 0; w < W; w++) { int index = tmp_index + w; out_ptr[index] = input_x_ptr[index] * new_scale_ptr[i] + new_bias_ptr[i]; } } } } } delete[] inv_std_ptr; #endif } } // namespace operators } // namespace paddle_mobile #endif
xiaohaichun/paddle-mobile
src/operators/math/gru_compute.h
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifdef GRU_OP #pragma once #include "operators/math/activation_functions.h" namespace paddle_mobile { namespace operators { namespace math { template <typename T> struct GRUMetaValue { T *gate_weight; T *state_weight; T *gate_value; T *reset_output_value; T *output_value; T *prev_out_value; }; template <typename DeviceType, typename T> struct GRUUnitFunctor { static void compute(GRUMetaValue<T> value, int frame_size, int batch_size, const ActivationType active_node, const ActivationType active_gate); }; } // namespace math } // namespace operators } // namespace paddle_mobile #endif
xiaohaichun/paddle-mobile
metal/paddle-mobile-demo/paddle-mobile-demo/LoadPointerViewController.h
// // LoadPointerViewController.h // paddle-mobile-demo // // Created by Xiao,Haichun on 2018/9/19. // Copyright © 2018年 orange. All rights reserved. // #import <UIKit/UIKit.h> @interface LoadPointerViewController : UIViewController @end
xiaohaichun/paddle-mobile
src/operators/math/pool_3x3.h
<filename>src/operators/math/pool_3x3.h /* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifdef POOL_OP #pragma once #ifdef _OPENMP #include <omp.h> #endif #include <algorithm> #include <vector> #include "framework/tensor.h" #if __ARM_NEON #include <arm_neon.h> #endif // __ARM_NEON namespace paddle_mobile { namespace operators { namespace math { void Pool3x3Avgs1p1(const framework::Tensor *input, framework::Tensor *output); void Pool3x3Maxs1p1(const framework::Tensor *input, framework::Tensor *output); void Pool3x3Max(std::vector<int> strides, std::vector<int> paddings, const framework::Tensor *input, framework::Tensor *output); void Pool3x3Avg(std::vector<int> strides, std::vector<int> paddings, const framework::Tensor *in_x, framework::Tensor *out); void Pool3x3Maxs1_int8(const framework::Tensor *input, framework::Tensor *output, int32_t pad_h, int32_t pad_w); void Pool3x3Maxs2_int8(const framework::Tensor *input, framework::Tensor *output, int32_t pad_h, int32_t pad_w); void Pool3x3Max_int8(const std::vector<int> &strides, const std::vector<int> &paddings, const framework::Tensor *input, framework::Tensor *output); } // namespace math } // namespace operators } // namespace paddle_mobile #endif
xiaohaichun/paddle-mobile
src/operators/kernel/central-arm-func/mul_arm_func.h
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifdef MUL_OP #pragma once namespace paddle_mobile { namespace operators { // 1、如果x,y维度都是2维, // x = [[1,2], y = [[5,6], // [3,4]] [7,8]] // 运算结果为正常矩阵相乘。结果 out = // [[1*5+2*7,1*6+2*8],[3*5+4*7, 3*6+4*8]] // // 2、如果x的维度大于2或者y的维度大于2,x的维度(2,3,4) ,y的维度(4,1,2) // x = [[[1,2,3,4], // [2,3,4,5], // [3,4,5,6]], // [[1,2,3,4], // [2,3,4,5], // [3,4,5,6]]] // y = [[[1,2]], // [[3,4]], // [[5,6]], // [[7,8]]] // 需要借助x_num_col_dims和y_num_col_dims将x和y的维度转换为2维 // 从模型中读到参数,x_num_col_dims = 2,y_num_col_dims = 1,左开右闭 // (1) 将x = (2,3,4)的index [0,x_num_col_dims)部分2,3相乘,得到6, // [x_num_col_dims,xdim.size())部分4相乘,得到4, // 将Tensor x的dims重写成(6,4) // (2) 将y = (4,1,2)的index [0,y_num_col_dims)部分4相乘,得到4, // [y_num_col_dims,ydim.size())部分1,2相乘,得到2, // 将Tensor y的dims重写成(4,2) // 并不影响x,y在内存中的分布。 // x = [[1,2,3,4], y = [[1,2], // [2,3,4,5], [3,4], // [3,4,5,6], 矩阵乘法 [5,6], // [1,2,3,4], [7,8]] // [2,3,4,5], // [3,4,5,6]] // 结果x(6行4列)乘y(4行2列),按1中矩阵相乘,结果out(6行2列) template <typename P> void MulCompute(const MulParam<CPU> &param) { const Tensor *input_x = param.InputX(); const Tensor *input_y = param.InputY(); Tensor *out = param.Out(); const Tensor x_matrix = input_x->dims().size() > 2 ? framework::ReshapeToMatrix(*input_x, param.XNumColDims()) : *input_x; const Tensor y_matrix = input_y->dims().size() > 2 ? framework::ReshapeToMatrix(*input_y, param.YNumColDims()) : *input_y; auto out_dim = out->dims(); if (out_dim.size() != 2) { out->Resize({x_matrix.dims()[0], y_matrix.dims()[1]}); } if (param.InputX()->type() == typeid(int8_t)) { out->mutable_data<int32_t>(); math::matmul<float, int32_t>(x_matrix, false, y_matrix, false, static_cast<float>(1), out, static_cast<float>(0)); } else { out->mutable_data<float>(); math::matmul<float>(x_matrix, false, y_matrix, false, static_cast<float>(1), out, static_cast<float>(0)); } if (out_dim.size() != 2) { out->Resize(out_dim); } } } // namespace operators } // namespace paddle_mobile #endif
xiaohaichun/paddle-mobile
src/operators/kernel/central-arm-func/fusion_fc_arm_func.h
<filename>src/operators/kernel/central-arm-func/fusion_fc_arm_func.h /* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifdef FUSION_FC_OP #pragma once #include <type_traits> #include "operators/math/math_function.h" #include "operators/op_param.h" namespace paddle_mobile { namespace operators { template <typename P, typename S> void FusionFcCompute(const FusionFcParam<CPU> &param) { const Tensor *input_x = param.InputX(); const Tensor *input_y = param.InputY(); Tensor *input_z = param.InputZ(); S *input_z_data = input_z->data<S>(); int axis = param.Axis(); Tensor *out = param.Out(); // int m = out->dims()[0]; // int n = out->dims()[1]; auto *out_data = out->mutable_data<P>(); float alpha = 1.0f; float beta = 1.0f; const Tensor x_matrix = input_x->dims().size() > 2 ? framework::ReshapeToMatrix(*input_x, param.XNumColDims()) : *input_x; const Tensor y_matrix = input_y->dims().size() > 2 ? framework::ReshapeToMatrix(*input_y, param.YNumColDims()) : *input_y; auto out_dim = out->dims(); if (out_dim.size() != 2) { out->Resize({x_matrix.dims()[0], y_matrix.dims()[1]}); } PADDLE_MOBILE_ENFORCE(out_dim.size() == 2, " out_dim.size must be 2."); PADDLE_MOBILE_ENFORCE(input_z->dims().size() == 1, "inpu_z size must be 1"); PADDLE_MOBILE_ENFORCE(out_dim[1] == input_z->dims()[0], " out_dim.size must be 2."); axis = (axis == -1 ? out_dim.size() - input_z->dims().size() : axis); PADDLE_MOBILE_ENFORCE(axis == 1, " to fit broadcast, axis = 1. "); if (std::is_same<P, int8_t>::value) { #ifdef FUSION_FC_INT8_OP alpha = param.InputScale()->data<float>()[0]; beta = 0.0f; math::matmul(x_matrix, false, y_matrix, false, alpha, out, beta, false, input_z_data, true); #endif } else { // bias_data的维度和out的第二个维度一致 int64_t classes = input_z->numel(); for (int i = 0; i < out_dim[0]; i++) { memory::Copy(out_data + i * classes, input_z_data, sizeof(float) * classes); } math::matmul<float>(x_matrix, false, y_matrix, false, alpha, out, beta, false); } PADDLE_MOBILE_ENFORCE(out_dim.size() == 2, " out_dim.size must be 2."); // if (out_dim.size() != 2) { // out->Resize(out_dim); // } } } // namespace operators } // namespace paddle_mobile #endif
xiaohaichun/paddle-mobile
src/framework/loader.h
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include <string> #include "common/types.h" #include "framework/program/program.h" namespace paddle_mobile { namespace framework { template <typename Dtype = CPU, Precision P = Precision::FP32> class Loader { public: /* * @b load separate format fluid model * @b 加载分开形式的 fluid 模型 * */ const Program<Dtype, P> Load(const std::string &dirname, bool optimize = false, bool quantification = false, bool can_add_split = false); /* * @b load combine format fluid mode * @b 加载结合在一起格式的模型 * */ const Program<Dtype, P> Load(const std::string &model_path, const std::string &para_path, bool optimize = false, bool quantification = false); const Program<Dtype, P> LoadCombinedMemory(size_t model_len, const uint8_t *model_buf, size_t combined_params_len, uint8_t *combined_params_buf, bool optimize = false, bool quantification = false); private: const Program<Dtype, P> LoadProgram(const std::string &model_path, bool optimize = false, bool quantification = false, bool can_add_split = false); void InitMemoryFromProgram( const std::shared_ptr<ProgramDesc> &originProgramDesc, const std::shared_ptr<Scope> &scope); }; } // namespace framework } // namespace paddle_mobile
xiaohaichun/paddle-mobile
src/framework/executor.h
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include <map> #include <memory> #include <string> #include <vector> #include "common/types.h" #include "common/util.h" #include "framework/lod_tensor.h" #include "framework/operator.h" #include "framework/program/program.h" #include "framework/tensor.h" namespace paddle_mobile { namespace framework { template <typename Dtype = CPU, Precision P = Precision::FP32> class Executor { public: typedef typename PrecisionTrait<P>::ptype Ptype; // exector constructor // @param program program converted from proto program in PaddlePaddle // @param use_optimize bool whether use operator fusion to speed up or not // @param loddable bool Executor(const framework::Program<Dtype> program, int batch_size = 1, const bool use_optimize = true, const bool loddable = false); // predict with tensor input // @param t input tensor to do prediction // @return predicted tensor std::shared_ptr<framework::Tensor> Predict(const framework::Tensor &t); // predict with lod tensor input // @param t input lod tensor to do prediction // @return predicted lod tensor std::shared_ptr<framework::LoDTensor> PredictLod( const framework::LoDTensor &t); // predict with vector input and dims // @param input vector whose elements will be formed // @param input lod tensor to do prediction // @param dims vector whose elements will be formed // @param input tensor shape // @return vector which is flatted from predicted tensor std::vector<Ptype> Predict(const std::vector<Ptype> &input, const std::vector<int64_t> &dims); #ifdef PADDLE_MOBILE_FPGA void InjectVariable(const framework::Tensor &t, std::string var_name); void FeedData(const framework::Tensor &t); std::shared_ptr<framework::Tensor> FetchResult(int id = -1); void Predict_From_To(int start = 0, int end = -1); void Predict_From(int start); void Predict_To(int end); #endif protected: Executor() = default; std::shared_ptr<framework::Tensor> Predict(const framework::Tensor &t, int block_id); bool varInputMemory(const std::shared_ptr<framework::VarDesc> &var_desc, framework::Variable *var, framework::LoDTensor *tensor) const; void InitMemory(); void InitCombineMemory(); void LoadMemory(void **data, const std::shared_ptr<framework::VarDesc> var_desc, framework::LoDTensor *tensor); #ifdef PADDLE_MOBILE_CL void LoadMemory(const framework::VarDesc var_desc, float *tensorInput, char **data); #endif framework::Program<Dtype> program_; int batch_size_ = 1; std::shared_ptr<framework::ProgramDesc> to_predict_program_; std::map<framework::BlockDesc, std::vector<std::shared_ptr<framework::OperatorBase<Dtype>>>> ops_of_block_; #ifdef PADDLE_MOBILE_PROFILE struct ProfInfo { int tid = 0; uint64_t runBegin = 0UL; uint64_t runEnd = 0UL; }; #endif bool use_optimize_ = false; bool loddable_ = false; }; } // namespace framework } // namespace paddle_mobile
xiaohaichun/paddle-mobile
src/operators/math/activation_functions.h
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include <math.h> #include <string> #include "common/enforce.h" namespace paddle_mobile { namespace operators { namespace math { #define SIGMOID_THRESHOLD_MIN -40.0 #define SIGMOID_THRESHOLD_MAX 13.0 #define EXP_MAX_INPUT 40.0 enum ActivationType { kSigmoid, kReLU, kTanh, kIdentity, }; inline ActivationType GetActivationType(const std::string &type) { if (type == "sigmoid") { return ActivationType::kSigmoid; } else if (type == "relu") { return ActivationType::kReLU; } else if (type == "tanh") { return ActivationType::kTanh; } else if (type == "identity" || type == "") { return ActivationType::kIdentity; } PADDLE_MOBILE_THROW_EXCEPTION("Not support activation type."); } namespace forward { template <typename T> T Identity(const T a) { return a; } template <typename T> T Relu(const T a) { return a > static_cast<T>(0.0) ? a : static_cast<T>(0.0); } template <typename T> T Sigmoid(const T a) { const T min = SIGMOID_THRESHOLD_MIN; const T max = SIGMOID_THRESHOLD_MAX; T tmp = (a < min) ? min : ((a > max) ? max : a); return static_cast<T>(1.0) / (static_cast<T>(1.0) + exp(-tmp)); } template <typename T> T Tanh(const T a) { T tmp = -2.0 * a; tmp = (tmp > EXP_MAX_INPUT) ? EXP_MAX_INPUT : tmp; return (2.0 / (1.0 + exp(tmp))) - 1.0; } } // namespace forward template <typename T> struct Active { typedef T (*Act)(T); }; static Active<float>::Act kActFloat[] = { &forward::Sigmoid<float>, &forward::Relu<float>, &forward::Tanh<float>, &forward::Identity<float>}; namespace forward { inline float activation(float a, int index) { return kActFloat[index](a); } } // namespace forward } // namespace math } // namespace operators } // namespace paddle_mobile
xiaohaichun/paddle-mobile
src/framework/tensor.h
<gh_stars>0 /* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include <cstdint> #include <cstring> #include <fstream> #include <memory> #include <string> #include <type_traits> #include <typeindex> #include <vector> #include "common/enforce.h" #include "framework/data_layout.h" #include "framework/tensor_base.h" #include "memory/t_malloc.h" namespace paddle_mobile { namespace framework { class LoDTensor; class Tensor : public TensorBase { public: Tensor() {} template <typename T> Tensor(std::vector<T> input, DDim ddim) { PADDLE_MOBILE_ENFORCE( input.size() == framework::product(ddim), "input vector'length should be equal to tensor's length"); auto input_ptr = mutable_data<T>(ddim); for (int i = 0; i < input.size(); ++i) { input_ptr[i] = input[i]; } } Tensor(const Tensor &inTensor) { this->dims_ = inTensor.dims_; this->holder_ = inTensor.holder_; this->offset_ = inTensor.offset_; } /*! Resize the dimensions of the memory block. */ inline Tensor &Resize(const DDim &dims) { dims_ = dims; return *this; } /*! The internal of two tensors share the same memory block. */ inline Tensor &ShareDataWith(const Tensor &src) { src.check_memory_size(); if (holder_.get() != src.holder_.get()) { *this = src; } return *this; } inline void *mutable_data(std::type_index type) { if (holder_ != nullptr) { holder_->set_type(type); } PADDLE_MOBILE_ENFORCE(numel() >= 0, "the Tensor's numel must >=0.") int64_t size = numel() * SizeOfType(type); if (holder_ == nullptr || holder_->size() < size + offset_) { holder_.reset(new PlaceholderImpl(size, type)); offset_ = 0; } return reinterpret_cast<void *>( reinterpret_cast<uintptr_t>(holder_->ptr()) + offset_); } /** * @brief Return a pointer to mutable memory block. * @note If not exist, then allocation. */ template <typename T> inline T *mutable_data() { static_assert(std::is_pod<T>::value, "T must be POD"); return reinterpret_cast<T *>(mutable_data(typeid(T))); } /** * @brief Return a pointer to mutable memory block. * * @param[in] dims The dimensions of the memory block. * @param[in] place The place of the memory block. * * @note If not exist, then allocation. */ template <typename T> inline T *mutable_data(DDim dims) { static_assert(std::is_pod<T>::value, "T must be POD"); Resize(dims); return mutable_data<T>(); } /** * @brief Return a sub-tensor of the given tensor. * * @param[in] begin_idx The index of the start row(inclusive) to * slice. * The index number begins from 0. * @param[in] end_idx The index of the end row(exclusive) to * slice. * The index number begins from 0. */ inline Tensor Slice(int begin_idx, int end_idx) const { check_memory_size(); PADDLE_MOBILE_ENFORCE(begin_idx >= 0, "The start row index must be greater than 0.") PADDLE_MOBILE_ENFORCE(end_idx <= dims_[0], "The end row index is out of bound.") PADDLE_MOBILE_ENFORCE( begin_idx < end_idx, "The start row index must be lesser than the end row index") if (dims_[0] == 1) { return *this; } else { size_t base = numel() / dims_[0]; Tensor dst; dst.holder_ = holder_; DDim dst_dims = dims_; dst_dims[0] = end_idx - begin_idx; dst.Resize(dst_dims); dst.offset_ = offset_ + begin_idx * base * SizeOfType(type()); return dst; } } /*! Return a pointer to mutable memory block. */ template <typename T> inline T *data() { check_memory_size(); PADDLE_MOBILE_ENFORCE( (std::is_same<T, void>::value || holder_->type().hash_code() == typeid(T).hash_code()), "Tensor holds the wrong type, it holds %s", this->holder_->type().name()); return reinterpret_cast<T *>(reinterpret_cast<uintptr_t>(holder_->ptr()) + offset_); } /*! Return a pointer to constant memory block. */ template <typename T> inline const T *data() const { check_memory_size(); PADDLE_MOBILE_ENFORCE( (std::is_same<T, void>::value || holder_->type().hash_code() == typeid(T).hash_code()), "Tensor holds the wrong type, it holds %s ,requested:%s", this->holder_->type().name(), typeid(T).name()); return reinterpret_cast<const T *>( reinterpret_cast<uintptr_t>(holder_->ptr()) + offset_); } private: struct PlaceholderImpl : public Placeholder { PlaceholderImpl(size_t size, std::type_index type) : ptr_(static_cast<uint8_t *>(memory::Alloc(size)), memory::PODDeleter<uint8_t>()), size_(size), type_(type) { PADDLE_MOBILE_ENFORCE(ptr_ != nullptr, "Insufficient memory to allocation"); } virtual size_t size() const { return size_; } virtual void *ptr() const { return static_cast<void *>(ptr_.get()); } virtual std::type_index type() const { return type_; } virtual void set_type(std::type_index type) { type_ = type; } std::unique_ptr<uint8_t, memory::PODDeleter<uint8_t>> ptr_; /*! the size of memory block. */ size_t size_; /* the current type of memory */ std::type_index type_; }; #ifdef PADDLE_MOBILE_FPGA public: // NOLINT inline void reset_data_ptr(void *p) { ((PlaceholderImpl *)(holder_.get()))->ptr_.reset((uint8_t *)p); // NOLINT } float scale[2]; // scale[0]= MAX/127.0, scale[1]= 127.0/MAX #endif }; #ifdef PADDLE_MOBILE_DEBUG inline Print &operator<<(Print &printer, const Tensor &tensor) { printer << " dims: " << tensor.dims() << "\n"; int stride = tensor.numel() / 20; stride = stride > 0 ? stride : 1; #ifndef PADDLE_MOBILE_FPGA for (int i = 0; i < tensor.numel(); i += stride) { if (tensor.type() == typeid(float)) { printer << tensor.data<float>()[i] << " "; } else if (tensor.type() == typeid(int32_t)) { printer << tensor.data<int32_t>()[i] << " "; } else if (tensor.type() == typeid(int64_t)) { printer << tensor.data<int64_t>()[i] << " "; } else if (tensor.type() == typeid(int8_t)) { printer << static_cast<int>(tensor.data<int8_t>()[i]) << " "; } else if (tensor.type() == typeid(int32_t)) { printer << tensor.data<int32_t>()[i] << " "; } } #endif return printer; } #endif inline Tensor ReshapeToMatrix(const Tensor &src, int num_col_dims) { Tensor res; res.ShareDataWith(src); res.Resize(flatten_to_2d(src.dims(), num_col_dims)); return res; } } // namespace framework } // namespace paddle_mobile
xiaohaichun/paddle-mobile
src/operators/math/gru_kernel.h
<reponame>xiaohaichun/paddle-mobile /* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifdef GRU_OP #pragma once #include <type_traits> #include "operators/math/activation_functions.h" namespace paddle_mobile { namespace operators { namespace math { namespace forward { template <typename T> class gru_resetOutput { public: void operator()(T *value_update_gate, T *value_reset_gate, T *prev_out, T *value_reset_output, ActivationType act_gate) { *value_update_gate = activation(*value_update_gate, act_gate); *value_reset_gate = activation(*value_reset_gate, act_gate); *value_reset_output = (*prev_out) * (*value_reset_gate); } }; template <typename T> class gru_finalOutput { public: void operator()(T *value_update_gate, T *value_frame_state, T *prev_out, T *value_output, ActivationType act_input) { *value_frame_state = activation(*value_frame_state, act_input); *value_output = *prev_out - ((*value_update_gate) * (*prev_out)) + ((*value_update_gate) * (*value_frame_state)); } }; } // namespace forward } // namespace math } // namespace operators } // namespace paddle_mobile #endif
xiaohaichun/paddle-mobile
src/operators/kernel/central-arm-func/pool_arm_func.h
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifdef POOL_OP #pragma once #include <string> #include <vector> #include "operators/math/pooling.h" namespace paddle_mobile { namespace operators { using framework::Tensor; template <typename T, typename S> void PoolBasic(std::string pooling_type, std::vector<int> ksize, std::vector<int> strides, std::vector<int> paddings, const Tensor *in_x, Tensor *out) { if (pooling_type == "max") { math::PoolFunctor<CPU, math::MaxPool<T>, T> pool2d_forward; math::MaxPool<T> pool_process; pool2d_forward(*in_x, ksize, strides, paddings, pool_process, out); } else if (pooling_type == "avg") { math::PoolFunctor<CPU, math::AvgPool<T, S>, T> pool2d_forward; math::AvgPool<T, S> pool_process; pool2d_forward(*in_x, ksize, strides, paddings, pool_process, out); } } template <typename P> void PoolCompute(const PoolParam<CPU> &param) { const Tensor *in_x = param.Input(); Tensor *out = param.Output(); std::string pooling_type = param.PoolingType(); std::vector<int> ksize = param.Ksize(); std::vector<int> strides = param.Strides(); std::vector<int> paddings = param.Paddings(); if (ksize.size() != 2) { LOG(paddle_mobile::LogLevel::kLOG_ERROR) << "Pool op only supports 2D and 3D input."; } if (param.isGlobalPooling()) { for (size_t i = 0; i < ksize.size(); ++i) { paddings[i] = 0; ksize[i] = static_cast<int>(in_x->dims()[i + 2]); } } if (in_x->type() == typeid(int8_t)) { if (pooling_type == "max" && ksize[0] == 3 && ksize[0] == ksize[1]) { if (strides[0] == strides[1] && strides[0] == 1) { math::Pool3x3Maxs1_int8(in_x, out, paddings[0], paddings[1]); } else if (strides[0] == strides[1] && strides[0] == 2) { math::Pool3x3Maxs2_int8(in_x, out, paddings[0], paddings[1]); } else { math::Pool3x3Max_int8(strides, paddings, in_x, out); } } else { PoolBasic<int8_t, int32_t>(pooling_type, ksize, strides, paddings, in_x, out); } } else { if (ksize[0] == 3 && ksize[0] == ksize[1]) { if (pooling_type == "max") { if (strides[0] == strides[1] && strides[0] == 1 && paddings[0] == paddings[1] && paddings[1] == 1) { math::Pool3x3Maxs1p1(in_x, out); } else { math::Pool3x3Max(strides, paddings, in_x, out); } } else if (pooling_type == "avg") { if (strides[0] == strides[1] && strides[0] == 1 && paddings[0] == paddings[1] && paddings[1] == 1) { math::Pool3x3Avgs1p1(in_x, out); } else { math::Pool3x3Avg(strides, paddings, in_x, out); } } } else if (ksize[0] == 2 && ksize[0] == ksize[1] && strides[0] == 2 && strides[0] == strides[1] && paddings[0] == paddings[1] && paddings[1] == 0) { #if __ARM_NEON #if __aarch64__ PoolBasic<float, float>(pooling_type, ksize, strides, paddings, in_x, out); #else /// todo: fix bug in Pool2x2 if (pooling_type == "max") { math::Pool2x2Maxs2p0(strides, paddings, in_x, out); } else if (pooling_type == "avg") { math::Pool2x2Avgs2p0(strides, paddings, in_x, out); } #endif #else PoolBasic<float, float>(pooling_type, ksize, strides, paddings, in_x, out); #endif // __ARM_NEON } else { PoolBasic<float, float>(pooling_type, ksize, strides, paddings, in_x, out); } } } } // namespace operators } // namespace paddle_mobile #endif
xiaohaichun/paddle-mobile
src/operators/math/gru_cpu_kernel.h
<gh_stars>1-10 /* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifdef GRU_OP #pragma once #include <type_traits> #include "operators/math/activation_functions.h" #include "operators/math/gru_compute.h" namespace paddle_mobile { namespace operators { namespace math { template <class OpResetOutput, typename T> void hl_naive_gru_forward_reset_output(OpResetOutput op_reset_output, T *gate_value, T *reset_output_value, T *prev_output_value, int frame_size, ActivationType active_gate) { T r_value_update_gate; T r_value_reset_gate; T r_value_reset_output; T r_prev_out = 0; T *update_gate = gate_value; T *reset_gate = gate_value + frame_size; for (int i = 0; i < frame_size; i++) { r_value_update_gate = update_gate[i]; r_value_reset_gate = reset_gate[i]; if (prev_output_value) { r_prev_out = prev_output_value[i]; } op_reset_output(&r_value_update_gate, &r_value_reset_gate, &r_prev_out, &r_value_reset_output, active_gate); update_gate[i] = r_value_update_gate; reset_gate[i] = r_value_reset_gate; reset_output_value[i] = r_value_reset_output; } } template <class OpFinalOutput, typename T> void hl_naive_gru_forward_final_output(OpFinalOutput op_final_output, T *gate_value, T *prev_output_value, T *output_value, int frame_size, ActivationType active_node) { T r_value_update_gate; T r_value_frame_state; T r_prev_out = 0; T r_output; T *update_gate = gate_value; T *frame_state = gate_value + frame_size * 2; for (int i = 0; i < frame_size; i++) { r_value_update_gate = update_gate[i]; r_value_frame_state = frame_state[i]; if (prev_output_value) { r_prev_out = prev_output_value[i]; } op_final_output(&r_value_update_gate, &r_value_frame_state, &r_prev_out, &r_output, active_node); frame_state[i] = r_value_frame_state; output_value[i] = r_output; } } template <class OpResetOutput, typename T> inline void forward_reset_output(OpResetOutput op_reset_output, GRUMetaValue<T> value, int frame_size, int batch_size, ActivationType active_gate) { for (int b = 0; b < batch_size; b++) { hl_naive_gru_forward_reset_output( op_reset_output, value.gate_value, value.reset_output_value, value.prev_out_value, frame_size, active_gate); value.gate_value += frame_size * 3; value.reset_output_value += frame_size; if (value.prev_out_value) { value.prev_out_value += frame_size; } } } template <class OpFinalOutput, typename T> inline void forward_final_output(OpFinalOutput op_final_output, GRUMetaValue<T> value, int frame_size, int batch_size, ActivationType active_node) { for (int b = 0; b < batch_size; b++) { hl_naive_gru_forward_final_output(op_final_output, value.gate_value, value.prev_out_value, value.output_value, frame_size, active_node); value.gate_value += frame_size * 3; value.output_value += frame_size; if (value.prev_out_value) { value.prev_out_value += frame_size; } } } } // namespace math } // namespace operators } // namespace paddle_mobile #endif
xiaohaichun/paddle-mobile
src/operators/kernel/central-arm-func/multiclass_nms_arm_func.h
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifdef MULTICLASSNMS_OP #pragma once #include <algorithm> #include <map> #include <utility> #include <vector> #include "framework/tensor.h" #include "operators/math/poly_util.h" #include "operators/op_param.h" namespace paddle_mobile { namespace operators { template <class T> bool SortScorePairDescend(const std::pair<float, T>& pair1, const std::pair<float, T>& pair2) { return pair1.first > pair2.first; } template <class T> static inline void GetMaxScoreIndex( const std::vector<T>& scores, const T threshold, int top_k, std::vector<std::pair<T, int>>* sorted_indices) { for (size_t i = 0; i < scores.size(); ++i) { if (scores[i] > threshold) { sorted_indices->push_back(std::make_pair(scores[i], i)); } } // Sort the score pair according to the scores in descending order std::stable_sort(sorted_indices->begin(), sorted_indices->end(), SortScorePairDescend<int>); // Keep top_k scores if needed. if (top_k > -1 && top_k < static_cast<int>(sorted_indices->size())) { sorted_indices->resize(top_k); } } template <class T> static inline T BBoxArea(const T* box, const bool normalized) { if (box[2] < box[0] || box[3] < box[1]) { // If coordinate values are is invalid // (e.g. xmax < xmin or ymax < ymin), return 0. return static_cast<T>(0.); } else { const T w = box[2] - box[0]; const T h = box[3] - box[1]; if (normalized) { return w * h; } else { // If coordinate values are not within range [0, 1]. return (w + 1) * (h + 1); } } } template <class T> static inline T JaccardOverlap(const T* box1, const T* box2, const bool normalized) { if (box2[0] > box1[2] || box2[2] < box1[0] || box2[1] > box1[3] || box2[3] < box1[1]) { return static_cast<T>(0.); } else { const T inter_xmin = std::max(box1[0], box2[0]); const T inter_ymin = std::max(box1[1], box2[1]); const T inter_xmax = std::min(box1[2], box2[2]); const T inter_ymax = std::min(box1[3], box2[3]); const T inter_w = inter_xmax - inter_xmin; const T inter_h = inter_ymax - inter_ymin; const T inter_area = inter_w * inter_h; const T bbox1_area = BBoxArea<T>(box1, normalized); const T bbox2_area = BBoxArea<T>(box2, normalized); return inter_area / (bbox1_area + bbox2_area - inter_area); } } template <class T> static inline T PolyIoU(const T* box1, const T* box2, const size_t box_size, const bool normalized) { T bbox1_area = math::PolyArea<T>(box1, box_size, normalized); T bbox2_area = math::PolyArea<T>(box2, box_size, normalized); T inter_area = math::PolyOverlapArea<T>(box1, box2, box_size, normalized); if (bbox1_area == 0 || bbox2_area == 0 || inter_area == 0) { // If coordinate values are is invalid // if area size <= 0, return 0. return static_cast<T>(0.); } else { return inter_area / (bbox1_area + bbox2_area - inter_area); } } template <typename T> static inline void NMSFast(const framework::Tensor& bbox, const framework::Tensor& scores, const T score_threshold, const T nms_threshold, const T eta, const int64_t top_k, std::vector<int>* selected_indices) { // The total boxes for each instance. int64_t num_boxes = bbox.dims()[0]; // 4: [xmin ymin xmax ymax] int64_t box_size = bbox.dims()[1]; std::vector<T> scores_data(num_boxes); std::copy_n(scores.data<T>(), num_boxes, scores_data.begin()); std::vector<std::pair<T, int>> sorted_indices; GetMaxScoreIndex(scores_data, score_threshold, top_k, &sorted_indices); selected_indices->clear(); T adaptive_threshold = nms_threshold; const T* bbox_data = bbox.data<T>(); while (sorted_indices.size() != 0) { const int idx = sorted_indices.front().second; bool keep = true; for (size_t k = 0; k < selected_indices->size(); ++k) { if (keep) { const int kept_idx = (*selected_indices)[k]; T overlap = T(0.); if (box_size == 4) { overlap = JaccardOverlap<T>(bbox_data + idx * box_size, bbox_data + kept_idx * box_size, true); } else { overlap = PolyIoU<T>(bbox_data + idx * box_size, bbox_data + kept_idx * box_size, box_size, true); } keep = overlap <= adaptive_threshold; } else { break; } } if (keep) { selected_indices->push_back(idx); } sorted_indices.erase(sorted_indices.begin()); if (keep && eta < 1 && adaptive_threshold > 0.5) { adaptive_threshold *= eta; } } } template <typename T> void MultiClassNMS(const framework::Tensor& scores, const framework::Tensor& bboxes, std::map<int, std::vector<int>>* indices, int* num_nmsed_out, const int& background_label, const int& nms_top_k, const int& keep_top_k, const T& nms_threshold, const T& nms_eta, const T& score_threshold) { int64_t class_num = scores.dims()[0]; int64_t predict_dim = scores.dims()[1]; int num_det = 0; for (int64_t c = 0; c < class_num; ++c) { if (c == background_label) continue; framework::Tensor score = scores.Slice(c, c + 1); /// [c] is key NMSFast<float>(bboxes, score, score_threshold, nms_threshold, nms_eta, nms_top_k, &((*indices)[c])); num_det += (*indices)[c].size(); } *num_nmsed_out = num_det; const T* scores_data = scores.data<T>(); if (keep_top_k > -1 && num_det > keep_top_k) { std::vector<std::pair<float, std::pair<int, int>>> score_index_pairs; for (const auto& it : *indices) { int label = it.first; const T* sdata = scores_data + label * predict_dim; const std::vector<int>& label_indices = it.second; for (size_t j = 0; j < label_indices.size(); ++j) { int idx = label_indices[j]; // PADDLE_ENFORCE_LT(idx, predict_dim); score_index_pairs.push_back( std::make_pair(sdata[idx], std::make_pair(label, idx))); } } // Keep top k results per image. std::stable_sort(score_index_pairs.begin(), score_index_pairs.end(), SortScorePairDescend<std::pair<int, int>>); score_index_pairs.resize(keep_top_k); // Store the new indices. std::map<int, std::vector<int>> new_indices; for (size_t j = 0; j < score_index_pairs.size(); ++j) { int label = score_index_pairs[j].second.first; int idx = score_index_pairs[j].second.second; new_indices[label].push_back(idx); } new_indices.swap(*indices); *num_nmsed_out = keep_top_k; } } template <typename T> void MultiClassOutput(const framework::Tensor& scores, const framework::Tensor& bboxes, const std::map<int, std::vector<int>>& selected_indices, framework::Tensor* outs) { int predict_dim = scores.dims()[1]; int box_size = bboxes.dims()[1]; int out_dim = bboxes.dims()[1] + 2; auto* scores_data = scores.data<T>(); auto* bboxes_data = bboxes.data<T>(); auto* odata = outs->data<T>(); int count = 0; for (const auto& it : selected_indices) { /// one batch int label = it.first; const T* sdata = scores_data + label * predict_dim; const std::vector<int>& indices = it.second; for (size_t j = 0; j < indices.size(); ++j) { int idx = indices[j]; const T* bdata = bboxes_data + idx * box_size; odata[count * out_dim] = label; // label odata[count * out_dim + 1] = sdata[idx]; // score // xmin, ymin, xmax, ymax std::memcpy(odata + count * out_dim + 2, bdata, box_size * sizeof(T)); count++; } } } template <typename P> void MultiClassNMSCompute(const MultiClassNMSParam<CPU>& param) { const auto* input_bboxes = param.InputBBoxes(); const auto& input_bboxes_dims = input_bboxes->dims(); const auto* input_scores = param.InputScores(); const auto& input_scores_dims = input_scores->dims(); auto* outs = param.Out(); auto background_label = param.BackGroundLabel(); auto nms_top_k = param.NMSTopK(); auto keep_top_k = param.KeepTopK(); auto nms_threshold = param.NMSThreshold(); auto nms_eta = param.NMSEta(); auto score_threshold = param.ScoreThreshold(); int64_t batch_size = input_scores_dims[0]; int64_t class_num = input_scores_dims[1]; int64_t predict_dim = input_scores_dims[2]; int64_t box_dim = input_bboxes_dims[2]; std::vector<std::map<int, std::vector<int>>> all_indices; std::vector<size_t> batch_starts = {0}; for (int64_t i = 0; i < batch_size; ++i) { framework::Tensor ins_score = input_scores->Slice(i, i + 1); ins_score.Resize({class_num, predict_dim}); framework::Tensor ins_boxes = input_bboxes->Slice(i, i + 1); ins_boxes.Resize({predict_dim, box_dim}); std::map<int, std::vector<int>> indices; int num_nmsed_out = 0; MultiClassNMS<float>(ins_score, ins_boxes, &indices, &num_nmsed_out, background_label, nms_top_k, keep_top_k, nms_threshold, nms_eta, score_threshold); all_indices.push_back(indices); batch_starts.push_back(batch_starts.back() + num_nmsed_out); } int num_kept = batch_starts.back(); if (num_kept == 0) { float* od = outs->mutable_data<float>({1}); od[0] = -1; } else { int64_t out_dim = box_dim + 2; outs->mutable_data<float>({num_kept, out_dim}); for (int64_t i = 0; i < batch_size; ++i) { framework::Tensor ins_score = input_scores->Slice(i, i + 1); ins_score.Resize({class_num, predict_dim}); framework::Tensor ins_boxes = input_bboxes->Slice(i, i + 1); ins_boxes.Resize({predict_dim, box_dim}); int64_t s = batch_starts[i]; int64_t e = batch_starts[i + 1]; if (e > s) { framework::Tensor out = outs->Slice(s, e); MultiClassOutput<float>(ins_score, ins_boxes, all_indices[i], &out); } } } // framework::LoD lod; // lod.emplace_back(batch_starts); // // outs->set_lod(lod); } } // namespace operators } // namespace paddle_mobile #endif
xiaohaichun/paddle-mobile
src/operators/fill_constant_op.h
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifdef FILL_CONSTANT_OP #pragma once #include <string> #include "framework/data_type.h" #include "framework/operator.h" #include "framework/selected_rows.h" #include "operators/math/math_function.h" #include "operators/op_param.h" namespace paddle_mobile { namespace operators { using std::string; template <typename DeviceType, typename T> class FillConstantOp : public framework::OperatorBase<DeviceType> { public: FillConstantOp(const string &type, const VariableNameMap &inputs, const VariableNameMap &outputs, const framework::AttributeMap attrs, std::shared_ptr<framework::Scope> scope) : framework::OperatorBase<DeviceType>(type, inputs, outputs, attrs, scope), param_(inputs, outputs, attrs, *scope) {} void RunImpl() { auto data_type = static_cast<_PaddleMobile__Framework__Proto__VarType__Type>( param_.DataDtype()); framework::Tensor *tensor = nullptr; auto value = param_.Value(); auto *outvar = param_.OutVar(); if (outvar->template IsType<framework::LoDTensor>()) { tensor = outvar->template GetMutable<framework::LoDTensor>(); } else if (outvar->template IsType<framework::SelectedRows>()) { tensor = outvar->template GetMutable<framework::SelectedRows>() ->mutable_value(); } else { PADDLE_MOBILE_THROW_EXCEPTION( "fill constant op's output only" "supports SelectedRows and LoDTensor"); } tensor->Resize(framework::make_ddim(param_.Shape())); tensor->mutable_data(framework::ToTypeIndex(data_type)); math::set_constant(tensor, value); } void Init() {} void InferShape() const { PADDLE_MOBILE_ENFORCE( param_.Out() != nullptr, "Output (Out) of fill_constant op should not be null."); framework::DDim ddim = framework::make_ddim(param_.Shape()); param_.Out()->Resize(ddim); } protected: FillConstantParam<DeviceType> param_; }; } // namespace operators } // namespace paddle_mobile #endif
xiaohaichun/paddle-mobile
src/fpga/common/driver.h
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <cstring> #include <map> #include "common/log.h" namespace paddle_mobile { namespace fpga { namespace driver { #define DIV_ROUND_UP(n, d) (((n) + (d)-1) / (d)) #define FPGA_REG_PHY_ADDR 0xa0000000 #define FPGA_REG_SIZE 0x1000 #define FPGA_MEM_PHY_ADDR 0x20000000 #define FPGA_MEM_SIZE 0x20000000 #define FPGA_PAGE_SIZE (16UL * 1024UL) // PE related macros const int MAX_NUM_PES = 6; const size_t MAX_TYPE_NAME_LENTH = 8; const int PE_IDX_CONV = 0; const int PE_IDX_POOLING = 1; const int PE_IDX_EW = 2; const int PE_IDX_BYPASS = 3; enum pe_status { IDLE = 0, BUSY = 1, ERROR = 2 }; struct MemoryCacheArgs { void *offset; size_t size; }; #define IOCTL_FPGA_MAGIC 'F' #define IOCTL_MEMCACHE_INVAL _IOW(IOCTL_FPGA_MAGIC, 12, struct MemoryCacheArgs) #define IOCTL_MEMCACHE_FLUSH _IOW(IOCTL_FPGA_MAGIC, 13, struct MemoryCacheArgs) struct fpga_pe { char type_name[MAX_TYPE_NAME_LENTH + 1]; struct pe_data_s *outer; pe_status status; uint64_t interrupt_cnt; }; struct pe_data_s { pthread_mutex_t mutex; struct fpga_pe pe_conv; struct fpga_pe pe_pooling; struct fpga_pe pe_ew; struct fpga_pe pe_bypass; struct fpga_pe *pes[MAX_NUM_PES]; int pe_num; }; struct fpga_memory { pthread_mutex_t mutex; uint64_t *bitmap; unsigned int *nr; unsigned int page_num; unsigned int page_num_long; uint64_t mem_start; uint64_t mem_end; }; struct FPGA_INFO { uint64_t FpgaRegPhyAddr; uint64_t FpgaMemPhyAddr; pthread_t poll_pid; void *FpgaRegVirAddr; struct pe_data_s *pe_data; std::map<void *, size_t> fpga_addr2size_map; std::map<void *, uint64_t> fpga_vaddr2paddr_map; const char *drvdevice_path; const char *memdevice_path; struct fpga_memory *memory_info; int fd_drv; int fd_mem; }; extern struct FPGA_INFO g_fpgainfo; inline uint64_t reg_readq(uint32_t offset) { uint64_t value = *(volatile uint64_t *)((uint8_t *)g_fpgainfo.FpgaRegVirAddr + // NOLINT offset); // NOLINT return value; } inline void reg_writeq(uint64_t value, uint32_t offset) { *(volatile uint64_t *)((uint8_t *)g_fpgainfo.FpgaRegVirAddr + // NOLINT offset) = value; } int open_device_driver(); int close_device_driver(); void *fpga_malloc_driver(size_t size); void fpga_free_driver(void *ptr); void fpga_copy_driver(void *dest, const void *src, size_t num); int fpga_flush_driver(void *address, size_t size); int fpga_invalidate_driver(void *address, size_t size); /*pe*/ uint64_t vaddr_to_paddr(void *address); int fpga_regpoll(uint64_t reg, uint64_t val, int time); } // namespace driver } // namespace fpga } // namespace paddle_mobile
xiaohaichun/paddle-mobile
src/io/api_paddle_mobile.h
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* * This file contains the implementation of inference API with Anakin engine * embeded, this API can only support Anakin models. */ #pragma once #include <vector> #include "io/paddle_inference_api.h" // from paddle_mobile #include "common/enforce.h" #include "common/types.h" #include "io/paddle_mobile.h" namespace paddle_mobile { template <typename Dtype = CPU, Precision P = Precision::FP32> class PaddleMobilePredictor : public PaddlePredictor { public: PaddleMobilePredictor() = delete; explicit PaddleMobilePredictor(const PaddleMobileConfig& config); bool Run(const std::vector<PaddleTensor>& inputs, std::vector<PaddleTensor>* output_data, int batch_size = -1) override; ~PaddleMobilePredictor() override; private: std::unique_ptr<PaddleMobile<Dtype, P>> paddle_mobile_; bool Init(const PaddleMobileConfig& config); PaddleMobileConfig config_; }; } // namespace paddle_mobile
xiaohaichun/paddle-mobile
src/operators/math/math_function.h
<gh_stars>0 /* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include <cmath> #include <string> #include "framework/tensor.h" namespace paddle_mobile { namespace operators { namespace math { void set_constant(framework::Tensor *tensor, float value); template <typename T> void matmul(const framework::Tensor &matrix_a, bool trans_a, const framework::Tensor &matrix_b, bool trans_b, T alpha, framework::Tensor *matrix_out, T beta, bool relu = false, float *bias = nullptr); template <typename T, typename S> void matmul(const framework::Tensor &matrix_a, bool trans_a, const framework::Tensor &matrix_b, bool trans_b, T alpha, framework::Tensor *matrix_out, T beta, bool relu = false, S *bias = nullptr, bool addOnRow = false); template <typename T> void matmulWithBn(const framework::Tensor &matrix_a, bool trans_a, const framework::Tensor &matrix_b, bool trans_b, T alpha, framework::Tensor *matrix_out, T beta, bool relu, framework::Tensor *new_scale, framework::Tensor *new_bias, int group, float *bias = nullptr); void matmulWithPRelu(const framework::Tensor &matrix_a, bool trans_a, const framework::Tensor &matrix_b, bool trans_b, framework::Tensor *matrix_out, float *p, std::string mode, float *bias, float *bias1); template <typename DeviceType, typename T> struct ClearTensor { void operator()(framework::Tensor *tensor); }; template <typename DeviceType, typename T> struct RowwiseAdd { void operator()(const framework::Tensor &input, const framework::Tensor &vec, framework::Tensor *output); }; } // namespace math } // namespace operators } // namespace paddle_mobile
luxomansilla/flutter_api
linux/include/flutter_api/flutter_api_plugin.h
#ifndef FLUTTER_PLUGIN_FLUTTER_API_PLUGIN_H_ #define FLUTTER_PLUGIN_FLUTTER_API_PLUGIN_H_ #include <flutter_linux/flutter_linux.h> G_BEGIN_DECLS #ifdef FLUTTER_PLUGIN_IMPL #define FLUTTER_PLUGIN_EXPORT __attribute__((visibility("default"))) #else #define FLUTTER_PLUGIN_EXPORT #endif typedef struct _FlutterApiPlugin FlutterApiPlugin; typedef struct { GObjectClass parent_class; } FlutterApiPluginClass; FLUTTER_PLUGIN_EXPORT GType flutter_api_plugin_get_type(); FLUTTER_PLUGIN_EXPORT void flutter_api_plugin_register_with_registrar( FlPluginRegistrar* registrar); G_END_DECLS #endif // FLUTTER_PLUGIN_FLUTTER_API_PLUGIN_H_
kriskate/motor-on-roller-blind-ws
src/MotorsSetup.h
#include <ArduinoJson.h> #include "WebSocketsServer.h" #include <Stepper_28BYJ_48.h> int M1_1 = 13; int M1_2 = 12; int M1_3 = 14; int M1_4 = 27; Stepper_28BYJ_48 stepper_1(M1_1, M1_2, M1_3, M1_4); //Initiate stepper driver String action; //Action manual/auto int path = 0; //Direction of blind (1 = down, 0 = stop, -1 = up) int setPos = 0; //The set position 0-100% by the client long currentPosition = 0; //Current position of the blind long maxPosition = 2000000; //Max position of the blind. Initial value boolean ccw = true; //Turns counter clockwise to lower the curtain void loadMotors(JsonVariant json) { currentPosition = json["currentPosition"].as<long>(); maxPosition = json["maxPosition"].as<long>(); } /* Turn of power to coils whenever the blind is not moving */ void stopPowerToCoils() { digitalWrite(M1_1, LOW); digitalWrite(M1_2, LOW); digitalWrite(M1_3, LOW); digitalWrite(M1_4, LOW); Serial.println(F("Motor stopped")); } void motors_broadcast(WebSocketsServer webSocket, String outputTopic, void (*sendmsg)(String topic, String payload)) { int set = (setPos * 100) / maxPosition; int pos = (currentPosition * 100) / maxPosition; webSocket.broadcastTXT("{ \"set\":" + String(set) + ", \"position\":" + String(pos) + " }"); sendmsg(outputTopic, "{ \"set\":" + String(set) + ", \"position\":" + String(pos) + " }"); Serial.println(F("Stopped. Reached wanted position")); } void motors_up() { Serial.println(F("Moving up")); stepper_1.step(ccw ? 1 : -1); currentPosition = currentPosition + 1; } void motors_down() { Serial.println(F("Moving down")); stepper_1.step(ccw ? -1 : 1); currentPosition = currentPosition - 1; } void motors_auto(int path) { if (currentPosition > path) { motors_down(); } else if (currentPosition < path) { motors_up(); } } void motors_manual() { Serial.println(F("Moving motor manually")); stepper_1.step(ccw ? path : -path); currentPosition = currentPosition + path; } boolean motorsLoop(uint8_t btndn, uint8_t btnup, WebSocketsServer webSocket, String outputTopic, void (*sendmsg)(String topic, String payload)) { bool pres_cont = false; while (!digitalRead(btndn) && currentPosition > 0) { motors_down(); yield(); delay(1); pres_cont = true; } while (!digitalRead(btnup) && currentPosition < maxPosition) { motors_up(); yield(); delay(1); pres_cont = true; } if (pres_cont) { motors_broadcast(webSocket, outputTopic, sendmsg); } return pres_cont; }