text,length,is_long_context,metric_val,label_metric "// Copyright (c) 2014-2018, The Monero Project // Copyright (c) 2018, The Loki Project // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. 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. // // 3. Neither the name of the copyright holder nor the names of its 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 HOLDER 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. // // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers #include ""include_base_utils.h"" using namespace epee; #include #include #include ""wipeable_string.h"" #include ""common/i18n.h"" #include ""string_tools.h"" #include ""serialization/string.h"" #include ""cryptonote_format_utils.h"" #include ""cryptonote_config.h"" #include ""crypto/crypto.h"" #include ""crypto/hash.h"" #include ""ringct/rctSigs.h"" #include ""cryptonote_basic/verification_context.h"" #include ""cryptonote_core/service_node_deregister.h"" #undef SARONITE_DEFAULT_LOG_CATEGORY #define SARONITE_DEFAULT_LOG_CATEGORY ""cn"" #define ENCRYPTED_PAYMENT_ID_TAIL 0x8d // #define ENABLE_HASH_CASH_INTEGRITY_CHECK using namespace crypto; static const uint64_t valid_decomposed_outputs[] = { (uint64_t)1, (uint64_t)2, (uint64_t)3, (uint64_t)4, (uint64_t)5, (uint64_t)6, (uint64_t)7, (uint64_t)8, (uint64_t)9, // 1 rok (uint64_t)10, (uint64_t)20, (uint64_t)30, (uint64_t)40, (uint64_t)50, (uint64_t)60, (uint64_t)70, (uint64_t)80, (uint64_t)90, (uint64_t)100, (uint64_t)200, (uint64_t)300, (uint64_t)400, (uint64_t)500, (uint64_t)600, (uint64_t)700, (uint64_t)800, (uint64_t)900, (uint64_t)1000, (uint64_t)2000, (uint64_t)3000, (uint64_t)4000, (uint64_t)5000, (uint64_t)6000, (uint64_t)7000, (uint64_t)8000, (uint64_t)9000, (uint64_t)10000, (uint64_t)20000, (uint64_t)30000, (uint64_t)40000, (uint64_t)50000, (uint64_t)60000, (uint64_t)70000, (uint64_t)80000, (uint64_t)90000, (uint64_t)100000, (uint64_t)200000, (uint64_t)300000, (uint64_t)400000, (uint64_t)500000, (uint64_t)600000, (uint64_t)700000, (uint64_t)800000, (uint64_t)900000, (uint64_t)1000000, (uint64_t)2000000, (uint64_t)3000000, (uint64_t)4000000, (uint64_t)5000000, (uint64_t)6000000, (uint64_t)7000000, (uint64_t)8000000, (uint64_t)9000000, // 1 micronero (uint64_t)10000000, (uint64_t)20000000, (uint64_t)30000000, (uint64_t)40000000, (uint64_t)50000000, (uint64_t)60000000, (uint64_t)70000000, (uint64_t)80000000, (uint64_t)90000000, (uint64_t)100000000, (uint64_t)200000000, (uint64_t)300000000, (uint64_t)400000000, (uint64_t)500000000, (uint64_t)600000000, (uint64_t)700000000, (uint64_t)800000000, (uint64_t)900000000, (uint64_t)1000000000, (uint64_t)2000000000, (uint64_t)3000000000, (uint64_t)4000000000, (uint64_t)5000000000, (uint64_t)6000000000, (uint64_t)7000000000, (uint64_t)8000000000, (uint64_t)9000000000, (uint64_t)10000000000, (uint64_t)20000000000, (uint64_t)30000000000, (uint64_t)40000000000, (uint64_t)50000000000, (uint64_t)60000000000, (uint64_t)70000000000, (uint64_t)80000000000, (uint64_t)90000000000, (uint64_t)100000000000, (uint64_t)200000000000, (uint64_t)300000000000, (uint64_t)400000000000, (uint64_t)500000000000, (uint64_t)600000000000, (uint64_t)700000000000, (uint64_t)800000000000, (uint64_t)900000000000, (uint64_t)1000000000000, (uint64_t)2000000000000, (uint64_t)3000000000000, (uint64_t)4000000000000, (uint64_t)5000000000000, (uint64_t)6000000000000, (uint64_t)7000000000000, (uint64_t)8000000000000, (uint64_t)9000000000000, // 1 monero (uint64_t)10000000000000, (uint64_t)20000000000000, (uint64_t)30000000000000, (uint64_t)40000000000000, (uint64_t)50000000000000, (uint64_t)60000000000000, (uint64_t)70000000000000, (uint64_t)80000000000000, (uint64_t)90000000000000, (uint64_t)100000000000000, (uint64_t)200000000000000, (uint64_t)300000000000000, (uint64_t)400000000000000, (uint64_t)500000000000000, (uint64_t)600000000000000, (uint64_t)700000000000000, (uint64_t)800000000000000, (uint64_t)900000000000000, (uint64_t)1000000000000000, (uint64_t)2000000000000000, (uint64_t)3000000000000000, (uint64_t)4000000000000000, (uint64_t)5000000000000000, (uint64_t)6000000000000000, (uint64_t)7000000000000000, (uint64_t)8000000000000000, (uint64_t)9000000000000000, (uint64_t)10000000000000000, (uint64_t)20000000000000000, (uint64_t)30000000000000000, (uint64_t)40000000000000000, (uint64_t)50000000000000000, (uint64_t)60000000000000000, (uint64_t)70000000000000000, (uint64_t)80000000000000000, (uint64_t)90000000000000000, (uint64_t)100000000000000000, (uint64_t)200000000000000000, (uint64_t)300000000000000000, (uint64_t)400000000000000000, (uint64_t)500000000000000000, (uint64_t)600000000000000000, (uint64_t)700000000000000000, (uint64_t)800000000000000000, (uint64_t)900000000000000000, (uint64_t)1000000000000000000, (uint64_t)2000000000000000000, (uint64_t)3000000000000000000, (uint64_t)4000000000000000000, (uint64_t)5000000000000000000, (uint64_t)6000000000000000000, (uint64_t)7000000000000000000, (uint64_t)8000000000000000000, (uint64_t)9000000000000000000, // 1 meganero (uint64_t)10000000000000000000ull }; static std::atomic default_decimal_point(CRYPTONOTE_DISPLAY_DECIMAL_POINT); static std::atomic tx_hashes_calculated_count(0); static std::atomic tx_hashes_cached_count(0); static std::atomic block_hashes_calculated_count(0); static std::atomic block_hashes_cached_count(0); #define CHECK_AND_ASSERT_THROW_MES_L1(expr, message) {if(!(expr)) {MWARNING(message); throw std::runtime_error(message);}} namespace cryptonote { static inline unsigned char *operator &(ec_point &point) { return &reinterpret_cast(point); } static inline const unsigned char *operator &(const ec_point &point) { return &reinterpret_cast(point); } // a copy of rct::addKeys, since we can't link to libringct to avoid circular dependencies static void add_public_key(crypto::public_key &AB, const crypto::public_key &A, const crypto::public_key &B) { ge_p3 B2, A2; CHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&B2, &B) == 0, ""ge_frombytes_vartime failed at ""+boost::lexical_cast(__LINE__)); CHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&A2, &A) == 0, ""ge_frombytes_vartime failed at ""+boost::lexical_cast(__LINE__)); ge_cached tmp2; ge_p3_to_cached(&tmp2, &B2); ge_p1p1 tmp3; ge_add(&tmp3, &A2, &tmp2); ge_p1p1_to_p3(&A2, &tmp3); ge_p3_tobytes(&AB, &A2); } } namespace cryptonote { //--------------------------------------------------------------- void get_transaction_prefix_hash(const transaction_prefix& tx, crypto::hash& h) { std::ostringstream s; binary_archive a(s); ::serialization::serialize(a, const_cast(tx)); crypto::cn_fast_hash(s.str().data(), s.str().size(), h); } //--------------------------------------------------------------- crypto::hash get_transaction_prefix_hash(const transaction_prefix& tx) { crypto::hash h = null_hash; get_transaction_prefix_hash(tx, h); return h; } //--------------------------------------------------------------- bool expand_transaction_1(transaction &tx, bool base_only) { if (tx.version >= 2 && !is_coinbase(tx)) { rct::rctSig &rv = tx.rct_signatures; if (rv.outPk.size() != tx.vout.size()) { LOG_PRINT_L1(""Failed to parse transaction from blob, bad outPk size in tx "" << get_transaction_hash(tx)); return false; } for (size_t n = 0; n < tx.rct_signatures.outPk.size(); ++n) rv.outPk[n].dest = rct::pk2rct(boost::get(tx.vout[n].target).key); if (!base_only) { const bool bulletproof = rv.type == rct::RCTTypeFullBulletproof || rv.type == rct::RCTTypeSimpleBulletproof; if (bulletproof) { if (rv.p.bulletproofs.size() != tx.vout.size()) { LOG_PRINT_L1(""Failed to parse transaction from blob, bad bulletproofs size in tx "" << get_transaction_hash(tx)); return false; } for (size_t n = 0; n < rv.outPk.size(); ++n) { rv.p.bulletproofs[n].V.resize(1); rv.p.bulletproofs[n].V[0] = rv.outPk[n].mask; } } } } return true; } //--------------------------------------------------------------- bool parse_and_validate_tx_from_blob(const blobdata& tx_blob, transaction& tx) { std::stringstream ss; ss << tx_blob; binary_archive ba(ss); bool r = ::serialization::serialize(ba, tx); CHECK_AND_ASSERT_MES(r, false, ""Failed to parse transaction from blob""); CHECK_AND_ASSERT_MES(expand_transaction_1(tx, false), false, ""Failed to expand transaction data""); tx.invalidate_hashes(); return true; } //--------------------------------------------------------------- bool parse_and_validate_tx_base_from_blob(const blobdata& tx_blob, transaction& tx) { std::stringstream ss; ss << tx_blob; binary_archive ba(ss); bool r = tx.serialize_base(ba); CHECK_AND_ASSERT_MES(r, false, ""Failed to parse transaction from blob""); CHECK_AND_ASSERT_MES(expand_transaction_1(tx, true), false, ""Failed to expand transaction data""); return true; } //--------------------------------------------------------------- bool parse_and_validate_tx_from_blob(const blobdata& tx_blob, transaction& tx, crypto::hash& tx_hash, crypto::hash& tx_prefix_hash) { std::stringstream ss; ss << tx_blob; binary_archive ba(ss); bool r = ::serialization::serialize(ba, tx); CHECK_AND_ASSERT_MES(r, false, ""Failed to parse transaction from blob""); CHECK_AND_ASSERT_MES(expand_transaction_1(tx, false), false, ""Failed to expand transaction data""); tx.invalidate_hashes(); //TODO: validate tx get_transaction_hash(tx, tx_hash); get_transaction_prefix_hash(tx, tx_prefix_hash); return true; } //--------------------------------------------------------------- bool generate_key_image_helper(const account_keys& ack, const std::unordered_map& subaddresses, const crypto::public_key& out_key, const crypto::public_key& tx_public_key, const std::vector& additional_tx_public_keys, size_t real_output_index, keypair& in_ephemeral, crypto::key_image& ki, hw::device &hwdev) { crypto::key_derivation recv_derivation = AUTO_VAL_INIT(recv_derivation); bool r = hwdev.generate_key_derivation(tx_public_key, ack.m_view_secret_key, recv_derivation); CHECK_AND_ASSERT_MES(r, false, ""key image helper: failed to generate_key_derivation("" << tx_public_key << "", "" << ack.m_view_secret_key << "")""); std::vector additional_recv_derivations; for (size_t i = 0; i < additional_tx_public_keys.size(); ++i) { crypto::key_derivation additional_recv_derivation = AUTO_VAL_INIT(additional_recv_derivation); r = hwdev.generate_key_derivation(additional_tx_public_keys[i], ack.m_view_secret_key, additional_recv_derivation); CHECK_AND_ASSERT_MES(r, false, ""key image helper: failed to generate_key_derivation("" << additional_tx_public_keys[i] << "", "" << ack.m_view_secret_key << "")""); additional_recv_derivations.push_back(additional_recv_derivation); } boost::optional subaddr_recv_info = is_out_to_acc_precomp(subaddresses, out_key, recv_derivation, additional_recv_derivations, real_output_index,hwdev); CHECK_AND_ASSERT_MES(subaddr_recv_info, false, ""key image helper: given output pubkey doesn't seem to belong to this address""); return generate_key_image_helper_precomp(ack, out_key, subaddr_recv_info->derivation, real_output_index, subaddr_recv_info->index, in_ephemeral, ki, hwdev); } //--------------------------------------------------------------- bool generate_key_image_helper_precomp(const account_keys& ack, const crypto::public_key& out_key, const crypto::key_derivation& recv_derivation, size_t real_output_index, const subaddress_index& received_index, keypair& in_ephemeral, crypto::key_image& ki, hw::device &hwdev) { if (ack.m_spend_secret_key == crypto::null_skey) { // for watch-only wallet, simply copy the known output pubkey in_ephemeral.pub = out_key; in_ephemeral.sec = crypto::null_skey; } else { // derive secret key with subaddress - step 1: original CN derivation crypto::secret_key scalar_step1; hwdev.derive_secret_key(recv_derivation, real_output_index, ack.m_spend_secret_key, scalar_step1); // computes Hs(a*R || idx) + b // step 2: add Hs(a || index_major || index_minor) crypto::secret_key subaddr_sk; crypto::secret_key scalar_step2; if (received_index.is_zero()) { scalar_step2 = scalar_step1; // treat index=(0,0) as a special case representing the main address } else { subaddr_sk = hwdev.get_subaddress_secret_key(ack.m_view_secret_key, received_index); hwdev.sc_secret_add(scalar_step2, scalar_step1,subaddr_sk); } in_ephemeral.sec = scalar_step2; if (ack.m_multisig_keys.empty()) { // when not in multisig, we know the full spend secret key, so the output pubkey can be obtained by scalarmultBase CHECK_AND_ASSERT_MES(hwdev.secret_key_to_public_key(in_ephemeral.sec, in_ephemeral.pub), false, ""Failed to derive public key""); } else { // when in multisig, we only know the partial spend secret key. but we do know the full spend public key, so the output pubkey can be obtained by using the standard CN key derivation CHECK_AND_ASSERT_MES(hwdev.derive_public_key(recv_derivation, real_output_index, ack.m_account_address.m_spend_public_key, in_ephemeral.pub), false, ""Failed to derive public key""); // and don't forget to add the contribution from the subaddress part if (!received_index.is_zero()) { crypto::public_key subaddr_pk; CHECK_AND_ASSERT_MES(hwdev.secret_key_to_public_key(subaddr_sk, subaddr_pk), false, ""Failed to derive public key""); add_public_key(in_ephemeral.pub, in_ephemeral.pub, subaddr_pk); } } CHECK_AND_ASSERT_MES(in_ephemeral.pub == out_key, false, ""key image helper precomp: given output pubkey doesn't match the derived one""); } hwdev.generate_key_image(in_ephemeral.pub, in_ephemeral.sec, ki); return true; } //--------------------------------------------------------------- uint64_t power_integral(uint64_t a, uint64_t b) { if(b == 0) return 1; uint64_t total = a; for(uint64_t i = 1; i != b; i++) total *= a; return total; } //--------------------------------------------------------------- bool parse_amount(uint64_t& amount, const std::string& str_amount_) { std::string str_amount = str_amount_; boost::algorithm::trim(str_amount); size_t point_index = str_amount.find_first_of('.'); size_t fraction_size; if (std::string::npos != point_index) { fraction_size = str_amount.size() - point_index - 1; while (default_decimal_point < fraction_size && '0' == str_amount.back()) { str_amount.erase(str_amount.size() - 1, 1); --fraction_size; } if (default_decimal_point < fraction_size) return false; str_amount.erase(point_index, 1); } else { fraction_size = 0; } if (str_amount.empty()) return false; if (fraction_size < default_decimal_point) { str_amount.append(default_decimal_point - fraction_size, '0'); } return string_tools::get_xtype_from_string(amount, str_amount); } //--------------------------------------------------------------- bool get_tx_fee(const transaction& tx, uint64_t & fee) { if (tx.version > 1) { fee = tx.rct_signatures.txnFee; return true; } uint64_t amount_in = 0; uint64_t amount_out = 0; for(auto& in: tx.vin) { CHECK_AND_ASSERT_MES(in.type() == typeid(txin_to_key), 0, ""unexpected type id in transaction""); amount_in += boost::get(in).amount; } for(auto& o: tx.vout) amount_out += o.amount; CHECK_AND_ASSERT_MES(amount_in >= amount_out, false, ""transaction spend ("" <& tx_extra, std::vector& tx_extra_fields) { tx_extra_fields.clear(); if(tx_extra.empty()) return true; std::string extra_str(reinterpret_cast(tx_extra.data()), tx_extra.size()); std::istringstream iss(extra_str); binary_archive ar(iss); bool eof = false; while (!eof) { tx_extra_field field; bool r = ::do_serialize(ar, field); CHECK_AND_NO_ASSERT_MES_L1(r, false, ""failed to deserialize extra field. extra = "" << string_tools::buff_to_hex_nodelimer(std::string(reinterpret_cast(tx_extra.data()), tx_extra.size()))); tx_extra_fields.push_back(field); std::ios_base::iostate state = iss.rdstate(); eof = (EOF == iss.peek()); iss.clear(state); } CHECK_AND_NO_ASSERT_MES_L1(::serialization::check_stream_state(ar), false, ""failed to deserialize extra field. extra = "" << string_tools::buff_to_hex_nodelimer(std::string(reinterpret_cast(tx_extra.data()), tx_extra.size()))); return true; } //--------------------------------------------------------------- crypto::public_key get_tx_pub_key_from_extra(const std::vector& tx_extra, size_t pk_index) { std::vector tx_extra_fields; parse_tx_extra(tx_extra, tx_extra_fields); tx_extra_pub_key pub_key_field; if(!find_tx_extra_field_by_type(tx_extra_fields, pub_key_field, pk_index)) return null_pkey; return pub_key_field.pub_key; } //--------------------------------------------------------------- crypto::public_key get_tx_pub_key_from_extra(const transaction_prefix& tx_prefix, size_t pk_index) { return get_tx_pub_key_from_extra(tx_prefix.extra, pk_index); } //--------------------------------------------------------------- crypto::public_key get_tx_pub_key_from_extra(const transaction& tx, size_t pk_index) { return get_tx_pub_key_from_extra(tx.extra, pk_index); } //--------------------------------------------------------------- static void add_data_to_tx_extra(std::vector& tx_extra, char const *data, size_t data_size, uint8_t tag) { size_t pos = tx_extra.size(); tx_extra.resize(tx_extra.size() + sizeof(tag) + data_size); tx_extra[pos++] = tag; std::memcpy(&tx_extra[pos], data, data_size); } //--------------------------------------------------------------- void add_tx_pub_key_to_extra(transaction& tx, const crypto::public_key& tx_pub_key) { add_tx_pub_key_to_extra(tx.extra, tx_pub_key); } //--------------------------------------------------------------- void add_tx_pub_key_to_extra(transaction_prefix& tx, const crypto::public_key& tx_pub_key) { add_tx_pub_key_to_extra(tx.extra, tx_pub_key); } //--------------------------------------------------------------- void add_tx_pub_key_to_extra(std::vector& tx_extra, const crypto::public_key& tx_pub_key) { add_data_to_tx_extra(tx_extra, reinterpret_cast(&tx_pub_key), sizeof(tx_pub_key), TX_EXTRA_TAG_PUBKEY); } //--------------------------------------------------------------- std::vector get_additional_tx_pub_keys_from_extra(const std::vector& tx_extra) { // parse std::vector tx_extra_fields; parse_tx_extra(tx_extra, tx_extra_fields); // find corresponding field tx_extra_additional_pub_keys additional_pub_keys; if(!find_tx_extra_field_by_type(tx_extra_fields, additional_pub_keys)) return {}; return additional_pub_keys.data; } //--------------------------------------------------------------- std::vector get_additional_tx_pub_keys_from_extra(const transaction_prefix& tx) { return get_additional_tx_pub_keys_from_extra(tx.extra); } //--------------------------------------------------------------- bool add_additional_tx_pub_keys_to_extra(std::vector& tx_extra, const std::vector& additional_pub_keys) { // convert to variant tx_extra_field field = tx_extra_additional_pub_keys{ additional_pub_keys }; // serialize std::ostringstream oss; binary_archive ar(oss); bool r = ::do_serialize(ar, field); CHECK_AND_NO_ASSERT_MES_L1(r, false, ""failed to serialize tx extra additional tx pub keys""); // append std::string tx_extra_str = oss.str(); size_t pos = tx_extra.size(); tx_extra.resize(tx_extra.size() + tx_extra_str.size()); memcpy(&tx_extra[pos], tx_extra_str.data(), tx_extra_str.size()); return true; } //--------------------------------------------------------------- bool add_extra_nonce_to_tx_extra(std::vector& tx_extra, const blobdata& extra_nonce) { CHECK_AND_ASSERT_MES(extra_nonce.size() <= TX_EXTRA_NONCE_MAX_COUNT, false, ""extra nonce could be 255 bytes max""); size_t start_pos = tx_extra.size(); tx_extra.resize(tx_extra.size() + 2 + extra_nonce.size()); //write tag tx_extra[start_pos] = TX_EXTRA_NONCE; //write len ++start_pos; tx_extra[start_pos] = static_cast(extra_nonce.size()); //write data ++start_pos; memcpy(&tx_extra[start_pos], extra_nonce.data(), extra_nonce.size()); return true; } //--------------------------------------------------------------- bool add_service_node_deregister_to_tx_extra(std::vector& tx_extra, const tx_extra_service_node_deregister& deregistration) { tx_extra_field field = tx_extra_service_node_deregister{deregistration.block_height, deregistration.service_node_index, deregistration.votes}; std::ostringstream oss; binary_archive ar(oss); bool r = ::do_serialize(ar, field); CHECK_AND_ASSERT_MES(r, false, ""failed to serialize tx extra service node deregister""); std::string tx_extra_str = oss.str(); size_t pos = tx_extra.size(); tx_extra.resize(tx_extra.size() + tx_extra_str.size()); memcpy(&tx_extra[pos], tx_extra_str.data(), tx_extra_str.size()); return true; } //--------------------------------------------------------------- void add_service_node_pubkey_to_tx_extra(std::vector& tx_extra, const crypto::public_key& pubkey) { add_data_to_tx_extra(tx_extra, reinterpret_cast(&pubkey), sizeof(pubkey), TX_EXTRA_TAG_SERVICE_NODE_PUBKEY); } //--------------------------------------------------------------- bool get_service_node_pubkey_from_tx_extra(const std::vector& tx_extra, crypto::public_key& pubkey) { std::vector tx_extra_fields; parse_tx_extra(tx_extra, tx_extra_fields); tx_extra_service_node_pubkey service_node_pubkey; bool result = find_tx_extra_field_by_type(tx_extra_fields, service_node_pubkey); if (!result) return false; pubkey = service_node_pubkey.m_service_node_key; return true; } //--------------------------------------------------------------- void add_service_node_contributor_to_tx_extra(std::vector& tx_extra, const cryptonote::account_public_address& address) { add_data_to_tx_extra(tx_extra, reinterpret_cast(&address), sizeof(address), TX_EXTRA_TAG_SERVICE_NODE_CONTRIBUTOR); } //--------------------------------------------------------------- bool get_tx_secret_key_from_tx_extra(const std::vector& tx_extra, crypto::secret_key& key) { std::vector tx_extra_fields; parse_tx_extra(tx_extra, tx_extra_fields); tx_extra_tx_secret_key seckey; bool result = find_tx_extra_field_by_type(tx_extra_fields, seckey); if (!result) return false; key = seckey.key; return true; } //--------------------------------------------------------------- void add_tx_secret_key_to_tx_extra(std::vector& tx_extra, const crypto::secret_key& key) { add_data_to_tx_extra(tx_extra, reinterpret_cast(&key), sizeof(key), TX_EXTRA_TAG_TX_SECRET_KEY); } //--------------------------------------------------------------- bool get_service_node_contributor_from_tx_extra(const std::vector& tx_extra, cryptonote::account_public_address& address) { std::vector tx_extra_fields; parse_tx_extra(tx_extra, tx_extra_fields); tx_extra_service_node_contributor contributor; bool result = find_tx_extra_field_by_type(tx_extra_fields, contributor); if (!result) return false; address.m_spend_public_key = contributor.m_spend_public_key; address.m_view_public_key = contributor.m_view_public_key; return true; } //--------------------------------------------------------------- bool get_service_node_register_from_tx_extra(const std::vector& tx_extra, tx_extra_service_node_register ®istration) { std::vector tx_extra_fields; parse_tx_extra(tx_extra, tx_extra_fields); bool result = find_tx_extra_field_by_type(tx_extra_fields, registration); return result && registration.m_public_spend_keys.size() == registration.m_public_view_keys.size(); } //--------------------------------------------------------------- bool add_service_node_register_to_tx_extra( std::vector& tx_extra, const std::vector& addresses, uint64_t portions_for_operator, const std::vector& portions, uint64_t expiration_timestamp, const crypto::signature& service_node_signature) { if (addresses.size() != portions.size()) { LOG_ERROR(""Tried to serialize registration with more addresses than portions, this should never happen""); return false; } std::vector public_view_keys(addresses.size()); std::vector public_spend_keys(addresses.size()); for (size_t i = 0; i < addresses.size(); i++) { public_view_keys[i] = addresses[i].m_view_public_key; public_spend_keys[i] = addresses[i].m_spend_public_key; } // convert to variant tx_extra_field field = tx_extra_service_node_register{ public_spend_keys, public_view_keys, portions_for_operator, portions, expiration_timestamp, service_node_signature }; // serialize std::ostringstream oss; binary_archive ar(oss); bool r = ::do_serialize(ar, field); CHECK_AND_NO_ASSERT_MES_L1(r, false, ""failed to serialize tx extra registration tx""); // append std::string tx_extra_str = oss.str(); size_t pos = tx_extra.size(); tx_extra.resize(tx_extra.size() + tx_extra_str.size()); memcpy(&tx_extra[pos], tx_extra_str.data(), tx_extra_str.size()); return true; } //--------------------------------------------------------------- void add_service_node_winner_to_tx_extra(std::vector& tx_extra, const crypto::public_key& winner) { add_data_to_tx_extra(tx_extra, reinterpret_cast(&winner), sizeof(winner), TX_EXTRA_TAG_SERVICE_NODE_WINNER); } //--------------------------------------------------------------- bool get_service_node_deregister_from_tx_extra(const std::vector& tx_extra, tx_extra_service_node_deregister &deregistration) { std::vector tx_extra_fields; parse_tx_extra(tx_extra, tx_extra_fields); bool result = find_tx_extra_field_by_type(tx_extra_fields, deregistration); return result; } //--------------------------------------------------------------- crypto::public_key get_service_node_winner_from_tx_extra(const std::vector& tx_extra) { // parse std::vector tx_extra_fields; parse_tx_extra(tx_extra, tx_extra_fields); // find corresponding field tx_extra_service_node_winner winner; if (!find_tx_extra_field_by_type(tx_extra_fields, winner)) return crypto::null_pkey; return winner.m_service_node_key; } //--------------------------------------------------------------- bool remove_field_from_tx_extra(std::vector& tx_extra, const std::type_info &type) { if (tx_extra.empty()) return true; std::string extra_str(reinterpret_cast(tx_extra.data()), tx_extra.size()); std::istringstream iss(extra_str); binary_archive ar(iss); std::ostringstream oss; binary_archive newar(oss); bool eof = false; while (!eof) { tx_extra_field field; bool r = ::do_serialize(ar, field); CHECK_AND_NO_ASSERT_MES_L1(r, false, ""failed to deserialize extra field. extra = "" << string_tools::buff_to_hex_nodelimer(std::string(reinterpret_cast(tx_extra.data()), tx_extra.size()))); if (field.type() != type) ::do_serialize(newar, field); std::ios_base::iostate state = iss.rdstate(); eof = (EOF == iss.peek()); iss.clear(state); } CHECK_AND_NO_ASSERT_MES_L1(::serialization::check_stream_state(ar), false, ""failed to deserialize extra field. extra = "" << string_tools::buff_to_hex_nodelimer(std::string(reinterpret_cast(tx_extra.data()), tx_extra.size()))); tx_extra.clear(); std::string s = oss.str(); tx_extra.reserve(s.size()); std::copy(s.begin(), s.end(), std::back_inserter(tx_extra)); return true; } //--------------------------------------------------------------- void set_payment_id_to_tx_extra_nonce(blobdata& extra_nonce, const crypto::hash& payment_id) { extra_nonce.clear(); extra_nonce.push_back(TX_EXTRA_NONCE_PAYMENT_ID); const uint8_t* payment_id_ptr = reinterpret_cast(&payment_id); std::copy(payment_id_ptr, payment_id_ptr + sizeof(payment_id), std::back_inserter(extra_nonce)); } //--------------------------------------------------------------- void set_encrypted_payment_id_to_tx_extra_nonce(blobdata& extra_nonce, const crypto::hash8& payment_id) { extra_nonce.clear(); extra_nonce.push_back(TX_EXTRA_NONCE_ENCRYPTED_PAYMENT_ID); const uint8_t* payment_id_ptr = reinterpret_cast(&payment_id); std::copy(payment_id_ptr, payment_id_ptr + sizeof(payment_id), std::back_inserter(extra_nonce)); } //--------------------------------------------------------------- bool get_payment_id_from_tx_extra_nonce(const blobdata& extra_nonce, crypto::hash& payment_id) { if(sizeof(crypto::hash) + 1 != extra_nonce.size()) return false; if(TX_EXTRA_NONCE_PAYMENT_ID != extra_nonce[0]) return false; payment_id = *reinterpret_cast(extra_nonce.data() + 1); return true; } //--------------------------------------------------------------- bool get_encrypted_payment_id_from_tx_extra_nonce(const blobdata& extra_nonce, crypto::hash8& payment_id) { if(sizeof(crypto::hash8) + 1 != extra_nonce.size()) return false; if (TX_EXTRA_NONCE_ENCRYPTED_PAYMENT_ID != extra_nonce[0]) return false; payment_id = *reinterpret_cast(extra_nonce.data() + 1); return true; } //--------------------------------------------------------------- bool get_inputs_money_amount(const transaction& tx, uint64_t& money) { money = 0; for(const auto& in: tx.vin) { CHECKED_GET_SPECIFIC_VARIANT(in, const txin_to_key, tokey_in, false); money += tokey_in.amount; } return true; } //--------------------------------------------------------------- uint64_t get_block_height(const block& b) { CHECK_AND_ASSERT_MES(b.miner_tx.vin.size() == 1, 0, ""wrong miner tx in block: "" << get_block_hash(b) << "", b.miner_tx.vin.size() != 1""); CHECKED_GET_SPECIFIC_VARIANT(b.miner_tx.vin[0], const txin_gen, coinbase_in, 0); return coinbase_in.height; } //--------------------------------------------------------------- bool check_inputs_types_supported(const transaction& tx) { for(const auto& in: tx.vin) { CHECK_AND_ASSERT_MES(in.type() == typeid(txin_to_key), false, ""wrong variant type: "" << in.type().name() << "", expected "" << typeid(txin_to_key).name() << "", in transaction id="" << get_transaction_hash(tx)); } return true; } //----------------------------------------------------------------------------------------------- bool check_outs_valid(const transaction& tx) { if (tx.is_deregister_tx()) { CHECK_AND_NO_ASSERT_MES(tx.vout.size() == 0, false, ""tx version deregister must have 0 outputs, received: "" << tx.vout.size() << "", id="" << get_transaction_hash(tx)); } if (tx.version >= 3) { CHECK_AND_NO_ASSERT_MES(tx.vout.size() == tx.output_unlock_times.size(), false, ""tx version 3 must have equal number of output unlock times and outputs""); } for(const tx_out& out: tx.vout) { CHECK_AND_ASSERT_MES(out.target.type() == typeid(txout_to_key), false, ""wrong variant type: "" << out.target.type().name() << "", expected "" << typeid(txout_to_key).name() << "", in transaction id="" << get_transaction_hash(tx)); if (tx.version == 1) { CHECK_AND_NO_ASSERT_MES(0 < out.amount, false, ""zero amount output in transaction id="" << get_transaction_hash(tx)); } if(!check_key(boost::get(out.target).key)) return false; } return true; } //----------------------------------------------------------------------------------------------- bool check_money_overflow(const transaction& tx) { return check_inputs_overflow(tx) && check_outs_overflow(tx); } //--------------------------------------------------------------- bool check_inputs_overflow(const transaction& tx) { uint64_t money = 0; for(const auto& in: tx.vin) { CHECKED_GET_SPECIFIC_VARIANT(in, const txin_to_key, tokey_in, false); if(money > tokey_in.amount + money) return false; money += tokey_in.amount; } return true; } //--------------------------------------------------------------- bool check_outs_overflow(const transaction& tx) { uint64_t money = 0; for(const auto& o: tx.vout) { if(money > o.amount + money) return false; money += o.amount; } return true; } //--------------------------------------------------------------- uint64_t get_outs_money_amount(const transaction& tx) { uint64_t outputs_amount = 0; for(const auto& o: tx.vout) outputs_amount += o.amount; return outputs_amount; } //--------------------------------------------------------------- std::string short_hash_str(const crypto::hash& h) { std::string res = string_tools::pod_to_hex(h); CHECK_AND_ASSERT_MES(res.size() == 64, res, ""wrong hash256 with string_tools::pod_to_hex conversion""); auto erased_pos = res.erase(8, 48); res.insert(8, ""....""); return res; } //--------------------------------------------------------------- bool is_out_to_acc(const account_keys& acc, const txout_to_key& out_key, const crypto::public_key& tx_pub_key, const std::vector& additional_tx_pub_keys, size_t output_index) { crypto::key_derivation derivation; bool r = acc.get_device().generate_key_derivation(tx_pub_key, acc.m_view_secret_key, derivation); CHECK_AND_ASSERT_MES(r, false, ""Failed to generate key derivation""); crypto::public_key pk; r = acc.get_device().derive_public_key(derivation, output_index, acc.m_account_address.m_spend_public_key, pk); CHECK_AND_ASSERT_MES(r, false, ""Failed to derive public key""); if (pk == out_key.key) return true; // try additional tx pubkeys if available if (!additional_tx_pub_keys.empty()) { CHECK_AND_ASSERT_MES(output_index < additional_tx_pub_keys.size(), false, ""wrong number of additional tx pubkeys""); r = acc.get_device().generate_key_derivation(additional_tx_pub_keys[output_index], acc.m_view_secret_key, derivation); CHECK_AND_ASSERT_MES(r, false, ""Failed to generate key derivation""); r = acc.get_device().derive_public_key(derivation, output_index, acc.m_account_address.m_spend_public_key, pk); CHECK_AND_ASSERT_MES(r, false, ""Failed to derive public key""); return pk == out_key.key; } return false; } //--------------------------------------------------------------- boost::optional is_out_to_acc_precomp(const std::unordered_map& subaddresses, const crypto::public_key& out_key, const crypto::key_derivation& derivation, const std::vector& additional_derivations, size_t output_index, hw::device &hwdev) { // try the shared tx pubkey crypto::public_key subaddress_spendkey; hwdev.derive_subaddress_public_key(out_key, derivation, output_index, subaddress_spendkey); auto found = subaddresses.find(subaddress_spendkey); if (found != subaddresses.end()) return subaddress_receive_info{ found->second, derivation }; // try additional tx pubkeys if available if (!additional_derivations.empty()) { CHECK_AND_ASSERT_MES(output_index < additional_derivations.size(), boost::none, ""wrong number of additional derivations""); hwdev.derive_subaddress_public_key(out_key, additional_derivations[output_index], output_index, subaddress_spendkey); found = subaddresses.find(subaddress_spendkey); if (found != subaddresses.end()) return subaddress_receive_info{ found->second, additional_derivations[output_index] }; } return boost::none; } //--------------------------------------------------------------- bool lookup_acc_outs(const account_keys& acc, const transaction& tx, std::vector& outs, uint64_t& money_transfered) { crypto::public_key tx_pub_key = get_tx_pub_key_from_extra(tx); if(null_pkey == tx_pub_key) return false; std::vector additional_tx_pub_keys = get_additional_tx_pub_keys_from_extra(tx); return lookup_acc_outs(acc, tx, tx_pub_key, additional_tx_pub_keys, outs, money_transfered); } //--------------------------------------------------------------- bool lookup_acc_outs(const account_keys& acc, const transaction& tx, const crypto::public_key& tx_pub_key, const std::vector& additional_tx_pub_keys, std::vector& outs, uint64_t& money_transfered) { CHECK_AND_ASSERT_MES(additional_tx_pub_keys.empty() || additional_tx_pub_keys.size() == tx.vout.size(), false, ""wrong number of additional pubkeys"" ); money_transfered = 0; size_t i = 0; for(const tx_out& o: tx.vout) { CHECK_AND_ASSERT_MES(o.target.type() == typeid(txout_to_key), false, ""wrong type id in transaction out"" ); if(is_out_to_acc(acc, boost::get(o.target), tx_pub_key, additional_tx_pub_keys, i)) { outs.push_back(i); money_transfered += o.amount; } i++; } return true; } //--------------------------------------------------------------- void get_blob_hash(const blobdata& blob, crypto::hash& res) { cn_fast_hash(blob.data(), blob.size(), res); } //--------------------------------------------------------------- void set_default_decimal_point(unsigned int decimal_point) { switch (decimal_point) { case 9: case 6: case 3: case 0: default_decimal_point = decimal_point; break; default: ASSERT_MES_AND_THROW(""Invalid decimal point specification: "" << decimal_point); } } //--------------------------------------------------------------- unsigned int get_default_decimal_point() { return default_decimal_point; } //--------------------------------------------------------------- std::string get_unit(unsigned int decimal_point) { if (decimal_point == (unsigned int)-1) decimal_point = default_decimal_point; switch (decimal_point) { case 9: return ""saronite""; case 6: return ""megarok""; case 3: return ""kilorok""; case 0: return ""rok""; default: ASSERT_MES_AND_THROW(""Invalid decimal point specification: "" << decimal_point); } } //--------------------------------------------------------------- std::string print_money(uint64_t amount, unsigned int decimal_point) { if (decimal_point == (unsigned int)-1) decimal_point = default_decimal_point; std::string s = std::to_string(amount); if(s.size() < decimal_point+1) { s.insert(0, decimal_point+1 - s.size(), '0'); } if (decimal_point > 0) s.insert(s.size() - decimal_point, "".""); return s; } //--------------------------------------------------------------- char const *print_tx_verification_context(tx_verification_context const &tvc, transaction const *tx) { static char buf[1024]; buf[0] = 0; char *bufPtr = buf; char *bufEnd = buf + sizeof(buf); if (tvc.m_verifivation_failed) bufPtr += snprintf(bufPtr, bufEnd - bufPtr, ""Verification failed, connection should be dropped, ""); //bad tx, should drop connection if (tvc.m_verifivation_impossible) bufPtr += snprintf(bufPtr, bufEnd - bufPtr, ""Verification impossible, related to alt chain, ""); //the transaction is related with an alternative blockchain if (tvc.m_should_be_relayed) bufPtr += snprintf(bufPtr, bufEnd - bufPtr, ""TX should be relayed, ""); if (tvc.m_added_to_pool) bufPtr += snprintf(bufPtr, bufEnd - bufPtr, ""TX added to pool, ""); if (tvc.m_low_mixin) bufPtr += snprintf(bufPtr, bufEnd - bufPtr, ""Insufficient mixin, ""); if (tvc.m_double_spend) bufPtr += snprintf(bufPtr, bufEnd - bufPtr, ""Double spend TX, ""); if (tvc.m_invalid_input) bufPtr += snprintf(bufPtr, bufEnd - bufPtr, ""Invalid inputs, ""); if (tvc.m_invalid_output) bufPtr += snprintf(bufPtr, bufEnd - bufPtr, ""Invalid outputs, ""); if (tvc.m_too_big) bufPtr += snprintf(bufPtr, bufEnd - bufPtr, ""TX too big, ""); if (tvc.m_overspend) bufPtr += snprintf(bufPtr, bufEnd - bufPtr, ""Overspend, ""); if (tvc.m_fee_too_low) bufPtr += snprintf(bufPtr, bufEnd - bufPtr, ""Fee too low, ""); if (tvc.m_not_rct) bufPtr += snprintf(bufPtr, bufEnd - bufPtr, ""TX is not a valid RCT TX., ""); if (tvc.m_invalid_version) bufPtr += snprintf(bufPtr, bufEnd - bufPtr, ""TX has invalid version, ""); if (tx) bufPtr += snprintf(bufPtr, bufEnd - bufPtr, ""TX Version: %d"", (int)tx->version); return buf; } //--------------------------------------------------------------- char const *print_vote_verification_context(vote_verification_context const &vvc, saronite::service_node_deregister::vote const *vote) { static char buf[1024]; buf[0] = 0; char *bufPtr = buf; char *bufEnd = buf + sizeof(buf); if (vvc.m_invalid_block_height) bufPtr += snprintf(bufPtr, bufEnd - bufPtr, ""Invalid block height: %s, "", vote ? std::to_string(vote->block_height).c_str() : ""??""); if (vvc.m_duplicate_voters) bufPtr += snprintf(bufPtr, bufEnd - bufPtr, ""Voters quorum index was duplicated: %s, "",vote ? std::to_string(vote->voters_quorum_index).c_str() : ""??""); if (vvc.m_voters_quorum_index_out_of_bounds) bufPtr += snprintf(bufPtr, bufEnd - bufPtr, ""Voters quorum index out of bounds: %s, "", vote ? std::to_string(vote->voters_quorum_index).c_str() : ""??""); if (vvc.m_service_node_index_out_of_bounds) bufPtr += snprintf(bufPtr, bufEnd - bufPtr, ""Service node index out of bounds: %s, "", vote ? std::to_string(vote->service_node_index).c_str() : ""??""); if (vvc.m_signature_not_valid) bufPtr += snprintf(bufPtr, bufEnd - bufPtr, ""Signature not valid, ""); if (vvc.m_added_to_pool) bufPtr += snprintf(bufPtr, bufEnd - bufPtr, ""Added to pool, ""); if (vvc.m_full_tx_deregister_made) bufPtr += snprintf(bufPtr, bufEnd - bufPtr, ""Full TX deregister made, ""); if (vvc.m_not_enough_votes) bufPtr += snprintf(bufPtr, bufEnd - bufPtr, ""Not enough votes, ""); return buf; } //--------------------------------------------------------------- crypto::hash get_blob_hash(const blobdata& blob) { crypto::hash h = null_hash; get_blob_hash(blob, h); return h; } //--------------------------------------------------------------- crypto::hash get_transaction_hash(const transaction& t) { crypto::hash h = null_hash; get_transaction_hash(t, h, NULL); return h; } //--------------------------------------------------------------- bool get_transaction_hash(const transaction& t, crypto::hash& res) { return get_transaction_hash(t, res, NULL); } //--------------------------------------------------------------- bool calculate_transaction_prunable_hash(const transaction& t, crypto::hash& res) { if (t.version == 1) return false; transaction &tt = const_cast(t); std::stringstream ss; binary_archive ba(ss); const size_t inputs = t.vin.size(); const size_t outputs = t.vout.size(); const size_t mixin = t.vin.empty() ? 0 : t.vin[0].type() == typeid(txin_to_key) ? boost::get(t.vin[0]).key_offsets.size() - 1 : 0; bool r = tt.rct_signatures.p.serialize_rctsig_prunable(ba, t.rct_signatures.type, inputs, outputs, mixin); CHECK_AND_ASSERT_MES(r, false, ""Failed to serialize rct signatures prunable""); cryptonote::get_blob_hash(ss.str(), res); return true; } //--------------------------------------------------------------- crypto::hash get_transaction_prunable_hash(const transaction& t) { crypto::hash res; CHECK_AND_ASSERT_THROW_MES(calculate_transaction_prunable_hash(t, res), ""Failed to calculate tx prunable hash""); return res; } //--------------------------------------------------------------- crypto::hash get_pruned_transaction_hash(const transaction& t, const crypto::hash &pruned_data_hash) { // v1 transactions hash the entire blob CHECK_AND_ASSERT_THROW_MES(t.version > 1, ""Hash for pruned v1 tx cannot be calculated""); // v2 transactions hash different parts together, than hash the set of those hashes crypto::hash hashes[3]; // prefix get_transaction_prefix_hash(t, hashes[0]); transaction &tt = const_cast(t); // base rct { std::stringstream ss; binary_archive ba(ss); const size_t inputs = t.vin.size(); const size_t outputs = t.vout.size(); bool r = tt.rct_signatures.serialize_rctsig_base(ba, inputs, outputs); CHECK_AND_ASSERT_THROW_MES(r, ""Failed to serialize rct signatures base""); cryptonote::get_blob_hash(ss.str(), hashes[1]); } // prunable rct hashes[2] = pruned_data_hash; // the tx hash is the hash of the 3 hashes crypto::hash res = cn_fast_hash(hashes, sizeof(hashes)); return res; } //--------------------------------------------------------------- bool calculate_transaction_hash(const transaction& t, crypto::hash& res, size_t* blob_size) { // v1 transactions hash the entire blob if (t.version == 1) { size_t ignored_blob_size, &blob_size_ref = blob_size ? *blob_size : ignored_blob_size; return get_object_hash(t, res, blob_size_ref); } // v2 transactions hash different parts together, than hash the set of those hashes crypto::hash hashes[3]; // prefix get_transaction_prefix_hash(t, hashes[0]); transaction &tt = const_cast(t); // base rct { std::stringstream ss; binary_archive ba(ss); const size_t inputs = t.vin.size(); const size_t outputs = t.vout.size(); bool r = tt.rct_signatures.serialize_rctsig_base(ba, inputs, outputs); CHECK_AND_ASSERT_MES(r, false, ""Failed to serialize rct signatures base""); cryptonote::get_blob_hash(ss.str(), hashes[1]); } // prunable rct if (t.rct_signatures.type == rct::RCTTypeNull) { hashes[2] = crypto::null_hash; } else { CHECK_AND_ASSERT_MES(calculate_transaction_prunable_hash(t, hashes[2]), false, ""Failed to get tx prunable hash""); } // the tx hash is the hash of the 3 hashes res = cn_fast_hash(hashes, sizeof(hashes)); // we still need the size if (blob_size) *blob_size = get_object_blobsize(t); return true; } //--------------------------------------------------------------- bool get_registration_hash(const std::vector& addresses, uint64_t operator_portions, const std::vector& portions, uint64_t expiration_timestamp, crypto::hash& hash) { if (addresses.size() != portions.size()) { LOG_ERROR(""get_registration_hash addresses.size() != portions.size()""); return false; } uint64_t portions_left = STAKING_PORTIONS; for (uint64_t portion : portions) { if (portion > portions_left) { LOG_ERROR(tr(""Your registration has more than "") << STAKING_PORTIONS << tr("" portions, this registration is invalid!"")); return false; } portions_left -= portion; } size_t size = addresses.size() * (sizeof(cryptonote::account_public_address) + sizeof(uint64_t)) + sizeof(uint64_t) + sizeof(uint64_t); char* buffer = new char[size]; char* buffer_iter = buffer; memcpy(buffer_iter, &operator_portions, sizeof(operator_portions)); buffer_iter += sizeof(operator_portions); for (size_t i = 0; i < addresses.size(); i++) { memcpy(buffer_iter, &addresses[i], sizeof(cryptonote::account_public_address)); buffer_iter += sizeof(cryptonote::account_public_address); memcpy(buffer_iter, &portions[i], sizeof(uint64_t)); buffer_iter += sizeof(uint64_t); } memcpy(buffer_iter, &expiration_timestamp, sizeof(expiration_timestamp)); buffer_iter += sizeof(expiration_timestamp); assert(buffer + size == buffer_iter); crypto::cn_fast_hash(buffer, size, hash); delete[] buffer; return true; } //--------------------------------------------------------------- bool get_transaction_hash(const transaction& t, crypto::hash& res, size_t* blob_size) { if (t.is_hash_valid()) { #ifdef ENABLE_HASH_CASH_INTEGRITY_CHECK CHECK_AND_ASSERT_THROW_MES(!calculate_transaction_hash(t, res, blob_size) || t.hash == res, ""tx hash cash integrity failure""); #endif res = t.hash; if (blob_size) { if (!t.is_blob_size_valid()) { t.blob_size = get_object_blobsize(t); t.set_blob_size_valid(true); } *blob_size = t.blob_size; } ++tx_hashes_cached_count; return true; } ++tx_hashes_calculated_count; bool ret = calculate_transaction_hash(t, res, blob_size); if (!ret) return false; t.hash = res; t.set_hash_valid(true); if (blob_size) { t.blob_size = *blob_size; t.set_blob_size_valid(true); } return true; } //--------------------------------------------------------------- bool get_transaction_hash(const transaction& t, crypto::hash& res, size_t& blob_size) { return get_transaction_hash(t, res, &blob_size); } //--------------------------------------------------------------- blobdata get_block_hashing_blob(const block& b) { blobdata blob = t_serializable_object_to_blob(static_cast(b)); crypto::hash tree_root_hash = get_tx_tree_hash(b); blob.append(reinterpret_cast(&tree_root_hash), sizeof(tree_root_hash)); blob.append(tools::get_varint_data(b.tx_hashes.size()+1)); return blob; } //--------------------------------------------------------------- bool calculate_block_hash(const block& b, crypto::hash& res) { // EXCEPTION FOR BLOCK 202612 const std::string correct_blob_hash_202612 = ""3a8a2b3a29b50fc86ff73dd087ea43c6f0d6b8f936c849194d5c84c737903966""; const std::string existing_block_id_202612 = ""bbd604d2ba11ba27935e006ed39c9bfdd99b76bf4a50654bc1e1e61217962698""; crypto::hash block_blob_hash = get_blob_hash(block_to_blob(b)); if (string_tools::pod_to_hex(block_blob_hash) == correct_blob_hash_202612) { string_tools::hex_to_pod(existing_block_id_202612, res); return true; } bool hash_result = get_object_hash(get_block_hashing_blob(b), res); if (hash_result) { // make sure that we aren't looking at a block with the 202612 block id but not the correct blobdata if (string_tools::pod_to_hex(res) == existing_block_id_202612) { LOG_ERROR(""Block with block id for 202612 but incorrect block blob hash found!""); res = null_hash; return false; } } return hash_result; } //--------------------------------------------------------------- bool get_block_hash(const block& b, crypto::hash& res) { if (b.is_hash_valid()) { #ifdef ENABLE_HASH_CASH_INTEGRITY_CHECK CHECK_AND_ASSERT_THROW_MES(!calculate_block_hash(b, res) || b.hash == res, ""block hash cash integrity failure""); #endif res = b.hash; ++block_hashes_cached_count; return true; } ++block_hashes_calculated_count; bool ret = calculate_block_hash(b, res); if (!ret) return false; b.hash = res; b.set_hash_valid(true); return true; } //--------------------------------------------------------------- crypto::hash get_block_hash(const block& b) { crypto::hash p = null_hash; get_block_hash(b, p); return p; } //--------------------------------------------------------------- bool get_block_longhash(const block& b, crypto::hash& res, uint64_t height) { blobdata bd = get_block_hashing_blob(b); const int cn_variant; if (b.major_version < 7) { cn_variant = 0; } else if (b.major_version =< 9) { cn_variant = 1; } else { cn_variant = 2; } crypto::cn_slow_hash(bd.data(), bd.size(), res, cn_variant); return true; } //--------------------------------------------------------------- std::vector relative_output_offsets_to_absolute(const std::vector& off) { std::vector res = off; for(size_t i = 1; i < res.size(); i++) res[i] += res[i-1]; return res; } //--------------------------------------------------------------- std::vector absolute_output_offsets_to_relative(const std::vector& off) { std::vector res = off; if(!off.size()) return res; std::sort(res.begin(), res.end());//just to be sure, actually it is already should be sorted for(size_t i = res.size()-1; i != 0; i--) res[i] -= res[i-1]; return res; } //--------------------------------------------------------------- crypto::hash get_block_longhash(const block& b, uint64_t height) { crypto::hash p = null_hash; get_block_longhash(b, p, height); return p; } //--------------------------------------------------------------- bool parse_and_validate_block_from_blob(const blobdata& b_blob, block& b) { std::stringstream ss; ss << b_blob; binary_archive ba(ss); bool r = ::serialization::serialize(ba, b); CHECK_AND_ASSERT_MES(r, false, ""Failed to parse block from blob""); b.invalidate_hashes(); b.miner_tx.invalidate_hashes(); return true; } //--------------------------------------------------------------- blobdata block_to_blob(const block& b) { return t_serializable_object_to_blob(b); } //--------------------------------------------------------------- bool block_to_blob(const block& b, blobdata& b_blob) { return t_serializable_object_to_blob(b, b_blob); } //--------------------------------------------------------------- blobdata tx_to_blob(const transaction& tx) { return t_serializable_object_to_blob(tx); } //--------------------------------------------------------------- bool tx_to_blob(const transaction& tx, blobdata& b_blob) { return t_serializable_object_to_blob(tx, b_blob); } //--------------------------------------------------------------- void get_tx_tree_hash(const std::vector& tx_hashes, crypto::hash& h) { tree_hash(tx_hashes.data(), tx_hashes.size(), h); } //--------------------------------------------------------------- crypto::hash get_tx_tree_hash(const std::vector& tx_hashes) { crypto::hash h = null_hash; get_tx_tree_hash(tx_hashes, h); return h; } //--------------------------------------------------------------- crypto::hash get_tx_tree_hash(const block& b) { std::vector txs_ids; crypto::hash h = null_hash; size_t bl_sz = 0; get_transaction_hash(b.miner_tx, h, bl_sz); txs_ids.push_back(h); for(auto& th: b.tx_hashes) txs_ids.push_back(th); return get_tx_tree_hash(txs_ids); } //--------------------------------------------------------------- bool is_valid_decomposed_amount(uint64_t amount) { const uint64_t *begin = valid_decomposed_outputs; const uint64_t *end = valid_decomposed_outputs + sizeof(valid_decomposed_outputs) / sizeof(valid_decomposed_outputs[0]); return std::binary_search(begin, end, amount); } //--------------------------------------------------------------- void get_hash_stats(uint64_t &tx_hashes_calculated, uint64_t &tx_hashes_cached, uint64_t &block_hashes_calculated, uint64_t & block_hashes_cached) { tx_hashes_calculated = tx_hashes_calculated_count; tx_hashes_cached = tx_hashes_cached_count; block_hashes_calculated = block_hashes_calculated_count; block_hashes_cached = block_hashes_cached_count; } //--------------------------------------------------------------- crypto::secret_key encrypt_key(crypto::secret_key key, const epee::wipeable_string &passphrase) { crypto::hash hash; crypto::cn_slow_hash(passphrase.data(), passphrase.size(), hash); sc_add((unsigned char*)key.data, (const unsigned char*)key.data, (const unsigned char*)hash.data); return key; } //--------------------------------------------------------------- crypto::secret_key decrypt_key(crypto::secret_key key, const epee::wipeable_string &passphrase) { crypto::hash hash; crypto::cn_slow_hash(passphrase.data(), passphrase.size(), hash); sc_sub((unsigned char*)key.data, (const unsigned char*)key.data, (const unsigned char*)hash.data); return key; } } ",16360,True,2717.8809204771173,median "//// DO NOT EDIT THIS FILE. IT WAS GENERATED. Manual changes to this file will be lost when it is generated again. Edit the files in the src/main/asciidoc/ directory instead. //// :jdkversion: 1.8 :github-tag: master :github-repo: spring-cloud/spring-cloud-stream-binder-rabbit :github-raw: https://raw.githubusercontent.com/{github-repo}/{github-tag} :github-code: https://github.com/{github-repo}/tree/{github-tag} image::https://circleci.com/gh/spring-cloud/spring-cloud-stream-binder-rabbit.svg?style=svg[""CircleCI"", link=""https://circleci.com/gh/spring-cloud/spring-cloud-stream-binder-rabbit""] image::https://codecov.io/gh/spring-cloud/spring-cloud-stream-binder-rabbit/branch/{github-tag}/graph/badge.svg[""codecov"", link=""https://codecov.io/gh/spring-cloud/spring-cloud-stream-binder-rabbit""] image::https://badges.gitter.im/spring-cloud/spring-cloud-stream-binder-rabbit.svg[Gitter, link=""https://gitter.im/spring-cloud/spring-cloud-stream-binder-rabbit?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge""] // ====================================================================================== //= Overview [partintro] -- This guide describes the RabbitMQ implementation of the Spring Cloud Stream Binder. It contains information about its design, usage and configuration options, as well as information on how the Stream Cloud Stream concepts map into RabbitMQ specific constructs. -- == Usage To use the RabbitMQ binder, you can add it to your Spring Cloud Stream application, by using the following Maven coordinates: [source,xml] ---- org.springframework.cloud spring-cloud-stream-binder-rabbit ---- Alternatively, you can use the Spring Cloud Stream RabbitMQ Starter, as follows: [source,xml] ---- org.springframework.cloud spring-cloud-starter-stream-rabbit ---- == RabbitMQ Binder Overview The following simplified diagram shows how the RabbitMQ binder operates: .RabbitMQ Binder image::{github-raw}/docs/src/main/asciidoc/images/rabbit-binder.png[width=300,scaledwidth=""50%""] By default, the RabbitMQ Binder implementation maps each destination to a `TopicExchange`. For each consumer group, a `Queue` is bound to that `TopicExchange`. Each consumer instance has a corresponding RabbitMQ `Consumer` instance for its group's `Queue`. For partitioned producers and consumers, the queues are suffixed with the partition index and use the partition index as the routing key. For anonymous consumers (those with no `group` property), an auto-delete queue (with a randomized unique name) is used. By using the optional `autoBindDlq` option, you can configure the binder to create and configure dead-letter queues (DLQs) (and a dead-letter exchange `DLX`, as well as routing infrastructure). By default, the dead letter queue has the name of the destination, appended with `.dlq`. If retry is enabled (`maxAttempts > 1`), failed messages are delivered to the DLQ after retries are exhausted. If retry is disabled (`maxAttempts = 1`), you should set `requeueRejected` to `false` (the default) so that failed messages are routed to the DLQ, instead of being re-queued. In addition, `republishToDlq` causes the binder to publish a failed message to the DLQ (instead of rejecting it). This feature lets additional information (such as the stack trace in the `x-exception-stacktrace` header) be added to the message in headers. See the <> for information about truncated stack traces. This option does not need retry enabled. You can republish a failed message after just one attempt. Starting with version 1.2, you can configure the delivery mode of republished messages. See the <>. If the stream listener throws an `ImmediateAcknowledgeAmqpException`, the DLQ is bypassed and the message simply discarded. Starting with version 2.1, this is true regardless of the setting of `republishToDlq`; previously it was only the case when `republishToDlq` was `false`. IMPORTANT: Setting `requeueRejected` to `true` (with `republishToDlq=false` ) causes the message to be re-queued and redelivered continually, which is likely not what you want unless the reason for the failure is transient. In general, you should enable retry within the binder by setting `maxAttempts` to greater than one or by setting `republishToDlq` to `true`. Starting with version 3.1.2, if the consumer is marked as `transacted`, publishing to the DLQ will participate in the transaction. This allows the transaction to roll back if the publishing fails for some reason (for example, if the user is not authorized to publish to the dead letter exchange). In addition, if the connection factory is configured for publisher confirms or returns, the publication to the DLQ will wait for the confirmation and check for a returned message. If a negative acknowledgment or returned message is received, the binder will throw an `AmqpRejectAndDontRequeueException`, allowing the broker to take care of publishing to the DLQ as if the `republishToDlq` property is `false`. See <> for more information about these properties. The framework does not provide any standard mechanism to consume dead-letter messages (or to re-route them back to the primary queue). Some options are described in <>. NOTE: When multiple RabbitMQ binders are used in a Spring Cloud Stream application, it is important to disable 'RabbitAutoConfiguration' to avoid the same configuration from `RabbitAutoConfiguration` being applied to the two binders. You can exclude the class by using the `@SpringBootApplication` annotation. Starting with version 2.0, the `RabbitMessageChannelBinder` sets the `RabbitTemplate.userPublisherConnection` property to `true` so that the non-transactional producers avoid deadlocks on consumers, which can happen if cached connections are blocked because of a https://www.rabbitmq.com/memory.html[memory alarm] on the broker. NOTE: Currently, a `multiplex` consumer (a single consumer listening to multiple queues) is only supported for message-driven consumers; polled consumers can only retrieve messages from a single queue. == Configuration Options This section contains settings specific to the RabbitMQ Binder and bound channels. For general binding configuration options and properties, see the https://cloud.spring.io/spring-cloud-static/spring-cloud-stream/current/reference/html/spring-cloud-stream.html#_configuration_options[Spring Cloud Stream core documentation]. [[rabbit-binder-properties]] === RabbitMQ Binder Properties By default, the RabbitMQ binder uses Spring Boot's `ConnectionFactory`. Conseuqently, it supports all Spring Boot configuration options for RabbitMQ. (For reference, see the https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#common-application-properties[Spring Boot documentation]). RabbitMQ configuration options use the `spring.rabbitmq` prefix. In addition to Spring Boot options, the RabbitMQ binder supports the following properties: spring.cloud.stream.rabbit.binder.adminAddresses:: A comma-separated list of RabbitMQ management plugin URLs. Only used when `nodes` contains more than one entry. Each entry in this list must have a corresponding entry in `spring.rabbitmq.addresses`. Only needed if you use a RabbitMQ cluster and wish to consume from the node that hosts the queue. See https://docs.spring.io/spring-amqp/reference/html/#queue-affinity[Queue Affinity and the LocalizedQueueConnectionFactory] for more information. + Default: empty. spring.cloud.stream.rabbit.binder.nodes:: A comma-separated list of RabbitMQ node names. When more than one entry, used to locate the server address where a queue is located. Each entry in this list must have a corresponding entry in `spring.rabbitmq.addresses`. Only needed if you use a RabbitMQ cluster and wish to consume from the node that hosts the queue. See https://docs.spring.io/spring-amqp/reference/html/_reference.html#queue-affinity[Queue Affinity and the LocalizedQueueConnectionFactory] for more information. + Default: empty. spring.cloud.stream.rabbit.binder.compressionLevel:: The compression level for compressed bindings. See `java.util.zip.Deflater`. + Default: `1` (BEST_LEVEL). spring.cloud.stream.binder.connection-name-prefix:: A connection name prefix used to name the connection(s) created by this binder. The name is this prefix followed by `#n`, where `n` increments each time a new connection is opened. + Default: none (Spring AMQP default). === RabbitMQ Consumer Properties The following properties are available for Rabbit consumers only and must be prefixed with `spring.cloud.stream.rabbit.bindings..consumer.`. However if the same set of properties needs to be applied to most bindings, to avoid repetition, Spring Cloud Stream supports setting values for all channels, in the format of `spring.cloud.stream.rabbit.default.=`. Also, keep in mind that binding specific property will override its equivalent in the default. acknowledgeMode:: The acknowledge mode. + Default: `AUTO`. anonymousGroupPrefix:: When the binding has no `group` property, an anonymous, auto-delete queue is bound to the destination exchange. The default naming stragegy for such queues results in a queue named `anonymous.`. Set this property to change the prefix to something other than the default. + Default: `anonymous.`. autoBindDlq:: Whether to automatically declare the DLQ and bind it to the binder DLX. + Default: `false`. bindingRoutingKey:: The routing key with which to bind the queue to the exchange (if `bindQueue` is `true`). Can be multiple keys - see `bindingRoutingKeyDelimiter`. For partitioned destinations, `-` is appended to each key. + Default: `#`. bindingRoutingKeyDelimiter:: When this is not null, 'bindingRoutingKey' is considered to be a list of keys delimited by this value; often a comma is used. + Default: `null`. bindQueue:: Whether to declare the queue and bind it to the destination exchange. Set it to `false` if you have set up your own infrastructure and have previously created and bound the queue. + Default: `true`. consumerTagPrefix:: Used to create the consumer tag(s); will be appended by `#n` where `n` increments for each consumer created. Example: `${spring.application.name}-${spring.cloud.stream.bindings.input.group}-${spring.cloud.stream.instance-index}`. + Default: none - the broker will generate random consumer tags. containerType:: Select the type of listener container to be used. See https://docs.spring.io/spring-amqp/reference/html/_reference.html#choose-container[Choosing a Container] in the Spring AMQP documentation for more information. + Default: `simple` deadLetterQueueName:: The name of the DLQ + Default: `prefix+destination.dlq` deadLetterExchange:: A DLX to assign to the queue. Relevant only if `autoBindDlq` is `true`. + Default: 'prefix+DLX' deadLetterExchangeType:: The type of the DLX to assign to the queue. Relevant only if `autoBindDlq` is `true`. + Default: 'direct' deadLetterRoutingKey:: A dead letter routing key to assign to the queue. Relevant only if `autoBindDlq` is `true`. + Default: `destination` declareDlx:: Whether to declare the dead letter exchange for the destination. Relevant only if `autoBindDlq` is `true`. Set to `false` if you have a pre-configured DLX. + Default: `true`. declareExchange:: Whether to declare the exchange for the destination. + Default: `true`. delayedExchange:: Whether to declare the exchange as a `Delayed Message Exchange`. Requires the delayed message exchange plugin on the broker. The `x-delayed-type` argument is set to the `exchangeType`. + Default: `false`. dlqBindingArguments:: Arguments applied when binding the dlq to the dead letter exchange; used with `headers` `deadLetterExchangeType` to specify headers to match on. For example `...dlqBindingArguments.x-match=any`, `...dlqBindingArguments.someHeader=someValue`. + Default: empty dlqDeadLetterExchange:: If a DLQ is declared, a DLX to assign to that queue. + Default: `none` dlqDeadLetterRoutingKey:: If a DLQ is declared, a dead letter routing key to assign to that queue. + Default: `none` dlqExpires:: How long before an unused dead letter queue is deleted (in milliseconds). + Default: `no expiration` dlqLazy:: Declare the dead letter queue with the `x-queue-mode=lazy` argument. See https://www.rabbitmq.com/lazy-queues.html[""`Lazy Queues`""]. Consider using a policy instead of this setting, because using a policy allows changing the setting without deleting the queue. + Default: `false`. dlqMaxLength:: Maximum number of messages in the dead letter queue. + Default: `no limit` dlqMaxLengthBytes:: Maximum number of total bytes in the dead letter queue from all messages. + Default: `no limit` dlqMaxPriority:: Maximum priority of messages in the dead letter queue (0-255). + Default: `none` dlqOverflowBehavior:: Action to take when `dlqMaxLength` or `dlqMaxLengthBytes` is exceeded; currently `drop-head` or `reject-publish` but refer to the RabbitMQ documentation. + Default: `none` dlqQuorum.deliveryLimit:: When `quorum.enabled=true`, set a delivery limit after which the message is dropped or dead-lettered. + Default: none - broker default will apply. dlqQuorum.enabled:: When true, create a quorum dead letter queue instead of a classic queue. + Default: false dlqQuorum.initialQuorumSize:: When `quorum.enabled=true`, set the initial quorum size. + Default: none - broker default will apply. dlqSingleActiveConsumer:: Set to true to set the `x-single-active-consumer` queue property to true. + Default: `false` dlqTtl:: Default time to live to apply to the dead letter queue when declared (in milliseconds). + Default: `no limit` durableSubscription:: Whether the subscription should be durable. Only effective if `group` is also set. + Default: `true`. exchangeAutoDelete:: If `declareExchange` is true, whether the exchange should be auto-deleted (that is, removed after the last queue is removed). + Default: `true`. exchangeDurable:: If `declareExchange` is true, whether the exchange should be durable (that is, it survives broker restart). + Default: `true`. exchangeType:: The exchange type: `direct`, `fanout`, `headers` or `topic` for non-partitioned destinations and `direct`, headers or `topic` for partitioned destinations. + Default: `topic`. exclusive:: Whether to create an exclusive consumer. Concurrency should be 1 when this is `true`. Often used when strict ordering is required but enabling a hot standby instance to take over after a failure. See `recoveryInterval`, which controls how often a standby instance attempts to consume. Consider using `singleActiveConsumer` instead when using RabbitMQ 3.8 or later. + Default: `false`. expires:: How long before an unused queue is deleted (in milliseconds). + Default: `no expiration` failedDeclarationRetryInterval:: The interval (in milliseconds) between attempts to consume from a queue if it is missing. + Default: 5000 [[spring-cloud-stream-rabbit-frame-max-headroom]] frameMaxHeadroom:: The number of bytes to reserve for other headers when adding the stack trace to a DLQ message header. All headers must fit within the `frame_max` size configured on the broker. Stack traces can be large; if the size plus this property exceeds `frame_max` then the stack trace will be truncated. A WARN log will be written; consider increasing the `frame_max` or reducing the stack trace by catching the exception and throwing one with a smaller stack trace. + Default: 20000 headerPatterns:: Patterns for headers to be mapped from inbound messages. + Default: `['*']` (all headers). lazy:: Declare the queue with the `x-queue-mode=lazy` argument. See https://www.rabbitmq.com/lazy-queues.html[""`Lazy Queues`""]. Consider using a policy instead of this setting, because using a policy allows changing the setting without deleting the queue. + Default: `false`. maxConcurrency:: The maximum number of consumers. Not supported when the `containerType` is `direct`. + Default: `1`. maxLength:: The maximum number of messages in the queue. + Default: `no limit` maxLengthBytes:: The maximum number of total bytes in the queue from all messages. + Default: `no limit` maxPriority:: The maximum priority of messages in the queue (0-255). + Default: `none` missingQueuesFatal:: When the queue cannot be found, whether to treat the condition as fatal and stop the listener container. Defaults to `false` so that the container keeps trying to consume from the queue -- for example, when using a cluster and the node hosting a non-HA queue is down. + Default: `false` overflowBehavior:: Action to take when `maxLength` or `maxLengthBytes` is exceeded; currently `drop-head` or `reject-publish` but refer to the RabbitMQ documentation. + Default: `none` prefetch:: Prefetch count. + Default: `1`. prefix:: A prefix to be added to the name of the `destination` and queues. + Default: """". queueBindingArguments:: Arguments applied when binding the queue to the exchange; used with `headers` `exchangeType` to specify headers to match on. For example `...queueBindingArguments.x-match=any`, `...queueBindingArguments.someHeader=someValue`. + Default: empty queueDeclarationRetries:: The number of times to retry consuming from a queue if it is missing. Relevant only when `missingQueuesFatal` is `true`. Otherwise, the container keeps retrying indefinitely. Not supported when the `containerType` is `direct`. + Default: `3` queueNameGroupOnly:: When true, consume from a queue with a name equal to the `group`. Otherwise the queue name is `destination.group`. This is useful, for example, when using Spring Cloud Stream to consume from an existing RabbitMQ queue. + Default: false. quorum.deliveryLimit:: When `quorum.enabled=true`, set a delivery limit after which the message is dropped or dead-lettered. + Default: none - broker default will apply. quorum.enabled:: When true, create a quorum queue instead of a classic queue. + Default: false quorum.initialQuorumSize:: When `quorum.enabled=true`, set the initial quorum size. + Default: none - broker default will apply. recoveryInterval:: The interval between connection recovery attempts, in milliseconds. + Default: `5000`. requeueRejected:: Whether delivery failures should be re-queued when retry is disabled or `republishToDlq` is `false`. + Default: `false`. [[spring-cloud-stream-rabbit-republish-delivery-mode]] republishDeliveryMode:: When `republishToDlq` is `true`, specifies the delivery mode of the republished message. + Default: `DeliveryMode.PERSISTENT` republishToDlq:: By default, messages that fail after retries are exhausted are rejected. If a dead-letter queue (DLQ) is configured, RabbitMQ routes the failed message (unchanged) to the DLQ. If set to `true`, the binder republishs failed messages to the DLQ with additional headers, including the exception message and stack trace from the cause of the final failure. Also see the <>. + Default: `true` singleActiveConsumer:: Set to true to set the `x-single-active-consumer` queue property to true. + Default: `false` transacted:: Whether to use transacted channels. + Default: `false`. ttl:: Default time to live to apply to the queue when declared (in milliseconds). + Default: `no limit` txSize:: The number of deliveries between acks. Not supported when the `containerType` is `direct`. + Default: `1`. === Advanced Listener Container Configuration To set listener container properties that are not exposed as binder or binding properties, add a single bean of type `ListenerContainerCustomizer` to the application context. The binder and binding properties will be set and then the customizer will be called. The customizer (`configure()` method) is provided with the queue name as well as the consumer group as arguments. === Advanced Queue/Exchange/Binding Configuration From time to time, the RabbitMQ team add new features that are enabled by setting some argument when declaring, for example, a queue. Generally, such features are enabled in the binder by adding appropriate properties, but this may not be immediately available in a current version. Starting with version 3.0.1, you can now add `DeclarableCustomizer` bean(s) to the application context to modify a `Declarable` (`Queue`, `Exchange` or `Binding`) just before the declaration is performed. This allows you to add arguments that are not currently directly supported by the binder. [[rabbit-receiving-batch]] === Receiving Batched Messages With the RabbitMQ binder, there are two types of batches handled by consumer bindings: ==== Batches Created by Producers Normally, if a producer binding has `batch-enabled=true` (see <>), or a message is created by a `BatchingRabbitTemplate`, elements of the batch are returned as individual calls to the listener method. Starting with version 3.0, any such batch can be presented as a `List` to the listener method if `spring.cloud.stream.bindings..consumer.batch-mode` is set to `true`. ==== Consumer-side Batching Starting with version 3.1, the consumer can be configured to assemble multiple inbound messages into a batch which is presented to the application as a `List` of converted payloads. The following simple application demonstrates how to use this technique: ==== [source, properties] ---- spring.cloud.stream.bindings.input-in-0.group=someGroup spring.cloud.stream.bindings.input-in-0.consumer.batch-mode=true spring.cloud.stream.rabbit.bindings.input-in-0.consumer.enable-batching=true spring.cloud.stream.rabbit.bindings.input-in-0.consumer.batch-size=10 spring.cloud.stream.rabbit.bindings.input-in-0.consumer.receive-timeout=200 ---- ==== ==== [source, java] ---- @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean Consumer> input() { return list -> { System.out.println(""Received "" + list.size()); list.forEach(thing -> { System.out.println(thing); // ... }); }; } @Bean public ApplicationRunner runner(RabbitTemplate template) { return args -> { template.convertAndSend(""input-in-0.someGroup"", ""{\\""field\\"":\\""value1\\""}""); template.convertAndSend(""input-in-0.someGroup"", ""{\\""field\\"":\\""value2\\""}""); }; } public static class Thing { private String field; public Thing() { } public Thing(String field) { this.field = field; } public String getField() { return this.field; } public void setField(String field) { this.field = field; } @Override public String toString() { return ""Thing [field="" + this.field + ""]""; } } } ---- ==== ==== [source] ---- Received 2 Thing [field=value1] Thing [field=value2] ---- ==== The number of messages in a batch is specified by the `batch-size` and `receive-timeout` properties; if the `receive-timeout` elapses with no new messages, a ""short"" batch is delivered. IMPORTANT: Consumer-side batching is only supported with `container-type=simple` (the default). If you wish to examine headers of consumer-side batched messages, you should consume `Message>`; the headers are a `List>` in a header `AmqpInboundChannelAdapter.CONSOLIDATED_HEADERS`, with the headers for each payload element in the corresponding index. Again, here is a simple example: ==== [source, java] ---- @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean Consumer>> input() { return msg -> { List things = msg.getPayload(); System.out.println(""Received "" + things.size()); @SuppressWarnings(""unchecked"") List> headers = (List>) msg.getHeaders().get(AmqpInboundChannelAdapter.CONSOLIDATED_HEADERS); for (int i = 0; i < things.size(); i++) { System.out.println(things.get(i) + "" myHeader="" + headers.get(i).get(""myHeader"")); // ... } }; } @Bean public ApplicationRunner runner(RabbitTemplate template) { return args -> { template.convertAndSend(""input-in-0.someGroup"", ""{\\""field\\"":\\""value1\\""}"", msg -> { msg.getMessageProperties().setHeader(""myHeader"", ""headerValue1""); return msg; }); template.convertAndSend(""input-in-0.someGroup"", ""{\\""field\\"":\\""value2\\""}"", msg -> { msg.getMessageProperties().setHeader(""myHeader"", ""headerValue2""); return msg; }); }; } public static class Thing { private String field; public Thing() { } public Thing(String field) { this.field = field; } public String getfield() { return this.field; } public void setfield(String field) { this.field = field; } @Override public String toString() { return ""Thing [field="" + this.field + ""]""; } } } ---- ==== ==== [source] ---- Received 2 Thing [field=value1] myHeader=headerValue1 Thing [field=value2] myHeader=headerValue2 ---- ==== [[rabbit-prod-props]] === Rabbit Producer Properties The following properties are available for Rabbit producers only and must be prefixed with `spring.cloud.stream.rabbit.bindings..producer.`. However if the same set of properties needs to be applied to most bindings, to avoid repetition, Spring Cloud Stream supports setting values for all channels, in the format of `spring.cloud.stream.rabbit.default.=`. Also, keep in mind that binding specific property will override its equivalent in the default. autoBindDlq:: Whether to automatically declare the DLQ and bind it to the binder DLX. + Default: `false`. batchingEnabled:: Whether to enable message batching by producers. Messages are batched into one message according to the following properties (described in the next three entries in this list): 'batchSize', `batchBufferLimit`, and `batchTimeout`. See https://docs.spring.io/spring-amqp//reference/html/_reference.html#template-batching[Batching] for more information. Also see <>. + Default: `false`. batchSize:: The number of messages to buffer when batching is enabled. + Default: `100`. batchBufferLimit:: The maximum buffer size when batching is enabled. + Default: `10000`. batchTimeout:: The batch timeout when batching is enabled. + Default: `5000`. bindingRoutingKey:: The routing key with which to bind the queue to the exchange (if `bindQueue` is `true`). Can be multiple keys - see `bindingRoutingKeyDelimiter`. For partitioned destinations, `-n` is appended to each key. Only applies if `requiredGroups` are provided and then only to those groups. + Default: `#`. bindingRoutingKeyDelimiter:: When this is not null, 'bindingRoutingKey' is considered to be a list of keys delimited by this value; often a comma is used. Only applies if `requiredGroups` are provided and then only to those groups. + Default: `null`. bindQueue:: Whether to declare the queue and bind it to the destination exchange. Set it to `false` if you have set up your own infrastructure and have previously created and bound the queue. Only applies if `requiredGroups` are provided and then only to those groups. + Default: `true`. compress:: Whether data should be compressed when sent. + Default: `false`. confirmAckChannel:: When `errorChannelEnabled` is true, a channel to which to send positive delivery acknowledgments (aka publisher confirms). If the channel does not exist, a `DirectChannel` is registered with this name. The connection factory must be configured to enable publisher confirms. Mutually exclusive with `useConfirmHeader`. + Default: `nullChannel` (acks are discarded). deadLetterQueueName:: The name of the DLQ Only applies if `requiredGroups` are provided and then only to those groups. + Default: `prefix+destination.dlq` deadLetterExchange:: A DLX to assign to the queue. Relevant only when `autoBindDlq` is `true`. Applies only when `requiredGroups` are provided and then only to those groups. + Default: 'prefix+DLX' deadLetterExchangeType:: The type of the DLX to assign to the queue. Relevant only if `autoBindDlq` is `true`. Applies only when `requiredGroups` are provided and then only to those groups. + Default: 'direct' deadLetterRoutingKey:: A dead letter routing key to assign to the queue. Relevant only when `autoBindDlq` is `true`. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `destination` declareDlx:: Whether to declare the dead letter exchange for the destination. Relevant only if `autoBindDlq` is `true`. Set to `false` if you have a pre-configured DLX. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `true`. declareExchange:: Whether to declare the exchange for the destination. + Default: `true`. delayExpression:: A SpEL expression to evaluate the delay to apply to the message (`x-delay` header). It has no effect if the exchange is not a delayed message exchange. + Default: No `x-delay` header is set. delayedExchange:: Whether to declare the exchange as a `Delayed Message Exchange`. Requires the delayed message exchange plugin on the broker. The `x-delayed-type` argument is set to the `exchangeType`. + Default: `false`. deliveryMode:: The delivery mode. + Default: `PERSISTENT`. dlqBindingArguments:: Arguments applied when binding the dlq to the dead letter exchange; used with `headers` `deadLetterExchangeType` to specify headers to match on. For example `...dlqBindingArguments.x-match=any`, `...dlqBindingArguments.someHeader=someValue`. Applies only when `requiredGroups` are provided and then only to those groups. + Default: empty dlqDeadLetterExchange:: When a DLQ is declared, a DLX to assign to that queue. Applies only if `requiredGroups` are provided and then only to those groups. + Default: `none` dlqDeadLetterRoutingKey:: When a DLQ is declared, a dead letter routing key to assign to that queue. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `none` dlqExpires:: How long (in milliseconds) before an unused dead letter queue is deleted. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `no expiration` dlqLazy:: Declare the dead letter queue with the `x-queue-mode=lazy` argument. See https://www.rabbitmq.com/lazy-queues.html[""`Lazy Queues`""]. Consider using a policy instead of this setting, because using a policy allows changing the setting without deleting the queue. Applies only when `requiredGroups` are provided and then only to those groups. + dlqMaxLength:: Maximum number of messages in the dead letter queue. Applies only if `requiredGroups` are provided and then only to those groups. + Default: `no limit` dlqMaxLengthBytes:: Maximum number of total bytes in the dead letter queue from all messages. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `no limit` dlqMaxPriority:: Maximum priority of messages in the dead letter queue (0-255) Applies only when `requiredGroups` are provided and then only to those groups. + Default: `none` dlqQuorum.deliveryLimit:: When `quorum.enabled=true`, set a delivery limit after which the message is dropped or dead-lettered. Applies only when `requiredGroups` are provided and then only to those groups. + Default: none - broker default will apply. dlqQuorum.enabled:: When true, create a quorum dead letter queue instead of a classic queue. Applies only when `requiredGroups` are provided and then only to those groups. + Default: false dlqQuorum.initialQuorumSize:: When `quorum.enabled=true`, set the initial quorum size. Applies only when `requiredGroups` are provided and then only to those groups. + Default: none - broker default will apply. dlqSingleActiveConsumer:: Set to true to set the `x-single-active-consumer` queue property to true. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `false` dlqTtl:: Default time (in milliseconds) to live to apply to the dead letter queue when declared. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `no limit` exchangeAutoDelete:: If `declareExchange` is `true`, whether the exchange should be auto-delete (it is removed after the last queue is removed). + Default: `true`. exchangeDurable:: If `declareExchange` is `true`, whether the exchange should be durable (survives broker restart). + Default: `true`. exchangeType:: The exchange type: `direct`, `fanout`, `headers` or `topic` for non-partitioned destinations and `direct`, `headers` or `topic` for partitioned destinations. + Default: `topic`. expires:: How long (in milliseconds) before an unused queue is deleted. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `no expiration` headerPatterns:: Patterns for headers to be mapped to outbound messages. + Default: `['*']` (all headers). lazy:: Declare the queue with the `x-queue-mode=lazy` argument. See https://www.rabbitmq.com/lazy-queues.html[""`Lazy Queues`""]. Consider using a policy instead of this setting, because using a policy allows changing the setting without deleting the queue. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `false`. maxLength:: Maximum number of messages in the queue. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `no limit` maxLengthBytes:: Maximum number of total bytes in the queue from all messages. Only applies if `requiredGroups` are provided and then only to those groups. + Default: `no limit` maxPriority:: Maximum priority of messages in the queue (0-255). Only applies if `requiredGroups` are provided and then only to those groups. + Default: `none` prefix:: A prefix to be added to the name of the `destination` exchange. + Default: """". queueBindingArguments:: Arguments applied when binding the queue to the exchange; used with `headers` `exchangeType` to specify headers to match on. For example `...queueBindingArguments.x-match=any`, `...queueBindingArguments.someHeader=someValue`. Applies only when `requiredGroups` are provided and then only to those groups. + Default: empty queueNameGroupOnly:: When `true`, consume from a queue with a name equal to the `group`. Otherwise the queue name is `destination.group`. This is useful, for example, when using Spring Cloud Stream to consume from an existing RabbitMQ queue. Applies only when `requiredGroups` are provided and then only to those groups. + Default: false. quorum.deliveryLimit:: When `quorum.enabled=true`, set a delivery limit after which the message is dropped or dead-lettered. Applies only when `requiredGroups` are provided and then only to those groups. + Default: none - broker default will apply. quorum.enabled:: When true, create a quorum queue instead of a classic queue. Applies only when `requiredGroups` are provided and then only to those groups. + Default: false quorum.initialQuorumSize:: When `quorum.enabled=true`, set the initial quorum size. Applies only when `requiredGroups` are provided and then only to those groups. + Default: none - broker default will apply. routingKeyExpression:: A SpEL expression to determine the routing key to use when publishing messages. For a fixed routing key, use a literal expression, such as `routingKeyExpression='my.routingKey'` in a properties file or `routingKeyExpression: '''my.routingKey'''` in a YAML file. + Default: `destination` or `destination-` for partitioned destinations. singleActiveConsumer:: Set to true to set the `x-single-active-consumer` queue property to true. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `false` transacted:: Whether to use transacted channels. + Default: `false`. ttl:: Default time (in milliseconds) to live to apply to the queue when declared. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `no limit` useConfirmHeader:: See <>. Mutually exclusive with `confirmAckChannel`. + NOTE: In the case of RabbitMQ, content type headers can be set by external applications. Spring Cloud Stream supports them as part of an extended internal protocol used for any type of transport -- including transports, such as Kafka (prior to 0.11), that do not natively support headers. [[publisher-confirms]] === Publisher Confirms There are two mechanisms to get the result of publishing a message; in each case, the connection factory must have `publisherConfirmType` set `ConfirmType.CORRELATED`. The ""legacy"" mechanism is to set the `confirmAckChannel` to the bean name of a message channel from which you can retrieve the confirmations asynchronously; negative acks are sent to the error channel (if enabled) - see <>. The preferred mechanism, added in version 3.1 is to use a correlation data header and wait for the result via its `Future` property. This is particularly useful with a batch listener because you can send multiple messages before waiting for the result. To use this technique, set the `useConfirmHeader` property to true The following simple application is an example of using this technique: ==== [source, properties] ---- spring.cloud.stream.bindings.input-in-0.group=someGroup spring.cloud.stream.bindings.input-in-0.consumer.batch-mode=true spring.cloud.stream.source=output spring.cloud.stream.bindings.output-out-0.producer.error-channel-enabled=true spring.cloud.stream.rabbit.bindings.output-out-0.producer.useConfirmHeader=true spring.cloud.stream.rabbit.bindings.input-in-0.consumer.auto-bind-dlq=true spring.cloud.stream.rabbit.bindings.input-in-0.consumer.batch-size=10 spring.rabbitmq.publisher-confirm-type=correlated spring.rabbitmq.publisher-returns=true ---- ==== ==== [source, java] ---- @SpringBootApplication public class Application { private static final Logger log = LoggerFactory.getLogger(Application.class); public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Autowired private StreamBridge bridge; @Bean Consumer> input() { return list -> { List results = new ArrayList<>(); list.forEach(str -> { log.info(""Received: "" + str); MyCorrelationData corr = new MyCorrelationData(UUID.randomUUID().toString(), str); results.add(corr); this.bridge.send(""output-out-0"", MessageBuilder.withPayload(str.toUpperCase()) .setHeader(AmqpHeaders.PUBLISH_CONFIRM_CORRELATION, corr) .build()); }); results.forEach(correlation -> { try { Confirm confirm = correlation.getFuture().get(10, TimeUnit.SECONDS); log.info(confirm + "" for "" + correlation.getPayload()); if (correlation.getReturnedMessage() != null) { log.error(""Message for "" + correlation.getPayload() + "" was returned ""); // try to re-publish, send a DLQ, etc } } catch (InterruptedException e) { Thread.currentThread().interrupt(); e.printStackTrace(); } catch (ExecutionException | TimeoutException e) { e.printStackTrace(); } }); }; } @Bean public ApplicationRunner runner(BatchingRabbitTemplate template) { return args -> IntStream.range(0, 10).forEach(i -> template.convertAndSend(""input-in-0"", ""input-in-0.rbgh303"", ""foo"" + i)); } @Bean public BatchingRabbitTemplate template(CachingConnectionFactory cf, TaskScheduler taskScheduler) { BatchingStrategy batchingStrategy = new SimpleBatchingStrategy(10, 1000000, 1000); return new BatchingRabbitTemplate(cf, batchingStrategy, taskScheduler); } } class MyCorrelationData extends CorrelationData { private final String payload; MyCorrelationData(String id, String payload) { super(id); this.payload = payload; } public String getPayload() { return this.payload; } } ---- ==== As you can see, we send each message and then await for the publication results. If the messages can't be routed, then correlation data is populated with the returned message before the future is completed. IMPORTANT: The correlation data must be provided with a unique `id` so that the framework can perform the correlation. You cannot set both `useConfirmHeader` and `confirmAckChannel` but you can still receive returned messages in the error channel when `useConfirmHeader` is true, but using the correlation header is more convenient. == Using Existing Queues/Exchanges By default, the binder will automatically provision a topic exchange with the name being derived from the value of the destination binding property ``. The destination defaults to the binding name, if not provided. When binding a consumer, a queue will automatically be provisioned with the name `.` (if a `group` binding property is specified), or an anonymous, auto-delete queue when there is no `group`. The queue will be bound to the exchange with the ""match-all"" wildcard routing key (`#`) for a non-partitioned binding or `-` for a partitioned binding. The prefix is an empty `String` by default. If an output binding is specified with `requiredGroups`, a queue/binding will be provisioned for each group. There are a number of rabbit-specific binding properties that allow you to modify this default behavior. If you have an existing exchange/queue that you wish to use, you can completely disable automatic provisioning as follows, assuming the exchange is named `myExchange` and the queue is named `myQueue`: * `spring.cloud.stream.bindings..destination=myExhange` * `spring.cloud.stream.bindings..group=myQueue` * `spring.cloud.stream.rabbit.bindings..consumer.bindQueue=false` * `spring.cloud.stream.rabbit.bindings..consumer.declareExchange=false` * `spring.cloud.stream.rabbit.bindings..consumer.queueNameGroupOnly=true` If you want the binder to provision the queue/exchange, but you want to do it using something other than the defaults discussed here, use the following properties. Refer to the property documentation above for more information. * `spring.cloud.stream.rabbit.bindings..consumer.bindingRoutingKey=myRoutingKey` * `spring.cloud.stream.rabbit.bindings..consumer.exchangeType=` * `spring.cloud.stream.rabbit.bindings..producer.routingKeyExpression='myRoutingKey'` There are similar properties used when declaring a dead-letter exchange/queue, when `autoBindDlq` is `true`. == Retry With the RabbitMQ Binder When retry is enabled within the binder, the listener container thread is suspended for any back off periods that are configured. This might be important when strict ordering is required with a single consumer. However, for other use cases, it prevents other messages from being processed on that thread. An alternative to using binder retry is to set up dead lettering with time to live on the dead-letter queue (DLQ) as well as dead-letter configuration on the DLQ itself. See ""`<>`"" for more information about the properties discussed here. You can use the following example configuration to enable this feature: * Set `autoBindDlq` to `true`. The binder create a DLQ. Optionally, you can specify a name in `deadLetterQueueName`. * Set `dlqTtl` to the back off time you want to wait between redeliveries. * Set the `dlqDeadLetterExchange` to the default exchange. Expired messages from the DLQ are routed to the original queue, because the default `deadLetterRoutingKey` is the queue name (`destination.group`). Setting to the default exchange is achieved by setting the property with no value, as shown in the next example. To force a message to be dead-lettered, either throw an `AmqpRejectAndDontRequeueException` or set `requeueRejected` to `false` (the default) and throw any exception. The loop continue without end, which is fine for transient problems, but you may want to give up after some number of attempts. Fortunately, RabbitMQ provides the `x-death` header, which lets you determine how many cycles have occurred. To acknowledge a message after giving up, throw an `ImmediateAcknowledgeAmqpException`. === Putting it All Together The following configuration creates an exchange `myDestination` with queue `myDestination.consumerGroup` bound to a topic exchange with a wildcard routing key `#`: [source] --- spring.cloud.stream.bindings.input.destination=myDestination spring.cloud.stream.bindings.input.group=consumerGroup #disable binder retries spring.cloud.stream.bindings.input.consumer.max-attempts=1 #dlx/dlq setup spring.cloud.stream.rabbit.bindings.input.consumer.auto-bind-dlq=true spring.cloud.stream.rabbit.bindings.input.consumer.dlq-ttl=5000 spring.cloud.stream.rabbit.bindings.input.consumer.dlq-dead-letter-exchange= --- This configuration creates a DLQ bound to a direct exchange (`DLX`) with a routing key of `myDestination.consumerGroup`. When messages are rejected, they are routed to the DLQ. After 5 seconds, the message expires and is routed to the original queue by using the queue name as the routing key, as shown in the following example: .Spring Boot application [source, java] ---- @SpringBootApplication @EnableBinding(Sink.class) public class XDeathApplication { public static void main(String[] args) { SpringApplication.run(XDeathApplication.class, args); } @StreamListener(Sink.INPUT) public void listen(String in, @Header(name = ""x-death"", required = false) Map death) { if (death != null && death.get(""count"").equals(3L)) { // giving up - don't send to DLX throw new ImmediateAcknowledgeAmqpException(""Failed after 4 attempts""); } throw new AmqpRejectAndDontRequeueException(""failed""); } } ---- Notice that the count property in the `x-death` header is a `Long`. [[rabbit-error-channels]] == Error Channels Starting with version 1.3, the binder unconditionally sends exceptions to an error channel for each consumer destination and can also be configured to send async producer send failures to an error channel. See ""`<>`"" for more information. RabbitMQ has two types of send failures: * Returned messages, * Negatively acknowledged https://www.rabbitmq.com/confirms.html[Publisher Confirms]. The latter is rare. According to the RabbitMQ documentation ""[A nack] will only be delivered if an internal error occurs in the Erlang process responsible for a queue."". You can also get a negative acknowledgment if you publish to a bounded queue with `reject-publish` queue overflow behavior. As well as enabling producer error channels (as described in ""`<>`""), the RabbitMQ binder only sends messages to the channels if the connection factory is appropriately configured, as follows: * `ccf.setPublisherConfirms(true);` * `ccf.setPublisherReturns(true);` When using Spring Boot configuration for the connection factory, set the following properties: * `spring.rabbitmq.publisher-confirms` * `spring.rabbitmq.publisher-returns` The payload of the `ErrorMessage` for a returned message is a `ReturnedAmqpMessageException` with the following properties: * `failedMessage`: The spring-messaging `Message` that failed to be sent. * `amqpMessage`: The raw spring-amqp `Message`. * `replyCode`: An integer value indicating the reason for the failure (for example, 312 - No route). * `replyText`: A text value indicating the reason for the failure (for example, `NO_ROUTE`). * `exchange`: The exchange to which the message was published. * `routingKey`: The routing key used when the message was published. Also see <> for an alternative mechanism to receive returned messages. For negatively acknowledged confirmations, the payload is a `NackedAmqpMessageException` with the following properties: * `failedMessage`: The spring-messaging `Message` that failed to be sent. * `nackReason`: A reason (if available -- you may need to examine the broker logs for more information). There is no automatic handling of these exceptions (such as sending to a <>). You can consume these exceptions with your own Spring Integration flow. = Appendices [appendix] [[building]] == Building :jdkversion: 1.8 === Basic Compile and Test Pre-requisites: * To compile, JDK {jdkversion} installed. * To run tests, RabbitMQ server running on `localhost:5672` The build uses the Maven wrapper so you don't have to install a specific version of Maven. The main build command is ---- $ ./mvnw clean install ---- NOTE: There are scripts in `./ci-docker-compose` that use https://docs.docker.com/compose//[Docker Compose] to start/stop a local RabbitMQ server. You can also add '-DskipTests' if you like, to avoid running the tests. NOTE: You can also install Maven (>=3.3.3) yourself and run the `mvn` command in place of `./mvnw` in the examples below. If you do that you also might need to add `-P spring` if your local Maven settings do not contain repository declarations for spring pre-release artifacts. NOTE: Be aware that you might need to increase the amount of memory available to Maven by setting a `MAVEN_OPTS` environment variable with a value like `-Xmx512m -XX:MaxPermSize=128m`. We try to cover this in the `.mvn` configuration, so if you find you have to do it to make a build succeed, please raise a ticket to get the settings added to source control. === Documentation There is a ""docs"" profile that will generate documentation. `./mvnw clean package -Pdocs -DskipTests` The reference documentation can then be found in `docs/target/contents/reference`. === Working with the code If you don't have an IDE preference we would recommend that you use https://www.springsource.com/developer/sts[Spring Tools Suite] or https://eclipse.org[Eclipse] when working with the code. We use the https://eclipse.org/m2e/[m2eclipe] eclipse plugin for maven support. Other IDEs and tools should also work without issue. ==== Importing into eclipse with m2eclipse We recommend the https://eclipse.org/m2e/[m2eclipe] eclipse plugin when working with eclipse. If you don't already have m2eclipse installed it is available from the ""eclipse marketplace"". Unfortunately m2e does not yet support Maven 3.3, so once the projects are imported into Eclipse you will also need to tell m2eclipse to use the `.settings.xml` file for the projects. If you do not do this you may see many different errors related to the POMs in the projects. Open your Eclipse preferences, expand the Maven preferences, and select User Settings. In the User Settings field click Browse and navigate to the Spring Cloud project you imported selecting the `.settings.xml` file in that project. Click Apply and then OK to save the preference changes. NOTE: Alternatively you can copy the repository settings from https://github.com/spring-cloud/spring-cloud-build/blob/master/.settings.xml[`.settings.xml`] into your own `~/.m2/settings.xml`. ==== Importing into eclipse without m2eclipse If you prefer not to use m2eclipse you can generate eclipse project metadata using the following command: [indent=0] ---- $ ./mvnw eclipse:eclipse ---- The generated eclipse projects can be imported by selecting `import existing projects` from the `file` menu. [[contributing]] == Contributing Spring Cloud is released under the non-restrictive Apache 2.0 license, and follows a very standard Github development process, using Github tracker for issues and merging pull requests into master. If you want to contribute even something trivial please do not hesitate, but follow the guidelines below. === Sign the Contributor License Agreement Before we accept a non-trivial patch or pull request we will need you to sign the https://support.springsource.com/spring_committer_signup[contributor's agreement]. Signing the contributor's agreement does not grant anyone commit rights to the main repository, but it does mean that we can accept your contributions, and you will get an author credit if we do. Active contributors might be asked to join the core team, and given the ability to merge pull requests. === Code Conventions and Housekeeping None of these is essential for a pull request, but they will all help. They can also be added after the original pull request but before a merge. * Use the Spring Framework code format conventions. If you use Eclipse you can import formatter settings using the `eclipse-code-formatter.xml` file from the https://github.com/spring-cloud/build/tree/master/eclipse-coding-conventions.xml[Spring Cloud Build] project. If using IntelliJ, you can use the https://plugins.jetbrains.com/plugin/6546[Eclipse Code Formatter Plugin] to import the same file. * Make sure all new `.java` files to have a simple Javadoc class comment with at least an `@author` tag identifying you, and preferably at least a paragraph on what the class is for. * Add the ASF license header comment to all new `.java` files (copy from existing files in the project) * Add yourself as an `@author` to the .java files that you modify substantially (more than cosmetic changes). * Add some Javadocs and, if you change the namespace, some XSD doc elements. * A few unit tests would help a lot as well -- someone has to do it. * If no-one else is using your branch, please rebase it against the current master (or other target branch in the main project). * When writing a commit message please follow https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html[these conventions], if you are fixing an existing issue please add `Fixes gh-XXXX` at the end of the commit message (where XXXX is the issue number). // ====================================================================================== ",12254,False,2251.1292326317407,median "/* -*- Mode:C++; c-file-style:""gnu""; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2009 University of Washington * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program 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 this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include ""tap-bridge.h"" #include ""tap-encode-decode.h"" #include ""ns3/node.h"" #include ""ns3/node-list.h"" #include ""ns3/channel.h"" #include ""ns3/packet.h"" #include ""ns3/ethernet-header.h"" #include ""ns3/ethernet-trailer.h"" #include ""ns3/llc-snap-header.h"" #include ""ns3/log.h"" #include ""ns3/abort.h"" #include ""ns3/boolean.h"" #include ""ns3/string.h"" #include ""ns3/enum.h"" #include ""ns3/ipv4.h"" #include ""ns3/arp-header.h"" #include ""ns3/simulator.h"" #include ""ns3/realtime-simulator-impl.h"" #include ""ns3/unix-fd-reader.h"" #include ""ns3/uinteger.h"" #include ""ns3/malicious-tag.h"" #include ""ns3/ipv4-packet-info-tag.h"" #include ""ns3/ipv4-l3-protocol.h"" #include ""ns3/udp-l4-protocol.h"" #include ""ns3/tcp-l4-protocol.h"" #include ""ns3/udp-header.h"" #include ""ns3/tcp-header.h"" #include #include #include #include #include #include #include // // Sometimes having a tap-creator is actually more trouble than solution. In // these cases you can uncomment the define of TAP_CREATOR below and the // simulation will just use a device you have preconfigured. This is useful // if you are running in an environment where you have got to run as root, // such as ORBIT or CORE. // #define NO_CREATOR 1 // uncomment for department managed machines #ifdef NO_CREATOR #include #include #include #include #endif #include #include NS_LOG_COMPONENT_DEFINE (""TapBridge""); namespace ns3 { FdReader::Data TapBridgeFdReader::DoRead (void) { NS_LOG_FUNCTION_NOARGS (); uint32_t bufferSize = 65536; uint8_t *buf = (uint8_t *)malloc (bufferSize); NS_ABORT_MSG_IF (buf == 0, ""malloc() failed""); NS_LOG_LOGIC (""Calling read on tap device fd "" << m_fd); ssize_t len = read (m_fd, buf, bufferSize); if (len <= 0) { NS_LOG_INFO (""TapBridgeFdReader::DoRead(): done""); free (buf); buf = 0; len = 0; } return FdReader::Data (buf, len); } #define TAP_MAGIC 95549 NS_OBJECT_ENSURE_REGISTERED (TapBridge); TypeId TapBridge::GetTypeId (void) { static TypeId tid = TypeId (""ns3::TapBridge"") .SetParent () .AddConstructor () .AddAttribute (""Mtu"", ""The MAC-level Maximum Transmission Unit"", UintegerValue (0), MakeUintegerAccessor (&TapBridge::SetMtu, &TapBridge::GetMtu), MakeUintegerChecker ()) .AddAttribute (""DeviceName"", ""The name of the tap device to create."", StringValue (""""), MakeStringAccessor (&TapBridge::m_tapDeviceName), MakeStringChecker ()) .AddAttribute (""Gateway"", ""The IP address of the default gateway to assign to the host machine, when in ConfigureLocal mode."", Ipv4AddressValue (""255.255.255.255""), MakeIpv4AddressAccessor (&TapBridge::m_tapGateway), MakeIpv4AddressChecker ()) .AddAttribute (""IpAddress"", ""The IP address to assign to the tap device, when in ConfigureLocal mode. "" ""This address will override the discovered IP address of the simulated device."", Ipv4AddressValue (""255.255.255.255""), MakeIpv4AddressAccessor (&TapBridge::m_tapIp), MakeIpv4AddressChecker ()) .AddAttribute (""MacAddress"", ""The MAC address to assign to the tap device, when in ConfigureLocal mode. "" ""This address will override the discovered MAC address of the simulated device."", Mac48AddressValue (Mac48Address (""ff:ff:ff:ff:ff:ff"")), MakeMac48AddressAccessor (&TapBridge::m_tapMac), MakeMac48AddressChecker ()) .AddAttribute (""Netmask"", ""The network mask to assign to the tap device, when in ConfigureLocal mode. "" ""This address will override the discovered MAC address of the simulated device."", Ipv4MaskValue (""255.255.255.255""), MakeIpv4MaskAccessor (&TapBridge::m_tapNetmask), MakeIpv4MaskChecker ()) .AddAttribute (""Start"", ""The simulation time at which to spin up the tap device read thread."", TimeValue (Seconds (0.)), MakeTimeAccessor (&TapBridge::m_tStart), MakeTimeChecker ()) .AddAttribute (""Stop"", ""The simulation time at which to tear down the tap device read thread."", TimeValue (Seconds (0.)), MakeTimeAccessor (&TapBridge::m_tStop), MakeTimeChecker ()) .AddAttribute (""Mode"", ""The operating and configuration mode to use."", EnumValue (USE_LOCAL), MakeEnumAccessor (&TapBridge::SetMode), MakeEnumChecker (CONFIGURE_LOCAL, ""ConfigureLocal"", USE_LOCAL, ""UseLocal"", USE_BRIDGE, ""UseBridge"")) ; return tid; } TapBridge::TapBridge () : m_node (0), m_ifIndex (0), m_sock (-1), m_startEvent (), m_stopEvent (), m_fdReader (0), m_ns3AddressRewritten (false) { NS_LOG_FUNCTION_NOARGS (); m_packetBuffer = new uint8_t[65536]; Start (m_tStart); } TapBridge::~TapBridge() { NS_LOG_FUNCTION_NOARGS (); StopTapDevice (); delete [] m_packetBuffer; m_packetBuffer = 0; m_bridgedDevice = 0; } void TapBridge::DoDispose () { NS_LOG_FUNCTION_NOARGS (); NetDevice::DoDispose (); } void TapBridge::Start (Time tStart) { NS_LOG_FUNCTION (tStart); // // Cancel any pending start event and schedule a new one at some relative time in the future. // Simulator::Cancel (m_startEvent); m_startEvent = Simulator::Schedule (tStart, &TapBridge::StartTapDevice, this); } void TapBridge::Stop (Time tStop) { NS_LOG_FUNCTION (tStop); // // Cancel any pending stop event and schedule a new one at some relative time in the future. // Simulator::Cancel (m_stopEvent); m_startEvent = Simulator::Schedule (tStop, &TapBridge::StopTapDevice, this); } void TapBridge::StartTapDevice (void) { NS_LOG_FUNCTION_NOARGS (); NS_ABORT_MSG_IF (m_sock != -1, ""TapBridge::StartTapDevice(): Tap is already started""); // // We're going to need a pointer to the realtime simulator implementation. // It's important to remember that access to that implementation may happen // in a completely different thread than the simulator is running in (we're // going to spin up that thread below). We are talking about multiple threads // here, so it is very, very dangerous to do any kind of reference couning on // a shared object that is unaware of what is happening. What we are going to // do to address that is to get a reference to the realtime simulator here // where we are running in the context of a running simulator scheduler -- // recall we did a Simulator::Schedule of this method above. We get the // simulator implementation pointer in a single-threaded way and save the // underlying raw pointer for use by the (other) read thread. We must not // free this pointer or we may delete the simulator out from under us an // everyone else. We assume that the simulator implementation cannot be // replaced while the tap bridge is running and so will remain valid through // the time during which the read thread is running. // Ptr impl = DynamicCast (Simulator::GetImplementation ()); m_rtImpl = GetPointer (impl); // // A similar story exists for the node ID. We can't just naively do a // GetNode ()->GetId () since GetNode is going to give us a Ptr which // is reference counted. We need to stash away the node ID for use in the // read thread. // m_nodeId = GetNode ()->GetId (); // // Spin up the tap bridge and start receiving packets. // NS_LOG_LOGIC (""Creating tap device""); // // Call out to a separate process running as suid root in order to get the // tap device allocated and set up. We do this to avoid having the entire // simulation running as root. If this method returns, we'll have a socket // waiting for us in m_sock that we can use to talk to the newly created // tap device. // CreateTap (); // // Now spin up a read thread to read packets from the tap device. // NS_ABORT_MSG_IF (m_fdReader != 0,""TapBridge::StartTapDevice(): Receive thread is already running""); NS_LOG_LOGIC (""Spinning up read thread""); m_fdReader = Create (); m_fdReader->Start (m_sock, MakeCallback (&TapBridge::ReadCallback, this)); } void TapBridge::StopTapDevice (void) { NS_LOG_FUNCTION_NOARGS (); if (m_fdReader != 0) { m_fdReader->Stop (); m_fdReader = 0; } if (m_sock != -1) { close (m_sock); m_sock = -1; } } void TapBridge::CreateTap (void) { NS_LOG_FUNCTION_NOARGS (); // // The TapBridge has three distinct operating modes. At this point, the // differences revolve around who is responsible for creating and configuring // the underlying network tap that we use. In ConfigureLocal mode, the // TapBridge has the responsibility for creating and configuring the TAP. // // In UseBridge or UseLocal modes, the user will provide us a configuration // and we have to adapt to it. For example, in UseLocal mode, the user will // be configuring a tap device outside the scope of the ns-3 simulation and // will be expecting us to work with it. The user will do something like: // // sudo tunctl -t tap0 // sudo ifconfig tap0 hw ether 00:00:00:00:00:01 // sudo ifconfig tap0 10.1.1.1 netmask 255.255.255.0 up // // The user will then set the ""Mode"" Attribute of the TapBridge to ""UseLocal"" // and the ""DeviceName"" Attribute to ""tap0"" in this case. // // In ConfigureLocal mode, the user is asking the TapBridge to do the // configuration and create a TAP with the provided ""DeviceName"" with which // the user can later do what she wants. We need to extract values for the // MAC address, IP address, net mask, etc, from the simualtion itself and // use them to initialize corresponding values on the created tap device. // // In UseBridge mode, the user is asking us to use an existing tap device // has been included in an OS bridge. She is asking us to take the simulated // net device and logically add it to the existing bridge. We expect that // the user has done something like: // // sudo brctl addbr mybridge // sudo tunctl -t mytap // sudo ifconfig mytap hw ether 00:00:00:00:00:01 // sudo ifconfig mytap 0.0.0.0 up // sudo brctl addif mybridge mytap // sudo brctl addif mybridge ... // sudo ifconfig mybridge 10.1.1.1 netmask 255.255.255.0 up // // The bottom line at this point is that we want to either create or use a // tap device on the host based on the verb part ""Use"" or ""Configure"" of the // operating mode. Unfortunately for us you have to have root privileges to // do either. Instead of running the entire simulation as root, we decided // to make a small program who's whole reason for being is to run as suid // root and do what it takes to create the tap. We're just going to pass // off the configuration information to that program and let it deal with // the situation. // // We're going to fork and exec that program soon, but first we need to have // a socket to talk to it with. So we create a local interprocess (Unix) // socket for that purpose. // int sock = socket (PF_UNIX, SOCK_DGRAM, 0); NS_ABORT_MSG_IF (sock == -1, ""TapBridge::CreateTap(): Unix socket creation error, errno = "" << strerror (errno)); // // Bind to that socket and let the kernel allocate an endpoint // struct sockaddr_un un; memset (&un, 0, sizeof (un)); un.sun_family = AF_UNIX; int status = bind (sock, (struct sockaddr*)&un, sizeof (sa_family_t)); NS_ABORT_MSG_IF (status == -1, ""TapBridge::CreateTap(): Could not bind(): errno = "" << strerror (errno)); NS_LOG_INFO (""Created Unix socket""); NS_LOG_INFO (""sun_family = "" << un.sun_family); NS_LOG_INFO (""sun_path = "" << un.sun_path); // // We have a socket here, but we want to get it there -- to the program we're // going to exec. What we'll do is to do a getsockname and then encode the // resulting address information as a string, and then send the string to the // program as an argument. So we need to get the sock name. // socklen_t len = sizeof (un); status = getsockname (sock, (struct sockaddr*)&un, &len); NS_ABORT_MSG_IF (status == -1, ""TapBridge::CreateTap(): Could not getsockname(): errno = "" << strerror (errno)); // // Now encode that socket name (family and path) as a string of hex digits // std::string path = TapBufferToString ((uint8_t *)&un, len); NS_LOG_INFO (""Encoded Unix socket as \\"""" << path << ""\\""""); // // Tom Goff reports the possiblility of a deadlock when trying to acquire the // python GIL here. He says that this might be due to trying to access Python // objects after fork() without calling PyOS_AfterFork() to properly reset // Python state (including the GIL). Originally these next three lines were // done after the fork, but were moved here to work around the deadlock. // Ptr nd = GetBridgedNetDevice (); Ptr n = nd->GetNode (); Ptr ipv4 = n->GetObject (); n->SetTapDevice(this); // // Fork and exec the process to create our socket. If we're us (the parent) // we wait for the child (the creator) to complete and read the socket it // created and passed back using the ancillary data mechanism. // pid_t pid = ::fork (); if (pid == 0) { NS_LOG_DEBUG (""Child process""); // // build a command line argument from the encoded endpoint string that // the socket creation process will use to figure out how to respond to // the (now) parent process. We're going to have to give this program // quite a bit of information. // // -d The name of the tap device we want to create; // -g The IP address to use as the default gateway; // -i The IP address to assign to the new tap device; // -m The MAC-48 address to assign to the new tap device; // -n The network mask to assign to the new tap device; // -o The operating mode of the bridge (1=ConfigureLocal, 2=UseLocal, 3=UseBridge) // -p the path to the unix socket described above. // // Example tap-creator -dnewdev -g1.2.3.2 -i1.2.3.1 -m08:00:2e:00:01:23 -n255.255.255.0 -o1 -pblah // // We want to get as much of this stuff automagically as possible. // // For CONFIGURE_LOCAL mode only: // is the IP address we are going to set in the newly // created Tap device on the Linux host. At the point in the simulation // where devices are coming up, we should have all of our IP addresses // assigned. That means that we can find the IP address to assign to // the new Tap device from the IP address associated with the bridged // net device. // bool wantIp = (m_mode == CONFIGURE_LOCAL); if (wantIp && (ipv4 == 0) && m_tapIp.IsBroadcast () && m_tapNetmask.IsEqual (Ipv4Mask::GetOnes ())) { NS_FATAL_ERROR (""TapBridge::CreateTap(): Tap device IP configuration requested but neither IP address nor IP netmask is provided""); } // Some stub values to make tap-creator happy Ipv4Address ipv4Address (""255.255.255.255""); Ipv4Mask ipv4Mask (""255.255.255.255""); if (ipv4 != 0) { uint32_t index = ipv4->GetInterfaceForDevice (nd); if (ipv4->GetNAddresses (index) > 1) { NS_LOG_WARN (""Underlying bridged NetDevice has multiple IP addresses; using first one.""); } ipv4Address = ipv4->GetAddress (index, 0).GetLocal (); // // The net mask is sitting right there next to the ipv4 address. // ipv4Mask = ipv4->GetAddress (index, 0).GetMask (); } // // The MAC address should also already be assigned and waiting for us in // the bridged net device. // Address address = nd->GetAddress (); Mac48Address mac48Address = Mac48Address::ConvertFrom (address); // // The device-name is something we may want the system to make up in // every case. We also rely on it being configured via an Attribute // through the helper. By default, it is set to the empty string // which tells the system to make up a device name such as ""tap123"". // std::ostringstream ossDeviceName; ossDeviceName << ""-d"" << m_tapDeviceName; // // The gateway-address is something we can't derive, so we rely on it // being configured via an Attribute through the helper. // std::ostringstream ossGateway; ossGateway << ""-g"" << m_tapGateway; // // For flexibility, we do allow a client to override any of the values // above via attributes, so only use our found values if the Attribute // is not equal to its default value (empty string or broadcast address). // std::ostringstream ossIp; if (m_tapIp.IsBroadcast ()) { ossIp << ""-i"" << ipv4Address; } else { ossIp << ""-i"" << m_tapIp; } std::ostringstream ossMac; if (m_tapMac.IsBroadcast ()) { ossMac << ""-m"" << mac48Address; } else { ossMac << ""-m"" << m_tapMac; } std::ostringstream ossNetmask; if (m_tapNetmask.IsEqual (Ipv4Mask::GetOnes ())) { ossNetmask << ""-n"" << ipv4Mask; } else { ossNetmask << ""-n"" << m_tapNetmask; } std::ostringstream ossMode; ossMode << ""-o""; if (m_mode == CONFIGURE_LOCAL) { ossMode << ""1""; } else if (m_mode == USE_LOCAL) { ossMode << ""2""; } else { ossMode << ""3""; } std::ostringstream ossPath; ossPath << ""-p"" << path; // // Execute the socket creation process image. // status = ::execlp (""tap-creator"", ""tap-creator"", // argv[0] (filename) ossDeviceName.str ().c_str (), // argv[1] (-d) ossGateway.str ().c_str (), // argv[2] (-g) ossIp.str ().c_str (), // argv[3] (-i) ossMac.str ().c_str (), // argv[4] (-m) ossNetmask.str ().c_str (), // argv[5] (-n) ossMode.str ().c_str (), // argv[6] (-o) ossPath.str ().c_str (), // argv[7] (-p) (char *)NULL); // // If the execlp successfully completes, it never returns. If it returns it failed or the OS is // broken. In either case, we bail. // NS_FATAL_ERROR (""TapBridge::CreateTap(): Back from execlp(), errno = "" << ::strerror (errno)); } else { NS_LOG_DEBUG (""Parent process""); // // We're the process running the emu net device. We need to wait for the // socket creator process to finish its job. // int st; pid_t waited = waitpid (pid, &st, 0); NS_ABORT_MSG_IF (waited == -1, ""TapBridge::CreateTap(): waitpid() fails, errno = "" << strerror (errno)); NS_ASSERT_MSG (pid == waited, ""TapBridge::CreateTap(): pid mismatch""); // // Check to see if the socket creator exited normally and then take a // look at the exit code. If it bailed, so should we. If it didn't // even exit normally, we bail too. // if (WIFEXITED (st)) { int exitStatus = WEXITSTATUS (st); NS_ABORT_MSG_IF (exitStatus != 0, ""TapBridge::CreateTap(): socket creator exited normally with status "" << exitStatus); } else { NS_FATAL_ERROR (""TapBridge::CreateTap(): socket creator exited abnormally""); } // // At this point, the socket creator has run successfully and should // have created our tap device, initialized it with the information we // passed and sent it back to the socket address we provided. A socket // (fd) we can use to talk to this tap device should be waiting on the // Unix socket we set up to receive information back from the creator // program. We've got to do a bunch of grunt work to get at it, though. // // The struct iovec below is part of a scatter-gather list. It describes a // buffer. In this case, it describes a buffer (an integer) that will // get the data that comes back from the socket creator process. It will // be a magic number that we use as a consistency/sanity check. // struct iovec iov; uint32_t magic; iov.iov_base = &magic; iov.iov_len = sizeof(magic); // // The CMSG macros you'll see below are used to create and access control // messages (which is another name for ancillary data). The ancillary // data is made up of pairs of struct cmsghdr structures and associated // data arrays. // // First, we're going to allocate a buffer on the stack to receive our // data array (that contains the socket). Sometimes you'll see this called // an ""ancillary element"" but the msghdr uses the control message termimology // so we call it ""control."" // size_t msg_size = sizeof(int); char control[CMSG_SPACE (msg_size)]; // // There is a msghdr that is used to minimize the number of parameters // passed to recvmsg (which we will use to receive our ancillary data). // This structure uses terminology corresponding to control messages, so // you'll see msg_control, which is the pointer to the ancillary data and // controllen which is the size of the ancillary data array. // // So, initialize the message header that describes the ancillary/control // data we expect to receive and point it to buffer. // struct msghdr msg; msg.msg_name = 0; msg.msg_namelen = 0; msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = control; msg.msg_controllen = sizeof (control); msg.msg_flags = 0; // // Now we can actually receive the interesting bits from the tap // creator process. Lots of pain to get four bytes. // ssize_t bytesRead = recvmsg (sock, &msg, 0); NS_ABORT_MSG_IF (bytesRead != sizeof(int), ""TapBridge::CreateTap(): Wrong byte count from socket creator""); // // There may be a number of message headers/ancillary data arrays coming in. // Let's look for the one with a type SCM_RIGHTS which indicates it's the // one we're interested in. // struct cmsghdr *cmsg; for (cmsg = CMSG_FIRSTHDR (&msg); cmsg != NULL; cmsg = CMSG_NXTHDR (&msg, cmsg)) { if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) { // // This is the type of message we want. Check to see if the magic // number is correct and then pull out the socket we care about if // it matches // if (magic == TAP_MAGIC) { NS_LOG_INFO (""Got SCM_RIGHTS with correct magic "" << magic); int *rawSocket = (int*)CMSG_DATA (cmsg); NS_LOG_INFO (""Got the socket from the socket creator = "" << *rawSocket); m_sock = *rawSocket; return; } else { NS_LOG_INFO (""Got SCM_RIGHTS, but with bad magic "" << magic); } } } NS_FATAL_ERROR (""Did not get the raw socket from the socket creator""); } } void TapBridge::ReadCallback (uint8_t *buf, ssize_t len) { NS_LOG_FUNCTION_NOARGS (); NS_ASSERT_MSG (buf != 0, ""invalid buf argument""); NS_ASSERT_MSG (len > 0, ""invalid len argument""); // // It's important to remember that we're in a completely different thread // than the simulator is running in. We need to synchronize with that // other thread to get the packet up into ns-3. What we will need to do // is to schedule a method to deal with the packet using the multithreaded // simulator we are most certainly running. However, I just said it -- we // are talking about two threads here, so it is very, very dangerous to do // any kind of reference counting on a shared object. Just don't do it. // So what we're going to do is pass the buffer allocated on the heap // into the ns-3 context thread where it will create the packet. // NS_LOG_INFO (""TapBridge::ReadCallback(): Received packet on node "" << m_nodeId); NS_LOG_INFO (""TapBridge::ReadCallback(): Scheduling handler""); NS_ASSERT_MSG (m_rtImpl, ""TapBridge::ReadCallback(): Realtime simulator implementation pointer not set""); m_rtImpl->ScheduleRealtimeNowWithContext (m_nodeId, MakeSpecialEvent (&TapBridge::ForwardToBridgedDevice, this, buf, len)); free(buf); buf = 0; //ForwardToBridgedDevice(buf, len); } void TapBridge::PacketSend(Ptr packet, Address src, Address dst, uint16_t type) { if (m_mode == USE_LOCAL) { if (m_ns3AddressRewritten == false) { Mac48Address learnedMac = Mac48Address::ConvertFrom (src); m_bridgedDevice->SetAddress (Mac48Address::ConvertFrom (learnedMac)); m_ns3AddressRewritten = true; } m_bridgedDevice->Send (packet, dst, type); return; } if (m_mode == USE_BRIDGE) m_bridgedDevice->SendFrom (packet, src, dst, type); else m_bridgedDevice->Send (packet, dst, type); } /* -*- Mode:C++; c-file-style:""gnu""; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2009 University of Washington * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program 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 this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef TAP_BRIDGE_H #define TAP_BRIDGE_H #include #include ""ns3/address.h"" #include ""ns3/net-device.h"" #include ""ns3/node.h"" #include ""ns3/callback.h"" #include ""ns3/packet.h"" #include ""ns3/traced-callback.h"" #include ""ns3/event-id.h"" #include ""ns3/nstime.h"" #include ""ns3/data-rate.h"" #include ""ns3/ptr.h"" #include ""ns3/mac48-address.h"" #include ""ns3/unix-fd-reader.h"" #include ""ns3/realtime-simulator-impl.h"" namespace ns3 { class TapBridgeFdReader : public FdReader { private: FdReader::Data DoRead (void); }; class Node; /** * \\ingroup tap-bridge * * \\brief A bridge to make it appear that a real host process is connected to * an ns-3 net device. * * The Tap Bridge lives in a kind of a gray world somewhere between a * Linux host and an ns-3 bridge device. From the Linux perspective, * this code appears as the user mode handler for a Tap net device. That * is, when the Linux host writes to a /dev/tap device (that is either * manually or automatically created depending on basic operating mode * -- more on this later), the write is redirected into the TapBridge that * lives in the ns-3 world; and from this perspective, becomes a read. * In other words, a Linux process writes a packet to a tap device and * this packet is redirected to an ns-3 process where it is received by * the TapBridge as a result of a read operation there. The TapBridge * then sends the packet to the ns-3 net device to which it is bridged. * In the other direction, a packet received by an ns-3 net device is * bridged to the TapBridge (it appears via a callback from that net * device. The TapBridge then takes that packet and writes it back to * the host using the Linux TAP mechanism. This write to the device will * then appear to the Linux host as if a packet has arrived on its * device. * * The upshot is that the Tap Bridge appears to bridge a tap device on a * Linux host in the ""real world"" to an ns-3 net device in the simulation * and make is appear that a ns-3 net device is actually installed in the * Linux host. In order to do this on the ns-3 side, we need a ""ghost * node"" in the simulation to hold the bridged ns-3 net device and the * TapBridge. This node should not actually do anything else in the * simulation since its job is simply to make the net device appear in * Linux. This is not just arbitrary policy, it is because: * * - Bits sent to the Tap Bridge from higher layers in the ghost node (using * the TapBridge Send() method) are completely ignored. The Tap Bridge is * not, itself, connected to any network, neither in Linux nor in ns-3; * - The bridged ns-3 net device is has had its receive callback disconnected * from the ns-3 node and reconnected to the Tap Bridge. All data received * by a bridged device will be sent to the Linux host and will not be * received by the node. From the perspective of the ghost node, you can * send over this device but you cannot ever receive. * * Of course, if you understand all of the issues you can take control of * your own destiny and do whatever you want -- we do not actively * prevent you from using the ghost node for anything you decide. You * will be able to perform typical ns-3 operations on the ghost node if * you so desire. The internet stack, for example, must be there and * functional on that node in order to participate in IP address * assignment and global routing. However, as mentioned above, * interfaces talking any Tap Bridge or associated bridged net devices * will not work completely. If you understand exactly what you are * doing, you can set up other interfaces and devices on the ghost node * and use them; or take advantage of the operational send side of the * bridged devices to create traffic generators. We generally recommend * that you treat this node as a ghost of the Linux host and leave it to * itself, though. */ class TapBridge : public NetDevice { public: static TypeId GetTypeId (void); /** * Enumeration of the operating modes supported in the class. * */ enum Mode { ILLEGAL, /**< mode not set */ CONFIGURE_LOCAL, /**< ns-3 creates and configures tap device */ USE_LOCAL, /**< ns-3 uses a pre-created tap, without configuring it */ USE_BRIDGE, /**< ns-3 uses a pre-created tap, and bridges to a bridging net device */ }; TapBridge (); virtual ~TapBridge (); /** * \\brief Get the bridged net device. * * The bridged net device is the ns-3 device to which this bridge is connected, * * \\returns the bridged net device. */ Ptr GetBridgedNetDevice (void); /** * \\brief Set the ns-3 net device to bridge. * * This method tells the bridge which ns-3 net device it should use to connect * the simulation side of the bridge. * * \\param bridgedDevice device to set * * \\attention The ns-3 net device that is being set as the device must have an * an IP address assigned to it before the simulation is run. This address * will be used to set the hardware address of the host Linux device. */ void SetBridgedNetDevice (Ptr bridgedDevice); /** * \\brief Set a start time for the device. * * The tap bridge consumes a non-trivial amount of time to start. It starts * up in the context of a scheduled event to ensure that all configuration * has been completed before extracting the configuration (IP addresses, etc.) * In order to allow a more reasonable start-up sequence than a thundering * herd of devices, the time at which each device starts is also configurable * bot via the Attribute system and via this call. * * \\param tStart the start time */ void Start (Time tStart); /** * Set a stop time for the device. * * @param tStop the stop time * * \\see TapBridge::Start */ void Stop (Time tStop); /** * Set the operating mode of this device. * * \\param mode The operating mode of this device. */ void SetMode (TapBridge::Mode mode); /** * Get the operating mode of this device. * * \\returns The operating mode of this device. */ TapBridge::Mode GetMode (void); // // The following methods are inherited from NetDevice base class and are // documented there. // virtual void SetIfIndex (const uint32_t index); virtual uint32_t GetIfIndex (void) const; virtual Ptr GetChannel (void) const; virtual void SetAddress (Address address); virtual Address GetAddress (void) const; virtual bool SetMtu (const uint16_t mtu); virtual uint16_t GetMtu (void) const; virtual bool IsLinkUp (void) const; virtual void AddLinkChangeCallback (Callback callback); virtual bool IsBroadcast (void) const; virtual Address GetBroadcast (void) const; virtual bool IsMulticast (void) const; virtual Address GetMulticast (Ipv4Address multicastGroup) const; virtual bool IsPointToPoint (void) const; virtual bool IsBridge (void) const; virtual bool Send (Ptr packet, const Address& dest, uint16_t protocolNumber); virtual bool SendFrom (Ptr packet, const Address& source, const Address& dest, uint16_t protocolNumber); virtual Ptr GetNode (void) const; virtual void SetNode (Ptr node); virtual bool NeedsArp (void) const; virtual void SetReceiveCallback (NetDevice::ReceiveCallback cb); virtual void SetPromiscReceiveCallback (NetDevice::PromiscReceiveCallback cb); virtual bool SupportsSendFrom () const; virtual Address GetMulticast (Ipv6Address addr) const; virtual void PacketSend(Ptr packet, Address src, Address dst, uint16_t type); virtual int MaliciousProcess (Ptr p, Address src, Address dest, uint16_t type, bool direction); protected: /** * \\internal * * Call out to a separate process running as suid root in order to get our * tap device created. We do this to avoid having the entire simulation * running as root. If this method returns, we'll have a socket waiting * for us in m_sock that we can use to talk to the tap device. */ virtual void DoDispose (void); bool ReceiveFromBridgedDevice (Ptr device, Ptr packet, uint16_t protocol, Address const &src, Address const &dst, PacketType packetType); bool DiscardFromBridgedDevice (Ptr device, Ptr packet, uint16_t protocol, Address const &src); private: /** * \\internal * * Call out to a separate process running as suid root in order to get our * tap device created. We do this to avoid having the entire simulation * running as root. If this method returns, we'll have a socket waiting * for us in m_sock that we can use to talk to the tap device. */ void CreateTap (void); /** * \\internal * * Spin up the device */ void StartTapDevice (void); /** * \\internal * * Tear down the device */ void StopTapDevice (void); /** * \\internal * * Callback to process packets that are read */ void ReadCallback (uint8_t *buf, ssize_t len); /* * \\internal * * Forward a packet received from the tap device to the bridged ns-3 * device * * \\param buf A character buffer containing the actual packet bits that were * received from the host. * \\param buf The length of the buffer. */ void ForwardToBridgedDevice (uint8_t *buf, ssize_t len); /** * \\internal * * The host we are bridged to is in the evil real world. Do some sanity * checking on a received packet to make sure it isn't too evil for our * poor naive virginal simulator to handle. * * \\param packet The packet we received from the host, and which we need * to check. * \\param src A pointer to the data structure that will get the source * MAC address of the packet (extracted from the packet Ethernet * header). * \\param dst A pointer to the data structure that will get the destination * MAC address of the packet (extracted from the packet Ethernet * header). * \\param type A pointer to the variable that will get the packet type from * either the Ethernet header in the case of type interpretation * (DIX framing) or from the 802.2 LLC header in the case of * length interpretation (802.3 framing). */ Ptr Filter (Ptr packet, Address *src, Address *dst, uint16_t *type); /** * \\internal * * Callback used to hook the standard packet receive callback of the TapBridge * ns-3 net device. This is never called, and therefore no packets will ever * be received forwarded up the IP stack on the ghost node through this device. */ NetDevice::ReceiveCallback m_rxCallback; /** * \\internal * * Callback used to hook the promiscuous packet receive callback of the TapBridge * ns-3 net device. This is never called, and therefore no packets will ever * be received forwarded up the IP stack on the ghost node through this device. * * Note that we intercept the similar callback in the bridged device in order to * do the actual bridging between the bridged ns-3 net device and the Tap device * on the host. */ NetDevice::PromiscReceiveCallback m_promiscRxCallback; /** * \\internal * * Pointer to the (ghost) Node to which we are connected. */ Ptr m_node; /** * \\internal * * The ns-3 interface index of this TapBridge net device. */ uint32_t m_ifIndex; /** * \\internal * * The common mtu to use for the net devices */ uint16_t m_mtu; /** * \\internal * * The socket (actually interpreted as fd) to use to talk to the Tap device on * the real internet host. */ int m_sock; /** * \\internal * * The ID of the ns-3 event used to schedule the start up of the underlying * host Tap device and ns-3 read thread. */ EventId m_startEvent; /** * \\internal * * The ID of the ns-3 event used to schedule the tear down of the underlying * host Tap device and ns-3 read thread. */ EventId m_stopEvent; /** * \\internal * * Includes the ns-3 read thread used to do blocking reads on the fd * corresponding to the host device. */ Ptr m_fdReader; /** * \\internal * * The operating mode of the bridge. Tells basically who creates and * configures the underlying network tap. */ Mode m_mode; /** * \\internal * * The (unused) MAC address of the TapBridge net device. Since the TapBridge * is implemented as a ns-3 net device, it is required to implement certain * functionality. In this case, the TapBridge is automatically assigned a * MAC address, but it is not used. */ Mac48Address m_address; /** * \\internal * * Time to start spinning up the device */ Time m_tStart; /** * \\internal * * Time to start tearing down the device */ Time m_tStop; /** * \\internal * * The name of the device to create on the host. If the device name is the * empty string, we allow the host kernel to choose a name. */ std::string m_tapDeviceName; /** * \\internal * * The IP address to use as the device default gateway on the host. */ Ipv4Address m_tapGateway; /** * \\internal * * The IP address to use as the device IP on the host. */ Ipv4Address m_tapIp; /** * \\internal * * The MAC address to use as the hardware address on the host; only used * in UseLocal mode. This value comes from the MAC * address assigned to the bridged ns-3 net device and matches the MAC * address of the underlying network TAP which we configured to have the * same value. */ Mac48Address m_tapMac; /** * \\internal * * The network mask to assign to the device created on the host. */ Ipv4Mask m_tapNetmask; /** * \\internal * * The ns-3 net device to which we are bridging. */ Ptr m_bridgedDevice; /** * \\internal * * Whether the MAC address of the underlying ns-3 device has already been * rewritten is stored in this variable (for UseLocal mode only). */ bool m_ns3AddressRewritten; /** * A 64K buffer to hold packet data while it is being sent. */ uint8_t *m_packetBuffer; /** * A copy of a raw pointer to the required real-time simulator implementation. * Never free this pointer! */ RealtimeSimulatorImpl *m_rtImpl; /* * a copy of the node id so the read thread doesn't have to GetNode() in * in order to find the node ID. Thread unsafe reference counting in * multithreaded apps is not a good thing. */ uint32_t m_nodeId; }; } // namespace ns3 #endif /* TAP_BRIDGE_H */ #define SENDING 0 #define RECEIVING 1 int TapBridge::MaliciousProcess (Ptr p, Address src, Address dest, uint16_t type, bool direction) { uint16_t protocol = 0; UdpHeader udpHeader; uint16_t udpdestPort, udpsrcPort; Application *ptr; lowerLayers ll; maloptions res; Mac48Address destination = Mac48Address::ConvertFrom (dest); Mac48Address source = Mac48Address::ConvertFrom (src); Ptr packet = p->Copy(); // copy one time //Setup malicious options for no modifications res.action=NONE; res.divert=false; res.replay=-1; res.delay=0.0; res.duptimes=1; res.burst=false; //Get pointer to proxy Ptr app = m_node->GetApplication(0); ptr = GetPointer(app); Ptr proxy = Ptr((MalProxy*)ptr); // 1. get IP header Ipv4Header ipHeader; packet->PeekHeader(ipHeader); protocol = ipHeader.GetProtocol(); if (protocol != UdpL4Protocol::PROT_NUMBER && protocol != proxy->IPprotoNum()) { return 0; } packet->RemoveHeader(ipHeader); //2. To Malproxy int action = NONE; if(direction==SENDING){ ll.dir=FROMTAP; }else{ ll.dir=TOTAP; } ll.iph=ipHeader; ll.ethdest=dest; ll.ethsrc=src; ll.ethtype=type; ll.obj=this; if(protocol== proxy->IPprotoNum() && proxy->ShouldDoTransport()){ action = proxy->MalTransportProtocol(packet, ll, &res); } //3. Old Malicious Actions (UDP Only) if (protocol == UdpL4Protocol::PROT_NUMBER && direction==SENDING && proxy->ShouldDoUDP()){ packet->PeekHeader(udpHeader); udpdestPort = udpHeader.GetDestinationPort(); udpsrcPort = udpHeader.GetSourcePort(); uint8_t *msg = new uint8_t[packet->GetSize()]; msg = packet->PeekDataForMal(); Message *m = new Message(msg+20+8); action = proxy->MalUDPMsg(m, ll.dir, &res); } //4. Process Actions if(action==RETRY){ return -2; } if (action == DROP) { return 1; } for (int i=1; i<= res.duptimes; i++) { Ptr packet_send = packet->Copy(); Ipv4Address ipdest, ipsource; if (res.divert) { static int num_nodes = NodeList::GetNNodes(); int r = rand()%num_nodes; while (r == m_nodeId) { if (m_nodeId == 0) r++; else r--; } Ptr targetNode = NodeList::GetNode(r); dest = targetNode->GetDevice(1)->GetAddress(); ipdest = *targetNode->m_ipv4AddressList.begin(); } else if (res.replay == 1) { ipdest = ipHeader.GetSource(); ipsource = ipHeader.GetDestination(); Address swap = dest; dest = src; src = swap; if(direction==SENDING){ direction=RECEIVING; }else{ direction=SENDING; } } else { ipdest = ipHeader.GetDestination(); ipsource = ipHeader.GetSource(); } if (protocol == UdpL4Protocol::PROT_NUMBER) { packet_send->RemoveHeader(udpHeader); udpHeader.EnableChecksums(); udpHeader.InitializeChecksum(ipsource, ipdest, UdpL4Protocol::PROT_NUMBER); udpHeader.SetDestinationPort (udpdestPort); udpHeader.SetSourcePort (udpsrcPort); packet_send->AddHeader(udpHeader); }else { uint8_t *msg = packet->PeekDataForMal(); Message *m = new Message(msg); m->DoChecksum(ipHeader.GetPayloadSize(),ipsource,ipdest,proxy->IPprotoNum()); } Ipv4Header ipHeadernew = ipHeader; ipHeadernew.EnableChecksum(); ipHeadernew.SetDestination(ipdest); ipHeadernew.SetSource(ipsource); packet_send->AddHeader(ipHeadernew); if (res.delay > 0) { Time next(Seconds(res.delay)); if(direction==SENDING){ Simulator::Schedule(next, &TapBridge::PacketSend, this, packet_send, src, dest, type); }else{ Simulator::Schedule(next, &TapBridge::SendToTap, this, packet_send, type, src, dest); } }else{ if(direction==SENDING){ PacketSend(packet_send, src, dest, type); }else{ SendToTap(packet_send,type, src,dest); } } } return 1; } void TapBridge::ForwardToBridgedDevice (uint8_t *buf, ssize_t len) { NS_LOG_FUNCTION (buf << len); ProfileFunction(""ForwardToBridgedDevice"", true); // RECEIVE A PACKET FROM TAP AND NOW FORWARD TO BRIDGED DEVICE // // There are three operating modes for the TapBridge // // CONFIGURE_LOCAL means that ns-3 will create and configure a tap device // and we are expected to use it. The tap device and the ns-3 net device // will have the same MAC address by definition. Thus Send and SendFrom // are equivalent in this case. We use Send to allow all ns-3 devices to // participate in this mode. // // USE_LOCAL mode tells us that we have got to USE a pre-created tap device // that will have a different MAC address from the ns-3 net device. We // also enforce the requirement that there will only be one MAC address // bridged on the Linux side so we can use Send (instead of SendFrom) in // the linux to ns-3 direction. Again, all ns-3 devices can participate // in this mode. // // USE_BRIDGE mode tells us that we are logically extending a Linux bridge // on which lies our tap device. In this case there may be many linux // net devices on the other side of the bridge and so we must use SendFrom // to preserve the possibly many source addresses. Thus, ns-3 devices // must support SendFrom in order to be considered for USE_BRIDGE mode. // // // First, create a packet out of the byte buffer we received and free that // buffer. // Ptr packet = Create (reinterpret_cast (buf), len); // XXX these should be deleted when they are destructed //free (buf); //buf = 0; // // Make sure the packet we received is reasonable enough for the rest of the // system to handle and get it ready to be injected directly into an ns-3 // device. What should come back is a packet with the Ethernet header // (and possibly an LLC header as well) stripped off. // Address src, dst; uint16_t type; int ret; NS_LOG_LOGIC (""Received packet from tap device""); NS_LOG_INFO (""Packet "" << packet->GetUid() << "" MAC ADDRESS OF TAP DEVICE: "" << GetAddress() << "" NODE "" << m_nodeId); Ptr p = Filter (packet, &src, &dst, &type); if (p == 0) { NS_LOG_LOGIC (""TapBridge::ForwardToBridgedDevice: Discarding packet as unfit for ns-3 consumption""); ProfileFunction(""ForwardToBridgedDevice"", false); return; } static unsigned long packetcnt = 0; if (packetcnt % 10000 == 0) ProfileFunction(""DUMP"", false); packetcnt ++; ProfileFunction(""ForwardToBridgedDevice"", false); if (m_node->IsMalicious() && type == 2048) { ret=MaliciousProcess(packet, src, dst, type, SENDING); if (ret == 1) { return; } if(ret == -2){ Application *ptr; Ptr app = m_node->GetApplication(0); ptr = GetPointer(app); Ptr proxy = Ptr((MalProxy*)ptr); proxy->StoreEvent(MakeSpecialEvent (&TapBridge::ForwardToBridgedDevice, this, buf, len)); return; } } else { } PacketSend(packet, src, dst, type); return; } Ptr TapBridge::Filter (Ptr p, Address *src, Address *dst, uint16_t *type) { NS_LOG_FUNCTION (p); uint32_t pktSize; // // We have a candidate packet for injection into ns-3. We expect that since // it came over a socket that provides Ethernet packets, it should be big // enough to hold an EthernetHeader. If it can't, we signify the packet // should be filtered out by returning 0. // pktSize = p->GetSize (); EthernetHeader header (false); if (pktSize < header.GetSerializedSize ()) { return 0; } p->RemoveHeader (header); NS_LOG_LOGIC (""Pkt source is "" << header.GetSource ()); NS_LOG_LOGIC (""Pkt destination is "" << header.GetDestination ()); NS_LOG_LOGIC (""Pkt LengthType is "" << header.GetLengthType ()); // // If the length/type is less than 1500, it corresponds to a length // interpretation packet. In this case, it is an 802.3 packet and // will also have an 802.2 LLC header. If greater than 1500, we // find the protocol number (Ethernet type) directly. // if (header.GetLengthType () <= 1500) { *src = header.GetSource (); *dst = header.GetDestination (); pktSize = p->GetSize (); LlcSnapHeader llc; if (pktSize < llc.GetSerializedSize ()) { return 0; } p->RemoveHeader (llc); *type = llc.GetType (); } else { *src = header.GetSource (); *dst = header.GetDestination (); *type = header.GetLengthType (); } // // What we give back is a packet without the Ethernet header (nor the // possible llc/snap header) on it. We think it is ready to send on // out the bridged net device. // return p; } Ptr TapBridge::GetBridgedNetDevice (void) { NS_LOG_FUNCTION_NOARGS (); return m_bridgedDevice; } void TapBridge::SetBridgedNetDevice (Ptr bridgedDevice) { NS_LOG_FUNCTION (bridgedDevice); NS_ASSERT_MSG (m_node != 0, ""TapBridge::SetBridgedDevice: Bridge not installed in a node""); NS_ASSERT_MSG (bridgedDevice != this, ""TapBridge::SetBridgedDevice: Cannot bridge to self""); NS_ASSERT_MSG (m_bridgedDevice == 0, ""TapBridge::SetBridgedDevice: Already bridged""); if (!Mac48Address::IsMatchingType (bridgedDevice->GetAddress ())) { NS_FATAL_ERROR (""TapBridge::SetBridgedDevice: Device does not support eui 48 addresses: cannot be added to bridge.""); } if (m_mode == USE_BRIDGE && !bridgedDevice->SupportsSendFrom ()) { NS_FATAL_ERROR (""TapBridge::SetBridgedDevice: Device does not support SendFrom: cannot be added to bridge.""); } // // We need to disconnect the bridged device from the internet stack on our // node to ensure that only one stack responds to packets inbound over the // bridged device. That one stack lives outside ns-3 so we just blatantly // steal the device callbacks. // // N.B This can be undone if someone does a RegisterProtocolHandler later // on this node. // if (!m_node->IsMalicious()) { // if the node is not malicious //bridgedDevice->SetReceiveCallback (MakeCallback (&TapBridge::DiscardFromBridgedDevice, this)); } //? bridgedDevice->SetPromiscReceiveCallback (MakeCallback (&TapBridge::ReceiveFromBridgedDevice, this)); m_bridgedDevice = bridgedDevice; } bool TapBridge::DiscardFromBridgedDevice (Ptr device, Ptr packet, uint16_t protocol, const Address &src) { NS_LOG_FUNCTION (device << packet << protocol << src); NS_LOG_LOGIC (""Discarding packet stolen from bridged device "" << device); return true; } bool TapBridge::ReceiveFromBridgedDevice ( Ptr device, Ptr packet, uint16_t protocol, const Address &src, const Address &dst, PacketType packetType) { NS_LOG_FUNCTION (device << packet->GetUid() << protocol << src << dst << packetType); NS_ASSERT_MSG (device == m_bridgedDevice, ""TapBridge::SetBridgedDevice: Received packet from unexpected device""); ProfileFunction(""Tap:Receive"", true); NS_LOG_DEBUG (""Packet UID is "" << packet->GetUid ()); // // There are three operating modes for the TapBridge // // CONFIGURE_LOCAL means that ns-3 will create and configure a tap device // and we are expected to use it. The tap device and the ns-3 net device // will have the same MAC address by definition. // // USE_LOCAL mode tells us that we have got to USE a pre-created tap device // that will have a different MAC address from the ns-3 net device. In this // case we will be spoofing the MAC address of a received packet to match // the single allowed address on the Linux side. // // USE_BRIDGE mode tells us that we are logically extending a Linux bridge // on which lies our tap device. // if (m_mode == CONFIGURE_LOCAL && packetType == PACKET_OTHERHOST) { // // We hooked the promiscuous mode protocol handler so we could get the // destination address of the actual packet. This means we will be // getting PACKET_OTHERHOST packets (not broadcast, not multicast, not // unicast to the ns-3 net device, but to some other address). In // CONFIGURE_LOCAL mode we are not interested in these packets since they // don't refer to the single MAC address shared by the ns-3 device and // the TAP device. If, however, we are in USE_LOCAL or USE_BRIDGE mode, // we want to act like a bridge and forward these PACKET_OTHERHOST // packets. // ProfileFunction(""Tap:Receive"", false); return true; } int ret; Ptr p=packet->Copy(); if (m_node->IsMalicious() && protocol == 2048) { ret=MaliciousProcess(p, src, dst, protocol, RECEIVING); if(ret==1){ return true; } if(ret==-2){ Application *ptr; Ptr app = m_node->GetApplication(0); ptr = GetPointer(app); Ptr proxy = Ptr((MalProxy*)ptr); proxy->StoreEvent(MakeEvent (&TapBridge::ReceiveFromBridgedDevice, this, device, packet, protocol, src,dst, packetType)); return true; } } Mac48Address from = Mac48Address::ConvertFrom (src); Mac48Address to = Mac48Address::ConvertFrom (dst); NS_LOG_INFO(""FROM: "" << from << "" ("" << src << "") TO: "" << to << "" ("" << dst << "")""); EthernetHeader header = EthernetHeader (false); header.SetSource (from); header.SetDestination (to); header.SetLengthType (protocol); p->AddHeader (header); NS_LOG_LOGIC (""Writing packet to Linux host""); NS_LOG_LOGIC (""Pkt source is "" << header.GetSource ()); NS_LOG_LOGIC (""Pkt destination is "" << header.GetDestination ()); NS_LOG_LOGIC (""Pkt LengthType is "" << header.GetLengthType ()); NS_LOG_LOGIC (""Pkt size is "" << p->GetSize ()); NS_ASSERT_MSG (p->GetSize () <= 65536, ""TapBridge::ReceiveFromBridgedDevice: Packet too big "" << p->GetSize ()); p->CopyData (m_packetBuffer, p->GetSize ()); uint32_t bytesWritten = write (m_sock, m_packetBuffer, p->GetSize ()); NS_ABORT_MSG_IF (bytesWritten != p->GetSize (), ""TapBridge::ReceiveFromBridgedDevice(): Write error.""); NS_LOG_LOGIC (""End of receive packet handling on node "" << m_node->GetId ()); ProfileFunction(""Tap:Receive"", false); return true; } bool TapBridge::SendToTap ( Ptr packet, uint16_t protocol, const Address &src, const Address &dst) { Mac48Address from = Mac48Address::ConvertFrom (src); Mac48Address to = Mac48Address::ConvertFrom (dst); NS_LOG_INFO(""FROM: "" << from << "" ("" << src << "") TO: "" << to << "" ("" << dst << "")""); Ptr p = packet->Copy (); EthernetHeader header = EthernetHeader (false); header.SetSource (from); header.SetDestination (to); header.SetLengthType (protocol); p->AddHeader (header); NS_LOG_LOGIC (""Writing packet to Linux host""); NS_LOG_LOGIC (""Pkt source is "" << header.GetSource ()); NS_LOG_LOGIC (""Pkt destination is "" << header.GetDestination ()); NS_LOG_LOGIC (""Pkt LengthType is "" << header.GetLengthType ()); NS_LOG_LOGIC (""Pkt size is "" << p->GetSize ()); NS_ASSERT_MSG (p->GetSize () <= 65536, ""TapBridge::ReceiveFromBridgedDevice: Packet too big "" << p->GetSize ()); p->CopyData (m_packetBuffer, p->GetSize ()); uint32_t bytesWritten = write (m_sock, m_packetBuffer, p->GetSize ()); NS_ABORT_MSG_IF (bytesWritten != p->GetSize (), ""TapBridge::ReceiveFromBridgedDevice(): Write error.""); NS_LOG_LOGIC (""End of receive packet handling on node "" << m_node->GetId ()); ProfileFunction(""Tap:Receive"", false); return true; } void TapBridge::SendPacket(Ptr packet, lowerLayers ll) { if(ll.dir==FROMTAP){ PacketSend(packet, ll.ethsrc, ll.ethdest, ll.ethtype); }else{ SendToTap(packet, ll.ethtype, ll.ethsrc, ll.ethdest); } } void TapBridge::SetIfIndex (const uint32_t index) { NS_LOG_FUNCTION_NOARGS (); m_ifIndex = index; } uint32_t TapBridge::GetIfIndex (void) const { NS_LOG_FUNCTION_NOARGS (); return m_ifIndex; } Ptr TapBridge::GetChannel (void) const { NS_LOG_FUNCTION_NOARGS (); return 0; } void TapBridge::SetAddress (Address address) { NS_LOG_FUNCTION (address); m_address = Mac48Address::ConvertFrom (address); } Address TapBridge::GetAddress (void) const { NS_LOG_FUNCTION_NOARGS (); return m_address; } void TapBridge::SetMode (enum Mode mode) { NS_LOG_FUNCTION (mode); m_mode = mode; } TapBridge::Mode TapBridge::GetMode (void) { NS_LOG_FUNCTION_NOARGS (); return m_mode; } bool TapBridge::SetMtu (const uint16_t mtu) { NS_LOG_FUNCTION_NOARGS (); m_mtu = mtu; return true; } uint16_t TapBridge::GetMtu (void) const { NS_LOG_FUNCTION_NOARGS (); return m_mtu; } bool TapBridge::IsLinkUp (void) const { NS_LOG_FUNCTION_NOARGS (); return true; } void TapBridge::AddLinkChangeCallback (Callback callback) { NS_LOG_FUNCTION_NOARGS (); } bool TapBridge::IsBroadcast (void) const { NS_LOG_FUNCTION_NOARGS (); return true; } Address TapBridge::GetBroadcast (void) const { NS_LOG_FUNCTION_NOARGS (); return Mac48Address (""ff:ff:ff:ff:ff:ff""); } bool TapBridge::IsMulticast (void) const { NS_LOG_FUNCTION_NOARGS (); return true; } Address TapBridge::GetMulticast (Ipv4Address multicastGroup) const { NS_LOG_FUNCTION (this << multicastGroup); Mac48Address multicast = Mac48Address::GetMulticast (multicastGroup); return multicast; } bool TapBridge::IsPointToPoint (void) const { NS_LOG_FUNCTION_NOARGS (); return false; } bool TapBridge::IsBridge (void) const { NS_LOG_FUNCTION_NOARGS (); // // Returning false from IsBridge in a device called TapBridge may seem odd // at first glance, but this test is for a device that bridges ns-3 devices // together. The Tap bridge doesn't do that -- it bridges an ns-3 device to // a Linux device. This is a completely different story. // return false; } bool TapBridge::Send (Ptr packet, const Address& dst, uint16_t protocol) { NS_LOG_FUNCTION (packet << dst << protocol); NS_FATAL_ERROR (""TapBridge::Send: You may not call Send on a TapBridge directly""); return false; } bool TapBridge::SendFrom (Ptr packet, const Address& src, const Address& dst, uint16_t protocol) { NS_LOG_FUNCTION (packet << src << dst << protocol); NS_FATAL_ERROR (""TapBridge::Send: You may not call SendFrom on a TapBridge directly""); return false; } Ptr TapBridge::GetNode (void) const { NS_LOG_FUNCTION_NOARGS (); return m_node; } void TapBridge::SetNode (Ptr node) { NS_LOG_FUNCTION_NOARGS (); m_node = node; } bool TapBridge::NeedsArp (void) const { NS_LOG_FUNCTION_NOARGS (); return true; } void TapBridge::SetReceiveCallback (NetDevice::ReceiveCallback cb) { NS_LOG_FUNCTION_NOARGS (); m_rxCallback = cb; } void TapBridge::SetPromiscReceiveCallback (NetDevice::PromiscReceiveCallback cb) { NS_LOG_FUNCTION_NOARGS (); m_promiscRxCallback = cb; } bool TapBridge::SupportsSendFrom () const { NS_LOG_FUNCTION_NOARGS (); return true; } Address TapBridge::GetMulticast (Ipv6Address addr) const { NS_LOG_FUNCTION (this << addr); return Mac48Address::GetMulticast (addr); } } // namespace ns3 ",16282,True,2794.0148764363594,median "*/--------------------------------------------------------------------------------\\ *| This file is part of Mockup loader | *| | *| The MIT License (MIT) | *| | *| Copyright (c) 2015 SBCG Team (www.sbcg.com.ua), Alexander Tsybulsky | *| | *| 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. | *\\--------------------------------------------------------------------------------/ *| project homepage: https://github.com/sbcgua/mockup_loader | *\\--------------------------------------------------------------------------------/ ********************************************************************** * MACRO ********************************************************************** define append_dummy. e_dummy_struc-tdate = &1. e_dummy_struc-tchar = &2. e_dummy_struc-tstring = &3. e_dummy_struc-tdecimal = &4. e_dummy_struc-tnumber = &5. if i_strict = abap_true. e_dummy_struc-traw = &6. e_dummy_struc-tinteger = &7. e_dummy_struc-talpha = &8. endif. append e_dummy_struc to e_dummy_tab. end-of-definition. define add_range. r_&1-sign = &2. r_&1-option = &3. r_&1-low = &4. append r_&1 to l_where-t&1. end-of-definition. define assert_excode. cl_abap_unit_assert=>assert_not_initial( act = lo_ex ). cl_abap_unit_assert=>assert_equals( exp = &1 act = lo_ex->code ). end-of-definition. ********************************************************************** * Test Class definition ********************************************************************** class lcl_test_mockup_utils definition for testing duration short risk level harmless. * ================ public section. types: begin of ty_dummy, mandt type mandt, tdate type datum, tchar type char08, traw type thraw1, tstring type string, talpha type veri_alpha, tdecimal type dmbtr, tnumber type numc04, tinteger type i, end of ty_dummy, tt_dummy type table of ty_dummy with default key. * ================ private section. methods setup. methods range_filtering for testing. methods get_dummy_data importing i_strict type abap_bool default abap_true exporting e_dummy_struc type ty_dummy e_dummy_tab type tt_dummy. methods filter_helper importing i_tab type tt_dummy i_filter type zcl_mockup_loader_utils=>tt_filter returning value(e_tab) type tt_dummy. methods filter_table for testing. methods filter_table_neg for testing. methods does_line_fit_filter for testing. methods build_filter_with_value for testing. methods build_filter for testing. endclass. ""lcl_test_mockup_loader ********************************************************************** * Implementation ********************************************************************** class lcl_test_mockup_utils implementation. ********************************************************************** * Setup methods ********************************************************************** method setup. endmethod. ""setup ********************************************************************** * Dummy data generation ********************************************************************** method get_dummy_data. clear e_dummy_tab. "" TDATE TCHAR TSTRING TDECIMAL TNUM TRAW TINT TALPHA append_dummy '20150101' 'Trololo1' 'String1' '1234567.81' 2015 '8A' 1111 '0000100000'. append_dummy '20160102' 'Trololo2' 'String2' '1234567.82' 2016 '8B' 2222 '0000200000'. append_dummy '20160103' 'Trololo3' 'String3' '1234567.83' 2015 '8C' 3333 '0000300000'. read table e_dummy_tab into e_dummy_struc index 1. endmethod. "" get_dummy_data ********************************************************************** * RANGE_FILTERING - test build_filter and does_line_fit_filter ********************************************************************** method range_filtering. data: dummy_tab_src type tt_dummy, dummy_tab_exp type tt_dummy, dummy type ty_dummy, l_filter type zcl_mockup_loader_utils=>tt_filter, lo_ex type ref to zcx_mockup_loader_error, lt_tywhere type zcl_mockup_loader_utils=>tt_where, l_tywhere type zcl_mockup_loader_utils=>ty_where, begin of l_where_err1, tnumber type range of numc04, tdate type range of datum, tother type tt_dummy, end of l_where_err1, begin of l_where_err2, tnumber type range of numc04, tdate type range of datum, tother type c, end of l_where_err2, begin of l_where, tnumber type range of numc04, tdate type range of datum, tother type range of c, end of l_where, r_number like line of l_where-tnumber, r_date like line of l_where-tdate, r_other like line of l_where-tother. get_dummy_data( importing e_dummy_tab = dummy_tab_src ). append initial line to l_where_err1-tnumber. append initial line to l_where_err2-tnumber. append initial line to dummy_tab_exp. "" Negative tests -------------------------------------------------------------------- "" Component is not a range table try. l_filter = zcl_mockup_loader_utils=>build_filter( i_where = l_where_err1 ). catch zcx_mockup_loader_error into lo_ex. endtry. assert_excode 'WS'. "" Component is not a table try. l_filter = zcl_mockup_loader_utils=>build_filter( i_where = l_where_err2 ). catch zcx_mockup_loader_error into lo_ex. endtry. assert_excode 'WS'. "" Unexpected types of filters l_tywhere-name = 'TNUMBER'. get reference of l_where into l_tywhere-range. try. l_filter = zcl_mockup_loader_utils=>build_filter( i_where = l_tywhere ). catch zcx_mockup_loader_error into lo_ex. endtry. assert_excode 'CE'. "" Filter is not range l_tywhere-name = 'TNUMBER'. get reference of dummy_tab_exp into l_tywhere-range. try. l_filter = zcl_mockup_loader_utils=>build_filter( i_where = l_tywhere ). catch zcx_mockup_loader_error into lo_ex. endtry. assert_excode 'RT'. "" Filter is not range + TABLE l_tywhere-name = 'TNUMBER'. get reference of dummy_tab_exp into l_tywhere-range. append l_tywhere to lt_tywhere. try. l_filter = zcl_mockup_loader_utils=>build_filter( i_where = lt_tywhere ). catch zcx_mockup_loader_error into lo_ex. endtry. clear lt_tywhere. assert_excode 'RT'. "" Wrong type of table try. l_filter = zcl_mockup_loader_utils=>build_filter( i_where = dummy_tab_exp ). catch zcx_mockup_loader_error into lo_ex. endtry. assert_excode 'WT'. "" Parameter is an unsupported type try. l_filter = zcl_mockup_loader_utils=>build_filter( i_where = lo_ex ). catch zcx_mockup_loader_error into lo_ex. endtry. assert_excode 'UT'. "" parameter is incorrect string pattern try. l_filter = zcl_mockup_loader_utils=>build_filter( i_where = 'TNUMBER??' ). catch zcx_mockup_loader_error into lo_ex. endtry. assert_excode 'SP'. "" Positive test RANGE STRUCTURE ----------------------------------------------------- dummy_tab_exp[] = dummy_tab_src[]. delete dummy_tab_exp where tnumber <> '2015' or tdate < '20160101'. add_range number 'I' 'EQ' '2015'. add_range date 'I' 'GE' '20160101'. add_range other 'I' 'GE' 'A'. try. l_filter = zcl_mockup_loader_utils=>build_filter( i_where = l_where ). catch zcx_mockup_loader_error into lo_ex. cl_abap_unit_assert=>fail( lo_ex->get_text( ) ). endtry. cl_abap_unit_assert=>assert_equals( act = filter_helper( i_tab = dummy_tab_src i_filter = l_filter ) exp = dummy_tab_exp ). "" Positive test TY_WHERE TABLE -------------------------------------------------- "" REUSE dummy_tab_exp and ranges from above l_tywhere-name = 'TNUMBER'. get reference of l_where-tnumber into l_tywhere-range. append l_tywhere to lt_tywhere. l_tywhere-name = 'TDATE'. get reference of l_where-tdate into l_tywhere-range. append l_tywhere to lt_tywhere. try . l_filter = zcl_mockup_loader_utils=>build_filter( i_where = lt_tywhere ). catch zcx_mockup_loader_error into lo_ex. cl_abap_unit_assert=>fail( lo_ex->get_text( ) ). endtry. cl_abap_unit_assert=>assert_equals( act = filter_helper( i_tab = dummy_tab_src i_filter = l_filter ) exp = dummy_tab_exp ). "" Positive test STRING -------------------------------------------------------------- dummy_tab_exp[] = dummy_tab_src[]. delete dummy_tab_exp where tnumber <> '2015'. try . l_filter = zcl_mockup_loader_utils=>build_filter( i_where = 'TNUMBER = 2015' ). catch zcx_mockup_loader_error into lo_ex. cl_abap_unit_assert=>fail( lo_ex->get_text( ) ). endtry. cl_abap_unit_assert=>assert_equals( act = filter_helper( i_tab = dummy_tab_src i_filter = l_filter ) exp = dummy_tab_exp ). "" Same but with lower case name try . l_filter = zcl_mockup_loader_utils=>build_filter( i_where = 'TnumBER = 2015' ). catch zcx_mockup_loader_error into lo_ex. cl_abap_unit_assert=>fail( lo_ex->get_text( ) ). endtry. cl_abap_unit_assert=>assert_equals( act = filter_helper( i_tab = dummy_tab_src i_filter = l_filter ) exp = dummy_tab_exp ). "" Positive test TY_WHERE STRUCTURE -------------------------------------------------- "" REUSE dummy_tab_exp and ranges from above l_tywhere-name = 'TNUMBER'. get reference of l_where-tnumber into l_tywhere-range. try . l_filter = zcl_mockup_loader_utils=>build_filter( i_where = l_tywhere ). catch zcx_mockup_loader_error into lo_ex. cl_abap_unit_assert=>fail( lo_ex->get_text( ) ). endtry. cl_abap_unit_assert=>assert_equals( act = filter_helper( i_tab = dummy_tab_src i_filter = l_filter ) exp = dummy_tab_exp ). endmethod. ""range_filtering method filter_helper. data dummy type ty_dummy. loop at i_tab into dummy. if zcl_mockup_loader_utils=>does_line_fit_filter( i_line = dummy i_filter = i_filter ) = abap_true. append dummy to e_tab. endif. endloop. endmethod. "" filter_helper method filter_table. data: dummy_tab_src type tt_dummy, lt_act type tt_dummy, lt_exp type tt_dummy, ls_act type ty_dummy, ls_exp type ty_dummy, l_str type string, lt_filter type zcl_mockup_loader_utils=>tt_filter, lo_ex type ref to zcx_mockup_loader_error. field-symbols like line of lt_filter. get_dummy_data( importing e_dummy_tab = dummy_tab_src ). "" Filter table l_str = '2015'. append initial line to lt_filter assigning . -name = 'TNUMBER'. -type = 'S'. get reference of l_str into -valref. try . zcl_mockup_loader_utils=>filter_table( exporting i_filter = lt_filter i_tab = dummy_tab_src importing e_container = lt_act ). catch zcx_mockup_loader_error into lo_ex. cl_abap_unit_assert=>fail( lo_ex->get_text( ) ). endtry. cl_abap_unit_assert=>assert_equals( act = lines( lt_act ) exp = 2 ). read table dummy_tab_src into ls_exp index 1. read table lt_act into ls_act index 1. cl_abap_unit_assert=>assert_equals( act = ls_act exp = ls_exp ). read table dummy_tab_src into ls_exp index 3. read table lt_act into ls_act index 2. cl_abap_unit_assert=>assert_equals( act = ls_act exp = ls_exp ). "" Filter structure l_str = '2016'. "" second line ! try . zcl_mockup_loader_utils=>filter_table( exporting i_filter = lt_filter i_tab = dummy_tab_src importing e_container = ls_act ). catch zcx_mockup_loader_error into lo_ex. cl_abap_unit_assert=>fail( lo_ex->get_text( ) ). endtry. read table dummy_tab_src into ls_exp index 2. cl_abap_unit_assert=>assert_equals( act = ls_act exp = ls_exp ). "" Filter with i_where (second line !) try . zcl_mockup_loader_utils=>filter_table( exporting i_where = 'TNUMBER=2016' i_tab = dummy_tab_src importing e_container = ls_act ). catch zcx_mockup_loader_error into lo_ex. cl_abap_unit_assert=>fail( lo_ex->get_text( ) ). endtry. read table dummy_tab_src into ls_exp index 2. cl_abap_unit_assert=>assert_equals( act = ls_act exp = ls_exp ). endmethod. "" filter_table. method filter_table_neg. data: dummy_tab_src type tt_dummy, ls_act type ty_dummy, lt_filter type zcl_mockup_loader_utils=>tt_filter, ls_filter like line of lt_filter, lo_ex type ref to zcx_mockup_loader_error. clear lo_ex. try . "" Different table line types zcl_mockup_loader_utils=>filter_table( exporting i_tab = dummy_tab_src i_filter = lt_filter importing e_container = lt_filter ). catch zcx_mockup_loader_error into lo_ex. endtry. assert_excode 'LT'. clear lo_ex. try . "" Different struc line types zcl_mockup_loader_utils=>filter_table( exporting i_tab = dummy_tab_src i_filter = lt_filter importing e_container = ls_filter ). catch zcx_mockup_loader_error into lo_ex. endtry. assert_excode 'LT'. clear lo_ex. try . "" Wrong container type zcl_mockup_loader_utils=>filter_table( exporting i_tab = dummy_tab_src i_filter = lt_filter importing e_container = lo_ex ). catch zcx_mockup_loader_error into lo_ex. endtry. assert_excode 'WT'. clear lo_ex. try . "" Wrong container type zcl_mockup_loader_utils=>filter_table( exporting i_tab = dummy_tab_src i_filter = lt_filter i_where = 'a=b' importing e_container = lo_ex ). catch zcx_mockup_loader_error into lo_ex. endtry. assert_excode 'OO'. endmethod. "" filter_table_neg. method does_line_fit_filter. data: lv_fit type abap_bool, ls_line type ty_dummy, lt_filter type zcl_mockup_loader_utils=>tt_filter, l_str type string. data: begin of l_where, tnumber type range of numc04, tdate type range of datum, end of l_where, r_number like line of l_where-tnumber, r_date like line of l_where-tdate. field-symbols like line of lt_filter. get_dummy_data( importing e_dummy_struc = ls_line ). "" Filter by string append initial line to lt_filter assigning . -name = 'TNUMBER'. -type = 'S'. get reference of l_str into -valref. l_str = '2015'. ls_line-tnumber = 2015. lv_fit = zcl_mockup_loader_utils=>does_line_fit_filter( i_line = ls_line i_filter = lt_filter ). cl_abap_unit_assert=>assert_true( lv_fit ). ls_line-tnumber = 2016. lv_fit = zcl_mockup_loader_utils=>does_line_fit_filter( i_line = ls_line i_filter = lt_filter ). cl_abap_unit_assert=>assert_false( lv_fit ). "" Filter by range clear lt_filter. add_range number 'I' 'EQ' '2015'. add_range date 'I' 'GE' '20160101'. append initial line to lt_filter assigning . -name = 'TNUMBER'. -type = 'R'. get reference of l_where-tnumber into -valref. append initial line to lt_filter assigning . -name = 'TDATE'. -type = 'R'. get reference of l_where-tdate into -valref. ls_line-tnumber = 2015. ls_line-tdate = '20160101'. lv_fit = zcl_mockup_loader_utils=>does_line_fit_filter( i_line = ls_line i_filter = lt_filter ). cl_abap_unit_assert=>assert_true( lv_fit ). ls_line-tnumber = 2015. ls_line-tdate = '20160108'. lv_fit = zcl_mockup_loader_utils=>does_line_fit_filter( i_line = ls_line i_filter = lt_filter ). cl_abap_unit_assert=>assert_true( lv_fit ). ls_line-tnumber = 2015. ls_line-tdate = '20150101'. lv_fit = zcl_mockup_loader_utils=>does_line_fit_filter( i_line = ls_line i_filter = lt_filter ). cl_abap_unit_assert=>assert_false( lv_fit ). ls_line-tnumber = 2016. ls_line-tdate = '20160108'. lv_fit = zcl_mockup_loader_utils=>does_line_fit_filter( i_line = ls_line i_filter = lt_filter ). cl_abap_unit_assert=>assert_false( lv_fit ). endmethod. "" does_line_fit_filter. method build_filter_with_value. data: l_val type string, lt_filter type zcl_mockup_loader_utils=>tt_filter, ls_filter like line of lt_filter, lo_ex type ref to zcx_mockup_loader_error. clear lo_ex. try . "" i_where not string lt_filter = zcl_mockup_loader_utils=>build_filter( i_where = 123 i_single_value = '234' ). catch zcx_mockup_loader_error into lo_ex. endtry. assert_excode 'PN'. clear lo_ex. try . "" i_value - elementary type lt_filter = zcl_mockup_loader_utils=>build_filter( i_where = '123' i_single_value = lt_filter ). catch zcx_mockup_loader_error into lo_ex. endtry. assert_excode 'ET'. clear lo_ex. try . "" positive test l_val = 'dummy'. lt_filter = zcl_mockup_loader_utils=>build_filter( i_where = 'fld' i_single_value = l_val ). catch zcx_mockup_loader_error into lo_ex. cl_abap_unit_assert=>fail( ). endtry. cl_abap_unit_assert=>assert_equals( act = lines( lt_filter ) exp = 1 ). read table lt_filter into ls_filter index 1. cl_abap_unit_assert=>assert_equals( act = ls_filter-name exp = 'FLD' ). cl_abap_unit_assert=>assert_equals( act = ls_filter-type exp = 'V' ). cl_abap_unit_assert=>assert_bound( act = ls_filter-valref ). l_val = 'something else'. field-symbols type string. assign ls_filter-valref->* to . cl_abap_unit_assert=>assert_equals( act = exp = 'dummy' ). endmethod. "" build_filter_with_value. method build_filter. data: lt_filter type zcl_mockup_loader_utils=>tt_filter, lt_filter_act type zcl_mockup_loader_utils=>tt_filter, ls_filter like line of lt_filter, lo_ex type ref to zcx_mockup_loader_error. ls_filter-name = 'AAA'. ls_filter-type = 'V'. append ls_filter to lt_filter. clear lo_ex. try . "" tt_filter pass through lt_filter_act = zcl_mockup_loader_utils=>build_filter( i_where = lt_filter ). catch zcx_mockup_loader_error into lo_ex. cl_abap_unit_assert=>fail( ). endtry. cl_abap_unit_assert=>assert_equals( act = lt_filter_act exp = lt_filter ). endmethod. "" build_filter. endclass. ",5233,False,1139.4767947402515,median "//===- Attributes.cpp - Implement AttributesList --------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // \\file // This file implements the Attribute, AttributeImpl, AttrBuilder, // AttributeListImpl, and AttributeList classes. // //===----------------------------------------------------------------------===// #include ""llvm/IR/Attributes.h"" #include ""AttributeImpl.h"" #include ""LLVMContextImpl.h"" #include ""llvm/ADT/ArrayRef.h"" #include ""llvm/ADT/FoldingSet.h"" #include ""llvm/ADT/Optional.h"" #include ""llvm/ADT/STLExtras.h"" #include ""llvm/ADT/SmallVector.h"" #include ""llvm/ADT/StringExtras.h"" #include ""llvm/ADT/StringRef.h"" #include ""llvm/ADT/StringSwitch.h"" #include ""llvm/ADT/Twine.h"" #include ""llvm/Config/llvm-config.h"" #include ""llvm/IR/Function.h"" #include ""llvm/IR/LLVMContext.h"" #include ""llvm/IR/Type.h"" #include ""llvm/Support/Compiler.h"" #include ""llvm/Support/Debug.h"" #include ""llvm/Support/ErrorHandling.h"" #include ""llvm/Support/MathExtras.h"" #include ""llvm/Support/raw_ostream.h"" #include #include #include #include #include #include #include #include #include using namespace llvm; //===----------------------------------------------------------------------===// // Attribute Construction Methods //===----------------------------------------------------------------------===// // allocsize has two integer arguments, but because they're both 32 bits, we can // pack them into one 64-bit value, at the cost of making said value // nonsensical. // // In order to do this, we need to reserve one value of the second (optional) // allocsize argument to signify ""not present."" static const unsigned AllocSizeNumElemsNotPresent = -1; static uint64_t packAllocSizeArgs(unsigned ElemSizeArg, const Optional &NumElemsArg) { assert((!NumElemsArg.hasValue() || *NumElemsArg != AllocSizeNumElemsNotPresent) && ""Attempting to pack a reserved value""); return uint64_t(ElemSizeArg) << 32 | NumElemsArg.getValueOr(AllocSizeNumElemsNotPresent); } static std::pair> unpackAllocSizeArgs(uint64_t Num) { unsigned NumElems = Num & std::numeric_limits::max(); unsigned ElemSizeArg = Num >> 32; Optional NumElemsArg; if (NumElems != AllocSizeNumElemsNotPresent) NumElemsArg = NumElems; return std::make_pair(ElemSizeArg, NumElemsArg); } Attribute Attribute::get(LLVMContext &Context, Attribute::AttrKind Kind, uint64_t Val) { LLVMContextImpl *pImpl = Context.pImpl; FoldingSetNodeID ID; ID.AddInteger(Kind); if (Val) ID.AddInteger(Val); void *InsertPoint; AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint); if (!PA) { // If we didn't find any existing attributes of the same shape then create a // new one and insert it. if (!Val) PA = new (pImpl->Alloc) EnumAttributeImpl(Kind); else PA = new (pImpl->Alloc) IntAttributeImpl(Kind, Val); pImpl->AttrsSet.InsertNode(PA, InsertPoint); } // Return the Attribute that we found or created. return Attribute(PA); } Attribute Attribute::get(LLVMContext &Context, StringRef Kind, StringRef Val) { LLVMContextImpl *pImpl = Context.pImpl; FoldingSetNodeID ID; ID.AddString(Kind); if (!Val.empty()) ID.AddString(Val); void *InsertPoint; AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint); if (!PA) { // If we didn't find any existing attributes of the same shape then create a // new one and insert it. void *Mem = pImpl->Alloc.Allocate(StringAttributeImpl::totalSizeToAlloc(Kind, Val), alignof(StringAttributeImpl)); PA = new (Mem) StringAttributeImpl(Kind, Val); pImpl->AttrsSet.InsertNode(PA, InsertPoint); } // Return the Attribute that we found or created. return Attribute(PA); } Attribute Attribute::get(LLVMContext &Context, Attribute::AttrKind Kind, Type *Ty) { LLVMContextImpl *pImpl = Context.pImpl; FoldingSetNodeID ID; ID.AddInteger(Kind); ID.AddPointer(Ty); void *InsertPoint; AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint); if (!PA) { // If we didn't find any existing attributes of the same shape then create a // new one and insert it. PA = new (pImpl->Alloc) TypeAttributeImpl(Kind, Ty); pImpl->AttrsSet.InsertNode(PA, InsertPoint); } // Return the Attribute that we found or created. return Attribute(PA); } Attribute Attribute::getWithAlignment(LLVMContext &Context, Align A) { assert(A <= llvm::Value::MaximumAlignment && ""Alignment too large.""); return get(Context, Alignment, A.value()); } Attribute Attribute::getWithStackAlignment(LLVMContext &Context, Align A) { assert(A <= 0x100 && ""Alignment too large.""); return get(Context, StackAlignment, A.value()); } Attribute Attribute::getWithDereferenceableBytes(LLVMContext &Context, uint64_t Bytes) { assert(Bytes && ""Bytes must be non-zero.""); return get(Context, Dereferenceable, Bytes); } Attribute Attribute::getWithDereferenceableOrNullBytes(LLVMContext &Context, uint64_t Bytes) { assert(Bytes && ""Bytes must be non-zero.""); return get(Context, DereferenceableOrNull, Bytes); } Attribute Attribute::getWithByValType(LLVMContext &Context, Type *Ty) { return get(Context, ByVal, Ty); } Attribute Attribute::getWithStructRetType(LLVMContext &Context, Type *Ty) { return get(Context, StructRet, Ty); } Attribute Attribute::getWithByRefType(LLVMContext &Context, Type *Ty) { return get(Context, ByRef, Ty); } Attribute Attribute::getWithPreallocatedType(LLVMContext &Context, Type *Ty) { return get(Context, Preallocated, Ty); } Attribute Attribute::getWithAllocSizeArgs(LLVMContext &Context, unsigned ElemSizeArg, const Optional &NumElemsArg) { assert(!(ElemSizeArg == 0 && NumElemsArg && *NumElemsArg == 0) && ""Invalid allocsize arguments -- given allocsize(0, 0)""); return get(Context, AllocSize, packAllocSizeArgs(ElemSizeArg, NumElemsArg)); } Attribute::AttrKind Attribute::getAttrKindFromName(StringRef AttrName) { return StringSwitch(AttrName) #define GET_ATTR_NAMES #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \\ .Case(#DISPLAY_NAME, Attribute::ENUM_NAME) #include ""llvm/IR/Attributes.inc"" .Default(Attribute::None); } StringRef Attribute::getNameFromAttrKind(Attribute::AttrKind AttrKind) { switch (AttrKind) { #define GET_ATTR_NAMES #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \\ case Attribute::ENUM_NAME: \\ return #DISPLAY_NAME; #include ""llvm/IR/Attributes.inc"" case Attribute::None: return ""none""; default: llvm_unreachable(""invalid Kind""); } } bool Attribute::doesAttrKindHaveArgument(Attribute::AttrKind AttrKind) { return AttrKind == Attribute::Alignment || AttrKind == Attribute::StackAlignment || AttrKind == Attribute::Dereferenceable || AttrKind == Attribute::AllocSize || AttrKind == Attribute::DereferenceableOrNull; } bool Attribute::isExistingAttribute(StringRef Name) { return StringSwitch(Name) #define GET_ATTR_NAMES #define ATTRIBUTE_ALL(ENUM_NAME, DISPLAY_NAME) .Case(#DISPLAY_NAME, true) #include ""llvm/IR/Attributes.inc"" .Default(false); } //===----------------------------------------------------------------------===// // Attribute Accessor Methods //===----------------------------------------------------------------------===// bool Attribute::isEnumAttribute() const { return pImpl && pImpl->isEnumAttribute(); } bool Attribute::isIntAttribute() const { return pImpl && pImpl->isIntAttribute(); } bool Attribute::isStringAttribute() const { return pImpl && pImpl->isStringAttribute(); } bool Attribute::isTypeAttribute() const { return pImpl && pImpl->isTypeAttribute(); } Attribute::AttrKind Attribute::getKindAsEnum() const { if (!pImpl) return None; assert((isEnumAttribute() || isIntAttribute() || isTypeAttribute()) && ""Invalid attribute type to get the kind as an enum!""); return pImpl->getKindAsEnum(); } uint64_t Attribute::getValueAsInt() const { if (!pImpl) return 0; assert(isIntAttribute() && ""Expected the attribute to be an integer attribute!""); return pImpl->getValueAsInt(); } StringRef Attribute::getKindAsString() const { if (!pImpl) return {}; assert(isStringAttribute() && ""Invalid attribute type to get the kind as a string!""); return pImpl->getKindAsString(); } StringRef Attribute::getValueAsString() const { if (!pImpl) return {}; assert(isStringAttribute() && ""Invalid attribute type to get the value as a string!""); return pImpl->getValueAsString(); } Type *Attribute::getValueAsType() const { if (!pImpl) return {}; assert(isTypeAttribute() && ""Invalid attribute type to get the value as a type!""); return pImpl->getValueAsType(); } bool Attribute::hasAttribute(AttrKind Kind) const { return (pImpl && pImpl->hasAttribute(Kind)) || (!pImpl && Kind == None); } bool Attribute::hasAttribute(StringRef Kind) const { if (!isStringAttribute()) return false; return pImpl && pImpl->hasAttribute(Kind); } MaybeAlign Attribute::getAlignment() const { assert(hasAttribute(Attribute::Alignment) && ""Trying to get alignment from non-alignment attribute!""); return MaybeAlign(pImpl->getValueAsInt()); } MaybeAlign Attribute::getStackAlignment() const { assert(hasAttribute(Attribute::StackAlignment) && ""Trying to get alignment from non-alignment attribute!""); return MaybeAlign(pImpl->getValueAsInt()); } uint64_t Attribute::getDereferenceableBytes() const { assert(hasAttribute(Attribute::Dereferenceable) && ""Trying to get dereferenceable bytes from "" ""non-dereferenceable attribute!""); return pImpl->getValueAsInt(); } uint64_t Attribute::getDereferenceableOrNullBytes() const { assert(hasAttribute(Attribute::DereferenceableOrNull) && ""Trying to get dereferenceable bytes from "" ""non-dereferenceable attribute!""); return pImpl->getValueAsInt(); } std::pair> Attribute::getAllocSizeArgs() const { assert(hasAttribute(Attribute::AllocSize) && ""Trying to get allocsize args from non-allocsize attribute""); return unpackAllocSizeArgs(pImpl->getValueAsInt()); } std::string Attribute::getAsString(bool InAttrGrp) const { if (!pImpl) return {}; if (hasAttribute(Attribute::SanitizeAddress)) return ""sanitize_address""; if (hasAttribute(Attribute::SanitizeHWAddress)) return ""sanitize_hwaddress""; if (hasAttribute(Attribute::SanitizeMemTag)) return ""sanitize_memtag""; if (hasAttribute(Attribute::AlwaysInline)) return ""alwaysinline""; if (hasAttribute(Attribute::ArgMemOnly)) return ""argmemonly""; if (hasAttribute(Attribute::Builtin)) return ""builtin""; if (hasAttribute(Attribute::Convergent)) return ""convergent""; if (hasAttribute(Attribute::SwiftError)) return ""swifterror""; if (hasAttribute(Attribute::SwiftSelf)) return ""swiftself""; if (hasAttribute(Attribute::SwiftAsync)) return ""swiftasync""; if (hasAttribute(Attribute::InaccessibleMemOnly)) return ""inaccessiblememonly""; if (hasAttribute(Attribute::InaccessibleMemOrArgMemOnly)) return ""inaccessiblemem_or_argmemonly""; if (hasAttribute(Attribute::InAlloca)) return ""inalloca""; if (hasAttribute(Attribute::InlineHint)) return ""inlinehint""; if (hasAttribute(Attribute::InReg)) return ""inreg""; if (hasAttribute(Attribute::JumpTable)) return ""jumptable""; if (hasAttribute(Attribute::MinSize)) return ""minsize""; if (hasAttribute(Attribute::Naked)) return ""naked""; if (hasAttribute(Attribute::Nest)) return ""nest""; if (hasAttribute(Attribute::NoAlias)) return ""noalias""; if (hasAttribute(Attribute::NoBuiltin)) return ""nobuiltin""; if (hasAttribute(Attribute::NoCallback)) return ""nocallback""; if (hasAttribute(Attribute::NoCapture)) return ""nocapture""; if (hasAttribute(Attribute::NoDuplicate)) return ""noduplicate""; if (hasAttribute(Attribute::NoFree)) return ""nofree""; if (hasAttribute(Attribute::NoImplicitFloat)) return ""noimplicitfloat""; if (hasAttribute(Attribute::NoInline)) return ""noinline""; if (hasAttribute(Attribute::NonLazyBind)) return ""nonlazybind""; if (hasAttribute(Attribute::NoMerge)) return ""nomerge""; if (hasAttribute(Attribute::NonNull)) return ""nonnull""; if (hasAttribute(Attribute::NoRedZone)) return ""noredzone""; if (hasAttribute(Attribute::NoReturn)) return ""noreturn""; if (hasAttribute(Attribute::NoSync)) return ""nosync""; if (hasAttribute(Attribute::NullPointerIsValid)) return ""null_pointer_is_valid""; if (hasAttribute(Attribute::WillReturn)) return ""willreturn""; if (hasAttribute(Attribute::NoCfCheck)) return ""nocf_check""; if (hasAttribute(Attribute::NoRecurse)) return ""norecurse""; if (hasAttribute(Attribute::NoUnwind)) return ""nounwind""; if (hasAttribute(Attribute::OptForFuzzing)) return ""optforfuzzing""; if (hasAttribute(Attribute::OptimizeNone)) return ""optnone""; if (hasAttribute(Attribute::OptimizeForSize)) return ""optsize""; if (hasAttribute(Attribute::ReadNone)) return ""readnone""; if (hasAttribute(Attribute::ReadOnly)) return ""readonly""; if (hasAttribute(Attribute::WriteOnly)) return ""writeonly""; if (hasAttribute(Attribute::Returned)) return ""returned""; if (hasAttribute(Attribute::ReturnsTwice)) return ""returns_twice""; if (hasAttribute(Attribute::SExt)) return ""signext""; if (hasAttribute(Attribute::SpeculativeLoadHardening)) return ""speculative_load_hardening""; if (hasAttribute(Attribute::Speculatable)) return ""speculatable""; if (hasAttribute(Attribute::StackProtect)) return ""ssp""; if (hasAttribute(Attribute::StackProtectReq)) return ""sspreq""; if (hasAttribute(Attribute::StackProtectStrong)) return ""sspstrong""; if (hasAttribute(Attribute::SafeStack)) return ""safestack""; if (hasAttribute(Attribute::ShadowCallStack)) return ""shadowcallstack""; if (hasAttribute(Attribute::StrictFP)) return ""strictfp""; if (hasAttribute(Attribute::SanitizeThread)) return ""sanitize_thread""; if (hasAttribute(Attribute::SanitizeMemory)) return ""sanitize_memory""; if (hasAttribute(Attribute::UWTable)) return ""uwtable""; if (hasAttribute(Attribute::ZExt)) return ""zeroext""; if (hasAttribute(Attribute::Cold)) return ""cold""; if (hasAttribute(Attribute::Hot)) return ""hot""; if (hasAttribute(Attribute::ImmArg)) return ""immarg""; if (hasAttribute(Attribute::NoUndef)) return ""noundef""; if (hasAttribute(Attribute::MustProgress)) return ""mustprogress""; const bool IsByVal = hasAttribute(Attribute::ByVal); if (IsByVal || hasAttribute(Attribute::StructRet)) { std::string Result; Result += IsByVal ? ""byval"" : ""sret""; if (Type *Ty = getValueAsType()) { raw_string_ostream OS(Result); Result += '('; Ty->print(OS, false, true); OS.flush(); Result += ')'; } return Result; } const bool IsByRef = hasAttribute(Attribute::ByRef); if (IsByRef || hasAttribute(Attribute::Preallocated)) { std::string Result = IsByRef ? ""byref"" : ""preallocated""; raw_string_ostream OS(Result); Result += '('; getValueAsType()->print(OS, false, true); OS.flush(); Result += ')'; return Result; } // FIXME: These should be output like this: // // align=4 // alignstack=8 // if (hasAttribute(Attribute::Alignment)) { std::string Result; Result += ""align""; Result += (InAttrGrp) ? ""="" : "" ""; Result += utostr(getValueAsInt()); return Result; } auto AttrWithBytesToString = [&](const char *Name) { std::string Result; Result += Name; if (InAttrGrp) { Result += ""=""; Result += utostr(getValueAsInt()); } else { Result += ""(""; Result += utostr(getValueAsInt()); Result += "")""; } return Result; }; if (hasAttribute(Attribute::StackAlignment)) return AttrWithBytesToString(""alignstack""); if (hasAttribute(Attribute::Dereferenceable)) return AttrWithBytesToString(""dereferenceable""); if (hasAttribute(Attribute::DereferenceableOrNull)) return AttrWithBytesToString(""dereferenceable_or_null""); if (hasAttribute(Attribute::AllocSize)) { unsigned ElemSize; Optional NumElems; std::tie(ElemSize, NumElems) = getAllocSizeArgs(); std::string Result = ""allocsize(""; Result += utostr(ElemSize); if (NumElems.hasValue()) { Result += ','; Result += utostr(*NumElems); } Result += ')'; return Result; } // Convert target-dependent attributes to strings of the form: // // ""kind"" // ""kind"" = ""value"" // if (isStringAttribute()) { std::string Result; { raw_string_ostream OS(Result); OS << '""' << getKindAsString() << '""'; // Since some attribute strings contain special characters that cannot be // printable, those have to be escaped to make the attribute value // printable as is. e.g. ""\\01__gnu_mcount_nc"" const auto &AttrVal = pImpl->getValueAsString(); if (!AttrVal.empty()) { OS << ""=\\""""; printEscapedString(AttrVal, OS); OS << ""\\""""; } } return Result; } llvm_unreachable(""Unknown attribute""); } bool Attribute::operator<(Attribute A) const { if (!pImpl && !A.pImpl) return false; if (!pImpl) return true; if (!A.pImpl) return false; return *pImpl < *A.pImpl; } void Attribute::Profile(FoldingSetNodeID &ID) const { ID.AddPointer(pImpl); } //===----------------------------------------------------------------------===// // AttributeImpl Definition //===----------------------------------------------------------------------===// bool AttributeImpl::hasAttribute(Attribute::AttrKind A) const { if (isStringAttribute()) return false; return getKindAsEnum() == A; } bool AttributeImpl::hasAttribute(StringRef Kind) const { if (!isStringAttribute()) return false; return getKindAsString() == Kind; } Attribute::AttrKind AttributeImpl::getKindAsEnum() const { assert(isEnumAttribute() || isIntAttribute() || isTypeAttribute()); return static_cast(this)->getEnumKind(); } uint64_t AttributeImpl::getValueAsInt() const { assert(isIntAttribute()); return static_cast(this)->getValue(); } StringRef AttributeImpl::getKindAsString() const { assert(isStringAttribute()); return static_cast(this)->getStringKind(); } StringRef AttributeImpl::getValueAsString() const { assert(isStringAttribute()); return static_cast(this)->getStringValue(); } Type *AttributeImpl::getValueAsType() const { assert(isTypeAttribute()); return static_cast(this)->getTypeValue(); } bool AttributeImpl::operator<(const AttributeImpl &AI) const { if (this == &AI) return false; // This sorts the attributes with Attribute::AttrKinds coming first (sorted // relative to their enum value) and then strings. if (isEnumAttribute()) { if (AI.isEnumAttribute()) return getKindAsEnum() < AI.getKindAsEnum(); if (AI.isIntAttribute()) return true; if (AI.isStringAttribute()) return true; if (AI.isTypeAttribute()) return true; } if (isTypeAttribute()) { if (AI.isEnumAttribute()) return false; if (AI.isTypeAttribute()) { assert(getKindAsEnum() != AI.getKindAsEnum() && ""Comparison of types would be unstable""); return getKindAsEnum() < AI.getKindAsEnum(); } if (AI.isIntAttribute()) return true; if (AI.isStringAttribute()) return true; } if (isIntAttribute()) { if (AI.isEnumAttribute()) return false; if (AI.isTypeAttribute()) return false; if (AI.isIntAttribute()) { if (getKindAsEnum() == AI.getKindAsEnum()) return getValueAsInt() < AI.getValueAsInt(); return getKindAsEnum() < AI.getKindAsEnum(); } if (AI.isStringAttribute()) return true; } assert(isStringAttribute()); if (AI.isEnumAttribute()) return false; if (AI.isTypeAttribute()) return false; if (AI.isIntAttribute()) return false; if (getKindAsString() == AI.getKindAsString()) return getValueAsString() < AI.getValueAsString(); return getKindAsString() < AI.getKindAsString(); } //===----------------------------------------------------------------------===// // AttributeSet Definition //===----------------------------------------------------------------------===// AttributeSet AttributeSet::get(LLVMContext &C, const AttrBuilder &B) { return AttributeSet(AttributeSetNode::get(C, B)); } AttributeSet AttributeSet::get(LLVMContext &C, ArrayRef Attrs) { return AttributeSet(AttributeSetNode::get(C, Attrs)); } AttributeSet AttributeSet::addAttribute(LLVMContext &C, Attribute::AttrKind Kind) const { if (hasAttribute(Kind)) return *this; AttrBuilder B; B.addAttribute(Kind); return addAttributes(C, AttributeSet::get(C, B)); } AttributeSet AttributeSet::addAttribute(LLVMContext &C, StringRef Kind, StringRef Value) const { AttrBuilder B; B.addAttribute(Kind, Value); return addAttributes(C, AttributeSet::get(C, B)); } AttributeSet AttributeSet::addAttributes(LLVMContext &C, const AttributeSet AS) const { if (!hasAttributes()) return AS; if (!AS.hasAttributes()) return *this; AttrBuilder B(AS); for (const auto &I : *this) B.addAttribute(I); return get(C, B); } AttributeSet AttributeSet::removeAttribute(LLVMContext &C, Attribute::AttrKind Kind) const { if (!hasAttribute(Kind)) return *this; AttrBuilder B(*this); B.removeAttribute(Kind); return get(C, B); } AttributeSet AttributeSet::removeAttribute(LLVMContext &C, StringRef Kind) const { if (!hasAttribute(Kind)) return *this; AttrBuilder B(*this); B.removeAttribute(Kind); return get(C, B); } AttributeSet AttributeSet::removeAttributes(LLVMContext &C, const AttrBuilder &Attrs) const { AttrBuilder B(*this); B.remove(Attrs); return get(C, B); } unsigned AttributeSet::getNumAttributes() const { return SetNode ? SetNode->getNumAttributes() : 0; } bool AttributeSet::hasAttribute(Attribute::AttrKind Kind) const { return SetNode ? SetNode->hasAttribute(Kind) : false; } bool AttributeSet::hasAttribute(StringRef Kind) const { return SetNode ? SetNode->hasAttribute(Kind) : false; } Attribute AttributeSet::getAttribute(Attribute::AttrKind Kind) const { return SetNode ? SetNode->getAttribute(Kind) : Attribute(); } Attribute AttributeSet::getAttribute(StringRef Kind) const { return SetNode ? SetNode->getAttribute(Kind) : Attribute(); } MaybeAlign AttributeSet::getAlignment() const { return SetNode ? SetNode->getAlignment() : None; } MaybeAlign AttributeSet::getStackAlignment() const { return SetNode ? SetNode->getStackAlignment() : None; } uint64_t AttributeSet::getDereferenceableBytes() const { return SetNode ? SetNode->getDereferenceableBytes() : 0; } uint64_t AttributeSet::getDereferenceableOrNullBytes() const { return SetNode ? SetNode->getDereferenceableOrNullBytes() : 0; } Type *AttributeSet::getByRefType() const { return SetNode ? SetNode->getByRefType() : nullptr; } Type *AttributeSet::getByValType() const { return SetNode ? SetNode->getByValType() : nullptr; } Type *AttributeSet::getStructRetType() const { return SetNode ? SetNode->getStructRetType() : nullptr; } Type *AttributeSet::getPreallocatedType() const { return SetNode ? SetNode->getPreallocatedType() : nullptr; } std::pair> AttributeSet::getAllocSizeArgs() const { return SetNode ? SetNode->getAllocSizeArgs() : std::pair>(0, 0); } std::string AttributeSet::getAsString(bool InAttrGrp) const { return SetNode ? SetNode->getAsString(InAttrGrp) : """"; } AttributeSet::iterator AttributeSet::begin() const { return SetNode ? SetNode->begin() : nullptr; } AttributeSet::iterator AttributeSet::end() const { return SetNode ? SetNode->end() : nullptr; } #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) LLVM_DUMP_METHOD void AttributeSet::dump() const { dbgs() << ""AS =\\n""; dbgs() << "" { ""; dbgs() << getAsString(true) << "" }\\n""; } #endif //===----------------------------------------------------------------------===// // AttributeSetNode Definition //===----------------------------------------------------------------------===// AttributeSetNode::AttributeSetNode(ArrayRef Attrs) : NumAttrs(Attrs.size()) { // There's memory after the node where we can store the entries in. llvm::copy(Attrs, getTrailingObjects()); for (const auto &I : *this) { if (I.isStringAttribute()) StringAttrs.insert({ I.getKindAsString(), I }); else AvailableAttrs.addAttribute(I.getKindAsEnum()); } } AttributeSetNode *AttributeSetNode::get(LLVMContext &C, ArrayRef Attrs) { SmallVector SortedAttrs(Attrs.begin(), Attrs.end()); llvm::sort(SortedAttrs); return getSorted(C, SortedAttrs); } AttributeSetNode *AttributeSetNode::getSorted(LLVMContext &C, ArrayRef SortedAttrs) { if (SortedAttrs.empty()) return nullptr; // Build a key to look up the existing attributes. LLVMContextImpl *pImpl = C.pImpl; FoldingSetNodeID ID; assert(llvm::is_sorted(SortedAttrs) && ""Expected sorted attributes!""); for (const auto &Attr : SortedAttrs) Attr.Profile(ID); void *InsertPoint; AttributeSetNode *PA = pImpl->AttrsSetNodes.FindNodeOrInsertPos(ID, InsertPoint); // If we didn't find any existing attributes of the same shape then create a // new one and insert it. if (!PA) { // Coallocate entries after the AttributeSetNode itself. void *Mem = ::operator new(totalSizeToAlloc(SortedAttrs.size())); PA = new (Mem) AttributeSetNode(SortedAttrs); pImpl->AttrsSetNodes.InsertNode(PA, InsertPoint); } // Return the AttributeSetNode that we found or created. return PA; } AttributeSetNode *AttributeSetNode::get(LLVMContext &C, const AttrBuilder &B) { // Add target-independent attributes. SmallVector Attrs; for (Attribute::AttrKind Kind = Attribute::None; Kind != Attribute::EndAttrKinds; Kind = Attribute::AttrKind(Kind + 1)) { if (!B.contains(Kind)) continue; Attribute Attr; switch (Kind) { case Attribute::ByVal: Attr = Attribute::getWithByValType(C, B.getByValType()); break; case Attribute::StructRet: Attr = Attribute::getWithStructRetType(C, B.getStructRetType()); break; case Attribute::ByRef: Attr = Attribute::getWithByRefType(C, B.getByRefType()); break; case Attribute::Preallocated: Attr = Attribute::getWithPreallocatedType(C, B.getPreallocatedType()); break; case Attribute::Alignment: assert(B.getAlignment() && ""Alignment must be set""); Attr = Attribute::getWithAlignment(C, *B.getAlignment()); break; case Attribute::StackAlignment: assert(B.getStackAlignment() && ""StackAlignment must be set""); Attr = Attribute::getWithStackAlignment(C, *B.getStackAlignment()); break; case Attribute::Dereferenceable: Attr = Attribute::getWithDereferenceableBytes( C, B.getDereferenceableBytes()); break; case Attribute::DereferenceableOrNull: Attr = Attribute::getWithDereferenceableOrNullBytes( C, B.getDereferenceableOrNullBytes()); break; case Attribute::AllocSize: { auto A = B.getAllocSizeArgs(); Attr = Attribute::getWithAllocSizeArgs(C, A.first, A.second); break; } default: Attr = Attribute::get(C, Kind); } Attrs.push_back(Attr); } // Add target-dependent (string) attributes. for (const auto &TDA : B.td_attrs()) Attrs.emplace_back(Attribute::get(C, TDA.first, TDA.second)); return getSorted(C, Attrs); } bool AttributeSetNode::hasAttribute(StringRef Kind) const { return StringAttrs.count(Kind); } Optional AttributeSetNode::findEnumAttribute(Attribute::AttrKind Kind) const { // Do a quick presence check. if (!hasAttribute(Kind)) return None; // Attributes in a set are sorted by enum value, followed by string // attributes. Binary search the one we want. const Attribute *I = std::lower_bound(begin(), end() - StringAttrs.size(), Kind, [](Attribute A, Attribute::AttrKind Kind) { return A.getKindAsEnum() < Kind; }); assert(I != end() && I->hasAttribute(Kind) && ""Presence check failed?""); return *I; } Attribute AttributeSetNode::getAttribute(Attribute::AttrKind Kind) const { if (auto A = findEnumAttribute(Kind)) return *A; return {}; } Attribute AttributeSetNode::getAttribute(StringRef Kind) const { return StringAttrs.lookup(Kind); } MaybeAlign AttributeSetNode::getAlignment() const { if (auto A = findEnumAttribute(Attribute::Alignment)) return A->getAlignment(); return None; } MaybeAlign AttributeSetNode::getStackAlignment() const { if (auto A = findEnumAttribute(Attribute::StackAlignment)) return A->getStackAlignment(); return None; } Type *AttributeSetNode::getByValType() const { if (auto A = findEnumAttribute(Attribute::ByVal)) return A->getValueAsType(); return nullptr; } Type *AttributeSetNode::getStructRetType() const { if (auto A = findEnumAttribute(Attribute::StructRet)) return A->getValueAsType(); return nullptr; } Type *AttributeSetNode::getByRefType() const { if (auto A = findEnumAttribute(Attribute::ByRef)) return A->getValueAsType(); return nullptr; } Type *AttributeSetNode::getPreallocatedType() const { if (auto A = findEnumAttribute(Attribute::Preallocated)) return A->getValueAsType(); return nullptr; } uint64_t AttributeSetNode::getDereferenceableBytes() const { if (auto A = findEnumAttribute(Attribute::Dereferenceable)) return A->getDereferenceableBytes(); return 0; } uint64_t AttributeSetNode::getDereferenceableOrNullBytes() const { if (auto A = findEnumAttribute(Attribute::DereferenceableOrNull)) return A->getDereferenceableOrNullBytes(); return 0; } std::pair> AttributeSetNode::getAllocSizeArgs() const { if (auto A = findEnumAttribute(Attribute::AllocSize)) return A->getAllocSizeArgs(); return std::make_pair(0, 0); } std::string AttributeSetNode::getAsString(bool InAttrGrp) const { std::string Str; for (iterator I = begin(), E = end(); I != E; ++I) { if (I != begin()) Str += ' '; Str += I->getAsString(InAttrGrp); } return Str; } //===----------------------------------------------------------------------===// // AttributeListImpl Definition //===----------------------------------------------------------------------===// /// Map from AttributeList index to the internal array index. Adding one happens /// to work, because -1 wraps around to 0. static unsigned attrIdxToArrayIdx(unsigned Index) { return Index + 1; } AttributeListImpl::AttributeListImpl(ArrayRef Sets) : NumAttrSets(Sets.size()) { assert(!Sets.empty() && ""pointless AttributeListImpl""); // There's memory after the node where we can store the entries in. llvm::copy(Sets, getTrailingObjects()); // Initialize AvailableFunctionAttrs and AvailableSomewhereAttrs // summary bitsets. for (const auto &I : Sets[attrIdxToArrayIdx(AttributeList::FunctionIndex)]) if (!I.isStringAttribute()) AvailableFunctionAttrs.addAttribute(I.getKindAsEnum()); for (const auto &Set : Sets) for (const auto &I : Set) if (!I.isStringAttribute()) AvailableSomewhereAttrs.addAttribute(I.getKindAsEnum()); } void AttributeListImpl::Profile(FoldingSetNodeID &ID) const { Profile(ID, makeArrayRef(begin(), end())); } void AttributeListImpl::Profile(FoldingSetNodeID &ID, ArrayRef Sets) { for (const auto &Set : Sets) ID.AddPointer(Set.SetNode); } bool AttributeListImpl::hasAttrSomewhere(Attribute::AttrKind Kind, unsigned *Index) const { if (!AvailableSomewhereAttrs.hasAttribute(Kind)) return false; if (Index) { for (unsigned I = 0, E = NumAttrSets; I != E; ++I) { if (begin()[I].hasAttribute(Kind)) { *Index = I - 1; break; } } } return true; } #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) LLVM_DUMP_METHOD void AttributeListImpl::dump() const { AttributeList(const_cast(this)).dump(); } #endif //===----------------------------------------------------------------------===// // AttributeList Construction and Mutation Methods //===----------------------------------------------------------------------===// AttributeList AttributeList::getImpl(LLVMContext &C, ArrayRef AttrSets) { assert(!AttrSets.empty() && ""pointless AttributeListImpl""); LLVMContextImpl *pImpl = C.pImpl; FoldingSetNodeID ID; AttributeListImpl::Profile(ID, AttrSets); void *InsertPoint; AttributeListImpl *PA = pImpl->AttrsLists.FindNodeOrInsertPos(ID, InsertPoint); // If we didn't find any existing attributes of the same shape then // create a new one and insert it. if (!PA) { // Coallocate entries after the AttributeListImpl itself. void *Mem = pImpl->Alloc.Allocate( AttributeListImpl::totalSizeToAlloc(AttrSets.size()), alignof(AttributeListImpl)); PA = new (Mem) AttributeListImpl(AttrSets); pImpl->AttrsLists.InsertNode(PA, InsertPoint); } // Return the AttributesList that we found or created. return AttributeList(PA); } AttributeList AttributeList::get(LLVMContext &C, ArrayRef> Attrs) { // If there are no attributes then return a null AttributesList pointer. if (Attrs.empty()) return {}; assert(llvm::is_sorted(Attrs, [](const std::pair &LHS, const std::pair &RHS) { return LHS.first < RHS.first; }) && ""Misordered Attributes list!""); assert(llvm::all_of(Attrs, [](const std::pair &Pair) { return Pair.second.isValid(); }) && ""Pointless attribute!""); // Create a vector if (unsigned, AttributeSetNode*) pairs from the attributes // list. SmallVector, 8> AttrPairVec; for (ArrayRef>::iterator I = Attrs.begin(), E = Attrs.end(); I != E; ) { unsigned Index = I->first; SmallVector AttrVec; while (I != E && I->first == Index) { AttrVec.push_back(I->second); ++I; } AttrPairVec.emplace_back(Index, AttributeSet::get(C, AttrVec)); } return get(C, AttrPairVec); } AttributeList AttributeList::get(LLVMContext &C, ArrayRef> Attrs) { // If there are no attributes then return a null AttributesList pointer. if (Attrs.empty()) return {}; assert(llvm::is_sorted(Attrs, [](const std::pair &LHS, const std::pair &RHS) { return LHS.first < RHS.first; }) && ""Misordered Attributes list!""); assert(llvm::none_of(Attrs, [](const std::pair &Pair) { return !Pair.second.hasAttributes(); }) && ""Pointless attribute!""); unsigned MaxIndex = Attrs.back().first; // If the MaxIndex is FunctionIndex and there are other indices in front // of it, we need to use the largest of those to get the right size. if (MaxIndex == FunctionIndex && Attrs.size() > 1) MaxIndex = Attrs[Attrs.size() - 2].first; SmallVector AttrVec(attrIdxToArrayIdx(MaxIndex) + 1); for (const auto &Pair : Attrs) AttrVec[attrIdxToArrayIdx(Pair.first)] = Pair.second; return getImpl(C, AttrVec); } AttributeList AttributeList::get(LLVMContext &C, AttributeSet FnAttrs, AttributeSet RetAttrs, ArrayRef ArgAttrs) { // Scan from the end to find the last argument with attributes. Most // arguments don't have attributes, so it's nice if we can have fewer unique // AttributeListImpls by dropping empty attribute sets at the end of the list. unsigned NumSets = 0; for (size_t I = ArgAttrs.size(); I != 0; --I) { if (ArgAttrs[I - 1].hasAttributes()) { NumSets = I + 2; break; } } if (NumSets == 0) { // Check function and return attributes if we didn't have argument // attributes. if (RetAttrs.hasAttributes()) NumSets = 2; else if (FnAttrs.hasAttributes()) NumSets = 1; } // If all attribute sets were empty, we can use the empty attribute list. if (NumSets == 0) return {}; SmallVector AttrSets; AttrSets.reserve(NumSets); // If we have any attributes, we always have function attributes. AttrSets.push_back(FnAttrs); if (NumSets > 1) AttrSets.push_back(RetAttrs); if (NumSets > 2) { // Drop the empty argument attribute sets at the end. ArgAttrs = ArgAttrs.take_front(NumSets - 2); llvm::append_range(AttrSets, ArgAttrs); } return getImpl(C, AttrSets); } AttributeList AttributeList::get(LLVMContext &C, unsigned Index, const AttrBuilder &B) { if (!B.hasAttributes()) return {}; Index = attrIdxToArrayIdx(Index); SmallVector AttrSets(Index + 1); AttrSets[Index] = AttributeSet::get(C, B); return getImpl(C, AttrSets); } AttributeList AttributeList::get(LLVMContext &C, unsigned Index, ArrayRef Kinds) { SmallVector, 8> Attrs; for (const auto K : Kinds) Attrs.emplace_back(Index, Attribute::get(C, K)); return get(C, Attrs); } AttributeList AttributeList::get(LLVMContext &C, unsigned Index, ArrayRef Kinds, ArrayRef Values) { assert(Kinds.size() == Values.size() && ""Mismatched attribute values.""); SmallVector, 8> Attrs; auto VI = Values.begin(); for (const auto K : Kinds) Attrs.emplace_back(Index, Attribute::get(C, K, *VI++)); return get(C, Attrs); } AttributeList AttributeList::get(LLVMContext &C, unsigned Index, ArrayRef Kinds) { SmallVector, 8> Attrs; for (const auto &K : Kinds) Attrs.emplace_back(Index, Attribute::get(C, K)); return get(C, Attrs); } AttributeList AttributeList::get(LLVMContext &C, ArrayRef Attrs) { if (Attrs.empty()) return {}; if (Attrs.size() == 1) return Attrs[0]; unsigned MaxSize = 0; for (const auto &List : Attrs) MaxSize = std::max(MaxSize, List.getNumAttrSets()); // If every list was empty, there is no point in merging the lists. if (MaxSize == 0) return {}; SmallVector NewAttrSets(MaxSize); for (unsigned I = 0; I < MaxSize; ++I) { AttrBuilder CurBuilder; for (const auto &List : Attrs) CurBuilder.merge(List.getAttributes(I - 1)); NewAttrSets[I] = AttributeSet::get(C, CurBuilder); } return getImpl(C, NewAttrSets); } AttributeList AttributeList::addAttribute(LLVMContext &C, unsigned Index, Attribute::AttrKind Kind) const { if (hasAttribute(Index, Kind)) return *this; AttributeSet Attrs = getAttributes(Index); // TODO: Insert at correct position and avoid sort. SmallVector NewAttrs(Attrs.begin(), Attrs.end()); NewAttrs.push_back(Attribute::get(C, Kind)); return setAttributes(C, Index, AttributeSet::get(C, NewAttrs)); } AttributeList AttributeList::addAttribute(LLVMContext &C, unsigned Index, StringRef Kind, StringRef Value) const { AttrBuilder B; B.addAttribute(Kind, Value); return addAttributes(C, Index, B); } AttributeList AttributeList::addAttribute(LLVMContext &C, unsigned Index, Attribute A) const { AttrBuilder B; B.addAttribute(A); return addAttributes(C, Index, B); } AttributeList AttributeList::setAttributes(LLVMContext &C, unsigned Index, AttributeSet Attrs) const { Index = attrIdxToArrayIdx(Index); SmallVector AttrSets(this->begin(), this->end()); if (Index >= AttrSets.size()) AttrSets.resize(Index + 1); AttrSets[Index] = Attrs; return AttributeList::getImpl(C, AttrSets); } AttributeList AttributeList::addAttributes(LLVMContext &C, unsigned Index, const AttrBuilder &B) const { if (!B.hasAttributes()) return *this; if (!pImpl) return AttributeList::get(C, {{Index, AttributeSet::get(C, B)}}); #ifndef NDEBUG // FIXME it is not obvious how this should work for alignment. For now, say // we can't change a known alignment. const MaybeAlign OldAlign = getAttributes(Index).getAlignment(); const MaybeAlign NewAlign = B.getAlignment(); assert((!OldAlign || !NewAlign || OldAlign == NewAlign) && ""Attempt to change alignment!""); #endif AttrBuilder Merged(getAttributes(Index)); Merged.merge(B); return setAttributes(C, Index, AttributeSet::get(C, Merged)); } AttributeList AttributeList::addParamAttribute(LLVMContext &C, ArrayRef ArgNos, Attribute A) const { assert(llvm::is_sorted(ArgNos)); SmallVector AttrSets(this->begin(), this->end()); unsigned MaxIndex = attrIdxToArrayIdx(ArgNos.back() + FirstArgIndex); if (MaxIndex >= AttrSets.size()) AttrSets.resize(MaxIndex + 1); for (unsigned ArgNo : ArgNos) { unsigned Index = attrIdxToArrayIdx(ArgNo + FirstArgIndex); AttrBuilder B(AttrSets[Index]); B.addAttribute(A); AttrSets[Index] = AttributeSet::get(C, B); } return getImpl(C, AttrSets); } AttributeList AttributeList::removeAttribute(LLVMContext &C, unsigned Index, Attribute::AttrKind Kind) const { if (!hasAttribute(Index, Kind)) return *this; Index = attrIdxToArrayIdx(Index); SmallVector AttrSets(this->begin(), this->end()); assert(Index < AttrSets.size()); AttrSets[Index] = AttrSets[Index].removeAttribute(C, Kind); return getImpl(C, AttrSets); } AttributeList AttributeList::removeAttribute(LLVMContext &C, unsigned Index, StringRef Kind) const { if (!hasAttribute(Index, Kind)) return *this; Index = attrIdxToArrayIdx(Index); SmallVector AttrSets(this->begin(), this->end()); assert(Index < AttrSets.size()); AttrSets[Index] = AttrSets[Index].removeAttribute(C, Kind); return getImpl(C, AttrSets); } AttributeList AttributeList::removeAttributes(LLVMContext &C, unsigned Index, const AttrBuilder &AttrsToRemove) const { if (!pImpl) return {}; Index = attrIdxToArrayIdx(Index); SmallVector AttrSets(this->begin(), this->end()); if (Index >= AttrSets.size()) AttrSets.resize(Index + 1); AttrSets[Index] = AttrSets[Index].removeAttributes(C, AttrsToRemove); return getImpl(C, AttrSets); } AttributeList AttributeList::removeAttributes(LLVMContext &C, unsigned WithoutIndex) const { if (!pImpl) return {}; WithoutIndex = attrIdxToArrayIdx(WithoutIndex); if (WithoutIndex >= getNumAttrSets()) return *this; SmallVector AttrSets(this->begin(), this->end()); AttrSets[WithoutIndex] = AttributeSet(); return getImpl(C, AttrSets); } AttributeList AttributeList::addDereferenceableAttr(LLVMContext &C, unsigned Index, uint64_t Bytes) const { AttrBuilder B; B.addDereferenceableAttr(Bytes); return addAttributes(C, Index, B); } AttributeList AttributeList::addDereferenceableOrNullAttr(LLVMContext &C, unsigned Index, uint64_t Bytes) const { AttrBuilder B; B.addDereferenceableOrNullAttr(Bytes); return addAttributes(C, Index, B); } AttributeList AttributeList::addAllocSizeAttr(LLVMContext &C, unsigned Index, unsigned ElemSizeArg, const Optional &NumElemsArg) { AttrBuilder B; B.addAllocSizeAttr(ElemSizeArg, NumElemsArg); return addAttributes(C, Index, B); } //===----------------------------------------------------------------------===// // AttributeList Accessor Methods //===----------------------------------------------------------------------===// AttributeSet AttributeList::getParamAttributes(unsigned ArgNo) const { return getAttributes(ArgNo + FirstArgIndex); } AttributeSet AttributeList::getRetAttributes() const { return getAttributes(ReturnIndex); } AttributeSet AttributeList::getFnAttributes() const { return getAttributes(FunctionIndex); } bool AttributeList::hasAttribute(unsigned Index, Attribute::AttrKind Kind) const { return getAttributes(Index).hasAttribute(Kind); } bool AttributeList::hasAttribute(unsigned Index, StringRef Kind) const { return getAttributes(Index).hasAttribute(Kind); } bool AttributeList::hasAttributes(unsigned Index) const { return getAttributes(Index).hasAttributes(); } bool AttributeList::hasFnAttribute(Attribute::AttrKind Kind) const { return pImpl && pImpl->hasFnAttribute(Kind); } bool AttributeList::hasFnAttribute(StringRef Kind) const { return hasAttribute(AttributeList::FunctionIndex, Kind); } bool AttributeList::hasParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const { return hasAttribute(ArgNo + FirstArgIndex, Kind); } bool AttributeList::hasAttrSomewhere(Attribute::AttrKind Attr, unsigned *Index) const { return pImpl && pImpl->hasAttrSomewhere(Attr, Index); } Attribute AttributeList::getAttribute(unsigned Index, Attribute::AttrKind Kind) const { return getAttributes(Index).getAttribute(Kind); } Attribute AttributeList::getAttribute(unsigned Index, StringRef Kind) const { return getAttributes(Index).getAttribute(Kind); } MaybeAlign AttributeList::getRetAlignment() const { return getAttributes(ReturnIndex).getAlignment(); } MaybeAlign AttributeList::getParamAlignment(unsigned ArgNo) const { return getAttributes(ArgNo + FirstArgIndex).getAlignment(); } Type *AttributeList::getParamByValType(unsigned Index) const { return getAttributes(Index+FirstArgIndex).getByValType(); } Type *AttributeList::getParamStructRetType(unsigned Index) const { return getAttributes(Index + FirstArgIndex).getStructRetType(); } Type *AttributeList::getParamByRefType(unsigned Index) const { return getAttributes(Index + FirstArgIndex).getByRefType(); } Type *AttributeList::getParamPreallocatedType(unsigned Index) const { return getAttributes(Index + FirstArgIndex).getPreallocatedType(); } MaybeAlign AttributeList::getStackAlignment(unsigned Index) const { return getAttributes(Index).getStackAlignment(); } uint64_t AttributeList::getDereferenceableBytes(unsigned Index) const { return getAttributes(Index).getDereferenceableBytes(); } uint64_t AttributeList::getDereferenceableOrNullBytes(unsigned Index) const { return getAttributes(Index).getDereferenceableOrNullBytes(); } std::pair> AttributeList::getAllocSizeArgs(unsigned Index) const { return getAttributes(Index).getAllocSizeArgs(); } std::string AttributeList::getAsString(unsigned Index, bool InAttrGrp) const { return getAttributes(Index).getAsString(InAttrGrp); } AttributeSet AttributeList::getAttributes(unsigned Index) const { Index = attrIdxToArrayIdx(Index); if (!pImpl || Index >= getNumAttrSets()) return {}; return pImpl->begin()[Index]; } AttributeList::iterator AttributeList::begin() const { return pImpl ? pImpl->begin() : nullptr; } AttributeList::iterator AttributeList::end() const { return pImpl ? pImpl->end() : nullptr; } //===----------------------------------------------------------------------===// // AttributeList Introspection Methods //===----------------------------------------------------------------------===// unsigned AttributeList::getNumAttrSets() const { return pImpl ? pImpl->NumAttrSets : 0; } #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) LLVM_DUMP_METHOD void AttributeList::dump() const { dbgs() << ""PAL[\\n""; for (unsigned i = index_begin(), e = index_end(); i != e; ++i) { if (getAttributes(i).hasAttributes()) dbgs() << "" { "" << i << "" => "" << getAsString(i) << "" }\\n""; } dbgs() << ""]\\n""; } #endif //===----------------------------------------------------------------------===// // AttrBuilder Method Implementations //===----------------------------------------------------------------------===// // FIXME: Remove this ctor, use AttributeSet. AttrBuilder::AttrBuilder(AttributeList AL, unsigned Index) { AttributeSet AS = AL.getAttributes(Index); for (const auto &A : AS) addAttribute(A); } AttrBuilder::AttrBuilder(AttributeSet AS) { for (const auto &A : AS) addAttribute(A); } void AttrBuilder::clear() { Attrs.reset(); TargetDepAttrs.clear(); Alignment.reset(); StackAlignment.reset(); DerefBytes = DerefOrNullBytes = 0; AllocSizeArgs = 0; ByValType = nullptr; StructRetType = nullptr; ByRefType = nullptr; PreallocatedType = nullptr; } AttrBuilder &AttrBuilder::addAttribute(Attribute Attr) { if (Attr.isStringAttribute()) { addAttribute(Attr.getKindAsString(), Attr.getValueAsString()); return *this; } Attribute::AttrKind Kind = Attr.getKindAsEnum(); Attrs[Kind] = true; if (Kind == Attribute::Alignment) Alignment = Attr.getAlignment(); else if (Kind == Attribute::StackAlignment) StackAlignment = Attr.getStackAlignment(); else if (Kind == Attribute::ByVal) ByValType = Attr.getValueAsType(); else if (Kind == Attribute::StructRet) StructRetType = Attr.getValueAsType(); else if (Kind == Attribute::ByRef) ByRefType = Attr.getValueAsType(); else if (Kind == Attribute::Preallocated) PreallocatedType = Attr.getValueAsType(); else if (Kind == Attribute::Dereferenceable) DerefBytes = Attr.getDereferenceableBytes(); else if (Kind == Attribute::DereferenceableOrNull) DerefOrNullBytes = Attr.getDereferenceableOrNullBytes(); else if (Kind == Attribute::AllocSize) AllocSizeArgs = Attr.getValueAsInt(); return *this; } AttrBuilder &AttrBuilder::addAttribute(StringRef A, StringRef V) { TargetDepAttrs[std::string(A)] = std::string(V); return *this; } AttrBuilder &AttrBuilder::removeAttribute(Attribute::AttrKind Val) { assert((unsigned)Val < Attribute::EndAttrKinds && ""Attribute out of range!""); Attrs[Val] = false; if (Val == Attribute::Alignment) Alignment.reset(); else if (Val == Attribute::StackAlignment) StackAlignment.reset(); else if (Val == Attribute::ByVal) ByValType = nullptr; else if (Val == Attribute::StructRet) StructRetType = nullptr; else if (Val == Attribute::ByRef) ByRefType = nullptr; else if (Val == Attribute::Preallocated) PreallocatedType = nullptr; else if (Val == Attribute::Dereferenceable) DerefBytes = 0; else if (Val == Attribute::DereferenceableOrNull) DerefOrNullBytes = 0; else if (Val == Attribute::AllocSize) AllocSizeArgs = 0; return *this; } AttrBuilder &AttrBuilder::removeAttributes(AttributeList A, uint64_t Index) { remove(A.getAttributes(Index)); return *this; } AttrBuilder &AttrBuilder::removeAttribute(StringRef A) { auto I = TargetDepAttrs.find(A); if (I != TargetDepAttrs.end()) TargetDepAttrs.erase(I); return *this; } std::pair> AttrBuilder::getAllocSizeArgs() const { return unpackAllocSizeArgs(AllocSizeArgs); } AttrBuilder &AttrBuilder::addAlignmentAttr(MaybeAlign Align) { if (!Align) return *this; assert(*Align <= llvm::Value::MaximumAlignment && ""Alignment too large.""); Attrs[Attribute::Alignment] = true; Alignment = Align; return *this; } AttrBuilder &AttrBuilder::addStackAlignmentAttr(MaybeAlign Align) { // Default alignment, allow the target to define how to align it. if (!Align) return *this; assert(*Align <= 0x100 && ""Alignment too large.""); Attrs[Attribute::StackAlignment] = true; StackAlignment = Align; return *this; } AttrBuilder &AttrBuilder::addDereferenceableAttr(uint64_t Bytes) { if (Bytes == 0) return *this; Attrs[Attribute::Dereferenceable] = true; DerefBytes = Bytes; return *this; } AttrBuilder &AttrBuilder::addDereferenceableOrNullAttr(uint64_t Bytes) { if (Bytes == 0) return *this; Attrs[Attribute::DereferenceableOrNull] = true; DerefOrNullBytes = Bytes; return *this; } AttrBuilder &AttrBuilder::addAllocSizeAttr(unsigned ElemSize, const Optional &NumElems) { return addAllocSizeAttrFromRawRepr(packAllocSizeArgs(ElemSize, NumElems)); } AttrBuilder &AttrBuilder::addAllocSizeAttrFromRawRepr(uint64_t RawArgs) { // (0, 0) is our ""not present"" value, so we need to check for it here. assert(RawArgs && ""Invalid allocsize arguments -- given allocsize(0, 0)""); Attrs[Attribute::AllocSize] = true; // Reuse existing machinery to store this as a single 64-bit integer so we can // save a few bytes over using a pair>. AllocSizeArgs = RawArgs; return *this; } AttrBuilder &AttrBuilder::addByValAttr(Type *Ty) { Attrs[Attribute::ByVal] = true; ByValType = Ty; return *this; } AttrBuilder &AttrBuilder::addStructRetAttr(Type *Ty) { Attrs[Attribute::StructRet] = true; StructRetType = Ty; return *this; } AttrBuilder &AttrBuilder::addByRefAttr(Type *Ty) { Attrs[Attribute::ByRef] = true; ByRefType = Ty; return *this; } AttrBuilder &AttrBuilder::addPreallocatedAttr(Type *Ty) { Attrs[Attribute::Preallocated] = true; PreallocatedType = Ty; return *this; } AttrBuilder &AttrBuilder::merge(const AttrBuilder &B) { // FIXME: What if both have alignments, but they don't match?! if (!Alignment) Alignment = B.Alignment; if (!StackAlignment) StackAlignment = B.StackAlignment; if (!DerefBytes) DerefBytes = B.DerefBytes; if (!DerefOrNullBytes) DerefOrNullBytes = B.DerefOrNullBytes; if (!AllocSizeArgs) AllocSizeArgs = B.AllocSizeArgs; if (!ByValType) ByValType = B.ByValType; if (!StructRetType) StructRetType = B.StructRetType; if (!ByRefType) ByRefType = B.ByRefType; if (!PreallocatedType) PreallocatedType = B.PreallocatedType; Attrs |= B.Attrs; for (const auto &I : B.td_attrs()) TargetDepAttrs[I.first] = I.second; return *this; } AttrBuilder &AttrBuilder::remove(const AttrBuilder &B) { // FIXME: What if both have alignments, but they don't match?! if (B.Alignment) Alignment.reset(); if (B.StackAlignment) StackAlignment.reset(); if (B.DerefBytes) DerefBytes = 0; if (B.DerefOrNullBytes) DerefOrNullBytes = 0; if (B.AllocSizeArgs) AllocSizeArgs = 0; if (B.ByValType) ByValType = nullptr; if (B.StructRetType) StructRetType = nullptr; if (B.ByRefType) ByRefType = nullptr; if (B.PreallocatedType) PreallocatedType = nullptr; Attrs &= ~B.Attrs; for (const auto &I : B.td_attrs()) TargetDepAttrs.erase(I.first); return *this; } bool AttrBuilder::overlaps(const AttrBuilder &B) const { // First check if any of the target independent attributes overlap. if ((Attrs & B.Attrs).any()) return true; // Then check if any target dependent ones do. for (const auto &I : td_attrs()) if (B.contains(I.first)) return true; return false; } bool AttrBuilder::contains(StringRef A) const { return TargetDepAttrs.find(A) != TargetDepAttrs.end(); } bool AttrBuilder::hasAttributes() const { return !Attrs.none() || !TargetDepAttrs.empty(); } bool AttrBuilder::hasAttributes(AttributeList AL, uint64_t Index) const { AttributeSet AS = AL.getAttributes(Index); for (const auto &Attr : AS) { if (Attr.isEnumAttribute() || Attr.isIntAttribute()) { if (contains(Attr.getKindAsEnum())) return true; } else { assert(Attr.isStringAttribute() && ""Invalid attribute kind!""); return contains(Attr.getKindAsString()); } } return false; } bool AttrBuilder::hasAlignmentAttr() const { return Alignment != 0; } bool AttrBuilder::operator==(const AttrBuilder &B) const { if (Attrs != B.Attrs) return false; for (td_const_iterator I = TargetDepAttrs.begin(), E = TargetDepAttrs.end(); I != E; ++I) if (B.TargetDepAttrs.find(I->first) == B.TargetDepAttrs.end()) return false; return Alignment == B.Alignment && StackAlignment == B.StackAlignment && DerefBytes == B.DerefBytes && ByValType == B.ByValType && StructRetType == B.StructRetType && ByRefType == B.ByRefType && PreallocatedType == B.PreallocatedType; } //===----------------------------------------------------------------------===// // AttributeFuncs Function Defintions //===----------------------------------------------------------------------===// /// Which attributes cannot be applied to a type. AttrBuilder AttributeFuncs::typeIncompatible(Type *Ty) { AttrBuilder Incompatible; if (!Ty->isIntegerTy()) // Attribute that only apply to integers. Incompatible.addAttribute(Attribute::SExt) .addAttribute(Attribute::ZExt); if (!Ty->isPointerTy()) // Attribute that only apply to pointers. Incompatible.addAttribute(Attribute::Nest) .addAttribute(Attribute::NoAlias) .addAttribute(Attribute::NoCapture) .addAttribute(Attribute::NonNull) .addAlignmentAttr(1) // the int here is ignored .addDereferenceableAttr(1) // the int here is ignored .addDereferenceableOrNullAttr(1) // the int here is ignored .addAttribute(Attribute::ReadNone) .addAttribute(Attribute::ReadOnly) .addAttribute(Attribute::InAlloca) .addPreallocatedAttr(Ty) .addByValAttr(Ty) .addStructRetAttr(Ty) .addByRefAttr(Ty); // Some attributes can apply to all ""values"" but there are no `void` values. if (Ty->isVoidTy()) Incompatible.addAttribute(Attribute::NoUndef); return Incompatible; } template static bool isEqual(const Function &Caller, const Function &Callee) { return Caller.getFnAttribute(AttrClass::getKind()) == Callee.getFnAttribute(AttrClass::getKind()); } /// Compute the logical AND of the attributes of the caller and the /// callee. /// /// This function sets the caller's attribute to false if the callee's attribute /// is false. template static void setAND(Function &Caller, const Function &Callee) { if (AttrClass::isSet(Caller, AttrClass::getKind()) && !AttrClass::isSet(Callee, AttrClass::getKind())) AttrClass::set(Caller, AttrClass::getKind(), false); } /// Compute the logical OR of the attributes of the caller and the /// callee. /// /// This function sets the caller's attribute to true if the callee's attribute /// is true. template static void setOR(Function &Caller, const Function &Callee) { if (!AttrClass::isSet(Caller, AttrClass::getKind()) && AttrClass::isSet(Callee, AttrClass::getKind())) AttrClass::set(Caller, AttrClass::getKind(), true); } /// If the inlined function had a higher stack protection level than the /// calling function, then bump up the caller's stack protection level. static void adjustCallerSSPLevel(Function &Caller, const Function &Callee) { #ifndef NDEBUG if (!Callee.hasFnAttribute(Attribute::AlwaysInline)) { assert(!(!Callee.hasStackProtectorFnAttr() && Caller.hasStackProtectorFnAttr()) && ""stack protected caller but callee requested no stack protector""); assert(!(!Caller.hasStackProtectorFnAttr() && Callee.hasStackProtectorFnAttr()) && ""stack protected callee but caller requested no stack protector""); } #endif // If upgrading the SSP attribute, clear out the old SSP Attributes first. // Having multiple SSP attributes doesn't actually hurt, but it adds useless // clutter to the IR. AttrBuilder OldSSPAttr; OldSSPAttr.addAttribute(Attribute::StackProtect) .addAttribute(Attribute::StackProtectStrong) .addAttribute(Attribute::StackProtectReq); if (Callee.hasFnAttribute(Attribute::StackProtectReq)) { Caller.removeAttributes(AttributeList::FunctionIndex, OldSSPAttr); Caller.addFnAttr(Attribute::StackProtectReq); } else if (Callee.hasFnAttribute(Attribute::StackProtectStrong) && !Caller.hasFnAttribute(Attribute::StackProtectReq)) { Caller.removeAttributes(AttributeList::FunctionIndex, OldSSPAttr); Caller.addFnAttr(Attribute::StackProtectStrong); } else if (Callee.hasFnAttribute(Attribute::StackProtect) && !Caller.hasFnAttribute(Attribute::StackProtectReq) && !Caller.hasFnAttribute(Attribute::StackProtectStrong)) Caller.addFnAttr(Attribute::StackProtect); } /// If the inlined function required stack probes, then ensure that /// the calling function has those too. static void adjustCallerStackProbes(Function &Caller, const Function &Callee) { if (!Caller.hasFnAttribute(""probe-stack"") && Callee.hasFnAttribute(""probe-stack"")) { Caller.addFnAttr(Callee.getFnAttribute(""probe-stack"")); } } /// If the inlined function defines the size of guard region /// on the stack, then ensure that the calling function defines a guard region /// that is no larger. static void adjustCallerStackProbeSize(Function &Caller, const Function &Callee) { Attribute CalleeAttr = Callee.getFnAttribute(""stack-probe-size""); if (CalleeAttr.isValid()) { Attribute CallerAttr = Caller.getFnAttribute(""stack-probe-size""); if (CallerAttr.isValid()) { uint64_t CallerStackProbeSize, CalleeStackProbeSize; CallerAttr.getValueAsString().getAsInteger(0, CallerStackProbeSize); CalleeAttr.getValueAsString().getAsInteger(0, CalleeStackProbeSize); if (CallerStackProbeSize > CalleeStackProbeSize) { Caller.addFnAttr(CalleeAttr); } } else { Caller.addFnAttr(CalleeAttr); } } } /// If the inlined function defines a min legal vector width, then ensure /// the calling function has the same or larger min legal vector width. If the /// caller has the attribute, but the callee doesn't, we need to remove the /// attribute from the caller since we can't make any guarantees about the /// caller's requirements. /// This function is called after the inlining decision has been made so we have /// to merge the attribute this way. Heuristics that would use /// min-legal-vector-width to determine inline compatibility would need to be /// handled as part of inline cost analysis. static void adjustMinLegalVectorWidth(Function &Caller, const Function &Callee) { Attribute CallerAttr = Caller.getFnAttribute(""min-legal-vector-width""); if (CallerAttr.isValid()) { Attribute CalleeAttr = Callee.getFnAttribute(""min-legal-vector-width""); if (CalleeAttr.isValid()) { uint64_t CallerVectorWidth, CalleeVectorWidth; CallerAttr.getValueAsString().getAsInteger(0, CallerVectorWidth); CalleeAttr.getValueAsString().getAsInteger(0, CalleeVectorWidth); if (CallerVectorWidth < CalleeVectorWidth) Caller.addFnAttr(CalleeAttr); } else { // If the callee doesn't have the attribute then we don't know anything // and must drop the attribute from the caller. Caller.removeFnAttr(""min-legal-vector-width""); } } } /// If the inlined function has null_pointer_is_valid attribute, /// set this attribute in the caller post inlining. static void adjustNullPointerValidAttr(Function &Caller, const Function &Callee) { if (Callee.nullPointerIsDefined() && !Caller.nullPointerIsDefined()) { Caller.addFnAttr(Attribute::NullPointerIsValid); } } struct EnumAttr { static bool isSet(const Function &Fn, Attribute::AttrKind Kind) { return Fn.hasFnAttribute(Kind); } static void set(Function &Fn, Attribute::AttrKind Kind, bool Val) { if (Val) Fn.addFnAttr(Kind); else Fn.removeFnAttr(Kind); } }; struct StrBoolAttr { static bool isSet(const Function &Fn, StringRef Kind) { auto A = Fn.getFnAttribute(Kind); return A.getValueAsString().equals(""true""); } static void set(Function &Fn, StringRef Kind, bool Val) { Fn.addFnAttr(Kind, Val ? ""true"" : ""false""); } }; #define GET_ATTR_NAMES #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \\ struct ENUM_NAME##Attr : EnumAttr { \\ static enum Attribute::AttrKind getKind() { \\ return llvm::Attribute::ENUM_NAME; \\ } \\ }; #define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME) \\ struct ENUM_NAME##Attr : StrBoolAttr { \\ static StringRef getKind() { return #DISPLAY_NAME; } \\ }; #include ""llvm/IR/Attributes.inc"" #define GET_ATTR_COMPAT_FUNC #include ""llvm/IR/Attributes.inc"" bool AttributeFuncs::areInlineCompatible(const Function &Caller, const Function &Callee) { return hasCompatibleFnAttrs(Caller, Callee); } bool AttributeFuncs::areOutlineCompatible(const Function &A, const Function &B) { return hasCompatibleFnAttrs(A, B); } void AttributeFuncs::mergeAttributesForInlining(Function &Caller, const Function &Callee) { mergeFnAttrs(Caller, Callee); } void AttributeFuncs::mergeAttributesForOutlining(Function &Base, const Function &ToMerge) { // We merge functions so that they meet the most general case. // For example, if the NoNansFPMathAttr is set in one function, but not in // the other, in the merged function we can say that the NoNansFPMathAttr // is not set. // However if we have the SpeculativeLoadHardeningAttr set true in one // function, but not the other, we make sure that the function retains // that aspect in the merged function. mergeFnAttrs(Base, ToMerge); } ",16262,True,2743.6470812101043,median ":spring-data-commons-ref: https://docs.spring.io/spring-data/data-commons/docs/current/reference/html == Spring Data Cloud Spanner https://projects.spring.io/spring-data/[Spring Data] is an abstraction for storing and retrieving POJOs in numerous storage technologies. Spring Cloud GCP adds Spring Data support for https://cloud.google.com/spanner/[Google Cloud Spanner]. Maven coordinates for this module only, using <>: [source,xml] ---- com.google.cloud spring-cloud-gcp-data-spanner ---- Gradle coordinates: [source] ---- dependencies { implementation(""com.google.cloud:spring-cloud-gcp-data-spanner"") } ---- We provide a link:../spring-cloud-gcp-starters/spring-cloud-gcp-starter-data-spanner[Spring Boot Starter for Spring Data Spanner], with which you can leverage our recommended auto-configuration setup. To use the starter, see the coordinates see below. Maven: [source,xml] ---- com.google.cloud spring-cloud-gcp-starter-data-spanner ---- Gradle: [source,subs=""normal""] ---- dependencies { implementation(""com.google.cloud:spring-cloud-gcp-starter-data-spanner"") } ---- This setup takes care of bringing in the latest compatible version of Cloud Java Cloud Spanner libraries as well. === Configuration To setup Spring Data Cloud Spanner, you have to configure the following: * Setup the connection details to Google Cloud Spanner. * Enable Spring Data Repositories (optional). ==== Cloud Spanner settings You can the use link:../spring-cloud-gcp-starters/spring-cloud-gcp-starter-data-spanner[Spring Boot Starter for Spring Data Spanner] to autoconfigure Google Cloud Spanner in your Spring application. It contains all the necessary setup that makes it easy to authenticate with your Google Cloud project. The following configuration options are available: |=== | Name | Description | Required | Default value | `spring.cloud.gcp.spanner.instance-id` | Cloud Spanner instance to use | Yes | | `spring.cloud.gcp.spanner.database` | Cloud Spanner database to use | Yes | | `spring.cloud.gcp.spanner.project-id` | GCP project ID where the Google Cloud Spanner API is hosted, if different from the one in the <> | No | | `spring.cloud.gcp.spanner.credentials.location` | OAuth2 credentials for authenticating with the Google Cloud Spanner API, if different from the ones in the <> | No | | `spring.cloud.gcp.spanner.credentials.encoded-key` | Base64-encoded OAuth2 credentials for authenticating with the Google Cloud Spanner API, if different from the ones in the <> | No | | `spring.cloud.gcp.spanner.credentials.scopes` | https://developers.google.com/identity/protocols/googlescopes[OAuth2 scope] for Spring Cloud GCP Cloud Spanner credentials | No | https://www.googleapis.com/auth/spanner.data | `spring.cloud.gcp.spanner.createInterleavedTableDdlOnDeleteCascade` | If `true`, then schema statements generated by `SpannerSchemaUtils` for tables with interleaved parent-child relationships will be ""ON DELETE CASCADE"". The schema for the tables will be ""ON DELETE NO ACTION"" if `false`. | No | `true` | `spring.cloud.gcp.spanner.numRpcChannels` | Number of gRPC channels used to connect to Cloud Spanner | No | 4 - Determined by Cloud Spanner client library | `spring.cloud.gcp.spanner.prefetchChunks` | Number of chunks prefetched by Cloud Spanner for read and query | No | 4 - Determined by Cloud Spanner client library | `spring.cloud.gcp.spanner.minSessions` | Minimum number of sessions maintained in the session pool | No | 0 - Determined by Cloud Spanner client library | `spring.cloud.gcp.spanner.maxSessions` | Maximum number of sessions session pool can have | No | 400 - Determined by Cloud Spanner client library | `spring.cloud.gcp.spanner.maxIdleSessions` | Maximum number of idle sessions session pool will maintain | No | 0 - Determined by Cloud Spanner client library | `spring.cloud.gcp.spanner.writeSessionsFraction` | Fraction of sessions to be kept prepared for write transactions | No | 0.2 - Determined by Cloud Spanner client library | `spring.cloud.gcp.spanner.keepAliveIntervalMinutes` | How long to keep idle sessions alive | No | 30 - Determined by Cloud Spanner client library | `spring.cloud.gcp.spanner.failIfPoolExhausted` | If all sessions are in use, fail the request by throwing an exception. Otherwise, by default, block until a session becomes available. | No | `false` | `spring.cloud.gcp.spanner.emulator.enabled` | Enables the usage of an emulator. If this is set to true, then you should set the `spring.cloud.gcp.spanner.emulator-host` to the host:port of your locally running emulator instance. | No | `false` | `spring.cloud.gcp.spanner.emulator-host` | The host and port of the Spanner emulator; can be overridden to specify connecting to an already-running https://cloud.google.com/spanner/docs/emulator#installing_and_running_the_emulator[Spanner emulator] instance. | No | `localhost:9010` |=== ==== Repository settings Spring Data Repositories can be configured via the `@EnableSpannerRepositories` annotation on your main `@Configuration` class. With our Spring Boot Starter for Spring Data Cloud Spanner, `@EnableSpannerRepositories` is automatically added. It is not required to add it to any other class, unless there is a need to override finer grain configuration parameters provided by https://github.com/GoogleCloudPlatform/spring-cloud-gcp/blob/master/spring-cloud-gcp-data-spanner/src/main/java/com/google/cloud/spring/data/spanner/repository/config/EnableSpannerRepositories.java[`@EnableSpannerRepositories`]. ==== Autoconfiguration Our Spring Boot autoconfiguration creates the following beans available in the Spring application context: - an instance of `SpannerTemplate` - an instance of `SpannerDatabaseAdminTemplate` for generating table schemas from object hierarchies and creating and deleting tables and databases - an instance of all user-defined repositories extending `SpannerRepository`, `CrudRepository`, `PagingAndSortingRepository`, when repositories are enabled - an instance of `DatabaseClient` from the Google Cloud Java Client for Spanner, for convenience and lower level API access === Object Mapping Spring Data Cloud Spanner allows you to map domain POJOs to Cloud Spanner tables via annotations: [source,java] ---- @Table(name = ""traders"") public class Trader { @PrimaryKey @Column(name = ""trader_id"") String traderId; String firstName; String lastName; @NotMapped Double temporaryNumber; } ---- Spring Data Cloud Spanner will ignore any property annotated with `@NotMapped`. These properties will not be written to or read from Spanner. ==== Constructors Simple constructors are supported on POJOs. The constructor arguments can be a subset of the persistent properties. Every constructor argument needs to have the same name and type as a persistent property on the entity and the constructor should set the property from the given argument. Arguments that are not directly set to properties are not supported. [source,java] ---- @Table(name = ""traders"") public class Trader { @PrimaryKey @Column(name = ""trader_id"") String traderId; String firstName; String lastName; @NotMapped Double temporaryNumber; public Trader(String traderId, String firstName) { this.traderId = traderId; this.firstName = firstName; } } ---- ==== Table The `@Table` annotation can provide the name of the Cloud Spanner table that stores instances of the annotated class, one per row. This annotation is optional, and if not given, the name of the table is inferred from the class name with the first character uncapitalized. ===== SpEL expressions for table names In some cases, you might want the `@Table` table name to be determined dynamically. To do that, you can use https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#expressions[Spring Expression Language]. For example: [source, java] ---- @Table(name = ""trades_#{tableNameSuffix}"") public class Trade { // ... } ---- The table name will be resolved only if the `tableNameSuffix` value/bean in the Spring application context is defined. For example, if `tableNameSuffix` has the value ""123"", the table name will resolve to `trades_123`. ==== Primary Keys For a simple table, you may only have a primary key consisting of a single column. Even in that case, the `@PrimaryKey` annotation is required. `@PrimaryKey` identifies the one or more ID properties corresponding to the primary key. Spanner has first class support for composite primary keys of multiple columns. You have to annotate all of your POJO's fields that the primary key consists of with `@PrimaryKey` as below: [source,java] ---- @Table(name = ""trades"") public class Trade { @PrimaryKey(keyOrder = 2) @Column(name = ""trade_id"") private String tradeId; @PrimaryKey(keyOrder = 1) @Column(name = ""trader_id"") private String traderId; private String action; private BigDecimal price; private Double shares; private String symbol; } ---- The `keyOrder` parameter of `@PrimaryKey` identifies the properties corresponding to the primary key columns in order, starting with 1 and increasing consecutively. Order is important and must reflect the order defined in the Cloud Spanner schema. In our example the DDL to create the table and its primary key is as follows: [source,sql] ---- CREATE TABLE trades ( trader_id STRING(MAX), trade_id STRING(MAX), action STRING(15), symbol STRING(10), price NUMERIC, shares FLOAT64 ) PRIMARY KEY (trader_id, trade_id) ---- Spanner does not have automatic ID generation. For most use-cases, sequential IDs should be used with caution to avoid creating data hotspots in the system. Read https://cloud.google.com/spanner/docs/schema-and-data-model#primary_keys[Spanner Primary Keys documentation] for a better understanding of primary keys and recommended practices. ==== Columns All accessible properties on POJOs are automatically recognized as a Cloud Spanner column. Column naming is generated by the `PropertyNameFieldNamingStrategy` by default defined on the `SpannerMappingContext` bean. The `@Column` annotation optionally provides a different column name than that of the property and some other settings: - `name` is the optional name of the column - `spannerTypeMaxLength` specifies for `STRING` and `BYTES` columns the maximum length. This setting is only used when generating DDL schema statements based on domain types. - `nullable` specifies if the column is created as `NOT NULL`. This setting is only used when generating DDL schema statements based on domain types. - `spannerType` is the Cloud Spanner column type you can optionally specify. If this is not specified then a compatible column type is inferred from the Java property type. - `spannerCommitTimestamp` is a boolean specifying if this property corresponds to an auto-populated commit timestamp column. Any value set in this property will be ignored when writing to Cloud Spanner. ==== Embedded Objects If an object of type `B` is embedded as a property of `A`, then the columns of `B` will be saved in the same Cloud Spanner table as those of `A`. If `B` has primary key columns, those columns will be included in the primary key of `A`. `B` can also have embedded properties. Embedding allows reuse of columns between multiple entities, and can be useful for implementing parent-child situations, because Cloud Spanner requires child tables to include the key columns of their parents. For example: [source,java] ---- class X { @PrimaryKey String grandParentId; long age; } class A { @PrimaryKey @Embedded X grandParent; @PrimaryKey(keyOrder = 2) String parentId; String value; } @Table(name = ""items"") class B { @PrimaryKey @Embedded A parent; @PrimaryKey(keyOrder = 2) String id; @Column(name = ""child_value"") String value; } ---- Entities of `B` can be stored in a table defined as: [source,sql] ---- CREATE TABLE items ( grandParentId STRING(MAX), parentId STRING(MAX), id STRING(MAX), value STRING(MAX), child_value STRING(MAX), age INT64 ) PRIMARY KEY (grandParentId, parentId, id) ---- Note that embedded properties' column names must all be unique. ==== Relationships Spring Data Cloud Spanner supports parent-child relationships using the Cloud Spanner https://cloud.google.com/spanner/docs/schema-and-data-model#creating-interleaved-tables[parent-child interleaved table mechanism]. Cloud Spanner interleaved tables enforce the one-to-many relationship and provide efficient queries and operations on entities of a single domain parent entity. These relationships can be up to 7 levels deep. Cloud Spanner also provides automatic cascading delete or enforces the deletion of child entities before parents. While one-to-one and many-to-many relationships can be implemented in Cloud Spanner and Spring Data Cloud Spanner using constructs of interleaved parent-child tables, only the parent-child relationship is natively supported. Cloud Spanner does not support the foreign key constraint, though the parent-child key constraint enforces a similar requirement when used with interleaved tables. For example, the following Java entities: [source,java] ---- @Table(name = ""Singers"") class Singer { @PrimaryKey long SingerId; String FirstName; String LastName; byte[] SingerInfo; @Interleaved List albums; } @Table(name = ""Albums"") class Album { @PrimaryKey long SingerId; @PrimaryKey(keyOrder = 2) long AlbumId; String AlbumTitle; } ---- These classes can correspond to an existing pair of interleaved tables. The `@Interleaved` annotation may be applied to `Collection` properties and the inner type is resolved as the child entity type. The schema needed to create them can also be generated using the `SpannerSchemaUtils` and run by using the `SpannerDatabaseAdminTemplate`: [source,java] ---- @Autowired SpannerSchemaUtils schemaUtils; @Autowired SpannerDatabaseAdminTemplate databaseAdmin; ... // Get the create statmenets for all tables in the table structure rooted at Singer List createStrings = this.schemaUtils.getCreateTableDdlStringsForInterleavedHierarchy(Singer.class); // Create the tables and also create the database if necessary this.databaseAdmin.executeDdlStrings(createStrings, true); ---- The `createStrings` list contains table schema statements using column names and types compatible with the provided Java type and any resolved child relationship types contained within based on the configured custom converters. [source,sql] ---- CREATE TABLE Singers ( SingerId INT64 NOT NULL, FirstName STRING(1024), LastName STRING(1024), SingerInfo BYTES(MAX), ) PRIMARY KEY (SingerId); CREATE TABLE Albums ( SingerId INT64 NOT NULL, AlbumId INT64 NOT NULL, AlbumTitle STRING(MAX), ) PRIMARY KEY (SingerId, AlbumId), INTERLEAVE IN PARENT Singers ON DELETE CASCADE; ---- The `ON DELETE CASCADE` clause indicates that Cloud Spanner will delete all Albums of a singer if the Singer is deleted. The alternative is `ON DELETE NO ACTION`, where a Singer cannot be deleted until all of its Albums have already been deleted. When using `SpannerSchemaUtils` to generate the schema strings, the `spring.cloud.gcp.spanner.createInterleavedTableDdlOnDeleteCascade` boolean setting determines if these schema are generated as `ON DELETE CASCADE` for `true` and `ON DELETE NO ACTION` for `false`. Cloud Spanner restricts these relationships to 7 child layers. A table may have multiple child tables. On updating or inserting an object to Cloud Spanner, all of its referenced children objects are also updated or inserted in the same request, respectively. On read, all of the interleaved child rows are also all read. ===== Lazy Fetch `@Interleaved` properties are retrieved eagerly by default, but can be fetched lazily for performance in both read and write: [source,java] ---- @Interleaved(lazy = true) List albums; ---- Lazily-fetched interleaved properties are retrieved upon the first interaction with the property. If a property marked for lazy fetching is never retrieved, then it is also skipped when saving the parent entity. If used inside a transaction, subsequent operations on lazily-fetched properties use the same transaction context as that of the original parent entity. ===== Declarative Filtering with `@Where` The `@Where` annotation could be applied to an entity class or to an interleaved property. This annotation provides an SQL where clause that will be applied at the fetching of interleaved collections or the entity itself. Let's say we have an `Agreement` with a list of `Participants` which could be assigned to it. We would like to fetch a list of currently active participants. For security reasons, all records should remain in the database forever, even if participants become inactive. That can be easily achieved with the `@Where` annotation, which is demonstrated by this example: [source, java] ---- @Table(name = ""participants"") public class Participant { //... boolean active; //... } @Table(name = ""agreements"") public class Agreement { //... @Interleaved @Where(""active = true"") List participants; Person person; //... } ---- ==== Supported Types Spring Data Cloud Spanner natively supports the following types for regular fields but also utilizes custom converters (detailed in following sections) and dozens of pre-defined Spring Data custom converters to handle other common Java types. Natively supported types: * `com.google.cloud.ByteArray` * `com.google.cloud.Date` * `com.google.cloud.Timestamp` * `java.lang.Boolean`, `boolean` * `java.lang.Double`, `double` * `java.lang.Long`, `long` * `java.lang.Integer`, `int` * `java.lang.String` * `double[]` * `long[]` * `boolean[]` * `java.util.Date` * `java.time.Instant` * `java.sql.Date` * `java.time.LocalDate` * `java.time.LocalDateTime` ==== Lists Spanner supports `ARRAY` types for columns. `ARRAY` columns are mapped to `List` fields in POJOS. Example: [source,java] ---- List curve; ---- The types inside the lists can be any singular property type. ==== Lists of Structs Cloud Spanner queries can https://cloud.google.com/spanner/docs/query-syntax#using-structs-with-select[construct STRUCT values] that appear as columns in the result. Cloud Spanner requires STRUCT values appear in ARRAYs at the root level: `SELECT ARRAY(SELECT STRUCT(1 as val1, 2 as val2)) as pair FROM Users`. Spring Data Cloud Spanner will attempt to read the column STRUCT values into a property that is an `Iterable` of an entity type compatible with the schema of the column STRUCT value. For the previous array-select example, the following property can be mapped with the constructed `ARRAY` column: `List pair;` where the `TwoInts` type is defined: [source, java] ---- class TwoInts { int val1; int val2; } ---- ==== Custom types Custom converters can be used to extend the type support for user defined types. . Converters need to implement the `org.springframework.core.convert.converter.Converter` interface in both directions. . The user defined type needs to be mapped to one of the basic types supported by Spanner: * `com.google.cloud.ByteArray` * `com.google.cloud.Date` * `com.google.cloud.Timestamp` * `java.lang.Boolean`, `boolean` * `java.lang.Double`, `double` * `java.lang.Long`, `long` * `java.lang.String` * `double[]` * `long[]` * `boolean[]` * `enum` types . An instance of both Converters needs to be passed to a `ConverterAwareMappingSpannerEntityProcessor`, which then has to be made available as a `@Bean` for `SpannerEntityProcessor`. For example: We would like to have a field of type `Person` on our `Trade` POJO: [source, java] ---- @Table(name = ""trades"") public class Trade { //... Person person; //... } ---- Where Person is a simple class: [source, java] ---- public class Person { public String firstName; public String lastName; } ---- We have to define the two converters: [source, java] ---- public class PersonWriteConverter implements Converter { @Override public String convert(Person person) { return person.firstName + "" "" + person.lastName; } } public class PersonReadConverter implements Converter { @Override public Person convert(String s) { Person person = new Person(); person.firstName = s.split("" "")[0]; person.lastName = s.split("" "")[1]; return person; } } ---- That will be configured in our `@Configuration` file: [source, java] ---- @Configuration public class ConverterConfiguration { @Bean public SpannerEntityProcessor spannerEntityProcessor(SpannerMappingContext spannerMappingContext) { return new ConverterAwareMappingSpannerEntityProcessor(spannerMappingContext, Arrays.asList(new PersonWriteConverter()), Arrays.asList(new PersonReadConverter())); } } ---- ==== Custom Converter for Struct Array Columns If a `Converter` is provided, then properties of type `List` can be used in your entity types. === Spanner Operations & Template `SpannerOperations` and its implementation, `SpannerTemplate`, provides the Template pattern familiar to Spring developers. It provides: - Resource management - One-stop-shop to Spanner operations with the Spring Data POJO mapping and conversion features - Exception conversion Using the `autoconfigure` provided by our Spring Boot Starter for Spanner, your Spring application context will contain a fully configured `SpannerTemplate` object that you can easily autowire in your application: [source,java] ---- @SpringBootApplication public class SpannerTemplateExample { @Autowired SpannerTemplate spannerTemplate; public void doSomething() { this.spannerTemplate.delete(Trade.class, KeySet.all()); //... Trade t = new Trade(); //... this.spannerTemplate.insert(t); //... List tradesByAction = spannerTemplate.findAll(Trade.class); //... } } ---- The Template API provides convenience methods for: - https://cloud.google.com/spanner/docs/reads[Reads], and by providing SpannerReadOptions and SpannerQueryOptions ** Stale read ** Read with secondary indices ** Read with limits and offsets ** Read with sorting - https://cloud.google.com/spanner/docs/reads#execute_a_query[Queries] - DML operations (delete, insert, update, upsert) - Partial reads ** You can define a set of columns to be read into your entity - Partial writes ** Persist only a few properties from your entity - Read-only transactions - Locking read-write transactions ==== SQL Query Cloud Spanner has SQL support for running read-only queries. All the query related methods start with `query` on `SpannerTemplate`. By using `SpannerTemplate`, you can run SQL queries that map to POJOs: [source,java] ---- List trades = this.spannerTemplate.query(Trade.class, Statement.of(""SELECT * FROM trades"")); ---- ==== Read Spanner exposes a https://cloud.google.com/spanner/docs/reads[Read API] for reading single row or multiple rows in a table or in a secondary index. Using `SpannerTemplate` you can run reads, as the following example shows: [source,java] ---- List trades = this.spannerTemplate.readAll(Trade.class); ---- Main benefit of reads over queries is reading multiple rows of a certain pattern of keys is much easier using the features of the https://github.com/GoogleCloudPlatform/google-cloud-java/blob/master/google-cloud-spanner/src/main/java/com/google/cloud/spanner/KeySet.java[`KeySet`] class. ==== Advanced reads ===== Stale read All reads and queries are *strong reads* by default. A *strong read* is a read at a current time and is guaranteed to see all data that has been committed up until the start of this read. An *exact staleness read* is read at a timestamp in the past. Cloud Spanner allows you to determine how current the data should be when you read data. With `SpannerTemplate` you can specify the `Timestamp` by setting it on `SpannerQueryOptions` or `SpannerReadOptions` to the appropriate read or query methods: Reads: [source,java] ---- // a read with options: SpannerReadOptions spannerReadOptions = new SpannerReadOptions().setTimestamp(myTimestamp); List trades = this.spannerTemplate.readAll(Trade.class, spannerReadOptions); ---- Queries: [source,java] ---- // a query with options: SpannerQueryOptions spannerQueryOptions = new SpannerQueryOptions().setTimestamp(myTimestamp); List trades = this.spannerTemplate.query(Trade.class, Statement.of(""SELECT * FROM trades""), spannerQueryOptions); ---- You can also read with https://cloud.google.com/spanner/docs/timestamp-bounds[*bounded staleness*] by setting `.setTimestampBound(TimestampBound.ofMinReadTimestamp(myTimestamp))` on the query and read options objects. Bounded staleness lets Cloud Spanner choose any point in time later than or equal to the given timestampBound, but it cannot be used inside transactions. ===== Read from a secondary index Using a https://cloud.google.com/spanner/docs/secondary-indexes[secondary index] is available for Reads via the Template API and it is also implicitly available via SQL for Queries. The following shows how to read rows from a table using a https://cloud.google.com/spanner/docs/secondary-indexes[secondary index] simply by setting `index` on `SpannerReadOptions`: [source,java] ---- SpannerReadOptions spannerReadOptions = new SpannerReadOptions().setIndex(""TradesByTrader""); List trades = this.spannerTemplate.readAll(Trade.class, spannerReadOptions); ---- ===== Read with offsets and limits Limits and offsets are only supported by Queries. The following will get only the first two rows of the query: [source,java] ---- SpannerQueryOptions spannerQueryOptions = new SpannerQueryOptions().setLimit(2).setOffset(3); List trades = this.spannerTemplate.query(Trade.class, Statement.of(""SELECT * FROM trades""), spannerQueryOptions); ---- Note that the above is equivalent of running `SELECT * FROM trades LIMIT 2 OFFSET 3`. ===== Sorting Reads by keys do not support sorting. However, queries on the Template API support sorting through standard SQL and also via Spring Data Sort API: [source,java] ---- List trades = this.spannerTemplate.queryAll(Trade.class, Sort.by(""action"")); ---- If the provided sorted field name is that of a property of the domain type, then the column name corresponding to that property will be used in the query. Otherwise, the given field name is assumed to be the name of the column in the Cloud Spanner table. Sorting on columns of Cloud Spanner types STRING and BYTES can be done while ignoring case: [source,java] ---- Sort.by(Order.desc(""action"").ignoreCase()) ---- ===== Partial read Partial read is only possible when using Queries. In case the rows returned by the query have fewer columns than the entity that it will be mapped to, Spring Data will map the returned columns only. This setting also applies to nested structs and their corresponding nested POJO properties. [source,java] ---- List trades = this.spannerTemplate.query(Trade.class, Statement.of(""SELECT action, symbol FROM trades""), new SpannerQueryOptions().setAllowMissingResultSetColumns(true)); ---- If the setting is set to `false`, then an exception will be thrown if there are missing columns in the query result. ===== Summary of options for Query vs Read |=== | Feature | Query supports it | Read supports it | SQL | yes | no | Partial read | yes | no | Limits | yes | no | Offsets | yes | no | Secondary index | yes | yes | Read using index range | no | yes | Sorting | yes | no |=== ==== Write / Update The write methods of `SpannerOperations` accept a POJO and writes all of its properties to Spanner. The corresponding Spanner table and entity metadata is obtained from the given object's actual type. If a POJO was retrieved from Spanner and its primary key properties values were changed and then written or updated, the operation will occur as if against a row with the new primary key values. The row with the original primary key values will not be affected. ===== Insert The `insert` method of `SpannerOperations` accepts a POJO and writes all of its properties to Spanner, which means the operation will fail if a row with the POJO's primary key already exists in the table. [source, java] ---- Trade t = new Trade(); this.spannerTemplate.insert(t); ---- ===== Update The `update` method of `SpannerOperations` accepts a POJO and writes all of its properties to Spanner, which means the operation will fail if the POJO's primary key does not already exist in the table. [source, java] ---- // t was retrieved from a previous operation this.spannerTemplate.update(t); ---- ===== Upsert The `upsert` method of `SpannerOperations` accepts a POJO and writes all of its properties to Spanner using update-or-insert. [source, java] ---- // t was retrieved from a previous operation or it's new this.spannerTemplate.upsert(t); ---- ===== Partial Update The update methods of `SpannerOperations` operate by default on all properties within the given object, but also accept `String[]` and `Optional>` of column names. If the `Optional` of set of column names is empty, then all columns are written to Spanner. However, if the Optional is occupied by an empty set, then no columns will be written. [source, java] ---- // t was retrieved from a previous operation or it's new this.spannerTemplate.update(t, ""symbol"", ""action""); ---- ==== DML DML statements can be run by using `SpannerOperations.executeDmlStatement`. Inserts, updates, and deletions can affect any number of rows and entities. You can run https://cloud.google.com/spanner/docs/dml-partitioned[partitioned DML] updates by using the `executePartitionedDmlStatement` method. Partitioned DML queries have performance benefits but also have restrictions and cannot be used inside transactions. ==== Transactions `SpannerOperations` provides methods to run `java.util.Function` objects within a single transaction while making available the read and write methods from `SpannerOperations`. ===== Read/Write Transaction Read and write transactions are provided by `SpannerOperations` via the `performReadWriteTransaction` method: [source,java] ---- @Autowired SpannerOperations mySpannerOperations; public String doWorkInsideTransaction() { return mySpannerOperations.performReadWriteTransaction( transActionSpannerOperations -> { // Work with transActionSpannerOperations here. // It is also a SpannerOperations object. return ""transaction completed""; } ); } ---- The `performReadWriteTransaction` method accepts a `Function` that is provided an instance of a `SpannerOperations` object. The final returned value and type of the function is determined by the user. You can use this object just as you would a regular `SpannerOperations` with a few exceptions: - Its read functionality cannot perform stale reads, because all reads and writes happen at the single point in time of the transaction. - It cannot perform sub-transactions via `performReadWriteTransaction` or `performReadOnlyTransaction`. As these read-write transactions are locking, it is recommended that you use the `performReadOnlyTransaction` if your function does not perform any writes. ===== Read-only Transaction The `performReadOnlyTransaction` method is used to perform read-only transactions using a `SpannerOperations`: [source,java] ---- @Autowired SpannerOperations mySpannerOperations; public String doWorkInsideTransaction() { return mySpannerOperations.performReadOnlyTransaction( transActionSpannerOperations -> { // Work with transActionSpannerOperations here. // It is also a SpannerOperations object. return ""transaction completed""; } ); } ---- The `performReadOnlyTransaction` method accepts a `Function` that is provided an instance of a `SpannerOperations` object. This method also accepts a `ReadOptions` object, but the only attribute used is the timestamp used to determine the snapshot in time to perform the reads in the transaction. If the timestamp is not set in the read options the transaction is run against the current state of the database. The final returned value and type of the function is determined by the user. You can use this object just as you would a regular `SpannerOperations` with a few exceptions: - Its read functionality cannot perform stale reads (other than the staleness set on the entire transaction), because all reads happen at the single point in time of the transaction. - It cannot perform sub-transactions via `performReadWriteTransaction` or `performReadOnlyTransaction` - It cannot perform any write operations. Because read-only transactions are non-locking and can be performed on points in time in the past, these are recommended for functions that do not perform write operations. ===== Declarative Transactions with @Transactional Annotation This feature requires a bean of `SpannerTransactionManager`, which is provided when using `spring-cloud-gcp-starter-data-spanner`. `SpannerTemplate` and `SpannerRepository` support running methods with the `@Transactional` https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#transaction-declarative[annotation] as transactions. If a method annotated with `@Transactional` calls another method also annotated, then both methods will work within the same transaction. `performReadOnlyTransaction` and `performReadWriteTransaction` cannot be used in `@Transactional` annotated methods because Cloud Spanner does not support transactions within transactions. ==== DML Statements `SpannerTemplate` supports https://cloud.google.com/spanner/docs/dml-tasks:[DML] `Statements`. DML statements can also be run in transactions by using `performReadWriteTransaction` or by using the `@Transactional` annotation. === Repositories {spring-data-commons-ref}/#repositories[Spring Data Repositories] are a powerful abstraction that can save you a lot of boilerplate code. For example: [source,java] ---- public interface TraderRepository extends SpannerRepository { } ---- Spring Data generates a working implementation of the specified interface, which can be conveniently autowired into an application. The `Trader` type parameter to `SpannerRepository` refers to the underlying domain type. The second type parameter, `String` in this case, refers to the type of the key of the domain type. For POJOs with a composite primary key, this ID type parameter can be any descendant of `Object[]` compatible with all primary key properties, any descendant of `Iterable`, or `com.google.cloud.spanner.Key`. If the domain POJO type only has a single primary key column, then the primary key property type can be used or the `Key` type. For example in case of Trades, that belong to a Trader, `TradeRepository` would look like this: [source,java] ---- public interface TradeRepository extends SpannerRepository { } ---- [source,java] ---- public class MyApplication { @Autowired SpannerTemplate spannerTemplate; @Autowired StudentRepository studentRepository; public void demo() { this.tradeRepository.deleteAll(); String traderId = ""demo_trader""; Trade t = new Trade(); t.symbol = stock; t.action = action; t.traderId = traderId; t.price = new BigDecimal(""100.0""); t.shares = 12345.6; this.spannerTemplate.insert(t); Iterable allTrades = this.tradeRepository.findAll(); int count = this.tradeRepository.countByAction(""BUY""); } } ---- ==== CRUD Repository `CrudRepository` methods work as expected, with one thing Spanner specific: the `save` and `saveAll` methods work as update-or-insert. ==== Paging and Sorting Repository You can also use `PagingAndSortingRepository` with Spanner Spring Data. The sorting and pageable `findAll` methods available from this interface operate on the current state of the Spanner database. As a result, beware that the state of the database (and the results) might change when moving page to page. ==== Spanner Repository The `SpannerRepository` extends the `PagingAndSortingRepository`, but adds the read-only and the read-write transaction functionality provided by Spanner. These transactions work very similarly to those of `SpannerOperations`, but is specific to the repository's domain type and provides repository functions instead of template functions. For example, this is a read-only transaction: [source,java] ---- @Autowired SpannerRepository myRepo; public String doWorkInsideTransaction() { return myRepo.performReadOnlyTransaction( transactionSpannerRepo -> { // Work with the single-transaction transactionSpannerRepo here. // This is a SpannerRepository object. return ""transaction completed""; } ); } ---- When creating custom repositories for your own domain types and query methods, you can extend `SpannerRepository` to access Cloud Spanner-specific features as well as all features from `PagingAndSortingRepository` and `CrudRepository`. === Query Methods `SpannerRepository` supports Query Methods. Described in the following sections, these are methods residing in your custom repository interfaces of which implementations are generated based on their names and annotations. Query Methods can read, write, and delete entities in Cloud Spanner. Parameters to these methods can be any Cloud Spanner data type supported directly or via custom configured converters. Parameters can also be of type `Struct` or POJOs. If a POJO is given as a parameter, it will be converted to a `Struct` with the same type-conversion logic as used to create write mutations. Comparisons using Struct parameters are limited to https://cloud.google.com/spanner/docs/data-types#limited-comparisons-for-struct[what is available with Cloud Spanner]. ==== Query methods by convention [source, java] ---- public interface TradeRepository extends SpannerRepository { List findByAction(String action); int countByAction(String action); // Named methods are powerful, but can get unwieldy List findTop3DistinctByActionAndSymbolIgnoreCaseOrTraderIdOrderBySymbolDesc( String action, String symbol, String traderId); } ---- In the example above, the {spring-data-commons-ref}/#repositories.query-methods[query methods] in `TradeRepository` are generated based on the name of the methods, using the {spring-data-commons-ref}#repositories.query-methods.query-creation[Spring Data Query creation naming convention]. `List findByAction(String action)` would translate to a `SELECT * FROM trades WHERE action = ?`. The function `List findTop3DistinctByActionAndSymbolIgnoreCaseOrTraderIdOrderBySymbolDesc(String action, String symbol, String traderId);` will be translated as the equivalent of this SQL query: [source, sql] ---- SELECT DISTINCT * FROM trades WHERE ACTION = ? AND LOWER(SYMBOL) = LOWER(?) AND TRADER_ID = ? ORDER BY SYMBOL DESC LIMIT 3 ---- The following filter options are supported: * Equality * Greater than or equals * Greater than * Less than or equals * Less than * Is null * Is not null * Is true * Is false * Like a string * Not like a string * Contains a string * Not contains a string * In * Not in Note that the phrase `SymbolIgnoreCase` is translated to `LOWER(SYMBOL) = LOWER(?)` indicating a non-case-sensitive matching. The `IgnoreCase` phrase may only be appended to fields that correspond to columns of type STRING or BYTES. The Spring Data ""AllIgnoreCase"" phrase appended at the end of the method name is not supported. The `Like` or `NotLike` naming conventions: [source, java] ---- List findBySymbolLike(String symbolFragment); ---- The param `symbolFragment` can contain https://cloud.google.com/spanner/docs/functions-and-operators#comparison-operators[wildcard characters] for string matching such as `_` and `%`. The `Contains` and `NotContains` naming conventions: [source, java] ---- List findBySymbolContains(String symbolFragment); ---- The param `symbolFragment` is a https://cloud.google.com/spanner/docs/functions-and-operators#regexp_contains[regular expression] that is checked for occurrences. The `In` and `NotIn` keywords must be used with `Iterable` corresponding parameters. Delete queries are also supported. For example, query methods such as `deleteByAction` or `removeByAction` delete entities found by `findByAction`. The delete operation happens in a single transaction. Delete queries can have the following return types: * An integer type that is the number of entities deleted * A collection of entities that were deleted * `void` ==== Custom SQL/DML query methods The example above for `List fetchByActionNamedQuery(String action)` does not match the {spring-data-commons-ref}#repositories.query-methods.query-creation[Spring Data Query creation naming convention], so we have to map a parametrized Spanner SQL query to it. The SQL query for the method can be mapped to repository methods in one of two ways: * `namedQueries` properties file * using the `@Query` annotation The names of the tags of the SQL correspond to the `@Param` annotated names of the method parameters. Interleaved properties are loaded eagerly, unless they are annotated with `@Interleaved(lazy = true)`. Custom SQL query methods can accept a single `Sort` or `Pageable` parameter that is applied on top of the specified custom query. It is the recommended way to control the sort order of the results, which is not guaranteed by the `ORDER BY` clause in the SQL query. This is due to the fact that the user-provided query is used as a sub-query, and Cloud Spanner doesn't preserve order in subquery results. You might want to use `ORDER BY` with `LIMIT` to obtain the top records, according to a specified order. However, to ensure the correct sort order of the final result set, sort options have to be passed in with a `Pageable`. [source, java] ---- @Query(""SELECT * FROM trades"") List fetchTrades(Pageable pageable); @Query(""SELECT * FROM trades ORDER BY price DESC LIMIT 1"") Trade topTrade(Pageable pageable); ---- This can be used: [source, java] ---- List customSortedTrades = tradeRepository.fetchTrades(PageRequest .of(2, 2, org.springframework.data.domain.Sort.by(Order.asc(""id"")))); ---- The results would be sorted by ""id"" in ascending order. Your query method can also return non-entity types: [source, java] ---- @Query(""SELECT COUNT(1) FROM trades WHERE action = @action"") int countByActionQuery(String action); @Query(""SELECT EXISTS(SELECT COUNT(1) FROM trades WHERE action = @action)"") boolean existsByActionQuery(String action); @Query(""SELECT action FROM trades WHERE action = @action LIMIT 1"") String getFirstString(@Param(""action"") String action); @Query(""SELECT action FROM trades WHERE action = @action"") List getFirstStringList(@Param(""action"") String action); ---- DML statements can also be run by query methods, but the only possible return value is a `long` representing the number of affected rows. The `dmlStatement` boolean setting must be set on `@Query` to indicate that the query method is run as a DML statement. [source, java] ---- @Query(value = ""DELETE FROM trades WHERE action = @action"", dmlStatement = true) long deleteByActionQuery(String action); ---- ===== Query methods with named queries properties By default, the `namedQueriesLocation` attribute on `@EnableSpannerRepositories` points to the `META-INF/spanner-named-queries.properties` file. You can specify the query for a method in the properties file by providing the SQL as the value for the ""interface.method"" property: [source, properties] ---- Trade.fetchByActionNamedQuery=SELECT * FROM trades WHERE trades.action = @tag0 ---- [source, java] ---- public interface TradeRepository extends SpannerRepository { // This method uses the query from the properties file instead of one generated based on name. List fetchByActionNamedQuery(@Param(""tag0"") String action); } ---- ===== Query methods with annotation Using the `@Query` annotation: [source, java] ---- public interface TradeRepository extends SpannerRepository { @Query(""SELECT * FROM trades WHERE trades.action = @tag0"") List fetchByActionNamedQuery(@Param(""tag0"") String action); } ---- Table names can be used directly. For example, ""trades"" in the above example. Alternatively, table names can be resolved from the `@Table` annotation on domain classes as well. In this case, the query should refer to table names with fully qualified class names between `:` characters: `:fully.qualified.ClassName:`. A full example would look like: [source, java] ---- @Query(""SELECT * FROM :com.example.Trade: WHERE trades.action = @tag0"") List fetchByActionNamedQuery(String action); ---- This allows table names evaluated with SpEL to be used in custom queries. SpEL can also be used to provide SQL parameters: [source, java] ---- @Query(""SELECT * FROM :com.example.Trade: WHERE trades.action = @tag0 AND price > #{#priceRadius * -1} AND price < #{#priceRadius * 2}"") List fetchByActionNamedQuery(String action, Double priceRadius); ---- When using the `IN` SQL clause, remember to use `IN UNNEST(@iterableParam)` to specify a single `Iterable` parameter. You can also use a fixed number of singular parameters such as `IN (@stringParam1, @stringParam2)`. ==== Projections Spring Data Spanner supports {spring-data-commons-ref}/#projections[projections]. You can define projection interfaces based on domain types and add query methods that return them in your repository: [source, java] ---- public interface TradeProjection { String getAction(); @Value(""#{target.symbol + ' ' + target.action}"") String getSymbolAndAction(); } public interface TradeRepository extends SpannerRepository { List findByTraderId(String traderId); List findByAction(String action); @Query(""SELECT action, symbol FROM trades WHERE action = @action"") List findByQuery(String action); } ---- Projections can be provided by name-convention-based query methods as well as by custom SQL queries. If using custom SQL queries, you can further restrict the columns retrieved from Spanner to just those required by the projection to improve performance. Properties of projection types defined using SpEL use the fixed name `target` for the underlying domain object. As a result accessing underlying properties take the form `target.`. ==== Empty result handling in repository methods Java `java.util.Optional` can be used to indicate the potential absence of a return value. Alternatively, query methods can return the result without a wrapper. In that case the absence of a query result is indicated by returning `null`. Repository methods returning collections are guaranteed never to return `null` but rather the corresponding empty collection. NOTE: You can enable nullability checks. For more details please see https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#null-safety[Spring Framework’s nullability docs]. ==== REST Repositories When running with Spring Boot, repositories can be exposed as REST services by simply adding this dependency to your pom file: [source,xml] ---- org.springframework.boot spring-boot-starter-data-rest ---- If you prefer to configure parameters (such as path), you can use `@RepositoryRestResource` annotation: [source,java] ---- @RepositoryRestResource(collectionResourceRel = ""trades"", path = ""trades"") public interface TradeRepository extends SpannerRepository { } ---- NOTE: For classes that have composite keys (multiple `@PrimaryKey` fields), only the `Key` type is supported for the repository ID type. For example, you can retrieve all `Trade` objects in the repository by using `curl \\http://:/trades`, or any specific trade via `curl \\http://:/trades/,`. The separator between your primary key components, `id` and `trader_id` in this case, is a comma by default, but can be configured to any string not found in your key values by extending the `SpannerKeyIdConverter` class: [source,java] ---- @Component class MySpecialIdConverter extends SpannerKeyIdConverter { @Override protected String getUrlIdSeparator() { return "":""; } } ---- You can also write trades using `curl -XPOST -H""Content-Type: application/json"" -d@test.json \\http://:/trades/` where the file `test.json` holds the JSON representation of a `Trade` object. === Database and Schema Admin Databases and tables inside Spanner instances can be created automatically from `SpannerPersistentEntity` objects: [source,java] ---- @Autowired private SpannerSchemaUtils spannerSchemaUtils; @Autowired private SpannerDatabaseAdminTemplate spannerDatabaseAdminTemplate; public void createTable(SpannerPersistentEntity entity) { if(!spannerDatabaseAdminTemplate.tableExists(entity.tableName()){ // The boolean parameter indicates that the database will be created if it does not exist. spannerDatabaseAdminTemplate.executeDdlStrings(Arrays.asList( spannerSchemaUtils.getCreateTableDDLString(entity.getType())), true); } } ---- Schemas can be generated for entire object hierarchies with interleaved relationships and composite keys. === Events Spring Data Cloud Spanner publishes events extending the Spring Framework's `ApplicationEvent` to the context that can be received by `ApplicationListener` beans you register. [options=""header""] |=== | Type| Description | Contents | `AfterReadEvent`|Published immediately after entities are read by key from Cloud Spanner by `SpannerTemplate`| The entities loaded. The read options and key-set originally specified for the load operation. | `AfterQueryEvent`|Published immediately after entities are read by query from Cloud Spanner by `SpannerTemplate`| The entities loaded. The query options and query statement originally specified for the load operation. | `BeforeExecuteDmlEvent`|Published immediately before DML statements are executed by `SpannerTemplate`| The DML statement to execute. | `AfterExecuteDmlEvent`|Published immediately after DML statements are executed by `SpannerTemplate`| The DML statement to execute and the number of rows affected by the operation as reported by Cloud Spanner. | `BeforeSaveEvent`|Published immediately before upsert/update/insert operations are executed by `SpannerTemplate`| The mutations to be sent to Cloud Spanner, the entities to be saved, and optionally the properties in those entities to save. | `AfterSaveEvent`|Published immediately after upsert/update/insert operations are executed by `SpannerTemplate`| The mutations sent to Cloud Spanner, the entities to be saved, and optionally the properties in those entities to save. | `BeforeDeleteEvent`|Published immediately before delete operations are executed by `SpannerTemplate`| The mutations to be sent to Cloud Spanner. The target entities, keys, or entity type originally specified for the delete operation. | `AfterDeleteEvent`|Published immediately after delete operations are executed by `SpannerTemplate`| The mutations sent to Cloud Spanner. The target entities, keys, or entity type originally specified for the delete operation. |=== === Auditing Spring Data Cloud Spanner supports the `@LastModifiedDate` and `@LastModifiedBy` auditing annotations for properties: [source,java] ---- @Table public class SimpleEntity { @PrimaryKey String id; @LastModifiedBy String lastUser; @LastModifiedDate DateTime lastTouched; } ---- Upon insert, update, or save, these properties will be set automatically by the framework before mutations are generated and saved to Cloud Spanner. To take advantage of these features, add the `@EnableSpannerAuditing` annotation to your configuration class and provide a bean for an `AuditorAware` implementation where the type `A` is the desired property type annotated by `@LastModifiedBy`: [source,java] ---- @Configuration @EnableSpannerAuditing public class Config { @Bean public AuditorAware auditorProvider() { return () -> Optional.of(""YOUR_USERNAME_HERE""); } } ---- The `AuditorAware` interface contains a single method that supplies the value for fields annotated by `@LastModifiedBy` and can be of any type. One alternative is to use Spring Security's `User` type: [source,java] ---- class SpringSecurityAuditorAware implements AuditorAware { public Optional getCurrentAuditor() { return Optional.ofNullable(SecurityContextHolder.getContext()) .map(SecurityContext::getAuthentication) .filter(Authentication::isAuthenticated) .map(Authentication::getPrincipal) .map(User.class::cast); } } ---- You can also set a custom provider for properties annotated `@LastModifiedDate` by providing a bean for `DateTimeProvider` and providing the bean name to `@EnableSpannerAuditing(dateTimeProviderRef = ""customDateTimeProviderBean"")`. === Multi-Instance Usage Your application can be configured to use multiple Cloud Spanner instances or databases by providing a custom bean for `DatabaseIdProvider`. The default bean uses the instance ID, database name, and project ID options you configured in `application.properties`. [source,java] ---- @Bean public DatabaseIdProvider databaseIdProvider() { // return custom connection options provider } ---- The `DatabaseId` given by this provider is used as the target database name and instance of each operation Spring Data Cloud Spanner executes. By providing a custom implementation of this bean (for example, supplying a thread-local `DatabaseId`), you can direct your application to use multiple instances or databases. Database administrative operations, such as creating tables using `SpannerDatabaseAdminTemplate`, will also utilize the provided `DatabaseId`. If you would like to configure every aspect of each connection (such as pool size and retry settings), you can supply a bean for `Supplier`. === Cloud Spanner Emulator The https://cloud.google.com/sdk[Cloud SDK] provides a local, in-memory emulator for Cloud Spanner, which you can use to develop and test your application. As the emulator stores data only in memory, it will not persist data across runs. It is intended to help you use Cloud Spanner for local development and testing, not for production deployments. In order to set up and start the emulator, you can follow https://cloud.google.com/spanner/docs/emulator[these steps]. This command can be used to create Cloud Spanner instances: ---- $ gcloud spanner instances create --config=emulator-config --description="""" --nodes=1 ---- Once the Spanner emulator is running, ensure that the following properties are set in your `application.properties` of your Spring application: ---- spring.cloud.gcp.spanner.emulator.enabled=true spring.cloud.gcp.spanner.emulator-host=${EMULATOR_HOSTPORT} ---- === Sample A https://github.com/GoogleCloudPlatform/spring-cloud-gcp/tree/master/spring-cloud-gcp-samples/spring-cloud-gcp-data-spanner-sample[sample application] is available. ",12204,False,2034.3986538537424,median "[[netty-component]] = Netty Component :docTitle: Netty :artifactId: camel-netty :description: Socket level networking using TCP or UDP with the Netty 4.x. :since: 2.14 :supportLevel: Stable :component-header: Both producer and consumer are supported include::{cq-version}@camel-quarkus:ROOT:partial$reference/components/netty.adoc[opts=optional] *Since Camel {since}* *{component-header}* The Netty component in Camel is a socket communication component, based on the http://netty.io/[Netty] project version 4. + Netty is a NIO client server framework which enables quick and easy development of networkServerInitializerFactory applications such as protocol servers and clients. + Netty greatly simplifies and streamlines network programming such as TCP and UDP socket server. This camel component supports both producer and consumer endpoints. The Netty component has several options and allows fine-grained control of a number of TCP/UDP communication parameters (buffer sizes, keepAlives, tcpNoDelay, etc) and facilitates both In-Only and In-Out communication on a Camel route. Maven users will need to add the following dependency to their `pom.xml` for this component: [source,xml] ---- org.apache.camel camel-netty x.x.x ---- == URI format The URI scheme for a netty component is as follows [source,text] ---- netty:tcp://0.0.0.0:99999[?options] netty:udp://remotehost:99999/[?options] ---- This component supports producer and consumer endpoints for both TCP and UDP. You can append query options to the URI in the following format, `?option=value&option=value&...` == Options // component options: START The Netty component supports 72 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *configuration* (common) | To use the NettyConfiguration as configuration when creating endpoints. | | NettyConfiguration | *disconnect* (common) | Whether or not to disconnect(close) from Netty Channel right after use. Can be used for both consumer and producer. | false | boolean | *keepAlive* (common) | Setting to ensure socket is not closed due to inactivity | true | boolean | *reuseAddress* (common) | Setting to facilitate socket multiplexing | true | boolean | *reuseChannel* (common) | This option allows producers and consumers (in client mode) to reuse the same Netty Channel for the lifecycle of processing the Exchange. This is useful if you need to call a server multiple times in a Camel route and want to use the same network connection. When using this, the channel is not returned to the connection pool until the Exchange is done; or disconnected if the disconnect option is set to true. The reused Channel is stored on the Exchange as an exchange property with the key NettyConstants#NETTY_CHANNEL which allows you to obtain the channel during routing and use it as well. | false | boolean | *sync* (common) | Setting to set endpoint as one-way or request-response | true | boolean | *tcpNoDelay* (common) | Setting to improve TCP protocol performance | true | boolean | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *broadcast* (consumer) | Setting to choose Multicast over UDP | false | boolean | *clientMode* (consumer) | If the clientMode is true, netty consumer will connect the address as a TCP client. | false | boolean | *reconnect* (consumer) | Used only in clientMode in consumer, the consumer will attempt to reconnect on disconnection if this is enabled | true | boolean | *reconnectInterval* (consumer) | Used if reconnect and clientMode is enabled. The interval in milli seconds to attempt reconnection | 10000 | int | *backlog* (consumer) | Allows to configure a backlog for netty consumer (server). Note the backlog is just a best effort depending on the OS. Setting this option to a value such as 200, 500 or 1000, tells the TCP stack how long the accept queue can be If this option is not configured, then the backlog depends on OS setting. | | int | *bossCount* (consumer) | When netty works on nio mode, it uses default bossCount parameter from Netty, which is 1. User can use this option to override the default bossCount from Netty | 1 | int | *bossGroup* (consumer) | Set the BossGroup which could be used for handling the new connection of the server side across the NettyEndpoint | | EventLoopGroup | *disconnectOnNoReply* (consumer) | If sync is enabled then this option dictates NettyConsumer if it should disconnect where there is no reply to send back. | true | boolean | *executorService* (consumer) | To use the given EventExecutorGroup. | | EventExecutorGroup | *maximumPoolSize* (consumer) | Sets a maximum thread pool size for the netty consumer ordered thread pool. The default size is 2 x cpu_core plus 1. Setting this value to eg 10 will then use 10 threads unless 2 x cpu_core plus 1 is a higher value, which then will override and be used. For example if there are 8 cores, then the consumer thread pool will be 17. This thread pool is used to route messages received from Netty by Camel. We use a separate thread pool to ensure ordering of messages and also in case some messages will block, then nettys worker threads (event loop) wont be affected. | | int | *nettyServerBootstrapFactory* (consumer) | To use a custom NettyServerBootstrapFactory | | NettyServerBootstrapFactory | *networkInterface* (consumer) | When using UDP then this option can be used to specify a network interface by its name, such as eth0 to join a multicast group. | | String | *noReplyLogLevel* (consumer) | If sync is enabled this option dictates NettyConsumer which logging level to use when logging a there is no reply to send back. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverClosedChannelException{zwsp}CaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an java.nio.channels.ClosedChannelException then its logged using this logging level. This is used to avoid logging the closed channel exceptions, as clients can disconnect abruptly and then cause a flood of closed exceptions in the Netty server. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | DEBUG | LoggingLevel | *serverExceptionCaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an exception then its logged using this logging level. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverInitializerFactory* (consumer) | To use a custom ServerInitializerFactory | | ServerInitializerFactory | *usingExecutorService* (consumer) | Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. | true | boolean | *connectTimeout* (producer) | Time to wait for a socket connection to be available. Value is in milliseconds. | 10000 | int | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *requestTimeout* (producer) | Allows to use a timeout for the Netty producer when calling a remote server. By default no timeout is in use. The value is in milli seconds, so eg 30000 is 30 seconds. The requestTimeout is using Netty's ReadTimeoutHandler to trigger the timeout. | | long | *clientInitializerFactory* (producer) | To use a custom ClientInitializerFactory | | ClientInitializerFactory | *correlationManager* (producer) | To use a custom correlation manager to manage how request and reply messages are mapped when using request/reply with the netty producer. This should only be used if you have a way to map requests together with replies such as if there is correlation ids in both the request and reply messages. This can be used if you want to multiplex concurrent messages on the same channel (aka connection) in netty. When doing this you must have a way to correlate the request and reply messages so you can store the right reply on the inflight Camel Exchange before its continued routed. We recommend extending the TimeoutCorrelationManagerSupport when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well. See also the producerPoolEnabled option for more details. | | NettyCamelStateCorrelationManager | *lazyChannelCreation* (producer) | Channels can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. | true | boolean | *producerPoolEnabled* (producer) | Whether producer pool is enabled or not. Important: If you turn this off then a single shared connection is used for the producer, also if you are doing request/reply. That means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement NettyCamelStateCorrelationManager as correlation manager and configure it via the correlationManager option. See also the correlationManager option for more details. | true | boolean | *producerPoolMaxActive* (producer) | Sets the cap on the number of objects that can be allocated by the pool (checked out to clients, or idle awaiting checkout) at a given time. Use a negative value for no limit. | -1 | int | *producerPoolMaxIdle* (producer) | Sets the cap on the number of idle instances in the pool. | 100 | int | *producerPoolMinEvictableIdle* (producer) | Sets the minimum amount of time (value in millis) an object may sit idle in the pool before it is eligible for eviction by the idle object evictor. | 300000 | long | *producerPoolMinIdle* (producer) | Sets the minimum number of instances allowed in the producer pool before the evictor thread (if active) spawns new objects. | | int | *udpConnectionlessSending* (producer) | This option supports connection less udp sending which is a real fire and forget. A connected udp send receive the PortUnreachableException if no one is listen on the receiving port. | false | boolean | *useByteBuf* (producer) | If the useByteBuf is true, netty producer will turn the message body into ByteBuf before sending it out. | false | boolean | *allowSerializedHeaders* (advanced) | Only used for TCP when transferExchange is true. When set to true, serializable objects in headers and properties will be added to the exchange. Otherwise Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *autowiredEnabled* (advanced) | Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc. | true | boolean | *channelGroup* (advanced) | To use a explicit ChannelGroup. | | ChannelGroup | *nativeTransport* (advanced) | Whether to use native transport instead of NIO. Native transport takes advantage of the host operating system and is only supported on some platforms. You need to add the netty JAR for the host operating system you are using. See more details at: \\http://netty.io/wiki/native-transports.html | false | boolean | *options* (advanced) | Allows to configure additional netty options using option. as prefix. For example option.child.keepAlive=false to set the netty option child.keepAlive=false. See the Netty documentation for possible options that can be used. | | Map | *receiveBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during inbound communication. Size is bytes. | 65536 | int | *receiveBufferSizePredictor* (advanced) | Configures the buffer size predictor. See details at Jetty documentation and this mail thread. | | int | *sendBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during outbound communication. Size is bytes. | 65536 | int | *transferExchange* (advanced) | Only used for TCP. You can transfer the exchange over the wire instead of just the body. The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *udpByteArrayCodec* (advanced) | For UDP only. If enabled the using byte array codec instead of Java serialization protocol. | false | boolean | *workerCount* (advanced) | When netty works on nio mode, it uses default workerCount parameter from Netty (which is cpu_core_threads x 2). User can use this option to override the default workerCount from Netty. | | int | *workerGroup* (advanced) | To use a explicit EventLoopGroup as the boss thread pool. For example to share a thread pool with multiple consumers or producers. By default each consumer or producer has their own worker pool with 2 x cpu count core threads. | | EventLoopGroup | *allowDefaultCodec* (codec) | The netty component installs a default codec if both, encoder/decoder is null and textline is false. Setting allowDefaultCodec to false prevents the netty component from installing a default codec as the first element in the filter chain. | true | boolean | *autoAppendDelimiter* (codec) | Whether or not to auto append missing end delimiter when sending using the textline codec. | true | boolean | *decoderMaxLineLength* (codec) | The max line length to use for the textline codec. | 1024 | int | *decoders* (codec) | A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *delimiter* (codec) | The delimiter to use for the textline codec. Possible values are LINE and NULL. There are 2 enums and the value can be one of: LINE, NULL | LINE | TextLineDelimiter | *encoders* (codec) | A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *encoding* (codec) | The encoding (a charset name) to use for the textline codec. If not provided, Camel will use the JVM default Charset. | | String | *textline* (codec) | Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; if not specified or the value is false, then Object Serialization is assumed over TCP - however only Strings are allowed to be serialized by default. | false | boolean | *enabledProtocols* (security) | Which protocols to enable when using SSL | TLSv1,TLSv1.1,TLSv1.2 | String | *keyStoreFile* (security) | Client side certificate keystore to be used for encryption | | File | *keyStoreFormat* (security) | Keystore format to be used for payload encryption. Defaults to JKS if not set | | String | *keyStoreResource* (security) | Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String | *needClientAuth* (security) | Configures whether the server needs client authentication when using SSL. | false | boolean | *passphrase* (security) | Password setting to use in order to encrypt/decrypt payloads sent using SSH | | String | *securityProvider* (security) | Security provider to be used for payload encryption. Defaults to SunX509 if not set. | | String | *ssl* (security) | Setting to specify whether SSL encryption is applied to this endpoint | false | boolean | *sslClientCertHeaders* (security) | When enabled and in SSL mode, then the Netty consumer will enrich the Camel Message with headers having information about the client certificate such as subject name, issuer name, serial number, and the valid date range. | false | boolean | *sslContextParameters* (security) | To configure security using SSLContextParameters | | SSLContextParameters | *sslHandler* (security) | Reference to a class that could be used to return an SSL Handler | | SslHandler | *trustStoreFile* (security) | Server side certificate keystore to be used for encryption | | File | *trustStoreResource* (security) | Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String | *useGlobalSslContextParameters* (security) | Enable usage of global SSL context parameters. | false | boolean |=== // component options: END // endpoint options: START The Netty endpoint is configured using URI syntax: ---- netty:protocol:host:port ---- with the following path and query parameters: === Path Parameters (3 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *protocol* | *Required* The protocol to use which can be tcp or udp. There are 2 enums and the value can be one of: tcp, udp | | String | *host* | *Required* The hostname. For the consumer the hostname is localhost or 0.0.0.0. For the producer the hostname is the remote host to connect to | | String | *port* | *Required* The host port number | | int |=== === Query Parameters (70 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *disconnect* (common) | Whether or not to disconnect(close) from Netty Channel right after use. Can be used for both consumer and producer. | false | boolean | *keepAlive* (common) | Setting to ensure socket is not closed due to inactivity | true | boolean | *reuseAddress* (common) | Setting to facilitate socket multiplexing | true | boolean | *reuseChannel* (common) | This option allows producers and consumers (in client mode) to reuse the same Netty Channel for the lifecycle of processing the Exchange. This is useful if you need to call a server multiple times in a Camel route and want to use the same network connection. When using this, the channel is not returned to the connection pool until the Exchange is done; or disconnected if the disconnect option is set to true. The reused Channel is stored on the Exchange as an exchange property with the key NettyConstants#NETTY_CHANNEL which allows you to obtain the channel during routing and use it as well. | false | boolean | *sync* (common) | Setting to set endpoint as one-way or request-response | true | boolean | *tcpNoDelay* (common) | Setting to improve TCP protocol performance | true | boolean | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *broadcast* (consumer) | Setting to choose Multicast over UDP | false | boolean | *clientMode* (consumer) | If the clientMode is true, netty consumer will connect the address as a TCP client. | false | boolean | *reconnect* (consumer) | Used only in clientMode in consumer, the consumer will attempt to reconnect on disconnection if this is enabled | true | boolean | *reconnectInterval* (consumer) | Used if reconnect and clientMode is enabled. The interval in milli seconds to attempt reconnection | 10000 | int | *backlog* (consumer) | Allows to configure a backlog for netty consumer (server). Note the backlog is just a best effort depending on the OS. Setting this option to a value such as 200, 500 or 1000, tells the TCP stack how long the accept queue can be If this option is not configured, then the backlog depends on OS setting. | | int | *bossCount* (consumer) | When netty works on nio mode, it uses default bossCount parameter from Netty, which is 1. User can use this option to override the default bossCount from Netty | 1 | int | *bossGroup* (consumer) | Set the BossGroup which could be used for handling the new connection of the server side across the NettyEndpoint | | EventLoopGroup | *disconnectOnNoReply* (consumer) | If sync is enabled then this option dictates NettyConsumer if it should disconnect where there is no reply to send back. | true | boolean | *exceptionHandler* (consumer) | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | | ExceptionHandler | *exchangePattern* (consumer) | Sets the exchange pattern when the consumer creates an exchange. There are 3 enums and the value can be one of: InOnly, InOut, InOptionalOut | | ExchangePattern | *nettyServerBootstrapFactory* (consumer) | To use a custom NettyServerBootstrapFactory | | NettyServerBootstrapFactory | *networkInterface* (consumer) | When using UDP then this option can be used to specify a network interface by its name, such as eth0 to join a multicast group. | | String | *noReplyLogLevel* (consumer) | If sync is enabled this option dictates NettyConsumer which logging level to use when logging a there is no reply to send back. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverClosedChannelException{zwsp}CaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an java.nio.channels.ClosedChannelException then its logged using this logging level. This is used to avoid logging the closed channel exceptions, as clients can disconnect abruptly and then cause a flood of closed exceptions in the Netty server. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | DEBUG | LoggingLevel | *serverExceptionCaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an exception then its logged using this logging level. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverInitializerFactory* (consumer) | To use a custom ServerInitializerFactory | | ServerInitializerFactory | *usingExecutorService* (consumer) | Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. | true | boolean | *connectTimeout* (producer) | Time to wait for a socket connection to be available. Value is in milliseconds. | 10000 | int | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *requestTimeout* (producer) | Allows to use a timeout for the Netty producer when calling a remote server. By default no timeout is in use. The value is in milli seconds, so eg 30000 is 30 seconds. The requestTimeout is using Netty's ReadTimeoutHandler to trigger the timeout. | | long | *clientInitializerFactory* (producer) | To use a custom ClientInitializerFactory | | ClientInitializerFactory | *correlationManager* (producer) | To use a custom correlation manager to manage how request and reply messages are mapped when using request/reply with the netty producer. This should only be used if you have a way to map requests together with replies such as if there is correlation ids in both the request and reply messages. This can be used if you want to multiplex concurrent messages on the same channel (aka connection) in netty. When doing this you must have a way to correlate the request and reply messages so you can store the right reply on the inflight Camel Exchange before its continued routed. We recommend extending the TimeoutCorrelationManagerSupport when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well. See also the producerPoolEnabled option for more details. | | NettyCamelStateCorrelationManager | *lazyChannelCreation* (producer) | Channels can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. | true | boolean | *producerPoolEnabled* (producer) | Whether producer pool is enabled or not. Important: If you turn this off then a single shared connection is used for the producer, also if you are doing request/reply. That means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement NettyCamelStateCorrelationManager as correlation manager and configure it via the correlationManager option. See also the correlationManager option for more details. | true | boolean | *producerPoolMaxActive* (producer) | Sets the cap on the number of objects that can be allocated by the pool (checked out to clients, or idle awaiting checkout) at a given time. Use a negative value for no limit. | -1 | int | *producerPoolMaxIdle* (producer) | Sets the cap on the number of idle instances in the pool. | 100 | int | *producerPoolMinEvictableIdle* (producer) | Sets the minimum amount of time (value in millis) an object may sit idle in the pool before it is eligible for eviction by the idle object evictor. | 300000 | long | *producerPoolMinIdle* (producer) | Sets the minimum number of instances allowed in the producer pool before the evictor thread (if active) spawns new objects. | | int | *udpConnectionlessSending* (producer) | This option supports connection less udp sending which is a real fire and forget. A connected udp send receive the PortUnreachableException if no one is listen on the receiving port. | false | boolean | *useByteBuf* (producer) | If the useByteBuf is true, netty producer will turn the message body into ByteBuf before sending it out. | false | boolean | *allowSerializedHeaders* (advanced) | Only used for TCP when transferExchange is true. When set to true, serializable objects in headers and properties will be added to the exchange. Otherwise Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *channelGroup* (advanced) | To use a explicit ChannelGroup. | | ChannelGroup | *nativeTransport* (advanced) | Whether to use native transport instead of NIO. Native transport takes advantage of the host operating system and is only supported on some platforms. You need to add the netty JAR for the host operating system you are using. See more details at: \\http://netty.io/wiki/native-transports.html | false | boolean | *options* (advanced) | Allows to configure additional netty options using option. as prefix. For example option.child.keepAlive=false to set the netty option child.keepAlive=false. See the Netty documentation for possible options that can be used. | | Map | *receiveBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during inbound communication. Size is bytes. | 65536 | int | *receiveBufferSizePredictor* (advanced) | Configures the buffer size predictor. See details at Jetty documentation and this mail thread. | | int | *sendBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during outbound communication. Size is bytes. | 65536 | int | *synchronous* (advanced) | Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported). | false | boolean | *transferExchange* (advanced) | Only used for TCP. You can transfer the exchange over the wire instead of just the body. The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *udpByteArrayCodec* (advanced) | For UDP only. If enabled the using byte array codec instead of Java serialization protocol. | false | boolean | *workerCount* (advanced) | When netty works on nio mode, it uses default workerCount parameter from Netty (which is cpu_core_threads x 2). User can use this option to override the default workerCount from Netty. | | int | *workerGroup* (advanced) | To use a explicit EventLoopGroup as the boss thread pool. For example to share a thread pool with multiple consumers or producers. By default each consumer or producer has their own worker pool with 2 x cpu count core threads. | | EventLoopGroup | *allowDefaultCodec* (codec) | The netty component installs a default codec if both, encoder/decoder is null and textline is false. Setting allowDefaultCodec to false prevents the netty component from installing a default codec as the first element in the filter chain. | true | boolean | *autoAppendDelimiter* (codec) | Whether or not to auto append missing end delimiter when sending using the textline codec. | true | boolean | *decoderMaxLineLength* (codec) | The max line length to use for the textline codec. | 1024 | int | *decoders* (codec) | A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *delimiter* (codec) | The delimiter to use for the textline codec. Possible values are LINE and NULL. There are 2 enums and the value can be one of: LINE, NULL | LINE | TextLineDelimiter | *encoders* (codec) | A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *encoding* (codec) | The encoding (a charset name) to use for the textline codec. If not provided, Camel will use the JVM default Charset. | | String | *textline* (codec) | Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; if not specified or the value is false, then Object Serialization is assumed over TCP - however only Strings are allowed to be serialized by default. | false | boolean | *enabledProtocols* (security) | Which protocols to enable when using SSL | TLSv1,TLSv1.1,TLSv1.2 | String | *keyStoreFile* (security) | Client side certificate keystore to be used for encryption | | File | *keyStoreFormat* (security) | Keystore format to be used for payload encryption. Defaults to JKS if not set | | String | *keyStoreResource* (security) | Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String | *needClientAuth* (security) | Configures whether the server needs client authentication when using SSL. | false | boolean | *passphrase* (security) | Password setting to use in order to encrypt/decrypt payloads sent using SSH | | String | *securityProvider* (security) | Security provider to be used for payload encryption. Defaults to SunX509 if not set. | | String | *ssl* (security) | Setting to specify whether SSL encryption is applied to this endpoint | false | boolean | *sslClientCertHeaders* (security) | When enabled and in SSL mode, then the Netty consumer will enrich the Camel Message with headers having information about the client certificate such as subject name, issuer name, serial number, and the valid date range. | false | boolean | *sslContextParameters* (security) | To configure security using SSLContextParameters | | SSLContextParameters | *sslHandler* (security) | Reference to a class that could be used to return an SSL Handler | | SslHandler | *trustStoreFile* (security) | Server side certificate keystore to be used for encryption | | File | *trustStoreResource* (security) | Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String |=== // endpoint options: END == Registry based Options Codec Handlers and SSL Keystores can be enlisted in the Registry, such as in the Spring XML file. The values that could be passed in, are the following: [width=""100%"",cols=""10%,90%"",options=""header"",] |=== |Name |Description |`passphrase` |password setting to use in order to encrypt/decrypt payloads sent using SSH |`keyStoreFormat` |keystore format to be used for payload encryption. Defaults to ""JKS"" if not set |`securityProvider` |Security provider to be used for payload encryption. Defaults to ""SunX509"" if not set. |`keyStoreFile` |*deprecated:* Client side certificate keystore to be used for encryption |`trustStoreFile` |*deprecated:* Server side certificate keystore to be used for encryption |`keyStoreResource` |Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with `""classpath:""`, `""file:""`, or `""http:""` to load the resource from different systems. |`trustStoreResource` |Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with `""classpath:""`, `""file:""`, or `""http:""` to load the resource from different systems. |`sslHandler` |Reference to a class that could be used to return an SSL Handler |`encoder` |A custom `ChannelHandler` class that can be used to perform special marshalling of outbound payloads. Must override io.netty.channel.ChannelInboundHandlerAdapter. |`encoders` |A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. |`decoder` |A custom `ChannelHandler` class that can be used to perform special marshalling of inbound payloads. Must override io.netty.channel.ChannelOutboundHandlerAdapter. |`decoders` |A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. |=== [NOTE] ==== Read below about using non shareable encoders/decoders. ==== === Using non shareable encoders or decoders If your encoders or decoders are not shareable (e.g. they don't have the @Shareable class annotation), then your encoder/decoder must implement the `org.apache.camel.component.netty.ChannelHandlerFactory` interface, and return a new instance in the `newChannelHandler` method. This is to ensure the encoder/decoder can safely be used. If this is not the case, then the Netty component will log a WARN when an endpoint is created. The Netty component offers a `org.apache.camel.component.netty.ChannelHandlerFactories` factory class, that has a number of commonly used methods. == Sending Messages to/from a Netty endpoint === Netty Producer In Producer mode, the component provides the ability to send payloads to a socket endpoint using either TCP or UDP protocols (with optional SSL support). The producer mode supports both one-way and request-response based operations. === Netty Consumer In Consumer mode, the component provides the ability to: * listen on a specified socket using either TCP or UDP protocols (with optional SSL support), * receive requests on the socket using text/xml, binary and serialized object based payloads and * send them along on a route as message exchanges. The consumer mode supports both one-way and request-response based operations. == Examples === A UDP Netty endpoint using Request-Reply and serialized object payload Note that Object serialization is not allowed by default, and so a decoder must be configured. [source,java] ---- @BindToRegistry(""decoder"") public ChannelHandler getDecoder() throws Exception { return new DefaultChannelHandlerFactory() { @Override public ChannelHandler newChannelHandler() { return new DatagramPacketObjectDecoder(ClassResolvers.weakCachingResolver(null)); } }; } RouteBuilder builder = new RouteBuilder() { public void configure() { from(""netty:udp://0.0.0.0:5155?sync=true&decoders=#decoder"") .process(new Processor() { public void process(Exchange exchange) throws Exception { Poetry poetry = (Poetry) exchange.getIn().getBody(); // Process poetry in some way exchange.getOut().setBody(""Message received); } } } }; ---- === A TCP based Netty consumer endpoint using One-way communication [source,java] ---- RouteBuilder builder = new RouteBuilder() { public void configure() { from(""netty:tcp://0.0.0.0:5150"") .to(""mock:result""); } }; ---- === An SSL/TCP based Netty consumer endpoint using Request-Reply communication [[Netty-UsingtheJSSEConfigurationUtility]] Using the JSSE Configuration Utility The Netty component supports SSL/TLS configuration through the xref:manual::camel-configuration-utilities.adoc[Camel JSSE Configuration Utility]. This utility greatly decreases the amount of component specific code you need to write and is configurable at the endpoint and component levels. The following examples demonstrate how to use the utility with the Netty component. [[Netty-Programmaticconfigurationofthecomponent]] Programmatic configuration of the component [source,java] ---- KeyStoreParameters ksp = new KeyStoreParameters(); ksp.setResource(""/users/home/server/keystore.jks""); ksp.setPassword(""keystorePassword""); KeyManagersParameters kmp = new KeyManagersParameters(); kmp.setKeyStore(ksp); kmp.setKeyPassword(""keyPassword""); SSLContextParameters scp = new SSLContextParameters(); scp.setKeyManagers(kmp); NettyComponent nettyComponent = getContext().getComponent(""netty"", NettyComponent.class); nettyComponent.setSslContextParameters(scp); ---- [[Netty-SpringDSLbasedconfigurationofendpoint]] Spring DSL based configuration of endpoint [source,xml] ---- ... ... ... ... ---- [[Netty-UsingBasicSSLTLSconfigurationontheJettyComponent]] Using Basic SSL/TLS configuration on the Jetty Component [source,java] ---- Registry registry = context.getRegistry(); registry.bind(""password"", ""changeit""); registry.bind(""ksf"", new File(""src/test/resources/keystore.jks"")); registry.bind(""tsf"", new File(""src/test/resources/keystore.jks"")); context.addRoutes(new RouteBuilder() { public void configure() { String netty_ssl_endpoint = ""netty:tcp://0.0.0.0:5150?sync=true&ssl=true&passphrase=#password"" + ""&keyStoreFile=#ksf&trustStoreFile=#tsf""; String return_string = ""When You Go Home, Tell Them Of Us And Say,"" + ""For Your Tomorrow, We Gave Our Today.""; from(netty_ssl_endpoint) .process(new Processor() { public void process(Exchange exchange) throws Exception { exchange.getOut().setBody(return_string); } } } }); ---- [[Netty-GettingaccesstoSSLSessionandtheclientcertificate]] Getting access to SSLSession and the client certificate You can get access to the `javax.net.ssl.SSLSession` if you eg need to get details about the client certificate. When `ssl=true` then the xref:netty-component.adoc[Netty] component will store the `SSLSession` as a header on the Camel Message as shown below: [source,java] ---- SSLSession session = exchange.getIn().getHeader(NettyConstants.NETTY_SSL_SESSION, SSLSession.class); // get the first certificate which is client certificate javax.security.cert.X509Certificate cert = session.getPeerCertificateChain()[0]; Principal principal = cert.getSubjectDN(); ---- Remember to set `needClientAuth=true` to authenticate the client, otherwise `SSLSession` cannot access information about the client certificate, and you may get an exception `javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated`. You may also get this exception if the client certificate is expired or not valid etc. [TIP] ==== The option `sslClientCertHeaders` can be set to `true` which then enriches the Camel Message with headers having details about the client certificate. For example the subject name is readily available in the header `CamelNettySSLClientCertSubjectName`. ==== === Using Multiple Codecs In certain cases it may be necessary to add chains of encoders and decoders to the netty pipeline. To add multpile codecs to a camel netty endpoint the 'encoders' and 'decoders' uri parameters should be used. Like the 'encoder' and 'decoder' parameters they are used to supply references (lists of ChannelUpstreamHandlers and ChannelDownstreamHandlers) that should be added to the pipeline. Note that if encoders is specified then the encoder param will be ignored, similarly for decoders and the decoder param. [NOTE] ==== Read further above about using non shareable encoders/decoders. ==== The lists of codecs need to be added to the Camel's registry so they can be resolved when the endpoint is created. [source,java] ---- ChannelHandlerFactory lengthDecoder = ChannelHandlerFactories.newLengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4); StringDecoder stringDecoder = new StringDecoder(); registry.bind(""length-decoder"", lengthDecoder); registry.bind(""string-decoder"", stringDecoder); LengthFieldPrepender lengthEncoder = new LengthFieldPrepender(4); StringEncoder stringEncoder = new StringEncoder(); registry.bind(""length-encoder"", lengthEncoder); registry.bind(""string-encoder"", stringEncoder); List decoders = new ArrayList(); decoders.add(lengthDecoder); decoders.add(stringDecoder); List encoders = new ArrayList(); encoders.add(lengthEncoder); encoders.add(stringEncoder); registry.bind(""encoders"", encoders); registry.bind(""decoders"", decoders); ---- Spring's native collections support can be used to specify the codec lists in an application context [source,xml] ---- ---- The bean names can then be used in netty endpoint definitions either as a comma separated list or contained in a List e.g. [source,java] ---- from(""direct:multiple-codec"").to(""netty:tcp://0.0.0.0:{{port}}?encoders=#encoders&sync=false""); from(""netty:tcp://0.0.0.0:{{port}}?decoders=#length-decoder,#string-decoder&sync=false"").to(""mock:multiple-codec""); ---- or via XML. [source,xml] ---- ---- == Closing Channel When Complete When acting as a server you sometimes want to close the channel when, for example, a client conversion is finished. + You can do this by simply setting the endpoint option `disconnect=true`. However you can also instruct Camel on a per message basis as follows. + To instruct Camel to close the channel, you should add a header with the key `CamelNettyCloseChannelWhenComplete` set to a boolean `true` value. + For instance, the example below will close the channel after it has written the bye message back to the client: [source,java] ---- from(""netty:tcp://0.0.0.0:8080"").process(new Processor() { public void process(Exchange exchange) throws Exception { String body = exchange.getIn().getBody(String.class); exchange.getOut().setBody(""Bye "" + body); // some condition which determines if we should close if (close) { exchange.getOut().setHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, true); } } }); ---- [[Netty-Addingcustomchannelpipelinefactoriestogaincompletecontroloveracreatedpipeline]] Adding custom channel pipeline factories to gain complete control over a created pipeline == Custom pipeline Custom channel pipelines provide complete control to the user over the handler/interceptor chain by inserting custom handler(s), encoder(s) & decoder(s) without having to specify them in the Netty Endpoint URL in a very simple way. In order to add a custom pipeline, a custom channel pipeline factory must be created and registered with the context via the context registry (Registry, or the camel-spring ApplicationContextRegistry etc). A custom pipeline factory must be constructed as follows * A Producer linked channel pipeline factory must extend the abstract class `ClientPipelineFactory`. * A Consumer linked channel pipeline factory must extend the abstract class `ServerInitializerFactory`. * The classes should override the initChannel() method in order to insert custom handler(s), encoder(s) and decoder(s). Not overriding the `initChannel()` method creates a pipeline with no handlers, encoders or decoders wired to the pipeline. The example below shows how ServerInitializerFactory factory may be created === Using custom pipeline factory [source,java] ---- public class SampleServerInitializerFactory extends ServerInitializerFactory { private int maxLineSize = 1024; protected void initChannel(Channel ch) throws Exception { ChannelPipeline channelPipeline = ch.pipeline(); channelPipeline.addLast(""encoder-SD"", new StringEncoder(CharsetUtil.UTF_8)); channelPipeline.addLast(""decoder-DELIM"", new DelimiterBasedFrameDecoder(maxLineSize, true, Delimiters.lineDelimiter())); channelPipeline.addLast(""decoder-SD"", new StringDecoder(CharsetUtil.UTF_8)); // here we add the default Camel ServerChannelHandler for the consumer, to allow Camel to route the message etc. channelPipeline.addLast(""handler"", new ServerChannelHandler(consumer)); } } ---- The custom channel pipeline factory can then be added to the registry and instantiated/utilized on a camel route in the following way [source,java] ---- Registry registry = camelContext.getRegistry(); ServerInitializerFactory factory = new TestServerInitializerFactory(); registry.bind(""spf"", factory); context.addRoutes(new RouteBuilder() { public void configure() { String netty_ssl_endpoint = ""netty:tcp://0.0.0.0:5150?serverInitializerFactory=#spf"" String return_string = ""When You Go Home, Tell Them Of Us And Say,"" + ""For Your Tomorrow, We Gave Our Today.""; from(netty_ssl_endpoint) .process(new Processor() { public void process(Exchange exchange) throws Exception { exchange.getOut().setBody(return_string); } } } }); ---- == Reusing Netty boss and worker thread pools Netty has two kind of thread pools: boss and worker. By default each Netty consumer and producer has their private thread pools. If you want to reuse these thread pools among multiple consumers or producers then the thread pools must be created and enlisted in the Registry. For example using Spring XML we can create a shared worker thread pool using the `NettyWorkerPoolBuilder` with 2 worker threads as shown below: [source,xml] ---- ---- [TIP] ==== For boss thread pool there is a `org.apache.camel.component.netty.NettyServerBossPoolBuilder` builder for Netty consumers, and a `org.apache.camel.component.netty.NettyClientBossPoolBuilder` for the Netty producers. ==== Then in the Camel routes we can refer to this worker pools by configuring the `workerPool` option in the URI as shown below: [source,xml] ---- ... ---- And if we have another route we can refer to the shared worker pool: [source,xml] ---- ... ---- and so forth. == Multiplexing concurrent messages over a single connection with request/reply When using Netty for request/reply messaging via the netty producer then by default each message is sent via a non-shared connection (pooled). This ensures that replies are automatic being able to map to the correct request thread for further routing in Camel. In other words correlation between request/reply messages happens out-of-the-box because the replies comes back on the same connection that was used for sending the request; and this connection is not shared with others. When the response comes back, the connection is returned back to the connection pool, where it can be reused by others. However if you want to multiplex concurrent request/responses on a single shared connection, then you need to turn off the connection pooling by setting `producerPoolEnabled=false`. Now this means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement `NettyCamelStateCorrelationManager` as correlation manager and configure it via the `correlationManager=#myManager` option. [NOTE] ==== We recommend extending the `TimeoutCorrelationManagerSupport` when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well. ==== You can find an example with the Apache Camel source code in the examples directory under the `camel-example-netty-custom-correlation` directory. include::camel-spring-boot::page$netty-starter.adoc[] ",12443,False,2353.8948629336614,median "#include ""Graphics\\Rendering\\Deferred\\DeferredRendererBP.h"" #include ""Graphics\\GraphicsAdapter.h"" #include ""Graphics\\Materials\\MaterialBP.h"" #include ""Graphics\\Models\\Shapes.h"" #include ""Core\\Math\\Interpolation.h"" #define PCF /* Deferred renderer works in three stages. First stage: - Accumilate all models that need to be rendered. - Static Models - Dynamic Models - Perform a G Buffer pass for each of them (LDR). - Discard almost fully transparent fragments - Save material properies into the G buffer. Second stage: - Perform direction light pass for each directional light (HDR). - Render shadow maps (PSSM / CSM). - Apply to full screen quad. - PCF smooth shadows. - Additively blend each light into HDR screen buffer. - Perform point light pass for each point light (HDR). - Apply to light volume sphere. - Additively blend each light into HDR screen buffer. Third stage: - Fix values for display monitor (LDR). - Reinhard tone mapping to go from HDR to LDR. - Apply gamma correction for each fragment. */ struct PlaneVertexFormat { Plutonium::Vector3 Position; Plutonium::Vector2 Uv; }; #pragma region Shader Sources constexpr const char *STATIC_GPASS_VRTX_SHDR_SRC = ""#version 430 core \\n"" ""struct FragInfo \\n"" ""{ \\n"" "" vec3 Position; \\n"" "" vec2 Uv; \\n"" "" mat3 TBN; \\n"" ""}; \\n"" ""uniform mat4 Projection; \\n"" ""uniform mat4 View; \\n"" ""uniform mat4 Model; \\n"" ""in vec3 Position; \\n"" ""in vec3 Normal; \\n"" ""in vec3 Tangent; \\n"" ""in vec2 Uv; \\n"" ""out FragInfo Frag; \\n"" ""void main() \\n"" ""{ \\n"" "" Frag.Position = (Model * vec4(Position, 1.0f)).xyz; \\n"" "" Frag.Uv = Uv; \\n"" "" vec3 t = normalize((Model * vec4(Tangent, 0.0f)).xyz); \\n"" "" vec3 n = normalize((Model * vec4(Normal, 0.0f)).xyz); \\n"" "" vec3 b = cross(n, t); \\n"" "" Frag.TBN = mat3(t, b, n); \\n"" "" gl_Position = Projection * View * Model * vec4(Position, 1.0f); \\n"" ""}""; constexpr const char *ANIMATED_GPASS_VRTX_SHDR_SRC = ""#version 430 core \\n"" ""struct FragInfo \\n"" ""{ \\n"" "" vec3 Position; \\n"" "" vec2 Uv; \\n"" "" mat3 TBN; \\n"" ""}; \\n"" ""uniform mat4 Model; \\n"" ""uniform mat4 View; \\n"" ""uniform mat4 Projection; \\n"" ""uniform float Blending; \\n"" ""in vec3 Position1; \\n"" ""in vec3 Normal1; \\n"" ""in vec3 Tangent1; \\n"" ""in vec2 Uv; \\n"" ""in vec3 Position2; \\n"" ""in vec3 Normal2; \\n"" ""in vec3 Tangent2; \\n"" ""out FragInfo Frag; \\n"" ""void main() \\n"" ""{ \\n"" "" vec3 position = mix(Position1, Position2, Blending); \\n"" "" vec3 normal = normalize(Normal1 + Normal2); \\n"" "" vec3 tangent = normalize(Tangent1 + Tangent2); \\n"" "" Frag.Position = (Model * vec4(position, 1.0f)).xyz; \\n"" "" Frag.Uv = Uv; \\n"" "" vec3 t = normalize((Model * vec4(tangent, 0.0f)).xyz); \\n"" "" vec3 n = normalize((Model * vec4(normal, 0.0f)).xyz); \\n"" "" vec3 b = cross(n, t); \\n"" "" Frag.TBN = mat3(t, b, n); \\n"" "" gl_Position = Projection * View * Model * vec4(position, 1.0f); \\n"" ""}""; constexpr const char *GPASS_FRAG_SHDR_SRC = ""#version 430 core \\n"" ""struct FragInfo \\n"" ""{ \\n"" "" vec3 Position; \\n"" "" vec2 Uv; \\n"" "" mat3 TBN; \\n"" ""}; \\n"" ""struct Material \\n"" ""{ \\n"" "" sampler2D Ambient; \\n"" "" sampler2D Diffuse; \\n"" "" sampler2D Specular; \\n"" "" sampler2D Opacity; \\n"" "" sampler2D Normal; \\n"" "" float SpecularExponent; \\n"" ""}; \\n"" ""uniform Material Object; \\n"" ""uniform float GammaCorrection; \\n"" ""in FragInfo Frag; \\n"" ""out vec4 NormalSpecular; \\n"" ""out vec4 PositionSpecular; \\n"" ""out vec3 Ambient; \\n"" ""out vec3 Diffuse; \\n"" ""void main() \\n"" ""{ \\n"" "" vec4 diffuse = texture(Object.Diffuse, Frag.Uv); \\n"" "" vec4 alpha = texture(Object.Opacity, Frag.Uv); \\n"" "" if ((alpha.r < 0.1f && alpha.g < 0.1f && alpha.r < 0.1f) || alpha.a < 0.1f || diffuse.a < 0.1f) discard; \\n"" "" vec3 normal = texture(Object.Normal, Frag.Uv).rgb * 2.0f - 1.0f; \\n"" "" normal = Frag.TBN * normalize(normal); \\n"" "" Ambient = texture(Object.Ambient, Frag.Uv).rgb; \\n"" "" Diffuse = diffuse.rgb; \\n"" "" NormalSpecular.xyz = normal; \\n"" "" NormalSpecular.w = texture(Object.Specular, Frag.Uv).r; \\n"" "" PositionSpecular.xyz = Frag.Position; \\n"" "" PositionSpecular.w = Object.SpecularExponent; \\n"" ""}""; constexpr const char *PASS_VRTX_SHDR_SRC = ""#version 430 core \\n"" ""in vec3 Position; \\n"" ""in vec2 ScreenCoordinate; \\n"" ""out vec2 Uv; \\n"" ""void main() \\n"" ""{ \\n"" "" Uv = ScreenCoordinate; \\n"" "" gl_Position = vec4(Position, 1.0f); \\n"" ""}""; constexpr const char *DSPASS_VRTX_SHDR_SRC = ""#version 430 core \\n"" ""uniform mat4 Model; \\n"" ""uniform mat4 CascadeSpace; \\n"" ""uniform float Blending; \\n"" ""in vec3 Position1; \\n"" ""in vec3 Position2; \\n"" ""in vec2 Uv; \\n"" ""out vec2 FragUv; \\n"" ""void main() \\n"" ""{ \\n"" "" FragUv = Uv; \\n"" "" gl_Position = CascadeSpace * Model * vec4(mix(Position1, Position2, Blending), 1.0f); \\n"" ""}""; constexpr const char *DPASS_FRAG_SHDR_SRC = ""#version 430 core \\n"" ""struct GBuffer \\n"" ""{ \\n"" "" sampler2D NormalSpecular; \\n"" "" sampler2D PositionSpecular; \\n"" "" sampler2D Ambient; \\n"" "" sampler2D Diffuse; \\n"" ""}; \\n"" ""struct DirectionalLight \\n"" ""{ \\n"" "" vec3 Direction; \\n"" "" vec4 Ambient; \\n"" "" vec4 Diffuse; \\n"" "" vec4 Specular; \\n"" "" mat4 CascadeSpace1; \\n"" "" sampler2D Cascade1; \\n"" "" float CascadeEnd1; \\n"" "" mat4 CascadeSpace2; \\n"" "" sampler2D Cascade2; \\n"" "" float CascadeEnd2; \\n"" "" mat4 CascadeSpace3; \\n"" "" sampler2D Cascade3; \\n"" "" float CascadeEnd3; \\n"" ""}; \\n"" ""uniform GBuffer Geometry; \\n"" ""uniform DirectionalLight Light; \\n"" ""uniform vec3 ViewPosition; \\n"" ""uniform mat4 View; \\n"" ""uniform float CascadeIntensity; \\n"" ""in vec2 Uv; \\n"" ""out vec4 FragColor; \\n"" ""float CalcShadowFactor(sampler2D cascade, vec4 pos, vec3 normal) \\n"" ""{ \\n"" "" vec3 ndc = (pos.xyz / pos.w) * 0.5f + 0.5f; \\n"" "" float bias = max(0.005f * (1.0f - dot(normal, Light.Direction)), 0.005f); \\n"" "" return texture(cascade, ndc.xy).x < ndc.z - bias ? 0.0f : 1.0f; \\n"" ""} \\n"" ""void main() \\n"" ""{ \\n"" "" vec4 posSpec = texture(Geometry.PositionSpecular, Uv); \\n"" "" vec4 normSpec = texture(Geometry.NormalSpecular, Uv); \\n"" "" vec3 objAmbient = texture(Geometry.Ambient, Uv).rgb; \\n"" "" vec3 objDiffuse = texture(Geometry.Diffuse, Uv).rgb; \\n"" "" vec4 pos = vec4(posSpec.xyz, 1.0f); \\n"" "" float viewSpaceZ = -(View * pos).z; \\n"" "" float visibility = 0.0f; \\n"" "" if (viewSpaceZ <= Light.CascadeEnd1) \\n"" "" { \\n"" "" visibility = CalcShadowFactor(Light.Cascade1, Light.CascadeSpace1 * pos, normSpec.xyz); \\n"" "" objAmbient.r = max(CascadeIntensity, objAmbient.r); \\n"" "" } \\n"" "" else if (viewSpaceZ <= Light.CascadeEnd2) \\n"" "" { \\n"" "" visibility = CalcShadowFactor(Light.Cascade2, Light.CascadeSpace2 * pos, normSpec.xyz); \\n"" "" objAmbient.g = max(CascadeIntensity, objAmbient.g); \\n"" "" } \\n"" "" else if (viewSpaceZ <= Light.CascadeEnd3) \\n"" "" { \\n"" "" visibility = CalcShadowFactor(Light.Cascade3, Light.CascadeSpace3 * pos, normSpec.xyz); \\n"" "" objAmbient.b = max(CascadeIntensity, objAmbient.b); \\n"" "" } \\n"" "" vec3 viewDir = normalize(ViewPosition - posSpec.xyz); \\n"" "" float intensity = max(0.0f, dot(normSpec.xyz, Light.Direction)); \\n"" "" vec3 halfwayDir = normalize(Light.Direction + viewDir); \\n"" "" float power = pow(max(0.0f, dot(normSpec.xyz, halfwayDir)), posSpec.w); \\n"" "" vec4 ambient = vec4(objAmbient, 1.0f) * Light.Ambient; \\n"" "" vec4 diffuse = vec4(objDiffuse, 1.0f) * Light.Diffuse * intensity; \\n"" "" vec4 specular = normSpec.w * Light.Specular * power; \\n"" "" FragColor = ambient + (visibility * (diffuse + specular)); \\n"" ""}""; constexpr const char *DPASS_PCF_FRAG_SHDR_SRC = ""#version 430 core \\n"" ""struct GBuffer \\n"" ""{ \\n"" "" sampler2D NormalSpecular; \\n"" "" sampler2D PositionSpecular; \\n"" "" sampler2D Ambient; \\n"" "" sampler2D Diffuse; \\n"" ""}; \\n"" ""struct DirectionalLight \\n"" ""{ \\n"" "" vec3 Direction; \\n"" "" vec4 Ambient; \\n"" "" vec4 Diffuse; \\n"" "" vec4 Specular; \\n"" "" mat4 CascadeSpace1; \\n"" "" sampler2D Cascade1; \\n"" "" float CascadeEnd1; \\n"" "" mat4 CascadeSpace2; \\n"" "" sampler2D Cascade2; \\n"" "" float CascadeEnd2; \\n"" "" mat4 CascadeSpace3; \\n"" "" sampler2D Cascade3; \\n"" "" float CascadeEnd3; \\n"" ""}; \\n"" ""uniform GBuffer Geometry; \\n"" ""uniform DirectionalLight Light; \\n"" ""uniform vec3 ViewPosition; \\n"" ""uniform mat4 View; \\n"" ""uniform float CascadeIntensity; \\n"" ""in vec2 Uv; \\n"" ""out vec4 FragColor; \\n"" ""float CalcShadowFactor(sampler2D cascade, vec4 pos, vec3 normal) \\n"" ""{ \\n"" "" vec3 ndc = (pos.xyz / pos.w) * 0.5f + 0.5f; \\n"" "" float bias = max(0.005f * (1.0f - dot(normal, Light.Direction)), 0.005f); \\n"" "" float result = 0.0f; \\n"" "" vec2 texelSize = 1.0f / textureSize(cascade, 0); \\n"" "" for (float x = -1.5f; x <= 1.5f; x += 1.0f) \\n"" "" { \\n"" "" for (float y = -1.5f; y <= 1.5f; y += 1.0f) \\n"" "" { \\n"" "" float pcf = texture(cascade, ndc.xy + vec2(x, y) * texelSize).x; \\n"" "" result += pcf < ndc.z - bias ? 0.1f : 1.0f; \\n"" "" } \\n"" "" } \\n"" "" return result / 16.0f; \\n"" ""} \\n"" ""void main() \\n"" ""{ \\n"" "" vec4 posSpec = texture(Geometry.PositionSpecular, Uv); \\n"" "" vec4 normSpec = texture(Geometry.NormalSpecular, Uv); \\n"" "" vec3 objAmbient = texture(Geometry.Ambient, Uv).rgb; \\n"" "" vec3 objDiffuse = texture(Geometry.Diffuse, Uv).rgb; \\n"" "" vec4 pos = vec4(posSpec.xyz, 1.0f); \\n"" "" float viewSpaceZ = -(View * pos).z; \\n"" "" float visibility = 0.0f; \\n"" "" if (viewSpaceZ <= Light.CascadeEnd1) \\n"" "" { \\n"" "" visibility = CalcShadowFactor(Light.Cascade1, Light.CascadeSpace1 * pos, normSpec.xyz); \\n"" "" objAmbient.r = max(CascadeIntensity, objAmbient.r); \\n"" "" } \\n"" "" else if (viewSpaceZ <= Light.CascadeEnd2) \\n"" "" { \\n"" "" visibility = CalcShadowFactor(Light.Cascade2, Light.CascadeSpace2 * pos, normSpec.xyz); \\n"" "" objAmbient.g = max(CascadeIntensity, objAmbient.g); \\n"" "" } \\n"" "" else if (viewSpaceZ <= Light.CascadeEnd3) \\n"" "" { \\n"" "" visibility = CalcShadowFactor(Light.Cascade3, Light.CascadeSpace3 * pos, normSpec.xyz); \\n"" "" objAmbient.b = max(CascadeIntensity, objAmbient.b); \\n"" "" } \\n"" "" vec3 viewDir = normalize(ViewPosition - posSpec.xyz); \\n"" "" float intensity = max(0.0f, dot(normSpec.xyz, Light.Direction)); \\n"" "" vec3 halfwayDir = normalize(Light.Direction + viewDir); \\n"" "" float power = pow(max(0.0f, dot(normSpec.xyz, halfwayDir)), posSpec.w); \\n"" "" vec4 ambient = vec4(objAmbient, 1.0f) * Light.Ambient; \\n"" "" vec4 diffuse = vec4(objDiffuse, 1.0f) * Light.Diffuse * intensity; \\n"" "" vec4 specular = normSpec.w * Light.Specular * power; \\n"" "" FragColor = ambient + (visibility * (diffuse + specular)); \\n"" ""}""; constexpr const char* DSPASS_FRAG_SHDR_SRC = ""#version 430 core \\n"" ""uniform sampler2D Opacity; \\n"" ""uniform sampler2D Diffuse; \\n"" ""in vec2 FragUv; \\n"" ""void main() \\n"" ""{ \\n"" "" vec4 alpha = texture(Opacity, FragUv); \\n"" "" float diffuse = texture(Diffuse, FragUv).a; \\n"" "" if ((alpha.r < 0.1f && alpha.g < 0.1f && alpha.r < 0.1f) || alpha.a < 0.1f || diffuse < 0.1f) discard; \\n"" "" gl_FragDepth = gl_FragCoord.z; \\n"" ""}""; constexpr const char *PPASS_VRTX_SHDR_SRC = ""#version 430 core \\n"" ""uniform mat4 Projection; \\n"" ""uniform mat4 View; \\n"" ""uniform mat4 Model; \\n"" ""in vec3 Position; \\n"" ""void main() \\n"" ""{ \\n"" "" gl_Position = Projection * View * Model * vec4(Position, 1.0f); \\n"" ""}""; constexpr const char *PPASS_FRAG_SHDR_SRC = ""#version 430 core \\n"" ""struct GBuffer \\n"" ""{ \\n"" "" sampler2D NormalSpecular; \\n"" "" sampler2D PositionSpecular; \\n"" "" sampler2D Ambient; \\n"" "" sampler2D Diffuse; \\n"" ""}; \\n"" ""struct PointLight \\n"" ""{ \\n"" "" vec3 Position; \\n"" "" float Constant; \\n"" "" float Linear; \\n"" "" float Quadratic; \\n"" "" vec4 Ambient; \\n"" "" vec4 Diffuse; \\n"" "" vec4 Specular; \\n"" ""}; \\n"" ""uniform GBuffer Geometry; \\n"" ""uniform PointLight Light; \\n"" ""uniform vec3 ViewPosition; \\n"" ""uniform vec2 ScreenSize; \\n"" ""out vec4 FragColor; \\n"" ""void main() \\n"" ""{ \\n"" "" vec2 uv = gl_FragCoord.xy / ScreenSize; \\n"" "" vec4 posSpec = texture(Geometry.PositionSpecular, uv); \\n"" "" vec4 normSpec = texture(Geometry.NormalSpecular, uv); \\n"" "" vec3 objAmbient = texture(Geometry.Ambient, uv).rgb; \\n"" "" vec3 objDiffuse = texture(Geometry.Diffuse, uv).rgb; \\n"" "" vec3 viewDir = normalize(ViewPosition - posSpec.xyz); \\n"" "" vec3 lightDir = normalize(Light.Position - posSpec.xyz); \\n"" "" float distance = length(Light.Position - posSpec.xyz); \\n"" "" float intensity = max(0.0f, dot(normSpec.xyz, lightDir)); \\n"" "" float attenuation = 1.0f / (Light.Constant + Light.Linear * distance + Light.Quadratic * distance * distance); \\n"" "" vec3 halfwayDir = normalize(lightDir + viewDir); \\n"" "" float power = pow(max(0.0f, dot(normSpec.xyz, halfwayDir)), posSpec.w); \\n"" "" vec4 ambient = vec4(objAmbient, 1.0f) * Light.Ambient * attenuation; \\n"" "" vec4 diffuse = vec4(objDiffuse, 1.0f) * Light.Diffuse * attenuation * intensity; \\n"" "" vec4 specular = normSpec.w * Light.Specular * attenuation * power; \\n"" "" FragColor = ambient + diffuse + specular, vec4(1.0f); \\n"" ""}""; constexpr const char *FPASS_FRAG_SHDR_SRC = ""#version 430 core \\n"" ""const vec3 ToLuma = vec3(0.229f, 0.587f, 0.114f); \\n"" ""uniform sampler2D HdrBuffer; \\n"" ""uniform float GammaCorrection; \\n"" ""uniform float Exposure; \\n"" ""in vec2 Uv; \\n"" ""out vec4 FragColor; \\n"" ""void main() \\n"" ""{ \\n"" "" vec3 hdr = texture(HdrBuffer, Uv).rgb; \\n"" "" vec3 mapped = vec3(1.0f) - exp(-hdr * Exposure); \\n"" "" vec3 corrected = pow(mapped, vec3(GammaCorrection)); \\n"" "" FragColor = vec4(corrected, 1.0f); \\n"" ""}""; constexpr const char *FPASS_FXAA_FRAG_SHDR_SRC = ""#version 430 core \\n"" ""const vec3 ToLuma = vec3(0.229f, 0.587f, 0.114f); \\n"" ""uniform sampler2D HdrBuffer; \\n"" ""uniform float GammaCorrection; \\n"" ""uniform float Exposure; \\n"" ""uniform vec2 TexelStep; \\n"" ""in vec2 Uv; \\n"" ""out vec4 FragColor; \\n"" ""void main() \\n"" ""{ \\n"" "" vec3 hdr = texture(HdrBuffer, Uv).rgb; \\n"" "" vec3 hdrNW = textureOffset(HdrBuffer, Uv, ivec2(-1, 1)).rgb; \\n"" "" vec3 hdrNE = textureOffset(HdrBuffer, Uv, ivec2(1, 1)).rgb; \\n"" "" vec3 hdrSW = textureOffset(HdrBuffer, Uv, ivec2(-1, -1)).rgb; \\n"" "" vec3 hdrSE = textureOffset(HdrBuffer, Uv, ivec2(1, -1)).rgb; \\n"" "" float luma = dot(hdr, ToLuma); \\n"" "" float lumaNW = dot(hdrNW, ToLuma); \\n"" "" float lumaNE = dot(hdrNE, ToLuma); \\n"" "" float lumaSW = dot(hdrSW, ToLuma); \\n"" "" float lumaSE = dot(hdrSE, ToLuma); \\n"" "" float lumaMin = min(luma, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE))); \\n"" "" float lumaMax = max(luma, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE))); \\n"" "" if (lumaMax - lumaMin >= lumaMax * 0.5f) \\n"" "" { \\n"" "" vec2 sampleDir = vec2(-((-lumaNW + lumaNE) - (lumaSW + lumaSE)), (lumaNW + lumaSW) - (lumaNE + lumaSE)); \\n"" "" float reduce = max((lumaNW + lumaNE + lumaSW + lumaSE) * 0.031f, 0.007f); \\n"" "" float minSampleDir = 1.0f / (min(abs(sampleDir.x), abs(sampleDir.y)) + reduce); \\n"" "" sampleDir = clamp(sampleDir * minSampleDir, vec2(-8.0f, -8.0f), vec2(8.0f, 8.0f)) * TexelStep; \\n"" "" vec3 ihdrSample = texture(HdrBuffer, Uv + sampleDir * (1.0f / 3.0f - 0.5f)).rgb; \\n"" "" vec3 hdrSample = texture(HdrBuffer, Uv + sampleDir * (2.0f / 3.0f - 0.5f)).rgb; \\n"" "" vec3 hdrTwoTab = (hdrSample + ihdrSample) * 0.5f; \\n"" "" vec3 ihdrSampleOut = texture(HdrBuffer, Uv + sampleDir * (0.0f / 3.0f - 0.5f)).rgb; \\n"" "" vec3 hdrSampleOut = texture(HdrBuffer, Uv + sampleDir * (3.0f / 3.0f - 0.5f)).rgb; \\n"" "" vec3 hdrFourTab = (hdrSampleOut + ihdrSampleOut) * 0.25f + hdrTwoTab * 0.5f; \\n"" "" float lumaFourTab = dot(hdrFourTab, ToLuma); \\n"" "" hdr = (lumaFourTab < lumaMin || lumaFourTab > lumaMax) ? hdrTwoTab : hdrFourTab; \\n"" "" } \\n"" "" vec3 mapped = vec3(1.0f) - exp(-hdr * Exposure); \\n"" "" vec3 corrected = pow(mapped, vec3(GammaCorrection)); \\n"" "" FragColor = vec4(corrected, 1.0f); \\n"" ""}""; constexpr const char *WIRE_VRTX_SHDR_SRC = ""#version 430 core \\n"" ""uniform mat4 Model; \\n"" ""uniform mat4 View; \\n"" ""uniform mat4 Projection; \\n"" ""uniform float Blending; \\n"" ""in vec3 Position; \\n"" ""in vec3 Position2; \\n"" ""in vec2 Uv; \\n"" ""out vec2 GeomUv; \\n"" ""void main() \\n"" ""{ \\n"" "" GeomUv = Uv; \\n"" "" gl_Position = Projection * View * Model * vec4(mix(Position, Position2, Blending), 1.0); \\n"" ""}""; constexpr const char *WIRE_GEOM_SHDR_SRC = ""#version 430 core \\n"" ""layout (triangles) in; \\n"" ""layout (triangle_strip, max_vertices = 3) out; \\n"" ""in vec2 GeomUv[]; \\n"" ""out vec2 FragUv; \\n"" ""out noperspective vec3 WireFrameDist; \\n"" ""void main() \\n"" ""{ \\n"" "" for (int i = 0; i < 3; i++) \\n"" "" { \\n"" "" gl_Position = gl_in[i].gl_Position; \\n"" "" FragUv = GeomUv[i]; \\n"" "" WireFrameDist = vec3(0.0f); \\n"" "" WireFrameDist[i] = 1.0f; \\n"" "" EmitVertex(); \\n"" "" } \\n"" ""}""; constexpr const char *WIRE_FRAG_SHDR_SRC = ""#version 430 core \\n"" ""uniform vec4 Color; \\n"" ""uniform sampler2D Diffuse; \\n"" ""in vec2 FragUv; \\n"" ""in vec3 WireFrameDist; \\n"" ""out vec4 FragColor; \\n"" ""void main() \\n"" ""{ \\n"" "" vec3 d = fwidth(WireFrameDist); \\n"" "" vec3 a = smoothstep(vec3(0.0f), d * 1.5f, WireFrameDist); \\n"" "" float edgeFactor = min(min(a.x, a.y), a.z); \\n"" "" vec4 base = vec4(texture(Diffuse, FragUv).rgb, 0.5f); \\n"" "" FragColor = mix(Color, base, edgeFactor); \\n"" ""}""; constexpr const char *WN_FRAG_SHDR_SRC = ""#version 430 core \\n"" ""uniform sampler2D NormalSpecular; \\n"" ""in vec2 Uv; \\n"" ""out vec4 FragColor; \\n"" ""void main() \\n"" ""{ \\n"" "" vec3 worldNormal = texture(NormalSpecular, Uv).xyz; \\n"" "" vec3 rgbNormal = normalize(worldNormal * 0.5f + 0.5f); \\n"" "" FragColor = vec4(rgbNormal, 1.0f); \\n"" ""}""; constexpr const char *AL_FRAG_SHDR_SRC = ""#version 430 core \\n"" ""uniform sampler2D Diffuse; \\n"" ""in vec2 Uv; \\n"" ""out vec4 FragColor; \\n"" ""void main() \\n"" ""{ \\n"" "" FragColor = vec4(texture(Diffuse, Uv).rgb, 1.0f); \\n"" ""}""; #pragma endregion Plutonium::DeferredRendererBP::DeferredRendererBP(Game * game, bool fxaa, bool softShadows) : game(game), Exposure(1.0f), CascadeLambda(0.5f), LightOffset(1.0f), DisplayType(RenderType::Normal) { /* Initialize G buffer. */ gbFbo = new RenderTarget(game->GetGraphics(), true); normalSpec = gbFbo->Attach(""Normal / Specular map"", AttachmentOutputType::HpVector4); posSpec = gbFbo->Attach(""Position / Specular exponent"", AttachmentOutputType::HpVector4); ambient = gbFbo->Attach(""Ambient"", AttachmentOutputType::RGB); diffuse = gbFbo->Attach(""Diffuse"", AttachmentOutputType::RGB); gbFbo->Finalize(); /* Initialize shader map buffer. */ dshdFbo = new RenderTarget(game->GetGraphics(), false, 1024, 4096); for (size_t i = 0; i < CASCADE_CNT; i++) cascades[i] = dshdFbo->Attach(""Directional Light Cascade Depth"", AttachmentOutputType::HpDepth, i == 0); dshdFbo->Finalize(); /* Initialize HDR lighting intermediate buffer. */ hdrFbo = new RenderTarget(game->GetGraphics(), true); screen = hdrFbo->Attach(""HDR Output"", AttachmentOutputType::LpVector4); hdrFbo->Finalize(); InitMeshes(); InitGsPass(); InitGdPass(); InitDsPass(); InitDPass(softShadows); InitPPass(); InitFPass(fxaa); InitWire(); InitWNormal(); InitAlbedo(); } Plutonium::DeferredRendererBP::~DeferredRendererBP(void) { delete_s(gbFbo); delete_s(dshdFbo); delete_s(hdrFbo); delete_s(defMaterial); delete_s(plane); delete_s(sphere); delete_s(gspass.shdr); delete_s(gdpass.shdr); delete_s(dspass.shdr); delete_s(dpass.shdr); delete_s(ppass.shdr); delete_s(wire.shdr); delete_s(wn.shdr); delete_s(al.shdr); } void Plutonium::DeferredRendererBP::Add(const StaticObject * model) { queuedModels.push_back(model); } void Plutonium::DeferredRendererBP::Add(const DynamicObject * model) { queuedAnimations.push_back(model); } void Plutonium::DeferredRendererBP::Add(const DirectionalLight * light) { queuedDLights.push_back(light); } void Plutonium::DeferredRendererBP::Add(const PointLight * light) { queuePLights.push_back(light); } void Plutonium::DeferredRendererBP::Render(const Camera * cam) { GraphicsAdapter *device = game->GetGraphics(); const MaterialBP *usedMaterial = DisplayType != RenderType::Lighting ? nullptr : defMaterial; /* Setup GBuffer. */ device->SetRenderTarget(gbFbo); device->Clear(ClearTarget::Color | ClearTarget::Depth); device->SetColorBlendFunction(BlendState::None); /* Perform geometry pass to fill the GBuffer. */ BeginGsPass(cam->GetProjection(), cam->GetView()); for (size_t i = 0; i < queuedModels.size(); i++) RenderModel(cam, queuedModels.at(i), usedMaterial); gspass.shdr->End(); BeginGdPass(cam->GetProjection(), cam->GetView()); for (size_t i = 0; i < queuedAnimations.size(); i++) RenderModel(cam, queuedAnimations.at(i), usedMaterial); gdpass.shdr->End(); /* Setup HDR buffer for lighting. */ device->SetRenderTarget(hdrFbo); device->Clear(ClearTarget::Color | ClearTarget::Depth); /* Render to HDR buffer is defined per render mode. */ switch (DisplayType) { case Plutonium::RenderType::Normal: case Plutonium::RenderType::Lighting: case Plutonium::RenderType::Shadows: RenderNormal(cam); break; case Plutonium::RenderType::Wireframe: RenderWireframe(cam->GetProjection(), cam->GetView()); break; case Plutonium::RenderType::WorldNormals: RenderWorldNormals(); break; case Plutonium::RenderType::Albedo: RenderAlbedo(); break; default: LOG_THROW(""Display type is not supported!""); break; } /* Setup default frame buffer and copy the depth buffer over from the G buffer (or hdr buffer for wireframe mode). */ device->SetRenderTarget(nullptr); device->SetColorBlendFunction(BlendState::None); device->SetDepthOuput(true); gbFbo->BlitDepth(); /* Final render pass to fix the fix the values for the display monitor. */ device->SetDepthOuput(false); FixForMonitor(); device->SetDepthOuput(true); /* Clear queues. */ queuedModels.clear(); queuedAnimations.clear(); queuedDLights.clear(); queuePLights.clear(); } #pragma region Initializers void Plutonium::DeferredRendererBP::InitMeshes(void) { /* Initialize plane used for fully screen rendering. */ plane = new Buffer(game->GetGraphics()->GetWindow(), BindTarget::Array); PlaneVertexFormat vertices[4] = { { Vector3(-1.0f, 1.0f, 0.0f), Vector2(0.0f, 1.0f) }, { Vector3(-1.0f, -1.0f, 0.0f), Vector2(0.0f, 0.0f) }, { Vector3(1.0f, 1.0f, 0.0f), Vector2(1.0f, 1.0f) }, { Vector3(1.0f, -1.0f, 0.0f), Vector2(1.0f, 0.0f) } }; plane->SetData(BufferUsage::StaticDraw, vertices, 4); /* Initialize sphere used for point light rendering. */ sphere = new Mesh(""Point light render spherer""); ShapeCreator::MakeSphere(sphere, 16, 16, 1.0f); sphere->Finalize(game->GetGraphics()->GetWindow()); /* Initialize the default material. */ defMaterial = MaterialBP::CreateNoInfo(game->GetLoader()); } void Plutonium::DeferredRendererBP::InitGsPass(void) { gspass.shdr = new Shader(STATIC_GPASS_VRTX_SHDR_SRC, GPASS_FRAG_SHDR_SRC); gspass.matProj = gspass.shdr->GetUniform(""Projection""); gspass.matview = gspass.shdr->GetUniform(""View""); gspass.matMdl = gspass.shdr->GetUniform(""Model""); gspass.specExp = gspass.shdr->GetUniform(""Object.SpecularExponent""); gspass.mapAmbi = gspass.shdr->GetUniform(""Object.Ambient""); gspass.mapDiff = gspass.shdr->GetUniform(""Object.Diffuse""); gspass.mapSpec = gspass.shdr->GetUniform(""Object.Specular""); gspass.mapAlpha = gspass.shdr->GetUniform(""Object.Opacity""); gspass.mapBump = gspass.shdr->GetUniform(""Object.Normal""); gspass.pos = gspass.shdr->GetAttribute(""Position""); gspass.norm = gspass.shdr->GetAttribute(""Normal""); gspass.tan = gspass.shdr->GetAttribute(""Tangent""); gspass.uv = gspass.shdr->GetAttribute(""Uv""); } void Plutonium::DeferredRendererBP::InitGdPass(void) { gdpass.shdr = new Shader(ANIMATED_GPASS_VRTX_SHDR_SRC, GPASS_FRAG_SHDR_SRC); gdpass.matProj = gdpass.shdr->GetUniform(""Projection""); gdpass.matView = gdpass.shdr->GetUniform(""View""); gdpass.matMdl = gdpass.shdr->GetUniform(""Model""); gdpass.amnt = gdpass.shdr->GetUniform(""Blending""); gdpass.specExp = gdpass.shdr->GetUniform(""Object.SpecularExponent""); gdpass.mapAmbi = gdpass.shdr->GetUniform(""Object.Ambient""); gdpass.mapDiff = gdpass.shdr->GetUniform(""Object.Diffuse""); gdpass.mapSpec = gdpass.shdr->GetUniform(""Object.Specular""); gdpass.mapAlpha = gdpass.shdr->GetUniform(""Object.Opacity""); gdpass.mapBump = gdpass.shdr->GetUniform(""Object.Normal""); gdpass.pos = gdpass.shdr->GetAttribute(""Position1""); gdpass.norm = gdpass.shdr->GetAttribute(""Normal1""); gdpass.tan = gdpass.shdr->GetAttribute(""Tangent1""); gdpass.pos2 = gdpass.shdr->GetAttribute(""Position2""); gdpass.norm2 = gdpass.shdr->GetAttribute(""Normal2""); gdpass.tan2 = gdpass.shdr->GetAttribute(""Tangent2""); gdpass.uv = gdpass.shdr->GetAttribute(""Uv""); } void Plutonium::DeferredRendererBP::InitDsPass(void) { dspass.shdr = new Shader(DSPASS_VRTX_SHDR_SRC, DSPASS_FRAG_SHDR_SRC); dspass.matLs = dspass.shdr->GetUniform(""CascadeSpace""); dspass.matMdl = dspass.shdr->GetUniform(""Model""); dspass.mapAlpha = dspass.shdr->GetUniform(""Opacity""); dspass.mapDiff = dspass.shdr->GetUniform(""Diffuse""); dspass.amnt = dspass.shdr->GetUniform(""Blending""); dspass.pos1 = dspass.shdr->GetAttribute(""Position1""); dspass.pos2 = dspass.shdr->GetAttribute(""Position2""); dspass.uv = dspass.shdr->GetAttribute(""Uv""); } void Plutonium::DeferredRendererBP::InitDPass(bool pcf) { dpass.shdr = new Shader(PASS_VRTX_SHDR_SRC, pcf ? DPASS_PCF_FRAG_SHDR_SRC : DPASS_FRAG_SHDR_SRC); dpass.normSpec = dpass.shdr->GetUniform(""Geometry.NormalSpecular""); dpass.posSpec = dpass.shdr->GetUniform(""Geometry.PositionSpecular""); dpass.ambi = dpass.shdr->GetUniform(""Geometry.Ambient""); dpass.diff = dpass.shdr->GetUniform(""Geometry.Diffuse""); dpass.dir = dpass.shdr->GetUniform(""Light.Direction""); dpass.clrAmbi = dpass.shdr->GetUniform(""Light.Ambient""); dpass.clrDiff = dpass.shdr->GetUniform(""Light.Diffuse""); dpass.clrSpec = dpass.shdr->GetUniform(""Light.Specular""); dpass.matCasc1 = dpass.shdr->GetUniform(""Light.CascadeSpace1""); dpass.matCasc2 = dpass.shdr->GetUniform(""Light.CascadeSpace2""); dpass.matCasc3 = dpass.shdr->GetUniform(""Light.CascadeSpace3""); dpass.end1 = dpass.shdr->GetUniform(""Light.CascadeEnd1""); dpass.end2 = dpass.shdr->GetUniform(""Light.CascadeEnd2""); dpass.end3 = dpass.shdr->GetUniform(""Light.CascadeEnd3""); dpass.shdw1 = dpass.shdr->GetUniform(""Light.Cascade1""); dpass.shdw2 = dpass.shdr->GetUniform(""Light.Cascade2""); dpass.shdw3 = dpass.shdr->GetUniform(""Light.Cascade3""); dpass.matView = dpass.shdr->GetUniform(""View""); dpass.multCasc = dpass.shdr->GetUniform(""CascadeIntensity""); dpass.camPos = dpass.shdr->GetUniform(""ViewPosition""); dpass.pos = dpass.shdr->GetAttribute(""Position""); dpass.uv = dpass.shdr->GetAttribute(""ScreenCoordinate""); } void Plutonium::DeferredRendererBP::InitPPass(void) { ppass.shdr = new Shader(PPASS_VRTX_SHDR_SRC, PPASS_FRAG_SHDR_SRC); ppass.matProj = ppass.shdr->GetUniform(""Projection""); ppass.matView = ppass.shdr->GetUniform(""View""); ppass.matMdl = ppass.shdr->GetUniform(""Model""); ppass.screen = ppass.shdr->GetUniform(""ScreenSize""); ppass.normSpec = ppass.shdr->GetUniform(""Geometry.NormalSpecular""); ppass.posSpec = ppass.shdr->GetUniform(""Geometry.PositionSpecular""); ppass.ambi = ppass.shdr->GetUniform(""Geometry.Ambient""); ppass.diff = ppass.shdr->GetUniform(""Geometry.Diffuse""); ppass.lpos = ppass.shdr->GetUniform(""Light.Position""); ppass.c = ppass.shdr->GetUniform(""Light.Constant""); ppass.l = ppass.shdr->GetUniform(""Light.Linear""); ppass.q = ppass.shdr->GetUniform(""Light.Quadratic""); ppass.clrAmbi = ppass.shdr->GetUniform(""Light.Ambient""); ppass.clrDiff = ppass.shdr->GetUniform(""Light.Diffuse""); ppass.clrSpec = ppass.shdr->GetUniform(""Light.Specular""); ppass.camPos = ppass.shdr->GetUniform(""ViewPosition""); ppass.pos = ppass.shdr->GetAttribute(""Position""); } void Plutonium::DeferredRendererBP::InitFPass(bool fxaa) { fpass.shdr = new Shader(PASS_VRTX_SHDR_SRC, fxaa ? FPASS_FXAA_FRAG_SHDR_SRC : FPASS_FRAG_SHDR_SRC); fpass.screen = fpass.shdr->GetUniform(""HdrBuffer""); fpass.gamma = fpass.shdr->GetUniform(""GammaCorrection""); fpass.exposure = fpass.shdr->GetUniform(""Exposure""); fpass.texelStep = fxaa ? fpass.shdr->GetUniform(""TexelStep"") : nullptr; fpass.pos = fpass.shdr->GetAttribute(""Position""); fpass.uv = fpass.shdr->GetAttribute(""ScreenCoordinate""); } void Plutonium::DeferredRendererBP::InitWire(void) { wire.shdr = new Shader(WIRE_VRTX_SHDR_SRC, WIRE_GEOM_SHDR_SRC, WIRE_FRAG_SHDR_SRC); wire.matProj = wire.shdr->GetUniform(""Projection""); wire.matView = wire.shdr->GetUniform(""View""); wire.matMdl = wire.shdr->GetUniform(""Model""); wire.clr = wire.shdr->GetUniform(""Color""); wire.mapDiff = wire.shdr->GetUniform(""Diffuse""); wire.amnt = wire.shdr->GetUniform(""Blending""); wire.pos = wire.shdr->GetAttribute(""Position""); wire.pos2 = wire.shdr->GetAttribute(""Position2""); wire.uv = wire.shdr->GetAttribute(""Uv""); } void Plutonium::DeferredRendererBP::InitWNormal(void) { wn.shdr = new Shader(PASS_VRTX_SHDR_SRC, WN_FRAG_SHDR_SRC); wn.normSpec = wn.shdr->GetUniform(""NormalSpecular""); wn.pos = wn.shdr->GetAttribute(""Position""); wn.uv = wn.shdr->GetAttribute(""ScreenCoordinate""); } void Plutonium::DeferredRendererBP::InitAlbedo(void) { al.shdr = new Shader(PASS_VRTX_SHDR_SRC, AL_FRAG_SHDR_SRC); al.diff = al.shdr->GetUniform(""Diffuse""); al.pos = al.shdr->GetAttribute(""Position""); al.uv = al.shdr->GetAttribute(""ScreenCoordinate""); } #pragma endregion void Plutonium::DeferredRendererBP::RenderNormal(const Camera * cam) { /* Add directional lights to the scene. */ for (size_t i = 0; i < queuedDLights.size(); i++) { const DirectionalLight *light = queuedDLights.at(i); std::vector ends; Matrix spaces[CASCADE_CNT]; /* Render shadow map. */ BeginDirShadowPass(); RenderDirLightShadow(cam, light, spaces, &ends); dspass.shdr->End(); /* Render lighting. */ BeginDirLightPass(cam->GetPosition()); RenderDirLight(cam->GetView(), light, spaces, &ends); dpass.shdr->End(); } /* Add point lights to the scene. */ BeginPntLightPass(cam->GetProjection(), cam->GetView(), cam->GetPosition()); for (size_t i = 0; i < queuePLights.size(); i++) { const PointLight *light = queuePLights.at(i); /* Only render the light if it's light can be viewed. */ if (cam->GetClip()->IntersectionSphere(light->Position, light->GetRadius())) { RenderPntLight(light); } } ppass.shdr->End(); } void Plutonium::DeferredRendererBP::RenderWireframe(const Matrix & projection, const Matrix & view) { /* Set global uniforms and initialize mix amounf to zero for static model pass. */ wire.shdr->Begin(); wire.matProj->Set(projection); wire.matView->Set(view); wire.amnt->Set(0.0f); /* Render static models. */ for (size_t i = 0; i < queuedModels.size(); i++) { /* Set model matrix. */ const StaticObject *model = queuedModels.at(i); wire.matMdl->Set(model->GetWorld()); /* Render all underlying shapes. */ const std::vector *shapes = model->GetModel()->GetShapes(); for (size_t j = 0; j < shapes->size(); j++) { MaterialBP *material = shapes->at(j).Material; if (material->Visible) { /* Set color to the designated debug color on debug mode or red on release mode. */ #if defined (DEBUG) wire.clr->Set(shapes->at(j).Material->Debug); #else wire.clr->Set(Color::Red()); #endif wire.mapDiff->Set(material->Diffuse); /* Set first and second position to the same mesh. */ Buffer *mesh = shapes->at(j).Mesh->GetVertexBuffer(); mesh->Bind(); wire.pos->Initialize(false, sizeof(VertexFormat), offset_ptr(VertexFormat, Position)); wire.pos2->Initialize(false, sizeof(VertexFormat), offset_ptr(VertexFormat, Position)); wire.uv->Initialize(false, sizeof(VertexFormat), offset_ptr(VertexFormat, Texture)); /* Render shape. */ glDrawArrays(GL_TRIANGLES, 0, static_cast(mesh->GetElementCount())); } } } /* Render dynamic models. */ for (size_t i = 0; i < queuedAnimations.size(); i++) { /* Set model matrix and mix amount. */ const DynamicObject *model = queuedAnimations.at(i); wire.matMdl->Set(model->GetWorld()); wire.amnt->Set(model->GetMixAmount()); /* Set color to the designated debug color on debug mode or yellow on release mode. */ #if defined (DEBUG) wire.clr->Set(model->GetModel()->GetMaterial()->Debug); #else wire.clr->Set(Color::Yellow()); #endif wire.mapDiff->Set(model->GetModel()->GetMaterial()->Diffuse); /* Set first position to the current frame. */ Buffer *mesh1 = model->GetCurrentFrame()->GetVertexBuffer(); mesh1->Bind(); wire.pos->Initialize(false, sizeof(VertexFormat), offset_ptr(VertexFormat, Position)); /* Set second position to the next frame. */ Buffer *mesh2 = model->GetNextFrame()->GetVertexBuffer(); mesh2->Bind(); wire.pos2->Initialize(false, sizeof(VertexFormat), offset_ptr(VertexFormat, Position)); wire.uv->Initialize(false, sizeof(VertexFormat), offset_ptr(VertexFormat, Texture)); /* Render shape. */ glDrawArrays(GL_TRIANGLES, 0, static_cast(mesh1->GetElementCount())); } wire.shdr->End(); } void Plutonium::DeferredRendererBP::RenderWorldNormals(void) { /* Setup shader. */ wn.shdr->Begin(); wn.normSpec->Set(normalSpec); /* Set viewing plane. */ plane->Bind(); wn.pos->Initialize(false, sizeof(PlaneVertexFormat), offset_ptr(PlaneVertexFormat, Position)); wn.uv->Initialize(false, sizeof(PlaneVertexFormat), offset_ptr(PlaneVertexFormat, Uv)); /* Render and end shader. */ glDrawArrays(GL_TRIANGLE_STRIP, 0, static_cast(plane->GetElementCount())); wn.shdr->End(); } void Plutonium::DeferredRendererBP::RenderAlbedo(void) { /* Setup shader. */ al.shdr->Begin(); al.diff->Set(diffuse); /* Set viewing plane. */ plane->Bind(); al.pos->Initialize(false, sizeof(PlaneVertexFormat), offset_ptr(PlaneVertexFormat, Position)); al.uv->Initialize(false, sizeof(PlaneVertexFormat), offset_ptr(PlaneVertexFormat, Uv)); /* Render and end shader. */ glDrawArrays(GL_TRIANGLE_STRIP, 0, static_cast(plane->GetElementCount())); al.shdr->End(); } void Plutonium::DeferredRendererBP::BeginGsPass(const Matrix & proj, const Matrix & view) { /* Set geometry pass global parameters. */ gspass.shdr->Begin(); gspass.matProj->Set(proj); gspass.matview->Set(view); } void Plutonium::DeferredRendererBP::BeginGdPass(const Matrix & proj, const Matrix & view) { /* Set geometry pass global parameters. */ gdpass.shdr->Begin(); gdpass.matProj->Set(proj); gdpass.matView->Set(view); } void Plutonium::DeferredRendererBP::BeginDirShadowPass(void) { GraphicsAdapter *device = game->GetGraphics(); /* Setup OpenGL and shader. */ device->SetRenderTarget(dshdFbo); device->SetDepthOuput(true); dspass.shdr->Begin(); } void Plutonium::DeferredRendererBP::BeginDirLightPass(Vector3 camPos) { GraphicsAdapter *device = game->GetGraphics(); /* Setup OpenGL and shader. */ device->SetRenderTarget(hdrFbo); device->SetColorBlendFunction(BlendState::Additive); device->SetBlend(BlendType::One, BlendType::One); device->SetDepthOuput(false); dpass.shdr->Begin(); /* Setup global uniforms. */ dpass.camPos->Set(camPos); dpass.normSpec->Set(normalSpec); dpass.posSpec->Set(posSpec); dpass.ambi->Set(ambient); dpass.diff->Set(diffuse); dpass.multCasc->Set(DisplayType != RenderType::Shadows ? 0.0f : 0.75f); /* Setup mesh. */ plane->Bind(); dpass.pos->Initialize(false, sizeof(PlaneVertexFormat), offset_ptr(PlaneVertexFormat, Position)); dpass.uv->Initialize(false, sizeof(PlaneVertexFormat), offset_ptr(PlaneVertexFormat, Uv)); } void Plutonium::DeferredRendererBP::BeginPntLightPass(const Matrix & proj, const Matrix & view, Vector3 camPos) { ppass.shdr->Begin(); /* Setup global uniforms. */ ppass.matProj->Set(proj); ppass.matView->Set(view); ppass.camPos->Set(camPos); ppass.screen->Set(game->GetGraphics()->GetWindow()->GetClientBounds().Size); ppass.normSpec->Set(normalSpec); ppass.posSpec->Set(posSpec); ppass.ambi->Set(ambient); ppass.diff->Set(diffuse); /* Setup mesh. */ sphere->GetVertexBuffer()->Bind(); ppass.pos->Initialize(false, sizeof(VertexFormat), offset_ptr(VertexFormat, Position)); } void Plutonium::DeferredRendererBP::SetCascadeMax(const Camera * cam, float max[CASCADE_CNT]) { for (size_t i = 1; i < CASCADE_CNT + 1; i++) { /* Get current amount value for logarithmic and linear scale. */ float a = static_cast(i) / static_cast(CASCADE_CNT); /* Get current logarithmic and linear(uniform) value. */ float log = cam->GetNear() * powf(cam->GetFar(), a); float uni = lerp(cam->GetNear(), cam->GetFar(), a); /* Mix them using the lambda as the result. */ max[i - 1] = CascadeLambda * log + (1.0f - CascadeLambda) * uni; } } float Plutonium::DeferredRendererBP::GetFurthestZFromCam(const Camera * cam) { Box scene; /* Add all static models to the scene bounding box if they cast a shadow. */ for (size_t i = 0; i < queuedModels.size(); i++) { const StaticObject *cur = queuedModels.at(i); if (cur->CastsShadows) scene = Box::Merge(scene, cur->GetBoundingBox()); } /* Add all animated models to the scene bounding box if they cast a shadow. */ for (size_t i = 0; i < queuedAnimations.size(); i++) { const DynamicObject *cur = queuedAnimations.at(i); if (cur->CastsShadows) scene = Box::Merge(scene, cur->GetBoundingBox()); } /* Calculate the furthest z coordinate in view space. */ float furthest = cam->GetNear(); for (size_t i = 0; i < 8; i++) { Vector3 corner = scene[i]; float z = -(cam->GetView() * corner).Z; furthest = max(furthest, z); } /* Return the minimum of the cull distance and the bounding box max to ensure we don't render behind the frustum. */ return min(furthest, cam->GetFar()); } void Plutonium::DeferredRendererBP::SetCascadeEnds(const Camera * cam, std::vector* ends) { float furthest = GetFurthestZFromCam(cam); float max[CASCADE_CNT]; SetCascadeMax(cam, max); /* Calculate how many cascades are actually needed (might save a shadow map render). */ size_t cascadeCnt = 1; for (size_t i = 0; i < CASCADE_CNT - 1; i++) { if (furthest >= max[i]) ++cascadeCnt; } /* Calculate the needed ends of the frustum. */ ends->push_back(cam->GetNear()); for (size_t i = 1; i < cascadeCnt; i++) { float a = static_cast(i) / static_cast(cascadeCnt); float log = cam->GetNear() * powf(furthest / cam->GetNear(), a); float uni = lerp(cam->GetNear(), furthest, a); ends->push_back(CascadeLambda * log + (1.0f - CascadeLambda) * uni); } ends->push_back(furthest); } Plutonium::Box Plutonium::DeferredRendererBP::CalcOrthoBox(const Camera * cam, float near, float far) { /* Gets the camera tangent of the camera fov and the aspect ratio. */ float tanFov = tanf(cam->GetFov() * 0.5f); float aspr = game->GetGraphics()->GetWindow()->AspectRatio(); /* Calculate the height and width of the near and far plane. */ float nh = tanFov * near; float nw = nh * aspr; float fh = tanFov * far; float fw = fh * aspr; /* Get the camera coordinate system. */ Vector3 right = cam->GetOrientation().GetRight(); Vector3 up = cam->GetOrientation().GetUp(); Vector3 back = cam->GetOrientation().GetForward(); /* Get the center of the near and far plane. */ Vector3 nc = cam->GetPosition() + back * near; Vector3 fc = cam->GetPosition() + back * far; /* Calculate the orthographic box corners. */ Box result; result = Box::Merge(result, nc - right * nw - up * nh); result = Box::Merge(result, nc - right * nw + up * nh); result = Box::Merge(result, nc + right * nw - up * nh); result = Box::Merge(result, nc + right * nw + up * nh); result = Box::Merge(result, fc - right * fw - up * fh); result = Box::Merge(result, fc - right * fw + up * fh); result = Box::Merge(result, fc + right * fw - up * fh); result = Box::Merge(result, fc + right * fw + up * fh); return result; } Plutonium::Matrix Plutonium::DeferredRendererBP::CalcDirLightVP(const Camera * cam, const Box & frustum, const DirectionalLight * light) { /* Create view matrix. */ Vector3 pos = frustum.GetCenter(); Matrix view = Matrix::CreateLookAt(pos, pos + light->GetDirection() * LightOffset, light->GetUp()); /* Create orthographic projection matrix. */ float d = max(frustum.Size.X, frustum.Size.Z); Matrix proj = Matrix::CreateOrtho(d, d, cam->GetNear(), cam->GetFar()); /* Return light space matrix. */ return proj * view; } void Plutonium::DeferredRendererBP::RenderModel(const Camera * cam, const StaticObject * model, const MaterialBP * overrideMaterial) { /* Only render the model if it's visible by the camera. */ Box bb = model->GetBoundingBox(); if (cam->GetClip()->IntersectionBox(bb.Position, bb.Size)) { /* Set model matrix. */ gspass.matMdl->Set(model->GetWorld()); /* Loops through all shapes in the model. */ const std::vector *shapes = model->GetModel()->GetShapes(); for (size_t i = 0; i < shapes->size(); i++) { /* Render the current material if it's visible. */ const MaterialBP *material = shapes->at(i).Material; if (material->Visible) { /* Only render the mesh if it's inside of the camera view. */ Mesh *mesh = shapes->at(i).Mesh; bb = mesh->GetBoundingBox() * model->GetWorld(); if (cam->GetClip()->IntersectionBox(bb.Position, bb.Size)) { Buffer *buffer = mesh->GetVertexBuffer(); /* Set material attributes. */ if (!overrideMaterial) { gspass.mapAmbi->Set(material->Ambient); gspass.mapDiff->Set(material->Diffuse); gspass.mapSpec->Set(material->Specular); gspass.specExp->Set(material->SpecularExponent); } else { gspass.mapAmbi->Set(overrideMaterial->Ambient); gspass.mapDiff->Set(overrideMaterial->Diffuse); gspass.mapSpec->Set(overrideMaterial->Specular); gspass.specExp->Set(overrideMaterial->SpecularExponent); } gspass.mapAlpha->Set(material->Opacity); gspass.mapBump->Set(material->Normal); /* Set mesh attributes. */ buffer->Bind(); gspass.pos->Initialize(false, sizeof(VertexFormat), offset_ptr(VertexFormat, Position)); gspass.norm->Initialize(false, sizeof(VertexFormat), offset_ptr(VertexFormat, Normal)); gspass.tan->Initialize(false, sizeof(VertexFormat), offset_ptr(VertexFormat, Tangent)); gspass.uv->Initialize(false, sizeof(VertexFormat), offset_ptr(VertexFormat, Texture)); /* Render the shape to the GBuffer. */ glDrawArrays(GL_TRIANGLES, 0, static_cast(buffer->GetElementCount())); } } } } } void Plutonium::DeferredRendererBP::RenderModel(const Camera * cam, const DynamicObject * model, const MaterialBP * overrideMaterial) { /* Only render the model if it's visible by the camera. */ Box bb = model->GetBoundingBox(); if (cam->GetClip()->IntersectionBox(bb.Position, bb.Size)) { /* Set model matrix and inter frame mix amount. */ gdpass.matMdl->Set(model->GetWorld()); gdpass.amnt->Set(model->GetMixAmount()); const MaterialBP *material = model->GetModel()->GetMaterial(); if (material->Visible) { Buffer *curMesh = model->GetCurrentFrame()->GetVertexBuffer(); Buffer *nextMesh = model->GetNextFrame()->GetVertexBuffer(); /* Set material attributes. */ if (!overrideMaterial) { gdpass.mapAmbi->Set(material->Ambient); gdpass.mapDiff->Set(material->Diffuse); gdpass.mapSpec->Set(material->Specular); gdpass.specExp->Set(material->SpecularExponent); } else { gdpass.mapAmbi->Set(overrideMaterial->Ambient); gdpass.mapDiff->Set(overrideMaterial->Diffuse); gdpass.mapSpec->Set(overrideMaterial->Specular); gdpass.specExp->Set(overrideMaterial->SpecularExponent); } gdpass.mapAlpha->Set(material->Opacity); gdpass.mapBump->Set(material->Normal); /* Set first mesh attributes. */ curMesh->Bind(); gdpass.pos->Initialize(false, sizeof(VertexFormat), offset_ptr(VertexFormat, Position)); gdpass.norm->Initialize(false, sizeof(VertexFormat), offset_ptr(VertexFormat, Normal)); gdpass.tan->Initialize(false, sizeof(VertexFormat), offset_ptr(VertexFormat, Tangent)); gdpass.uv->Initialize(false, sizeof(VertexFormat), offset_ptr(VertexFormat, Texture)); /* Set second mesh attributes. */ nextMesh->Bind(); gdpass.pos2->Initialize(false, sizeof(VertexFormat), offset_ptr(VertexFormat, Position)); gdpass.norm2->Initialize(false, sizeof(VertexFormat), offset_ptr(VertexFormat, Normal)); gdpass.tan2->Initialize(false, sizeof(VertexFormat), offset_ptr(VertexFormat, Tangent)); /* Render the shape to the GBuffer. */ glDrawArrays(GL_TRIANGLES, 0, static_cast(curMesh->GetElementCount())); } } } #include ""Core\\String.h"" void Plutonium::DeferredRendererBP::RenderDirLightShadow(const Camera * cam, const DirectionalLight * light, Matrix * spaces, std::vector * ends) { SetCascadeEnds(cam, ends); /* Loop through cascades. */ for (size_t i = 0, j = 1; j < ends->size(); i++, j++) { spaces[i] = CalcDirLightVP(cam, CalcOrthoBox(cam, ends->at(i), ends->at(j)), light); /* Set current cascade as the writing target and clear it. */ dshdFbo->BindForWriting(cascades[i]); game->GetGraphics()->Clear(ClearTarget::Depth); /* Only render to the depth buffer if the light is allowed to create shadows. */ if (light->CreatesShadows) { dspass.matLs->Set(spaces[i]); dspass.amnt->Set(0.0f); /* Render all static models to depth map. */ for (size_t k = 0; k < queuedModels.size(); k++) { /* Only render the model if it is allowed to cast a shadow. */ const StaticObject *model = queuedModels.at(k); if (!model->CastsShadows) continue; /* Set model matrix. */ dspass.matMdl->Set(model->GetWorld()); /* Loop through all shapes in the mode. */ const std::vector *shapes = model->GetModel()->GetShapes(); for (size_t l = 0; l < shapes->size(); l++) { const MaterialBP *material = shapes->at(l).Material; if (material->Visible) { Buffer *buffer = shapes->at(l).Mesh->GetVertexBuffer(); /* Set material attributes. */ dspass.mapDiff->Set(material->Diffuse); dspass.mapAlpha->Set(material->Opacity); /* Set mesh attributes. */ buffer->Bind(); dspass.pos1->Initialize(false, sizeof(VertexFormat), offset_ptr(VertexFormat, Position)); dspass.pos2->Initialize(false, sizeof(VertexFormat), offset_ptr(VertexFormat, Position)); dspass.uv->Initialize(false, sizeof(VertexFormat), offset_ptr(VertexFormat, Texture)); /* Render the shape to the shadow depth buffer. */ glDrawArrays(GL_TRIANGLES, 0, static_cast(buffer->GetElementCount())); } } } /* Render all dynamic models to depth map. */ for (size_t k = 0; k < queuedAnimations.size(); k++) { /* Only render the model if it is allowed to cast a shadow. */ const DynamicObject *model = queuedAnimations.at(k); if (!model->CastsShadows) continue; /* Set model matrix. */ dspass.matMdl->Set(model->GetWorld()); dspass.amnt->Set(model->GetMixAmount()); const MaterialBP *material = model->GetModel()->GetMaterial(); if (material->Visible) { Buffer *cur = model->GetCurrentFrame()->GetVertexBuffer(); Buffer *next = model->GetNextFrame()->GetVertexBuffer(); /* Set material attributes. */ dspass.mapDiff->Set(material->Diffuse); dspass.mapAlpha->Set(material->Opacity); /* Set mesh attributes. */ cur->Bind(); dspass.pos1->Initialize(false, sizeof(VertexFormat), offset_ptr(VertexFormat, Position)); dspass.uv->Initialize(false, sizeof(VertexFormat), offset_ptr(VertexFormat, Texture)); next->Bind(); dspass.pos2->Initialize(false, sizeof(VertexFormat), offset_ptr(VertexFormat, Position)); /* Render the shape to the shadow depth buffer. */ glDrawArrays(GL_TRIANGLES, 0, static_cast(cur->GetElementCount())); } } } } } void Plutonium::DeferredRendererBP::RenderDirLight(const Matrix & view, const DirectionalLight * light, Matrix * spaces, std::vector * ends) { dpass.dir->Set(-normalize(light->GetDirection())); dpass.clrAmbi->Set(light->Ambient); dpass.clrDiff->Set(light->Diffuse); dpass.clrSpec->Set(light->Specular); dpass.matView->Set(view); dpass.matCasc1->Set(spaces[0]); dpass.matCasc2->Set(spaces[1]); dpass.matCasc3->Set(spaces[2]); dpass.end1->Set(ends->at(1)); dpass.end2->Set(ends->size() > 2 ? ends->at(2) : maxv()); dpass.end3->Set(ends->size() > 3 ? ends->at(3) : maxv()); dpass.shdw1->Set(cascades[0]); dpass.shdw2->Set(cascades[1]); dpass.shdw3->Set(cascades[2]); glDrawArrays(GL_TRIANGLE_STRIP, 0, static_cast(plane->GetElementCount())); } void Plutonium::DeferredRendererBP::RenderPntLight(const PointLight * light) { ppass.matMdl->Set(Matrix::CreateTranslation(light->Position) * Matrix::CreateScalar(light->GetRadius())); ppass.lpos->Set(light->Position); ppass.c->Set(light->Constant); ppass.l->Set(light->Linear); ppass.q->Set(light->Quadratic); ppass.clrAmbi->Set(light->Ambient); ppass.clrDiff->Set(light->Diffuse); ppass.clrSpec->Set(light->Specular); glDrawArrays(GL_TRIANGLES, 0, static_cast(sphere->GetVertexBuffer()->GetElementCount())); } void Plutonium::DeferredRendererBP::FixForMonitor(void) { /* Start shader. */ fpass.shdr->Begin(); /* Set uniforms. */ fpass.screen->Set(screen); fpass.gamma->Set(game->GetGraphics()->GetWindow()->GetGraphicsDevice().GammaCorrection); if (fpass.texelStep) fpass.texelStep->Set(Vector2::One() / game->GetGraphics()->GetWindow()->GetClientBounds().Size); fpass.exposure->Set(Exposure); /* Setup screen quad (use dpass quad plane). */ plane->Bind(); fpass.pos->Initialize(false, sizeof(PlaneVertexFormat), offset_ptr(PlaneVertexFormat, Position)); fpass.uv->Initialize(false, sizeof(PlaneVertexFormat), offset_ptr(PlaneVertexFormat, Uv)); /* Fix for monitor for each fragment and end shader. */ glDrawArrays(GL_TRIANGLE_STRIP, 0, static_cast(plane->GetElementCount())); fpass.shdr->End(); }",16310,True,2558.490341118562,median "/* * Copyright 2019 WebAssembly Community Group participants * * 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. */ // // Asyncify: async/await style code transformation, that allows pausing // and resuming. This lets a language support synchronous operations in // an async manner, for example, you can do a blocking wait, and that will // be turned into code that unwinds the stack at the ""blocking"" operation, // then is able to rewind it back up when the actual async operation // comples, the so the code appears to have been running synchronously // all the while. Use cases for this include coroutines, python generators, // etc. // // The approach here is a third-generation design after Emscripten's original // Asyncify and then Emterpreter-Async approaches: // // * Old Asyncify rewrote control flow in LLVM IR. A problem is that this // needs to save all SSA registers as part of the local state, which can be // very costly. A further increase can happen because of phis that are // added because of control flow transformations. As a result we saw // pathological cases where the code size increase was unacceptable. // * Emterpreter-Async avoids any risk of code size increase by running it // in a little bytecode VM, which also makes pausing/resuming trivial. // Speed is the main downside here; however, the approach did prove that by // *selectively* emterpretifying only certain code, many projects can run // at full speed - often just the ""main loop"" must be emterpreted, while // high-speed code that it calls, and in which cannot be an async operation, // remain at full speed. // // New Asyncify's design learns from both of those: // // * The code rewrite is done in Binaryen, that is, at the wasm level. At // this level we will only need to save wasm locals, which is a much smaller // number than LLVM's SSA registers. // * We aim for low but non-zero overhead. Low overhead is very important // for obvious reasons, while Emterpreter-Async proved it is tolerable to // have *some* overhead, if the transform can be applied selectively. // // The specific transform implemented here is nicknamed ""Bysyncify"" (as it is // in BinarYen, and ""B"" comes after ""A""). It is simpler than old Asyncify but // has low overhead when properly optimized. Old Asyncify worked at the CFG // level and added branches there; new Asyncify on the other hand works on the // structured control flow of wasm and simply ""skips over"" code when rewinding // the stack, and jumps out when unwinding. The transformed code looks // conceptually like this: // // void foo(int x) { // // new prelude // if (rewinding) { // loadLocals(); // } // // main body starts here // if (!rewinding) { // // some code we must skip while rewinding // x = x + 1; // x = x / 2; // } // // If rewinding, do this call only if it is the right one. // if (!rewinding or nextCall == 0) { // bar(x); // if (unwinding) { // noteUnWound(0); // saveLocals(); // return; // } // } // if (!rewinding) { // // more code we must skip while rewinding // while (x & 7) { // x = x + 1; // } // } // [..] // // The general idea is that while rewinding we just ""keep going forward"", // skipping code we should not run. That is, instead of jumping directly // to the right place, we have ifs that skip along instead. The ifs for // rewinding and unwinding should be well-predicted, so the overhead should // not be very high. However, we do need to reach the right location via // such skipping, which means that in a very large function the rewind // takes some extra time. On the other hand, though, code that cannot // unwind or rewind (like that loop near the end) can run at full speed. // Overall, this should allow good performance with small overhead that is // mostly noticed at rewind time. // // After this pass is run a new i32 global ""__asyncify_state"" is added, which // has the following values: // // 0: normal execution // 1: unwinding the stack // 2: rewinding the stack // // There is also ""__asyncify_data"" which when rewinding and unwinding // contains a pointer to a data structure with the info needed to rewind // and unwind: // // { // offsets // i32 - current asyncify stack location // 0 // i32 - asyncify stack end // 4 // } // // The asyncify stack is a representation of the call frame, as a list of // indexes of calls. In the example above, we saw index ""0"" for calling ""bar"" // from ""foo"". When unwinding, the indexes are added to the stack; when // rewinding, they are popped off; the current asyncify stack location is // undated while doing both operations. The asyncify stack is also used to // save locals. Note that the stack end location is provided, which is for // error detection. // // Note: all pointers are assumed to be 4-byte aligned. // // When you start an unwinding operation, you must set the initial fields // of the data structure, that is, set the current stack location to the // proper place, and the end to the proper end based on how much memory // you reserved. Note that asyncify will grow the stack up. // // The pass will also create five functions that let you control unwinding // and rewinding: // // * asyncify_start_unwind(data : i32): call this to start unwinding the // stack from the current location. ""data"" must point to a data // structure as described above (with fields containing valid data). // // * asyncify_stop_unwind(): call this to note that unwinding has // concluded. If no other code will run before you start to rewind, // this is not strictly necessary, however, if you swap between // coroutines, or even just want to run some normal code during a // ""sleep"", then you must call this at the proper time. Otherwise, // the code will think it is still unwinding when it should not be, // which means it will keep unwinding in a meaningless way. // // * asyncify_start_rewind(data : i32): call this to start rewinding the // stack vack up to the location stored in the provided data. This prepares // for the rewind; to start it, you must call the first function in the // call stack to be unwound. // // * asyncify_stop_rewind(): call this to note that rewinding has // concluded, and normal execution can resume. // // * asyncify_get_state(): call this to get the current value of the // internal ""__asyncify_state"" variable as described above. // It can be used to distinguish between unwinding/rewinding and normal // calls, so that you know when to start an asynchronous operation and // when to propagate results back. // // These four functions are exported so that you can call them from the // outside. If you want to manage things from inside the wasm, then you // couldn't have called them before they were created by this pass. To work // around that, you can create imports to asyncify.start_unwind, // asyncify.stop_unwind, asyncify.start_rewind, and asyncify.stop_rewind; // if those exist when this pass runs then it will turn those into direct // calls to the functions that it creates. Note that when doing everything // in wasm like this, Asyncify must not instrument your ""runtime"" support // code, that is, the code that initiates unwinds and rewinds and stops them. // If it did, the unwind would not stop until you left the wasm module // entirely, etc. Therefore we do not instrument a function if it has // a call to the four asyncify_* methods. Note that you may need to disable // inlining if that would cause code that does need to be instrumented // show up in that runtime code. // // To use this API, call asyncify_start_unwind when you want to. The call // stack will then be unwound, and so execution will resume in the JS or // other host environment on the outside that called into wasm. When you // return there after unwinding, call asyncify_stop_unwind. Then when // you want to rewind, call asyncify_start_rewind, and then call the same // initial function you called before, so that unwinding can begin. The // unwinding will reach the same function from which you started, since // we are recreating the call stack. At that point you should call // asyncify_stop_rewind and then execution can resume normally. // // Note that the asyncify_* API calls will verify that the data structure // is valid, checking if the current location is past the end. If so, they // will throw a wasm unreachable. No check is done during unwinding or // rewinding, to keep things fast - in principle, from when unwinding begins // and until it ends there should be no memory accesses aside from the // asyncify code itself (and likewise when rewinding), so there should be // no chance of memory corruption causing odd errors. However, the low // overhead of this approach does cause an error only to be shown when // unwinding/rewinding finishes, and not at the specific spot where the // stack end was exceeded. // // By default this pass is very careful: it assumes that any import and // any indirect call may start an unwind/rewind operation. If you know more // specific information you can inform asyncify about that, which can reduce // a great deal of overhead, as it can instrument less code. The relevant // options to wasm-opt etc. are: // // --pass-arg=asyncify-imports@module1.base1,module2.base2,module3.base3 // // Each module.base in that comma-separated list will be considered to // be an import that can unwind/rewind, and all others are assumed not to // (aside from the asyncify.* imports, which are always assumed to). // Each entry can end in a '*' in which case it is matched as a prefix. // // The list of imports can be a response file (which is convenient if it // is long, or you don't want to bother escaping it on the commandline // etc.), e.g. --pass-arg=asyncify-imports@@file.txt will load the // contents of file.txt (note the double ""@@"" - the first is the // separator for --pass-arg, and the second is the usual convention for // indicating a response file). // // --pass-arg=asyncify-ignore-imports // // Ignore all imports (except for bynsyncify.*), that is, assume none of // them can start an unwind/rewind. (This is effectively the same as // providing asyncify-imports with a list of non-existent imports.) // // --pass-arg=asyncify-ignore-indirect // // Ignore all indirect calls. This implies that you know an call stack // will never need to be unwound with an indirect call somewhere in it. // If that is true for your codebase, then this can be extremely useful // as otherwise it looks like any indirect call can go to a lot of places. // // --pass-arg=asyncify-asserts // // This enables extra asserts in the output, like checking if we in // an unwind/rewind in an invalid place (this can be helpful for manual // tweaking of the only-list / remove-list, see later). // // --pass-arg=asyncify-verbose // // Logs out instrumentation decisions to the console. This can help figure // out why a certain function was instrumented. // // For manual fine-tuning of the list of instrumented functions, there are lists // that you can set. These must be used carefully, as misuse can break your // application - for example, if a function is called that should be // instrumented but isn't because of these options, then bad things can happen. // Note that even if you test this locally then users running your code in // production may reach other code paths. Use these carefully! // // Each of the lists can be used with a response file (@filename, which is then // loaded from the file). You can also use '*' wildcard matching in the lists. // // --pass-arg=asyncify-removelist@name1,name2,name3 // // If the ""remove-list"" is provided, then the functions in it will be // *removed* from the list of instrumented functions. That is, they won't // be instrumented even if it looks like they need to be. This can be // useful if you know things the safe whole-program analysis doesn't, e.g. // that certain code paths will not be taken, where certain indirect calls // will go, etc. // // --pass-arg=asyncify-addlist@name1,name2,name3 // // If the ""add-list"" is provided, then the functions in the list will be // *added* to the list of instrumented functions, that is, they will be // instrumented even if otherwise we think they don't need to be. As by // default everything will be instrumented in the safest way possible, // this is only useful if you use ignore-indirect and use this to fix up // some indirect calls that *do* need to be instrumented, or if you will // do some later transform of the code that adds more call paths, etc. // // --pass-arg=asyncify-onlylist@name1,name2,name3 // // If the ""only-list"" is provided, then *only* the functions in the list // will be instrumented, and nothing else. // // Note that there are two types of instrumentation that happen for each // function: if foo() can be part of a pause/resume operation, then we need to // instrument code inside it to support pausing and resuming, but also, we need // callers of the function to instrument calls to it. Normally this is already // taken care of as the callers need to be instrumented as well anyhow. However, // the ignore-indirect option makes things more complicated, since we can't tell // where all the calls to foo() are - all we see are indirect calls that do not // refer to foo() by name. To make it possible for you to use the add-list or // only-list with ignore-indirect, those lists affect *both* kinds of // instrumentation. That is, if parent() calls foo() indirectly, and you add // parent() to the add-list, then the indirect calls in parent() will be // instrumented to support pausing/resuming, even if ignore-indirect is set. // Typically you don't need to think about this, and just add all the functions // that can be on the stack while pausing - what this means is that when you do // so, indirect calls will just work. (The cost is that an instrumented function // will check for pausing at all indirect calls, which may be unnecessary in // some cases; but this is an instrumented function anyhow, and indirect calls // are slower anyhow, so this simple model seems good enough - a more complex // model where you can specify ""instrument, but not indirect calls from me"" // would likely have little benefit.) // // TODO When wasm has GC, extending the live ranges of locals can keep things // alive unnecessarily. We may want to set locals to null at the end // of their original range. // #include ""cfg/liveness-traversal.h"" #include ""ir/effects.h"" #include ""ir/find_all.h"" #include ""ir/literal-utils.h"" #include ""ir/memory-utils.h"" #include ""ir/module-utils.h"" #include ""ir/utils.h"" #include ""pass.h"" #include ""support/file.h"" #include ""support/string.h"" #include ""wasm-builder.h"" #include ""wasm.h"" namespace wasm { namespace { static const Name ASYNCIFY_STATE = ""__asyncify_state""; static const Name ASYNCIFY_GET_STATE = ""asyncify_get_state""; static const Name ASYNCIFY_DATA = ""__asyncify_data""; static const Name ASYNCIFY_START_UNWIND = ""asyncify_start_unwind""; static const Name ASYNCIFY_STOP_UNWIND = ""asyncify_stop_unwind""; static const Name ASYNCIFY_START_REWIND = ""asyncify_start_rewind""; static const Name ASYNCIFY_STOP_REWIND = ""asyncify_stop_rewind""; static const Name ASYNCIFY_UNWIND = ""__asyncify_unwind""; static const Name ASYNCIFY = ""asyncify""; static const Name START_UNWIND = ""start_unwind""; static const Name STOP_UNWIND = ""stop_unwind""; static const Name START_REWIND = ""start_rewind""; static const Name STOP_REWIND = ""stop_rewind""; static const Name ASYNCIFY_GET_CALL_INDEX = ""__asyncify_get_call_index""; static const Name ASYNCIFY_CHECK_CALL_INDEX = ""__asyncify_check_call_index""; // TODO: having just normal/unwind_or_rewind would decrease code // size, but make debugging harder enum class State { Normal = 0, Unwinding = 1, Rewinding = 2 }; enum class DataOffset { BStackPos = 0, BStackEnd = 4 }; const auto STACK_ALIGN = 4; // A helper class for managing fake global names. Creates the globals and // provides mappings for using them. // Fake globals are used to stash and then use return values from calls. We need // to store them somewhere that is valid Binaryen IR, but also will be ignored // by the Asyncify instrumentation, so we don't want to use a local. What we do // is replace the local used to receive a call's result with a fake global.set // to stash it, then do a fake global.get to receive it afterwards. (We do it in // two steps so that if we are async, we only do the first and not the second, // i.e., we don't store to the target local if not running normally). class FakeGlobalHelper { Module& module; public: FakeGlobalHelper(Module& module) : module(module) { Builder builder(module); std::string prefix = ""asyncify_fake_call_global_""; for (auto type : collectTypes()) { auto global = prefix + Type(type).toString(); map[type] = global; rev[global] = type; module.addGlobal(builder.makeGlobal( global, type, LiteralUtils::makeZero(type, module), Builder::Mutable)); } } ~FakeGlobalHelper() { for (auto& pair : map) { auto name = pair.second; module.removeGlobal(name); } } Name getName(Type type) { return map.at(type); } Type getTypeOrNone(Name name) { auto iter = rev.find(name); if (iter != rev.end()) { return iter->second; } return Type::none; } private: std::map map; std::map rev; // Collect the types returned from all calls for which call support globals // may need to be generated. using Types = std::unordered_set; Types collectTypes() { ModuleUtils::ParallelFunctionAnalysis analysis( module, [&](Function* func, Types& types) { if (!func->body) { return; } struct TypeCollector : PostWalker { Types& types; TypeCollector(Types& types) : types(types) {} void visitCall(Call* curr) { if (curr->type.isConcrete()) { types.insert(curr->type); } } void visitCallIndirect(CallIndirect* curr) { if (curr->type.isConcrete()) { types.insert(curr->type); } } }; TypeCollector(types).walk(func->body); }); Types types; for (auto& pair : analysis.map) { Types& functionTypes = pair.second; for (auto t : functionTypes) { types.insert(t); } } return types; } }; class PatternMatcher { public: std::string designation; std::set names; std::set patterns; std::set patternsMatched; std::map unescaped; PatternMatcher(std::string designation, Module& module, const String::Split& list) : designation(designation) { // The lists contain human-readable strings. Turn them into the // internal escaped names for later comparisons for (auto& name : list) { auto escaped = WasmBinaryBuilder::escape(name); unescaped[escaped.str] = name; if (name.find('*') != std::string::npos) { patterns.insert(escaped.str); } else { auto* func = module.getFunctionOrNull(escaped); if (!func) { std::cerr << ""warning: Asyncify "" << designation << ""list contained a non-existing function name: "" << name << "" ("" << escaped << "")\\n""; } else if (func->imported()) { Fatal() << ""Asyncify "" << designation << ""list contained an imported function name (use the import "" ""list for imports): "" << name << '\\n'; } names.insert(escaped.str); } } } bool match(Name funcName) { if (names.count(funcName) > 0) { return true; } else { for (auto& pattern : patterns) { if (String::wildcardMatch(pattern, funcName.str)) { patternsMatched.insert(pattern); return true; } } } return false; } void checkPatternsMatches() { for (auto& pattern : patterns) { if (patternsMatched.count(pattern) == 0) { std::cerr << ""warning: Asyncify "" << designation << ""list contained a non-matching pattern: "" << unescaped[pattern] << "" ("" << pattern << "")\\n""; } } } }; // Analyze the entire module to see which calls may change the state, that // is, start an unwind or rewind), either in itself or in something called // by it. // Handles global module management, needed from the various parts of this // transformation. class ModuleAnalyzer { Module& module; bool canIndirectChangeState; struct Info : public ModuleUtils::CallGraphPropertyAnalysis::FunctionInfo { // The function name. Name name; // If this function can start an unwind/rewind. bool canChangeState = false; // If this function is part of the runtime that receives an unwinding // and starts a rewinding. If so, we do not instrument it, see above. // This is only relevant when handling things entirely inside wasm, // as opposed to imports. bool isBottomMostRuntime = false; // If this function is part of the runtime that starts an unwinding // and stops a rewinding. If so, we do not instrument it, see above. // The difference between the top-most and bottom-most runtime is that // the top-most part is still marked as changing the state; so things // that call it are instrumented. This is not done for the bottom. bool isTopMostRuntime = false; bool inRemoveList = false; bool addedFromList = false; }; typedef std::map Map; Map map; public: ModuleAnalyzer(Module& module, std::function canImportChangeState, bool canIndirectChangeState, const String::Split& removeListInput, const String::Split& addListInput, const String::Split& onlyListInput, bool asserts, bool verbose) : module(module), canIndirectChangeState(canIndirectChangeState), fakeGlobals(module), asserts(asserts), verbose(verbose) { PatternMatcher removeList(""remove"", module, removeListInput); PatternMatcher addList(""add"", module, addListInput); PatternMatcher onlyList(""only"", module, onlyListInput); // Rename the asyncify imports so their internal name matches the // convention. This makes replacing them with the implementations // later easier. std::map renamings; for (auto& func : module.functions) { if (func->module == ASYNCIFY) { if (func->base == START_UNWIND) { renamings[func->name] = ASYNCIFY_START_UNWIND; } else if (func->base == STOP_UNWIND) { renamings[func->name] = ASYNCIFY_STOP_UNWIND; } else if (func->base == START_REWIND) { renamings[func->name] = ASYNCIFY_START_REWIND; } else if (func->base == STOP_REWIND) { renamings[func->name] = ASYNCIFY_STOP_REWIND; } else { Fatal() << ""call to unidenfied asyncify import: "" << func->base; } } } ModuleUtils::renameFunctions(module, renamings); // Scan to see which functions can directly change the state. // Also handle the asyncify imports, removing them (as we will implement // them later), and replace calls to them with calls to the later proper // name. ModuleUtils::CallGraphPropertyAnalysis scanner( module, [&](Function* func, Info& info) { info.name = func->name; if (func->imported()) { // The relevant asyncify imports can definitely change the state. if (func->module == ASYNCIFY && (func->base == START_UNWIND || func->base == STOP_REWIND)) { info.canChangeState = true; } else { info.canChangeState = canImportChangeState(func->module, func->base); if (verbose && info.canChangeState) { std::cout << ""[asyncify] "" << func->name << "" is an import that can change the state\\n""; } } return; } struct Walker : PostWalker { Info& info; Module& module; bool canIndirectChangeState; Walker(Info& info, Module& module, bool canIndirectChangeState) : info(info), module(module), canIndirectChangeState(canIndirectChangeState) {} void visitCall(Call* curr) { if (curr->isReturn) { Fatal() << ""tail calls not yet supported in asyncify""; } auto* target = module.getFunction(curr->target); if (target->imported() && target->module == ASYNCIFY) { // Redirect the imports to the functions we'll add later. if (target->base == START_UNWIND) { info.canChangeState = true; info.isTopMostRuntime = true; } else if (target->base == STOP_UNWIND) { info.isBottomMostRuntime = true; } else if (target->base == START_REWIND) { info.isBottomMostRuntime = true; } else if (target->base == STOP_REWIND) { info.canChangeState = true; info.isTopMostRuntime = true; } else { WASM_UNREACHABLE(""call to unidenfied asyncify import""); } } } void visitCallIndirect(CallIndirect* curr) { if (curr->isReturn) { Fatal() << ""tail calls not yet supported in asyncify""; } if (canIndirectChangeState) { info.canChangeState = true; } // TODO optimize the other case, at least by type } }; Walker walker(info, module, canIndirectChangeState); walker.walk(func->body); if (info.isBottomMostRuntime) { info.canChangeState = false; // TODO: issue warnings on suspicious things, like a function in // the bottom-most runtime also doing top-most runtime stuff // like starting and unwinding. } if (verbose && info.canChangeState) { std::cout << ""[asyncify] "" << func->name << "" can change the state due to initial scan\\n""; } }); // Functions in the remove-list are assumed to not change the state. for (auto& pair : scanner.map) { auto* func = pair.first; auto& info = pair.second; if (removeList.match(func->name)) { info.inRemoveList = true; if (verbose && info.canChangeState) { std::cout << ""[asyncify] "" << func->name << "" is in the remove-list, ignore\\n""; } info.canChangeState = false; } } // Remove the asyncify imports, if any, and any calls to them. std::vector funcsToDelete; for (auto& pair : scanner.map) { auto* func = pair.first; auto& callsTo = pair.second.callsTo; if (func->imported() && func->module == ASYNCIFY) { funcsToDelete.push_back(func->name); } std::vector callersToDelete; for (auto* target : callsTo) { if (target->imported() && target->module == ASYNCIFY) { callersToDelete.push_back(target); } } for (auto* target : callersToDelete) { callsTo.erase(target); } } for (auto name : funcsToDelete) { module.removeFunction(name); } scanner.propagateBack([](const Info& info) { return info.canChangeState; }, [](const Info& info) { return !info.isBottomMostRuntime && !info.inRemoveList; }, [verbose](Info& info, Function* reason) { if (verbose && !info.canChangeState) { std::cout << ""[asyncify] "" << info.name << "" can change the state due to "" << reason->name << ""\\n""; } info.canChangeState = true; }, scanner.IgnoreNonDirectCalls); map.swap(scanner.map); if (!onlyListInput.empty()) { // Only the functions in the only-list can change the state. for (auto& func : module.functions) { if (!func->imported()) { auto& info = map[func.get()]; bool matched = onlyList.match(func->name); info.canChangeState = matched; if (matched) { info.addedFromList = true; } if (verbose) { std::cout << ""[asyncify] "" << func->name << ""'s state is set based on the only-list to "" << matched << '\\n'; } } } } if (!addListInput.empty()) { for (auto& func : module.functions) { if (!func->imported() && addList.match(func->name)) { auto& info = map[func.get()]; if (verbose && !info.canChangeState) { std::cout << ""[asyncify] "" << func->name << "" is in the add-list, add\\n""; } info.canChangeState = true; info.addedFromList = true; } } } removeList.checkPatternsMatches(); addList.checkPatternsMatches(); onlyList.checkPatternsMatches(); } bool needsInstrumentation(Function* func) { auto& info = map[func]; return info.canChangeState && !info.isTopMostRuntime; } bool canChangeState(Expression* curr, Function* func) { // Look inside to see if we call any of the things we know can change the // state. // TODO: caching, this is O(N^2) struct Walker : PostWalker { void visitCall(Call* curr) { // We only implement these at the very end, but we know that they // definitely change the state. if (curr->target == ASYNCIFY_START_UNWIND || curr->target == ASYNCIFY_STOP_REWIND || curr->target == ASYNCIFY_GET_CALL_INDEX || curr->target == ASYNCIFY_CHECK_CALL_INDEX) { canChangeState = true; return; } if (curr->target == ASYNCIFY_STOP_UNWIND || curr->target == ASYNCIFY_START_REWIND) { isBottomMostRuntime = true; return; } // The target may not exist if it is one of our temporary intrinsics. auto* target = module->getFunctionOrNull(curr->target); if (target && (*map)[target].canChangeState) { canChangeState = true; } } void visitCallIndirect(CallIndirect* curr) { hasIndirectCall = true; } Module* module; ModuleAnalyzer* analyzer; Map* map; bool hasIndirectCall = false; bool canChangeState = false; bool isBottomMostRuntime = false; }; Walker walker; walker.module = &module; walker.analyzer = this; walker.map = ↦ walker.walk(curr); // An indirect call is normally ignored if we are ignoring indirect calls. // However, see the docs at the top: if the function we are inside was // specifically added by the user (in the only-list or the add-list) then we // instrument indirect calls from it (this allows specifically allowing some // indirect calls but not others). if (walker.hasIndirectCall && (canIndirectChangeState || map[func].addedFromList)) { walker.canChangeState = true; } // The bottom-most runtime can never change the state. return walker.canChangeState && !walker.isBottomMostRuntime; } FakeGlobalHelper fakeGlobals; bool asserts; bool verbose; }; // Checks if something performs a call: either a direct or indirect call, // and perhaps it is dropped or assigned to a local. This captures all the // cases of a call in flat IR. static bool doesCall(Expression* curr) { if (auto* set = curr->dynCast()) { curr = set->value; } else if (auto* drop = curr->dynCast()) { curr = drop->value; } return curr->is() || curr->is(); } class AsyncifyBuilder : public Builder { public: AsyncifyBuilder(Module& wasm) : Builder(wasm) {} Expression* makeGetStackPos() { return makeLoad(4, false, int32_t(DataOffset::BStackPos), 4, makeGlobalGet(ASYNCIFY_DATA, Type::i32), Type::i32); } Expression* makeIncStackPos(int32_t by) { if (by == 0) { return makeNop(); } return makeStore( 4, int32_t(DataOffset::BStackPos), 4, makeGlobalGet(ASYNCIFY_DATA, Type::i32), makeBinary(AddInt32, makeGetStackPos(), makeConst(Literal(by))), Type::i32); } Expression* makeStateCheck(State value) { return makeBinary(EqInt32, makeGlobalGet(ASYNCIFY_STATE, Type::i32), makeConst(Literal(int32_t(value)))); } Expression* makeNegatedStateCheck(State value) { return makeUnary(EqZInt32, makeStateCheck(value)); } }; // Instrument control flow, around calls and adding skips for rewinding. struct AsyncifyFlow : public Pass { bool isFunctionParallel() override { return true; } ModuleAnalyzer* analyzer; AsyncifyFlow* create() override { return new AsyncifyFlow(analyzer); } AsyncifyFlow(ModuleAnalyzer* analyzer) : analyzer(analyzer) {} void runOnFunction(PassRunner* runner, Module* module_, Function* func_) override { module = module_; func = func_; builder = make_unique(*module); // If the function cannot change our state, we have nothing to do - // we will never unwind or rewind the stack here. if (!analyzer->needsInstrumentation(func)) { if (analyzer->asserts) { addAssertsInNonInstrumented(func); } return; } // Rewrite the function body. // Each function we enter will pop one from the stack, which is the index // of the next call to make. auto* block = builder->makeBlock( {builder->makeIf(builder->makeStateCheck( State::Rewinding), // TODO: such checks can be !normal makeCallIndexPop()), process(func->body)}); if (func->sig.results != Type::none) { // Rewriting control flow may alter things; make sure the function ends in // something valid (which the optimizer can remove later). block->list.push_back(builder->makeUnreachable()); } block->finalize(); func->body = block; // Making things like returns conditional may alter types. ReFinalize().walkFunctionInModule(func, module); } private: std::unique_ptr builder; Module* module; Function* func; // Each call in the function has an index, noted during unwind and checked // during rewind. Index callIndex = 0; Expression* process(Expression* curr) { if (!analyzer->canChangeState(curr, func)) { return makeMaybeSkip(curr); } // The IR is in flat form, which makes this much simpler: there are no // unnecessarily nested side effects or control flow, so we can add // skips for rewinding in an easy manner, putting a single if around // whole chunks of code. Also calls are separated out so that it is easy // to add the necessary checks for them for unwinding/rewinding support. // // Aside from that, we must ""linearize"" all control flow so that we can // reach the right part when rewinding, which is done by always skipping // forward. For example, for an if we do this: // // if (condition()) { // side1(); // } else { // side2(); // } // => // if (!rewinding) { // temp = condition(); // } // if (rewinding || temp) { // side1(); // } // if (rewinding || !temp) { // side2(); // } // // This way we will linearly get through all the code in the function, // if we are rewinding. In a similar way we skip over breaks, etc.; just // ""keep on truckin'"". // // Note that temp locals added in this way are just normal locals, and in // particular they are saved and loaded. That way if we resume from the // first if arm we will avoid the second. if (auto* block = curr->dynCast()) { // At least one of our children may change the state. Clump them as // necessary. Index i = 0; auto& list = block->list; while (i < list.size()) { if (analyzer->canChangeState(list[i], func)) { list[i] = process(list[i]); i++; } else { Index end = i + 1; while (end < list.size() && !analyzer->canChangeState(list[end], func)) { end++; } // We have a range of [i, end) in which the state cannot change, // so all we need to do is skip it if rewinding. if (end == i + 1) { list[i] = makeMaybeSkip(list[i]); } else { auto* block = builder->makeBlock(); for (auto j = i; j < end; j++) { block->list.push_back(list[j]); } block->finalize(); list[i] = makeMaybeSkip(block); for (auto j = i + 1; j < end; j++) { list[j] = builder->makeNop(); } } i = end; } } return block; } else if (auto* iff = curr->dynCast()) { // The state change cannot be in the condition due to flat form, so it // must be in one of the children. assert(!analyzer->canChangeState(iff->condition, func)); // We must linearize this, which means we pass through both arms if we // are rewinding. if (!iff->ifFalse) { iff->condition = builder->makeBinary( OrInt32, iff->condition, builder->makeStateCheck(State::Rewinding)); iff->ifTrue = process(iff->ifTrue); iff->finalize(); return iff; } auto conditionTemp = builder->addVar(func, Type::i32); // TODO: can avoid pre if the condition is a get or a const auto* pre = makeMaybeSkip(builder->makeLocalSet(conditionTemp, iff->condition)); iff->condition = builder->makeLocalGet(conditionTemp, Type::i32); iff->condition = builder->makeBinary( OrInt32, iff->condition, builder->makeStateCheck(State::Rewinding)); iff->ifTrue = process(iff->ifTrue); auto* otherArm = iff->ifFalse; iff->ifFalse = nullptr; iff->finalize(); // Add support for the second arm as well. auto* otherIf = builder->makeIf( builder->makeBinary( OrInt32, builder->makeUnary(EqZInt32, builder->makeLocalGet(conditionTemp, Type::i32)), builder->makeStateCheck(State::Rewinding)), process(otherArm)); otherIf->finalize(); return builder->makeBlock({pre, iff, otherIf}); } else if (auto* loop = curr->dynCast()) { loop->body = process(loop->body); return loop; } else if (doesCall(curr)) { return makeCallSupport(curr); } // We must handle all control flow above, and all things that can change // the state, so there should be nothing that can reach here - add it // earlier as necessary. // std::cout << *curr << '\\n'; WASM_UNREACHABLE(""unexpected expression type""); } // Possibly skip some code, if rewinding. Expression* makeMaybeSkip(Expression* curr) { return builder->makeIf(builder->makeStateCheck(State::Normal), curr); } Expression* makeCallSupport(Expression* curr) { // TODO: stop doing this after code can no longer reach a call that may // change the state assert(doesCall(curr)); assert(curr->type == Type::none); // The case of a set is tricky: we must *not* execute the set when // unwinding, since at that point we have a fake value for the return, // and if we applied it to the local, it would end up saved and then // potentially used later - and with coalescing, that may interfere // with other things. Note also that at this point in the process we // have not yet written the load saving/loading code, so the optimizer // doesn't see that locals will have another use at the beginning and // end of the function. We don't do that yet because we don't want it // to force the final number of locals to be too high, but we also // must be careful to never touch a local unnecessarily to avoid bugs. // To implement this, write to a fake global; we'll fix it up after // AsyncifyLocals locals adds local saving/restoring. auto* set = curr->dynCast(); if (set) { auto name = analyzer->fakeGlobals.getName(set->value->type); curr = builder->makeGlobalSet(name, set->value); set->value = builder->makeGlobalGet(name, set->value->type); } // Instrument the call itself (or, if a drop, the drop+call). auto index = callIndex++; // Execute the call, if either normal execution, or if rewinding and this // is the right call to go into. // TODO: we can read the next call index once in each function (but should // avoid saving/restoring that local later) curr = builder->makeIf( builder->makeIf(builder->makeStateCheck(State::Normal), builder->makeConst(int32_t(1)), makeCallIndexPeek(index)), builder->makeSequence(curr, makePossibleUnwind(index, set))); return curr; } Expression* makePossibleUnwind(Index index, Expression* ifNotUnwinding) { // In this pass we emit an ""unwind"" as a call to a fake intrinsic. We // will implement it in the later pass. (We can't create the unwind block // target here, as the optimizer would remove it later; we can only add // it when we add its contents, later.) return builder->makeIf( builder->makeStateCheck(State::Unwinding), builder->makeCall( ASYNCIFY_UNWIND, {builder->makeConst(int32_t(index))}, Type::none), ifNotUnwinding); } Expression* makeCallIndexPeek(Index index) { // Emit an intrinsic for this, as we store the index into a local, and // don't want it to be seen by asyncify itself. return builder->makeCall(ASYNCIFY_CHECK_CALL_INDEX, {builder->makeConst(int32_t(index))}, Type::i32); } Expression* makeCallIndexPop() { // Emit an intrinsic for this, as we store the index into a local, and // don't want it to be seen by asyncify itself. return builder->makeCall(ASYNCIFY_GET_CALL_INDEX, {}, Type::none); } // Given a function that is not instrumented - because we proved it doesn't // need it, or depending on the only-list / remove-list - add assertions that // verify that property at runtime. // Note that it is ok to run code while sleeping (if you are careful not // to break assumptions in the program!) - so what is actually // checked here is if the state *changes* in an uninstrumented function. // That is, if in an uninstrumented function, a sleep should not begin // from any call. void addAssertsInNonInstrumented(Function* func) { auto oldState = builder->addVar(func, Type::i32); // Add a check at the function entry. func->body = builder->makeSequence( builder->makeLocalSet(oldState, builder->makeGlobalGet(ASYNCIFY_STATE, Type::i32)), func->body); // Add a check around every call. struct Walker : PostWalker { void visitCall(Call* curr) { // Tail calls will need another type of check, as they wouldn't reach // this assertion. assert(!curr->isReturn); handleCall(curr); } void visitCallIndirect(CallIndirect* curr) { // Tail calls will need another type of check, as they wouldn't reach // this assertion. assert(!curr->isReturn); handleCall(curr); } void handleCall(Expression* call) { auto* check = builder->makeIf( builder->makeBinary(NeInt32, builder->makeGlobalGet(ASYNCIFY_STATE, Type::i32), builder->makeLocalGet(oldState, Type::i32)), builder->makeUnreachable()); Expression* rep; if (call->type.isConcrete()) { auto temp = builder->addVar(func, call->type); rep = builder->makeBlock({ builder->makeLocalSet(temp, call), check, builder->makeLocalGet(temp, call->type), }); } else { rep = builder->makeSequence(call, check); } replaceCurrent(rep); } Function* func; AsyncifyBuilder* builder; Index oldState; }; Walker walker; walker.func = func; walker.builder = builder.get(); walker.oldState = oldState; walker.walk(func->body); } }; // Instrument local saving/restoring. struct AsyncifyLocals : public WalkerPass> { bool isFunctionParallel() override { return true; } ModuleAnalyzer* analyzer; AsyncifyLocals* create() override { return new AsyncifyLocals(analyzer); } AsyncifyLocals(ModuleAnalyzer* analyzer) : analyzer(analyzer) {} void visitCall(Call* curr) { // Replace calls to the fake intrinsics. if (curr->target == ASYNCIFY_UNWIND) { replaceCurrent(builder->makeBreak(ASYNCIFY_UNWIND, curr->operands[0])); } else if (curr->target == ASYNCIFY_GET_CALL_INDEX) { replaceCurrent(builder->makeSequence( builder->makeIncStackPos(-4), builder->makeLocalSet( rewindIndex, builder->makeLoad( 4, false, 0, 4, builder->makeGetStackPos(), Type::i32)))); } else if (curr->target == ASYNCIFY_CHECK_CALL_INDEX) { replaceCurrent(builder->makeBinary( EqInt32, builder->makeLocalGet(rewindIndex, Type::i32), builder->makeConst( Literal(int32_t(curr->operands[0]->cast()->value.geti32()))))); } } void visitGlobalSet(GlobalSet* curr) { auto type = analyzer->fakeGlobals.getTypeOrNone(curr->name); if (type != Type::none) { replaceCurrent( builder->makeLocalSet(getFakeCallLocal(type), curr->value)); } } void visitGlobalGet(GlobalGet* curr) { auto type = analyzer->fakeGlobals.getTypeOrNone(curr->name); if (type != Type::none) { replaceCurrent(builder->makeLocalGet(getFakeCallLocal(type), type)); } } Index getFakeCallLocal(Type type) { auto iter = fakeCallLocals.find(type); if (iter != fakeCallLocals.end()) { return iter->second; } return fakeCallLocals[type] = builder->addVar(getFunction(), type); } void doWalkFunction(Function* func) { // If the function cannot change our state, we have nothing to do - // we will never unwind or rewind the stack here. if (!analyzer->needsInstrumentation(func)) { return; } // Find the locals that we actually need to load and save: any local that is // alive at a relevant call site must be handled, but others can be ignored. findRelevantLiveLocals(func); // The new function body has a prelude to load locals if rewinding, // then the actual main body, which does all its unwindings by breaking // to the unwind block, which then handles pushing the call index, as // well as saving the locals. // An index is needed for getting the unwinding and rewinding call indexes // around TODO: can this be the same index? auto unwindIndex = builder->addVar(func, Type::i32); rewindIndex = builder->addVar(func, Type::i32); // Rewrite the function body. builder = make_unique(*getModule()); walk(func->body); // After the normal function body, emit a barrier before the postamble. Expression* barrier; if (func->sig.results == Type::none) { // The function may have ended without a return; ensure one. barrier = builder->makeReturn(); } else { // The function must have returned or hit an unreachable, but emit one // to make possible bugs easier to figure out (as this should never be // reached). The optimizer can remove this anyhow. barrier = builder->makeUnreachable(); } auto* newBody = builder->makeBlock( {builder->makeIf(builder->makeStateCheck(State::Rewinding), makeLocalLoading()), builder->makeLocalSet( unwindIndex, builder->makeBlock(ASYNCIFY_UNWIND, builder->makeSequence(func->body, barrier))), makeCallIndexPush(unwindIndex), makeLocalSaving()}); if (func->sig.results != Type::none) { // If we unwind, we must still ""return"" a value, even if it will be // ignored on the outside. newBody->list.push_back( LiteralUtils::makeZero(func->sig.results, *getModule())); newBody->finalize(func->sig.results); } func->body = newBody; // Making things like returns conditional may alter types. ReFinalize().walkFunctionInModule(func, getModule()); } private: std::unique_ptr builder; Index rewindIndex; std::map fakeCallLocals; std::set relevantLiveLocals; void findRelevantLiveLocals(Function* func) { struct RelevantLiveLocalsWalker : public LivenessWalker> { // Basic blocks that have a possible unwind/rewind in them. std::set relevantBasicBlocks; void visitCall(Call* curr) { if (!currBasicBlock) { return; } // Note blocks where we might unwind/rewind, all of which have a // possible call to ASYNCIFY_CHECK_CALL_INDEX emitted right before the // actual call. // Note that each relevant original call was turned into a sequence of // instructions, one of which is an if and then a call to this special // intrinsic. We rely on the fact that if a local was live at the // original call, it also would be in all that sequence of instructions, // and in particular at the call we look for here (which is right before // the call, and so anything that has its final use at the call is still // live here). if (curr->target == ASYNCIFY_CHECK_CALL_INDEX) { relevantBasicBlocks.insert(currBasicBlock); } } }; RelevantLiveLocalsWalker walker; walker.walkFunctionInModule(func, getModule()); // The relevant live locals are ones that are alive at an unwind/rewind // location. TODO look more precisely inside basic blocks, as one might stop // being live in the middle for (auto* block : walker.liveBlocks) { if (walker.relevantBasicBlocks.count(block)) { for (auto local : block->contents.start) { relevantLiveLocals.insert(local); } } } } Expression* makeLocalLoading() { if (relevantLiveLocals.empty()) { return builder->makeNop(); } auto* func = getFunction(); auto numLocals = func->getNumLocals(); Index total = 0; for (Index i = 0; i < numLocals; i++) { if (!relevantLiveLocals.count(i)) { continue; } total += func->getLocalType(i).getByteSize(); } auto* block = builder->makeBlock(); block->list.push_back(builder->makeIncStackPos(-total)); auto tempIndex = builder->addVar(func, Type::i32); block->list.push_back( builder->makeLocalSet(tempIndex, builder->makeGetStackPos())); Index offset = 0; for (Index i = 0; i < numLocals; i++) { if (!relevantLiveLocals.count(i)) { continue; } auto localType = func->getLocalType(i); SmallVector loads; for (const auto& type : localType) { auto size = type.getByteSize(); assert(size % STACK_ALIGN == 0); // TODO: higher alignment? loads.push_back( builder->makeLoad(size, true, offset, STACK_ALIGN, builder->makeLocalGet(tempIndex, Type::i32), type)); offset += size; } Expression* load; if (loads.size() == 1) { load = loads[0]; } else if (localType.size() > 1) { load = builder->makeTupleMake(std::move(loads)); } else { WASM_UNREACHABLE(""Unexpected empty type""); } block->list.push_back(builder->makeLocalSet(i, load)); } block->finalize(); return block; } Expression* makeLocalSaving() { if (relevantLiveLocals.empty()) { return builder->makeNop(); } auto* func = getFunction(); auto numLocals = func->getNumLocals(); auto* block = builder->makeBlock(); auto tempIndex = builder->addVar(func, Type::i32); block->list.push_back( builder->makeLocalSet(tempIndex, builder->makeGetStackPos())); Index offset = 0; for (Index i = 0; i < numLocals; i++) { if (!relevantLiveLocals.count(i)) { continue; } auto localType = func->getLocalType(i); size_t j = 0; for (const auto& type : localType) { auto size = type.getByteSize(); Expression* localGet = builder->makeLocalGet(i, localType); if (localType.size() > 1) { localGet = builder->makeTupleExtract(localGet, j); } assert(size % STACK_ALIGN == 0); // TODO: higher alignment? block->list.push_back( builder->makeStore(size, offset, STACK_ALIGN, builder->makeLocalGet(tempIndex, Type::i32), localGet, type)); offset += size; ++j; } } block->list.push_back(builder->makeIncStackPos(offset)); block->finalize(); return block; } Expression* makeCallIndexPush(Index tempIndex) { // TODO: add a check against the stack end here return builder->makeSequence( builder->makeStore(4, 0, 4, builder->makeGetStackPos(), builder->makeLocalGet(tempIndex, Type::i32), Type::i32), builder->makeIncStackPos(4)); } }; } // anonymous namespace static std::string getFullImportName(Name module, Name base) { return std::string(module.str) + '.' + base.str; } struct Asyncify : public Pass { void run(PassRunner* runner, Module* module) override { bool optimize = runner->options.optimizeLevel > 0; // Ensure there is a memory, as we need it. MemoryUtils::ensureExists(module->memory); // Find which things can change the state. auto stateChangingImports = String::trim(read_possible_response_file( runner->options.getArgumentOrDefault(""asyncify-imports"", """"))); auto ignoreImports = runner->options.getArgumentOrDefault(""asyncify-ignore-imports"", """"); bool allImportsCanChangeState = stateChangingImports == """" && ignoreImports == """"; String::Split listedImports(stateChangingImports, "",""); // TODO: consider renaming asyncify-ignore-indirect to // asyncify-ignore-nondirect, but that could break users. auto ignoreNonDirect = runner->options.getArgumentOrDefault( ""asyncify-ignore-indirect"", """") == """"; std::string removeListInput = runner->options.getArgumentOrDefault(""asyncify-removelist"", """"); if (removeListInput.empty()) { // Support old name for now to avoid immediate breakage TODO remove removeListInput = runner->options.getArgumentOrDefault(""asyncify-blacklist"", """"); } String::Split removeList( String::trim(read_possible_response_file(removeListInput)), "",""); String::Split addList( String::trim(read_possible_response_file( runner->options.getArgumentOrDefault(""asyncify-addlist"", """"))), "",""); std::string onlyListInput = runner->options.getArgumentOrDefault(""asyncify-onlylist"", """"); if (onlyListInput.empty()) { // Support old name for now to avoid immediate breakage TODO remove onlyListInput = runner->options.getArgumentOrDefault(""asyncify-whitelist"", """"); } String::Split onlyList( String::trim(read_possible_response_file(onlyListInput)), "",""); auto asserts = runner->options.getArgumentOrDefault(""asyncify-asserts"", """") != """"; auto verbose = runner->options.getArgumentOrDefault(""asyncify-verbose"", """") != """"; removeList = handleBracketingOperators(removeList); addList = handleBracketingOperators(addList); onlyList = handleBracketingOperators(onlyList); if (!onlyList.empty() && (!removeList.empty() || !addList.empty())) { Fatal() << ""It makes no sense to use both an asyncify only-list together "" ""with another list.""; } auto canImportChangeState = [&](Name module, Name base) { if (allImportsCanChangeState) { return true; } auto full = getFullImportName(module, base); for (auto& listedImport : listedImports) { if (String::wildcardMatch(listedImport, full)) { return true; } } return false; }; // Scan the module. ModuleAnalyzer analyzer(*module, canImportChangeState, ignoreNonDirect, removeList, addList, onlyList, asserts, verbose); // Add necessary globals before we emit code to use them. addGlobals(module); // Instrument the flow of code, adding code instrumentation and // skips for when rewinding. We do this on flat IR so that it is // practical to add code around each call, without affecting // anything else. { PassRunner runner(module); runner.add(""flatten""); // Dce is useful here, since AsyncifyFlow makes control flow conditional, // which may make unreachable code look reachable. It also lets us ignore // unreachable code here. runner.add(""dce""); if (optimize) { // Optimizing before BsyncifyFlow is crucial, especially coalescing, // because the flow changes add many branches, break up if-elses, etc., // all of which extend the live ranges of locals. In other words, it is // not possible to coalesce well afterwards. runner.add(""remove-unused-names""); runner.add(""simplify-locals-nonesting""); runner.add(""reorder-locals""); runner.add(""coalesce-locals""); runner.add(""simplify-locals-nonesting""); runner.add(""reorder-locals""); runner.add(""merge-blocks""); } runner.add(make_unique(&analyzer)); runner.setIsNested(true); runner.setValidateGlobally(false); runner.run(); } // Next, add local saving/restoring logic. We optimize before doing this, // to undo the extra code generated by flattening, and to arrive at the // minimal amount of locals (which is important as we must save and // restore those locals). We also and optimize after as well to simplify // the code as much as possible. { PassRunner runner(module); if (optimize) { runner.addDefaultFunctionOptimizationPasses(); } runner.add(make_unique(&analyzer)); if (optimize) { runner.addDefaultFunctionOptimizationPasses(); } runner.setIsNested(true); runner.setValidateGlobally(false); runner.run(); } // Finally, add function support (that should not have been seen by // the previous passes). addFunctions(module); } private: void addGlobals(Module* module) { Builder builder(*module); module->addGlobal(builder.makeGlobal(ASYNCIFY_STATE, Type::i32, builder.makeConst(int32_t(0)), Builder::Mutable)); module->addGlobal(builder.makeGlobal(ASYNCIFY_DATA, Type::i32, builder.makeConst(int32_t(0)), Builder::Mutable)); } void addFunctions(Module* module) { Builder builder(*module); auto makeFunction = [&](Name name, bool setData, State state) { std::vector params; if (setData) { params.push_back(Type::i32); } auto* body = builder.makeBlock(); body->list.push_back(builder.makeGlobalSet( ASYNCIFY_STATE, builder.makeConst(int32_t(state)))); if (setData) { body->list.push_back(builder.makeGlobalSet( ASYNCIFY_DATA, builder.makeLocalGet(0, Type::i32))); } // Verify the data is valid. auto* stackPos = builder.makeLoad(4, false, int32_t(DataOffset::BStackPos), 4, builder.makeGlobalGet(ASYNCIFY_DATA, Type::i32), Type::i32); auto* stackEnd = builder.makeLoad(4, false, int32_t(DataOffset::BStackEnd), 4, builder.makeGlobalGet(ASYNCIFY_DATA, Type::i32), Type::i32); body->list.push_back( builder.makeIf(builder.makeBinary(GtUInt32, stackPos, stackEnd), builder.makeUnreachable())); body->finalize(); auto func = builder.makeFunction( name, Signature(Type(params), Type::none), {}, body); module->addFunction(std::move(func)); module->addExport(builder.makeExport(name, name, ExternalKind::Function)); }; makeFunction(ASYNCIFY_START_UNWIND, true, State::Unwinding); makeFunction(ASYNCIFY_STOP_UNWIND, false, State::Normal); makeFunction(ASYNCIFY_START_REWIND, true, State::Rewinding); makeFunction(ASYNCIFY_STOP_REWIND, false, State::Normal); module->addFunction( builder.makeFunction(ASYNCIFY_GET_STATE, Signature(Type::none, Type::i32), {}, builder.makeGlobalGet(ASYNCIFY_STATE, Type::i32))); module->addExport(builder.makeExport( ASYNCIFY_GET_STATE, ASYNCIFY_GET_STATE, ExternalKind::Function)); } }; Pass* createAsyncifyPass() { return new Asyncify(); } // Helper passes that can be run after Asyncify. template struct ModAsyncify : public WalkerPass>> { bool isFunctionParallel() override { return true; } ModAsyncify* create() override { return new ModAsyncify(); } void doWalkFunction(Function* func) { // Find the asyncify state name. auto* unwind = this->getModule()->getExport(ASYNCIFY_STOP_UNWIND); auto* unwindFunc = this->getModule()->getFunction(unwind->value); FindAll sets(unwindFunc->body); assert(sets.list.size() == 1); asyncifyStateName = sets.list[0]->name; // Walk and optimize. this->walk(func->body); } // Note that we don't just implement GetGlobal as we may know the value is // *not* 0, 1, or 2, but not know the actual value. So what we can say depends // on the comparison being done on it, and so we implement Binary and // Select. void visitBinary(Binary* curr) { // Check if this is a comparison of the asyncify state to a specific // constant, which we may know is impossible. bool flip = false; if (curr->op == NeInt32) { flip = true; } else if (curr->op != EqInt32) { return; } auto* c = curr->right->dynCast(); if (!c) { return; } auto* get = curr->left->dynCast(); if (!get || get->name != asyncifyStateName) { return; } // This is a comparison of the state to a constant, check if we know the // value. int32_t value; auto checkedValue = c->value.geti32(); if ((checkedValue == int(State::Unwinding) && neverUnwind) || (checkedValue == int(State::Rewinding) && neverRewind)) { // We know the state is checked against an impossible value. value = 0; } else if (checkedValue == int(State::Unwinding) && this->unwinding) { // We know we are in fact unwinding right now. value = 1; unsetUnwinding(); } else { return; } if (flip) { value = 1 - value; } Builder builder(*this->getModule()); this->replaceCurrent(builder.makeConst(int32_t(value))); } void visitSelect(Select* curr) { auto* get = curr->condition->dynCast(); if (!get || get->name != asyncifyStateName) { return; } // This is a comparison of the state to zero, which means we are checking // ""if running normally, run this code, but if rewinding, ignore it"". If // we know we'll never rewind, we can optimize this. if (neverRewind) { Builder builder(*this->getModule()); curr->condition = builder.makeConst(int32_t(0)); } } void visitCall(Call* curr) { unsetUnwinding(); if (!importsAlwaysUnwind) { return; } auto* target = this->getModule()->getFunction(curr->target); if (!target->imported()) { return; } // This is an import that definitely unwinds. Await the next check of // the state in this linear execution trace, which we can turn into a // constant. this->unwinding = true; } void visitCallIndirect(CallIndirect* curr) { unsetUnwinding(); } static void doNoteNonLinear( ModAsyncify* self, Expression**) { // When control flow branches, stop tracking an unwinding. self->unsetUnwinding(); } void visitGlobalSet(GlobalSet* set) { // TODO: this could be more precise unsetUnwinding(); } private: Name asyncifyStateName; // Whether we just did a call to an import that indicates we are unwinding. bool unwinding = false; void unsetUnwinding() { this->unwinding = false; } }; // // Assume imports that may unwind will always unwind, and that rewinding never // happens. // Pass* createModAsyncifyAlwaysOnlyUnwindPass() { return new ModAsyncify(); } // // Assume that we never unwind, but may still rewind. // struct ModAsyncifyNeverUnwind : public Pass { void run(PassRunner* runner, Module* module) override {} }; Pass* createModAsyncifyNeverUnwindPass() { return new ModAsyncify(); } } // namespace wasm ",16264,False,2466.3879116760295,median "/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2019-2020 Baldur Karlsson * * 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 ""../gl_driver.h"" #include ""common/common.h"" #include ""strings/string_utils.h"" #if ENABLED(RDOC_WIN32) && ENABLED(RENDERDOC_DX_GL_INTEROP) struct ID3D11Resource; void *UnwrapDXDevice(void *dxDevice); ID3D11Resource *UnwrapDXResource(void *dxObject); void GetDXTextureProperties(void *dxObject, ResourceFormat &fmt, uint32_t &width, uint32_t &height, uint32_t &depth, uint32_t &mips, uint32_t &layers, uint32_t &samples); BOOL WrappedOpenGL::wglDXSetResourceShareHandleNV(void *dxObject, HANDLE shareHandle) { // no-op return GL.wglDXSetResourceShareHandleNV(dxObject, shareHandle); } HANDLE WrappedOpenGL::wglDXOpenDeviceNV(void *dxDevice) { void *unwrapped = UnwrapDXDevice(dxDevice); if(unwrapped) { HANDLE ret = (HANDLE)GL.wglDXOpenDeviceNV(unwrapped); SetLastError(S_OK); return ret; } SetLastError(ERROR_NOT_SUPPORTED); return 0; } BOOL WrappedOpenGL::wglDXCloseDeviceNV(HANDLE hDevice) { return GL.wglDXCloseDeviceNV(hDevice); } struct WrappedHANDLE { HANDLE real; GLResource res; }; HANDLE Unwrap(HANDLE h) { return ((WrappedHANDLE *)h)->real; } HANDLE WrappedOpenGL::wglDXRegisterObjectNV(HANDLE hDevice, void *dxObject, GLuint name, GLenum type, GLenum access) { RDCASSERT(IsCaptureMode(m_State)); ID3D11Resource *real = UnwrapDXResource(dxObject); if(real == NULL) { SetLastError(ERROR_OPEN_FAILED); return 0; } WrappedHANDLE *wrapped = new WrappedHANDLE(); if(type == eGL_RENDERBUFFER) wrapped->res = RenderbufferRes(GetCtx(), name); else if(type == eGL_NONE) wrapped->res = BufferRes(GetCtx(), name); else wrapped->res = TextureRes(GetCtx(), name); GLResourceRecord *record = GetResourceManager()->GetResourceRecord(wrapped->res); if(!record) { RDCERR(""Unrecognised object with type %x and name %u"", type, name); delete wrapped; return NULL; } SERIALISE_TIME_CALL(wrapped->real = GL.wglDXRegisterObjectNV(hDevice, real, name, type, access)); if(wrapped->real == NULL) { delete wrapped; return NULL; } { RDCASSERT(record); USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_wglDXRegisterObjectNV(ser, wrapped->res, type, dxObject); record->AddChunk(scope.Get()); } if(type != eGL_NONE) { ResourceFormat fmt; uint32_t width = 0, height = 0, depth = 0, mips = 0, layers = 0, samples = 0; GetDXTextureProperties(dxObject, fmt, width, height, depth, mips, layers, samples); GL.glTextureParameteriEXT(wrapped->res.name, type, eGL_TEXTURE_MAX_LEVEL, GLint(mips - 1)); ResourceId texId = record->GetResourceID(); m_Textures[texId].resource = wrapped->res; m_Textures[texId].curType = type; m_Textures[texId].width = width; m_Textures[texId].height = height; m_Textures[texId].depth = RDCMAX(depth, samples); m_Textures[texId].samples = samples; m_Textures[texId].dimension = 2; if(type == eGL_TEXTURE_1D || type == eGL_TEXTURE_1D_ARRAY) m_Textures[texId].dimension = 1; else if(type == eGL_TEXTURE_3D) m_Textures[texId].dimension = 3; m_Textures[texId].internalFormat = MakeGLFormat(fmt); m_Textures[texId].mipsValid = (1 << mips) - 1; } return wrapped; } BOOL WrappedOpenGL::wglDXUnregisterObjectNV(HANDLE hDevice, HANDLE hObject) { // don't need to intercept this, as the DX and GL textures will be deleted independently BOOL ret = GL.wglDXUnregisterObjectNV(hDevice, Unwrap(hObject)); delete(WrappedHANDLE *)hObject; return ret; } BOOL WrappedOpenGL::wglDXObjectAccessNV(HANDLE hObject, GLenum access) { // we don't need to care about access return GL.wglDXObjectAccessNV(Unwrap(hObject), access); } BOOL WrappedOpenGL::wglDXLockObjectsNV(HANDLE hDevice, GLint count, HANDLE *hObjects) { HANDLE *unwrapped = new HANDLE[count]; for(GLint i = 0; i < count; i++) unwrapped[i] = Unwrap(hObjects[i]); BOOL ret; SERIALISE_TIME_CALL(ret = GL.wglDXLockObjectsNV(hDevice, count, unwrapped)); if(IsActiveCapturing(m_State)) { for(GLint i = 0; i < count; i++) { WrappedHANDLE *w = (WrappedHANDLE *)hObjects[i]; USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_wglDXLockObjectsNV(ser, w->res); GetContextRecord()->AddChunk(scope.Get()); GetResourceManager()->MarkResourceFrameReferenced(GetResourceManager()->GetResID(w->res), eFrameRef_Read); } } SAFE_DELETE_ARRAY(unwrapped); return ret; } BOOL WrappedOpenGL::wglDXUnlockObjectsNV(HANDLE hDevice, GLint count, HANDLE *hObjects) { HANDLE *unwrapped = new HANDLE[count]; for(GLint i = 0; i < count; i++) unwrapped[i] = Unwrap(hObjects[i]); BOOL ret = GL.wglDXUnlockObjectsNV(hDevice, count, unwrapped); SAFE_DELETE_ARRAY(unwrapped); return ret; } #else BOOL WrappedOpenGL::wglDXSetResourceShareHandleNV(void *dxObject, HANDLE shareHandle) { return 0; } HANDLE WrappedOpenGL::wglDXOpenDeviceNV(void *dxDevice) { return 0; } BOOL WrappedOpenGL::wglDXCloseDeviceNV(HANDLE hDevice) { return 0; } HANDLE WrappedOpenGL::wglDXRegisterObjectNV(HANDLE hDevice, void *dxObject, GLuint name, GLenum type, GLenum access) { return 0; } BOOL WrappedOpenGL::wglDXUnregisterObjectNV(HANDLE hDevice, HANDLE hObject) { return 0; } BOOL WrappedOpenGL::wglDXObjectAccessNV(HANDLE hObject, GLenum access) { return 0; } BOOL WrappedOpenGL::wglDXLockObjectsNV(HANDLE hDevice, GLint count, HANDLE *hObjects) { return 0; } BOOL WrappedOpenGL::wglDXUnlockObjectsNV(HANDLE hDevice, GLint count, HANDLE *hObjects) { return 0; } #endif template bool WrappedOpenGL::Serialise_wglDXRegisterObjectNV(SerialiserType &ser, GLResource Resource, GLenum type, void *dxObject) { SERIALISE_ELEMENT(Resource); GLenum internalFormat = eGL_NONE; uint32_t width = 0, height = 0, depth = 0, mips = 0, layers = 0, samples = 0; if(ser.IsWriting()) { ResourceFormat format; #if ENABLED(RDOC_WIN32) && ENABLED(RENDERDOC_DX_GL_INTEROP) GetDXTextureProperties(dxObject, format, width, height, depth, mips, layers, samples); if(type != eGL_NONE) internalFormat = MakeGLFormat(format); #else RDCERR(""Should never happen - cannot serialise wglDXRegisterObjectNV, interop is disabled""); #endif } SERIALISE_ELEMENT(type); SERIALISE_ELEMENT(internalFormat); SERIALISE_ELEMENT(width); SERIALISE_ELEMENT(height); SERIALISE_ELEMENT(depth); SERIALISE_ELEMENT(mips); SERIALISE_ELEMENT(layers); SERIALISE_ELEMENT(samples); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { GLuint name = Resource.name; switch(type) { case eGL_NONE: case eGL_TEXTURE_BUFFER: { GL.glNamedBufferDataEXT(name, width, NULL, eGL_STATIC_DRAW); break; } case eGL_TEXTURE_1D: GL.glTextureStorage1DEXT(name, type, mips, internalFormat, width); break; case eGL_TEXTURE_1D_ARRAY: GL.glTextureStorage2DEXT(name, type, mips, internalFormat, width, layers); break; // treat renderbuffers and texture rects as tex2D just to make things easier case eGL_RENDERBUFFER: case eGL_TEXTURE_RECTANGLE: case eGL_TEXTURE_2D: case eGL_TEXTURE_CUBE_MAP: GL.glTextureStorage2DEXT(name, type, mips, internalFormat, width, height); break; case eGL_TEXTURE_2D_ARRAY: case eGL_TEXTURE_CUBE_MAP_ARRAY: GL.glTextureStorage3DEXT(name, type, mips, internalFormat, width, height, layers); break; case eGL_TEXTURE_2D_MULTISAMPLE: GL.glTextureStorage2DMultisampleEXT(name, type, samples, internalFormat, width, height, GL_TRUE); break; case eGL_TEXTURE_2D_MULTISAMPLE_ARRAY: GL.glTextureStorage3DMultisampleEXT(name, type, samples, internalFormat, width, height, layers, GL_TRUE); break; case eGL_TEXTURE_3D: GL.glTextureStorage3DEXT(name, type, mips, internalFormat, width, height, depth); break; default: RDCERR(""Unexpected type of interop texture: %s"", ToStr(type).c_str()); break; } if(type != eGL_NONE) { ResourceId liveId = GetResourceManager()->GetResID(Resource); m_Textures[liveId].curType = type; m_Textures[liveId].width = width; m_Textures[liveId].height = height; m_Textures[liveId].depth = RDCMAX(depth, samples); m_Textures[liveId].samples = samples; m_Textures[liveId].dimension = 2; if(type == eGL_TEXTURE_1D || type == eGL_TEXTURE_1D_ARRAY) m_Textures[liveId].dimension = 1; else if(type == eGL_TEXTURE_3D) m_Textures[liveId].dimension = 3; m_Textures[liveId].internalFormat = internalFormat; m_Textures[liveId].mipsValid = (1 << mips) - 1; } if(type == eGL_NONE || type == eGL_TEXTURE_BUFFER) { ResourceId liveId = GetResourceManager()->GetResID(Resource); m_Buffers[liveId].size = width; } AddResourceInitChunk(Resource); } return true; } template bool WrappedOpenGL::Serialise_wglDXLockObjectsNV(SerialiserType &ser, GLResource Resource) { SERIALISE_ELEMENT(Resource); SERIALISE_ELEMENT_LOCAL(textype, Resource.Namespace == eResBuffer ? eGL_NONE : m_Textures[GetResourceManager()->GetResID(Resource)].curType) .Hidden(); // buffer contents are easier to save if(textype == eGL_NONE) { byte *Contents = NULL; uint32_t length = 1; // while writing, fetch the buffer's size and contents if(ser.IsWriting()) { GL.glGetNamedBufferParameterivEXT(Resource.name, eGL_BUFFER_SIZE, (GLint *)&length); Contents = new byte[length]; GLuint oldbuf = 0; GL.glGetIntegerv(eGL_COPY_READ_BUFFER_BINDING, (GLint *)&oldbuf); GL.glBindBuffer(eGL_COPY_READ_BUFFER, Resource.name); GL.glGetBufferSubData(eGL_COPY_READ_BUFFER, 0, (GLsizeiptr)length, Contents); GL.glBindBuffer(eGL_COPY_READ_BUFFER, oldbuf); } SERIALISE_ELEMENT_ARRAY(Contents, length); SERIALISE_ELEMENT(length); SERIALISE_CHECK_READ_ERRORS(); // restore on replay if(IsReplayingAndReading()) { uint32_t liveLength = 1; GL.glGetNamedBufferParameterivEXT(Resource.name, eGL_BUFFER_SIZE, (GLint *)&liveLength); GL.glNamedBufferSubData(Resource.name, 0, (GLsizeiptr)RDCMIN(length, liveLength), Contents); } } else { GLuint ppb = 0, pub = 0; PixelPackState pack; PixelUnpackState unpack; // save and restore pixel pack/unpack state. We only need one or the other but for clarity we // push and pop both always. if(ser.IsWriting() || !IsStructuredExporting(m_State)) { GL.glGetIntegerv(eGL_PIXEL_PACK_BUFFER_BINDING, (GLint *)&ppb); GL.glGetIntegerv(eGL_PIXEL_UNPACK_BUFFER_BINDING, (GLint *)&pub); GL.glBindBuffer(eGL_PIXEL_PACK_BUFFER, 0); GL.glBindBuffer(eGL_PIXEL_UNPACK_BUFFER, 0); pack.Fetch(false); unpack.Fetch(false); ResetPixelPackState(false, 1); ResetPixelUnpackState(false, 1); } TextureData &details = m_Textures[GetResourceManager()->GetResID(Resource)]; GLuint tex = Resource.name; // serialise the metadata for convenience SERIALISE_ELEMENT_LOCAL(internalFormat, details.internalFormat).Hidden(); SERIALISE_ELEMENT_LOCAL(width, details.width).Hidden(); SERIALISE_ELEMENT_LOCAL(height, details.height).Hidden(); SERIALISE_ELEMENT_LOCAL(depth, details.depth).Hidden(); RDCASSERT(internalFormat == details.internalFormat, internalFormat, details.internalFormat); RDCASSERT(width == details.width, width, details.width); RDCASSERT(height == details.height, height, details.height); RDCASSERT(depth == details.depth, depth, details.depth); GLenum fmt = GetBaseFormat(internalFormat); GLenum type = GetDataType(internalFormat); GLint dim = details.dimension; uint32_t size = (uint32_t)GetByteSize(width, height, depth, fmt, type); int mips = 0; if(!IsStructuredExporting(m_State)) mips = GetNumMips(textype, tex, width, height, depth); SERIALISE_ELEMENT(mips).Hidden(); byte *scratchBuf = NULL; // on read and write, we allocate a single buffer big enough for all mips and re-use it // to avoid repeated new/free. scratchBuf = AllocAlignedBuffer(size); GLuint prevtex = 0; if(!IsStructuredExporting(m_State)) { GL.glGetIntegerv(TextureBinding(details.curType), (GLint *)&prevtex); GL.glBindTexture(textype, tex); } for(int i = 0; i < mips; i++) { int w = RDCMAX(details.width >> i, 1); int h = RDCMAX(details.height >> i, 1); int d = RDCMAX(details.depth >> i, 1); if(textype == eGL_TEXTURE_CUBE_MAP_ARRAY || textype == eGL_TEXTURE_1D_ARRAY || textype == eGL_TEXTURE_2D_ARRAY) d = details.depth; size = (uint32_t)GetByteSize(w, h, d, fmt, type); GLenum targets[] = { eGL_TEXTURE_CUBE_MAP_POSITIVE_X, eGL_TEXTURE_CUBE_MAP_NEGATIVE_X, eGL_TEXTURE_CUBE_MAP_POSITIVE_Y, eGL_TEXTURE_CUBE_MAP_NEGATIVE_Y, eGL_TEXTURE_CUBE_MAP_POSITIVE_Z, eGL_TEXTURE_CUBE_MAP_NEGATIVE_Z, }; int count = ARRAY_COUNT(targets); if(textype != eGL_TEXTURE_CUBE_MAP) { targets[0] = textype; count = 1; } for(int trg = 0; trg < count; trg++) { if(ser.IsWriting()) { // we avoid glGetTextureImageEXT as it seems buggy for cubemap faces GL.glGetTexImage(targets[trg], i, fmt, type, scratchBuf); } // serialise without allocating memory as we already have our scratch buf sized. ser.Serialise(""SubresourceContents""_lit, scratchBuf, size, SerialiserFlags::NoFlags); if(IsReplayingAndReading() && !ser.IsErrored()) { if(dim == 1) GL.glTextureSubImage1DEXT(tex, targets[trg], i, 0, w, fmt, type, scratchBuf); else if(dim == 2) GL.glTextureSubImage2DEXT(tex, targets[trg], i, 0, 0, w, h, fmt, type, scratchBuf); else if(dim == 3) GL.glTextureSubImage3DEXT(tex, targets[trg], i, 0, 0, 0, w, h, d, fmt, type, scratchBuf); } } } FreeAlignedBuffer(scratchBuf); // restore pixel (un)packing state if(ser.IsWriting() || !IsStructuredExporting(m_State)) { GL.glBindBuffer(eGL_PIXEL_PACK_BUFFER, ppb); GL.glBindBuffer(eGL_PIXEL_UNPACK_BUFFER, pub); pack.Apply(false); unpack.Apply(false); } if(!IsStructuredExporting(m_State)) GL.glBindTexture(textype, prevtex); SERIALISE_CHECK_READ_ERRORS(); } return true; } #pragma region Memory Objects template bool WrappedOpenGL::Serialise_glCreateMemoryObjectsEXT(SerialiserType &ser, GLsizei n, GLuint *memoryObjects) { SERIALISE_ELEMENT(n); SERIALISE_ELEMENT_LOCAL(memory, GetResourceManager()->GetResID(ExtMemRes(GetCtx(), *memoryObjects))) .TypedAs(""GLResource""_lit); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { CheckReplayFunctionPresent(glCreateMemoryObjectsEXT); GLuint real = 0; GL.glCreateMemoryObjectsEXT(1, &real); GLResource res = ExtMemRes(GetCtx(), real); ResourceId live = m_ResourceManager->RegisterResource(res); GetResourceManager()->AddLiveResource(memory, res); AddResource(memory, ResourceType::Memory, ""Memory Object""); } return true; } void WrappedOpenGL::glCreateMemoryObjectsEXT(GLsizei n, GLuint *memoryObjects) { SERIALISE_TIME_CALL(GL.glCreateMemoryObjectsEXT(n, memoryObjects)); for(GLsizei i = 0; i < n; i++) { GLResource res = ExtMemRes(GetCtx(), memoryObjects[i]); ResourceId id = GetResourceManager()->RegisterResource(res); if(IsCaptureMode(m_State)) { Chunk *chunk = NULL; { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glCreateMemoryObjectsEXT(ser, 1, memoryObjects + i); chunk = scope.Get(); } GLResourceRecord *record = GetResourceManager()->AddResourceRecord(id); RDCASSERT(record); record->AddChunk(chunk); } else { GetResourceManager()->AddLiveResource(id, res); } } } void WrappedOpenGL::glDeleteMemoryObjectsEXT(GLsizei n, const GLuint *memoryObjects) { for(GLsizei i = 0; i < n; i++) { GLResource res = ExtMemRes(GetCtx(), memoryObjects[i]); if(GetResourceManager()->HasCurrentResource(res)) { if(GetResourceManager()->HasResourceRecord(res)) GetResourceManager()->GetResourceRecord(res)->Delete(GetResourceManager()); GetResourceManager()->UnregisterResource(res); } } GL.glDeleteMemoryObjectsEXT(n, memoryObjects); } template bool WrappedOpenGL::Serialise_glMemoryObjectParameterivEXT(SerialiserType &ser, GLuint memoryObjectHandle, GLenum pname, const GLint *params) { SERIALISE_ELEMENT_LOCAL(memoryObject, ExtMemRes(GetCtx(), memoryObjectHandle)); SERIALISE_ELEMENT(pname); // if other parameters are added in future that take more than one value, change the array count // here. SERIALISE_ELEMENT_ARRAY(params, 1U); SERIALISE_CHECK_READ_ERRORS(); RDCASSERT(pname == eGL_DEDICATED_MEMORY_OBJECT_EXT || pname == eGL_PROTECTED_MEMORY_OBJECT_EXT); if(IsReplayingAndReading()) { CheckReplayFunctionPresent(glMemoryObjectParameterivEXT); GL.glMemoryObjectParameterivEXT(memoryObject.name, pname, params); AddResourceInitChunk(memoryObject); } return true; } void WrappedOpenGL::glMemoryObjectParameterivEXT(GLuint memoryObject, GLenum pname, const GLint *params) { SERIALISE_TIME_CALL(GL.glMemoryObjectParameterivEXT(memoryObject, pname, params)); if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(ExtMemRes(GetCtx(), memoryObject)); if(!record) { RDCERR(""Called glMemoryObjectParameterivEXT with invalid/unrecognised memory object""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glMemoryObjectParameterivEXT(ser, memoryObject, pname, params); if(IsActiveCapturing(m_State)) { GetContextRecord()->AddChunk(scope.Get()); GetResourceManager()->MarkResourceFrameReferenced(record->GetResourceID(), eFrameRef_Read); } else { record->AddChunk(scope.Get()); } } } template bool WrappedOpenGL::Serialise_glImportMemoryFdEXT(SerialiserType &ser, GLuint memoryHandle, GLuint64 size, GLenum handleType, GLint fd) { SERIALISE_ELEMENT_LOCAL(memory, ExtMemRes(GetCtx(), memoryHandle)); SERIALISE_ELEMENT(size); SERIALISE_ELEMENT(handleType); SERIALISE_ELEMENT(fd); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // nothing to do - we don't replay external memory we just allocate textures/buffers with their // own backing store. Keep this around for tracking purposes AddResourceInitChunk(memory); } return true; } void WrappedOpenGL::glImportMemoryFdEXT(GLuint memory, GLuint64 size, GLenum handleType, GLint fd) { SERIALISE_TIME_CALL(GL.glImportMemoryFdEXT(memory, size, handleType, fd)); if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(ExtMemRes(GetCtx(), memory)); if(!record) { RDCERR(""Called glImportMemoryFdEXT with invalid/unrecognised memory object""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glImportMemoryFdEXT(ser, memory, size, handleType, fd); record->AddChunk(scope.Get()); } } template bool WrappedOpenGL::Serialise_glImportMemoryWin32HandleEXT(SerialiserType &ser, GLuint memoryHandle, GLuint64 size, GLenum handleType, void *handlePtr) { SERIALISE_ELEMENT_LOCAL(memory, ExtMemRes(GetCtx(), memoryHandle)); SERIALISE_ELEMENT(size); SERIALISE_ELEMENT(handleType); SERIALISE_ELEMENT_LOCAL(handle, uint64_t(handlePtr)); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // nothing to do - we don't replay external memory we just allocate textures/buffers with their // own backing store. Keep this around for tracking purposes AddResourceInitChunk(memory); } return true; } void WrappedOpenGL::glImportMemoryWin32HandleEXT(GLuint memory, GLuint64 size, GLenum handleType, void *handle) { SERIALISE_TIME_CALL(GL.glImportMemoryWin32HandleEXT(memory, size, handleType, handle)); if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(ExtMemRes(GetCtx(), memory)); if(!record) { RDCERR(""Called glImportMemoryWin32HandleEXT with invalid/unrecognised memory object""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glImportMemoryWin32HandleEXT(ser, memory, size, handleType, handle); record->AddChunk(scope.Get()); } } template bool WrappedOpenGL::Serialise_glImportMemoryWin32NameEXT(SerialiserType &ser, GLuint memoryHandle, GLuint64 size, GLenum handleType, const void *namePtr) { SERIALISE_ELEMENT_LOCAL(memory, ExtMemRes(GetCtx(), memoryHandle)); SERIALISE_ELEMENT(size); SERIALISE_ELEMENT(handleType); SERIALISE_ELEMENT_LOCAL(name, StringFormat::Wide2UTF8((const wchar_t *)namePtr)); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // nothing to do - we don't replay external memory we just allocate textures/buffers with their // own backing store. Keep this around for tracking purposes AddResourceInitChunk(memory); } return true; } void WrappedOpenGL::glImportMemoryWin32NameEXT(GLuint memory, GLuint64 size, GLenum handleType, const void *name) { SERIALISE_TIME_CALL(GL.glImportMemoryWin32NameEXT(memory, size, handleType, name)); if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(ExtMemRes(GetCtx(), memory)); if(!record) { RDCERR(""Called glImportMemoryWin32NameEXT with invalid/unrecognised memory object""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glImportMemoryWin32NameEXT(ser, memory, size, handleType, name); record->AddChunk(scope.Get()); } } #pragma endregion #pragma region Semaphores template bool WrappedOpenGL::Serialise_glGenSemaphoresEXT(SerialiserType &ser, GLsizei n, GLuint *semaphores) { SERIALISE_ELEMENT(n); SERIALISE_ELEMENT_LOCAL(semaphore, GetResourceManager()->GetResID(ExtSemRes(GetCtx(), *semaphores))) .TypedAs(""GLResource""_lit); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { CheckReplayFunctionPresent(glGenSemaphoresEXT); GLuint real = 0; GL.glGenSemaphoresEXT(1, &real); GLResource res = ExtSemRes(GetCtx(), real); ResourceId live = m_ResourceManager->RegisterResource(res); GetResourceManager()->AddLiveResource(semaphore, res); AddResource(semaphore, ResourceType::Sync, ""Semaphore""); } return true; } void WrappedOpenGL::glGenSemaphoresEXT(GLsizei n, GLuint *semaphores) { SERIALISE_TIME_CALL(GL.glGenSemaphoresEXT(n, semaphores)); for(GLsizei i = 0; i < n; i++) { GLResource res = ExtSemRes(GetCtx(), semaphores[i]); ResourceId id = GetResourceManager()->RegisterResource(res); if(IsCaptureMode(m_State)) { Chunk *chunk = NULL; { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glGenSemaphoresEXT(ser, 1, semaphores + i); chunk = scope.Get(); } GLResourceRecord *record = GetResourceManager()->AddResourceRecord(id); RDCASSERT(record); record->AddChunk(chunk); } else { GetResourceManager()->AddLiveResource(id, res); } } } void WrappedOpenGL::glDeleteSemaphoresEXT(GLsizei n, const GLuint *semaphores) { for(GLsizei i = 0; i < n; i++) { GLResource res = ExtSemRes(GetCtx(), semaphores[i]); if(GetResourceManager()->HasCurrentResource(res)) { if(GetResourceManager()->HasResourceRecord(res)) GetResourceManager()->GetResourceRecord(res)->Delete(GetResourceManager()); GetResourceManager()->UnregisterResource(res); } } GL.glDeleteSemaphoresEXT(n, semaphores); } template bool WrappedOpenGL::Serialise_glSemaphoreParameterui64vEXT(SerialiserType &ser, GLuint semaphoreHandle, GLenum pname, const GLuint64 *params) { SERIALISE_ELEMENT_LOCAL(semaphore, ExtSemRes(GetCtx(), semaphoreHandle)); SERIALISE_ELEMENT(pname); // if other parameters are added in future that take more than one value, change the array count // here. SERIALISE_ELEMENT_ARRAY(params, 1U); SERIALISE_CHECK_READ_ERRORS(); RDCASSERT(pname == eGL_D3D12_FENCE_VALUE_EXT); if(IsReplayingAndReading()) { CheckReplayFunctionPresent(glSemaphoreParameterui64vEXT); GL.glSemaphoreParameterui64vEXT(semaphore.name, pname, params); AddResourceInitChunk(semaphore); } return true; } void WrappedOpenGL::glSemaphoreParameterui64vEXT(GLuint semaphore, GLenum pname, const GLuint64 *params) { SERIALISE_TIME_CALL(GL.glSemaphoreParameterui64vEXT(semaphore, pname, params)); if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(ExtSemRes(GetCtx(), semaphore)); if(!record) { RDCERR(""Called glSemaphoreParameterui64vEXT with invalid/unrecognised semaphore""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glSemaphoreParameterui64vEXT(ser, semaphore, pname, params); if(IsActiveCapturing(m_State)) { GetContextRecord()->AddChunk(scope.Get()); GetResourceManager()->MarkResourceFrameReferenced(record->GetResourceID(), eFrameRef_Read); } else { record->AddChunk(scope.Get()); } } } template bool WrappedOpenGL::Serialise_glImportSemaphoreFdEXT(SerialiserType &ser, GLuint semaphoreHandle, GLenum handleType, GLint fd) { SERIALISE_ELEMENT_LOCAL(semaphore, ExtSemRes(GetCtx(), semaphoreHandle)); SERIALISE_ELEMENT(handleType); SERIALISE_ELEMENT(fd); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // nothing to do - we don't replay semaphores we just fully glFinish() when we need to wait on // them (just in case). AddResourceInitChunk(semaphore); } return true; } void WrappedOpenGL::glImportSemaphoreFdEXT(GLuint semaphore, GLenum handleType, GLint fd) { SERIALISE_TIME_CALL(GL.glImportSemaphoreFdEXT(semaphore, handleType, fd)); if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(ExtSemRes(GetCtx(), semaphore)); if(!record) { RDCERR(""Called glImportSemaphoreFdEXT with invalid/unrecognised semaphore object""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glImportSemaphoreFdEXT(ser, semaphore, handleType, fd); record->AddChunk(scope.Get()); } } template bool WrappedOpenGL::Serialise_glImportSemaphoreWin32HandleEXT(SerialiserType &ser, GLuint semaphoreHandle, GLenum handleType, void *handlePtr) { SERIALISE_ELEMENT_LOCAL(semaphore, ExtSemRes(GetCtx(), semaphoreHandle)); SERIALISE_ELEMENT(handleType); SERIALISE_ELEMENT_LOCAL(handle, uint64_t(handlePtr)); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // nothing to do - we don't replay semaphores we just fully glFinish() when we need to wait on // them (just in case). AddResourceInitChunk(semaphore); } return true; } void WrappedOpenGL::glImportSemaphoreWin32HandleEXT(GLuint semaphore, GLenum handleType, void *handle) { SERIALISE_TIME_CALL(GL.glImportSemaphoreWin32HandleEXT(semaphore, handleType, handle)); if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(ExtSemRes(GetCtx(), semaphore)); if(!record) { RDCERR(""Called glImportSemaphoreWin32HandleEXT with invalid/unrecognised semaphore object""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glImportSemaphoreWin32HandleEXT(ser, semaphore, handleType, handle); record->AddChunk(scope.Get()); } } template bool WrappedOpenGL::Serialise_glImportSemaphoreWin32NameEXT(SerialiserType &ser, GLuint semaphoreHandle, GLenum handleType, const void *namePtr) { SERIALISE_ELEMENT_LOCAL(semaphore, ExtSemRes(GetCtx(), semaphoreHandle)); SERIALISE_ELEMENT(handleType); SERIALISE_ELEMENT_LOCAL(name, StringFormat::Wide2UTF8((const wchar_t *)namePtr)); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // nothing to do - we don't replay semaphores we just fully glFinish() when we need to wait on // them (just in case). AddResourceInitChunk(semaphore); } return true; } void WrappedOpenGL::glImportSemaphoreWin32NameEXT(GLuint semaphore, GLenum handleType, const void *name) { SERIALISE_TIME_CALL(GL.glImportSemaphoreWin32NameEXT(semaphore, handleType, name)); if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(ExtSemRes(GetCtx(), semaphore)); if(!record) { RDCERR(""Called glImportSemaphoreWin32NameEXT with invalid/unrecognised semaphore object""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glImportSemaphoreWin32NameEXT(ser, semaphore, handleType, name); record->AddChunk(scope.Get()); } } template bool WrappedOpenGL::Serialise_glWaitSemaphoreEXT(SerialiserType &ser, GLuint semaphoreHandle, GLuint numBufferBarriers, const GLuint *bufferHandles, GLuint numTextureBarriers, const GLuint *textureHandles, const GLenum *srcLayouts) { // can't serialise arrays of GL handles since they're not wrapped or typed :(. rdcarray buffers, textures; if(ser.IsWriting()) { buffers.reserve(numBufferBarriers); for(GLuint i = 0; i < numBufferBarriers; i++) buffers.push_back(BufferRes(GetCtx(), bufferHandles ? bufferHandles[i] : 0)); textures.reserve(numTextureBarriers); for(GLuint i = 0; i < numTextureBarriers; i++) textures.push_back(TextureRes(GetCtx(), textureHandles ? textureHandles[i] : 0)); } SERIALISE_ELEMENT_LOCAL(semaphore, ExtSemRes(GetCtx(), semaphoreHandle)); SERIALISE_ELEMENT(numBufferBarriers); SERIALISE_ELEMENT(buffers); SERIALISE_ELEMENT(numTextureBarriers); SERIALISE_ELEMENT(textures); SERIALISE_ELEMENT_ARRAY(srcLayouts, numTextureBarriers); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // nothing to do - we don't replay semaphores we just fully glFinish() when we need to wait on // them (just in case). GL.glFinish(); } return true; } void WrappedOpenGL::glWaitSemaphoreEXT(GLuint semaphore, GLuint numBufferBarriers, const GLuint *buffers, GLuint numTextureBarriers, const GLuint *textures, const GLenum *srcLayouts) { SERIALISE_TIME_CALL(GL.glWaitSemaphoreEXT(semaphore, numBufferBarriers, buffers, numTextureBarriers, textures, srcLayouts)); if(IsActiveCapturing(m_State)) { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glWaitSemaphoreEXT(ser, semaphore, numBufferBarriers, buffers, numTextureBarriers, textures, srcLayouts); GetContextRecord()->AddChunk(scope.Get()); GetResourceManager()->MarkResourceFrameReferenced(ExtSemRes(GetCtx(), semaphore), eFrameRef_Read); for(GLuint b = 0; buffers && b < numBufferBarriers; b++) GetResourceManager()->MarkResourceFrameReferenced(BufferRes(GetCtx(), buffers[b]), eFrameRef_Read); for(GLuint t = 0; textures && t < numTextureBarriers; t++) GetResourceManager()->MarkResourceFrameReferenced(TextureRes(GetCtx(), textures[t]), eFrameRef_Read); } } template bool WrappedOpenGL::Serialise_glSignalSemaphoreEXT(SerialiserType &ser, GLuint semaphoreHandle, GLuint numBufferBarriers, const GLuint *bufferHandles, GLuint numTextureBarriers, const GLuint *textureHandles, const GLenum *dstLayouts) { // can't serialise arrays of GL handles since they're not wrapped or typed :(. rdcarray buffers, textures; if(ser.IsWriting()) { buffers.reserve(numBufferBarriers); for(GLuint i = 0; i < numBufferBarriers; i++) buffers.push_back(BufferRes(GetCtx(), bufferHandles ? bufferHandles[i] : 0)); textures.reserve(numTextureBarriers); for(GLuint i = 0; i < numTextureBarriers; i++) textures.push_back(TextureRes(GetCtx(), textureHandles ? textureHandles[i] : 0)); } SERIALISE_ELEMENT_LOCAL(semaphore, ExtSemRes(GetCtx(), semaphoreHandle)); SERIALISE_ELEMENT(numBufferBarriers); SERIALISE_ELEMENT(buffers); SERIALISE_ELEMENT(numTextureBarriers); SERIALISE_ELEMENT(textures); SERIALISE_ELEMENT_ARRAY(dstLayouts, numTextureBarriers); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // nothing to do - we don't replay semaphores we just fully glFinish() when we need to wait on // them (just in case). } return true; } void WrappedOpenGL::glSignalSemaphoreEXT(GLuint semaphore, GLuint numBufferBarriers, const GLuint *buffers, GLuint numTextureBarriers, const GLuint *textures, const GLenum *dstLayouts) { SERIALISE_TIME_CALL(GL.glSignalSemaphoreEXT(semaphore, numBufferBarriers, buffers, numTextureBarriers, textures, dstLayouts)); if(IsActiveCapturing(m_State)) { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glSignalSemaphoreEXT(ser, semaphore, numBufferBarriers, buffers, numTextureBarriers, textures, dstLayouts); GetContextRecord()->AddChunk(scope.Get()); GetResourceManager()->MarkResourceFrameReferenced(ExtSemRes(GetCtx(), semaphore), eFrameRef_Read); for(GLuint b = 0; buffers && b < numBufferBarriers; b++) GetResourceManager()->MarkResourceFrameReferenced(BufferRes(GetCtx(), buffers[b]), eFrameRef_Read); for(GLuint t = 0; textures && t < numTextureBarriers; t++) GetResourceManager()->MarkResourceFrameReferenced(TextureRes(GetCtx(), textures[t]), eFrameRef_Read); } } #pragma endregion #pragma region Keyed Mutexes template bool WrappedOpenGL::Serialise_glAcquireKeyedMutexWin32EXT(SerialiserType &ser, GLuint memoryHandle, GLuint64 key, GLuint timeout) { SERIALISE_ELEMENT_LOCAL(memory, ExtSemRes(GetCtx(), memoryHandle)); SERIALISE_ELEMENT(key); SERIALISE_ELEMENT(timeout); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // nothing to do - we don't replay keyed mutexes as we don't create external memory } return true; } GLboolean WrappedOpenGL::glAcquireKeyedMutexWin32EXT(GLuint memory, GLuint64 key, GLuint timeout) { GLboolean ret; SERIALISE_TIME_CALL(ret = GL.glAcquireKeyedMutexWin32EXT(memory, key, timeout)); if(IsActiveCapturing(m_State)) { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glAcquireKeyedMutexWin32EXT(ser, memory, key, timeout); GetContextRecord()->AddChunk(scope.Get()); GetResourceManager()->MarkResourceFrameReferenced(ExtMemRes(GetCtx(), memory), eFrameRef_Read); } return ret; } template bool WrappedOpenGL::Serialise_glReleaseKeyedMutexWin32EXT(SerialiserType &ser, GLuint memoryHandle, GLuint64 key) { SERIALISE_ELEMENT_LOCAL(memory, ExtSemRes(GetCtx(), memoryHandle)); SERIALISE_ELEMENT(key); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // nothing to do - we don't replay keyed mutexes as we don't create external memory } return true; } GLboolean WrappedOpenGL::glReleaseKeyedMutexWin32EXT(GLuint memory, GLuint64 key) { GLboolean ret; SERIALISE_TIME_CALL(ret = GL.glReleaseKeyedMutexWin32EXT(memory, key)); if(IsActiveCapturing(m_State)) { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glReleaseKeyedMutexWin32EXT(ser, memory, key); GetContextRecord()->AddChunk(scope.Get()); GetResourceManager()->MarkResourceFrameReferenced(ExtMemRes(GetCtx(), memory), eFrameRef_Read); } return ret; } #pragma endregion #pragma region Buffers template bool WrappedOpenGL::Serialise_glNamedBufferStorageMemEXT(SerialiserType &ser, GLuint bufferHandle, GLsizeiptr sizeptr, GLuint memoryHandle, GLuint64 offset) { SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle)); SERIALISE_ELEMENT_LOCAL(size, (uint64_t)sizeptr); SERIALISE_ELEMENT_LOCAL(memory, ExtMemRes(GetCtx(), memoryHandle)); SERIALISE_ELEMENT(offset); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // Replay external buffer storage backed by external memory as just a plain buffer. // we have to come up with flags that will work regardless, so we're conservative here. // The spec says memory object backed buffers can't be mapped, but we set DYNAMIC_STORAGE as // it's unclear if they can be updated with glBufferSubData or not. GLbitfield flags = eGL_DYNAMIC_STORAGE_BIT; GL.glNamedBufferStorageEXT(buffer.name, (GLsizeiptr)size, NULL, flags); ResourceId id = GetResourceManager()->GetResID(buffer); m_Buffers[id].size = size; AddResourceInitChunk(buffer); DerivedResource(memory, GetResourceManager()->GetOriginalID(id)); } return true; } void WrappedOpenGL::glNamedBufferStorageMemEXT(GLuint buffer, GLsizeiptr size, GLuint memory, GLuint64 offset) { SERIALISE_TIME_CALL(GL.glNamedBufferStorageMemEXT(buffer, size, memory, offset)); if(IsCaptureMode(m_State)) { GLResourceRecord *bufrecord = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)); GLResourceRecord *memrecord = GetResourceManager()->GetResourceRecord(ExtMemRes(GetCtx(), memory)); if(!bufrecord) { RDCERR(""Called glNamedBufferStorageMemEXT with invalid buffer""); return; } if(!memrecord) { RDCERR(""Called glNamedBufferStorageMemEXT with invalid memory object""); return; } // when bound to external memory, immediately consider dirty GetResourceManager()->MarkDirtyResource(bufrecord->Resource); USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glNamedBufferStorageMemEXT(ser, buffer, size, memory, offset); bufrecord->AddChunk(scope.Get()); bufrecord->AddParent(memrecord); bufrecord->Length = (int32_t)size; } } void WrappedOpenGL::glBufferStorageMemEXT(GLenum target, GLsizeiptr size, GLuint memory, GLuint64 offset) { SERIALISE_TIME_CALL(GL.glBufferStorageMemEXT(target, size, memory, offset)); if(IsCaptureMode(m_State)) { GLResourceRecord *bufrecord = GetCtxData().m_BufferRecord[BufferIdx(target)]; GLResourceRecord *memrecord = GetResourceManager()->GetResourceRecord(ExtMemRes(GetCtx(), memory)); if(!bufrecord) { RDCERR(""Called glBufferStorageMemEXT with no buffer bound to %s"", ToStr(target).c_str()); return; } if(!memrecord) { RDCERR(""Called glNamedBufferStorageMemEXT with invalid memory object""); return; } // when bound to external memory, immediately consider dirty GetResourceManager()->MarkDirtyResource(bufrecord->Resource); USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glNamedBufferStorageMemEXT(ser, bufrecord->Resource.name, size, memory, offset); bufrecord->AddChunk(scope.Get()); bufrecord->AddParent(memrecord); bufrecord->Length = (int32_t)size; } } #pragma endregion #pragma region Textures template bool WrappedOpenGL::Serialise_glTextureStorageMem1DEXT(SerialiserType &ser, GLuint textureHandle, GLsizei levels, GLenum internalFormat, GLsizei width, GLuint memoryHandle, GLuint64 offset) { SERIALISE_ELEMENT_LOCAL(texture, TextureRes(GetCtx(), textureHandle)); SERIALISE_ELEMENT(levels); SERIALISE_ELEMENT(internalFormat); SERIALISE_ELEMENT(width); SERIALISE_ELEMENT_LOCAL(memory, ExtMemRes(GetCtx(), memoryHandle)); SERIALISE_ELEMENT(offset); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // Replay external texture storage backed by external memory as just a plain texture. ResourceId liveId = GetResourceManager()->GetResID(texture); m_Textures[liveId].width = width; m_Textures[liveId].height = 1; m_Textures[liveId].depth = 1; m_Textures[liveId].dimension = 1; m_Textures[liveId].internalFormat = internalFormat; m_Textures[liveId].emulated = false; m_Textures[liveId].mipsValid = (1 << levels) - 1; GL.glTextureStorage1DEXT(texture.name, m_Textures[liveId].curType, levels, internalFormat, width); AddResourceInitChunk(texture); DerivedResource(memory, GetResourceManager()->GetOriginalID(liveId)); } return true; } void WrappedOpenGL::glTextureStorageMem1DEXT(GLuint texture, GLsizei levels, GLenum internalFormat, GLsizei width, GLuint memory, GLuint64 offset) { SERIALISE_TIME_CALL( GL.glTextureStorageMem1DEXT(texture, levels, internalFormat, width, memory, offset)); if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(TextureRes(GetCtx(), texture)); if(!record) { RDCERR(""Calling glTextureStorageMem1DEXT with unrecognised texture""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glTextureStorageMem1DEXT(ser, texture, levels, internalFormat, width, memory, offset); record->AddChunk(scope.Get()); // when bound to external memory, immediately consider dirty GetResourceManager()->MarkDirtyResource(record->Resource); ResourceId texId = record->GetResourceID(); m_Textures[texId].width = width; m_Textures[texId].height = 1; m_Textures[texId].depth = 1; m_Textures[texId].dimension = 1; m_Textures[texId].internalFormat = internalFormat; m_Textures[texId].mipsValid = (1 << levels) - 1; } } void WrappedOpenGL::glTexStorageMem1DEXT(GLenum target, GLsizei levels, GLenum internalFormat, GLsizei width, GLuint memory, GLuint64 offset) { SERIALISE_TIME_CALL(GL.glTexStorageMem1DEXT(target, levels, internalFormat, width, memory, offset)); if(IsCaptureMode(m_State) && !IsProxyTarget(target)) { GLResourceRecord *record = GetCtxData().GetActiveTexRecord(target); if(!record) { RDCERR(""Calling glTextureStorageMem1DEXT with no texture bound""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glTextureStorageMem1DEXT(ser, record->Resource.name, levels, internalFormat, width, memory, offset); record->AddChunk(scope.Get()); // when bound to external memory, immediately consider dirty GetResourceManager()->MarkDirtyResource(record->Resource); ResourceId texId = record->GetResourceID(); m_Textures[texId].width = width; m_Textures[texId].height = 1; m_Textures[texId].depth = 1; m_Textures[texId].dimension = 1; m_Textures[texId].internalFormat = internalFormat; m_Textures[texId].mipsValid = (1 << levels) - 1; } } template bool WrappedOpenGL::Serialise_glTextureStorageMem2DEXT(SerialiserType &ser, GLuint textureHandle, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLuint memoryHandle, GLuint64 offset) { SERIALISE_ELEMENT_LOCAL(texture, TextureRes(GetCtx(), textureHandle)); SERIALISE_ELEMENT(levels); SERIALISE_ELEMENT(internalFormat); SERIALISE_ELEMENT(width); SERIALISE_ELEMENT(height); SERIALISE_ELEMENT_LOCAL(memory, ExtMemRes(GetCtx(), memoryHandle)); SERIALISE_ELEMENT(offset); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // Replay external texture storage backed by external memory as just a plain texture. ResourceId liveId = GetResourceManager()->GetResID(texture); m_Textures[liveId].width = width; m_Textures[liveId].height = height; m_Textures[liveId].depth = 1; m_Textures[liveId].dimension = 2; m_Textures[liveId].internalFormat = internalFormat; m_Textures[liveId].emulated = false; m_Textures[liveId].mipsValid = (1 << levels) - 1; GL.glTextureStorage2DEXT(texture.name, m_Textures[liveId].curType, levels, internalFormat, width, height); AddResourceInitChunk(texture); DerivedResource(memory, GetResourceManager()->GetOriginalID(liveId)); } return true; } void WrappedOpenGL::glTextureStorageMem2DEXT(GLuint texture, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLuint memory, GLuint64 offset) { SERIALISE_TIME_CALL( GL.glTextureStorageMem2DEXT(texture, levels, internalFormat, width, height, memory, offset)); if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(TextureRes(GetCtx(), texture)); if(!record) { RDCERR(""Calling glTextureStorageMem2DEXT with unrecognised texture""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glTextureStorageMem2DEXT(ser, texture, levels, internalFormat, width, height, memory, offset); record->AddChunk(scope.Get()); // when bound to external memory, immediately consider dirty GetResourceManager()->MarkDirtyResource(record->Resource); ResourceId texId = record->GetResourceID(); m_Textures[texId].width = width; m_Textures[texId].height = height; m_Textures[texId].depth = 1; m_Textures[texId].dimension = 2; m_Textures[texId].internalFormat = internalFormat; m_Textures[texId].mipsValid = (1 << levels) - 1; } } void WrappedOpenGL::glTexStorageMem2DEXT(GLenum target, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLuint memory, GLuint64 offset) { SERIALISE_TIME_CALL( GL.glTexStorageMem2DEXT(target, levels, internalFormat, width, height, memory, offset)); if(IsCaptureMode(m_State) && !IsProxyTarget(target)) { GLResourceRecord *record = GetCtxData().GetActiveTexRecord(target); if(!record) { RDCERR(""Calling glTextureStorageMem2DEXT with no texture bound""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glTextureStorageMem2DEXT(ser, record->Resource.name, levels, internalFormat, width, height, memory, offset); record->AddChunk(scope.Get()); // when bound to external memory, immediately consider dirty GetResourceManager()->MarkDirtyResource(record->Resource); ResourceId texId = record->GetResourceID(); m_Textures[texId].width = width; m_Textures[texId].height = height; m_Textures[texId].depth = 1; m_Textures[texId].dimension = 2; m_Textures[texId].internalFormat = internalFormat; m_Textures[texId].mipsValid = (1 << levels) - 1; } } template bool WrappedOpenGL::Serialise_glTextureStorageMem2DMultisampleEXT( SerialiserType &ser, GLuint textureHandle, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations, GLuint memoryHandle, GLuint64 offset) { SERIALISE_ELEMENT_LOCAL(texture, TextureRes(GetCtx(), textureHandle)); SERIALISE_ELEMENT(samples); SERIALISE_ELEMENT(internalFormat); SERIALISE_ELEMENT(width); SERIALISE_ELEMENT(height); SERIALISE_ELEMENT_TYPED(bool, fixedSampleLocations); SERIALISE_ELEMENT_LOCAL(memory, ExtMemRes(GetCtx(), memoryHandle)); SERIALISE_ELEMENT(offset); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // the DSA function is emulated if not present, but we need to check the underlying function is // present CheckReplayFunctionPresent(glTexStorage2DMultisample); // Replay external texture storage backed by external memory as just a plain texture. ResourceId liveId = GetResourceManager()->GetResID(texture); m_Textures[liveId].width = width; m_Textures[liveId].height = height; m_Textures[liveId].depth = 1; m_Textures[liveId].samples = samples; m_Textures[liveId].dimension = 2; m_Textures[liveId].internalFormat = internalFormat; m_Textures[liveId].emulated = false; m_Textures[liveId].mipsValid = 1; GL.glTextureStorage2DMultisampleEXT(texture.name, m_Textures[liveId].curType, samples, internalFormat, width, height, fixedSampleLocations); AddResourceInitChunk(texture); DerivedResource(memory, GetResourceManager()->GetOriginalID(liveId)); } return true; } void WrappedOpenGL::glTextureStorageMem2DMultisampleEXT(GLuint texture, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset) { SERIALISE_TIME_CALL(GL.glTextureStorageMem2DMultisampleEXT( texture, samples, internalFormat, width, height, fixedSampleLocations, memory, offset)); if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(TextureRes(GetCtx(), texture)); if(!record) { RDCERR(""Calling glTextureStorageMem2DMultisampleEXT with unrecognised texture""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glTextureStorageMem2DMultisampleEXT(ser, texture, samples, internalFormat, width, height, fixedSampleLocations, memory, offset); record->AddChunk(scope.Get()); // when bound to external memory, immediately consider dirty GetResourceManager()->MarkDirtyResource(record->Resource); ResourceId texId = record->GetResourceID(); m_Textures[texId].width = width; m_Textures[texId].height = height; m_Textures[texId].samples = samples; m_Textures[texId].depth = 1; m_Textures[texId].dimension = 2; m_Textures[texId].internalFormat = internalFormat; m_Textures[texId].mipsValid = 1; } } void WrappedOpenGL::glTexStorageMem2DMultisampleEXT(GLenum target, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset) { SERIALISE_TIME_CALL(GL.glTexStorageMem2DMultisampleEXT( target, samples, internalFormat, width, height, fixedSampleLocations, memory, offset)); if(IsCaptureMode(m_State) && !IsProxyTarget(target)) { GLResourceRecord *record = GetCtxData().GetActiveTexRecord(target); if(!record) { RDCERR(""Calling glTexStorageMem2DMultisampleEXT with no texture bound""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glTextureStorageMem2DMultisampleEXT(ser, record->Resource.name, samples, internalFormat, width, height, fixedSampleLocations, memory, offset); record->AddChunk(scope.Get()); GetResourceManager()->MarkDirtyResource(record->Resource); ResourceId texId = record->GetResourceID(); m_Textures[texId].width = width; m_Textures[texId].height = height; m_Textures[texId].samples = samples; m_Textures[texId].depth = 1; m_Textures[texId].dimension = 2; m_Textures[texId].internalFormat = internalFormat; m_Textures[texId].mipsValid = 1; } } template bool WrappedOpenGL::Serialise_glTextureStorageMem3DEXT(SerialiserType &ser, GLuint textureHandle, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLuint memoryHandle, GLuint64 offset) { SERIALISE_ELEMENT_LOCAL(texture, TextureRes(GetCtx(), textureHandle)); SERIALISE_ELEMENT(levels); SERIALISE_ELEMENT(internalFormat); SERIALISE_ELEMENT(width); SERIALISE_ELEMENT(height); SERIALISE_ELEMENT(depth); SERIALISE_ELEMENT_LOCAL(memory, ExtMemRes(GetCtx(), memoryHandle)); SERIALISE_ELEMENT(offset); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // Replay external texture storage backed by external memory as just a plain texture. ResourceId liveId = GetResourceManager()->GetResID(texture); m_Textures[liveId].width = width; m_Textures[liveId].height = height; m_Textures[liveId].depth = depth; m_Textures[liveId].dimension = 3; m_Textures[liveId].internalFormat = internalFormat; m_Textures[liveId].emulated = false; m_Textures[liveId].mipsValid = (1 << levels) - 1; GL.glTextureStorage3DEXT(texture.name, m_Textures[liveId].curType, levels, internalFormat, width, height, depth); AddResourceInitChunk(texture); DerivedResource(memory, GetResourceManager()->GetOriginalID(liveId)); } return true; } void WrappedOpenGL::glTextureStorageMem3DEXT(GLuint texture, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLuint memory, GLuint64 offset) { SERIALISE_TIME_CALL(GL.glTextureStorageMem3DEXT(texture, levels, internalFormat, width, height, depth, memory, offset)); if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(TextureRes(GetCtx(), texture)); if(!record) { RDCERR(""Calling glTextureStorageMem3DEXT with unrecognised texture""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glTextureStorageMem3DEXT(ser, texture, levels, internalFormat, width, height, depth, memory, offset); record->AddChunk(scope.Get()); GetResourceManager()->MarkDirtyResource(record->Resource); ResourceId texId = record->GetResourceID(); m_Textures[texId].width = width; m_Textures[texId].height = height; m_Textures[texId].depth = depth; m_Textures[texId].dimension = 3; m_Textures[texId].internalFormat = internalFormat; m_Textures[texId].mipsValid = (1 << levels) - 1; } } void WrappedOpenGL::glTexStorageMem3DEXT(GLenum target, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLuint memory, GLuint64 offset) { SERIALISE_TIME_CALL(GL.glTexStorageMem3DEXT(target, levels, internalFormat, width, height, depth, memory, offset)); if(IsCaptureMode(m_State) && !IsProxyTarget(target)) { GLResourceRecord *record = GetCtxData().GetActiveTexRecord(target); if(!record) { RDCERR(""Calling glTextureStorageMem3DEXT with no texture bound""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glTextureStorageMem3DEXT(ser, record->Resource.name, levels, internalFormat, width, height, depth, memory, offset); record->AddChunk(scope.Get()); GetResourceManager()->MarkDirtyResource(record->Resource); ResourceId texId = record->GetResourceID(); m_Textures[texId].width = width; m_Textures[texId].height = height; m_Textures[texId].depth = depth; m_Textures[texId].dimension = 3; m_Textures[texId].internalFormat = internalFormat; m_Textures[texId].mipsValid = (1 << levels) - 1; } } template bool WrappedOpenGL::Serialise_glTextureStorageMem3DMultisampleEXT( SerialiserType &ser, GLuint textureHandle, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations, GLuint memoryHandle, GLuint64 offset) { SERIALISE_ELEMENT_LOCAL(texture, TextureRes(GetCtx(), textureHandle)); SERIALISE_ELEMENT(samples); SERIALISE_ELEMENT(internalFormat); SERIALISE_ELEMENT(width); SERIALISE_ELEMENT(height); SERIALISE_ELEMENT(depth); SERIALISE_ELEMENT_TYPED(bool, fixedSampleLocations); SERIALISE_ELEMENT_LOCAL(memory, ExtMemRes(GetCtx(), memoryHandle)); SERIALISE_ELEMENT(offset); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // Replay external texture storage backed by external memory as just a plain texture. ResourceId liveId = GetResourceManager()->GetResID(texture); m_Textures[liveId].width = width; m_Textures[liveId].height = height; m_Textures[liveId].depth = depth; m_Textures[liveId].samples = samples; m_Textures[liveId].dimension = 3; m_Textures[liveId].internalFormat = internalFormat; m_Textures[liveId].emulated = false; m_Textures[liveId].mipsValid = 1; GL.glTextureStorage3DMultisampleEXT(texture.name, m_Textures[liveId].curType, samples, internalFormat, width, height, depth, fixedSampleLocations); AddResourceInitChunk(texture); DerivedResource(memory, GetResourceManager()->GetOriginalID(liveId)); } return true; } void WrappedOpenGL::glTextureStorageMem3DMultisampleEXT(GLuint texture, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset) { SERIALISE_TIME_CALL(GL.glTextureStorageMem3DMultisampleEXT( texture, samples, internalFormat, width, height, depth, fixedSampleLocations, memory, offset)); if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(TextureRes(GetCtx(), texture)); if(!record) { RDCERR(""Calling glTextureStorageMem3DMultisampleEXT with unrecognised texture""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glTextureStorageMem3DMultisampleEXT(ser, texture, samples, internalFormat, width, height, depth, fixedSampleLocations, memory, offset); record->AddChunk(scope.Get()); GetResourceManager()->MarkDirtyResource(record->Resource); ResourceId texId = record->GetResourceID(); m_Textures[texId].width = width; m_Textures[texId].height = height; m_Textures[texId].samples = samples; m_Textures[texId].depth = depth; m_Textures[texId].dimension = 3; m_Textures[texId].internalFormat = internalFormat; m_Textures[texId].mipsValid = 1; } } void WrappedOpenGL::glTexStorageMem3DMultisampleEXT(GLenum target, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset) { SERIALISE_TIME_CALL(GL.glTexStorageMem3DMultisampleEXT( target, samples, internalFormat, width, height, depth, fixedSampleLocations, memory, offset)); if(IsCaptureMode(m_State) && !IsProxyTarget(target)) { GLResourceRecord *record = GetCtxData().GetActiveTexRecord(target); if(!record) { RDCERR(""Calling glTexStorageMem3DMultisampleEXT with no texture bound""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glTextureStorageMem3DMultisampleEXT(ser, record->Resource.name, samples, internalFormat, width, height, depth, fixedSampleLocations, memory, offset); record->AddChunk(scope.Get()); GetResourceManager()->MarkDirtyResource(record->Resource); ResourceId texId = record->GetResourceID(); m_Textures[texId].width = width; m_Textures[texId].height = height; m_Textures[texId].samples = samples; m_Textures[texId].depth = depth; m_Textures[texId].dimension = 3; m_Textures[texId].internalFormat = internalFormat; m_Textures[texId].mipsValid = 1; } } #pragma endregion INSTANTIATE_FUNCTION_SERIALISED(void, wglDXRegisterObjectNV, GLResource Resource, GLenum type, void *dxObject); INSTANTIATE_FUNCTION_SERIALISED(void, wglDXLockObjectsNV, GLResource Resource); INSTANTIATE_FUNCTION_SERIALISED(void, glCreateMemoryObjectsEXT, GLsizei n, GLuint *memoryObjects); INSTANTIATE_FUNCTION_SERIALISED(void, glMemoryObjectParameterivEXT, GLuint memoryObject, GLenum pname, const GLint *params); INSTANTIATE_FUNCTION_SERIALISED(void, glTextureStorageMem1DEXT, GLuint texture, GLsizei levels, GLenum internalFormat, GLsizei width, GLuint memory, GLuint64 offset); INSTANTIATE_FUNCTION_SERIALISED(void, glTextureStorageMem2DEXT, GLuint texture, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLuint memory, GLuint64 offset); INSTANTIATE_FUNCTION_SERIALISED(void, glTextureStorageMem2DMultisampleEXT, GLuint texture, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset); INSTANTIATE_FUNCTION_SERIALISED(void, glTextureStorageMem3DEXT, GLuint texture, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLuint memory, GLuint64 offset); INSTANTIATE_FUNCTION_SERIALISED(void, glTextureStorageMem3DMultisampleEXT, GLuint texture, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset); INSTANTIATE_FUNCTION_SERIALISED(void, glNamedBufferStorageMemEXT, GLuint buffer, GLsizeiptr size, GLuint memory, GLuint64 offset); INSTANTIATE_FUNCTION_SERIALISED(void, glGenSemaphoresEXT, GLsizei n, GLuint *semaphores); INSTANTIATE_FUNCTION_SERIALISED(void, glSemaphoreParameterui64vEXT, GLuint semaphore, GLenum pname, const GLuint64 *params); INSTANTIATE_FUNCTION_SERIALISED(void, glWaitSemaphoreEXT, GLuint semaphore, GLuint numBufferBarriers, const GLuint *buffers, GLuint numTextureBarriers, const GLuint *textures, const GLenum *srcLayouts); INSTANTIATE_FUNCTION_SERIALISED(void, glSignalSemaphoreEXT, GLuint semaphore, GLuint numBufferBarriers, const GLuint *buffers, GLuint numTextureBarriers, const GLuint *textures, const GLenum *dstLayouts); INSTANTIATE_FUNCTION_SERIALISED(void, glImportMemoryFdEXT, GLuint memory, GLuint64 size, GLenum handleType, GLint fd); INSTANTIATE_FUNCTION_SERIALISED(void, glImportSemaphoreFdEXT, GLuint semaphore, GLenum handleType, GLint fd); INSTANTIATE_FUNCTION_SERIALISED(void, glImportMemoryWin32HandleEXT, GLuint memory, GLuint64 size, GLenum handleType, void *handle); INSTANTIATE_FUNCTION_SERIALISED(void, glImportMemoryWin32NameEXT, GLuint memory, GLuint64 size, GLenum handleType, const void *name); INSTANTIATE_FUNCTION_SERIALISED(void, glImportSemaphoreWin32HandleEXT, GLuint semaphore, GLenum handleType, void *handle); INSTANTIATE_FUNCTION_SERIALISED(void, glImportSemaphoreWin32NameEXT, GLuint semaphore, GLenum handleType, const void *name); INSTANTIATE_FUNCTION_SERIALISED(GLboolean, glAcquireKeyedMutexWin32EXT, GLuint memory, GLuint64 key, GLuint timeout); INSTANTIATE_FUNCTION_SERIALISED(GLboolean, glReleaseKeyedMutexWin32EXT, GLuint memory, GLuint64 key); ",16164,True,3575.4697881899724,median "CLASS zcl_excel_converter DEFINITION PUBLIC CREATE PUBLIC . *""* public components of class ZCL_EXCEL_CONVERTER *""* do not include other source files here!!! PUBLIC SECTION. TYPE-POOLS abap . CLASS-METHODS class_constructor . METHODS ask_option RETURNING VALUE(rs_option) TYPE zexcel_s_converter_option RAISING zcx_excel . METHODS convert IMPORTING !is_option TYPE zexcel_s_converter_option OPTIONAL !io_alv TYPE REF TO object OPTIONAL !it_table TYPE STANDARD TABLE OPTIONAL !i_row_int TYPE i DEFAULT 1 !i_column_int TYPE i DEFAULT 1 !i_table TYPE flag OPTIONAL !i_style_table TYPE zexcel_table_style OPTIONAL !io_worksheet TYPE REF TO zcl_excel_worksheet OPTIONAL CHANGING !co_excel TYPE REF TO zcl_excel OPTIONAL RAISING zcx_excel . METHODS create_path RETURNING VALUE(r_path) TYPE string . METHODS get_file EXPORTING !e_bytecount TYPE i !et_file TYPE solix_tab !e_file TYPE xstring . METHODS get_option RETURNING VALUE(rs_option) TYPE zexcel_s_converter_option . METHODS open_file . METHODS set_option IMPORTING !is_option TYPE zexcel_s_converter_option . METHODS write_file IMPORTING !i_path TYPE string OPTIONAL . *""* protected components of class ZCL_EXCEL_CONVERTER *""* do not include other source files here!!! PROTECTED SECTION. TYPES: BEGIN OF t_relationship, id TYPE string, type TYPE string, target TYPE string, END OF t_relationship . TYPES: BEGIN OF t_fileversion, appname TYPE string, lastedited TYPE string, lowestedited TYPE string, rupbuild TYPE string, codename TYPE string, END OF t_fileversion . TYPES: BEGIN OF t_sheet, name TYPE string, sheetid TYPE string, id TYPE string, END OF t_sheet . TYPES: BEGIN OF t_workbookpr, codename TYPE string, defaultthemeversion TYPE string, END OF t_workbookpr . TYPES: BEGIN OF t_sheetpr, codename TYPE string, END OF t_sheetpr . DATA w_row_int TYPE zexcel_cell_row VALUE 1. ""#EC NOTEXT . . . . . . . . . . "" . DATA w_col_int TYPE zexcel_cell_column VALUE 1. ""#EC NOTEXT . . . . . . . . . . "" . *""* private components of class ZCL_EXCEL_CONVERTER *""* do not include other source files here!!! PRIVATE SECTION. CLASS-METHODS get_subclasses IMPORTING is_clskey TYPE seoclskey CHANGING ct_classes TYPE seor_implementing_keys. DATA wo_excel TYPE REF TO zcl_excel . DATA wo_worksheet TYPE REF TO zcl_excel_worksheet . DATA wo_autofilter TYPE REF TO zcl_excel_autofilter . DATA wo_table TYPE REF TO data . DATA wo_data TYPE REF TO data . DATA wt_fieldcatalog TYPE zexcel_t_converter_fcat . DATA ws_layout TYPE zexcel_s_converter_layo . DATA wt_colors TYPE zexcel_t_converter_col . DATA wt_filter TYPE zexcel_t_converter_fil . CLASS-DATA wt_objects TYPE tt_alv_types . CLASS-DATA w_fcount TYPE numc3 . DATA wt_sort_values TYPE tt_sort_values . DATA wt_subtotal_rows TYPE tt_subtotal_rows . DATA wt_styles TYPE tt_styles . CONSTANTS c_type_hdr TYPE c VALUE 'H'. ""#EC NOTEXT CONSTANTS c_type_str TYPE c VALUE 'P'. ""#EC NOTEXT CONSTANTS c_type_nor TYPE c VALUE 'N'. ""#EC NOTEXT CONSTANTS c_type_sub TYPE c VALUE 'S'. ""#EC NOTEXT CONSTANTS c_type_tot TYPE c VALUE 'T'. ""#EC NOTEXT DATA wt_color_styles TYPE tt_color_styles . CLASS-DATA ws_option TYPE zexcel_s_converter_option . CLASS-DATA ws_indx TYPE indx . CLASS-METHODS init_option . CLASS-METHODS get_alv_converters. METHODS bind_table IMPORTING !i_style_table TYPE zexcel_table_style RETURNING VALUE(r_freeze_col) TYPE int1 RAISING zcx_excel . METHODS bind_cells RETURNING VALUE(r_freeze_col) TYPE int1 RAISING zcx_excel . METHODS clean_fieldcatalog . METHODS create_color_style IMPORTING !i_style TYPE zexcel_cell_style !is_colors TYPE zexcel_s_converter_col RETURNING VALUE(ro_style) TYPE REF TO zcl_excel_style . METHODS create_formular_subtotal IMPORTING !i_row_int_start TYPE zexcel_cell_row !i_row_int_end TYPE zexcel_cell_row !i_column TYPE zexcel_cell_column_alpha !i_totals_function TYPE zexcel_table_totals_function RETURNING VALUE(r_formula) TYPE string . METHODS create_formular_total IMPORTING !i_row_int TYPE zexcel_cell_row !i_column TYPE zexcel_cell_column_alpha !i_totals_function TYPE zexcel_table_totals_function RETURNING VALUE(r_formula) TYPE string . METHODS create_style_hdr IMPORTING !i_alignment TYPE zexcel_alignment OPTIONAL RETURNING VALUE(ro_style) TYPE REF TO zcl_excel_style . METHODS create_style_normal IMPORTING !i_alignment TYPE zexcel_alignment OPTIONAL !i_inttype TYPE inttype OPTIONAL !i_decimals TYPE int1 OPTIONAL RETURNING VALUE(ro_style) TYPE REF TO zcl_excel_style . METHODS create_style_stripped IMPORTING !i_alignment TYPE zexcel_alignment OPTIONAL !i_inttype TYPE inttype OPTIONAL !i_decimals TYPE int1 OPTIONAL RETURNING VALUE(ro_style) TYPE REF TO zcl_excel_style . METHODS create_style_subtotal IMPORTING !i_alignment TYPE zexcel_alignment OPTIONAL !i_inttype TYPE inttype OPTIONAL !i_decimals TYPE int1 OPTIONAL RETURNING VALUE(ro_style) TYPE REF TO zcl_excel_style . METHODS create_style_total IMPORTING !i_alignment TYPE zexcel_alignment OPTIONAL !i_inttype TYPE inttype OPTIONAL !i_decimals TYPE int1 OPTIONAL RETURNING VALUE(ro_style) TYPE REF TO zcl_excel_style . METHODS create_table . METHODS create_text_subtotal IMPORTING !i_value TYPE any !i_totals_function TYPE zexcel_table_totals_function RETURNING VALUE(r_text) TYPE string . METHODS create_worksheet IMPORTING !i_table TYPE flag DEFAULT 'X' !i_style_table TYPE zexcel_table_style RAISING zcx_excel . METHODS execute_converter IMPORTING !io_object TYPE REF TO object !it_table TYPE STANDARD TABLE RAISING zcx_excel . METHODS get_color_style IMPORTING !i_row TYPE zexcel_cell_row !i_fieldname TYPE fieldname !i_style TYPE zexcel_cell_style RETURNING VALUE(r_style) TYPE zexcel_cell_style . METHODS get_function_number IMPORTING !i_totals_function TYPE zexcel_table_totals_function RETURNING VALUE(r_function_number) TYPE int1 . METHODS get_style IMPORTING !i_type TYPE ty_style_type !i_alignment TYPE zexcel_alignment DEFAULT space !i_inttype TYPE inttype DEFAULT space !i_decimals TYPE int1 DEFAULT 0 RETURNING VALUE(r_style) TYPE zexcel_cell_style . METHODS loop_normal IMPORTING !i_row_int TYPE zexcel_cell_row !i_col_int TYPE zexcel_cell_column RETURNING VALUE(r_freeze_col) TYPE int1 RAISING zcx_excel . METHODS loop_subtotal IMPORTING !i_row_int TYPE zexcel_cell_row !i_col_int TYPE zexcel_cell_column RETURNING VALUE(r_freeze_col) TYPE int1 RAISING zcx_excel . METHODS set_autofilter_area . METHODS set_cell_format IMPORTING !i_inttype TYPE inttype !i_decimals TYPE int1 RETURNING VALUE(r_format) TYPE zexcel_number_format . METHODS set_fieldcatalog . ENDCLASS. CLASS zcl_excel_converter IMPLEMENTATION. METHOD ask_option. DATA: ls_sval TYPE sval, lt_sval TYPE STANDARD TABLE OF sval, l_returncode TYPE string, lt_fields TYPE ddfields, ls_fields TYPE dfies. FIELD-SYMBOLS: TYPE any. rs_option = ws_option. CALL FUNCTION 'DDIF_FIELDINFO_GET' EXPORTING tabname = 'ZEXCEL_S_CONVERTER_OPTION' TABLES dfies_tab = lt_fields EXCEPTIONS not_found = 1 internal_error = 2 OTHERS = 3. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF. LOOP AT lt_fields INTO ls_fields. ASSIGN COMPONENT ls_fields-fieldname OF STRUCTURE ws_option TO . IF sy-subrc = 0. CLEAR ls_sval. ls_sval-tabname = ls_fields-tabname. ls_sval-fieldname = ls_fields-fieldname. ls_sval-value = . ls_sval-field_attr = space. ls_sval-field_obl = space. ls_sval-comp_code = space. ls_sval-fieldtext = ls_fields-scrtext_m. ls_sval-comp_tab = space. ls_sval-comp_field = space. ls_sval-novaluehlp = space. INSERT ls_sval INTO TABLE lt_sval. ENDIF. ENDLOOP. CALL FUNCTION 'POPUP_GET_VALUES' EXPORTING popup_title = 'Excel creation options'(008) IMPORTING returncode = l_returncode TABLES fields = lt_sval EXCEPTIONS error_in_fields = 1 OTHERS = 2. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ELSEIF l_returncode = 'A'. RAISE EXCEPTION TYPE zcx_excel. ELSE. LOOP AT lt_sval INTO ls_sval. ASSIGN COMPONENT ls_sval-fieldname OF STRUCTURE ws_option TO . IF sy-subrc = 0. = ls_sval-value. ENDIF. ENDLOOP. set_option( is_option = ws_option ) . rs_option = ws_option. ENDIF. ENDMETHOD. METHOD bind_cells. * Do we need subtotals with grouping READ TABLE wt_fieldcatalog TRANSPORTING NO FIELDS WITH KEY is_subtotalled = abap_true. IF sy-subrc = 0 . r_freeze_col = loop_subtotal( i_row_int = w_row_int i_col_int = w_col_int ) . ELSE. r_freeze_col = loop_normal( i_row_int = w_row_int i_col_int = w_col_int ) . ENDIF. ENDMETHOD. METHOD bind_table. DATA: lt_field_catalog TYPE zexcel_t_fieldcatalog, ls_field_catalog TYPE zexcel_s_fieldcatalog, ls_fcat TYPE zexcel_s_converter_fcat, lo_column TYPE REF TO zcl_excel_column, lv_col_int TYPE zexcel_cell_column, lv_col_alpha TYPE zexcel_cell_column_alpha, ls_settings TYPE zexcel_s_table_settings, lv_line TYPE i. FIELD-SYMBOLS: TYPE ANY TABLE. ASSIGN wo_data->* TO . ls_settings-table_style = i_style_table. ls_settings-top_left_column = zcl_excel_common=>convert_column2alpha( ip_column = w_col_int ). ls_settings-top_left_row = w_row_int. ls_settings-show_row_stripes = ws_layout-is_stripped. DESCRIBE TABLE wt_fieldcatalog LINES lv_line. lv_line = lv_line + 1 + w_col_int. ls_settings-bottom_right_column = zcl_excel_common=>convert_column2alpha( ip_column = lv_line ). DESCRIBE TABLE LINES lv_line. ls_settings-bottom_right_row = lv_line + 1 + w_row_int. SORT wt_fieldcatalog BY position. LOOP AT wt_fieldcatalog INTO ls_fcat. MOVE-CORRESPONDING ls_fcat TO ls_field_catalog. ls_field_catalog-dynpfld = abap_true. INSERT ls_field_catalog INTO TABLE lt_field_catalog. ENDLOOP. wo_worksheet->bind_table( EXPORTING ip_table = it_field_catalog = lt_field_catalog is_table_settings = ls_settings IMPORTING es_table_settings = ls_settings ). LOOP AT wt_fieldcatalog INTO ls_fcat. lv_col_int = w_col_int + ls_fcat-position - 1. lv_col_alpha = zcl_excel_common=>convert_column2alpha( lv_col_int ). * Freeze panes IF ls_fcat-fix_column = abap_true. ADD 1 TO r_freeze_col. ENDIF. * Now let's check for optimized IF ls_fcat-is_optimized = abap_true. lo_column = wo_worksheet->get_column( ip_column = lv_col_alpha ). lo_column->set_auto_size( ip_auto_size = abap_true ) . ENDIF. * Now let's check for visible IF ls_fcat-is_hidden = abap_true. lo_column = wo_worksheet->get_column( ip_column = lv_col_alpha ). lo_column->set_visible( ip_visible = abap_false ) . ENDIF. ENDLOOP. ENDMETHOD. METHOD class_constructor. DATA: ls_objects TYPE ts_alv_types. DATA: ls_option TYPE zexcel_s_converter_option, l_uname TYPE sy-uname. GET PARAMETER ID 'ZUS' FIELD l_uname. IF l_uname IS INITIAL OR l_uname = space. l_uname = sy-uname. ENDIF. get_alv_converters( ). CONCATENATE 'EXCEL_' sy-uname INTO ws_indx-srtfd. IMPORT p1 = ls_option FROM DATABASE indx(xl) TO ws_indx ID ws_indx-srtfd. IF sy-subrc = 0. ws_option = ls_option. ELSE. init_option( ) . ENDIF. ENDMETHOD. METHOD clean_fieldcatalog. DATA: l_position TYPE tabfdpos. FIELD-SYMBOLS: TYPE zexcel_s_converter_fcat. SORT wt_fieldcatalog BY position col_id. CLEAR l_position. LOOP AT wt_fieldcatalog ASSIGNING . ADD 1 TO l_position. -position = l_position. * Default stype with alignment and format -style_hdr = get_style( i_type = c_type_hdr i_alignment = -alignment ). IF ws_layout-is_stripped = abap_true. -style_stripped = get_style( i_type = c_type_str i_alignment = -alignment i_inttype = -inttype i_decimals = -decimals ). ENDIF. -style_normal = get_style( i_type = c_type_nor i_alignment = -alignment i_inttype = -inttype i_decimals = -decimals ). -style_subtotal = get_style( i_type = c_type_sub i_alignment = -alignment i_inttype = -inttype i_decimals = -decimals ). -style_total = get_style( i_type = c_type_tot i_alignment = -alignment i_inttype = -inttype i_decimals = -decimals ). ENDLOOP. ENDMETHOD. METHOD convert. IF is_option IS SUPPLIED. ws_option = is_option. ENDIF. execute_converter( EXPORTING io_object = io_alv it_table = it_table ) . IF io_worksheet IS SUPPLIED AND io_worksheet IS BOUND. wo_worksheet = io_worksheet. ENDIF. IF co_excel IS SUPPLIED. IF co_excel IS NOT BOUND. CREATE OBJECT co_excel. co_excel->zif_excel_book_properties~creator = sy-uname. ENDIF. wo_excel = co_excel. ENDIF. * Move table to data object and clean it up IF wt_fieldcatalog IS NOT INITIAL. create_table( ). ELSE. wo_data = wo_table . ENDIF. IF wo_excel IS NOT BOUND. CREATE OBJECT wo_excel. wo_excel->zif_excel_book_properties~creator = sy-uname. ENDIF. IF wo_worksheet IS NOT BOUND. "" Get active sheet wo_worksheet = wo_excel->get_active_worksheet( ). wo_worksheet->set_title( ip_title = 'Sheet1'(001) ). ENDIF. IF i_row_int <= 0. w_row_int = 1. ELSE. w_row_int = i_row_int. ENDIF. IF i_column_int <= 0. w_col_int = 1. ELSE. w_col_int = i_column_int. ENDIF. create_worksheet( i_table = i_table i_style_table = i_style_table ) . ENDMETHOD. METHOD create_color_style. DATA: ls_styles TYPE ts_styles. DATA: lo_style TYPE REF TO zcl_excel_style. READ TABLE wt_styles INTO ls_styles WITH KEY guid = i_style. IF sy-subrc = 0. lo_style = wo_excel->add_new_style( ). * lo_style->borders = ls_styles-style->borders. * lo_style->protection = ls_styles-style->protection. lo_style->font->bold = ls_styles-style->font->bold. lo_style->alignment->horizontal = ls_styles-style->alignment->horizontal. lo_style->number_format->format_code = ls_styles-style->number_format->format_code. lo_style->font->color-rgb = is_colors-fontcolor. lo_style->fill->filltype = zcl_excel_style_fill=>c_fill_solid. lo_style->fill->fgcolor-rgb = is_colors-fillcolor. ro_style = lo_style. ENDIF. ENDMETHOD. METHOD create_formular_subtotal. DATA: l_row_alpha_start TYPE string, l_row_alpha_end TYPE string, l_func_num TYPE string. l_row_alpha_start = i_row_int_start. l_row_alpha_end = i_row_int_end. l_func_num = get_function_number( i_totals_function = i_totals_function ). CONCATENATE 'SUBTOTAL(' l_func_num ',' i_column l_row_alpha_start ':' i_column l_row_alpha_end ')' INTO r_formula. ENDMETHOD. METHOD create_formular_total. DATA: l_row_alpha TYPE string, l_row_e_alpha TYPE string. l_row_alpha = w_row_int + 1. l_row_e_alpha = i_row_int. CONCATENATE i_totals_function '(' i_column l_row_alpha ':' i_column l_row_e_alpha ')' INTO r_formula. ENDMETHOD. METHOD create_path. DATA: l_sep TYPE c, l_path TYPE string, l_return TYPE i. CLEAR r_path. "" Save the file cl_gui_frontend_services=>get_sapgui_workdir( CHANGING sapworkdir = l_path EXCEPTIONS get_sapworkdir_failed = 1 cntl_error = 2 error_no_gui = 3 not_supported_by_gui = 4 ). IF sy-subrc <> 0. * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO * WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4. CONCATENATE 'Excel_' w_fcount '.xlsx' INTO r_path. ELSE. DO. ADD 1 TO w_fcount. *-obtain file separator character--------------------------------------- CALL METHOD cl_gui_frontend_services=>get_file_separator CHANGING file_separator = l_sep EXCEPTIONS cntl_error = 1 error_no_gui = 2 not_supported_by_gui = 3 OTHERS = 4. IF sy-subrc <> 0. l_sep = ''. ENDIF. CONCATENATE l_path l_sep 'Excel_' w_fcount '.xlsx' INTO r_path. IF cl_gui_frontend_services=>file_exist( file = r_path ) = abap_true. cl_gui_frontend_services=>file_delete( EXPORTING filename = r_path CHANGING rc = l_return EXCEPTIONS OTHERS = 1 ). IF sy-subrc = 0 . RETURN. ENDIF. ELSE. RETURN. ENDIF. ENDDO. ENDIF. ENDMETHOD. METHOD create_style_hdr. DATA: lo_style TYPE REF TO zcl_excel_style. lo_style = wo_excel->add_new_style( ). lo_style->font->bold = abap_true. lo_style->font->color-rgb = zcl_excel_style_color=>c_white. lo_style->fill->filltype = zcl_excel_style_fill=>c_fill_solid. lo_style->fill->fgcolor-rgb = 'FF4F81BD'. IF i_alignment IS SUPPLIED AND i_alignment IS NOT INITIAL. lo_style->alignment->horizontal = i_alignment. ENDIF. ro_style = lo_style . ENDMETHOD. METHOD create_style_normal. DATA: lo_style TYPE REF TO zcl_excel_style, l_format TYPE zexcel_number_format. IF i_inttype IS SUPPLIED AND i_inttype IS NOT INITIAL. l_format = set_cell_format( i_inttype = i_inttype i_decimals = i_decimals ) . ENDIF. IF l_format IS NOT INITIAL OR ( i_alignment IS SUPPLIED AND i_alignment IS NOT INITIAL ) . lo_style = wo_excel->add_new_style( ). IF i_alignment IS SUPPLIED AND i_alignment IS NOT INITIAL. lo_style->alignment->horizontal = i_alignment. ENDIF. IF l_format IS NOT INITIAL. lo_style->number_format->format_code = l_format. ENDIF. ro_style = lo_style . ENDIF. ENDMETHOD. METHOD create_style_stripped. DATA: lo_style TYPE REF TO zcl_excel_style. DATA: l_format TYPE zexcel_number_format. lo_style = wo_excel->add_new_style( ). lo_style->fill->filltype = zcl_excel_style_fill=>c_fill_solid. lo_style->fill->fgcolor-rgb = 'FFDBE5F1'. IF i_alignment IS SUPPLIED AND i_alignment IS NOT INITIAL. lo_style->alignment->horizontal = i_alignment. ENDIF. IF i_inttype IS SUPPLIED AND i_inttype IS NOT INITIAL. l_format = set_cell_format( i_inttype = i_inttype i_decimals = i_decimals ) . IF l_format IS NOT INITIAL. lo_style->number_format->format_code = l_format. ENDIF. ENDIF. ro_style = lo_style. ENDMETHOD. METHOD create_style_subtotal. DATA: lo_style TYPE REF TO zcl_excel_style. DATA: l_format TYPE zexcel_number_format. lo_style = wo_excel->add_new_style( ). lo_style->font->bold = abap_true. IF i_alignment IS SUPPLIED AND i_alignment IS NOT INITIAL. lo_style->alignment->horizontal = i_alignment. ENDIF. IF i_inttype IS SUPPLIED AND i_inttype IS NOT INITIAL. l_format = set_cell_format( i_inttype = i_inttype i_decimals = i_decimals ) . IF l_format IS NOT INITIAL. lo_style->number_format->format_code = l_format. ENDIF. ENDIF. ro_style = lo_style . ENDMETHOD. METHOD create_style_total. DATA: lo_style TYPE REF TO zcl_excel_style. DATA: l_format TYPE zexcel_number_format. lo_style = wo_excel->add_new_style( ). lo_style->font->bold = abap_true. CREATE OBJECT lo_style->borders->top. lo_style->borders->top->border_style = zcl_excel_style_border=>c_border_thin. lo_style->borders->top->border_color-rgb = zcl_excel_style_color=>c_black. CREATE OBJECT lo_style->borders->right. lo_style->borders->right->border_style = zcl_excel_style_border=>c_border_none. lo_style->borders->right->border_color-rgb = zcl_excel_style_color=>c_black. CREATE OBJECT lo_style->borders->down. lo_style->borders->down->border_style = zcl_excel_style_border=>c_border_double. lo_style->borders->down->border_color-rgb = zcl_excel_style_color=>c_black. CREATE OBJECT lo_style->borders->left. lo_style->borders->left->border_style = zcl_excel_style_border=>c_border_none. lo_style->borders->left->border_color-rgb = zcl_excel_style_color=>c_black. IF i_alignment IS SUPPLIED AND i_alignment IS NOT INITIAL. lo_style->alignment->horizontal = i_alignment. ENDIF. IF i_inttype IS SUPPLIED AND i_inttype IS NOT INITIAL. l_format = set_cell_format( i_inttype = i_inttype i_decimals = i_decimals ) . IF l_format IS NOT INITIAL. lo_style->number_format->format_code = l_format. ENDIF. ENDIF. ro_style = lo_style . ENDMETHOD. METHOD create_table. TYPES: BEGIN OF ts_output, fieldname TYPE fieldname, function TYPE funcname, END OF ts_output. DATA: lo_data TYPE REF TO data. DATA: lo_addit TYPE REF TO cl_abap_elemdescr, lt_components_tab TYPE cl_abap_structdescr=>component_table, ls_components TYPE abap_componentdescr, lo_table TYPE REF TO cl_abap_tabledescr, lo_struc TYPE REF TO cl_abap_structdescr. FIELD-SYMBOLS: TYPE zexcel_s_converter_fcat, TYPE any, TYPE STANDARD TABLE, TYPE any, TYPE STANDARD TABLE. SORT wt_fieldcatalog BY position. ASSIGN wo_table->* TO . READ TABLE ASSIGNING INDEX 1. IF sy-subrc EQ 0 . LOOP AT wt_fieldcatalog ASSIGNING . ASSIGN COMPONENT -columnname OF STRUCTURE TO . IF sy-subrc = 0. ls_components-name = -columnname. TRY. lo_addit ?= cl_abap_typedescr=>describe_by_data( ). CATCH cx_sy_move_cast_error. CLEAR lo_addit. DELETE TABLE wt_fieldcatalog FROM . ENDTRY. IF lo_addit IS BOUND. ls_components-type = lo_addit . INSERT ls_components INTO TABLE lt_components_tab. ENDIF. ENDIF. ENDLOOP. IF lt_components_tab IS NOT INITIAL. ""create new line type TRY. lo_struc = cl_abap_structdescr=>create( p_components = lt_components_tab p_strict = abap_false ). CATCH cx_sy_struct_creation. RETURN. "" We can not do anything in this case. ENDTRY. lo_table = cl_abap_tabledescr=>create( lo_struc ). CREATE DATA wo_data TYPE HANDLE lo_table. CREATE DATA lo_data TYPE HANDLE lo_struc. ASSIGN wo_data->* TO . ASSIGN lo_data->* TO . LOOP AT ASSIGNING . CLEAR . MOVE-CORRESPONDING TO . APPEND TO . ENDLOOP. ENDIF. ENDIF. ENDMETHOD. METHOD create_text_subtotal. DATA: l_string(256) TYPE c, l_func TYPE string. CASE i_totals_function. WHEN zcl_excel_table=>totals_function_sum. "" Total l_func = 'Total'(003). WHEN zcl_excel_table=>totals_function_min. "" Minimum l_func = 'Minimum'(004). WHEN zcl_excel_table=>totals_function_max. "" Maximum l_func = 'Maximum'(005). WHEN zcl_excel_table=>totals_function_average. "" Mean Value l_func = 'Average'(006). WHEN zcl_excel_table=>totals_function_count. "" Count l_func = 'Count'(007). WHEN OTHERS. CLEAR l_func. ENDCASE. MOVE i_value TO l_string. CONCATENATE l_string l_func INTO r_text SEPARATED BY space. ENDMETHOD. METHOD create_worksheet. DATA: l_freeze_col TYPE i. IF wo_data IS BOUND AND wo_worksheet IS BOUND. wo_worksheet->zif_excel_sheet_properties~summarybelow = zif_excel_sheet_properties=>c_below_on. "" By default is on IF wt_fieldcatalog IS INITIAL. set_fieldcatalog( ) . ELSE. clean_fieldcatalog( ) . ENDIF. IF i_table = abap_true. l_freeze_col = bind_table( i_style_table = i_style_table ) . ELSEIF wt_filter IS NOT INITIAL. * Let's check for filter. wo_autofilter = wo_excel->add_new_autofilter( io_sheet = wo_worksheet ). l_freeze_col = bind_cells( ) . set_autofilter_area( ) . ELSE. l_freeze_col = bind_cells( ) . ENDIF. * Check for freeze panes IF ws_layout-is_fixed = abap_true. IF l_freeze_col = 0. l_freeze_col = w_col_int. ENDIF. wo_worksheet->freeze_panes( EXPORTING ip_num_columns = l_freeze_col ip_num_rows = w_row_int ) . ENDIF. ENDIF. ENDMETHOD. METHOD execute_converter. DATA: lo_if TYPE REF TO zif_excel_converter, ls_types TYPE ts_alv_types, lo_addit TYPE REF TO cl_abap_classdescr, lo_addit_superclass TYPE REF TO cl_abap_classdescr. IF io_object IS BOUND. TRY. lo_addit ?= cl_abap_typedescr=>describe_by_object_ref( io_object ). CATCH cx_sy_move_cast_error. RAISE EXCEPTION TYPE zcx_excel. ENDTRY. ls_types-seoclass = lo_addit->get_relative_name( ). READ TABLE wt_objects INTO ls_types WITH TABLE KEY seoclass = ls_types-seoclass. IF sy-subrc NE 0. DO. FREE lo_addit_superclass. lo_addit_superclass = lo_addit->get_super_class_type( ). IF lo_addit_superclass IS INITIAL. CLEAR ls_types-clsname. EXIT. ENDIF. lo_addit = lo_addit_superclass. ls_types-seoclass = lo_addit->get_relative_name( ). READ TABLE wt_objects INTO ls_types WITH TABLE KEY seoclass = ls_types-seoclass. IF sy-subrc EQ 0. EXIT. ENDIF. ENDDO. ENDIF. IF ls_types-clsname IS NOT INITIAL. CREATE OBJECT lo_if TYPE (ls_types-clsname). lo_if->create_fieldcatalog( EXPORTING is_option = ws_option io_object = io_object it_table = it_table IMPORTING es_layout = ws_layout et_fieldcatalog = wt_fieldcatalog eo_table = wo_table et_colors = wt_colors et_filter = wt_filter ). * data lines of highest level. IF ws_layout-max_subtotal_level > 0. ADD 1 TO ws_layout-max_subtotal_level. ENDIF. ELSE. RAISE EXCEPTION TYPE zcx_excel. ENDIF. ELSE. REFRESH wt_fieldcatalog. GET REFERENCE OF it_table INTO wo_table. ENDIF. ENDMETHOD. METHOD get_alv_converters. DATA: lt_direct_implementations TYPE seor_implementing_keys, lt_all_implementations TYPE seor_implementing_keys, ls_impkey TYPE seor_implementing_key, ls_classkey TYPE seoclskey, lr_implementation TYPE REF TO zif_excel_converter, ls_object TYPE ts_alv_types, lr_classdescr TYPE REF TO cl_abap_classdescr. ls_classkey-clsname = 'ZIF_EXCEL_CONVERTER'. CALL FUNCTION 'SEO_INTERFACE_IMPLEM_GET_ALL' EXPORTING intkey = ls_classkey IMPORTING impkeys = lt_direct_implementations EXCEPTIONS OTHERS = 2. CHECK sy-subrc = 0. LOOP AT lt_direct_implementations INTO ls_impkey. lr_classdescr ?= cl_abap_classdescr=>describe_by_name( ls_impkey-clsname ). IF lr_classdescr->is_instantiatable( ) = abap_true. APPEND ls_impkey TO lt_all_implementations. ENDIF. ls_classkey-clsname = ls_impkey-clsname. get_subclasses( EXPORTING is_clskey = ls_classkey CHANGING ct_classes = lt_all_implementations ). ENDLOOP. SORT lt_all_implementations BY clsname. DELETE ADJACENT DUPLICATES FROM lt_all_implementations COMPARING clsname. LOOP AT lt_all_implementations INTO ls_impkey. CLEAR ls_object. CREATE OBJECT lr_implementation TYPE (ls_impkey-clsname). ls_object-seoclass = lr_implementation->get_supported_class( ). IF ls_object-seoclass IS NOT INITIAL. ls_object-clsname = ls_impkey-clsname. INSERT ls_object INTO TABLE wt_objects. ENDIF. ENDLOOP. ENDMETHOD. METHOD get_color_style. DATA: ls_colors TYPE zexcel_s_converter_col, ls_color_styles TYPE ts_color_styles, lo_style TYPE REF TO zcl_excel_style. r_style = i_style. "" Default we change nothing IF wt_colors IS NOT INITIAL. * Full line has color READ TABLE wt_colors INTO ls_colors WITH KEY rownumber = i_row columnname = space. IF sy-subrc = 0. READ TABLE wt_color_styles INTO ls_color_styles WITH KEY guid_old = i_style fontcolor = ls_colors-fontcolor fillcolor = ls_colors-fillcolor. IF sy-subrc = 0. r_style = ls_color_styles-style_new->get_guid( ). ELSE. lo_style = create_color_style( i_style = i_style is_colors = ls_colors ) . r_style = lo_style->get_guid( ) . ls_color_styles-guid_old = i_style. ls_color_styles-fontcolor = ls_colors-fontcolor. ls_color_styles-fillcolor = ls_colors-fillcolor. ls_color_styles-style_new = lo_style. INSERT ls_color_styles INTO TABLE wt_color_styles. ENDIF. ELSE. * Only field has color READ TABLE wt_colors INTO ls_colors WITH KEY rownumber = i_row columnname = i_fieldname. IF sy-subrc = 0. READ TABLE wt_color_styles INTO ls_color_styles WITH KEY guid_old = i_style fontcolor = ls_colors-fontcolor fillcolor = ls_colors-fillcolor. IF sy-subrc = 0. r_style = ls_color_styles-style_new->get_guid( ). ELSE. lo_style = create_color_style( i_style = i_style is_colors = ls_colors ) . ls_color_styles-guid_old = i_style. ls_color_styles-fontcolor = ls_colors-fontcolor. ls_color_styles-fillcolor = ls_colors-fillcolor. ls_color_styles-style_new = lo_style. INSERT ls_color_styles INTO TABLE wt_color_styles. r_style = ls_color_styles-style_new->get_guid( ). ENDIF. ELSE. r_style = i_style. ENDIF. ENDIF. ELSE. r_style = i_style. ENDIF. ENDMETHOD. METHOD get_file. DATA: lo_excel_writer TYPE REF TO zif_excel_writer. DATA: ls_seoclass TYPE seoclass. IF wo_excel IS BOUND. CREATE OBJECT lo_excel_writer TYPE zcl_excel_writer_2007. e_file = lo_excel_writer->write_file( wo_excel ). SELECT SINGLE * INTO ls_seoclass FROM seoclass WHERE clsname = 'CL_BCS_CONVERT'. IF sy-subrc = 0. CALL METHOD (ls_seoclass-clsname)=>xstring_to_solix EXPORTING iv_xstring = e_file RECEIVING et_solix = et_file. e_bytecount = xstrlen( e_file ). ELSE. "" Convert to binary CALL FUNCTION 'SCMS_XSTRING_TO_BINARY' EXPORTING buffer = e_file IMPORTING output_length = e_bytecount TABLES binary_tab = et_file. ENDIF. ENDIF. ENDMETHOD. METHOD get_function_number. *Number Function *1 AVERAGE *2 COUNT *3 COUNTA *4 MAX *5 MIN *6 PRODUCT *7 STDEV *8 STDEVP *9 SUM *10 VAR *11 VARP CASE i_totals_function. WHEN zcl_excel_table=>totals_function_sum. "" Total r_function_number = 9. WHEN zcl_excel_table=>totals_function_min. "" Minimum r_function_number = 5. WHEN zcl_excel_table=>totals_function_max. "" Maximum r_function_number = 4. WHEN zcl_excel_table=>totals_function_average. "" Mean Value r_function_number = 1. WHEN zcl_excel_table=>totals_function_count. "" Count r_function_number = 2. WHEN OTHERS. CLEAR r_function_number. ENDCASE. ENDMETHOD. METHOD get_option. rs_option = ws_option. ENDMETHOD. METHOD get_style. DATA: ls_styles TYPE ts_styles, lo_style TYPE REF TO zcl_excel_style. CLEAR r_style. READ TABLE wt_styles INTO ls_styles WITH TABLE KEY type = i_type alignment = i_alignment inttype = i_inttype decimals = i_decimals. IF sy-subrc = 0. r_style = ls_styles-guid. ELSE. CASE i_type. WHEN c_type_hdr. "" Header lo_style = create_style_hdr( i_alignment = i_alignment ). WHEN c_type_str. ""Stripped lo_style = create_style_stripped( i_alignment = i_alignment i_inttype = i_inttype i_decimals = i_decimals ). WHEN c_type_nor. ""Normal lo_style = create_style_normal( i_alignment = i_alignment i_inttype = i_inttype i_decimals = i_decimals ). WHEN c_type_sub. ""Subtotals lo_style = create_style_subtotal( i_alignment = i_alignment i_inttype = i_inttype i_decimals = i_decimals ). WHEN c_type_tot. ""Totals lo_style = create_style_total( i_alignment = i_alignment i_inttype = i_inttype i_decimals = i_decimals ). ENDCASE. IF lo_style IS NOT INITIAL. r_style = lo_style->get_guid( ). ls_styles-type = i_type. ls_styles-alignment = i_alignment. ls_styles-inttype = i_inttype. ls_styles-decimals = i_decimals. ls_styles-guid = r_style. ls_styles-style = lo_style. INSERT ls_styles INTO TABLE wt_styles. ENDIF. ENDIF. ENDMETHOD. METHOD get_subclasses. DATA: lt_subclasses TYPE seor_inheritance_keys, ls_subclass TYPE seor_inheritance_key, lr_classdescr TYPE REF TO cl_abap_classdescr. CALL FUNCTION 'SEO_CLASS_GET_ALL_SUBS' EXPORTING clskey = is_clskey IMPORTING inhkeys = lt_subclasses EXCEPTIONS class_not_existing = 1 OTHERS = 2. CHECK sy-subrc = 0. LOOP AT lt_subclasses INTO ls_subclass. lr_classdescr ?= cl_abap_classdescr=>describe_by_name( ls_subclass-clsname ). IF lr_classdescr->is_instantiatable( ) = abap_true. APPEND ls_subclass TO ct_classes. ENDIF. ENDLOOP. ENDMETHOD. METHOD init_option. ws_option-filter = abap_true. ws_option-hidenc = abap_true. ws_option-subtot = abap_true. ENDMETHOD. METHOD loop_normal. DATA: l_row_int_end TYPE zexcel_cell_row, l_row_int TYPE zexcel_cell_row, l_col_int TYPE zexcel_cell_column, l_col_alpha TYPE zexcel_cell_column_alpha, l_cell_value TYPE zexcel_cell_value, l_s_color TYPE abap_bool, lo_column TYPE REF TO zcl_excel_column, l_formula TYPE zexcel_cell_formula, l_style TYPE zexcel_cell_style, l_cells TYPE i, l_count TYPE i, l_table_row TYPE i. FIELD-SYMBOLS: TYPE any, TYPE STANDARD TABLE, TYPE zexcel_s_converter_fcat, TYPE any. ASSIGN wo_data->* TO . DESCRIBE TABLE wt_fieldcatalog LINES l_cells. DESCRIBE TABLE LINES l_count. l_cells = l_cells * l_count. * It is better to loop column by column LOOP AT wt_fieldcatalog ASSIGNING . l_row_int = i_row_int. l_col_int = i_col_int + -position - 1. * Freeze panes IF -fix_column = abap_true. ADD 1 TO r_freeze_col. ENDIF. l_s_color = abap_true. l_col_alpha = zcl_excel_common=>convert_column2alpha( l_col_int ). * Only if the Header is required create it. IF ws_option-hidehd IS INITIAL. "" First of all write column header l_cell_value = -scrtext_m. wo_worksheet->set_cell( ip_column = l_col_alpha ip_row = l_row_int ip_value = l_cell_value ip_style = -style_hdr ). ADD 1 TO l_row_int. ENDIF. LOOP AT ASSIGNING . l_table_row = sy-tabix. * Now the cell values ASSIGN COMPONENT -columnname OF STRUCTURE TO . * Now let's write the cell values IF ws_layout-is_stripped = abap_true AND l_s_color = abap_true. l_style = get_color_style( i_row = l_table_row i_fieldname = -columnname i_style = -style_stripped ). wo_worksheet->set_cell( ip_column = l_col_alpha ip_row = l_row_int ip_value = ip_style = l_style ). CLEAR l_s_color. ELSE. l_style = get_color_style( i_row = l_table_row i_fieldname = -columnname i_style = -style_normal ). wo_worksheet->set_cell( ip_column = l_col_alpha ip_row = l_row_int ip_value = ip_style = l_style ). l_s_color = abap_true. ENDIF. READ TABLE wt_filter TRANSPORTING NO FIELDS WITH TABLE KEY rownumber = l_table_row columnname = -columnname. IF sy-subrc = 0. wo_worksheet->get_cell( EXPORTING ip_column = l_col_alpha ip_row = l_row_int IMPORTING ep_value = l_cell_value ). wo_autofilter->set_value( i_column = l_col_int i_value = l_cell_value ). ENDIF. ADD 1 TO l_row_int. ENDLOOP. * Now let's check for optimized IF -is_optimized = abap_true . lo_column = wo_worksheet->get_column( ip_column = l_col_alpha ). lo_column->set_auto_size( ip_auto_size = abap_true ) . ENDIF. * Now let's check for visible IF -is_hidden = abap_true. lo_column = wo_worksheet->get_column( ip_column = l_col_alpha ). lo_column->set_visible( ip_visible = abap_false ) . ENDIF. * Now let's check for total versus subtotal. IF -totals_function IS NOT INITIAL. l_row_int_end = l_row_int - 1. l_formula = create_formular_total( i_row_int = l_row_int_end i_column = l_col_alpha i_totals_function = -totals_function ). wo_worksheet->set_cell( ip_column = l_col_alpha ip_row = l_row_int ip_formula = l_formula ip_style = -style_total ). ENDIF. ENDLOOP. ENDMETHOD. METHOD loop_subtotal. DATA: l_row_int_start TYPE zexcel_cell_row, l_row_int_end TYPE zexcel_cell_row, l_row_int TYPE zexcel_cell_row, l_col_int TYPE zexcel_cell_column, l_col_alpha TYPE zexcel_cell_column_alpha, l_col_alpha_start TYPE zexcel_cell_column_alpha, l_cell_value TYPE zexcel_cell_value, l_s_color TYPE abap_bool, lo_column TYPE REF TO zcl_excel_column, lo_row TYPE REF TO zcl_excel_row, l_formula TYPE zexcel_cell_formula, l_style TYPE zexcel_cell_style, l_text TYPE string, ls_sort_values TYPE ts_sort_values, ls_subtotal_rows TYPE ts_subtotal_rows, l_sort_level TYPE int4, l_hidden TYPE int4, l_line TYPE i, l_cells TYPE i, l_count TYPE i, l_table_row TYPE i, lt_fcat TYPE zexcel_t_converter_fcat. FIELD-SYMBOLS: TYPE any, TYPE STANDARD TABLE, TYPE zexcel_s_converter_fcat, TYPE any, TYPE any, TYPE ts_sort_values. ASSIGN wo_data->* TO . REFRESH: wt_sort_values, wt_subtotal_rows. DESCRIBE TABLE wt_fieldcatalog LINES l_cells. DESCRIBE TABLE LINES l_count. l_cells = l_cells * l_count. READ TABLE ASSIGNING INDEX 1. IF sy-subrc = 0. l_row_int = i_row_int + 1. lt_fcat = wt_fieldcatalog. SORT lt_fcat BY sort_level DESCENDING. LOOP AT lt_fcat ASSIGNING WHERE is_subtotalled = abap_true. ASSIGN COMPONENT -columnname OF STRUCTURE TO . ls_sort_values-fieldname = -columnname. ls_sort_values-row_int = l_row_int. ls_sort_values-sort_level = -sort_level. ls_sort_values-is_collapsed = -is_collapsed. CREATE DATA ls_sort_values-value LIKE . ASSIGN ls_sort_values-value->* TO . = . INSERT ls_sort_values INTO TABLE wt_sort_values. ENDLOOP. ENDIF. l_row_int = i_row_int. * Let's check if we need to hide a sort level. DESCRIBE TABLE wt_sort_values LINES l_line. IF l_line <= 1. CLEAR l_hidden. ELSE. LOOP AT wt_sort_values INTO ls_sort_values WHERE is_collapsed = abap_false. IF l_hidden < ls_sort_values-sort_level. l_hidden = ls_sort_values-sort_level. ENDIF. ENDLOOP. ENDIF. ADD 1 TO l_hidden. "" As this is the first level we show. * First loop without formular only addtional rows with subtotal text. LOOP AT ASSIGNING . ADD 1 TO l_row_int. "" 1 is for header row. l_row_int_start = l_row_int. SORT lt_fcat BY sort_level DESCENDING. LOOP AT lt_fcat ASSIGNING WHERE is_subtotalled = abap_true. l_col_int = i_col_int + -position - 1. l_col_alpha = zcl_excel_common=>convert_column2alpha( l_col_int ). * Now the cell values ASSIGN COMPONENT -columnname OF STRUCTURE TO . IF sy-subrc = 0. READ TABLE wt_sort_values ASSIGNING WITH TABLE KEY fieldname = -columnname. IF sy-subrc = 0. ASSIGN -value->* TO . IF <> OR -new = abap_true. * First let's remmember the subtotal values as it has to appear later. ls_subtotal_rows-row_int = l_row_int. ls_subtotal_rows-row_int_start = -row_int. ls_subtotal_rows-columnname = -columnname. INSERT ls_subtotal_rows INTO TABLE wt_subtotal_rows. * Now let's write the subtotal line l_cell_value = create_text_subtotal( i_value = i_totals_function = -totals_function ). wo_worksheet->set_cell( ip_column = l_col_alpha ip_row = l_row_int ip_value = l_cell_value ip_abap_type = cl_abap_typedescr=>typekind_string ip_style = -style_subtotal ). lo_row = wo_worksheet->get_row( ip_row = l_row_int ). lo_row->set_outline_level( ip_outline_level = -sort_level ) . IF -is_collapsed = abap_true. IF -sort_level > l_hidden. lo_row->set_visible( ip_visible = abap_false ) . ENDIF. lo_row->set_collapsed( ip_collapsed = -is_collapsed ) . ENDIF. * Now let's change the key ADD 1 TO l_row_int. = . -new = abap_false. l_line = -sort_level. LOOP AT wt_sort_values ASSIGNING WHERE sort_level >= l_line. -row_int = l_row_int. ENDLOOP. ENDIF. ENDIF. ENDIF. ENDLOOP. ENDLOOP. ADD 1 TO l_row_int. l_row_int_start = l_row_int. SORT lt_fcat BY sort_level DESCENDING. LOOP AT lt_fcat ASSIGNING WHERE is_subtotalled = abap_true. l_col_int = i_col_int + -position - 1. l_col_alpha = zcl_excel_common=>convert_column2alpha( l_col_int ). READ TABLE wt_sort_values ASSIGNING WITH TABLE KEY fieldname = -columnname. IF sy-subrc = 0. ASSIGN -value->* TO . ls_subtotal_rows-row_int = l_row_int. ls_subtotal_rows-row_int_start = -row_int. ls_subtotal_rows-columnname = -columnname. INSERT ls_subtotal_rows INTO TABLE wt_subtotal_rows. * First let's write the value as it has to appear. l_cell_value = create_text_subtotal( i_value = i_totals_function = -totals_function ). wo_worksheet->set_cell( ip_column = l_col_alpha ip_row = l_row_int ip_value = l_cell_value ip_abap_type = cl_abap_typedescr=>typekind_string ip_style = -style_subtotal ). l_sort_level = -sort_level. lo_row = wo_worksheet->get_row( ip_row = l_row_int ). lo_row->set_outline_level( ip_outline_level = l_sort_level ) . IF -is_collapsed = abap_true. IF -sort_level > l_hidden. lo_row->set_visible( ip_visible = abap_false ) . ENDIF. lo_row->set_collapsed( ip_collapsed = -is_collapsed ) . ENDIF. ADD 1 TO l_row_int. ENDIF. ENDLOOP. * Let's write the Grand total l_sort_level = 0. lo_row = wo_worksheet->get_row( ip_row = l_row_int ). lo_row->set_outline_level( ip_outline_level = l_sort_level ) . * lo_row_dim->set_collapsed( ip_collapsed = -is_collapsed ) . Not on grand total l_text = create_text_subtotal( i_value = 'Grand'(002) i_totals_function = -totals_function ). l_col_alpha_start = zcl_excel_common=>convert_column2alpha( i_col_int ). wo_worksheet->set_cell( ip_column = l_col_alpha_start ip_row = l_row_int ip_value = l_text ip_abap_type = cl_abap_typedescr=>typekind_string ip_style = -style_subtotal ). * It is better to loop column by column second time around * Second loop with formular and data. LOOP AT wt_fieldcatalog ASSIGNING . l_row_int = i_row_int. l_col_int = i_col_int + -position - 1. * Freeze panes IF -fix_column = abap_true. ADD 1 TO r_freeze_col. ENDIF. l_s_color = abap_true. l_col_alpha = zcl_excel_common=>convert_column2alpha( l_col_int ). "" First of all write column header l_cell_value = -scrtext_m. wo_worksheet->set_cell( ip_column = l_col_alpha ip_row = l_row_int ip_value = l_cell_value ip_abap_type = cl_abap_typedescr=>typekind_string ip_style = -style_hdr ). ADD 1 TO l_row_int. LOOP AT ASSIGNING . l_table_row = sy-tabix. * Now the cell values ASSIGN COMPONENT -columnname OF STRUCTURE TO . * Let's check for subtotal lines DO. READ TABLE wt_subtotal_rows TRANSPORTING NO FIELDS WITH TABLE KEY row_int = l_row_int. IF sy-subrc = 0. IF -is_subtotalled = abap_false AND -totals_function IS NOT INITIAL. DO. READ TABLE wt_subtotal_rows INTO ls_subtotal_rows WITH TABLE KEY row_int = l_row_int. IF sy-subrc = 0. l_row_int_start = ls_subtotal_rows-row_int_start. l_row_int_end = l_row_int - 1. l_formula = create_formular_subtotal( i_row_int_start = l_row_int_start i_row_int_end = l_row_int_end i_column = l_col_alpha i_totals_function = -totals_function ). wo_worksheet->set_cell( ip_column = l_col_alpha ip_row = l_row_int ip_formula = l_formula ip_style = -style_subtotal ). IF -is_collapsed = abap_true. lo_row = wo_worksheet->get_row( ip_row = l_row_int ). lo_row->set_collapsed( ip_collapsed = -is_collapsed ). IF -sort_level > l_hidden. lo_row->set_visible( ip_visible = abap_false ) . ENDIF. ENDIF. ADD 1 TO l_row_int. ELSE. EXIT. ENDIF. ENDDO. ELSE. ADD 1 TO l_row_int. ENDIF. ELSE. EXIT. ENDIF. ENDDO. * Let's set the row dimension values lo_row = wo_worksheet->get_row( ip_row = l_row_int ). lo_row->set_outline_level( ip_outline_level = ws_layout-max_subtotal_level ) . IF -is_collapsed = abap_true. lo_row->set_visible( ip_visible = abap_false ) . lo_row->set_collapsed( ip_collapsed = -is_collapsed ) . ENDIF. * Now let's write the cell values IF ws_layout-is_stripped = abap_true AND l_s_color = abap_true. l_style = get_color_style( i_row = l_table_row i_fieldname = -columnname i_style = -style_stripped ). wo_worksheet->set_cell( ip_column = l_col_alpha ip_row = l_row_int ip_value = ip_style = l_style ). CLEAR l_s_color. ELSE. l_style = get_color_style( i_row = l_table_row i_fieldname = -columnname i_style = -style_normal ). wo_worksheet->set_cell( ip_column = l_col_alpha ip_row = l_row_int ip_value = ip_style = l_style ). l_s_color = abap_true. ENDIF. READ TABLE wt_filter TRANSPORTING NO FIELDS WITH TABLE KEY rownumber = l_table_row columnname = -columnname. IF sy-subrc = 0. wo_worksheet->get_cell( EXPORTING ip_column = l_col_alpha ip_row = l_row_int IMPORTING ep_value = l_cell_value ). wo_autofilter->set_value( i_column = l_col_int i_value = l_cell_value ). ENDIF. ADD 1 TO l_row_int. ENDLOOP. * Let's check for subtotal lines DO. READ TABLE wt_subtotal_rows TRANSPORTING NO FIELDS WITH TABLE KEY row_int = l_row_int. IF sy-subrc = 0. IF -is_subtotalled = abap_false AND -totals_function IS NOT INITIAL. DO. READ TABLE wt_subtotal_rows INTO ls_subtotal_rows WITH TABLE KEY row_int = l_row_int. IF sy-subrc = 0. l_row_int_start = ls_subtotal_rows-row_int_start. l_row_int_end = l_row_int - 1. l_formula = create_formular_subtotal( i_row_int_start = l_row_int_start i_row_int_end = l_row_int_end i_column = l_col_alpha i_totals_function = -totals_function ). wo_worksheet->set_cell( ip_column = l_col_alpha ip_row = l_row_int ip_formula = l_formula ip_style = -style_subtotal ). IF -is_collapsed = abap_true. lo_row = wo_worksheet->get_row( ip_row = l_row_int ). lo_row->set_collapsed( ip_collapsed = -is_collapsed ). ENDIF. ADD 1 TO l_row_int. ELSE. EXIT. ENDIF. ENDDO. ELSE. ADD 1 TO l_row_int. ENDIF. ELSE. EXIT. ENDIF. ENDDO. * Now let's check for Grand total IF -is_subtotalled = abap_false AND -totals_function IS NOT INITIAL. l_row_int_start = i_row_int + 1. l_row_int_end = l_row_int - 1. l_formula = create_formular_subtotal( i_row_int_start = l_row_int_start i_row_int_end = l_row_int_end i_column = l_col_alpha i_totals_function = -totals_function ). wo_worksheet->set_cell( ip_column = l_col_alpha ip_row = l_row_int ip_formula = l_formula ip_style = -style_subtotal ). ENDIF. * Now let's check for optimized IF -is_optimized = abap_true. lo_column = wo_worksheet->get_column( ip_column = l_col_alpha ). lo_column->set_auto_size( ip_auto_size = abap_true ) . ENDIF. * Now let's check for visible IF -is_hidden = abap_true. lo_column = wo_worksheet->get_column( ip_column = l_col_alpha ). lo_column->set_visible( ip_visible = abap_false ) . ENDIF. ENDLOOP. ENDMETHOD. METHOD open_file. DATA: l_bytecount TYPE i, lt_file TYPE solix_tab, l_dir TYPE string. FIELD-SYMBOLS: TYPE ANY TABLE. ASSIGN wo_data->* TO . * catch zcx_excel . *endtry. IF wo_excel IS BOUND. get_file( IMPORTING e_bytecount = l_bytecount et_file = lt_file ) . l_dir = create_path( ) . cl_gui_frontend_services=>gui_download( EXPORTING bin_filesize = l_bytecount filename = l_dir filetype = 'BIN' CHANGING data_tab = lt_file ). cl_gui_frontend_services=>execute( EXPORTING document = l_dir * application = * parameter = * default_directory = * maximized = * minimized = * synchronous = * operation = 'OPEN' EXCEPTIONS cntl_error = 1 error_no_gui = 2 bad_parameter = 3 file_not_found = 4 path_not_found = 5 file_extension_unknown = 6 error_execute_failed = 7 synchronous_failed = 8 not_supported_by_gui = 9 ). IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF. ENDIF. ENDMETHOD. METHOD set_autofilter_area. DATA: ls_area TYPE zexcel_s_autofilter_area, l_lines TYPE i, lt_values TYPE zexcel_t_autofilter_values, ls_values TYPE zexcel_s_autofilter_values. * Let's check for filter. IF wo_autofilter IS BOUND. ls_area-row_start = 1. lt_values = wo_autofilter->get_values( ) . SORT lt_values BY column ASCENDING. DESCRIBE TABLE lt_values LINES l_lines. READ TABLE lt_values INTO ls_values INDEX 1. IF sy-subrc = 0. ls_area-col_start = ls_values-column. ENDIF. READ TABLE lt_values INTO ls_values INDEX l_lines. IF sy-subrc = 0. ls_area-col_end = ls_values-column. ENDIF. wo_autofilter->set_filter_area( is_area = ls_area ) . ENDIF. ENDMETHOD. METHOD set_cell_format. DATA: l_format TYPE zexcel_number_format. CLEAR r_format. CASE i_inttype. WHEN cl_abap_typedescr=>typekind_date. r_format = wo_worksheet->get_default_excel_date_format( ). WHEN cl_abap_typedescr=>typekind_time. r_format = wo_worksheet->get_default_excel_time_format( ). WHEN cl_abap_typedescr=>typekind_float OR cl_abap_typedescr=>typekind_packed OR cl_abap_typedescr=>typekind_decfloat OR cl_abap_typedescr=>typekind_decfloat16 OR cl_abap_typedescr=>typekind_decfloat34. IF i_decimals > 0 . l_format = '#,##0.'. DO i_decimals TIMES. CONCATENATE l_format '0' INTO l_format. ENDDO. r_format = l_format. ENDIF. WHEN cl_abap_typedescr=>typekind_int OR cl_abap_typedescr=>typekind_int1 OR cl_abap_typedescr=>typekind_int2. r_format = '#,##0'. ENDCASE. ENDMETHOD. METHOD set_fieldcatalog. DATA: lr_data TYPE REF TO data, lo_structdescr TYPE REF TO cl_abap_structdescr, lt_dfies TYPE ddfields, ls_dfies TYPE dfies. DATA: ls_fcat TYPE zexcel_s_converter_fcat. FIELD-SYMBOLS: TYPE ANY TABLE. ASSIGN wo_data->* TO . CREATE DATA lr_data LIKE LINE OF . lo_structdescr ?= cl_abap_structdescr=>describe_by_data_ref( lr_data ). lt_dfies = zcl_excel_common=>describe_structure( io_struct = lo_structdescr ). LOOP AT lt_dfies INTO ls_dfies. MOVE-CORRESPONDING ls_dfies TO ls_fcat. ls_fcat-columnname = ls_dfies-fieldname. INSERT ls_fcat INTO TABLE wt_fieldcatalog. ENDLOOP. clean_fieldcatalog( ). ENDMETHOD. METHOD set_option. IF ws_indx-begdt IS INITIAL. ws_indx-begdt = sy-datum. ENDIF. ws_indx-aedat = sy-datum. ws_indx-usera = sy-uname. ws_indx-pgmid = sy-cprog. EXPORT p1 = is_option TO DATABASE indx(xl) FROM ws_indx ID ws_indx-srtfd. IF sy-subrc = 0. ws_option = is_option. ENDIF. ENDMETHOD. METHOD write_file. DATA: l_bytecount TYPE i, lt_file TYPE solix_tab, l_dir TYPE string. FIELD-SYMBOLS: TYPE ANY TABLE. ASSIGN wo_data->* TO . * catch zcx_excel . *endtry. IF wo_excel IS BOUND. get_file( IMPORTING e_bytecount = l_bytecount et_file = lt_file ) . IF i_path IS INITIAL. l_dir = create_path( ) . ELSE. l_dir = i_path. ENDIF. cl_gui_frontend_services=>gui_download( EXPORTING bin_filesize = l_bytecount filename = l_dir filetype = 'BIN' CHANGING data_tab = lt_file ). ENDIF. ENDMETHOD. ENDCLASS. ",15916,True,3312.0726581834138,median "// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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. // = Creating a Simple Web Application Using a MySQL Database :jbake-type: tutorial :jbake-tags: tutorials :jbake-status: published :icons: font :syntax: true :source-highlighter: pygments :toc: left :toc-title: :description: Creating a Simple Web Application Using a MySQL Database - Apache NetBeans :keywords: Apache NetBeans, Tutorials, Creating a Simple Web Application Using a MySQL Database Written by Troy Giunipero This document describes how to create a simple web application that connects to a MySQL database server. It also covers some basic ideas and technologies in web development, such as link:http://www.oracle.com/technetwork/java/overview-138580.html[+JavaServer Pages+] (JSP), link:http://www.oracle.com/technetwork/java/index-jsp-135995.html[+JavaServer Pages Standard Tag Library+] (JSTL), the link:http://docs.oracle.com/javase/tutorial/jdbc/overview/index.html[+Java Database Connectivity+] (JDBC) API, and two-tier, client-server architecture. This tutorial is designed for beginners who have a basic understanding of web development and are looking to apply their knowledge using a MySQL database. link:http://www.mysql.com[+MySQL+] is a popular open source database management system commonly used in web applications due to its speed, flexibility and reliability. MySQL employs SQL, or _Structured Query Language_, for accessing and processing data contained in databases. This tutorial is a continuation from the link:../ide/mysql.html[+Connecting to a MySQL Database+] tutorial and assumes that you have already created a MySQL database named `MyNewDatabase`, which you have registered a connection for in the NetBeans IDE. The table data used in that tutorial is contained in link:https://netbeans.org/projects/samples/downloads/download/Samples%252FJava%2520Web%252Fifpwafcad.sql[+ifpwafcad.sql+] and is also required for this tutorial. This SQL file creates two tables, `Subject` and `Counselor`, then populates them with sample data. If needed, save this file to your computer, then open it in the NetBeans IDE and run it on the MySQL database named `MyNewDatabase`. image::images/netbeans-stamp-80-74-73.png[title=""Content on this page applies to the NetBeans IDE 7.2, 7.3, 7.4 and 8.0""] *To follow this tutorial, you need the following software and resources.* |=== |Software or Resource |Version Required |link:https://netbeans.org/downloads/index.html[+NetBeans IDE+] |7.2, 7.3, 7.4, 8.0, Java EE bundle |link:http://www.oracle.com/technetwork/java/javase/downloads/index.html[+Java Development Kit (JDK)+] |version 7 or 8 |link:http://dev.mysql.com/downloads/mysql/[+MySQL database server+] |5.x |MySQL Connector/J JDBC Driver |version 5.x |GlassFish Server Open Source Edition |3.x or 4.x |=== *Notes:* * The Java download bundle of the NetBeans IDE enables you to install the GlassFish server. You require the GlassFish server to work through this tutorial. * The link:http://dev.mysql.com/downloads/connector/j/[+MySQL Connector/J JDBC Driver+], necessary for communication between Java platforms and the MySQL database protocol, is included in the NetBeans IDE. * If you need to compare your project with a working solution, you can link:https://netbeans.org/projects/samples/downloads/download/Samples%252FJava%2520Web%252FIFPWAFCAD.zip[+download the sample application+]. [[planStructure]] == Planning the Structure Simple web applications can be designed using a _two-tier architecture_, in which a client communicates directly with a server. In this tutorial, a Java web application communicates directly with a MySQL database using the Java Database Connectivity API. Essentially, it is the link:http://dev.mysql.com/downloads/connector/j/[+MySQL Connector/J JDBC Driver+] that enables communication between the Java code understood by the application server (the GlassFish server), and any content in SQL, the language understood by the database server (MySQL). The application you build in this tutorial involves the creation of two JSP pages. In each of these pages you use HTML and CSS to implement a simple interface, and apply JSTL technology to perform the logic that directly queries the database and inserts the retrieved data into the two pages. The two database tables, `Subject` and `Counselor`, are contained in the MySQL database, `MyNewDatabase`, which you create by completing the link:../ide/mysql.html[+Connecting to a MySQL Database+] tutorial. Consider the following two-tier scenario. image::images/ifpwafcad-structure.png[title=""Sample structure of a two-tier web application""] The welcome page (`index.jsp`) presents the user with a simple HTML form. When a browser requests `index.jsp`, the JSTL code within the page initiates a query on `MyNewDatabase`. It retrieves data from the `Subject` database table, and inserts it into to the page before it is sent to the browser. When the user submits his or her selection in the welcome page's HTML form, the submit initiates a request for the response page (`response.jsp`). Again, the JSTL code within the page initiates a query on `MyNewDatabase`. This time, it retrieves data from both the `Subject` and `Counselor` tables and inserts it into to the page, allowing the user to view data based upon his or her selection when the page is returned to the browser. In order to implement the scenario described above, you develop a simple application for a fictitious organization named IFPWAFCAD, The International Former Professional Wrestlers' Association for Counseling and Development. === index.jsp image::images/index-page.png[title=""index.jsp displayed in a browser""] === response.jsp image::images/response-page.png[title=""response.jsp displayed in a browser""] [[createProject]] == Creating a New Project Begin by creating a new Java web project in the IDE: 1. Choose File > New Project (Ctrl-Shift-N; ⌘-Shift-N on Mac) from the main menu. Select the Java Web category, then select Web Application. Click Next. image::images/new-project.png[title=""Use the IDE's New Project wizard to create a new project""] The New Project wizard allows you to create an empty web application in a standard IDE project. The standard project uses an IDE-generated Ant build script to compile, deploy, and run the application. . In Project Name, enter *IFPWAFCAD*. Also, specify the location for the project on your computer. (By default, the IDE places projects in a `NetBeansProjects` folder located in your home directory.) Click Next. . In the Server and Settings panel, specify the GlassFish server as server which will be used to run the application. *Note. *The GlassFish server displays in the Server drop-down field if you installed the Java version of the link:https://netbeans.org/downloads/index.html[+NetBeans IDE+]. Because the GlassFish server is included in the download, it is automatically registered with the IDE. If you want to use a different server for this project, click the Add button located next to the Server drop-down field, and register a different server with the IDE. However, working with servers other than the GlassFish server is beyond the scope of this tutorial. . In the Java EE Version field, select *Java EE 5*. image::images/server-settings.png[title=""Specify server settings in the New Web Application wizard""] Java EE 6 and Java EE 7 web projects do not require the use of the `web.xml` deployment descriptor, and the NetBeans project template does not include the `web.xml` file in Java EE 6 and Java EE 7 projects. However, this tutorial demonstrates how to declare a data source in the deployment descriptor, and it does not rely on any features specific to Java EE 6 or Java EE 7, so you can set the project version to Java EE 5. *Note.* You could equally set the project version to Java EE 6 or Java EE 7 and then create a `web.xml` deployment descriptor. (From the New File wizard, select the Web category, then Standard Deployment Descriptor.) . Click Finish. The IDE creates a project template for the entire application, and opens an empty JSP page (`index.jsp`) in the editor. The `index.jsp` file serves as the welcome page for the application. [[prepareInterface]] == Preparing the Web Interface Begin by preparing the welcome (`index.jsp`) and response (`response.jsp`) pages. The welcome page implements an HTML form that is used to capture user data. Both pages implement an HTML table to display data in a structured fashion. In this section, you also create a stylesheet that enhances the appearance of both pages. * <> * <> * <> [[welcomePage]] === Setting up the welcome page Confirm that `index.jsp` is open in the editor. If the file is not already open, double-click `index.jsp` under the Web Pages node in the IFPWAFCAD project in the Projects window. 1. In the editor, change the text between the `` tags to: `IFPWAFCAD Homepage`. 2. Change the text between the `<h1>` tags to: `Welcome to IFPWAFCAD, the International Former Professional Wrestlers' Association for Counseling and Development!`. 3. Open the IDE's Palette by choosing Window > Palette (Ctrl-Shift-8; ⌘-Shift-8 on Mac) from the main menu. Hover your pointer over the Table icon from the HTML category and note that the default code snippet for the item displays. image::images/palette.png[title=""Palette displays code snippet when hovering over an item""] [tips]#You can configure the Palette to your liking - right-click in the Palette and choose Show Big Icons and Hide Item Names to have it display as in the image above.# . Place your cursor at a point just after the `<h1>` tags. (This is where you want to implement the new HTML table.) Then, in the Palette, double-click the Table icon. . In the Insert Table dialog that displays, specify the following values then click OK: * *Rows*: 2 * *Columns*: 1 * *Border Size*: 0 The HTML table code is generated and added to your page. . Add the following content to the table heading and the cell of the first table row (new content shown in *bold*): [source,xml] ---- <table border=""0""> <thead> <tr> <th>*IFPWAFCAD offers expert counseling in a wide range of fields.*</th> </tr> </thead> <tbody> <tr> <td>*To view the contact details of an IFPWAFCAD certified former professional wrestler in your area, select a subject below:*</td> </tr> ---- . For the bottom row of the table, insert an HTML form. To do so, place your cursor between the second pair of `<td>` tags, then double-click the HTML form ( image:images/html-form-icon.png[] ) icon in the Palette. In the Insert Form dialog, type in `response.jsp` in the Action text field, then click OK. image::images/insert-form.png[title=""Specify form settings in the Insert Form dialog""] . Type in the following content between the `<form>` tags (new content shown in *bold*): [source,xml] ---- <tr> <td> <form action=""response.jsp""> *<strong>Select a subject:</strong>* </form> </td> </tr> ---- . Press Enter to add an empty line after the content you just added and then double-click Drop-down List in the Palette to open the Insert Drop-down dialog box. . Type `subject_id` for the Name text field in the Insert Drop-down dialog and click OK. Note that the code snippet for the drop-down list is added to the form. The number of options for the drop-down is currently not important. Later in the tutorial you will add JSTL tags that dynamically generate options based on the data gathered from the Subject database table. . Add a submit button item ( image:images/submit-button.png[] ) to a point just after the drop-down list you just added. You can either use the Palette to do this, or invoke the editor's code completion as illustrated in the previous step. In the Insert Button dialog, enter `submit` for both the Label and Name text fields, then click OK. . To format your code, right-click in the editor and choose Format (Alt-Shift-F; Ctrl-Shift-F on Mac). Your code is automatically formatted, and should now look similar to the following: [source,xml] ---- <body> <h2>Welcome to <strong>IFPWAFCAD</strong>, the International Former Professional Wrestlers' Association for Counseling and Development! </h2> <table border=""0""> <thead> <tr> <th>IFPWAFCAD offers expert counseling in a wide range of fields.</th> </tr> </thead> <tbody> <tr> <td>To view the contact details of an IFPWAFCAD certified former professional wrestler in your area, select a subject below:</td> </tr> <tr> <td> <form action=""response.jsp""> <strong>Select a subject:</strong> <select name=""subject_id""> <option></option> </select> <input type=""submit"" value=""submit"" name=""submit"" /> </form> </td> </tr> </tbody> </table> </body> ---- To view this page in a browser, right-click in the editor and choose Run File (Shift-F6; Fn-Shift-F6 on Mac). When you do this, the JSP page is automatically compiled and deployed to your server. The IDE opens your default browser to display the page from its deployed location. image::images/browser-output.png[title=""index.jsp displays in a browser""] [[responsePage]] === Creating the response page In order to prepare the interface for `response.jsp` you must first create the file in your project. Note that most of the content that displays in this page is generated dynamically using JSP technology. Therefore, in the following steps you add _placeholders_ which you will later substitute for the JSP code. 1. Right-click the IFPWAFCAD project node in the Projects window and choose New > JSP. The New JSP File dialog opens. 2. In the JSP File Name field, enter `response`. Note that Web Pages is currently selected for the Location field, meaning that the file will be created in the project's `web` directory. This is the same location as where the `index.jsp` welcome page resides. 3. Accept any other default settings and click Finish. A template for the new `response.jsp` page is generated and opens in the editor. A new JSP node also displays under Web Pages in the Projects window. image::images/response-jsp-node.png[title=""response.jsp node appears in the Projects window""] . In the editor, change the title to: `IFPWAFCAD - {placeholder}`. . Remove the `<h1>Hello World!</h1>` line between the `<body>` tags, then copy and paste the following HTML table into the body of the page: [source,xml] ---- <table border=""0""> <thead> <tr> <th colspan=""2"">{placeholder}</th> </tr> </thead> <tbody> <tr> <td><strong>Description: </strong></td> <td><span style=""font-size:smaller; font-style:italic;"">{placeholder}</span></td> </tr> <tr> <td><strong>Counselor: </strong></td> <td>{placeholder} <br> <span style=""font-size:smaller; font-style:italic;""> member since: {placeholder}</span> </td> </tr> <tr> <td><strong>Contact Details: </strong></td> <td><strong>email: </strong> <a href=""mailto:{placeholder}"">{placeholder}</a> <br><strong>phone: </strong>{placeholder} </td> </tr> </tbody> </table> ---- To view this page in a browser, right-click in the editor and choose Run File (Shift-F6; Fn-Shift-F6 on Mac). The page compiles, is deployed to the GlassFish server, and opens in your default browser. image::images/browser-response.png[title=""response.jsp displays in a browser""] [[stylesheet]] === Creating a stylesheet Create a simple stylesheet that enhances the display of the web interface. This tutorial assumes that you understand how style rules function, and how they affect corresponding HTML elements found in `index.jsp` and `response.jsp`. 1. Open the New File wizard by pressing the New File ( image:images/new-file-btn.png[] ) button in the IDE's main toolbar. Select the Web category, then select Cascading Style Sheet and click Next. 2. Type `style` for CSS File Name and click Finish. The IDE creates an empty CSS file and places it in the same project location as `index.jsp` and `response.jsp`. Note that a node for `style.css` now displays within the project in the Projects window, and the file opens in the editor. 3. In the editor, add the following content to the `style.css` file: [source,java] ---- body { font-family: Verdana, Arial, sans-serif; font-size: smaller; padding: 50px; color: #555; } h1 { text-align: left; letter-spacing: 6px; font-size: 1.4em; color: #be7429; font-weight: normal; width: 450px; } table { width: 580px; padding: 10px; background-color: #c5e7e0; } th { text-align: left; border-bottom: 1px solid; } td { padding: 10px; } a:link { color: #be7429; font-weight: normal; text-decoration: none; } a:link:hover { color: #be7429; font-weight: normal; text-decoration: underline; } ---- . Link the stylesheet to `index.jsp` and `response.jsp`. In both pages, add the following line between the `<head>` tags: [source,java] ---- <link rel=""stylesheet"" type=""text/css"" href=""style.css""> ---- [tips]#To quickly navigate between files that are open in the editor, press Ctrl-Tab, then select the file you are wanting.# [[prepareCommunication]] == Preparing Communication between the Application and Database The most efficient way to implement communication between the server and database is to set up a database _connection pool_. Creating a new connection for each client request can be very time-consuming, especially for applications that continuously receive a large number of requests. To remedy this, numerous connections are created and maintained in a connection pool. Any incoming requests that require access to the application's data layer use an already-created connection from the pool. Likewise, when a request is completed, the connection is not closed down, but returned to the pool. After preparing the data source and connection pool for the server, you then need to instruct the application to use the data source. This is typically done by creating an entry in the application's `web.xml` deployment descriptor. Finally, you need to ensure that the database driver (MySQL Connector/J JDBC Driver) is accessible to the server. *Important: * From this point forward, you need you ensure that you have a MySQL database instance named `MyNewDatabase` set up that contains sample data provided in link:https://netbeans.org/projects/samples/downloads/download/Samples%252FJava%2520Web%252Fifpwafcad.sql[+ifpwafcad.sql+]. This SQL file creates two tables, `Subject` and `Counselor`, then populates them with sample data. If you have not already done this, or if you need help with this task, see link:../../docs/ide/mysql.html[+Connecting to a MySQL Database+] before proceeding further. Also, your database needs to be password-protected to create a data source and work with the GlassFish server in this tutorial. If you are using the default MySQL `root` account with an empty password, you can set the password from a command-line prompt. This tutorial uses `nbuser` as an example password. To set your password to `_nbuser_`, navigate to your MySQL installation's `bin` directory in the command-line prompt and enter the following: [source,java] ---- shell> mysql -u root mysql> UPDATE mysql.user SET Password = PASSWORD('_nbuser_') -> WHERE User = 'root'; mysql> FLUSH PRIVILEGES; ---- For more information, see the official MySQL Reference Manual: link:http://dev.mysql.com/doc/refman/5.1/en/default-privileges.html[+Securing the Initial MySQL Accounts+]. 1. <<setUpJDBC,Setting up a JDBC data source and connection pool>> 2. <<referenceDataSource,Referencing the data source from the application>> 3. <<addJar,Adding the database driver's JAR file to the server>> [[setUpJDBC]] === Setting up a JDBC data source and connection pool The GlassFish Server Open Source Edition contains Database Connection Pooling (DBCP) libraries that provide connection pooling functionality in a way that is transparent to you as a developer. To take advantage of this, you need to configure a link:http://docs.oracle.com/javase/tutorial/jdbc/overview/index.html[+JDBC+] (Java Database Connectivity) _data source_ for the server which your application can use for connection pooling. For more information on JDBC technology, see link:http://docs.oracle.com/javase/tutorial/jdbc/basics/index.html[+The Java Tutorials: JDBC Basics+]. You could configure the data source directly within the GlassFish server Admin Console, or, as described below, you can declare the resources that your application needs in a `glassfish-resources.xml` file. When the application is deployed, the server reads in the resource declarations, and creates the necessary resources. The following steps demonstrate how to declare a connection pool, and a data source that relies on the connection pool. The NetBeans JDBC Resource wizard allows you to perform both actions. 1. Open the New File wizard by pressing the New File ( image:images/new-file-btn.png[] ) button in the IDE's main toolbar. Select the GlassFish server category, then select JDBC Resource and click Next. 2. In step 2, General Attributes, choose the Create New JDBC Connection Pool option, then in the JNDI Name text field, type in *jdbc/IFPWAFCAD*. image::images/jdbc-resource-wizard.png[title=""Specify data source settings in the JDBC Resource wizard""] [tips]#The JDBC data source relies on link:http://www.oracle.com/technetwork/java/jndi/index.html[+JNDI+], the Java Naming and Directory Interface. The JNDI API provides a uniform way for applications to find and access data sources. For more information, see link:http://docs.oracle.com/javase/jndi/tutorial/[+The JNDI Tutorial+].# . Optionally, add a description for the data source. For example, type in: `Accesses the database that provides data for the IFPWAFCAD application`. . Click Next, then click Next again to skip step 3, Additional Properties. . In Step 4, type in *IfpwafcadPool* for JDBC Connection Pool Name. Make sure the Extract from Existing Connection option is selected, and choose `jdbc:mysql://localhost:3306/MyNewDatabase` from the drop-down list. Click Next. image::images/jdbc-resource-wizard2.png[title=""Specify connection pool settings in the JDBC Resource wizard""] *Note: *The wizard detects any database connections that have been set up in the IDE. Therefore, you need to have already created a connection to the `MyNewDatabase` database at this point. You can verify what connections have been created by opening the Services window (Ctrl-5; ⌘-5 on Mac) and looking for connection nodes ( image:images/connection-node-icon.png[] ) under the Databases category. . In Step 5, select `javax.sql.ConnectionPoolDataSource` in the Resource Type drop-down list. Note that the IDE extracts information from the database connection you specified in the previous step, and sets name-value properties for the new connection pool. image::images/jdbc-resource-wizard3.png[title=""Default values are based on information extracted from the selected database connection""] . Click Finish. The wizard generates a `glassfish-resources.xml` file that contains entries for the data source and connection pool you specified. In the Projects window, you can open the `glassfish-resources.xml` file that was created under the Server Resources node and note that, within the `<resources>` tags, a data source and connection pool have been declared containing the values you previously specified. To confirm that a new data source and connection pool are indeed registered with the GlassFish server, you can deploy the project to the server, then locate the resources in the IDE's Services window: 1. In the Projects window, right-click the IFPWAFCAD project node and choose Deploy. The server starts up if not already running, and the project is compiled and deployed to it. 2. Open the Services window (Ctrl-5; ⌘-5 on Mac) and expand the Servers > GlassFish > Resources > JDBC > JDBC Resources and Connection Pools nodes. Note that the new data source and connection pool are now displayed: image::images/services-window-glassfish.png[title=""New data source and connection pool displayed in Services window""] [[referenceDataSource]] === Referencing the data source from the application You need to reference the JDBC resource you just configured from the web application. To do so, you can create an entry in the application's `web.xml` deployment descriptor. Deployment descriptors are XML-based text files that contain information describing how an application is to be deployed to a specific environment. For example, they are normally used to specify application context parameters and behavioral patterns, security settings, as well as mappings for servlets, filters and listeners. *Note.* If you specified Java EE 6 or Java EE 7 as the Java version when you created the project, you need to create the deployment descriptor file by choosing Web > Standard Deployment Descriptor in the New File wizard. Perform the following steps to reference the data source in the application's deployment descriptor. 1. In the Projects window, expand the Configuration Files folder and double-click `web.xml` to open the file in the editor. 2. Click the References tab located along the top of the editor. 3. Expand the Resource References heading and click Add to open the Add Resource Reference dialog. 4. For Resource Name, enter the resource name that you gave when configuring the data source for the server above (`jdbc/IFPWAFCAD`). 5. Type *`javax.sql.ConnectionPoolDataSource`* in the Resource Type field. Click OK. The Description field is optional, but you can enter a human-readable description of the resource, e.g., `Database for IFPWAFCAD application`. image::images/add-resource-reference.png[title=""Specify resource properties in the Add Resource Reference dialog""] The new resource is now listed under the Resource References heading. . To verify that the resource is now added to the `web.xml` file, click the Source tab located along the top of the editor. Notice that the following <`resource-ref`> tags are now included. [source,xml] ---- <resource-ref> <description>Database for IFPWAFCAD application</description> <res-ref-name>jdbc/IFPWAFCAD</res-ref-name> <res-type>javax.sql.ConnectionPoolDataSource</res-type> <res-auth>Container</res-auth> <res-sharing-scope>Shareable</res-sharing-scope> </resource-ref> ---- [[addJar]] === Adding the database driver's JAR file to the server Adding the database driver's JAR file is another step that is vital to enabling the server to communicate with your database. Ordinarily, you would need to locate your database driver's installation directory and copy the `mysql-connector-java-5.1.6-bin.jar` file from the driver's root directory into the library folder of the server you are using. Fortunately, the IDE's server management is able to detect at deployment whether the JAR file has been added - and if not, it does so automatically. In order to demonstrate this, open the Servers manager (Choose Tools > Servers). The IDE provides a JDBC driver deployment option. If the option is enabled, it initiates a check to determine whether any drivers are required for the server's deployed applications. In the case of MySQL, if the driver is required and it is missing, the IDE's bundled driver is deployed to the appropriate location on the server. 1. Choose Tools > Servers to open the Servers manager. Select the GlassFish server in the left pane. 2. In the main pane, select the Enable JDBC Driver Deployment option. image::images/servers-window.png[title=""JDBC Driver Deployment option enables automatic driver deployment""] . Before you close the Servers manager, make a note of the path indicated in the Domains folder text field. When you connect to the GlassFish server in the IDE, you are actually connecting to an _instance_ of the application server. Each instance runs applications in a unique domain, and the Domain Name field indicates the name of the domain your server is using. As shown in the image above, the driver JAR file should be located within `domain1`, which is the default domain created upon installing the GlassFish server. . Click Close to exit the Servers manager. . On your computer, navigate to the GlassFish server installation directory and drill into the `domains` > `domain1` > `lib` subfolder. Because you should have already deployed the IFPWAFCAD project to the server, you should see the `mysql-connector-java-5.1.6-bin.jar` file. If you do not see the driver JAR file, perform the following step. . Deploy your project to the server. In the IDE's Projects window, choose Deploy from the right-click menu of the project node. You can view progress in the IDE's Output window (Ctrl-4; ⌘-4 on Mac). The output indicates that the MySQL driver is deployed to a location in the GlassFish server. image::images/output-window.png[title=""Output window indicates that the MySQL driver has been deployed""] Now, if you return to the `domain1/lib` subfolder on your computer, you can see that the `mysql-connector-java-5.1.6-bin.jar` file has been automatically added. [[addLogic]] == Adding Dynamic Logic Returning to the `index.jsp` and `response.jsp` placeholders that you created earlier in the tutorial, you can now implement the JSTL code that enables pages to generate content _dynamically_, i.e., based on user input. To do so, perform the following three tasks. 1. <<addJSTL,Add the JSTL library to the project's classpath>> 2. <<implementCode,Implement JSTL code>> [[addJSTL]] === Adding the JSTL library to the project's classpath You can apply the link:http://www.oracle.com/technetwork/java/index-jsp-135995.html[+JavaServer Pages Standard Tag Library+] (JSTL) to access and display data taken from the database. The GlassFish server includes the JSTL library by default. You can verify this by expanding the GlassFish Server node under the Libraries node in the Projects window, and searching for the `javax.servlet.jsp.jstl.jar` library. (Older versions of the GlassFish server use the `jstl-impl.jar` library.) Because the GlassFish server libraries are by default added to your project's classpath, you do not have to perform any steps for this task. JSTL provides the following four basic areas of functionality. * `core`: common, structural tasks such as iterators and conditionals for handling flow control * `fmt`: internationalization and localization message formatting * `sql`: simple database access * `xml`: handling of XML content This tutorial focuses on usage of the `core` and `sql` tag libraries. [[implementCode]] === Implementing JSTL code Now you can implement the code that dynamically retrieves and displays data for each page. Both pages require that you implement an SQL query that utilizes the data source created earlier in the tutorial. The IDE provides several database-specific JSTL snippets which you can select from the Palette (Ctrl-Shift-8; ⌘-Shift-8 on Mac). image::images/palette-db.png[title=""Choose database-specific JSTL snippets from the Palette""] ==== index.jsp In order to dynamically display the contents of the form in `index.jsp`, you need to access all `name`s from the `Subject` database table. 1. Hover your mouse over the DB Report item in the Palette. image::images/db-report.png[title=""Type 'db' and press Ctrl-Space to access database-specific JSTL snippets""] The DB Report item uses the `<sql:query>` tag to create an SQL query, then it uses the `<c:forEach>` tag to loop through the query's `resultset` and output the retrieved data. . Place your cursor above the `<%@page ... %>` declaration (line 7), then double-click the DB Report item in the Palette. In the dialog that displays, enter the following details: * *Variable Name:* `subjects` * *Scope:* `page` * *Data Source:* `jdbc/IFPWAFCAD` * *Query Statement:* `SELECT subject_id, name FROM Subject` image::images/insert-db-report.png[title=""Use the Insert DB Report dialog to specify query-specific details""] . Click OK. The following content is generated in the `index.jsp` file. (New content shown in *bold*.) [source,xml] ---- *<%@taglib prefix=""c"" uri=""http://java.sun.com/jsp/jstl/core""%> <%@taglib prefix=""sql"" uri=""http://java.sun.com/jsp/jstl/sql""%>* <%-- Document : index Author : nbuser --%> *<sql:query var=""subjects"" dataSource=""jdbc/IFPWAFCAD""> SELECT subject_id, name FROM Subject </sql:query> <table border=""1""> <!-- column headers --> <tr> <c:forEach var=""columnName"" items=""${subjects.columnNames}""> <th><c:out value=""${columnName}""/></th> </c:forEach> </tr> <!-- column data --> <c:forEach var=""row"" items=""${subjects.rowsByIndex}""> <tr> <c:forEach var=""column"" items=""${row}""> <td><c:out value=""${column}""/></td> </c:forEach> </tr> </c:forEach> </table>* <%@page contentType=""text/html"" pageEncoding=""UTF-8""%> <!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01 Transitional//EN"" ""http://www.w3.org/TR/html4/loose.dtd""> ---- Note that the IDE automatically added `taglib` directives needed for the JSTL tags used in the generated content (`<sql:query>` and `<c:forEach>`). A `taglib` directive declares that the JSP page uses custom (i.e., JSTL) tags, names the tag library that defines them, and specifies their tag prefix. . Run the project to see how it displays in a browser. Right-click the project node in the Projects window and choose Run. When you choose Run, the IDE deploys the project to the GlassFish server, the index page is compiled into a servlet, and the welcome page opens in your default browser. The code generated from the DB Report item creates the following table in the welcome page. image::images/db-report-table.png[title=""Use DB Report for quick prototyping of database table data""] As you can see, the DB Report item enables you to quickly test your database connection, and enables you to view table data from the database in your browser. This can be particularly useful when prototyping. The following steps demonstrate how to integrate the generated code into the HTML drop-down list you created earlier in the tutorial. . Examine the column data in the generated code. Two `<c:forEach>` tags are used; one is nested inside the other. This causes the JSP container (i.e., the GlassFish server) to perform a loop on all table rows, and for each row, it loops through all columns. In this manner, data for the entire table is displayed. . Integrate the `<c:forEach>` tags into the HTML form as follows. The value of each item becomes the `subject_id`, and the output text becomes the `name`, as recorded in the database. (Changes are displayed in *bold*). [source,xml] ---- <form action=""response.jsp""> <strong>Select a subject:</strong> <select name=""subject_id""> *<c:forEach var=""row"" items=""${subjects.rowsByIndex}""> <c:forEach var=""column"" items=""${row}"">* <option *value=""<c:out value=""${column}""/>""*>*<c:out value=""${column}""/>*</option> *</c:forEach> </c:forEach>* </select> <input type=""submit"" value=""submit"" name=""submit"" /> </form> ---- [tips]#An alternative, simpler way to integrate the `<c:forEach>` tags into the HTML form would be as follows.# [source,xml] ---- <form action=""response.jsp""> <strong>Select a subject:</strong> <select name=""subject_id""> *<c:forEach var=""row"" items=""${subjects.rows}"">* <option *value=""${row.subject_id}""*>*${row.name}*</option> *</c:forEach>* </select> <input type=""submit"" value=""submit"" name=""submit"" /> </form> ---- In either case, the `<c:forEach>` tags loop through all `subject_id` and `name` values from the SQL query, and insert each pair into the HTML `<option>` tags. In this manner, the form's drop-down list is populated with data. . Delete the table that was generated from the DB Report item. (Deletion shown below as *[.line-through]#strike-through text#*.) [source,xml] ---- <%@taglib prefix=""c"" uri=""http://java.sun.com/jsp/jstl/core""%> <%@taglib prefix=""sql"" uri=""http://java.sun.com/jsp/jstl/sql""%> <%-- Document : index Created on : Dec 22, 2009, 7:39:49 PM Author : nbuser --%> <sql:query var=""subjects"" dataSource=""jdbc/IFPWAFCAD""> SELECT subject_id, name FROM Subject </sql:query> *[.line-through]#<table border=""1""> <!-- column headers --> <tr> <c:forEach var=""columnName"" items=""${subjects.columnNames}""> <th><c:out value=""${columnName}""/></th> </c:forEach> </tr> <!-- column data --> <c:forEach var=""row"" items=""${subjects.rowsByIndex}""> <tr> <c:forEach var=""column"" items=""${row}""> <td><c:out value=""${column}""/></td> </c:forEach> </tr> </c:forEach> </table>#* <%@page contentType=""text/html"" pageEncoding=""UTF-8""%> <!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01 Transitional//EN"" ""http://www.w3.org/TR/html4/loose.dtd""> ---- . Save your changes (Ctrl-S; ⌘-S on Mac). . Refresh the welcome page of the project in your browser. Note that the drop-down list in the browser now contains subject names that were retrieved from the database. You do not need to redeploy your project because compile-on-save is enabled for your project by default. This means that when you modify and save a file, the file is automatically compiled and deployed and you do not need to recompile the entire project. You can enable and disable compile-on-save for your project in the Compiling category of the Properties window of the project. ==== response.jsp The response page provides details for the counselor who corresponds to the subject chosen in the welcome page. The query you create must select the counselor record whose `counselor_id` matches the `counselor_idfk` from the selected subject record. 1. Place your cursor above the `<%@page ... %>` declaration (line 7), and double-click DB Query in the Palette to open the Insert DB Query dialog box. 2. Enter the following details in the Insert DB Query dialog box. * *Variable Name:* `counselorQuery` * *Scope:* `page` * *Data Source:* `jdbc/IFPWAFCAD` * *Query Statement:* `SELECT * FROM Subject, Counselor WHERE Counselor.counselor_id = Subject.counselor_idfk AND Subject.subject_id = ? <sql:param value=""${param.subject_id}""/>` image::images/insert-db-query2.png[title=""Use the Insert DB Query dialog to specify query-specific details""] . Click OK. The following content is generated in the `response.jsp` file. (New content shown in *bold*.) [source,xml] ---- *<%@taglib prefix=""sql"" uri=""http://java.sun.com/jsp/jstl/sql""%>* <%-- Document : response Created on : Dec 22, 2009, 8:52:57 PM Author : nbuser --%> *<sql:query var=""counselorQuery"" dataSource=""jdbc/IFPWAFCAD""> SELECT * FROM Subject, Counselor WHERE Counselor.counselor_id = Subject.counselor_idfk AND Subject.subject_id = ? <sql:param value=""${param.subject_id}""/> </sql:query>* <%@page contentType=""text/html"" pageEncoding=""UTF-8""%> <!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01 Transitional//EN"" ""http://www.w3.org/TR/html4/loose.dtd""> ---- Note that the IDE automatically added the `taglib` directive needed for the `<sql:query>` tag. Also, note that you used an `<sql:param>` tag directly within the query. Because this query relies on the `subject_id` value that was submitted from `index.jsp`, you can extract the value using an EL (Expression Language) statement in the form of `${param.subject_id}`, and then pass it to the `<sql:param>` tag so that it can be used in place of the SQL question mark (`?`) during runtime. . Use a `<c:set>` tag to set a variable that corresponds to the first record (i.e., row) of the `resultset` returned from the query. (New content shown in *bold*.) [source,xml] ---- <sql:query var=""counselorQuery"" dataSource=""jdbc/IFPWAFCAD""> SELECT * FROM Subject, Counselor WHERE Counselor.counselor_id = Subject.counselor_idfk AND Subject.subject_id = ? <sql:param value=""${param.subject_id}""/> </sql:query> *<c:set var=""counselorDetails"" value=""${counselorQuery.rows[0]}""/>* ---- Although the `resultset` returned from the query should only contain a single record, this is a necessary step because the page needs to access values from the record using EL (Expression Language) statements. Recall that in `index.jsp`, you were able to access values from the `resultset` simply by using a `<c:forEach>` tag. However, the `<c:forEach>` tag operates by setting a variable for the rows contained in the query, thus enabling you to extract values by including the row variable in EL statements. . Add the `taglib` directive for the JSTL `core` library to the top of the file, so that the `<c:set>` tag is understood. (New content shown in *bold*.) [source,java] ---- *<%@taglib prefix=""c"" uri=""http://java.sun.com/jsp/jstl/core""%>* <%@taglib prefix=""sql"" uri=""http://java.sun.com/jsp/jstl/sql""%> ---- . In the HTML markup, replace all placeholders with EL statements code that display the data held in the `counselorDetails` variable. (Changes below shown in *bold*): [source,xml] ---- <html> <head> <meta http-equiv=""Content-Type"" content=""text/html; charset=UTF-8""/> <link rel=""stylesheet"" type=""text/css"" href=""style.css""> <title>*${counselorDetails.name}*
*${counselorDetails.name}*
Description: *${counselorDetails.description}*
Counselor: *${counselorDetails.first_name} ${counselorDetails.nick_name} ${counselorDetails.last_name}*
member since: *${counselorDetails.member_since}*
Contact Details: email: *${counselorDetails.email}*
phone: *${counselorDetails.telephone}*
---- [[run]] == Running the Completed Application You've now completed the application. Try running it again to see how it displays in a browser. Note that because of NetBeans' Compile on Save feature, you do not need to worry about compiling or redeploying the application. When you run a project, you can be sure the deployment contains your latest changes. Click the Run Project ( image:images/run-project-btn.png[] ) button in the main toolbar. The `index.jsp` page opens in the IDE's default browser. When `index.jsp` displays in the browser, select a subject from the drop-down list and click `submit`. You should now be forwarded to the `response.jsp` page, showing details corresponding to your selection. image::images/response-display.png[title=""response.jsp displayed in a browser, showing data retrieved from database""] This concludes the Creating a Simple Web Application Using a MySQL Database tutorial. This document demonstrated how to create a simple web application that connects to a MySQL database. It also demonstrated how to construct an application using a basic two-tier architecture, and utilized numerous technologies including JSP, JSTL, JDBC, and JNDI as a means of accessing and displaying data dynamically. [[troubleshoot]] == Troubleshooting Most of the problems that occur with the tutorial application are due to communication difficulties between the GlassFish Server Open Source Edition and the MySQL database server. If your application does not display correctly, or if you are receiving a server error, the following examinations may be useful. * <> * <> * <> * <> * <> [[access]] === Do database resources exist? Use the IDE's Services window (Ctrl-5; ⌘-5 on Mac) to ensure that the MySQL server is running, and that `MyNewDatabase` is accessible and contains appropriate table data. * To connect to the MySQL database server, right-click the MySQL Server node and choose Connect. * If a connection node ( image:images/db-connection-node.png[] ) for `MyNewDatabase` does not display in the Services window, you can create a connection by right-clicking the MySQL driver node ( image:images/driver-node.png[] ) and choosing Connect Using. Enter the required details in the dialog that displays. image::images/new-db-connection-dialog.png[title=""Establish a database connection in the IDE using the New Database Connection dialog""] [tips]#The fields provided in the New Database Connection dialog mirror the URL string entered in the Show JDBC URL option. Therefore, if you know the URL (e.g., `jdbc:mysql://localhost:3306/MyNewDatabase`) you can paste it into the Show JDBC URL field, and the remaining dialog fields become automatically populated.# * To ensure that the `Subject` and `Counselor` tables exist and that they contain sample data, expand the `MyNewDatabase` connection node ( image:images/db-connection-node.png[] ) and locate the `MyNewDatabase` catalog node ( image:images/db-catalog-node.png[] ). Expand the catalog node to view existing tables. You can view table data by right-clicking a table node and choosing View Data. image::images/services-window-view-data.png[title=""View table data by choosing View Data from the right-click menu of a database table node""] [[datasource]] === Do the connection pool and data source exist on the server? After deploying the application to the GlassFish server, the `glassfish-resources.xml` contained in the project should instruct the server to create a JDBC resource and connection pool. You can determine whether these exist from the Servers node in the Services window. * Expand the Servers > the GlassFish Server > Resources node. Expand JDBC Resources to view the `jdbc/IFPWAFCAD` data source that was created from `glassfish-resources.xml`. Expand the Connection Pools node to view the `IfpwafcadPool` connection pool that was created from `glassfish-resources.xml`. (This is <>.) [[driver]] === Is the MySQL Connector/J driver accessible to the GlassFish server? Make sure that the MySQL Connector/J driver has been deployed to the GlassFish server. (This is discussed in <>.) * Locate the GlassFish server installation folder on your computer and drill down into the `GlassFish domains/domain1/lib` subfolder. Here you should find the `mysql-connector-java-5.1.6-bin.jar` file. [[password]] === Is the database password-protected? The database needs to be password-protected to enable the GlassFish server data source to work properly in this tutorial. If you are using the default MySQL `root` account with an empty password, you can set the password from a command-line prompt. * To set your password to `_nbuser_`, navigate to your MySQL installation's `bin` directory in the command-line prompt and enter the following: [source,java] ---- shell> mysql -u root mysql> UPDATE mysql.user SET Password = PASSWORD('_nbuser_') -> WHERE User = 'root'; mysql> FLUSH PRIVILEGES; ---- For more information, see the official MySQL Reference Manual: link:http://dev.mysql.com/doc/refman/5.1/en/default-privileges.html[+Securing the Initial MySQL Accounts+]. [[ping]] === Are the connection pool properties correctly set? Ensure that the connection pool is working correctly for the server. 1. Open the Services window (Ctrl-5; ⌘-5 on Mac) and expand the Servers node. 2. Right-click the GlassFish server node and choose View Admin Console. 3. Enter the username and password if you are prompted. You can view the username and password in the Servers manager. 4. In the tree on the left side of the console, expand the Resources > JDBC > JDBC Connection Pools > `IfpwafcadPool` node. Details for the `IfpwafcadPool` connection pool display in the main window. 5. Click the Ping button. If the connection pool is set up correctly, you will see a '`Ping Succeeded`' message. image::images/ping-succeeded.png[title=""Test your connection pool by clicking Ping in the GlassFish server Admin Console""] . If the ping fails, click the Additional Properties tab and ensure that the listed property values are correctly set. link:/about/contact_form.html?to=3&subject=Feedback:%20Creating%20Web%20App%20MySQL[+Send Us Your Feedback+] [[seealso]] == See Also For more information about Java web development, see the following resources. * *NetBeans Articles and Tutorials* * link:../ide/mysql.html[+Connecting to a MySQL Database in NetBeans IDE+]. Covers the basics of working with a MySQL database in the IDE. * link:jsf20-intro.html[+Introduction to JavaServer Faces 2.x+]. An introductory tutorial describing how to use the JSF framework in a Java web project. * link:quickstart-webapps-spring.html[+Introduction to the Spring Framework+]. An introductory tutorial describing how to create an MVC web application using the Spring Framework. * *Java Database Connectivity (JDBC)* * link:http://docs.oracle.com/javase/tutorial/jdbc/overview/index.html[+JDBC Overview+] * link:http://download.oracle.com/javase/6/docs/technotes/guides/jdbc/getstart/GettingStartedTOC.fm.html[+Getting Started with the JDBC API+] * link:http://docs.oracle.com/javase/tutorial/jdbc/basics/index.html[+The Java Tutorials: JDBC Basics+] * *JavaServer Pages Standard Tag Library (JSTL)* * link:http://www.oracle.com/technetwork/java/index-jsp-135995.html[+JavaServer Pages Standard Tag Library+] (official product page) * *Java Naming and Directory Interface (JNDI)* * link:http://www.oracle.com/technetwork/java/jndi-136720.html[+Java SE Core Technologies - Java Naming and Directory Interface+] * link:http://docs.oracle.com/javase/jndi/tutorial/[+The JNDI Tutorial+] * link:http://docs.oracle.com/javase/tutorial/jndi/index.html[+The Java Tutorials: Java Naming and Directory Interface+] ",12081,False,2256.0620840365373,median "CLASS zcl_transport_controller DEFINITION PUBLIC CREATE PUBLIC . PUBLIC SECTION. *""* public components of class ZCL_TRANSPORT_CONTROLLER *""* do not include other source files here!!! CONSTANTS c_tr_attribute_id TYPE trattr VALUE 'ZBT_BUG'. ""#EC NOTEXT CLASS-METHODS create IMPORTING !transport TYPE REF TO zcl_transport RAISING zcx_create_exception . CLASS-METHODS exist IMPORTING !transport TYPE REF TO zcl_transport RETURNING value(return) TYPE flag . CLASS-METHODS find_by_key IMPORTING value(id) TYPE zbt_transporter-transportreq RETURNING value(return) TYPE REF TO zcl_transport RAISING zcx_not_found_exception . CLASS-METHODS find_all_bug_transports IMPORTING !bug TYPE REF TO zcl_bug RETURNING value(result) TYPE zbt_transport_tbl . CLASS-METHODS update IMPORTING !transport TYPE REF TO zcl_transport RAISING zcx_update_exception . CLASS-METHODS delete IMPORTING !transport TYPE REF TO zcl_transport RAISING zcx_delete_exception . CLASS-METHODS read_tr_attributes IMPORTING !trkorr TYPE trkorr RETURNING value(bugs) TYPE zbt_producto_bug_id_tbl . CLASS-METHODS update_tr_attributes IMPORTING !transport TYPE REF TO zcl_transport . PROTECTED SECTION. private section. *""* private components of class ZCL_TRANSPORT_CONTROLLER *""* do not include other source files here!!! class-data TRANSPORT_BUFFER type ZBT_TRANSPORT_TBL . class-methods RETRIEVE_BUGS_FROM_PERSISTENCE importing !TRANSPORT type ref to ZCL_TRANSPORT returning value(BUGS) type ZBT_BUGS raising ZCX_NOT_FOUND_EXCEPTION . ENDCLASS. CLASS ZCL_TRANSPORT_CONTROLLER IMPLEMENTATION. METHOD create. DATA: l_str TYPE zbt_transporter, lt_bugs TYPE zbt_bugs, l_bug TYPE LINE OF zbt_bugs, lo_producto TYPE REF TO zcl_producto, lo_transaccion TYPE REF TO zcl_transaction_service, lo_exception TYPE REF TO cx_root. TRY . lt_bugs = transport->get_bugs( ). LOOP AT lt_bugs INTO l_bug. AT FIRST. CREATE OBJECT lo_transaccion. lo_transaccion->start( ). l_str-transportreq = transport->get_id( ). ENDAT. l_str-bug = l_bug-oref->get_id( ). lo_producto = l_bug-oref->get_producto( ). l_str-producto = lo_producto->get_id( ). zca_transport_persist=>agent->create_persistent( i_bug = l_str-bug i_producto = l_str-producto i_transportreq = l_str-transportreq ). AT LAST. lo_transaccion->end( ). ENDAT. ENDLOOP. CATCH cx_root INTO lo_exception. RAISE EXCEPTION TYPE zcx_create_exception EXPORTING textid = zcx_create_exception=>zcx_create_exception previous = lo_exception. ENDTRY. ENDMETHOD. ""create METHOD delete. DATA: l_str TYPE zbt_transporter, lt_bugs TYPE zbt_bugs, l_bug TYPE LINE OF zbt_bugs, lo_producto TYPE REF TO zcl_producto, lo_transaccion TYPE REF TO zcl_transaction_service, lo_exception TYPE REF TO cx_root. TRY . lt_bugs = transport->get_bugs( ). LOOP AT lt_bugs INTO l_bug. AT FIRST. CREATE OBJECT lo_transaccion. lo_transaccion->start( ). l_str-transportreq = transport->get_id( ). ENDAT. l_str-bug = l_bug-oref->get_id( ). l_str-producto = lo_producto->get_id( ). zca_transport_persist=>agent->delete_persistent( i_bug = l_str-bug i_producto = l_str-producto i_transportreq = l_str-transportreq ). AT LAST. lo_transaccion->end( ). ENDAT. ENDLOOP. CATCH cx_root INTO lo_exception. RAISE EXCEPTION TYPE zcx_delete_exception EXPORTING textid = zcx_delete_exception=>zcx_delete_exception previous = lo_exception. ENDTRY. ENDMETHOD. ""delete METHOD exist. DATA: l_id TYPE zbt_transporter-transportreq. TRY . l_id = transport->get_id( ). zcl_transport_controller=>find_by_key( l_id ). return = 'X'. CATCH cx_root. return = space. ENDTRY. ENDMETHOD. ""EXIST METHOD find_all_bug_transports. DATA: lo_qm TYPE REF TO if_os_query_manager, lo_q TYPE REF TO if_os_query, lo_producto TYPE REF TO zcl_producto, lo_transporte TYPE REF TO zcl_transport, l_id_producto TYPE zbt_producto-producto, l_id_bug TYPE zbt_id_bug, l_id_transporte TYPE zbt_transportreq, l_str TYPE zbt_transport_str, lt_transporte_persist TYPE osreftab, lo_transporte_persist TYPE REF TO zcl_transport_persist. FIELD-SYMBOLS: TYPE osref. l_id_bug = bug->get_id( ). lo_producto = bug->get_producto( ). l_id_producto = lo_producto->get_id( ). * Montamos una query para obtener las secciones de un bug lo_qm = cl_os_system=>get_query_manager( ). lo_q = lo_qm->create_query( i_filter = 'PRODUCTO = PAR1 AND BUG = PAR2 ' ). lt_transporte_persist[] = zca_transport_persist=>agent->if_os_ca_persistency~get_persistent_by_query( i_query = lo_q i_par1 = l_id_producto i_par2 = l_id_bug ). LOOP AT lt_transporte_persist ASSIGNING . lo_transporte_persist ?= . l_id_transporte = lo_transporte_persist->get_transportreq( ). READ TABLE result WITH KEY transport_id = l_id_transporte TRANSPORTING NO FIELDS. IF NOT sy-subrc IS INITIAL. TRY . lo_transporte = find_by_key( l_id_transporte ). l_str-transport_id = l_id_transporte. l_str-oref = lo_transporte. INSERT l_str INTO TABLE result[]. CATCH zcx_not_found_exception. ENDTRY. ENDIF. ENDLOOP. ENDMETHOD. ""find_all_bug_transports METHOD find_by_key. DATA: lt_bugs TYPE zbt_bugs, l_bug TYPE LINE OF zbt_bugs, l_transport_buffer TYPE LINE OF zbt_transport_tbl. READ TABLE transport_buffer WITH KEY transport_id = id INTO l_transport_buffer. IF NOT sy-subrc IS INITIAL. l_transport_buffer-transport_id = id. CREATE OBJECT l_transport_buffer-oref EXPORTING id = l_transport_buffer-transport_id. INSERT l_transport_buffer INTO TABLE transport_buffer. return = l_transport_buffer-oref. * Retrieve bugs related to this transport request from within persistence layer lt_bugs = retrieve_bugs_from_persistence( return ). LOOP AT lt_bugs INTO l_bug. return->add_bug( l_bug-oref ). ENDLOOP. ELSE. return = l_transport_buffer-oref. ENDIF. IF NOT return IS BOUND. * If nothing is found... RAISE EXCEPTION TYPE zcx_not_found_exception EXPORTING textid = zcx_not_found_exception=>zcx_not_found_exception. ENDIF. ENDMETHOD. ""find_by_key METHOD read_tr_attributes. * types: TRWBO. DATA: lt_attr TYPE TRATTRIBUTES, ""trwbo_t_e070a, l_attr TYPE LINE OF TRATTRIBUTES, ""trwbo_t_e070a, l_bug TYPE LINE OF zbt_producto_bug_id_tbl. CALL FUNCTION 'TR_READ_ATTRIBUTES' EXPORTING iv_request = trkorr IMPORTING et_attributes = lt_attr EXCEPTIONS invalid_request = 1 no_authorization = 2 OTHERS = 3. LOOP AT lt_attr INTO l_attr WHERE attribute = c_tr_attribute_id. l_bug = l_attr-reference. INSERT l_bug INTO TABLE bugs[]. ENDLOOP. ENDMETHOD. ""read_tr_attributes METHOD retrieve_bugs_from_persistence. DATA: lo_qm TYPE REF TO if_os_query_manager, lo_q TYPE REF TO if_os_query, lo_producto TYPE REF TO zcl_producto, lo_bug TYPE REF TO zcl_bug, lt_bug_id TYPE zbt_producto_bug_id_tbl, l_bug_str TYPE LINE OF zbt_bugs, l_bug_id TYPE LINE OF zbt_producto_bug_id_tbl, l_id_producto TYPE zbt_producto-producto, l_id_bug TYPE zbt_id_bug, lo_exception TYPE REF TO cx_root, lt_transporte_persist TYPE osreftab, l_transport_id TYPE zbt_transporter-transportreq, lo_transporte_persist TYPE REF TO zcl_transport_persist. FIELD-SYMBOLS: TYPE osref. l_transport_id = transport->get_id( ). * Montamos una query para obtener las secciones de un bug lo_qm = cl_os_system=>get_query_manager( ). lo_q = lo_qm->create_query( i_filter = 'TRANSPORTREQ = PAR1' ). lt_transporte_persist[] = zca_transport_persist=>agent->if_os_ca_persistency~get_persistent_by_query( i_query = lo_q i_par1 = l_transport_id ). * We read attributes from the transport order (all bugs must be in DB, but...) lt_bug_id[] = zcl_transport_controller=>read_tr_attributes( l_transport_id ). LOOP AT lt_bug_id INTO l_bug_id. TRY. lo_producto = zcl_producto_controller=>find_by_key( l_bug_id-producto ). lo_bug = zcl_bug_controller=>find_by_key( id = l_bug_id-bug producto = lo_producto ). l_bug_str-producto_id = l_bug_id-producto. l_bug_str-bug_id = l_bug_id-bug. l_bug_str-oref = lo_bug. READ TABLE bugs WITH KEY producto_id = l_id_producto bug_id = l_id_bug TRANSPORTING NO FIELDS. IF NOT sy-subrc IS INITIAL. INSERT l_bug_str INTO TABLE bugs. ENDIF. CATCH zcx_not_found_exception. ENDTRY. ENDLOOP. LOOP AT lt_transporte_persist ASSIGNING . * Now we add bugs from BugTracker Tables TRY . lo_transporte_persist ?= . l_id_bug = lo_transporte_persist->get_bug( ). l_id_producto = lo_transporte_persist->get_producto( ). lo_producto = zcl_producto_controller=>find_by_key( id = l_id_producto ). lo_bug = zcl_bug_controller=>find_by_key( id = l_id_bug producto = lo_producto ). l_bug_str-producto_id = l_id_producto. l_bug_str-bug_id = l_id_bug. l_bug_str-oref = lo_bug. READ TABLE bugs WITH KEY producto_id = l_id_producto bug_id = l_id_bug TRANSPORTING NO FIELDS. IF NOT sy-subrc IS INITIAL. INSERT l_bug_str INTO TABLE bugs. ENDIF. CATCH cx_root INTO lo_exception. RAISE EXCEPTION TYPE zcx_not_found_exception EXPORTING textid = zcx_not_found_exception=>zcx_not_found_exception previous = lo_exception. ENDTRY. ENDLOOP. ENDMETHOD. ""retrieve_bugs_from_persistence METHOD update. DATA: lo_persist TYPE REF TO zcl_transport_persist, l_tr_str TYPE zbt_transporter, lt_new_bugs TYPE zbt_bugs, lt_old_bugs TYPE zbt_bugs, l_bug_str TYPE LINE OF zbt_bugs, lo_producto TYPE REF TO zcl_producto, lo_transaccion TYPE REF TO zcl_transaction_service, lo_exception TYPE REF TO cx_root. TRY . * Firstly, it's necessary to retrieve to which bugs is this TR related before de modification lt_old_bugs[] = retrieve_bugs_from_persistence( transport ). lt_new_bugs[] = transport->get_bugs( ). CREATE OBJECT lo_transaccion. lo_transaccion->start( ). l_tr_str-transportreq = transport->get_id( ). * Compare current bugs with those that exist in DB LOOP AT lt_new_bugs INTO l_bug_str. l_tr_str-bug = l_bug_str-bug_id. l_tr_str-producto = l_bug_str-producto_id. READ TABLE lt_old_bugs WITH KEY producto_id = l_bug_str-producto_id bug_id = l_bug_str-bug_id TRANSPORTING NO FIELDS. IF sy-subrc IS INITIAL. lo_persist = zca_transport_persist=>agent->get_persistent( i_bug = l_tr_str-bug i_producto = l_tr_str-producto i_transportreq = l_tr_str-transportreq ). DELETE lt_old_bugs WHERE producto_id = l_bug_str-producto_id AND bug_id = l_bug_str-bug_id. ELSE. lo_persist = zca_transport_persist=>agent->create_persistent( i_bug = l_tr_str-bug i_producto = l_tr_str-producto i_transportreq = l_tr_str-transportreq ). ENDIF. ENDLOOP. * Know we proced to delete old bugs that are no more related to this TR LOOP AT lt_old_bugs INTO l_bug_str. READ TABLE lt_new_bugs WITH KEY producto_id = l_bug_str-producto_id bug_id = l_bug_str-bug_id TRANSPORTING NO FIELDS. IF NOT sy-subrc IS INITIAL. l_tr_str-bug = l_bug_str-bug_id. l_tr_str-producto = l_bug_str-producto_id. zca_transport_persist=>agent->delete_persistent( i_bug = l_tr_str-bug i_producto = l_tr_str-producto i_transportreq = l_tr_str-transportreq ). ENDIF. ENDLOOP. lo_transaccion->end( ). CATCH cx_root INTO lo_exception. RAISE EXCEPTION TYPE zcx_update_exception EXPORTING textid = zcx_update_exception=>zcx_update_exception previous = lo_exception. ENDTRY. ENDMETHOD. ""update METHOD update_tr_attributes. DATA: lt_attributes TYPE trwbo_t_e070a, lt_attributes_aux TYPE trwbo_t_e070a, l_trkorr TYPE trkorr, lo_producto TYPE REF TO zcl_producto, l_bug_id TYPE LINE OF zbt_producto_bug_id_tbl, l_attribute TYPE LINE OF trwbo_t_e070a, lt_bugs TYPE zbt_bugs, l_bug TYPE LINE OF zbt_bugs. l_trkorr = transport->get_id( ). CALL FUNCTION 'TR_READ_ATTRIBUTES' EXPORTING iv_request = l_trkorr IMPORTING et_attributes = lt_attributes EXCEPTIONS invalid_request = 1 no_authorization = 2 OTHERS = 3. lt_bugs = transport->get_bugs( ). LOOP AT lt_bugs INTO l_bug. l_trkorr = transport->get_id( ). lo_producto = l_bug-oref->get_producto( ). l_bug_id-producto = lo_producto->get_id( ). l_bug_id-bug = l_bug-oref->get_id( ). READ TABLE lt_attributes WITH KEY trkorr = l_trkorr attribute = c_tr_attribute_id reference = l_bug_id INTO l_attribute. IF NOT sy-subrc IS INITIAL. DESCRIBE TABLE lt_attributes LINES l_attribute-pos. ADD 1 TO l_attribute-pos. l_attribute-trkorr = l_trkorr. l_attribute-attribute = c_tr_attribute_id. l_attribute-reference = l_bug_id. INSERT l_attribute INTO TABLE lt_attributes[]. CLEAR lt_attributes_aux[]. INSERT l_attribute INTO TABLE lt_attributes_aux[]. CALL FUNCTION 'TR_APPEND_ATTRIBUTES' EXPORTING iv_request = l_trkorr it_attributes = lt_attributes_aux[] EXCEPTIONS invalid_request = 1 invalid_attribute = 2 no_authorization = 3 enqueue_failed = 4 db_access_error = 5 OTHERS = 6. ENDIF. ENDLOOP. LOOP AT lt_attributes INTO l_attribute. l_bug_id = l_attribute-reference. READ TABLE lt_bugs WITH KEY producto_id = l_bug_id-producto bug_id = l_bug_id-bug TRANSPORTING NO FIELDS. IF NOT sy-subrc IS INITIAL. CLEAR lt_attributes_aux[]. INSERT l_attribute INTO TABLE lt_attributes_aux[]. CALL FUNCTION 'TR_DELETE_ATTRIBUTES' EXPORTING iv_request = l_trkorr it_attributes = lt_attributes_aux[] EXCEPTIONS invalid_request = 1 invalid_attribute = 2 no_authorization = 3 enqueue_failed = 4 db_access_error = 5 OTHERS = 6. ENDIF. ENDLOOP. COMMIT WORK AND WAIT. ENDMETHOD. ""update_tr_attributes ENDCLASS. ",4115,False,1022.009728803743,median "/*############################################################################## HPCC SYSTEMS software Copyright (C) 2015 HPCC Systems®. 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. ############################################################################## */ #include ""platform.h"" #include ""cassandra.h"" #include ""jexcept.hpp"" #include ""jthread.hpp"" #include ""hqlplugins.hpp"" #include ""deftype.hpp"" #include ""eclhelper.hpp"" #include ""eclrtl.hpp"" #include ""eclrtl_imp.hpp"" #include ""rtlds_imp.hpp"" #include ""rtlfield.hpp"" #include ""rtlembed.hpp"" #include ""roxiemem.hpp"" #include ""nbcd.hpp"" #include ""cassandraembed.hpp"" static const char * compatibleVersions[] = { ""Cassandra Embed Helper 1.0.0"", NULL }; static const char *version = ""Cassandra Embed Helper 1.0.0""; extern ""C"" DECL_EXPORT bool getECLPluginDefinition(ECLPluginDefinitionBlock *pb) { if (pb->size == sizeof(ECLPluginDefinitionBlockEx)) { ECLPluginDefinitionBlockEx * pbx = (ECLPluginDefinitionBlockEx *) pb; pbx->compatibleVersions = compatibleVersions; } else if (pb->size != sizeof(ECLPluginDefinitionBlock)) return false; pb->magicVersion = PLUGIN_VERSION; pb->version = version; pb->moduleName = ""cassandra""; pb->ECL = NULL; pb->flags = PLUGIN_MULTIPLE_VERSIONS; pb->description = ""Cassandra Embed Helper""; return true; } namespace cassandraembed { extern void UNSUPPORTED(const char *feature) { throw MakeStringException(-1, ""UNSUPPORTED feature: %s not supported in Cassandra plugin"", feature); } static void logCallBack(const CassLogMessage *message, void *data) { DBGLOG(""cassandra: %s - %s"", cass_log_level_string(message->severity), message->message); } extern void failx(const char *message, ...) { va_list args; va_start(args,message); StringBuffer msg; msg.append(""cassandra: "").valist_appendf(message,args); va_end(args); rtlFail(0, msg.str()); } extern void fail(const char *message) { StringBuffer msg; msg.append(""cassandra: "").append(message); rtlFail(0, msg.str()); } void check(CassError rc) { if (rc != CASS_OK) { fail(cass_error_desc(rc)); } } // Wrappers to Cassandra structures that require corresponding releases void CassandraClusterSession::setOptions(const StringArray &options) { const char *contact_points = ""localhost""; const char *user = """"; const char *password = """"; StringBuffer epText; ForEachItemIn(idx, options) { const char *opt = options.item(idx); const char *val = strchr(opt, '='); if (val) { StringBuffer optName(val-opt, opt); val++; if (stricmp(optName, ""contact_points"")==0 || stricmp(optName, ""server"")==0) { contact_points = val; // Note that lifetime of val is adequate for this to be safe if (contact_points[0]=='.') { SocketEndpoint ep(contact_points); ep.getIpText(epText.clear()); contact_points = epText.str(); } } else if (stricmp(optName, ""user"")==0) user = val; else if (stricmp(optName, ""password"")==0) password = val; else if (stricmp(optName, ""keyspace"")==0) keyspace.set(val); else if (stricmp(optName, ""maxFutures"")==0) { if (!semaphore) { maxFutures=getUnsignedOption(val, ""maxFutures""); if (maxFutures) semaphore = new Semaphore(maxFutures); } } else if (stricmp(optName, ""maxRetries"")==0) maxRetries=getUnsignedOption(val, ""maxRetries""); else if (stricmp(optName, ""port"")==0) { unsigned port = getUnsignedOption(val, ""port""); checkSetOption(cass_cluster_set_port(cluster, port), ""port""); } else if (stricmp(optName, ""protocol_version"")==0) { unsigned protocol_version = getUnsignedOption(val, ""protocol_version""); checkSetOption(cass_cluster_set_protocol_version(cluster, protocol_version), ""protocol_version""); } else if (stricmp(optName, ""num_threads_io"")==0) { unsigned num_threads_io = getUnsignedOption(val, ""num_threads_io""); cass_cluster_set_num_threads_io(cluster, num_threads_io); // No status return } else if (stricmp(optName, ""queue_size_io"")==0) { unsigned queue_size_io = getUnsignedOption(val, ""queue_size_io""); checkSetOption(cass_cluster_set_queue_size_io(cluster, queue_size_io), ""queue_size_io""); } else if (stricmp(optName, ""core_connections_per_host"")==0) { unsigned core_connections_per_host = getUnsignedOption(val, ""core_connections_per_host""); checkSetOption(cass_cluster_set_core_connections_per_host(cluster, core_connections_per_host), ""core_connections_per_host""); } else if (stricmp(optName, ""max_connections_per_host"")==0) { unsigned max_connections_per_host = getUnsignedOption(val, ""max_connections_per_host""); checkSetOption(cass_cluster_set_max_connections_per_host(cluster, max_connections_per_host), ""max_connections_per_host""); } else if (stricmp(optName, ""max_concurrent_creation"")==0) { unsigned max_concurrent_creation = getUnsignedOption(val, ""max_concurrent_creation""); checkSetOption(cass_cluster_set_max_concurrent_creation(cluster, max_concurrent_creation), ""max_concurrent_creation""); } else if (stricmp(optName, ""write_bytes_high_water_mark"")==0) { unsigned write_bytes_high_water_mark = getUnsignedOption(val, ""write_bytes_high_water_mark""); checkSetOption(cass_cluster_set_write_bytes_high_water_mark(cluster, write_bytes_high_water_mark), ""write_bytes_high_water_mark""); } else if (stricmp(optName, ""write_bytes_low_water_mark"")==0) { unsigned write_bytes_low_water_mark = getUnsignedOption(val, ""write_bytes_low_water_mark""); checkSetOption(cass_cluster_set_write_bytes_low_water_mark(cluster, write_bytes_low_water_mark), ""write_bytes_low_water_mark""); } else if (stricmp(optName, ""pending_requests_high_water_mark"")==0) { unsigned pending_requests_high_water_mark = getUnsignedOption(val, ""pending_requests_high_water_mark""); checkSetOption(cass_cluster_set_pending_requests_high_water_mark(cluster, pending_requests_high_water_mark), ""pending_requests_high_water_mark""); } else if (stricmp(optName, ""pending_requests_low_water_mark"")==0) { unsigned pending_requests_low_water_mark = getUnsignedOption(val, ""pending_requests_low_water_mark""); checkSetOption(cass_cluster_set_pending_requests_low_water_mark(cluster, pending_requests_low_water_mark), ""pending_requests_low_water_mark""); } else if (stricmp(optName, ""max_concurrent_requests_threshold"")==0) { unsigned max_concurrent_requests_threshold = getUnsignedOption(val, ""max_concurrent_requests_threshold""); checkSetOption(cass_cluster_set_max_concurrent_requests_threshold(cluster, max_concurrent_requests_threshold), ""max_concurrent_requests_threshold""); } else if (stricmp(optName, ""connect_timeout"")==0) { unsigned connect_timeout = getUnsignedOption(val, ""connect_timeout""); cass_cluster_set_connect_timeout(cluster, connect_timeout); } else if (stricmp(optName, ""request_timeout"")==0) { unsigned request_timeout = getUnsignedOption(val, ""request_timeout""); cass_cluster_set_request_timeout(cluster, request_timeout); } else if (stricmp(optName, ""load_balance_round_robin"")==0) { cass_bool_t enable = getBoolOption(val, ""load_balance_round_robin""); if (enable==cass_true) cass_cluster_set_load_balance_round_robin(cluster); } else if (stricmp(optName, ""load_balance_dc_aware"")==0) { StringArray lbargs; lbargs.appendList(val, ""|""); if (lbargs.length() != 3) failx(""Invalid value '%s' for option %s - expected 3 subvalues (separate with |)"", val, optName.str()); unsigned usedPerRemote = getUnsignedOption(lbargs.item(2), ""load_balance_dc_aware""); cass_bool_t allowRemote = getBoolOption(lbargs.item(2), ""load_balance_dc_aware""); checkSetOption(cass_cluster_set_load_balance_dc_aware(cluster, lbargs.item(0), usedPerRemote, allowRemote), ""load_balance_dc_aware""); } else if (stricmp(optName, ""token_aware_routing"")==0) { cass_bool_t enable = getBoolOption(val, ""token_aware_routing""); cass_cluster_set_token_aware_routing(cluster, enable); } else if (stricmp(optName, ""latency_aware_routing"")==0) { cass_bool_t enable = getBoolOption(val, ""latency_aware_routing""); cass_cluster_set_latency_aware_routing(cluster, enable); } else if (stricmp(optName, ""latency_aware_routing_settings"")==0) { StringArray subargs; subargs.appendList(val, ""|""); if (subargs.length() != 5) failx(""Invalid value '%s' for option %s - expected 5 subvalues (separate with |)"", val, optName.str()); cass_double_t exclusion_threshold = getDoubleOption(subargs.item(0), ""exclusion_threshold""); cass_uint64_t scale_ms = getUnsigned64Option(subargs.item(1), ""scale_ms""); cass_uint64_t retry_period_ms = getUnsigned64Option(subargs.item(2), ""retry_period_ms""); cass_uint64_t update_rate_ms = getUnsigned64Option(subargs.item(3), ""update_rate_ms""); cass_uint64_t min_measured = getUnsigned64Option(subargs.item(4), ""min_measured""); cass_cluster_set_latency_aware_routing_settings(cluster, exclusion_threshold, scale_ms, retry_period_ms, update_rate_ms, min_measured); } else if (stricmp(optName, ""tcp_nodelay"")==0) { cass_bool_t enable = getBoolOption(val, ""tcp_nodelay""); cass_cluster_set_tcp_nodelay(cluster, enable); } else if (stricmp(optName, ""tcp_keepalive"")==0) { StringArray subargs; subargs.appendList(val, ""|""); if (subargs.length() != 2) failx(""Invalid value '%s' for option %s - expected 2 subvalues (separate with |)"", val, optName.str()); cass_bool_t enabled = getBoolOption(subargs.item(0), ""enabled""); unsigned delay_secs = getUnsignedOption(subargs.item(0), ""delay_secs""); cass_cluster_set_tcp_keepalive(cluster, enabled, delay_secs); } else failx(""Unrecognized option %s"", optName.str()); } } cass_cluster_set_contact_points(cluster, contact_points); if (*user || *password) cass_cluster_set_credentials(cluster, user, password); } void CassandraClusterSession::checkSetOption(CassError rc, const char *name) { if (rc != CASS_OK) { failx(""While setting option %s: %s"", name, cass_error_desc(rc)); } } cass_bool_t CassandraClusterSession::getBoolOption(const char *val, const char *option) { return strToBool(val) ? cass_true : cass_false; } unsigned CassandraClusterSession::getUnsignedOption(const char *val, const char *option) { char *endp; long value = strtoul(val, &endp, 0); if (endp==val || *endp != '\\0' || value > UINT_MAX || value < 0) failx(""Invalid value '%s' for option %s"", val, option); return (unsigned) value; } unsigned CassandraClusterSession::getDoubleOption(const char *val, const char *option) { char *endp; double value = strtod(val, &endp); if (endp==val || *endp != '\\0') failx(""Invalid value '%s' for option %s"", val, option); return value; } __uint64 CassandraClusterSession::getUnsigned64Option(const char *val, const char *option) { // MORE - could check it's all digits (with optional leading spaces...), if we cared. return rtlVStrToUInt8(val); } void CassandraClusterSession::connect() { assertex(cluster && !session); session.setown(new CassandraSession(cass_session_new())); CassandraFuture future(keyspace.isEmpty() ? cass_session_connect(*session, cluster) : cass_session_connect_keyspace(*session, cluster, keyspace)); future.wait(""connect""); } void CassandraClusterSession::disconnect() { session.clear(); } CassandraPrepared *CassandraClusterSession::prepareStatement(const char *query, bool trace) const { assertex(session); CriticalBlock b(cacheCrit); Linked cached = preparedCache.getValue(query); if (cached) return cached.getClear(); { // We don't want to block cache lookups while we prepare a new bound statement // Note - if multiple threads try to prepare the same (new) statement at the same time, it's not catastrophic CriticalUnblock b(cacheCrit); CassandraFuture futurePrep(cass_session_prepare(*session, query)); futurePrep.wait(""prepare statement""); cached.setown(new CassandraPrepared(cass_future_get_prepared(futurePrep), trace ? query : NULL)); } preparedCache.setValue(query, cached); // NOTE - this links parameter return cached.getClear(); } CassandraStatementInfo *CassandraClusterSession::createStatementInfo(const char *script, unsigned numParams, CassBatchType batchMode, unsigned pageSize) const { Owned prepared = prepareStatement(script, false); // We could make tracing selectable return new CassandraStatementInfo(session, prepared, numParams, batchMode, pageSize, semaphore, maxRetries); } void CassandraClusterSession::executeAsync(CIArrayOf &batch, const char *what) const { CIArrayOf futures; ForEachItemIn(idx, batch) futures.append(*new CassandraRetryingFuture(*session, batch.item(idx).getClear(), semaphore, maxRetries)); ForEachItemIn(idx2, futures) futures.item(idx2).wait(what); } typedef CassandraClusterSession *CassandraClusterSessionPtr; typedef MapBetween ClusterSessionMap; static CriticalSection clusterCacheCrit; static ClusterSessionMap cachedSessions; CassandraClusterSession *lookupCachedSession(hash64_t hash, const StringArray &opts) { Owned cluster; CassandraClusterSessionPtr *found = cachedSessions.getValue(hash); if (found) cluster.set(*found); if (!cluster) { cluster.setown(new CassandraClusterSession(cass_cluster_new())); cluster->setOptions(opts); cluster->connect(); cachedSessions.setValue(hash, cluster.getLink()); } return cluster.getClear(); } MODULE_INIT(INIT_PRIORITY_STANDARD) { cass_log_set_callback(logCallBack, NULL); cass_log_set_level(CASS_LOG_WARN); return true; } MODULE_EXIT() { HashIterator i(cachedSessions); ForEach(i) { CassandraClusterSession *session = *cachedSessions.mapToValue(&i.query()); ::Release(session); } } //------------------ void CassandraFuture::wait(const char *why) const { cass_future_wait(future); CassError rc = cass_future_error_code(future); if(rc != CASS_OK) { const char *message; size_t length; cass_future_error_message(future, &message, &length); VStringBuffer err(""cassandra: failed to %s (%.*s)"", why, (int) length, message); #ifdef _DEBUG DBGLOG(""%s"", err.str()); #endif rtlFail(0, err.str()); } } void CassandraSession::set(CassSession *_session) { if (session) { CassandraFuture close_future(cass_session_close(session)); cass_future_wait(close_future); cass_session_free(session); } session = _session; } //---------------------- CassandraRetryingFuture::CassandraRetryingFuture(CassSession *_session, CassStatement *_statement, Semaphore *_limiter, unsigned _retries) : session(_session), statement(_statement), retries(_retries), limiter(_limiter), future(NULL) { execute(); } CassandraRetryingFuture::~CassandraRetryingFuture() { if (future) cass_future_free(future); } void CassandraRetryingFuture::wait(const char *why) { cass_future_wait(future); CassError rc = cass_future_error_code(future); if(rc != CASS_OK) { switch (rc) { case CASS_ERROR_LIB_NO_HOSTS_AVAILABLE: // MORE - are there others we should retry? if (retry(why)) break; // fall into default: const char *message; size_t length; cass_future_error_message(future, &message, &length); VStringBuffer err(""cassandra: failed to %s (%.*s)"", why, (int) length, message); rtlFail(0, err.str()); } } } bool CassandraRetryingFuture::retry(const char *why) { for (int i = 0; i < retries; i++) { execute(); cass_future_wait(future); CassError rc = cass_future_error_code(future); if (rc == CASS_OK) return true; Sleep(10); } return false; } void CassandraRetryingFuture::execute() { if (limiter) limiter->wait(); future = cass_session_execute(session, statement); if (limiter) cass_future_set_callback(future, signaller, limiter); // Note - this will call the callback if the future has already completed } void CassandraRetryingFuture::signaller(CassFuture *future, void *data) { Semaphore *sem = (Semaphore *) data; sem->signal(); } //---------------------- CassandraStatementInfo::CassandraStatementInfo(CassandraSession *_session, CassandraPrepared *_prepared, unsigned _numBindings, CassBatchType _batchMode, unsigned pageSize, Semaphore *_semaphore, unsigned _maxRetries) : session(_session), prepared(_prepared), numBindings(_numBindings), batchMode(_batchMode), semaphore(_semaphore), maxRetries(_maxRetries) { assertex(prepared && *prepared); statement.setown(new CassandraStatement(cass_prepared_bind(*prepared))); if (pageSize) cass_statement_set_paging_size(*statement, pageSize); inBatch = false; } CassandraStatementInfo::~CassandraStatementInfo() { stop(); futures.kill(); } void CassandraStatementInfo::stop() { iterator.clear(); result.clear(); prepared.clear(); } bool CassandraStatementInfo::next() { for (;;) { if (!iterator) { if (result) iterator.setown(new CassandraIterator(cass_iterator_from_result(*result))); else return false; } if (cass_iterator_next(*iterator)) return true; iterator.clear(); if (!cass_result_has_more_pages(*result)) { result.clear(); break; } cass_statement_set_paging_state(*statement, *result); result.setown(new CassandraFutureResult(cass_session_execute(*session, *statement))); } return false; } void CassandraStatementInfo::startStream() { if (batchMode != (CassBatchType) -1) batch.setown(new CassandraBatch(batchMode)); statement.setown(new CassandraStatement(cass_prepared_bind(*prepared))); inBatch = true; } void CassandraStatementInfo::endStream() { if (batch) { result.setown(new CassandraFutureResult (cass_session_execute_batch(*session, *batch))); assertex (rowCount() == 0); } else { ForEachItemIn(idx, futures) { futures.item(idx).wait(""endStream""); } } } void CassandraStatementInfo::execute() { assertex(statement && *statement); if (batch) { check(cass_batch_add_statement(*batch, *statement)); statement.setown(new CassandraStatement(cass_prepared_bind(*prepared))); } else if (inBatch) { futures.append(*new CassandraRetryingFuture(*session, statement->getClear(), semaphore, maxRetries)); statement.setown(new CassandraStatement(cass_prepared_bind(*prepared))); } else { result.setown(new CassandraFutureResult(cass_session_execute(*session, *statement))); } } // Conversions from Cassandra values to ECL data static const char *getTypeName(CassValueType type) { switch (type) { case CASS_VALUE_TYPE_CUSTOM: return ""CUSTOM""; case CASS_VALUE_TYPE_ASCII: return ""ASCII""; case CASS_VALUE_TYPE_BIGINT: return ""BIGINT""; case CASS_VALUE_TYPE_BLOB: return ""BLOB""; case CASS_VALUE_TYPE_BOOLEAN: return ""BOOLEAN""; case CASS_VALUE_TYPE_COUNTER: return ""COUNTER""; case CASS_VALUE_TYPE_DECIMAL: return ""DECIMAL""; case CASS_VALUE_TYPE_DOUBLE: return ""DOUBLE""; case CASS_VALUE_TYPE_FLOAT: return ""FLOAT""; case CASS_VALUE_TYPE_INT: return ""INT""; case CASS_VALUE_TYPE_TEXT: return ""TEXT""; case CASS_VALUE_TYPE_TIMESTAMP: return ""TIMESTAMP""; case CASS_VALUE_TYPE_UUID: return ""UUID""; case CASS_VALUE_TYPE_VARCHAR: return ""VARCHAR""; case CASS_VALUE_TYPE_VARINT: return ""VARINT""; case CASS_VALUE_TYPE_TIMEUUID: return ""TIMEUUID""; case CASS_VALUE_TYPE_INET: return ""INET""; case CASS_VALUE_TYPE_LIST: return ""LIST""; case CASS_VALUE_TYPE_MAP: return ""MAP""; case CASS_VALUE_TYPE_SET: return ""SET""; default: return ""UNKNOWN""; } } __declspec(noreturn) static void typeError(const char *expected, const CassValue *value, const RtlFieldInfo *field) __attribute__((noreturn)); static void typeError(const char *expected, const CassValue *value, const RtlFieldInfo *field) { VStringBuffer msg(""cassandra: type mismatch - %s expected"", expected); if (field) msg.appendf("" for field %s"", field->name); if (value) msg.appendf("", received %s"", getTypeName(cass_value_type(value))); rtlFail(0, msg.str()); } extern bool isInteger(const CassValueType t) { switch (t) { case CASS_VALUE_TYPE_TIMESTAMP: case CASS_VALUE_TYPE_INT: case CASS_VALUE_TYPE_BIGINT: case CASS_VALUE_TYPE_COUNTER: case CASS_VALUE_TYPE_VARINT: return true; default: return false; } } extern bool isString(CassValueType t) { switch (t) { case CASS_VALUE_TYPE_VARCHAR: case CASS_VALUE_TYPE_TEXT: case CASS_VALUE_TYPE_ASCII: return true; default: return false; } } // when extracting elements of a set, field will point at the SET info- we want to get the typeInfo for the element type static const RtlTypeInfo *getFieldBaseType(const RtlFieldInfo *field) { const RtlTypeInfo *type = field->type; if ((type->fieldType & RFTMkind) == type_set) return type->queryChildType(); else return type; } static int getNumFields(const RtlTypeInfo *record) { int count = 0; const RtlFieldInfo * const *fields = record->queryFields(); assertex(fields); while (*fields++) count++; return count; } extern bool getBooleanResult(const RtlFieldInfo *field, const CassValue *value) { if (cass_value_is_null(value)) { NullFieldProcessor p(field); return p.boolResult; } if (cass_value_type(value) != CASS_VALUE_TYPE_BOOLEAN) typeError(""boolean"", value, field); cass_bool_t output; check(cass_value_get_bool(value, &output)); return output != cass_false; } extern void getDataResult(const RtlFieldInfo *field, const CassValue *value, size32_t &chars, void * &result) { if (cass_value_is_null(value)) { NullFieldProcessor p(field); rtlStrToDataX(chars, result, p.resultChars, p.stringResult); return; } // We COULD require that the field being retrieved is a blob - but Cassandra seems happy to use any field here, and // it seems like it could be more useful to support anything // if (cass_value_type(value) != CASS_VALUE_TYPE_BLOB) // typeError(""blob"", value, field); const cass_byte_t *bytes; size_t size; check(cass_value_get_bytes(value, &bytes, &size)); rtlStrToDataX(chars, result, size, bytes); } extern double getRealResult(const RtlFieldInfo *field, const CassValue *value) { if (cass_value_is_null(value)) { NullFieldProcessor p(field); return p.doubleResult; } else if (isInteger(cass_value_type(value))) return (double) getSignedResult(field, value); else switch (cass_value_type(value)) { case CASS_VALUE_TYPE_FLOAT: { cass_float_t output_f; check(cass_value_get_float(value, &output_f)); return output_f; } case CASS_VALUE_TYPE_DOUBLE: { cass_double_t output_d; check(cass_value_get_double(value, &output_d)); return output_d; } default: typeError(""double"", value, field); } } extern __int64 getSignedResult(const RtlFieldInfo *field, const CassValue *value) { if (cass_value_is_null(value)) { NullFieldProcessor p(field); return p.intResult; } switch (cass_value_type(value)) { case CASS_VALUE_TYPE_INT: { cass_int32_t output; check(cass_value_get_int32(value, &output)); return output; } case CASS_VALUE_TYPE_TIMESTAMP: case CASS_VALUE_TYPE_BIGINT: case CASS_VALUE_TYPE_COUNTER: case CASS_VALUE_TYPE_VARINT: { cass_int64_t output; check(cass_value_get_int64(value, &output)); return output; } default: typeError(""integer"", value, field); } } extern unsigned __int64 getUnsignedResult(const RtlFieldInfo *field, const CassValue *value) { if (cass_value_is_null(value)) { NullFieldProcessor p(field); return p.uintResult; } return (__uint64) getSignedResult(field, value); } extern void getStringResult(const RtlFieldInfo *field, const CassValue *value, size32_t &chars, char * &result) { if (cass_value_is_null(value)) { NullFieldProcessor p(field); rtlStrToStrX(chars, result, p.resultChars, p.stringResult); return; } switch (cass_value_type(value)) { case CASS_VALUE_TYPE_ASCII: { const char *output; size_t length; check(cass_value_get_string(value, &output, &length)); rtlStrToStrX(chars, result, length, output); break; } case CASS_VALUE_TYPE_VARCHAR: case CASS_VALUE_TYPE_TEXT: { const char *output; size_t length; check(cass_value_get_string(value, &output, &length)); unsigned numchars = rtlUtf8Length(length, output); rtlUtf8ToStrX(chars, result, numchars, output); break; } default: typeError(""string"", value, field); } } extern void getUTF8Result(const RtlFieldInfo *field, const CassValue *value, size32_t &chars, char * &result) { if (cass_value_is_null(value)) { NullFieldProcessor p(field); rtlUtf8ToUtf8X(chars, result, p.resultChars, p.stringResult); return; } switch (cass_value_type(value)) { case CASS_VALUE_TYPE_ASCII: { const char *output; size_t length; check(cass_value_get_string(value, &output, &length)); rtlStrToUtf8X(chars, result, length, output); break; } case CASS_VALUE_TYPE_VARCHAR: case CASS_VALUE_TYPE_TEXT: { const char * output; size_t length; check(cass_value_get_string(value, &output, &length)); unsigned numchars = rtlUtf8Length(length, output); rtlUtf8ToUtf8X(chars, result, numchars, output); break; } default: typeError(""string"", value, field); } } extern void getUnicodeResult(const RtlFieldInfo *field, const CassValue *value, size32_t &chars, UChar * &result) { if (cass_value_is_null(value)) { NullFieldProcessor p(field); rtlUnicodeToUnicodeX(chars, result, p.resultChars, p.unicodeResult); return; } switch (cass_value_type(value)) { case CASS_VALUE_TYPE_ASCII: { const char * output; size_t length; check(cass_value_get_string(value, &output, &length)); rtlStrToUnicodeX(chars, result, length, output); break; } case CASS_VALUE_TYPE_VARCHAR: case CASS_VALUE_TYPE_TEXT: { const char * output; size_t length; check(cass_value_get_string(value, &output, &length)); unsigned numchars = rtlUtf8Length(length, output); rtlUtf8ToUnicodeX(chars, result, numchars, output); break; } default: typeError(""string"", value, field); } } extern void getDecimalResult(const RtlFieldInfo *field, const CassValue *value, Decimal &result) { // Note - Cassandra has a decimal type, but it's not particularly similar to the ecl one. Map to string for now, as we do in MySQL if (cass_value_is_null(value)) { NullFieldProcessor p(field); result.set(p.decimalResult); return; } size32_t chars; rtlDataAttr tempStr; cassandraembed::getStringResult(field, value, chars, tempStr.refstr()); result.setString(chars, tempStr.getstr()); if (field) { RtlDecimalTypeInfo *dtype = (RtlDecimalTypeInfo *) field->type; result.setPrecision(dtype->getDecimalDigits(), dtype->getDecimalPrecision()); } } // A CassandraRowBuilder object is used to construct an ECL row from a Cassandra row class CassandraRowBuilder : public CInterfaceOf { public: CassandraRowBuilder(const CassandraStatementInfo *_stmtInfo) : stmtInfo(_stmtInfo), colIdx(0), numIteratorFields(0), nextIteratedField(0) { } virtual bool getBooleanResult(const RtlFieldInfo *field) { return cassandraembed::getBooleanResult(field, nextField(field)); } virtual void getDataResult(const RtlFieldInfo *field, size32_t &len, void * &result) { cassandraembed::getDataResult(field, nextField(field), len, result); } virtual double getRealResult(const RtlFieldInfo *field) { return cassandraembed::getRealResult(field, nextField(field)); } virtual __int64 getSignedResult(const RtlFieldInfo *field) { return cassandraembed::getSignedResult(field, nextField(field)); } virtual unsigned __int64 getUnsignedResult(const RtlFieldInfo *field) { return cassandraembed::getUnsignedResult(field, nextField(field)); } virtual void getStringResult(const RtlFieldInfo *field, size32_t &chars, char * &result) { cassandraembed::getStringResult(field, nextField(field), chars, result); } virtual void getUTF8Result(const RtlFieldInfo *field, size32_t &chars, char * &result) { cassandraembed::getUTF8Result(field, nextField(field), chars, result); } virtual void getUnicodeResult(const RtlFieldInfo *field, size32_t &chars, UChar * &result) { cassandraembed::getUnicodeResult(field, nextField(field), chars, result); } virtual void getDecimalResult(const RtlFieldInfo *field, Decimal &value) { cassandraembed::getDecimalResult(field, nextField(field), value); } virtual void processBeginSet(const RtlFieldInfo * field, bool &isAll) { isAll = false; iterator.setown(new CassandraIterator(cass_iterator_from_collection(nextField(field)))); } virtual bool processNextSet(const RtlFieldInfo * field) { numIteratorFields = 1; return *iterator && cass_iterator_next(*iterator); // If field was NULL, we'll have a NULL iterator (representing an empty set/list) // Can't distinguish empty set from NULL field, so assume the former (rather than trying to deliver the default value for the set field) } virtual void processBeginDataset(const RtlFieldInfo * field) { numIteratorFields = getNumFields(field->type->queryChildType()); switch (numIteratorFields) { case 1: iterator.setown(new CassandraIterator(cass_iterator_from_collection(nextField(field)))); break; case 2: iterator.setown(new CassandraIterator(cass_iterator_from_map(nextField(field)))); break; default: UNSUPPORTED(""Nested datasets with > 2 fields""); } } virtual void processBeginRow(const RtlFieldInfo * field) { } virtual bool processNextRow(const RtlFieldInfo * field) { nextIteratedField = 0; return *iterator && cass_iterator_next(*iterator); // If field was NULL, we'll have a NULL iterator (representing an empty set/list/map) // Can't distinguish empty set from NULL field, so assume the former (rather than trying to deliver the default value for the set field) } virtual void processEndSet(const RtlFieldInfo * field) { iterator.clear(); numIteratorFields = 0; } virtual void processEndDataset(const RtlFieldInfo * field) { iterator.clear(); numIteratorFields = 0; } virtual void processEndRow(const RtlFieldInfo * field) { } protected: const CassValue *nextField(const RtlFieldInfo * field) { const CassValue *ret; if (iterator) { switch (numIteratorFields) { case 1: ret = cass_iterator_get_value(*iterator); break; case 2: if (nextIteratedField==0) ret = cass_iterator_get_map_key(*iterator); else ret = cass_iterator_get_map_value(*iterator); nextIteratedField++; break; default: throwUnexpected(); } } else ret = cass_row_get_column(stmtInfo->queryRow(), colIdx++); if (!ret) failx(""Too many fields in ECL output row, reading field %s"", field->name); return ret; } const CassandraStatementInfo *stmtInfo; Owned iterator; int colIdx; int numIteratorFields; int nextIteratedField; }; // Bind Cassandra columns from an ECL record class CassandraRecordBinder : public CInterfaceOf { public: CassandraRecordBinder(const IContextLogger &_logctx, const RtlTypeInfo *_typeInfo, const CassandraStatementInfo *_stmtInfo, int _firstParam) : logctx(_logctx), typeInfo(_typeInfo), stmtInfo(_stmtInfo), firstParam(_firstParam), dummyField("""", NULL, typeInfo), thisParam(_firstParam) { } int numFields() { int count = 0; const RtlFieldInfo * const *fields = typeInfo->queryFields(); assertex(fields); while (*fields++) count++; return count; } void processRow(const byte *row) { thisParam = firstParam; typeInfo->process(row, row, &dummyField, *this); // Bind the variables for the current row } virtual void processString(unsigned len, const char *value, const RtlFieldInfo * field) { size32_t utf8chars; rtlDataAttr utfText; rtlStrToUtf8X(utf8chars, utfText.refstr(), len, value); if (collection) checkBind(cass_collection_append_string_n(*collection, utfText.getstr(), rtlUtf8Size(utf8chars, utfText.getstr())), field); else checkBind(cass_statement_bind_string_n(stmtInfo->queryStatement(), checkNextParam(field), utfText.getstr(), rtlUtf8Size(utf8chars, utfText.getstr())), field); } virtual void processBool(bool value, const RtlFieldInfo * field) { if (collection) checkBind(cass_collection_append_bool(*collection, value ? cass_true : cass_false), field); else checkBind(cass_statement_bind_bool(stmtInfo->queryStatement(), checkNextParam(field), value ? cass_true : cass_false), field); } virtual void processData(unsigned len, const void *value, const RtlFieldInfo * field) { if (collection) checkBind(cass_collection_append_bytes(*collection, (const cass_byte_t*) value, len), field); else checkBind(cass_statement_bind_bytes(stmtInfo->queryStatement(), checkNextParam(field), (const cass_byte_t*) value, len), field); } virtual void processInt(__int64 value, const RtlFieldInfo * field) { if (getFieldBaseType(field)->size(NULL,NULL)>4) { if (collection) checkBind(cass_collection_append_int64(*collection, value), field); else checkBind(cass_statement_bind_int64(stmtInfo->queryStatement(), checkNextParam(field), value), field); } else { if (collection) checkBind(cass_collection_append_int32(*collection, value), field); else checkBind(cass_statement_bind_int32(stmtInfo->queryStatement(), checkNextParam(field), value), field); } } virtual void processUInt(unsigned __int64 value, const RtlFieldInfo * field) { UNSUPPORTED(""UNSIGNED columns""); } virtual void processReal(double value, const RtlFieldInfo * field) { if (getFieldBaseType(field)->size(NULL,NULL)>4) { if (collection) checkBind(cass_collection_append_double(*collection, value), field); else checkBind(cass_statement_bind_double(stmtInfo->queryStatement(), checkNextParam(field), value), field); } else { if (collection) checkBind(cass_collection_append_float(*collection, (float) value), field); else checkBind(cass_statement_bind_float(stmtInfo->queryStatement(), checkNextParam(field), (float) value), field); } } virtual void processDecimal(const void *value, unsigned digits, unsigned precision, const RtlFieldInfo * field) { Decimal val; size32_t bytes; rtlDataAttr decText; val.setDecimal(digits, precision, value); val.getStringX(bytes, decText.refstr()); processUtf8(bytes, decText.getstr(), field); } virtual void processUDecimal(const void *value, unsigned digits, unsigned precision, const RtlFieldInfo * field) { UNSUPPORTED(""UNSIGNED decimals""); } virtual void processUnicode(unsigned chars, const UChar *value, const RtlFieldInfo * field) { size32_t utf8chars; rtlDataAttr utfText; rtlUnicodeToUtf8X(utf8chars, utfText.refstr(), chars, value); if (collection) checkBind(cass_collection_append_string_n(*collection, utfText.getstr(), rtlUtf8Size(utf8chars, utfText.getstr())), field); else checkBind(cass_statement_bind_string_n(stmtInfo->queryStatement(), checkNextParam(field), utfText.getstr(), rtlUtf8Size(utf8chars, utfText.getstr())), field); } virtual void processQString(unsigned len, const char *value, const RtlFieldInfo * field) { size32_t charCount; rtlDataAttr text; rtlQStrToStrX(charCount, text.refstr(), len, value); processUtf8(charCount, text.getstr(), field); } virtual void processUtf8(unsigned chars, const char *value, const RtlFieldInfo * field) { if (collection) checkBind(cass_collection_append_string_n(*collection, value, rtlUtf8Size(chars, value)), field); else checkBind(cass_statement_bind_string_n(stmtInfo->queryStatement(), checkNextParam(field), value, rtlUtf8Size(chars, value)), field); } virtual bool processBeginSet(const RtlFieldInfo * field, unsigned numElements, bool isAll, const byte *data) { if (isAll) UNSUPPORTED(""SET(ALL)""); // We don't know whether the corresponding field in Cassandra is a list or a set. Try binding a dummy list to tell which. CassandraCollection temp(cass_collection_new(CASS_COLLECTION_TYPE_LIST, 0)); if (cass_statement_bind_collection(stmtInfo->queryStatement(), thisParam, temp) == CASS_OK) collection.setown(new CassandraCollection(cass_collection_new(CASS_COLLECTION_TYPE_LIST, numElements))); else collection.setown(new CassandraCollection(cass_collection_new(CASS_COLLECTION_TYPE_SET, numElements))); return true; } virtual bool processBeginDataset(const RtlFieldInfo * field, unsigned numRows) { // If there's a single field, assume we are mapping to a SET/LIST // If there are two, assume it's a MAP // Otherwise, fail int numFields = getNumFields(field->type->queryChildType()); if (numFields < 1 || numFields > 2) { UNSUPPORTED(""Nested datasets with > 2 fields""); } collection.setown(new CassandraCollection(cass_collection_new(numFields==1 ? CASS_COLLECTION_TYPE_SET : CASS_COLLECTION_TYPE_MAP, numRows))); return true; } virtual bool processBeginRow(const RtlFieldInfo * field) { return true; } virtual void processEndSet(const RtlFieldInfo * field) { checkBind(cass_statement_bind_collection(stmtInfo->queryStatement(), checkNextParam(field), *collection), field); collection.clear(); } virtual void processEndDataset(const RtlFieldInfo * field) { checkBind(cass_statement_bind_collection(stmtInfo->queryStatement(), checkNextParam(field), *collection), field); collection.clear(); } virtual void processEndRow(const RtlFieldInfo * field) { } protected: inline unsigned checkNextParam(const RtlFieldInfo * field) { if (logctx.queryTraceLevel() > 4) logctx.CTXLOG(""Binding %s to %d"", field->name, thisParam); return thisParam++; } inline void checkBind(CassError rc, const RtlFieldInfo * field) { if (rc != CASS_OK) { failx(""While binding parameter %s: %s"", field->name, cass_error_desc(rc)); } } const RtlTypeInfo *typeInfo; const CassandraStatementInfo *stmtInfo; Owned collection; const IContextLogger &logctx; int firstParam; RtlFieldStrInfo dummyField; int thisParam; }; // class CassandraDatasetBinder : public CassandraRecordBinder { public: CassandraDatasetBinder(const IContextLogger &_logctx, IRowStream * _input, const RtlTypeInfo *_typeInfo, const CassandraStatementInfo *_stmt, int _firstParam) : input(_input), CassandraRecordBinder(_logctx, _typeInfo, _stmt, _firstParam) { } bool bindNext() { roxiemem::OwnedConstRoxieRow nextRow = (const byte *) input->ungroupedNextRow(); if (!nextRow) return false; processRow((const byte *) nextRow.get()); // Bind the variables for the current row return true; } void executeAll(CassandraStatementInfo *stmtInfo) { stmtInfo->startStream(); while (bindNext()) { stmtInfo->execute(); } stmtInfo->endStream(); } protected: Owned input; }; // A Cassandra function that returns a dataset will return a CassandraRowStream object that can be // interrogated to return each row of the result in turn class CassandraRowStream : public CInterfaceOf { public: CassandraRowStream(CassandraDatasetBinder *_inputStream, CassandraStatementInfo *_stmtInfo, IEngineRowAllocator *_resultAllocator) : inputStream(_inputStream), stmtInfo(_stmtInfo), resultAllocator(_resultAllocator) { executePending = true; eof = false; } virtual const void *nextRow() { // A little complex when streaming data in as well as out - want to execute for every input record if (eof) return NULL; for (;;) { if (executePending) { executePending = false; if (inputStream && !inputStream->bindNext()) { noteEOF(); return NULL; } stmtInfo->execute(); } if (stmtInfo->next()) break; if (inputStream) executePending = true; else { noteEOF(); return NULL; } } RtlDynamicRowBuilder rowBuilder(resultAllocator); CassandraRowBuilder cassandraRowBuilder(stmtInfo); const RtlTypeInfo *typeInfo = resultAllocator->queryOutputMeta()->queryTypeInfo(); assertex(typeInfo); RtlFieldStrInfo dummyField("""", NULL, typeInfo); size32_t len = typeInfo->build(rowBuilder, 0, &dummyField, cassandraRowBuilder); return rowBuilder.finalizeRowClear(len); } virtual void stop() { resultAllocator.clear(); stmtInfo->stop(); } protected: void noteEOF() { if (!eof) { eof = true; stop(); } } Linked inputStream; Linked stmtInfo; Linked resultAllocator; bool executePending; bool eof; }; // Each call to a Cassandra function will use a new CassandraEmbedFunctionContext object class CassandraEmbedFunctionContext : public CInterfaceOf { public: CassandraEmbedFunctionContext(const IContextLogger &_logctx, const IThorActivityContext *_activityCtx, unsigned _flags, const char *options) : logctx(_logctx), activityCtx(_activityCtx), flags(_flags), nextParam(0), numParams(0), batchMode((CassBatchType) -1), pageSize(0) { StringArray opts; opts.appendList(options, "",""); hash64_t hash = 0; ForEachItemInRev(idx, opts) { const char *opt = opts.item(idx); if (strnicmp(opt, ""batch="", 6)==0) { const char *val=opt+6; if (stricmp(val, ""LOGGED"")==0) batchMode = CASS_BATCH_TYPE_LOGGED; else if (stricmp(val, ""UNLOGGED"")==0) batchMode = CASS_BATCH_TYPE_UNLOGGED; else if (stricmp(val, ""COUNTER"")==0) batchMode = CASS_BATCH_TYPE_COUNTER; opts.remove(idx); } else if (strnicmp(opt, ""pagesize="", 9)==0) { pageSize = atoi(opt+9); opts.remove(idx); } else hash = rtlHash64VStr(opt, hash); } cluster.setown(lookupCachedSession(hash, opts)); } virtual bool getBooleanResult() { bool ret = cassandraembed::getBooleanResult(NULL, getScalarResult()); checkSingleRow(); return ret; } virtual void getDataResult(size32_t &len, void * &result) { cassandraembed::getDataResult(NULL, getScalarResult(), len, result); checkSingleRow(); } virtual double getRealResult() { double ret = cassandraembed::getRealResult(NULL, getScalarResult()); checkSingleRow(); return ret; } virtual __int64 getSignedResult() { __int64 ret = cassandraembed::getSignedResult(NULL, getScalarResult()); checkSingleRow(); return ret; } virtual unsigned __int64 getUnsignedResult() { unsigned __int64 ret = cassandraembed::getUnsignedResult(NULL, getScalarResult()); checkSingleRow(); return ret; } virtual void getStringResult(size32_t &chars, char * &result) { cassandraembed::getStringResult(NULL, getScalarResult(), chars, result); checkSingleRow(); } virtual void getUTF8Result(size32_t &chars, char * &result) { cassandraembed::getUTF8Result(NULL, getScalarResult(), chars, result); checkSingleRow(); } virtual void getUnicodeResult(size32_t &chars, UChar * &result) { cassandraembed::getUnicodeResult(NULL, getScalarResult(), chars, result); checkSingleRow(); } virtual void getDecimalResult(Decimal &value) { cassandraembed::getDecimalResult(NULL, getScalarResult(), value); checkSingleRow(); } virtual void getSetResult(bool & __isAllResult, size32_t & __resultBytes, void * & __result, int elemType, size32_t elemSize) { CassandraIterator iterator(cass_iterator_from_collection(getScalarResult())); rtlRowBuilder out; byte *outData = NULL; size32_t outBytes = 0; while (cass_iterator_next(iterator)) { const CassValue *value = cass_iterator_get_value(iterator); assertex(value); if (elemSize != UNKNOWN_LENGTH) { out.ensureAvailable(outBytes + elemSize); outData = out.getbytes() + outBytes; } switch ((type_t) elemType) { case type_int: rtlWriteInt(outData, cassandraembed::getSignedResult(NULL, value), elemSize); break; case type_unsigned: rtlWriteInt(outData, cassandraembed::getUnsignedResult(NULL, value), elemSize); break; case type_real: if (elemSize == sizeof(double)) * (double *) outData = cassandraembed::getRealResult(NULL, value); else { assertex(elemSize == sizeof(float)); * (float *) outData = (float) cassandraembed::getRealResult(NULL, value); } break; case type_boolean: assertex(elemSize == sizeof(bool)); * (bool *) outData = cassandraembed::getBooleanResult(NULL, value); break; case type_string: case type_varstring: { rtlDataAttr str; size32_t lenBytes; cassandraembed::getStringResult(NULL, value, lenBytes, str.refstr()); if (elemSize == UNKNOWN_LENGTH) { if (elemType == type_string) { out.ensureAvailable(outBytes + lenBytes + sizeof(size32_t)); outData = out.getbytes() + outBytes; * (size32_t *) outData = lenBytes; rtlStrToStr(lenBytes, outData+sizeof(size32_t), lenBytes, str.getstr()); outBytes += lenBytes + sizeof(size32_t); } else { out.ensureAvailable(outBytes + lenBytes + 1); outData = out.getbytes() + outBytes; rtlStrToVStr(0, outData, lenBytes, str.getstr()); outBytes += lenBytes + 1; } } else { if (elemType == type_string) rtlStrToStr(elemSize, outData, lenBytes, str.getstr()); else rtlStrToVStr(elemSize, outData, lenBytes, str.getstr()); // Fixed size null terminated strings... weird. } break; } case type_unicode: case type_utf8: { rtlDataAttr str; size32_t lenChars; cassandraembed::getUTF8Result(NULL, value, lenChars, str.refstr()); const char * text = str.getstr(); size32_t lenBytes = rtlUtf8Size(lenChars, text); if (elemType == type_utf8) { assertex (elemSize == UNKNOWN_LENGTH); out.ensureAvailable(outBytes + lenBytes + sizeof(size32_t)); outData = out.getbytes() + outBytes; * (size32_t *) outData = lenChars; rtlStrToStr(lenBytes, outData+sizeof(size32_t), lenBytes, text); outBytes += lenBytes + sizeof(size32_t); } else { if (elemSize == UNKNOWN_LENGTH) { // You can't assume that number of chars in utf8 matches number in unicode16 ... size32_t numchars16; rtlDataAttr unicode16; rtlUtf8ToUnicodeX(numchars16, unicode16.refustr(), lenChars, text); out.ensureAvailable(outBytes + numchars16*sizeof(UChar) + sizeof(size32_t)); outData = out.getbytes() + outBytes; * (size32_t *) outData = numchars16; rtlUnicodeToUnicode(numchars16, (UChar *) (outData+sizeof(size32_t)), numchars16, unicode16.getustr()); outBytes += numchars16*sizeof(UChar) + sizeof(size32_t); } else rtlUtf8ToUnicode(elemSize / sizeof(UChar), (UChar *) outData, lenChars, text); } break; } default: fail(""type mismatch - unsupported return type""); } if (elemSize != UNKNOWN_LENGTH) outBytes += elemSize; } __isAllResult = false; __resultBytes = outBytes; __result = out.detachdata(); } virtual IRowStream *getDatasetResult(IEngineRowAllocator * _resultAllocator) { return new CassandraRowStream(inputStream, stmtInfo, _resultAllocator); } virtual byte * getRowResult(IEngineRowAllocator * _resultAllocator) { if (!stmtInfo->hasResult() || stmtInfo->rowCount() != 1) typeError(""row"", NULL, NULL); CassandraRowStream stream(NULL, stmtInfo, _resultAllocator); roxiemem::OwnedConstRoxieRow ret = stream.nextRow(); stream.stop(); if (ret == NULL) // Check for exactly one returned row typeError(""row"", NULL, NULL); return (byte *) ret.getClear(); } virtual size32_t getTransformResult(ARowBuilder & rowBuilder) { if (!stmtInfo->hasResult() || stmtInfo->rowCount() != 1) typeError(""row"", NULL, NULL); if (!stmtInfo->next()) fail(""Failed to read row""); CassandraRowBuilder cassandraRowBuilder(stmtInfo); const RtlTypeInfo *typeInfo = rowBuilder.queryAllocator()->queryOutputMeta()->queryTypeInfo(); assertex(typeInfo); RtlFieldStrInfo dummyField("""", NULL, typeInfo); return typeInfo->build(rowBuilder, 0, &dummyField, cassandraRowBuilder); } virtual void bindRowParam(const char *name, IOutputMetaData & metaVal, const byte *val) override { CassandraRecordBinder binder(logctx, metaVal.queryTypeInfo(), stmtInfo, nextParam); binder.processRow(val); nextParam += binder.numFields(); } virtual void bindDatasetParam(const char *name, IOutputMetaData & metaVal, IRowStream * val) { // We only support a single dataset parameter... // MORE - look into batch? if (inputStream) { fail(""At most one dataset parameter supported""); } inputStream.setown(new CassandraDatasetBinder(logctx, LINK(val), metaVal.queryTypeInfo(), stmtInfo, nextParam)); nextParam += inputStream->numFields(); } virtual void bindBooleanParam(const char *name, bool val) { checkBind(cass_statement_bind_bool(stmtInfo->queryStatement(), checkNextParam(name), val ? cass_true : cass_false), name); } virtual void bindDataParam(const char *name, size32_t len, const void *val) { checkBind(cass_statement_bind_bytes(stmtInfo->queryStatement(), checkNextParam(name), (const cass_byte_t*) val, len), name); } virtual void bindFloatParam(const char *name, float val) { checkBind(cass_statement_bind_float(stmtInfo->queryStatement(), checkNextParam(name), val), name); } virtual void bindRealParam(const char *name, double val) { checkBind(cass_statement_bind_double(stmtInfo->queryStatement(), checkNextParam(name), val), name); } virtual void bindSignedSizeParam(const char *name, int size, __int64 val) { if (size > 4) checkBind(cass_statement_bind_int64(stmtInfo->queryStatement(), checkNextParam(name), val), name); else checkBind(cass_statement_bind_int32(stmtInfo->queryStatement(), checkNextParam(name), val), name); } virtual void bindSignedParam(const char *name, __int64 val) { bindSignedSizeParam(name, 8, val); } virtual void bindUnsignedSizeParam(const char *name, int size, unsigned __int64 val) { UNSUPPORTED(""UNSIGNED columns""); } virtual void bindUnsignedParam(const char *name, unsigned __int64 val) { UNSUPPORTED(""UNSIGNED columns""); } virtual void bindStringParam(const char *name, size32_t len, const char *val) { size32_t utf8chars; rtlDataAttr utfText; rtlStrToUtf8X(utf8chars, utfText.refstr(), len, val); checkBind(cass_statement_bind_string_n(stmtInfo->queryStatement(), checkNextParam(name), utfText.getstr(), rtlUtf8Size(utf8chars, utfText.getstr())), name); } virtual void bindVStringParam(const char *name, const char *val) { bindStringParam(name, strlen(val), val); } virtual void bindUTF8Param(const char *name, size32_t chars, const char *val) { checkBind(cass_statement_bind_string_n(stmtInfo->queryStatement(), checkNextParam(name), val, rtlUtf8Size(chars, val)), name); } virtual void bindUnicodeParam(const char *name, size32_t chars, const UChar *val) { size32_t utf8chars; rtlDataAttr utfText; rtlUnicodeToUtf8X(utf8chars, utfText.refstr(), chars, val); checkBind(cass_statement_bind_string_n(stmtInfo->queryStatement(), checkNextParam(name), utfText.getstr(), rtlUtf8Size(utf8chars, utfText.getstr())), name); } virtual void bindSetParam(const char *name, int elemType, size32_t elemSize, bool isAll, size32_t totalBytes, const void *setData) { if (isAll) UNSUPPORTED(""SET(ALL)""); type_t typecode = (type_t) elemType; const byte *inData = (const byte *) setData; const byte *endData = inData + totalBytes; int numElems; if (elemSize == UNKNOWN_LENGTH) { numElems = 0; // Will need 2 passes to work out how many elements there are in the set :( while (inData < endData) { int thisSize; switch (elemType) { case type_varstring: thisSize = strlen((const char *) inData) + 1; break; case type_string: thisSize = * (size32_t *) inData + sizeof(size32_t); break; case type_unicode: thisSize = (* (size32_t *) inData) * sizeof(UChar) + sizeof(size32_t); break; case type_utf8: thisSize = rtlUtf8Size(* (size32_t *) inData, inData + sizeof(size32_t)) + sizeof(size32_t); break; default: fail(""Unsupported parameter type""); break; } inData += thisSize; numElems++; } inData = (const byte *) setData; } else numElems = totalBytes / elemSize; // We don't know whether the corresponding field in Cassandra is a list or a set. Try binding a dummy list to tell which. Owned collection; CassandraCollection temp(cass_collection_new(CASS_COLLECTION_TYPE_LIST, 0)); if (cass_statement_bind_collection(stmtInfo->queryStatement(), nextParam, temp) == CASS_OK) collection.setown(new CassandraCollection(cass_collection_new(CASS_COLLECTION_TYPE_LIST, numElems))); else collection.setown(new CassandraCollection(cass_collection_new(CASS_COLLECTION_TYPE_SET, numElems))); while (inData < endData) { size32_t thisSize = elemSize; CassError rc; switch (typecode) { case type_int: if (elemSize > 4) rc = cass_collection_append_int64(*collection, rtlReadInt(inData, elemSize)); else rc = cass_collection_append_int32(*collection, rtlReadInt(inData, elemSize)); break; case type_unsigned: UNSUPPORTED(""UNSIGNED columns""); break; case type_varstring: { size32_t numChars = strlen((const char *) inData); if (elemSize == UNKNOWN_LENGTH) thisSize = numChars + 1; size32_t utf8chars; rtlDataAttr utfText; rtlStrToUtf8X(utf8chars, utfText.refstr(), numChars, (const char *) inData); rc = cass_collection_append_string_n(*collection, utfText.getstr(), rtlUtf8Size(utf8chars, utfText.getstr())); break; } case type_string: { if (elemSize == UNKNOWN_LENGTH) { thisSize = * (size32_t *) inData; inData += sizeof(size32_t); } size32_t utf8chars; rtlDataAttr utfText; rtlStrToUtf8X(utf8chars, utfText.refstr(), thisSize, (const char *) inData); rc = cass_collection_append_string_n(*collection, utfText.getstr(), rtlUtf8Size(utf8chars, utfText.getstr())); break; } case type_real: if (elemSize == sizeof(double)) rc = cass_collection_append_double(*collection, * (double *) inData); else rc = cass_collection_append_float(*collection, * (float *) inData); break; case type_boolean: assertex(elemSize == sizeof(bool)); rc = cass_collection_append_bool(*collection, *(bool*)inData ? cass_true : cass_false); break; case type_unicode: { if (elemSize == UNKNOWN_LENGTH) { thisSize = (* (size32_t *) inData) * sizeof(UChar); // NOTE - it's in chars... inData += sizeof(size32_t); } unsigned unicodeChars; rtlDataAttr unicode; rtlUnicodeToUtf8X(unicodeChars, unicode.refstr(), thisSize / sizeof(UChar), (const UChar *) inData); size32_t sizeBytes = rtlUtf8Size(unicodeChars, unicode.getstr()); rc = cass_collection_append_string_n(*collection, unicode.getstr(), sizeBytes); break; } case type_utf8: { assertex (elemSize == UNKNOWN_LENGTH); size32_t numChars = * (size32_t *) inData; inData += sizeof(size32_t); thisSize = rtlUtf8Size(numChars, inData); rc = cass_collection_append_string_n(*collection, (const char *) inData, thisSize); break; } case type_data: if (elemSize == UNKNOWN_LENGTH) { thisSize = * (size32_t *) inData; inData += sizeof(size32_t); } rc = cass_collection_append_bytes(*collection, (const cass_byte_t*) inData, thisSize); break; default: fail(""Unsupported parameter type""); } checkBind(rc, name); inData += thisSize; } checkBind(cass_statement_bind_collection(stmtInfo->queryStatement(), checkNextParam(name), *collection), name); } virtual IInterface *bindParamWriter(IInterface *esdl, const char *esdlservice, const char *esdltype, const char *name) { return NULL; } virtual void paramWriterCommit(IInterface *writer) { } virtual void writeResult(IInterface *esdl, const char *esdlservice, const char *esdltype, IInterface *writer) { } virtual void importFunction(size32_t lenChars, const char *text) { throwUnexpected(); } virtual void compileEmbeddedScript(size32_t chars, const char *_script) { // Incoming script is not necessarily null terminated. Note that the chars refers to utf8 characters and not bytes. rtlSubstituteActivityContext(queryString, activityCtx, chars, _script); const char *script = queryString.str(); // Now null terminated if ((flags & (EFnoreturn|EFnoparams)) == (EFnoreturn|EFnoparams)) { for (;;) { const char *nextScript = findUnquoted(script, ';'); if (!nextScript) { // script should be pointing at only trailing whitespace, else it's a ""missing ;"" error break; } CassandraStatement statement(cass_statement_new_n(script, nextScript-script, 0)); CassandraFuture future(cass_session_execute(cluster->querySession(), statement)); future.wait(""execute statement""); script = nextScript; } } else { if ((flags & EFnoparams) == 0) numParams = countBindings(script); else numParams = 0; stmtInfo.setown(cluster->createStatementInfo(script, numParams, batchMode, pageSize)); } } virtual void callFunction() { // Does not seem to be a way to check number of parameters expected... // if (nextParam != cass_statement_bind_count(stmtInfo)) // fail(""Not enough parameters""); try { if (stmtInfo && !stmtInfo->hasResult()) lazyExecute(); } catch (IException *E) { StringBuffer msg; E->errorMessage(msg); msg.appendf("" (processing query %s)"", queryString.str()); throw makeStringException(E->errorCode(), msg); } } protected: void lazyExecute() { if (inputStream) inputStream->executeAll(stmtInfo); else stmtInfo->execute(); } const CassValue *getScalarResult() { if (!stmtInfo->next()) typeError(""scalar"", NULL, NULL); if (cass_row_get_column(stmtInfo->queryRow(), 1)) typeError(""scalar"", NULL, NULL); const CassValue *result = cass_row_get_column(stmtInfo->queryRow(), 0); if (!result) typeError(""scalar"", NULL, NULL); return result; } void checkSingleRow() { if (stmtInfo->rowCount() != 1) typeError(""scalar"", NULL, NULL); } unsigned countBindings(const char *query) { unsigned queryCount = 0; while ((query = findUnquoted(query, '?')) != NULL) queryCount++; return queryCount; } const char *findUnquoted(const char *query, char searchFor) { // Note - returns pointer to char AFTER the first occurrence of searchFor outside of quotes char inStr = '\\0'; char ch; while ((ch = *query++) != 0) { if (ch == inStr) inStr = false; else switch (ch) { case '\\'': case '""': inStr = ch; break; case '\\\\': if (inStr && *query) query++; break; case '/': if (!inStr) { if (*query=='/') { while (*query && *query != '\\n') query++; } else if (*query=='*') { query++; for (;;) { if (!*query) fail(""Unterminated comment in query string""); if (*query=='*' && query[1]=='/') { query+= 2; break; } query++; } } } break; default: if (!inStr && ch==searchFor) return query; break; } } return NULL; } inline unsigned checkNextParam(const char *name) { if (nextParam == numParams) failx(""Too many parameters supplied: No matching ? for parameter %s"", name); return nextParam++; } inline void checkBind(CassError rc, const char *name) { if (rc != CASS_OK) { failx(""While binding parameter %s: %s"", name, cass_error_desc(rc)); } } Owned cluster; Owned stmtInfo; Owned inputStream; const IContextLogger &logctx; const IThorActivityContext *activityCtx; unsigned flags; unsigned nextParam; unsigned numParams; StringBuffer queryString; CassBatchType batchMode; unsigned pageSize; }; class CassandraEmbedContext : public CInterfaceOf { public: virtual IEmbedFunctionContext *createFunctionContext(unsigned flags, const char *options) override { return createFunctionContextEx(nullptr, nullptr, flags, options); } virtual IEmbedFunctionContext *createFunctionContextEx(ICodeContext * ctx, const IThorActivityContext *activityCtx, unsigned flags, const char *options) override { if (flags & EFimport) UNSUPPORTED(""IMPORT""); else return new CassandraEmbedFunctionContext(ctx ? ctx->queryContextLogger() : queryDummyContextLogger(), activityCtx, flags, options); } virtual IEmbedServiceContext *createServiceContext(const char *service, unsigned flags, const char *options) override { throwUnexpected(); } }; extern DECL_EXPORT IEmbedContext* getEmbedContext() { return new CassandraEmbedContext(); } extern DECL_EXPORT bool syntaxCheck(const char *script) { return true; // MORE } } // namespace ",16133,True,2788.3028317445965,median "/** * @file ubcc1pi_standalone/Helpers/CrossSectionHelper.cxx * * @brief The implementation of the cross section helper class */ #include ""ubcc1pi_standalone/Helpers/CrossSectionHelper.h"" #include ""ubcc1pi_standalone/Helpers/AnalysisHelper.h"" #include ""ubcc1pi_standalone/Helpers/GeometryHelper.h"" #include #include #include namespace ubcc1pi { CrossSectionHelper::FluxReweightor::FluxReweightor(const std::vector &binEdges, const std::vector &binValuesNominal, const SystDimensionsMap &fluxWeightsDimensions) : /// @cond Doxygen can't handle this initilizer list m_dimensions(fluxWeightsDimensions), m_pFluxNominal(CrossSectionHelper::GetTH1F(binEdges)), m_pSpectrumNominal(CrossSectionHelper::GetTH1F(binEdges)), m_spectrumVariations(CrossSectionHelper::GetSystTH1FMap(binEdges, fluxWeightsDimensions)), // Define the cache-function that gets the integrated flux variations // ATTN it might look a bit odd to some to define a function in the constructor! To be clear, here we are initalizing the member // variable named m_getIntegratedFluxVariationFunction. This is a SystCacheFunction that takes a lambda function as it's first paramter // and stores the logic for later. When the user calls GetIntegratedFluxVariation() we ask the SystCacheFunction to check if it has the // value we are looking for in it's cache. If the answer is yes, then we just return the cached value. If the answer is no, then we call // the logic (defined in the lambda function below), store the result in the cache for later and return it. m_getIntegratedFluxVariationFunction([&](const std::string ¶mName, const unsigned int universeIndex) { // Setup a new histogram to hold the reweighted flux auto pReweightedFlux = CrossSectionHelper::GetTH1F(binEdges); // Get the event rate spectrum in this universe const auto pSpectrumVariation = m_spectrumVariations.at(paramName).at(universeIndex); // Loop over each bin const auto nBins = binEdges.size() - 1; for (unsigned iBin = 1; iBin <= nBins; ++iBin) { // Get bin value for the nominal spectrum and the specturm in this universe const auto nEventsNominal = m_pSpectrumNominal->GetBinContent(iBin); const auto nEventsVariation = pSpectrumVariation->GetBinContent(iBin); // Get the ratio of the variation to the nominal (if not possible use a unit weight) const auto weight = (nEventsNominal <= std::numeric_limits::epsilon() ? 1.f : (nEventsVariation / nEventsNominal) ); // Apply this weight to the nominal flux const auto nominalFlux = m_pFluxNominal->GetBinContent(iBin); const auto reweightedFlux = nominalFlux * weight; // Store the result pReweightedFlux->SetBinContent(iBin, reweightedFlux); } // Return the integrated flux return this->GetIntegratedFlux(pReweightedFlux); }, m_dimensions) /// @endcond { // There should be one more bin edge than the number of bins if (binEdges.size() != binValuesNominal.size() + 1) throw std::invalid_argument(""FluxReweightor::FluxReweightor - Number of bin edges doesn't match number of bins!""); // Fill the nominal flux histogram for (unsigned int iBin = 1; iBin <= binValuesNominal.size(); ++iBin) { // ATTN here we shift the index by 1 as root enumerates bins from 1 and the vector enumerates from 0 m_pFluxNominal->SetBinContent(iBin, binValuesNominal.at(iBin - 1)); } } // ----------------------------------------------------------------------------------------------------------------------------------------- void CrossSectionHelper::FluxReweightor::AddEvent(const float trueNuEnergy, const float nominalWeight, const SystFloatMap &fluxWeights) { // Make sure we have a valid input map CrossSectionHelper::ValidateSystMap(fluxWeights, m_dimensions); // Here we clear any cached values for the integrated flux variations because we are modifying the event rate spectra m_getIntegratedFluxVariationFunction.ClearCache(); // Fill the nominal spectrum m_pSpectrumNominal->Fill(trueNuEnergy, nominalWeight); // Fill the universes for (const auto &[paramName, weights] : fluxWeights) { auto &spectrumUniverses = m_spectrumVariations.at(paramName); for (unsigned int iUni = 0; iUni < weights.size(); ++iUni) { const auto universeWeight = nominalWeight * weights.at(iUni); spectrumUniverses.at(iUni)->Fill(trueNuEnergy, universeWeight); } } } // ----------------------------------------------------------------------------------------------------------------------------------------- std::shared_ptr CrossSectionHelper::FluxReweightor::GetNominalFlux() const { return m_pFluxNominal; } // ----------------------------------------------------------------------------------------------------------------------------------------- float CrossSectionHelper::FluxReweightor::GetIntegratedFlux(const std::shared_ptr &pFlux) const { float total = 0.f; for (unsigned int iBin = 1; iBin <= static_cast(pFlux->GetNbinsX()); ++iBin) { total += pFlux->GetBinContent(iBin); } return total; } // ----------------------------------------------------------------------------------------------------------------------------------------- float CrossSectionHelper::FluxReweightor::GetIntegratedNominalFlux() const { return this->GetIntegratedFlux(m_pFluxNominal); } // ----------------------------------------------------------------------------------------------------------------------------------------- float CrossSectionHelper::FluxReweightor::GetIntegratedFluxVariation(const std::string ¶mName, const unsigned int universeIndex) { // Call the cache-function to either calculate the return value or retrieve it from the cache return m_getIntegratedFluxVariationFunction(paramName, universeIndex); } // ----------------------------------------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------------------------------------- CrossSectionHelper::CrossSection::CrossSection(const SystParams &systParams, const std::vector &binEdges, const bool hasUnderflow, const bool hasOverflow, const bool scaleByBinWidth) : m_systParams(systParams), m_binEdges(binEdges), m_metadata(binEdges, hasUnderflow, hasOverflow, scaleByBinWidth), m_scaleByBinWidth(scaleByBinWidth), m_pSignal_true_nom(CrossSectionHelper::GetTH1F(binEdges)), m_pSignal_selected_recoTrue_nom(CrossSectionHelper::GetTH2F(binEdges)), m_pBackground_selected_reco_nom(CrossSectionHelper::GetTH1F(binEdges)), m_pBNBData_selected_reco(CrossSectionHelper::GetTH1F(binEdges)) { // Make sure the bin edges are valid const int nAnalysisBins = (binEdges.size() - 1) - (hasUnderflow ? 1 : 0) - (hasOverflow ? 1 : 0); if (nAnalysisBins <= 0) throw std::invalid_argument(""CrossSection::CrossSection - Insufficient bin edges provided!""); // Setup a dimensions map for the miscellaneous (""misc"") multisim parameters. // These are added in ad-hoc (i.e. they don't come from the weights stored in the truth information) const SystDimensionsMap miscDimensions = { // Here we apply a weight to each event using the Poisson bootstrap method to estimate the MC stats uncertainty { ""bootstrap"", systParams.nBootstrapUniverses }, // Here we apply a 2-universe multisim in which we weight the dirt up and down by 100% { ""dirt"", 2 } }; // Setup the maps to hold the histograms for the multisim parameters m_signal_true_multisims.emplace(""flux"", CrossSectionHelper::GetSystTH1FMap(binEdges, systParams.fluxDimensions)); m_signal_true_multisims.emplace(""xsec"", CrossSectionHelper::GetSystTH1FMap(binEdges, systParams.xsecDimensions)); m_signal_true_multisims.emplace(""misc"", CrossSectionHelper::GetSystTH1FMap(binEdges, miscDimensions)); m_signal_selected_recoTrue_multisims.emplace(""flux"", CrossSectionHelper::GetSystTH2FMap(binEdges, systParams.fluxDimensions)); m_signal_selected_recoTrue_multisims.emplace(""xsec"", CrossSectionHelper::GetSystTH2FMap(binEdges, systParams.xsecDimensions)); m_signal_selected_recoTrue_multisims.emplace(""misc"", CrossSectionHelper::GetSystTH2FMap(binEdges, miscDimensions)); m_background_selected_reco_multisims.emplace(""flux"", CrossSectionHelper::GetSystTH1FMap(binEdges, systParams.fluxDimensions)); m_background_selected_reco_multisims.emplace(""xsec"", CrossSectionHelper::GetSystTH1FMap(binEdges, systParams.xsecDimensions)); m_background_selected_reco_multisims.emplace(""misc"", CrossSectionHelper::GetSystTH1FMap(binEdges, miscDimensions)); // Setup the maps to hold the histograms for the unisim parameters m_signal_true_unisims.emplace(""detector"", CrossSectionHelper::GetSystUnisimTH1FMap(binEdges, systParams.detVarDimensions)); m_signal_selected_recoTrue_unisims.emplace(""detector"", CrossSectionHelper::GetSystUnisimTH2FMap(binEdges, systParams.detVarDimensions)); m_background_selected_reco_unisims.emplace(""detector"", CrossSectionHelper::GetSystUnisimTH1FMap(binEdges, systParams.detVarDimensions)); // ATTN we could in theory include other unisim parameters here using a different name. At the moment we only use ""detector"". } // ----------------------------------------------------------------------------------------------------------------------------------------- void CrossSectionHelper::CrossSection::AddSignalEvent(const float recoValue, const float trueValue, const bool isSelected, const float nominalWeight, const SystFloatMap &fluxWeights, const SystFloatMap &xsecWeights) { // Get the miscellaneous weights const SystFloatMap miscWeights = { // Generate the bootstrap weights { ""bootstrap"", CrossSectionHelper::GenerateBootstrapWeights(m_systParams.nBootstrapUniverses) }, // A signal event is never dirt - so just use a unit weight { ""dirt"", {1.f, 1.f} } }; m_pSignal_true_nom->Fill(trueValue, nominalWeight); CrossSectionHelper::FillSystTH1FMap(trueValue, nominalWeight, fluxWeights, m_signal_true_multisims.at(""flux"")); CrossSectionHelper::FillSystTH1FMap(trueValue, nominalWeight, xsecWeights, m_signal_true_multisims.at(""xsec"")); CrossSectionHelper::FillSystTH1FMap(trueValue, nominalWeight, miscWeights, m_signal_true_multisims.at(""misc"")); if (!isSelected) return; // ATTN the reco value is only used if the event is selected m_pSignal_selected_recoTrue_nom->Fill(recoValue, trueValue, nominalWeight); CrossSectionHelper::FillSystTH2FMap(recoValue, trueValue, nominalWeight, fluxWeights, m_signal_selected_recoTrue_multisims.at(""flux"")); CrossSectionHelper::FillSystTH2FMap(recoValue, trueValue, nominalWeight, xsecWeights, m_signal_selected_recoTrue_multisims.at(""xsec"")); CrossSectionHelper::FillSystTH2FMap(recoValue, trueValue, nominalWeight, miscWeights, m_signal_selected_recoTrue_multisims.at(""misc"")); } // ----------------------------------------------------------------------------------------------------------------------------------------- void CrossSectionHelper::CrossSection::AddSignalEventDetVar(const float recoValue, const float trueValue, const bool isSelected, const float nominalWeight, const std::string ¶mName) { if (!static_cast(m_signal_true_unisims.at(""detector"").count(paramName))) throw std::invalid_argument(""CrossSection::AddSignalEventDetVar - Unknown parameter or CV sample name \\"""" + paramName + ""\\""""); m_signal_true_unisims.at(""detector"").at(paramName)->Fill(trueValue, nominalWeight); if (!isSelected) return; m_signal_selected_recoTrue_unisims.at(""detector"").at(paramName)->Fill(recoValue, trueValue, nominalWeight); } // ----------------------------------------------------------------------------------------------------------------------------------------- void CrossSectionHelper::CrossSection::AddSelectedBackgroundEvent(const float recoValue, const bool isDirt, const float nominalWeight, const SystFloatMap &fluxWeights, const SystFloatMap &xsecWeights) { // The weight to apply as a result of dirt // - For non-dirt events, just use zero (i.e. no change from the nominal simulation) // - For dirt event we here use +-100% const auto dirtWeightDelta = isDirt ? 1.f : 0.f; // Get the miscellaneous weights const SystFloatMap miscWeights = { // Generate the bootstrap weights { ""bootstrap"", CrossSectionHelper::GenerateBootstrapWeights(m_systParams.nBootstrapUniverses) }, // Apply the dirt weight { ""dirt"", {1.f - dirtWeightDelta, 1.f + dirtWeightDelta} } }; m_pBackground_selected_reco_nom->Fill(recoValue, nominalWeight); CrossSectionHelper::FillSystTH1FMap(recoValue, nominalWeight, fluxWeights, m_background_selected_reco_multisims.at(""flux"")); CrossSectionHelper::FillSystTH1FMap(recoValue, nominalWeight, xsecWeights, m_background_selected_reco_multisims.at(""xsec"")); CrossSectionHelper::FillSystTH1FMap(recoValue, nominalWeight, miscWeights, m_background_selected_reco_multisims.at(""misc"")); } // ----------------------------------------------------------------------------------------------------------------------------------------- void CrossSectionHelper::CrossSection::AddSelectedBackgroundEventDetVar(const float recoValue, const float nominalWeight, const std::string ¶mName) { if (!static_cast(m_background_selected_reco_unisims.at(""detector"").count(paramName))) throw std::invalid_argument(""CrossSection::AddSelectedBackgroundEventDetVar - Unknown parameter or CV sample name \\"""" + paramName + ""\\""""); m_background_selected_reco_unisims.at(""detector"").at(paramName)->Fill(recoValue, nominalWeight); } // ----------------------------------------------------------------------------------------------------------------------------------------- void CrossSectionHelper::CrossSection::AddSelectedBNBDataEvent(const float recoValue) { m_pBNBData_selected_reco->Fill(recoValue); } // ----------------------------------------------------------------------------------------------------------------------------------------- ubsmear::UBXSecMeta CrossSectionHelper::CrossSection::GetMetadata() const { return m_metadata; } // ----------------------------------------------------------------------------------------------------------------------------------------- std::vector CrossSectionHelper::CrossSection::GetBinEdges() const { return m_binEdges; } // ----------------------------------------------------------------------------------------------------------------------------------------- ubsmear::UBMatrix CrossSectionHelper::CrossSection::GetBinWidths() const { return m_metadata.GetBinWidths(); } // ----------------------------------------------------------------------------------------------------------------------------------------- ubsmear::UBMatrix CrossSectionHelper::CrossSection::GetCrossSection(const ubsmear::UBMatrix &selected, const ubsmear::UBMatrix &backgrounds, const float integratedFlux, const float exposurePOT, const float nTargets) const { // Check the input event rate has the right dimensions if (selected.GetColumns() != 1) throw std::invalid_argument(""CrossSection::GetCrossSection - Input event rate isn't a column vector""); if (selected.GetRows() != m_metadata.GetNBins()) throw std::invalid_argument(""CrossSection::GetCrossSection - Input event rate has the wrong number of bins""); // Check the input backgrounds have the right dimensions if (backgrounds.GetColumns() != 1) throw std::invalid_argument(""CrossSection::GetCrossSection - Input background rate isn't a column vector""); if (backgrounds.GetRows() != m_metadata.GetNBins()) throw std::invalid_argument(""CrossSection::GetCrossSection - Input background rate has the wrong number of bins""); // Get the normalisation factor const auto norm = integratedFlux * exposurePOT * nTargets; if (norm <= std::numeric_limits::epsilon()) throw std::invalid_argument(""CrossSection::GetCrossSection - Product of flux, exposure and targets non-positive""); // Get the column vector of bin widths const auto binWidths = this->GetBinWidths(); // Now get the flux-integrated, forward-folded cross-section by // - Subtracting the backgrounds // - Scaling by the normalisation factor // - Scaling (element wise) by the bin-widths return ubsmear::ElementWiseOperation( (selected - backgrounds), binWidths * norm, [](const float numerator, const float denominator) { if (denominator <= std::numeric_limits::epsilon()) throw std::logic_error(""CrossSection::GetCrossSection - Found a bin in which the denominator (flux * POT * nTargets * binWidth) is <= 0""); return numerator / denominator; } ); } // ----------------------------------------------------------------------------------------------------------------------------------------- std::shared_ptr CrossSectionHelper::CrossSection::GetSmearingMatrix(const std::shared_ptr &pSignal_true, const std::shared_ptr &pSignal_selected_recoTrue) const { // Get the input histograms as a matrix const auto allTrue = CrossSectionHelper::GetMatrixFromHist(pSignal_true); const auto selectedRecoTrue = CrossSectionHelper::GetMatrixFromHist(pSignal_selected_recoTrue); // Check theh matrices have the expected sizes if (!ubsmear::UBMatrixHelper::IsSquare(selectedRecoTrue)) throw std::invalid_argument(""CrossSection::GetSmearingMatrix - input reco-true matrix isn't square""); const auto nBins = allTrue.GetRows(); if (selectedRecoTrue.GetRows() != nBins) throw std::invalid_argument(""CrossSection::GetSmearingMatrix - the input objects differ in number of bins""); // Get the elements of the smearing matrix std::vector elements; for (unsigned int iReco = 0; iReco < nBins; ++iReco) { for (unsigned int iTrue = 0; iTrue < nBins; ++iTrue) { // Get the total number of signal events in this true bin const auto denominator = allTrue.At(iTrue, 0); // ATTN. If we find a bin in which there are no signal events, then there's no sensible value for the smearing matrix element // Here we return null to indicate that the smearing matrix can't be found if (denominator <= std::numeric_limits::epsilon()) return std::shared_ptr(nullptr); elements.push_back(selectedRecoTrue.At(iReco, iTrue) / denominator); } } return std::make_shared(elements, nBins, nBins); } // ----------------------------------------------------------------------------------------------------------------------------------------- ubsmear::UBMatrix CrossSectionHelper::CrossSection::GetSignalSelectedTrue(const std::shared_ptr &pSignal_selected_recoTrue) const { // Get the input histogram as a matrix const auto recoTrueMatrix = CrossSectionHelper::GetMatrixFromHist(pSignal_selected_recoTrue); // Integrate over the reco bins std::vector elements; for (unsigned int iTrue = 0; iTrue < recoTrueMatrix.GetColumns(); ++iTrue) { float sum = 0.f; for (unsigned int iReco = 0; iReco < recoTrueMatrix.GetRows(); ++iReco) { sum += recoTrueMatrix.At(iReco, iTrue); } elements.push_back(sum); } // Return the result as a column vector return ubsmear::UBMatrix(elements, recoTrueMatrix.GetColumns(), 1); } // ----------------------------------------------------------------------------------------------------------------------------------------- ubsmear::UBMatrix CrossSectionHelper::CrossSection::GetSelectedBNBDataEvents() const { return CrossSectionHelper::GetMatrixFromHist(m_pBNBData_selected_reco); } // ----------------------------------------------------------------------------------------------------------------------------------------- ubsmear::UBMatrix CrossSectionHelper::CrossSection::GetSelectedBackgroundEvents() const { return CrossSectionHelper::GetMatrixFromHist(m_pBackground_selected_reco_nom); } // ----------------------------------------------------------------------------------------------------------------------------------------- ubsmear::UBMatrix CrossSectionHelper::CrossSection::GetSelectedSignalEvents() const { return this->GetSignalSelectedTrue(m_pSignal_selected_recoTrue_nom); } // ----------------------------------------------------------------------------------------------------------------------------------------- ubsmear::UBMatrix CrossSectionHelper::CrossSection::GetSignalEvents() const { return CrossSectionHelper::GetMatrixFromHist(m_pSignal_true_nom); } // ----------------------------------------------------------------------------------------------------------------------------------------- ubsmear::UBMatrix CrossSectionHelper::CrossSection::GetBNBDataCrossSection(const ScalingData &scalingData) const { // Get the number of selected events in BNB data const auto selected = CrossSectionHelper::GetMatrixFromHist(m_pBNBData_selected_reco); // Get the number of predicted backgrounds in the nominal universe const auto backgrounds = CrossSectionHelper::GetMatrixFromHist(m_pBackground_selected_reco_nom); // Get the integrated flux in the nominal universe const auto integratedFlux = scalingData.pFluxReweightor->GetIntegratedNominalFlux(); // Get the cross-section return this->GetCrossSection(selected, backgrounds, integratedFlux, scalingData.exposurePOT, scalingData.nTargets); } // ----------------------------------------------------------------------------------------------------------------------------------------- ubsmear::UBMatrix CrossSectionHelper::CrossSection::GetPredictedCrossSection(const ScalingData &scalingData) const { // Get the number of signal events in the nominal simulation in true bins const auto signal = CrossSectionHelper::GetMatrixFromHist(m_pSignal_true_nom); // Get the number of backgrounds is zero as we are effectively applying a ""perfect"" selection const auto zeroVector = ubsmear::UBMatrixHelper::GetZeroMatrix(signal.GetRows(), 1); // Get the integrated flux in the nominal universe const auto integratedFlux = scalingData.pFluxReweightor->GetIntegratedNominalFlux(); // Get the cross-section return this->GetCrossSection(signal, zeroVector, integratedFlux, scalingData.exposurePOT, scalingData.nTargets); } // ----------------------------------------------------------------------------------------------------------------------------------------- std::shared_ptr CrossSectionHelper::CrossSection::GetSmearingMatrixNominal() const { // Get the smearing matrix in the nominal universe return this->GetSmearingMatrix(m_pSignal_true_nom, m_pSignal_selected_recoTrue_nom); } // ----------------------------------------------------------------------------------------------------------------------------------------- ubsmear::UBMatrix CrossSectionHelper::CrossSection::GetSmearingMatrix() const { // Get the smearing matrix in the nominal universe const auto pSmearingMatrix = this->GetSmearingMatrixNominal(); // Check we were able to find the smearing matrix if (!pSmearingMatrix) throw std::logic_error(""CrossSection::GetSmearingMatrix - There's a bin with no signal events! Can't get the smearing matrix""); return *pSmearingMatrix; } // ----------------------------------------------------------------------------------------------------------------------------------------- ubsmear::UBMatrix CrossSectionHelper::CrossSection::GetBNBDataCrossSectionStatUncertainty(const ScalingData &scalingData) const { // Get the number of selected events in BNB data const auto selected = CrossSectionHelper::GetMatrixFromHist(m_pBNBData_selected_reco); // Get a vector containing the count uncertainties (Poisson) on each bin std::vector elements; const auto nBins = selected.GetRows(); for (unsigned int iBin = 0; iBin < nBins; ++iBin) { elements.push_back(AnalysisHelper::GetCountUncertainty(selected.At(iBin, 0))); } const ubsmear::UBMatrix selectedUncertainty(elements, nBins, 1); // Get the integrated flux in the nominal universe const auto integratedFlux = scalingData.pFluxReweightor->GetIntegratedNominalFlux(); // Scale the uncertainty on the number of selected events by same factor as the cross-section. // ATTN to apply the scaling we reuse the GetCrossSection function but intead pass it the count uncertainties as ""selected"" a zero // vector as the ""backgrounds"" const auto zeroVector = ubsmear::UBMatrixHelper::GetZeroMatrix(nBins, 1); return this->GetCrossSection(selectedUncertainty, zeroVector, integratedFlux, scalingData.exposurePOT, scalingData.nTargets); } // ----------------------------------------------------------------------------------------------------------------------------------------- CrossSectionHelper::SystBiasCovarianceMap CrossSectionHelper::CrossSection::GetBNBDataCrossSectionSystUncertainties(const ScalingData &scalingData) const { // Setup the output map SystBiasCovarianceMap outputMap; // Add the multisim parameters // ATTN the use of m_signal_true_multisims is arbitrary, we could use any multisims map for (const auto &[group, map] : m_signal_true_multisims) { for (const auto &entry : map) { const auto ¶mName = entry.first; outputMap[group].emplace(paramName, this->GetBNBDataCrossSectionDistributionParams(group, paramName, scalingData)); } } // Add the unisim parameters // ATTN again the use of m_signal_true_unisims is arbitrary, we could use any unisims map for (const auto &[group, map] : m_signal_true_unisims) { // ATTN for now we only have detector parameters that are unisims, if others are added later then we would need to add a clause here // to get the relevent dimensions. if (group != ""detector"") throw std::logic_error(""CrossSection::GetBNBDataCrossSectionSystUncertainties - Don't know dimensions of group: \\"""" + group + ""\\""""); const auto dimensions = m_systParams.detVarDimensions; // Extract the central-value names from the dimensions object std::vector cvNames; for (const auto &[paramName, cvName] : dimensions) cvNames.push_back(cvName); for (const auto &entry : map) { const auto ¶mName = entry.first; // ATTN The paramName could either be a detector variation sample of the name of a CV sample. // Here we check if the paramName is for a CV sample and if so, we can skip it. const auto isCVName = (std::find(cvNames.begin(), cvNames.end(), paramName) != cvNames.end()); if (isCVName) continue; // Get the central-value name that corresponds to this parameter const auto &cvName = dimensions.at(paramName); outputMap[group].emplace(paramName, this->GetBNBDataCrossSectionDistributionParamsUnisim(group, paramName, cvName, scalingData)); } } // Get the special POT normalisation uncertainty const auto pXSecNom = std::make_shared( this->GetBNBDataCrossSection(scalingData) ); outputMap[""misc""].emplace(""POT"", this->GetDistributionParamsNormalisation(pXSecNom, m_systParams.potFracUncertainty)); return outputMap; } // ----------------------------------------------------------------------------------------------------------------------------------------- CrossSectionHelper::SystBiasCovarianceMap CrossSectionHelper::CrossSection::GetSmearingMatrixSystUncertainties() const { // Setup the output map SystBiasCovarianceMap outputMap; // Add the multisim parameters // ATTN the use of m_signal_true_multisims is arbitrary, we could use any multisims map for (const auto &[group, map] : m_signal_true_multisims) { for (const auto &entry : map) { const auto ¶mName = entry.first; outputMap[group].emplace(paramName, this->GetSmearingMatrixDistributionParams(group, paramName)); } } // Add the unisim parameters // ATTN again the use of m_signal_true_unisims is arbitrary, we could use any unisims map for (const auto &[group, map] : m_signal_true_unisims) { // ATTN for now we only have detector parameters that are unisims, if others are added later then we would need to add a clause here // to get the relevent dimensions. if (group != ""detector"") throw std::logic_error(""CrossSection::GetSmearingMatrixSystUncertainties - Don't know dimensions of group: \\"""" + group + ""\\""""); const auto dimensions = m_systParams.detVarDimensions; // Extract the central-value names from the dimensions object std::vector cvNames; for (const auto &[paramName, cvName] : dimensions) cvNames.push_back(cvName); for (const auto &entry : map) { const auto ¶mName = entry.first; // ATTN The paramName could either be a detector variation sample of the name of a CV sample. // Here we check if the paramName is for a CV sample and if so, we can skip it. const auto isCVName = (std::find(cvNames.begin(), cvNames.end(), paramName) != cvNames.end()); if (isCVName) continue; // Get the central-value name that corresponds to this parameter const auto &cvName = dimensions.at(paramName); outputMap[group].emplace(paramName, this->GetSmearingMatrixDistributionParamsUnisim(group, paramName, cvName)); } } // Get the special POT normalisation uncertainty // ATTN no uncertainty is assigned to the smearing matrix due to POT normalisation (use a factor of 0.f) const auto pSmearingNom = CrossSectionHelper::FlattenMatrix(this->GetSmearingMatrixNominal()); outputMap[""misc""].emplace(""POT"", this->GetDistributionParamsNormalisation(pSmearingNom, 0.f)); return outputMap; } // ----------------------------------------------------------------------------------------------------------------------------------------- CrossSectionHelper::SystBiasCovariancePair CrossSectionHelper::CrossSection::GetPredictedCrossSectionStatUncertainty(const ScalingData &scalingData) const { // Get the number of universes for this systematic parameter // ATTN this choice of m_signal_true_multisims here is arbitrary, any of the mutlisims maps would do const auto nUniverses = m_systParams.nBootstrapUniverses; // Get the nominal cross-section const auto pXSecNom = std::make_shared(this->GetPredictedCrossSection(scalingData)); // Get the number of backgrounds is zero as we are effectively applying a ""perfect"" selection const auto zeroVector = ubsmear::UBMatrixHelper::GetZeroMatrix(pXSecNom->GetRows(), 1); // Get the integrated flux in the nominal universe const auto integratedFlux = scalingData.pFluxReweightor->GetIntegratedNominalFlux(); // The bootstrap universes const auto universes = m_signal_true_multisims.at(""misc"").at(""bootstrap""); // Get the distribution parameters return this->GetDistributionParams([&](const unsigned int &iUni) { // This is the function we call to get the value in each universe // Get the number of signal events in the nominal simulation in true bins const auto signal = CrossSectionHelper::GetMatrixFromHist(universes.at(iUni)); // Get the cross-section return std::make_shared ( this->GetCrossSection(signal, zeroVector, integratedFlux, scalingData.exposurePOT, scalingData.nTargets) ); }, nUniverses, pXSecNom); } // ----------------------------------------------------------------------------------------------------------------------------------------- ubsmear::UBMatrix CrossSectionHelper::CrossSection::GetBNBDataCrossSectionInUniverse(const std::string &group, const std::string ¶mName, const unsigned int universeIndex, const ScalingData &scalingData) const { // ATTN for speed, this function (and other similar functions) doesn't explicitly check if the input group, paramName, universeIndex is // valid. Instead we rely on the internal range checking of the .at() method for STL containers. This is for peformance reasons as this // function gets called once per universe! // Get the number of selected events in BNB data const auto selected = CrossSectionHelper::GetMatrixFromHist(m_pBNBData_selected_reco); // Get the number of predicted backgrounds in the supplied universe const auto backgrounds = CrossSectionHelper::GetMatrixFromHist(m_background_selected_reco_multisims.at(group).at(paramName).at(universeIndex)); // Get the integrated flux in the supplied universe (if it's not a flux parameter, then use the nominal universe) const auto integratedFlux = ( group == ""flux"" ? scalingData.pFluxReweightor->GetIntegratedFluxVariation(paramName, universeIndex) : scalingData.pFluxReweightor->GetIntegratedNominalFlux() ); // Get the cross-section return this->GetCrossSection(selected, backgrounds, integratedFlux, scalingData.exposurePOT, scalingData.nTargets); } // ----------------------------------------------------------------------------------------------------------------------------------------- ubsmear::UBMatrix CrossSectionHelper::CrossSection::GetBNBDataCrossSectionForUnisim(const std::string &group, const std::string ¶mName, const ScalingData &scalingData) const { // Get the number of selected events in BNB data const auto selected = CrossSectionHelper::GetMatrixFromHist(m_pBNBData_selected_reco); // Get the number of predicted backgrounds in the supplied universe const auto backgrounds = CrossSectionHelper::GetMatrixFromHist(m_background_selected_reco_unisims.at(group).at(paramName)); // Get the integrated flux in the nominal universe const auto integratedFlux = scalingData.pFluxReweightor->GetIntegratedNominalFlux(); // Get the cross-section return this->GetCrossSection(selected, backgrounds, integratedFlux, scalingData.exposurePOT, scalingData.nTargets); } // ----------------------------------------------------------------------------------------------------------------------------------------- CrossSectionHelper::SystBiasCovariancePair CrossSectionHelper::CrossSection::GetDistributionParams(const std::function(const unsigned int)> &func, const unsigned int nUniverses, const std::shared_ptr &pNominal) const { if (nUniverses == 0) throw std::logic_error(""CrossSection::GetDisributionParams - No universes supplied""); // Insist the nominal input is a column vector if (pNominal->GetColumns() != 1) throw std::logic_error(""CrossSection::GetDisributionParams - Input nominal is not a column vector""); // Get the number of bins const auto nBins = pNominal->GetRows(); // Setup some empty matrices to hold the mean vector and error matrices auto meanSum = ubsmear::UBMatrixHelper::GetZeroMatrix(nBins, 1); auto errorMatrixSum = ubsmear::UBMatrixHelper::GetZeroMatrix(nBins, nBins); // Loop over the universes unsigned int nValidUniverses = 0u; for (unsigned int iUni = 0; iUni < nUniverses; ++iUni) { //// BEGIN DEBUG AnalysisHelper::PrintLoadingBar(iUni, nUniverses); //// END DEBUG // Get the value in this universe const auto pUniverse = func(iUni); // Insist that we get a valid quanitiy in this universes if (!pUniverse) continue; // Count the number of valid universes nValidUniverses++; // Loop over the bins // ATTN for speed we don't expcitly check here if the universe has the same number of bins as the nominal. Instead we rely on the // internal range checking of the ubsmear::UBMatrix class for (unsigned int iBin = 0; iBin < nBins; ++iBin) { // Add up the universes meanSum.SetElement(iBin, 0, meanSum.At(iBin, 0) + pUniverse->At(iBin, 0)); // Loop over the bins again // ATTN the error matrix is symmetic so here we only set one half of the off-diagonals within the universe loop and then copy // them over to the other half afterwards. This is done for performance reasons as it halves the number of inserts required const auto diffI = pUniverse->At(iBin, 0) - pNominal->At(iBin, 0); for (unsigned int jBin = 0; jBin <= iBin; ++jBin) { const auto diffJ = pUniverse->At(jBin, 0) - pNominal->At(jBin, 0); // Add up the error matrix elements errorMatrixSum.SetElement(iBin, jBin, errorMatrixSum.At(iBin, jBin) + diffI*diffJ); } } } std::cout << ""DEBUG - Valid universes: "" << nValidUniverses << "" / "" << nUniverses << std::endl; // Scale the sums by the number of universes if (nValidUniverses == 0) throw std::logic_error(""CrossSection::GetDisributionParams - Desired quantity was invalid in all universes""); const auto scaleFactor = 1.f / static_cast(nValidUniverses); const auto mean = meanSum * scaleFactor; const auto errorMatrix = errorMatrixSum * scaleFactor; // Get the bias vector const auto pBias = std::make_shared(mean - *pNominal); // Get the covariance matrix auto pCovarianceMatrix = std::make_shared(ubsmear::UBMatrixHelper::GetZeroMatrix(nBins, nBins)); for (unsigned int iBin = 0; iBin < nBins; ++iBin) { for (unsigned int jBin = 0; jBin <= iBin; ++jBin) { // ATTN here we use the fact that V_ij = E_ij - b_i*b_j // - E_ij = error matrix element // - V_ij = covariance matrix element // - b_i = bias vector element // // This is done instead of calculating the covariance directly as this only requires one pass through the universe loop. const auto covariance = errorMatrix.At(iBin, jBin) - pBias->At(iBin, 0)*pBias->At(jBin, 0); pCovarianceMatrix->SetElement(iBin, jBin, covariance); pCovarianceMatrix->SetElement(jBin, iBin, covariance); } } return { pBias, pCovarianceMatrix }; } // ----------------------------------------------------------------------------------------------------------------------------------------- CrossSectionHelper::SystBiasCovariancePair CrossSectionHelper::CrossSection::GetDistributionParamsUnisim(const std::shared_ptr &pVaried, const std::shared_ptr &pCentralValue, const std::shared_ptr &pNominal) const { // Check the input matrices are valid if (!pVaried || !pCentralValue || !pNominal) throw std::invalid_argument(""CrossSection::GetDistributionParamsUnisim - One or more of the inputs are not valid""); // Check ths input matrices have the desired dimensions if (pVaried->GetColumns() != 1 || pCentralValue->GetColumns() != 1 || pNominal->GetColumns() != 1) throw std::invalid_argument(""CrossSection::GetDistributionParamsUnisim - One or more of the inputs are not a column vector""); const auto nBins = pVaried->GetRows(); if (pCentralValue->GetRows() != nBins || pNominal->GetRows() != nBins) throw std::invalid_argument(""CrossSection::GetDistributionParamsUnisim - Input column vectors have different sizes""); // Get the fractional bias of the cross-section away from the central value const auto fracBias = ubsmear::ElementWiseOperation( (*pVaried - *pCentralValue), *pCentralValue, [](const float numerator, const float denominator) { // ATTN here we decide what to do if there's a bin of the central-value that's zero // In this case we don't have any information, so here we set the fractional bias to 0. if (std::abs(denominator) <= std::numeric_limits::epsilon()) return 0.f; return numerator / denominator; } ); // Apply the fractional bias to the nominal cross-section const auto bias = ubsmear::ElementWiseOperation( fracBias, *pNominal, [](const float lhs, const float rhs) { return lhs * rhs; } ); // Return the result (use a zero matrix for the covariance) return { std::make_shared(bias), std::make_shared(ubsmear::UBMatrixHelper::GetZeroMatrix(nBins, nBins)) }; } // ----------------------------------------------------------------------------------------------------------------------------------------- CrossSectionHelper::SystBiasCovariancePair CrossSectionHelper::CrossSection::GetDistributionParamsNormalisation(const std::shared_ptr &pNominal, const float fracUncertainty) const { // Check the input matrix are valid if (!pNominal) throw std::invalid_argument(""CrossSection::GetDistributionParamsNormalisation - The input nominal is not valid""); // Check ths input matrix has the desired dimensions if (pNominal->GetColumns() != 1) throw std::invalid_argument(""CrossSection::GetDistributionParamsNormalisation - The input is not a column vector""); const auto nBins = pNominal->GetRows(); // Scale the nominal value by the fractional uncertainty to get the bias, and use a zero matrix for the covariance return { std::make_shared((*pNominal) * fracUncertainty), std::make_shared(ubsmear::UBMatrixHelper::GetZeroMatrix(nBins, nBins)) }; } // ----------------------------------------------------------------------------------------------------------------------------------------- CrossSectionHelper::SystBiasCovariancePair CrossSectionHelper::CrossSection::GetBNBDataCrossSectionDistributionParams(const std::string &group, const std::string ¶mName, const ScalingData &scalingData) const { std::cout << ""DEBUG - Processing parameter: "" << group << "", "" << paramName << std::endl; // Get the number of universes for this systematic parameter // ATTN this choice of m_signal_true_multisims here is arbitrary, any of the mutlisims maps would do const auto nUniverses = m_signal_true_multisims.at(group).at(paramName).size(); // Get the nominal cross-section const auto pXSecNom = std::make_shared(this->GetBNBDataCrossSection(scalingData)); // Get the distirbution parameters return this->GetDistributionParams([&](const unsigned int &iUni) { // This is the function we call to get the value in each universe return std::make_shared( this->GetBNBDataCrossSectionInUniverse(group, paramName, iUni, scalingData) ); }, nUniverses, pXSecNom); } // ----------------------------------------------------------------------------------------------------------------------------------------- CrossSectionHelper::SystBiasCovariancePair CrossSectionHelper::CrossSection::GetBNBDataCrossSectionDistributionParamsUnisim(const std::string &group, const std::string ¶mName, const std::string &cvName, const ScalingData &scalingData) const { std::cout << ""DEBUG - Processing parameter: "" << group << "", "" << paramName << "" (with central value: "" << cvName << "")"" << std::endl; // Get the cross-section using the unisim sample, in the central value sample and in the nominal universe const auto pXSec = std::make_shared( this->GetBNBDataCrossSectionForUnisim(group, paramName, scalingData) ); const auto pXSecCV = std::make_shared( this->GetBNBDataCrossSectionForUnisim(group, cvName, scalingData) ); const auto pXSecNom = std::make_shared( this->GetBNBDataCrossSection(scalingData) ); // Get the parameters return this->GetDistributionParamsUnisim(pXSec, pXSecCV, pXSecNom); } // ----------------------------------------------------------------------------------------------------------------------------------------- std::shared_ptr CrossSectionHelper::CrossSection::GetSmearingMatrixInUniverse(const std::string &group, const std::string ¶mName, const unsigned int universeIndex) const { return this->GetSmearingMatrix(m_signal_true_multisims.at(group).at(paramName).at(universeIndex), m_signal_selected_recoTrue_multisims.at(group).at(paramName).at(universeIndex)); } // ----------------------------------------------------------------------------------------------------------------------------------------- std::shared_ptr CrossSectionHelper::CrossSection::GetSmearingMatrixForUnisim(const std::string &group, const std::string ¶mName) const { return this->GetSmearingMatrix(m_signal_true_unisims.at(group).at(paramName), m_signal_selected_recoTrue_unisims.at(group).at(paramName)); } // ----------------------------------------------------------------------------------------------------------------------------------------- CrossSectionHelper::SystBiasCovariancePair CrossSectionHelper::CrossSection::GetSmearingMatrixDistributionParams(const std::string &group, const std::string ¶mName) const { std::cout << ""DEBUG - Smearing matrix. Processing parameter: "" << group << "", "" << paramName << std::endl; // Get the number of universes for this systematic parameter // ATTN this choice of m_signal_true_multisims here is arbitrary, any of the mutlisims maps would do const auto nUniverses = m_signal_true_multisims.at(group).at(paramName).size(); // Get the nominal smearing matrix const auto pSmearingNom = CrossSectionHelper::FlattenMatrix(this->GetSmearingMatrixNominal()); if (!pSmearingNom) throw std::logic_error(""CrossSection::GetSmearingMatrixDistributionParams - The nominal smearing matrix can't be calculated""); // Get the distirbution parameters return this->GetDistributionParams([&](const unsigned int &iUni) { // This is the function we call to get the value in each universe return CrossSectionHelper::FlattenMatrix(this->GetSmearingMatrixInUniverse(group, paramName, iUni)); }, nUniverses, pSmearingNom); } // ----------------------------------------------------------------------------------------------------------------------------------------- CrossSectionHelper::SystBiasCovariancePair CrossSectionHelper::CrossSection::GetSmearingMatrixDistributionParamsUnisim(const std::string &group, const std::string ¶mName, const std::string &cvName) const { std::cout << ""DEBUG - Smearing matrix. Processing parameter: "" << group << "", "" << paramName << "" (with central value: "" << cvName << "")"" << std::endl; // Get the smearing matrix using the unisim sample, in the central value sample and in the nominal universe const auto pSmearing = CrossSectionHelper::FlattenMatrix(this->GetSmearingMatrixForUnisim(group, paramName)); const auto pSmearingCV = CrossSectionHelper::FlattenMatrix(this->GetSmearingMatrixForUnisim(group, cvName)); const auto pSmearingNom = CrossSectionHelper::FlattenMatrix(this->GetSmearingMatrixNominal()); // Get the parameters return this->GetDistributionParamsUnisim(pSmearing, pSmearingCV, pSmearingNom); } // ----------------------------------------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------------------------------------- std::shared_ptr CrossSectionHelper::GetTH1F(const std::vector &binEdges) { return std::make_shared((""xSecHist_"" + std::to_string(m_histCount++)).c_str(), """", binEdges.size() - 1, binEdges.data()); } // ----------------------------------------------------------------------------------------------------------------------------------------- std::shared_ptr CrossSectionHelper::GetTH2F(const std::vector &binEdges) { return std::make_shared((""xSecHist_"" + std::to_string(m_histCount++)).c_str(), """", binEdges.size() - 1, binEdges.data(), binEdges.size() - 1, binEdges.data()); } // ----------------------------------------------------------------------------------------------------------------------------------------- CrossSectionHelper::SystTH1FMap CrossSectionHelper::GetSystTH1FMap(const std::vector &binEdges, const SystDimensionsMap &dimensions) { SystTH1FMap map; for (const auto &[paramName, nUniverses] : dimensions) { std::vector< std::shared_ptr > universes; for (unsigned int iUni = 0; iUni < nUniverses; ++iUni) { universes.push_back(CrossSectionHelper::GetTH1F(binEdges)); } map.emplace(paramName, universes); } return map; } // ----------------------------------------------------------------------------------------------------------------------------------------- CrossSectionHelper::SystUnisimTH1FMap CrossSectionHelper::GetSystUnisimTH1FMap(const std::vector &binEdges, const SystUnisimDimensionsMap &dimensions) { SystUnisimTH1FMap map; // Setup a vector to keep track of the used central-values sample names std::vector allCVNames; for (const auto &[paramName, cvName] : dimensions) { // Include all parameter names map.emplace(paramName, CrossSectionHelper::GetTH1F(binEdges)); // If we haven't seen this central value sample name before, then add it too! if (std::find(allCVNames.begin(), allCVNames.end(), cvName) == allCVNames.end()) { if (map.find(cvName) != map.end()) throw std::invalid_argument(""CrossSectionHelper::GetSystUnisimTH1FMap - Name \\"""" + cvName + ""\\"" is describes a parameter and a central-value sample""); map.emplace(cvName, CrossSectionHelper::GetTH1F(binEdges)); allCVNames.push_back(cvName); } } return map; } // ----------------------------------------------------------------------------------------------------------------------------------------- CrossSectionHelper::SystTH2FMap CrossSectionHelper::GetSystTH2FMap(const std::vector &binEdges, const SystDimensionsMap &dimensions) { SystTH2FMap map; for (const auto &[paramName, nUniverses] : dimensions) { std::vector< std::shared_ptr > universes; for (unsigned int iUni = 0; iUni < nUniverses; ++iUni) { universes.push_back(CrossSectionHelper::GetTH2F(binEdges)); } map.emplace(paramName, universes); } return map; } // ----------------------------------------------------------------------------------------------------------------------------------------- CrossSectionHelper::SystUnisimTH2FMap CrossSectionHelper::GetSystUnisimTH2FMap(const std::vector &binEdges, const SystUnisimDimensionsMap &dimensions) { SystUnisimTH2FMap map; // Setup a vector to keep track of the used central-values sample names std::vector allCVNames; for (const auto &[paramName, cvName] : dimensions) { // Include all parameter names map.emplace(paramName, CrossSectionHelper::GetTH2F(binEdges)); // If we haven't seen this central value sample name before, then add it too! if (std::find(allCVNames.begin(), allCVNames.end(), cvName) == allCVNames.end()) { if (map.find(cvName) != map.end()) throw std::invalid_argument(""CrossSectionHelper::GetSystUnisimTH2FMap - Name \\"""" + cvName + ""\\"" is describes a parameter and a central-value sample""); map.emplace(cvName, CrossSectionHelper::GetTH2F(binEdges)); allCVNames.push_back(cvName); } } return map; } // ----------------------------------------------------------------------------------------------------------------------------------------- CrossSectionHelper::SystFloatMap CrossSectionHelper::GetUnitWeightsMap(const SystDimensionsMap &dimensions) { // Make a new map for the output SystFloatMap map; // Loop over all parameters in the input dimensions map for (const auto &[paramName, nUniverses] : dimensions) { // Add a weight of 1.f for each universe map.emplace(paramName, std::vector(nUniverses, 1.f)); } return map; } // ----------------------------------------------------------------------------------------------------------------------------------------- CrossSectionHelper::SystFloatMap CrossSectionHelper::ScaleWeightsMap(const SystFloatMap &weightsMap, const float &divisor) { // Check the input divisor isn't zero if (std::abs(divisor) <= std::numeric_limits::epsilon()) throw std::invalid_argument(""CrossSectionHelper::ScaleWeightsMap - The input divisor is zero""); auto map = weightsMap; for (auto &[paramName, weights] : map) { for (auto &weight : weights) { weight /= divisor; } } return map; } // ----------------------------------------------------------------------------------------------------------------------------------------- CrossSectionHelper::SystFloatMap CrossSectionHelper::GetWeightsMap(const Event::Truth &truth, const SystDimensionsMap &dimensions) { if (!truth.systParamNames.IsSet() || !truth.systParamFirstValueIndex.IsSet() || !truth.systParamValues.IsSet()) throw std::invalid_argument(""CrossSectionHelper::GetWeightsMap - Systematic parameters are not set in the input truth information""); const auto &systParamNames = truth.systParamNames(); const auto &systParamFirstValueIndex = truth.systParamFirstValueIndex(); const auto &systParamValues = truth.systParamValues(); // Get the total number of parameters available const auto nParameters = systParamNames.size(); // Make a new map for the output SystFloatMap map; // Loop over all parameters in the input dimensions map for (const auto &[paramName, nUniverses] : dimensions) { // Find the desired name const auto iter = std::find(systParamNames.begin(), systParamNames.end(), paramName); if (iter == systParamNames.end()) throw std::invalid_argument(""CrossSectionHelper::GetWeightsMap - Unknown parameter: "" + paramName); // Get the index of the requested parameter const unsigned int index = std::distance(systParamNames.begin(), iter); // Get the first and last value in the weights vector const unsigned int firstValueIndex = systParamFirstValueIndex.at(index); const unsigned int lastValueIndex = ((index == nParameters - 1u) ? systParamValues.size() : systParamFirstValueIndex.at(index + 1u)); // Pick out the weights corresponding the the desired parameter const std::vector weights(std::next(systParamValues.begin(), firstValueIndex), std::next(systParamValues.begin(), lastValueIndex)); // Check that we have the right number of weights if (weights.size() != nUniverses) throw std::invalid_argument(""CrossSectionHelper::GetWeightsMap - Number of weights for parameter "" + paramName + "" doesn't match the input dimensions""); // Setup the output map entry auto &outputWeights = map[paramName]; // Fill the output weights for (const auto &weight : weights) { // ATTN sometimes we have non-physical weights in the input. Here we decide what to do with them! // If the weight is non-negative and non-infinite then it's okay! if (weight >= 0.f && std::abs(std::abs(weight) - std::numeric_limits::max()) > std::numeric_limits::epsilon() && std::isfinite(weight)) { outputWeights.push_back(weight); continue; } // Force negative weights to be zero and infinite weights to be unity outputWeights.push_back((weight < 0.f) ? 0.f : 1.f); } } return map; } // ----------------------------------------------------------------------------------------------------------------------------------------- CrossSectionHelper::SystFloatMap CrossSectionHelper::GetWeightsMap(const Event::Truth &truth, const SystDimensionsMap &dimensions, const SystMutuallyExclusiveDimensionsMap &mutuallyExclusiveDimensions) { // Make a new map for the output SystFloatMap map; // Make new dimensions map to populate with the parameters that are available in the input truth information directly SystDimensionsMap availableParamDimensions; const auto &systParamNames = truth.systParamNames(); // Find which parameters (if any) are built from mutually exclusive parameters for (const auto &[paramName, nUniverses] : dimensions) { // Check if this parameter name is available in the input truth information, if so just skip it for later if (std::find(systParamNames.begin(), systParamNames.end(), paramName) != systParamNames.end()) { availableParamDimensions.emplace(paramName, nUniverses); continue; } // Insist that parameters not available in the input truth information are listed in the mutually exlusive dimensions if (mutuallyExclusiveDimensions.find(paramName) == mutuallyExclusiveDimensions.end()) throw std::invalid_argument(""CrossSectionHelper::GetWeightsMap - Parameter \\"""" + paramName + ""\\"" isn't listed in the input truth information or in the supplied mutually exclusive parameter names""); // We have a mutually exclusive parameter, so get it's weights const auto &[parameters, nUniversesCheck] = mutuallyExclusiveDimensions.at(paramName); if (nUniverses != nUniversesCheck) throw std::invalid_argument(""CrossSectionHelper::GetWeightsMap - Inconsistent number of universes specified for parameter: \\"""" + paramName + ""\\""""); const auto weights = CrossSectionHelper::GetMutuallyExclusiveWeights(truth, parameters, nUniverses); // Add the result to the output map map.emplace(paramName, weights); } // Now get the weights from the rest of the parameters auto availableParamWeights = CrossSectionHelper::GetWeightsMap(truth, availableParamDimensions); // Combine this together and return it! map.insert(availableParamWeights.begin(), availableParamWeights.end()); return map; } // ----------------------------------------------------------------------------------------------------------------------------------------- std::vector CrossSectionHelper::GetMutuallyExclusiveWeights(const Event::Truth &truth, const std::vector ¶meters, const unsigned int nUniverses) { // Build a dimensions map using the same number of universes for each parameter SystDimensionsMap dimensions; for (const auto ¶mName : parameters) dimensions.emplace(paramName, nUniverses); // Get the weights map for these parameters individually const auto weightsMap = CrossSectionHelper::GetWeightsMap(truth, dimensions); // Extract the mutually exclusive weights std::vector weights; for (unsigned int iUni = 0; iUni < nUniverses; ++iUni) { // Find the parameter name for which the weight is not exactly one float weight = 1.f; bool foundNonUnitWeight = false; for (const auto ¶mName : parameters) { const auto universeWeight = weightsMap.at(paramName).at(iUni); if (std::abs(universeWeight - 1.f) > std::numeric_limits::epsilon()) { // This weight is something other than one! // If we find more than one weight that's not exactly one - then the parameters aren't mutually exclusive! if (foundNonUnitWeight) throw std::logic_error(""CrossSectionHelper::GetMutuallyExclusiveWeights - Input weights aren't mutually exclusive""); // Store this weight weight = universeWeight; foundNonUnitWeight = true; } } // ATTN it's still posible that all universe weights are exactly one. This is okay - just use 1.f as the weight weights.push_back(weight); } return weights; } // ----------------------------------------------------------------------------------------------------------------------------------------- std::vector CrossSectionHelper::GenerateBootstrapWeights(const unsigned int nUniverses) { std::poisson_distribution poisson(1.f); std::vector weights; for (unsigned int iUni = 0; iUni < nUniverses; ++iUni) { weights.push_back(static_cast(poisson(m_generator))); } return weights; } // ----------------------------------------------------------------------------------------------------------------------------------------- void CrossSectionHelper::FillSystTH1FMap(const float value, const float nominalWeight, const SystFloatMap &weights, SystTH1FMap &map) { // Validate the dimensions of the input SystMaps CrossSectionHelper::ValidateSystMap(weights, CrossSectionHelper::GetSystMapDimensions(map)); // Fill the histograms in each systematic universe for (const auto &[paramName, universeWeights] : weights) { const auto nUniverses = universeWeights.size(); auto &histVector = map.at(paramName); // ATTN this should never happen because of the above ValidateSystMap check, but including here for sanity if (histVector.size() != nUniverses) throw std::logic_error(""CrossSectionHelper::FillSystTH1FMap - Input weights map and SystTH1FMap have different dimensions""); for (unsigned int iUni = 0; iUni < nUniverses; ++iUni) { // ATTN we use the product of the nominal weight and the universe weight const auto weight = nominalWeight * universeWeights.at(iUni); histVector.at(iUni)->Fill(value, weight); } } } // ----------------------------------------------------------------------------------------------------------------------------------------- void CrossSectionHelper::FillSystTH2FMap(const float xValue, const float yValue, const float nominalWeight, const SystFloatMap &weights, SystTH2FMap &map) { // Validate the dimensions of the input SystMaps CrossSectionHelper::ValidateSystMap(weights, CrossSectionHelper::GetSystMapDimensions(map)); // Fill the histograms in each systematic universe for (const auto &[paramName, universeWeights] : weights) { const auto nUniverses = universeWeights.size(); auto &histVector = map.at(paramName); // ATTN this should never happen because of the above ValidateSystMap check, but including here for sanity if (histVector.size() != nUniverses) throw std::logic_error(""CrossSectionHelper::FillSystTH1FMap - Input weights map and SystTH1FMap have different dimensions""); for (unsigned int iUni = 0; iUni < nUniverses; ++iUni) { // ATTN we use the product of the nominal weight and the universe weight const auto weight = nominalWeight * universeWeights.at(iUni); histVector.at(iUni)->Fill(xValue, yValue, weight); } } } // ----------------------------------------------------------------------------------------------------------------------------------------- ubsmear::UBMatrix CrossSectionHelper::GetMatrixFromHist(const std::shared_ptr &pHist) { std::vector elements; const unsigned int nBins = pHist->GetNbinsX(); for (unsigned int iBin = 1; iBin <= nBins; ++iBin) { elements.push_back(pHist->GetBinContent(iBin)); } return ubsmear::UBMatrix(elements, nBins, 1); } // ----------------------------------------------------------------------------------------------------------------------------------------- ubsmear::UBMatrix CrossSectionHelper::GetMatrixFromHist(const std::shared_ptr &pHist) { std::vector< std::vector > elements; const unsigned int nBinsX = pHist->GetNbinsX(); const unsigned int nBinsY = pHist->GetNbinsY(); for (unsigned int iBinX = 1; iBinX <= nBinsX; ++iBinX) { // Make a new row elements.emplace_back(); auto &row = elements.back(); for (unsigned int iBinY = 1; iBinY <= nBinsY; ++iBinY) { row.push_back(pHist->GetBinContent(iBinX, iBinY)); } } return ubsmear::UBMatrix(elements); } // ----------------------------------------------------------------------------------------------------------------------------------------- std::shared_ptr CrossSectionHelper::FlattenMatrix(const std::shared_ptr &pMatrix) { if (!pMatrix) throw std::invalid_argument(""CrossSectionHelper::FlattenMatrix - Input matrix pointer is null""); return std::make_shared(ubsmear::UBSmearingHelper::Flatten(*pMatrix)); } // ----------------------------------------------------------------------------------------------------------------------------------------- std::tuple< std::vector, bool, bool > CrossSectionHelper::GetExtendedBinEdges(const float min, const float max, const std::vector &binEdges) { // Ensure that we have at least one input bin if (binEdges.size() < 2) throw std::invalid_argument(""CrossSectionHelper::GetExtendedBinEdges - Fewer than two input bin edges were supplied""); // Ensure that the input bin edges are sorted if (!std::is_sorted(binEdges.begin(), binEdges.end())) throw std::invalid_argument(""CrossSectionHelper::GetExtendedBinEdges - Input bin edges are not sorted into ascending order""); // Get the first and last bin edges supplied const auto firstEdge = binEdges.front(); const auto lastEdge = binEdges.back(); // Check if the first/last edge is already at the min/max const auto isFirstEdgeAtMin = (std::abs(firstEdge - min) <= std::numeric_limits::epsilon()); const auto isLastEdgeAtMax = (std::abs(lastEdge - max) <= std::numeric_limits::epsilon()); // If the first/last edge isn't at min/max, then make sure that it's not below/above if (!isFirstEdgeAtMin && firstEdge < min) throw std::invalid_argument(""CrossSectionHelper::GetExtendedBinEdges - Lowest input bin edge is smaller than the supplied minimum value""); if (!isLastEdgeAtMax && lastEdge > max) throw std::invalid_argument(""CrossSectionHelper::GetExtendedBinEdges - Uppermost input bin edge is larget than the supplied maximum value""); // Determine if we need to extend to an extra underflow/overflow bin edge const auto hasUnderflow = !isFirstEdgeAtMin; const auto hasOverflow = !isLastEdgeAtMax; // Setup the output bin edges std::vector extendedBinEdges; // Add the underflow bin if required if (hasUnderflow) extendedBinEdges.push_back(min); // Add the supplied bins extendedBinEdges.insert(extendedBinEdges.end(), binEdges.begin(), binEdges.end()); // Add the overflow bin if required if (hasOverflow) extendedBinEdges.push_back(max); return {extendedBinEdges, hasUnderflow, hasOverflow}; } // ----------------------------------------------------------------------------------------------------------------------------------------- std::vector CrossSectionHelper::GetNominalFluxHistNames(const std::vector &nuPdgsSignal, const std::map &nuPdgToHistName, const std::string &nomHistPattern) { std::vector histNames; for (const auto &nuPdg : nuPdgsSignal) { const auto iter = nuPdgToHistName.find(nuPdg); if (iter == nuPdgToHistName.end()) throw std::logic_error(""CrossSectionHelper::GetNominalFluxHistNames - Can't find name corresponding to PDG code "" + std::to_string(nuPdg)); const auto &nuName = iter->second; const auto histName = std::regex_replace(nomHistPattern, std::regex(""NEUTRINO""), nuName); histNames.push_back(histName); } return histNames; } // ----------------------------------------------------------------------------------------------------------------------------------------- std::pair< std::vector, std::vector > CrossSectionHelper::ReadNominalFlux(const std::string &fileName, const std::vector &histNames, const float pot) { if (histNames.empty()) throw std::invalid_argument(""CrossSectionHelper::ReadNominalFlux - No histogram names supplied""); // Open the flux file for reading TFile *pFluxFile = new TFile(fileName.c_str(), ""READ""); if (!pFluxFile->IsOpen()) throw std::invalid_argument(""CrossSectionHelper::ReadNominalFlux - Can't open flux file: "" + fileName); // Get the scaling factor to go from the event rate in the flux file, to the flux itself // Here we get the flux in neutrinos/POT/bin/cm2 by scaling the event rate (in the samples) down by POT and the cross-sectional area of the active volume // Here we also scale up the fluxes by 1e10 for the sake of comparison just so we are working with reasonable numbers const float unitsScaling = 1e10; const auto fluxScaleFactor = unitsScaling / (pot * (GeometryHelper::highX - GeometryHelper::lowX) * (GeometryHelper::highY - GeometryHelper::lowY)); bool isFirstHist = true; std::vector fluxBinEdges, fluxBinValuesNominal; for (const auto &histName : histNames) { // Get the nominal flux const auto pFluxHist = static_cast(pFluxFile->Get(histName.c_str())); if (!pFluxHist) throw std::logic_error(""CrossSectionHelper::ReadNominalFlux - Input file doesn't contain histogram with name: "" + histName); // Get the number of bins const unsigned int nFluxBins = pFluxHist->GetNbinsX(); if (!isFirstHist && nFluxBins != (fluxBinEdges.size() - 1)) throw std::logic_error(""CrossSectionHelper::ReadNominalFlux - Supplied flux histograms have an inconsistent number of bins""); // Get the flux bin edges and content for (unsigned int iBin = 1; iBin <= nFluxBins; ++iBin) { const auto flux = pFluxHist->GetBinContent(iBin) * fluxScaleFactor; const float lowEdge = pFluxHist->GetBinLowEdge(iBin); const float binWidth = pFluxHist->GetBinWidth(iBin); if (isFirstHist) { fluxBinEdges.push_back(lowEdge); // Add the upper edge of the last bin if (iBin == nFluxBins) { fluxBinEdges.push_back(lowEdge + binWidth); } fluxBinValuesNominal.push_back(flux); } else { // If this isn't the first flux histogram, then add to the existing flux fluxBinValuesNominal.at(iBin - 1) += flux; // Check that the bin edges are consistent if (std::abs(fluxBinEdges.at(iBin - 1) - lowEdge) > std::numeric_limits::epsilon()) throw std::logic_error(""CrossSectionHelper::ReadNominalFlux - Supplied flux histograms have an inconsistent binning (low edge)""); } } isFirstHist = false; } return {fluxBinEdges, fluxBinValuesNominal}; } // ----------------------------------------------------------------------------------------------------------------------------------------- ubsmear::UBMatrix CrossSectionHelper::GetErrorMatrix(const ubsmear::UBMatrix &biasVector, const ubsmear::UBMatrix &covarianceMatrix) { // Make sure the dimensions of the input are valid if (biasVector.GetColumns() != 1) throw std::invalid_argument(""CrossSectionHelper::GetErrorMatrix - Input bias vector isn't a column vector""); if (!ubsmear::UBMatrixHelper::IsSquare(covarianceMatrix)) throw std::invalid_argument(""CrossSectionHelper::GetErrorMatrix - Input covariance matrix isn't square""); const auto nBins = covarianceMatrix.GetRows(); if (biasVector.GetRows() != nBins) throw std::invalid_argument(""CrossSectionHelper::GetErrorMatrix - Input bias vector and covariance matrix have incompatible dimensions""); // Make a new matrix for the output auto errorMatrix = ubsmear::UBMatrixHelper::GetZeroMatrix(nBins, nBins); for (unsigned int iRow = 0; iRow < nBins; ++iRow) { for (unsigned int iCol = 0; iCol < nBins; ++iCol) { errorMatrix.SetElement(iRow, iCol, (biasVector.At(iRow, 0) * biasVector.At(iCol, 0)) + covarianceMatrix.At(iRow, iCol)); } } return errorMatrix; } } // namespace ubcc1pi ",16279,True,3421.2994173787715,median "--- title: ""FreeBSD/pc98 5.3-RELEASE Installation Instructions"" sidenav: download --- ++++

The FreeBSD Project

Copyright © 2000, 2001, 2002, 2003, 2004 The FreeBSD Documentation Project


This article gives some brief instructions on installing FreeBSD/pc98 5.3-RELEASE, with particular emphasis given to obtaining a FreeBSD distribution. Some notes on troubleshooting and frequently-asked questions are also given.


1 Installing FreeBSD

This section documents the process of installing a new distribution of FreeBSD. These instructions pay particular emphasis to the process of obtaining the FreeBSD 5.3-RELEASE distribution and to beginning the installation procedure. The ``Installing FreeBSD'' chapter of the FreeBSD Handbook provides more in-depth information about the installation program itself, including a guided walkthrough with screenshots.

If you are upgrading from a previous release of FreeBSD, please see Section 3 for instructions on upgrading.


1.1 Getting Started

Probably the most important pre-installation step that can be taken is that of reading the various instruction documents provided with FreeBSD. A roadmap of documents pertaining to this release of FreeBSD can be found in README.TXT, which can usually be found in the same location as this file; most of these documents, such as the release notes and the hardware compatibility list, are also accessible in the Documentation menu of the installer.

Note that on-line versions of the FreeBSD FAQ and Handbook are also available from the FreeBSD Project Web site, if you have an Internet connection.

This collection of documents may seem daunting, but the time spent reading them will likely be saved many times over. Being familiar with what resources are available can also be helpful in the event of problems during installation.

The best laid plans sometimes go awry, so if you run into trouble take a look at Section 4, which contains valuable troubleshooting information. You should also read an updated copy of ERRATA.TXT before installing, since this will alert you to any problems which have reported in the interim for your particular release.

Important: While FreeBSD does its best to safeguard against accidental loss of data, it's still more than possible to wipe out your entire disk with this installation if you make a mistake. Please do not proceed to the final FreeBSD installation menu unless you've adequately backed up any important data first.


1.2 Hardware Requirements

FreeBSD for the NEC PC-98x1 requires a 486 or better processor to install and run (although FreeBSD can run on 386 processors with a custom kernel) and at least 8 megs of RAM to install and 7 megs to run. You will need at least 150MB of free hard drive space for the most minimal installation. See below for ways of shrinking existing DOS partitions in order to install FreeBSD.

If you are not familiar with configuring hardware for FreeBSD, you should be sure to read the HARDWARE.TXT file; it contains important information on what hardware is supported by FreeBSD.


1.3 Floppy Disk Image Instructions

Depending on how you choose to install FreeBSD, you may need to create a set of floppy disks (usually three) to begin the installation process. This section briefly describes how to create these disks, either from a CDROM installation or from the Internet. Note that in the common case of installing FreeBSD from CDROM, on a machine that supports bootable CDROMs, the steps outlined in this section will not be needed and can be skipped.

For a normal CDROM or network installation, all you need to copy onto actual floppies from the floppies/ directory are the boot.flp and kernX.flp images (for 1.44MB floppies) or boot-small.flp and kern-small.flp images (for 1.2MB floppies).

Getting these images over the network is easy. Simply fetch the release/floppies/boot.flp, and all of the release/floppies/kernX.flp files from ftp://ftp.FreeBSD.org/ or one of the many mirrors listed at FTP Sites section of the Handbook, or on the http://mirrorlist.FreeBSD.org/ Web pages.

Get approximately three blank, freshly formatted floppies and image copy boot.flp onto one and the kernX.flp files onto the others. These images are not DOS files. You cannot simply copy them to a DOS or UFS floppy as regular files, you need to ``image'' copy them to the floppy with rawrite.exe under DOS (see the tools directory on your CDROM or FreeBSD FTP mirror) or the dd(1) command in UNIX.

For example, to create the kernel floppy image from DOS, you'd do something like this:

A> rawrite

Assuming that you'd copied rawrite.exe and boot.flp into a directory somewhere. You would do the same for the kernX.flp files, of course.

If you're creating the boot floppy from a UNIX machine, you may find that:

# dd if=floppies/boot.flp of=/dev/rfd0.1440

or

# dd if=floppies/boot-small.flp of=/dev/rfd0.1200

work well, depending on your hardware and operating system environment (different versions of UNIX have different names for the floppy drive).


1.4 Installing FreeBSD from CDROM or the Internet

The easiest type of installation is from CDROM. If you have a supported CDROM drive and a FreeBSD installation CDROM, there is a next way of starting the installation from it:

  • Build a set of FreeBSD boot floppies from the floppies/ directory in every FreeBSD distribution. Read Section 1.3 for more information on creating the bootable floppies under different operating systems. Then you simply boot from the first floppy and you should soon be in the FreeBSD installation.



If you don't have a CDROM and would like to simply install over the net using PPP, SLIP or a dedicated connection, you should start the installation by building a set of FreeBSD boot floppies from the files floppies/boot.flp and floppies/kernX.flp using the instructions found in Section 1.3. Restart your computer using the boot.flp disk; when prompted, insert the other disks as required. Then, please go to Section 1.5.5 for additional tips on installing via FTP or NFS.


1.5 Detail on various installation types

Once you've gotten yourself to the initial installation screen somehow, you should be able to follow the various menu prompts and go from there. If you've never used the FreeBSD installation before, you are also encouraged to read some of the documentation in the Documentation submenu as well as the general ``Usage'' instructions on the first menu.

Note: If you get stuck at a screen, press the F1 key for online documentation relevant to that specific section.

If you've never installed FreeBSD before, or even if you have, the ``Standard'' installation mode is the most recommended since it makes sure that you'll visit all the various important checklist items along the way. If you're much more comfortable with the FreeBSD installation process and know exactly what you want to do, use the ``Express'' or ``Custom'' installation options. If you're upgrading an existing system, use the ``Upgrade'' option.

The FreeBSD installer supports the direct use of floppy, DOS, tape, CDROM, FTP, NFS and UFS partitions as installation media; further tips on installing from each type of media are listed below.


1.5.1 Installing from a Network CDROM

If you simply wish to install from a local CDROM drive then see Section 1.4. If you don't have a CDROM drive on your system and wish to use a FreeBSD distribution CD in the CDROM drive of another system to which you have network connectivity, there are also several ways of going about it:

  • If you would be able to FTP install FreeBSD directly from the CDROM drive in some FreeBSD machine, it's quite easy: You ensure an FTP server is running and then simply add the following line to the password file (using the vipw(8) command):

    ftp:*:99:99::0:0:FTP:/cdrom:/sbin/nologin
    

    On the machine on which you are running the install, go to the Options menu and set Release Name to any. You may then choose a Media type of FTP and type in ftp://machine after picking ``URL'' in the ftp sites menu.

    Warning: This may allow anyone on the local network (or Internet) to make ``anonymous FTP'' connections to this machine, which may not be desirable.

  • If you would rather use NFS to export the CDROM directly to the machine(s) you'll be installing from, you need to first add an entry to the /etc/exports file (on the machine with the CDROM drive). The example below allows the machine ziggy.foo.com to mount the CDROM directly via NFS during installation:

    /cdrom          -ro             ziggy.foo.com
    

    The machine with the CDROM must also be configured as an NFS server, of course, and if you're not sure how to do that then an NFS installation is probably not the best choice for you unless you're willing to read up on rc.conf(5) and configure things appropriately. Assuming that this part goes smoothly, you should be able to enter: cdrom-host:/cdrom as the path for an NFS installation when the target machine is installed, e.g. wiggy:/cdrom.


1.5.2 Installing from Floppies

If you must install from floppy disks, either due to unsupported hardware or just because you enjoy doing things the hard way, you must first prepare some floppies for the install.

First, make your boot floppies as described in Section 1.3.

Second, peruse Section 2 and pay special attention to the ``Distribution Format'' section since it describes which files you're going to need to put onto floppy and which you can safely skip.

Next you will need, at minimum, as many 1.44MB floppies as it takes to hold all files in the bin (binary distribution) directory. If you're preparing these floppies under DOS, then these floppies must be formatted using the MS-DOS FORMAT command. If you're using Windows, use the Windows File Manager format command.

Important: Frequently, floppy disks come ``factory preformatted''. While convenient, many problems reported by users in the past have resulted from the use of improperly formatted media. Re-format them yourself, just to make sure.

If you're creating the floppies from another FreeBSD machine, a format is still not a bad idea though you don't need to put a DOS filesystem on each floppy. You can use the disklabel(8) and newfs(8) commands to put a UFS filesystem on a floppy, as the following sequence of commands illustrates:

# fdformat -f 1440 fd0
# disklabel -w fd0 floppy3
# newfs -i 65536 /dev/fd0

After you've formatted the floppies for DOS or UFS, you'll need to copy the files onto them. The distribution files are sized so that a floppy disk will hold a single file. Each distribution should go into its own subdirectory on the floppy, e.g.: a:\\bin\\bin.inf, a:\\bin\\bin.aa, a:\\bin\\bin.ab, ...

Important: The bin.inf file also needs to go on the first floppy of the bin set since it is read by the installation program in order to figure out how many additional pieces to look for when fetching and concatenating the distribution. When putting distributions onto floppies, the distname.inf file must occupy the first floppy of each distribution set.

Once you come to the Media screen of the install, select ``Floppy'' and you'll be prompted for the rest.


1.5.3 Installing from a DOS partition

To prepare for installation from an MS-DOS partition you should simply copy the files from the distribution into a directory called FREEBSD on the Primary DOS partition (A:). For example, to do a minimal installation of FreeBSD from DOS using files copied from the CDROM, you might do something like this:

A:\\> MD A:\\FREEBSD
A:\\> XCOPY /S E:\\BASE A:\\FREEBSD\\BASE

Assuming that E: was where your CD was mounted.

For as many distributions as you wish to install from DOS (and you have free space for), install each one in a directory under A:\\FREEBSD - the BIN dist is only the minimal requirement.

Once you've copied the directories, you can simply launch the installation from floppies as normal and select ``DOS'' as your media type when the time comes.


1.5.4 Installing from QIC/SCSI Tape

When installing from tape, the installation program expects the files to be simply tar'ed onto it, so after fetching all of the files for the distributions you're interested in, simply use tar(1) to get them onto the tape with a command something like this:

# cd /where/you/have/your/dists
# tar cvf /dev/sa0 dist1 .. dist2

When you go to do the installation, you should also make sure that you leave enough room in some temporary directory (which you'll be allowed to choose) to accommodate the full contents of the tape you've created. Due to the non-random access nature of tapes, this method of installation requires quite a bit of temporary storage. You should expect to require as much temporary storage as you have stuff written on tape.

Note: When going to do the installation, the tape must be in the drive before booting from the boot floppies. The installation ``probe'' may otherwise fail to find it.

Now create a boot floppy as described in Section 1.3 and proceed with the installation.


1.5.5 Installing over a Network using FTP or NFS

After making the boot floppies as described in the first section, you can load the rest of the installation over a network using one of 3 types of connections: serial port, parallel port, or Ethernet.


1.5.5.1 Serial Port

SLIP support is rather primitive, and is limited primarily to hard-wired links, such as a serial cable running between two computers. The link must be hard-wired because the SLIP installation doesn't currently offer a dialing capability. If you need to dial out with a modem or otherwise dialog with the link before connecting to it, then the PPP utility should be used instead.

If you're using PPP, make sure that you have your Internet Service Provider's IP address and DNS information handy as you'll need to know it fairly early in the installation process. You may also need to know your own IP address, though PPP supports dynamic address negotiation and may be able to pick up this information directly from your ISP if they support it.

You will also need to know how to use the various ``AT commands'' for dialing out with your particular brand of modem as the PPP dialer provides only a very simple terminal emulator.


1.5.5.2 Parallel Port

If a hard-wired connection to another FreeBSD or Linux machine is available, you might also consider installing over a ``laplink'' style parallel port cable. The data rate over the parallel port is much higher than what is typically possible over a serial line (up to 50k/sec), thus resulting in a quicker installation. It's not typically necessary to use ``real'' IP addresses when using a point-to-point parallel cable in this way and you can generally just use RFC 1918 style addresses for the ends of the link (e.g. 10.0.0.1, 10.0.0.2, etc).

Important: If you use a Linux machine rather than a FreeBSD machine as your PLIP peer, you will also have to specify link0 in the TCP/IP setup screen's ``extra options for ifconfig'' field in order to be compatible with Linux's slightly different PLIP protocol.


1.5.5.3 Ethernet

FreeBSD supports most common Ethernet cards; a table of supported cards is provided as part of the FreeBSD Hardware Notes (see HARDWARE.TXT in the Documentation menu on the boot floppy or the top level directory of the CDROM). If you are using one of the supported PCMCIA Ethernet cards, also be sure that it's plugged in before the laptop is powered on. FreeBSD does not, unfortunately, currently support ``hot insertion'' of PCMCIA cards during installation.

You will also need to know your IP address on the network, the netmask value for your subnet and the name of your machine. Your system administrator can tell you which values are appropriate to your particular network setup. If you will be referring to other hosts by name rather than IP address, you'll also need a name server and possibly the address of a gateway (if you're using PPP, it's your provider's IP address) to use in talking to it. If you want to install by FTP via an HTTP proxy (see below), you will also need the proxy's address.

If you do not know the answers to these questions then you should really probably talk to your system administrator first before trying this type of installation. Using a randomly chosen IP address or netmask on a live network is almost guaranteed not to work, and will probably result in a lecture from said system administrator.

Once you have a network connection of some sort working, the installation can continue over NFS or FTP.


1.5.5.4 NFS installation tips

NFS installation is fairly straight-forward: Simply copy the FreeBSD distribution files you want onto a server somewhere and then point the NFS media selection at it.

If this server supports only ``privileged port'' access (this is generally the default for Sun and Linux workstations), you may need to set this option in the Options menu before installation can proceed.

If you have a poor quality Ethernet card which suffers from very slow transfer rates, you may also wish to toggle the appropriate Options flag.

In order for NFS installation to work, the server must also support ``subdir mounts'', e.g. if your FreeBSD distribution directory lives on wiggy:/usr/archive/stuff/FreeBSD, then wiggy will have to allow the direct mounting of /usr/archive/stuff/FreeBSD, not just /usr or /usr/archive/stuff.

In FreeBSD's /etc/exports file this is controlled by the -alldirs option. Other NFS servers may have different conventions. If you are getting Permission Denied messages from the server then it's likely that you don't have this properly enabled.


1.5.5.5 FTP Installation tips

FTP installation may be done from any mirror site containing a reasonably up-to-date version of FreeBSD. A full menu of reasonable choices for almost any location in the world is provided in the FTP site menu during installation.

If you are installing from some other FTP site not listed in this menu, or you are having troubles getting your name server configured properly, you can also specify your own URL by selecting the ``URL'' choice in that menu. A URL can contain a hostname or an IP address, so something like the following would work in the absence of a name server:

ftp://216.66.64.162/pub/FreeBSD/releases/pc98/4.2-RELEASE

There are three FTP installation modes you can use:

  • FTP: This method uses the standard ``Active'' mode for transfers, in which the server initiates a connection to the client. This will not work through most firewalls but will often work best with older FTP servers that do not support passive mode. If your connection hangs with passive mode, try this one.

  • FTP Passive: This sets the FTP ""Passive"" mode which prevents the server from opening connections to the client. This option is best for users to pass through firewalls that do not allow incoming connections on random port addresses.

  • FTP via an HTTP proxy: This option instructs FreeBSD to use HTTP to connect to a proxy for all FTP operations. The proxy will translate the requests and send them to the FTP server. This allows the user to pass through firewalls that do not allow FTP at all, but offer an HTTP proxy. You must specify the hostname of the proxy in addition to the FTP server.

    In the rare case that you have an FTP proxy that does not go through HTTP, you can specify the URL as something like:

    ftp://foo.bar.com:port/pub/FreeBSD
    

    In the URL above, port is the port number of the proxy FTP server.




2 Distribution Format

A typical FreeBSD distribution directory looks something like this (exact details may vary depending on version, architecture, and other factors):

ERRATA.HTM      README.TXT      compat1x        dict            kernel
ERRATA.TXT      RELNOTES.HTM    compat20        doc             manpages
HARDWARE.HTM    RELNOTES.TXT    compat21        docbook.css     packages
HARDWARE.TXT    base            compat22        filename.txt    ports
INSTALL.HTM     boot            compat3x        floppies        proflibs
INSTALL.TXT     catpages        compat4x        games           src
README.HTM      cdrom.inf       crypto          info            tools

If you want to do a CDROM, FTP or NFS installation from this distribution directory, all you need to do is make the 1.44MB boot floppies from the floppies directory (see Section 1.3 for instructions on how to do this), boot them and follow the instructions. The rest of the data needed during the installation will be obtained automatically based on your selections. If you've never installed FreeBSD before, you also want to read the entirety of this document (the installation instructions) file.

If you're trying to do some other type of installation or are merely curious about how a distribution is organized, what follows is a more thorough description of some of these items in more detail:

  1. The *.TXT and *.HTM files contain documentation (for example, this document is contained in both INSTALL.TXT and INSTALL.HTM) and should be read before starting an installation. The *.TXT files are plain text, while the *.HTM files are HTML files that can be read by almost any Web browser. Some distributions may contain documentation in other formats as well, such as PDF or PostScript.

  2. docbook.css is a Cascading Style Sheet (CSS) file used by some Web browsers for formatting the HTML documentation.

  3. The base, catpages, crypto, dict, doc, games, info, manpages, proflibs, and src directories contain the primary distribution components of FreeBSD itself and are split into smaller files for easy packing onto floppies (should that be necessary).

  4. The compat1x, compat20, compat21, compat22, compat3x, and compat4x directories contain distributions for compatibility with older releases and are distributed as single gzip'd tar files - they can be installed during release time or later by running their install.sh scripts.

  5. The floppies/ subdirectory contains the floppy installation images; further information on using them can be found in Section 1.3.

  6. The packages and ports directories contain the FreeBSD Packages and Ports Collections. Packages may be installed from the packages directory by running the command:

    #/stand/sysinstall configPackages
    

    Packages can also be installed by feeding individual filenames in packages/ to the pkg_add(1) command.

    The Ports Collection may be installed like any other distribution and requires about 190MB unpacked. More information on the ports collection may be obtained from http://www.FreeBSD.org/ports/ or locally from /usr/share/doc/handbook if you've installed the doc distribution.

  7. Last of all, the tools directory contains various DOS tools for discovering disk geometries, installing boot managers and the like. It is purely optional and provided only for user convenience.



A typical distribution directory (for example, the info distribution) looks like this internally:

CHECKSUM.MD5    info.ab         info.ad         info.inf        install.sh
info.aa         info.ac         info.ae         info.mtree

The CHECKSUM.MD5 file contains MD5 signatures for each file, should data corruption be suspected, and is purely for reference. It is not used by the actual installation and does not need to be copied with the rest of the distribution files. The info.a* files are split, gzip'd tar files, the contents of which can be viewed by doing:

# cat info.a* | tar tvzf -

During installation, they are automatically concatenated and extracted by the installation procedure.

The info.inf file is also necessary since it is read by the installation program in order to figure out how many pieces to look for when fetching and concatenating the distribution. When putting distributions onto floppies, the .inf file must occupy the first floppy of each distribution set!

The info.mtree file is another non-essential file which is provided for user reference. It contains the MD5 signatures of the unpacked distribution files and can be later used with the mtree(8) program to verify the installation permissions and checksums against any possible modifications to the file. When used with the base distribution, this can be an excellent way of detecting trojan horse attacks on your system.

Finally, the install.sh file is for use by those who want to install the distribution after installation time. To install the info distribution from CDROM after a system was installed, for example, you'd do:

# cd /cdrom/info
# sh install.sh

3 Upgrading FreeBSD

These instructions describe a procedure for doing a binary upgrade from an older version of FreeBSD.

Warning: While the FreeBSD upgrade procedure does its best to safeguard against accidental loss of data, it is still more than possible to wipe out your entire disk with this installation! Please do not accept the final confirmation request unless you have adequately backed up any important data files.

Important: These notes assume that you are using the version of sysinstall(8) supplied with the version of FreeBSD to which you intend to upgrade. Using a mismatched version of sysinstall(8) is almost guaranteed to cause problems and has been known to leave systems in an unusable state. The most commonly made mistake in this regard is the use of an old copy of sysinstall(8) from an existing installation to upgrade to a newer version of FreeBSD. This is not recommended.

Warning: Binary upgrades to FreeBSD 5.3-RELEASE from FreeBSD 4-STABLE are not supported at this time. There are some files present in a FreeBSD 4-STABLE whose presence can be disruptive, but are not removed by a binary upgrade. One notable example is that an old /usr/include/g++ directory will cause C++ programs to compile incorrectly (or not at all).

These upgrade instructions are provided for the use of users upgrading from relatively recent FreeBSD 5-STABLE snapshots.


3.1 Introduction

The upgrade procedure replaces distributions selected by the user with those corresponding to the new FreeBSD release. It preserves standard system configuration data, as well as user data, installed packages and other software.

Administrators contemplating an upgrade are encouraged to study this section in its entirety before commencing an upgrade. Failure to do so may result in a failed upgrade or loss of data.


3.1.1 Upgrade Overview

Upgrading of a distribution is performed by extracting the new version of the component over the top of the previous version. Files belonging to the old distribution are not deleted.

System configuration is preserved by retaining and restoring the previous version of the following files:

Xaccel.ini, XF86Config, adduser.conf, aliases, aliases.db, amd.map, crontab, csh.cshrc, csh.login, csh.logout, cvsupfile, dhclient.conf, disktab, dm.conf, dumpdates, exports, fbtab, fstab, ftpusers, gettytab, gnats, group, hosts, hosts.allow, hosts.equiv, hosts.lpd, inetd.conf, localtime, login.access, login.conf, mail, mail.rc, make.conf, manpath.config, master.passwd, motd, namedb, networks, newsyslog.conf, nsmb.conf, nsswitch.conf, pam.conf, passwd, periodic, ppp, printcap, profile, pwd.db, rc.conf, rc.conf.local, rc.firewall, rc.local, remote, resolv.conf, rmt, sendmail.cf, sendmail.cw, services, shells, skeykeys, spwd.db, ssh, syslog.conf, ttys, uucp

The versions of these files which correspond to the new version are moved to /etc/upgrade/. The system administrator may peruse these new versions and merge components as desired. Note that many of these files are interdependent, and the best merge procedure is to copy all site-specific data from the current files into the new.

During the upgrade procedure, the administrator is prompted for a location into which all files from /etc/ are saved. In the event that local modifications have been made to other files, they may be subsequently retrieved from this location.


3.2 Procedure

This section details the upgrade procedure. Particular attention is given to items which substantially differ from a normal installation.


3.2.1 Backup

User data and system configuration should be backed up before upgrading. While the upgrade procedure does its best to prevent accidental mistakes, it is possible to partially or completely destroy data and configuration information.


3.2.2 Mount Filesystems

The disklabel editor is entered with the nominated disk's filesystem devices listed. Prior to commencing the upgrade, the administrator should make a note of the device names and corresponding mountpoints. These mountpoints should be entered here. Do not set the ``newfs flag'' for any filesystems, as this will cause data loss.


3.2.3 Select Distributions

When selecting distributions, there are no constraints on which must be selected. As a general rule, the base distribution should be selected for an update, and the man distribution if manpages are already installed. Other distributions may be selected beyond those originally installed if the administrator wishes to add additional functionality.


3.2.4 After Installation

Once the installation procedure has completed, the administrator is prompted to examine the new configuration files. At this point, checks should be made to ensure that the system configuration is valid. In particular, the /etc/rc.conf and /etc/fstab files should be checked.


3.3 Upgrading from Source Code

Those interested in an upgrade method that allows more flexibility and sophistication should take a look at The Cutting Edge in the FreeBSD Handbook. This procedure involves rebuilding all of FreeBSD from source code. It requires reliable network connectivity, extra disk space, and time, but has advantages for networks and other more complex installations. This is roughly the same procedure as is used for track the -STABLE or -CURRENT development branches.

/usr/src/UPDATING contains important information on updating a FreeBSD system from source code. It lists various issues resulting from changes in FreeBSD that may affect an upgrade.


4 Troubleshooting

4.1 Repairing an Existing FreeBSD Installation

FreeBSD features a ``Fixit'' option in the top menu of the boot floppy. To use it, you will also need either a fixit.flp image floppy, generated in the same fashion as the boot floppy, or the ``live filesystem'' CDROM; typically the second CDROM in a multi-disc FreeBSD distribution.

To invoke fixit, simply boot the kern.flp floppy, choose the ``Fixit'' item and insert the fixit floppy or CDROM when asked. You will then be placed into a shell with a wide variety of commands available (in the /stand and /mnt2/stand directories) for checking, repairing and examining filesystems and their contents. Some UNIX administration experience is required to use the fixit option.


This file, and other release-related documents, can be downloaded from ftp://ftp.FreeBSD.org/.

For questions about FreeBSD, read the documentation before contacting <questions@FreeBSD.org>.

For questions about this documentation, e-mail <doc@FreeBSD.org>.

++++ ",12467,True,2560.932201341572,median "#include ""SamplePlugin.h"" #include ""OgreShaderSubRenderState.h"" #include ""ShaderSystem.h"" #include ""ShaderExReflectionMap.h"" #include ""OgreShaderExInstancedViewports.h"" #include ""OgreShaderExTextureAtlasSampler.h"" #include ""OgreBillboard.h"" using namespace Ogre; using namespace OgreBites; //----------------------------------------------------------------------- const String DIRECTIONAL_LIGHT_NAME = ""DirectionalLight""; const String POINT_LIGHT_NAME = ""PointLight""; const String INSTANCED_VIEWPORTS_NAME = ""InstancedViewports""; const String ADD_LOTS_OF_MODELS_NAME = ""AddLotsOfModels""; const String SPOT_LIGHT_NAME = ""SpotLight""; const String PER_PIXEL_FOG_BOX = ""PerPixelFog""; const String ATLAS_AUTO_BORDER_MODE = ""AutoBorderAtlasing""; const String MAIN_ENTITY_MESH = ""ShaderSystem.mesh""; const String SPECULAR_BOX = ""SpecularBox""; const String REFLECTIONMAP_BOX = ""ReflectionMapBox""; const String REFLECTIONMAP_POWER_SLIDER = ""ReflectionPowerSlider""; const String MAIN_ENTITY_NAME = ""MainEntity""; const String EXPORT_BUTTON_NAME = ""ExportMaterial""; const String FLUSH_BUTTON_NAME = ""FlushShaderCache""; const String LAYERBLEND_BUTTON_NAME = ""ChangeLayerBlendType""; const String MODIFIER_VALUE_SLIDER = ""ModifierValueSlider""; const String SAMPLE_MATERIAL_GROUP = ""RTShaderSystemMaterialsGroup""; const int MESH_ARRAY_SIZE = 2; const String MESH_ARRAY[MESH_ARRAY_SIZE] = { MAIN_ENTITY_MESH, ""knot.mesh"" }; #ifndef OGRE_STATIC_LIB SamplePlugin* sp; Sample* s; //----------------------------------------------------------------------- extern ""C"" _OgreSampleExport void dllStartPlugin() { s = new Sample_ShaderSystem; sp = OGRE_NEW SamplePlugin(s->getInfo()[""Title""] + "" Sample""); sp->addSample(s); Root::getSingleton().installPlugin(sp); } //----------------------------------------------------------------------- extern ""C"" _OgreSampleExport void dllStopPlugin() { Root::getSingleton().uninstallPlugin(sp); OGRE_DELETE sp; delete s; } #endif //----------------------------------------------------------------------- Sample_ShaderSystem::Sample_ShaderSystem() : mInfiniteFrustum( &mObjectMemoryManager ), mLayeredBlendingEntity(NULL) { mInfo[""Title""] = ""Shader System""; mInfo[""Description""] = ""Demonstrate the capabilities of the RT Shader System component."" ""1. Fixed Function Pipeline emulation."" ""2. On the fly shader generation based on existing material."" ""3. On the fly shader synchronization with scene state (Lights, Fog)."" ""4. Built in lighting models: Per vertex, Per pixel, Normal map tangent and object space."" ""5. Pluggable custom shaders extensions."" ""6. Built in material script parsing that includes extended attributes."" ""7. Built in material script serialization."" ; mInfo[""Thumbnail""] = ""thumb_shadersystem.png""; mInfo[""Category""] = ""Lighting""; mInfo[""Help""] = ""F2 Toggle Shader System globally. "" ""F3 Toggles Global Lighting Model. "" ""Modify target model attributes and scene settings and observe the generated shaders count. "" ""Press the export button in order to export current target model material. "" ""The model above the target will import this material next time the sample reloads. "" ""Right click on object to see the shaders it currently uses. "" ; mPointLightNode = NULL; mReflectionMapFactory = NULL; mInstancedViewportsEnable = false; mInstancedViewportsSubRenderState = NULL; mInstancedViewportsFactory = NULL; mBbsFlare = NULL; mAddedLotsOfModels = false; mNumberOfModelsAdded = 0; } //----------------------------------------------------------------------- Sample_ShaderSystem::~Sample_ShaderSystem() { } //----------------------------------------------------------------------- void Sample_ShaderSystem::_shutdown() { destroyInstancedViewports(); SdkSample::_shutdown(); } //----------------------------------------------------------------------- void Sample_ShaderSystem::checkBoxToggled(CheckBox* box) { const String& cbName = box->getName(); if (cbName == SPECULAR_BOX) { setSpecularEnable(box->isChecked()); } else if (cbName == REFLECTIONMAP_BOX) { setReflectionMapEnable(box->isChecked()); } else if (cbName == DIRECTIONAL_LIGHT_NAME) { updateLightState(cbName, box->isChecked()); } else if (cbName == POINT_LIGHT_NAME) { updateLightState(cbName, box->isChecked()); } else if (cbName == INSTANCED_VIEWPORTS_NAME) { updateInstancedViewports(box->isChecked()); } else if (cbName == ADD_LOTS_OF_MODELS_NAME) { updateAddLotsOfModels(box->isChecked()); } else if (cbName == SPOT_LIGHT_NAME) { updateLightState(cbName, box->isChecked()); } else if (cbName == PER_PIXEL_FOG_BOX) { setPerPixelFogEnable(box->isChecked()); } else if (cbName == ATLAS_AUTO_BORDER_MODE) { setAtlasBorderMode(box->isChecked()); } } //----------------------------------------------------------------------- void Sample_ShaderSystem::itemSelected(SelectMenu* menu) { if (menu == mLightingModelMenu) { int curModelIndex = menu->getSelectionIndex(); if (curModelIndex >= SSLM_PerVertexLighting && curModelIndex <= SSLM_NormalMapLightingObjectSpace) { setCurrentLightingModel((ShaderSystemLightingModel)curModelIndex); } } else if (menu == mFogModeMenu) { int curModeIndex = menu->getSelectionIndex(); if (curModeIndex >= FOG_NONE && curModeIndex <= FOG_LINEAR) { mSceneMgr->setFog((FogMode)curModeIndex, ColourValue(1.0, 1.0, 1.0, 0.0), 0.0015, 350.0, 1500.0); } } else if (menu == mShadowMenu) { int curShadowTypeIndex = menu->getSelectionIndex(); applyShadowType(curShadowTypeIndex); } else if(menu == mLanguageMenu) { ShaderGenerator::getSingletonPtr()->setTargetLanguage(menu->getSelectedItem()); } } //----------------------------------------------------------------------- void Sample_ShaderSystem::buttonHit( OgreBites::Button* b ) { // Case the current material of the main entity should be exported. if (b->getName() == EXPORT_BUTTON_NAME) { const String& materialName = mMainEntity->getSubEntity(0)->getMaterialName(); exportRTShaderSystemMaterial(mExportMaterialPath + ""ShaderSystemExport.material"", materialName); } // Case the shader cache should be flushed. else if (b->getName() == FLUSH_BUTTON_NAME) { mShaderGenerator->flushShaderCache(); } // Case the blend layer type modified. else if (b->getName() == LAYERBLEND_BUTTON_NAME && mLayerBlendSubRS != NULL) { changeTextureLayerBlendMode(); } } //-------------------------------------------------------------------------- void Sample_ShaderSystem::sliderMoved(Slider* slider) { if (slider->getName() == REFLECTIONMAP_POWER_SLIDER) { Real reflectionPower = slider->getValue(); if (mReflectionMapSubRS != NULL) { ShaderExReflectionMap* reflectionMapSubRS = static_cast(mReflectionMapSubRS); // Since RTSS export caps based on the template sub render states we have to update the template reflection sub render state. reflectionMapSubRS->setReflectionPower(reflectionPower); // Grab the instances set and update them with the new reflection power value. // The instances are the actual sub render states that have been assembled to create the final shaders. // Every time that the shaders have to be re-generated (light changes, fog changes etc..) a new set of sub render states // based on the template sub render states assembled for each pass. // From that set of instances a CPU program is generated and afterward a GPU program finally generated. RTShader::SubRenderStateSet instanceSet = mReflectionMapSubRS->getAccessor()->getSubRenderStateInstanceSet(); RTShader::SubRenderStateSetIterator it = instanceSet.begin(); RTShader::SubRenderStateSetIterator itEnd = instanceSet.end(); for (; it != itEnd; ++it) { ShaderExReflectionMap* reflectionMapSubRSInstance = static_cast(*it); reflectionMapSubRSInstance->setReflectionPower(reflectionPower); } } } if (slider->getName() == MODIFIER_VALUE_SLIDER) { if (mLayeredBlendingEntity != NULL) { Ogre::Real val = mModifierValueSlider->getValue(); mLayeredBlendingEntity->getSubEntity(0)->setCustomParameter(2, Vector4(val,val,val,0)); } } } Light * Sample_ShaderSystem::getLightNamedFromSceneManager(const String &name) { LightArray lightList = mSceneMgr->getGlobalLightList().lights; for (unsigned int i = 0; i < lightList.size(); ++i) { if(lightList[i]->getName() == name) return lightList[i]; } return NULL; } //----------------------------------------------------------------------- bool Sample_ShaderSystem::frameRenderingQueued( const FrameEvent& evt ) { // Make this viewport work with shader generator scheme. mSceneMgr->getCurrentViewport()->setMaterialScheme(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME); if (getLightNamedFromSceneManager(SPOT_LIGHT_NAME) != NULL) { Light* light = getLightNamedFromSceneManager(SPOT_LIGHT_NAME); light->getParentSceneNode()->setPosition(mCamera->getDerivedPosition() + mCamera->getDerivedUp() * 20.0); light->setDirection(mCamera->getDerivedDirection()); } if (mPointLightNode != NULL) { static Real sTotalTime = 0.0; sTotalTime += evt.timeSinceLastFrame; mPointLightNode->yaw(Degree(evt.timeSinceLastFrame * 15)); mPointLightNode->setPosition(0.0, Math::Sin(sTotalTime) * 30.0, 0.0); } updateTargetObjInfo(); return SdkSample::frameRenderingQueued(evt); } //----------------------------------------------------------------------- //void Sample_ShaderSystem::setupView() //{ // // setup default viewport layout and camera // mCamera = mSceneMgr->createCamera(""MainCamera""); // mViewport = mWindow->addViewport(mCamera); // mCamera->setAspectRatio((Ogre::Real)mViewport->getActualWidth() / (Ogre::Real)mViewport->getActualHeight()); // mCamera->setNearClipDistance(5); // // mCameraMan = new SdkCameraMan(mCamera); // create a default camera controller //} //----------------------------------------------------------------------- void Sample_ShaderSystem::setupContent() { // Setup default effects values. mCurLightingModel = SSLM_PerVertexLighting; mPerPixelFogEnable = false; mSpecularEnable = false; mReflectionMapEnable = false; mReflectionMapSubRS = NULL; mLayerBlendSubRS = NULL; mRayQuery = mSceneMgr->createRayQuery(Ray()); mTargetObj = NULL; // Set ambient lighting. mSceneMgr->setAmbientLight(ColourValue(0.2, 0.2, 0.2)); // Setup the sky box, mSceneMgr->setSkyBox(true, ""Examples/SceneCubeMap2""); MeshManager::getSingleton().createPlane(""Myplane"", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Plane(Vector3::UNIT_Y, 0), 1500,1500,25,25,true,1,60,60,Vector3::UNIT_Z); Entity* pPlaneEnt = mSceneMgr->createEntity( ""Myplane"" ); pPlaneEnt->setName(""plane""); pPlaneEnt->setMaterialName(""Examples/Rockwall""); pPlaneEnt->setCastShadows(false); SceneNode *planeNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); planeNode->setPosition(Vector3(0,0,0)); planeNode->attachObject(pPlaneEnt); // Load sample meshes and generate tangent vectors. for (int i=0; i < MESH_ARRAY_SIZE; ++i) { const String& curMeshName = MESH_ARRAY[i]; MeshPtr pMesh = MeshManager::getSingleton().load(curMeshName, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY, HardwareBuffer::HBU_STATIC_WRITE_ONLY, true, true); //so we can still read it // Build tangent vectors, all our meshes use only 1 texture coordset // Note we can build into VES_TANGENT now (SM2+) unsigned short src, dest; if (!pMesh->suggestTangentVectorBuildParams(VES_TANGENT, src, dest)) { pMesh->buildTangentVectors(VES_TANGENT, src, dest); } } SceneNode* childNode; // Create the main entity and mark it as the current target object. mMainEntity = mSceneMgr->createEntity(MAIN_ENTITY_MESH); mMainEntity->setName(MAIN_ENTITY_NAME); mTargetEntities.push_back(mMainEntity); childNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); childNode->attachObject(mMainEntity); mTargetObj = mMainEntity; // Create reflection entity that will show the exported material. const String& mainExportedMaterial = mMainEntity->getSubEntity(0)->getMaterialName() + ""_RTSS_Export""; MaterialPtr matMainEnt = MaterialManager::getSingleton().getByName(mainExportedMaterial, SAMPLE_MATERIAL_GROUP); Entity *entity = mSceneMgr->createEntity(MAIN_ENTITY_MESH); entity->setName(""ExportedMaterialEntity""); entity->setMaterial(matMainEnt); childNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); childNode->setPosition(0.0, 200.0, -200.0); childNode->attachObject(entity); // Create texture layer blending demonstration entity. mLayeredBlendingEntity = mSceneMgr->createEntity(MAIN_ENTITY_MESH); mLayeredBlendingEntity->setName(""LayeredBlendingMaterialEntity""); mLayeredBlendingEntity->setMaterialName(""RTSS/LayeredBlending""); mLayeredBlendingEntity->getSubEntity(0)->setCustomParameter(2, Vector4::ZERO); childNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); childNode->setPosition(300.0, 200.0, -200.0); childNode->attachObject(mLayeredBlendingEntity); // Grab the render state of the material. RTShader::RenderState* renderState = mShaderGenerator->getRenderState(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME, ""RTSS/LayeredBlending"", 0); if (renderState != NULL) { const SubRenderStateList& subRenderStateList = renderState->getTemplateSubRenderStateList(); SubRenderStateListConstIterator it = subRenderStateList.begin(); SubRenderStateListConstIterator itEnd = subRenderStateList.end(); // Search for the texture layer blend sub state. for (; it != itEnd; ++it) { SubRenderState* curSubRenderState = *it; if (curSubRenderState->getType() == LayeredBlending::Type) { mLayerBlendSubRS = static_cast(curSubRenderState); break; } } } // Create per pixel lighting demonstration entity. Entity *knotEntity = mSceneMgr->createEntity(""knot.mesh""); knotEntity->setName(""PerPixelEntity""); knotEntity->setMaterialName(""RTSS/PerPixel_SinglePass""); childNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); childNode->setPosition(300.0, 100.0, -100.0); childNode->attachObject(knotEntity); // Create normal map lighting demonstration entity. knotEntity = mSceneMgr->createEntity(""knot.mesh""); knotEntity->setName(""NormalMapEntity""); knotEntity->setMaterialName(""RTSS/NormalMapping_SinglePass""); childNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); childNode->setPosition(-300.0, 100.0, -100.0); childNode->attachObject(knotEntity); // OpenGL ES 2.0 does not support texture atlases. But ES 3.0 does! #if OGRE_NO_GLES3_SUPPORT == 1 if (Ogre::Root::getSingletonPtr()->getRenderSystem()->getName().find(""OpenGL ES 2"") == String::npos) #endif { RTShader::RenderState* pMainRenderState = RTShader::ShaderGenerator::getSingleton().createOrRetrieveRenderState(Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME).first; pMainRenderState->addTemplateSubRenderState( Ogre::RTShader::ShaderGenerator::getSingleton().createSubRenderState( Ogre::RTShader::TextureAtlasSampler::Type)); // Create texture atlas object and node ManualObject* atlasObject = createTextureAtlasObject(); childNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); childNode->setPosition(-600.0, 0, -850.0); childNode->attachObject(atlasObject); } createDirectionalLight(); createPointLight(); createSpotLight(); RenderState* schemRenderState = mShaderGenerator->getRenderState(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME); // Take responsibility for updating the light count manually. schemRenderState->setLightCountAutoUpdate(false); mSceneMgr->updateSceneGraph(); setupUI(); mCamera->setPosition(0.0, 300.0, 450.0); mCamera->lookAt(0.0, 150.0, 0.0); // Mark system as on. mDetailsPanel->setParamValue(11, ""On""); // a friendly reminder StringVector names; names.push_back(""Help""); mTrayMgr->createParamsPanel(TL_TOPLEFT, ""Help"", 100, names)->setParamValue(0, ""H/F1""); updateSystemShaders(); } //----------------------------------------------------------------------- void Sample_ShaderSystem::setupUI() { // Create language selection mLanguageMenu = mTrayMgr->createLongSelectMenu(TL_TOPLEFT, ""LangMode"", ""Language"", 220, 120, 10); // Use GLSL ES in case of OpenGL ES 2 render system. if (Ogre::Root::getSingletonPtr()->getRenderSystem()->getName().find(""OpenGL ES 2"") != String::npos) { mLanguageMenu->addItem(""glsles""); mShaderGenerator->setTargetLanguage(""glsles""); } // Use GLSL in case of OpenGL render system. else if (Ogre::Root::getSingletonPtr()->getRenderSystem()->getName().find(""OpenGL"") != String::npos) { mLanguageMenu->addItem(""glsl""); mShaderGenerator->setTargetLanguage(""glsl""); } // Use HLSL in case of D3D9 render system. else if (Ogre::Root::getSingletonPtr()->getRenderSystem()->getName().find(""Direct3D9"") != String::npos) { mLanguageMenu->addItem(""hlsl""); mShaderGenerator->setTargetLanguage(""hlsl""); } mLanguageMenu->addItem(""cg""); // create check boxes to toggle lights. mDirLightCheckBox = mTrayMgr->createCheckBox(TL_TOPLEFT, DIRECTIONAL_LIGHT_NAME, ""Directional Light"", 220); mPointLightCheckBox = mTrayMgr->createCheckBox(TL_TOPLEFT, POINT_LIGHT_NAME, ""Point Light"", 220); mSpotLightCheckBox = mTrayMgr->createCheckBox(TL_TOPLEFT, SPOT_LIGHT_NAME, ""Spot Light"", 220); mInstancedViewportsCheckBox = mTrayMgr->createCheckBox(TL_TOPLEFT, INSTANCED_VIEWPORTS_NAME, ""Instanced Viewports"", 220); mAddLotsOfModels = mTrayMgr->createCheckBox(TL_TOPLEFT, ADD_LOTS_OF_MODELS_NAME, ""Add lots of models"", 220); mDirLightCheckBox->setChecked(true); mPointLightCheckBox->setChecked(true); mSpotLightCheckBox->setChecked(false); mInstancedViewportsCheckBox->setChecked(false); mAddLotsOfModels->setChecked(false); #ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS mTrayMgr->createCheckBox(TL_TOPLEFT, PER_PIXEL_FOG_BOX, ""Per Pixel Fog"", 220)->setChecked(mPerPixelFogEnable); #endif #ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS mTrayMgr->createCheckBox(TL_TOPLEFT, ATLAS_AUTO_BORDER_MODE, ""Atlas auto border"", 220)->setChecked(true); setAtlasBorderMode(true); #endif // Create fog widgets. mFogModeMenu = mTrayMgr->createLongSelectMenu(TL_TOPLEFT, ""FogMode"", ""Fog Mode"", 220, 120, 10); mFogModeMenu->addItem(""None""); mFogModeMenu->addItem(""Exp""); mFogModeMenu->addItem(""Exp2""); mFogModeMenu->addItem(""Linear""); // Create shadow menu. mShadowMenu = mTrayMgr->createLongSelectMenu(TL_TOPLEFT, ""ShadowType"", ""Shadow"", 220, 120, 10); mShadowMenu->addItem(""None""); #ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS mShadowMenu->addItem(""PSSM 3""); #endif // Flush shader cache button. mTrayMgr->createButton(TL_TOPLEFT, FLUSH_BUTTON_NAME, ""Flush Shader Cache"", 220); // create target model widgets. mTargetObjMatName = mTrayMgr->createLabel(TL_TOPLEFT, ""TargetObjMatName"", """", 220); mTargetObjVS = mTrayMgr->createLabel(TL_TOPLEFT, ""TargetObjVS"", """", 220); mTargetObjFS = mTrayMgr->createLabel(TL_TOPLEFT, ""TargetObjFS"", """", 220); // Create main entity widgets. mTrayMgr->createLabel(TL_BOTTOM, ""MainEntityLabel"", ""Main Entity Settings"", 240); mTrayMgr->createCheckBox(TL_BOTTOM, SPECULAR_BOX, ""Specular"", 240)->setChecked(mSpecularEnable); // Allow reflection map only on PS3 and above since with all lights on + specular + bump we // exceed the instruction count limits of PS2. if (GpuProgramManager::getSingleton().isSyntaxSupported(""ps_3_0"") || GpuProgramManager::getSingleton().isSyntaxSupported(""glsles"") || GpuProgramManager::getSingleton().isSyntaxSupported(""fp30"")) { mTrayMgr->createCheckBox(TL_BOTTOM, REFLECTIONMAP_BOX, ""Reflection Map"", 240)->setChecked(mReflectionMapEnable); mReflectionPowerSlider = mTrayMgr->createThickSlider(TL_BOTTOM, REFLECTIONMAP_POWER_SLIDER, ""Reflection Power"", 240, 80, 0, 1, 100); mReflectionPowerSlider->setValue(0.5, false); } mLightingModelMenu = mTrayMgr->createLongSelectMenu(TL_BOTTOM, ""TargetModelLighting"", """", 240, 230, 10); mLightingModelMenu ->addItem(""Per Vertex""); #ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS mLightingModelMenu ->addItem(""Per Pixel""); mLightingModelMenu ->addItem(""Normal Map - Tangent Space""); mLightingModelMenu ->addItem(""Normal Map - Object Space""); #endif mTrayMgr->createButton(TL_BOTTOM, EXPORT_BUTTON_NAME, ""Export Material"", 240); #ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS mLayerBlendLabel = mTrayMgr->createLabel(TL_RIGHT, ""Blend Type"", ""Blend Type"", 240); mTrayMgr->createButton(TL_RIGHT, LAYERBLEND_BUTTON_NAME, ""Change Blend Type"", 220); mModifierValueSlider = mTrayMgr->createThickSlider(TL_RIGHT, MODIFIER_VALUE_SLIDER, ""Modifier"", 240, 80, 0, 1, 100); mModifierValueSlider->setValue(0.0,false); // Update the caption. if(mLayerBlendSubRS) updateLayerBlendingCaption(mLayerBlendSubRS->getBlendMode(1)); #endif mTrayMgr->showCursor(); } //----------------------------------------------------------------------- void Sample_ShaderSystem::cleanupContent() { // UnLoad sample meshes and generate tangent vectors. for (int i=0; i < MESH_ARRAY_SIZE; ++i) { const String& curMeshName = MESH_ARRAY[i]; MeshManager::getSingleton().unload(curMeshName); } MeshManager::getSingleton().remove(MAIN_ENTITY_MESH); mTargetEntities.clear(); MeshManager::getSingleton().remove(""Myplane""); mSceneMgr->destroyQuery(mRayQuery); } //----------------------------------------------------------------------- void Sample_ShaderSystem::setCurrentLightingModel(ShaderSystemLightingModel lightingModel) { if (mCurLightingModel != lightingModel) { mCurLightingModel = lightingModel; EntityListIterator it = mTargetEntities.begin(); EntityListIterator itEnd = mTargetEntities.end(); for (; it != itEnd; ++it) { generateShaders(*it); } } } //----------------------------------------------------------------------- void Sample_ShaderSystem::setSpecularEnable(bool enable) { if (mSpecularEnable != enable) { mSpecularEnable = enable; updateSystemShaders(); } } //----------------------------------------------------------------------- void Sample_ShaderSystem::setReflectionMapEnable(bool enable) { if (mReflectionMapEnable != enable) { mReflectionMapEnable = enable; updateSystemShaders(); } } //----------------------------------------------------------------------- void Sample_ShaderSystem::setPerPixelFogEnable( bool enable ) { #ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS if (mPerPixelFogEnable != enable) { mPerPixelFogEnable = enable; // Grab the scheme render state. RenderState* schemRenderState = mShaderGenerator->getRenderState(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME); const SubRenderStateList& subRenderStateList = schemRenderState->getTemplateSubRenderStateList(); SubRenderStateListConstIterator it = subRenderStateList.begin(); SubRenderStateListConstIterator itEnd = subRenderStateList.end(); FFPFog* fogSubRenderState = NULL; // Search for the fog sub state. for (; it != itEnd; ++it) { SubRenderState* curSubRenderState = *it; if (curSubRenderState->getType() == FFPFog::Type) { fogSubRenderState = static_cast(curSubRenderState); break; } } // Create the fog sub render state if need to. if (fogSubRenderState == NULL) { SubRenderState* subRenderState = mShaderGenerator->createSubRenderState(FFPFog::Type); fogSubRenderState = static_cast(subRenderState); schemRenderState->addTemplateSubRenderState(fogSubRenderState); } // Select the desired fog calculation mode. if (mPerPixelFogEnable) { fogSubRenderState->setCalcMode(FFPFog::CM_PER_PIXEL); } else { fogSubRenderState->setCalcMode(FFPFog::CM_PER_VERTEX); } // Invalidate the scheme in order to re-generate all shaders based technique related to this scheme. mShaderGenerator->invalidateScheme(Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME); } #endif } void Sample_ShaderSystem::setAtlasBorderMode( bool enable ) { #ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS TextureAtlasSamplerFactory::getSingleton().setDefaultAtlasingAttributes( TextureAtlasSamplerFactory::ipmRelative, 1, enable); mShaderGenerator->invalidateScheme(Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME); #endif } //----------------------------------------------------------------------- void Sample_ShaderSystem::updateSystemShaders() { EntityListIterator it = mTargetEntities.begin(); EntityListIterator itEnd = mTargetEntities.end(); for (; it != itEnd; ++it) { generateShaders(*it); } } //----------------------------------------------------------------------- void Sample_ShaderSystem::generateShaders(Entity* entity) { for (unsigned int i=0; i < entity->getNumSubEntities(); ++i) { SubEntity* curSubEntity = entity->getSubEntity(i); const String& curMaterialName = curSubEntity->getMaterialName(); bool success; // Create the shader based technique of this material. success = mShaderGenerator->createShaderBasedTechnique(curMaterialName, MaterialManager::DEFAULT_SCHEME_NAME, RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME); // Setup custom shader sub render states according to current setup. if (success) { MaterialPtr curMaterial = MaterialManager::getSingleton().getByName(curMaterialName); Pass* curPass = curMaterial->getTechnique(0)->getPass(0); if (mSpecularEnable) { curPass->setSpecular(ColourValue::White); curPass->setShininess(32.0); } else { curPass->setSpecular(ColourValue::Black); curPass->setShininess(0.0); } // Grab the first pass render state. // NOTE: For more complicated samples iterate over the passes and build each one of them as desired. RTShader::RenderState* renderState = mShaderGenerator->getRenderState(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME, curMaterialName, 0); // Remove all sub render states. renderState->reset(); #ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS if (mCurLightingModel == SSLM_PerVertexLighting) { RTShader::SubRenderState* perPerVertexLightModel = mShaderGenerator->createSubRenderState(RTShader::FFPLighting::Type); renderState->addTemplateSubRenderState(perPerVertexLightModel); } #endif #ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS else if (mCurLightingModel == SSLM_PerPixelLighting) { RTShader::SubRenderState* perPixelLightModel = mShaderGenerator->createSubRenderState(RTShader::PerPixelLighting::Type); renderState->addTemplateSubRenderState(perPixelLightModel); } else if (mCurLightingModel == SSLM_NormalMapLightingTangentSpace) { // Apply normal map only on main entity. if (entity->getName() == MAIN_ENTITY_NAME) { RTShader::SubRenderState* subRenderState = mShaderGenerator->createSubRenderState(RTShader::NormalMapLighting::Type); RTShader::NormalMapLighting* normalMapSubRS = static_cast(subRenderState); normalMapSubRS->setNormalMapSpace(RTShader::NormalMapLighting::NMS_TANGENT); normalMapSubRS->setNormalMapTextureName(""Panels_Normal_Tangent.png""); renderState->addTemplateSubRenderState(normalMapSubRS); } // It is secondary entity -> use simple per pixel lighting. else { RTShader::SubRenderState* perPixelLightModel = mShaderGenerator->createSubRenderState(RTShader::PerPixelLighting::Type); renderState->addTemplateSubRenderState(perPixelLightModel); } } else if (mCurLightingModel == SSLM_NormalMapLightingObjectSpace) { // Apply normal map only on main entity. if (entity->getName() == MAIN_ENTITY_NAME) { RTShader::SubRenderState* subRenderState = mShaderGenerator->createSubRenderState(RTShader::NormalMapLighting::Type); RTShader::NormalMapLighting* normalMapSubRS = static_cast(subRenderState); normalMapSubRS->setNormalMapSpace(RTShader::NormalMapLighting::NMS_OBJECT); normalMapSubRS->setNormalMapTextureName(""Panels_Normal_Obj.png""); renderState->addTemplateSubRenderState(normalMapSubRS); } // It is secondary entity -> use simple per pixel lighting. else { RTShader::SubRenderState* perPixelLightModel = mShaderGenerator->createSubRenderState(RTShader::PerPixelLighting::Type); renderState->addTemplateSubRenderState(perPixelLightModel); } } #endif if (mReflectionMapEnable) { RTShader::SubRenderState* subRenderState = mShaderGenerator->createSubRenderState(ShaderExReflectionMap::Type); ShaderExReflectionMap* reflectionMapSubRS = static_cast(subRenderState); reflectionMapSubRS->setReflectionMapType(TEX_TYPE_CUBE_MAP); reflectionMapSubRS->setReflectionPower(mReflectionPowerSlider->getValue()); // Setup the textures needed by the reflection effect. reflectionMapSubRS->setMaskMapTextureName(""Panels_refmask.png""); reflectionMapSubRS->setReflectionMapTextureName(""cubescene.jpg""); renderState->addTemplateSubRenderState(subRenderState); mReflectionMapSubRS = subRenderState; } else { mReflectionMapSubRS = NULL; } // Invalidate this material in order to re-generate its shaders. mShaderGenerator->invalidateMaterial(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME, curMaterialName); } } } //----------------------------------------------------------------------- void Sample_ShaderSystem::createDirectionalLight() { Light* light; Vector3 dir; // create pivot node mDirectionalLightNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); light = mSceneMgr->createLight(); light->setName(DIRECTIONAL_LIGHT_NAME); mDirectionalLightNode->attachObject(light); light->setType(Light::LT_DIRECTIONAL); light->setCastShadows(true); dir.x = 0.5; dir.y = -1.0; dir.z = 0.3; dir.normalise(); light->setDirection(dir); light->setDiffuseColour(0.65, 0.15, 0.15); light->setSpecularColour(0.5, 0.5, 0.5); // Create billboard set. mBbsFlare = mSceneMgr->createBillboardSet(); mBbsFlare->setMaterialName(""Examples/Flare3""); mBbsFlare->createBillboard(-dir * 500.0)->setColour(light->getDiffuseColour()); mBbsFlare->setCastShadows(false); mDirectionalLightNode->attachObject(mBbsFlare); } //----------------------------------------------------------------------- void Sample_ShaderSystem::createPointLight() { Light* light; Vector3 dir; // create pivot node mPointLightNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); light = mSceneMgr->createLight(); light->setName(POINT_LIGHT_NAME); mPointLightNode->attachObject(light); mPointLightNode->setPosition(Vector3(200, 100, 0)); light->setType(Light::LT_POINT); light->setCastShadows(false); dir.x = 0.5; dir.y = 0.0; dir.z = 0.0f; dir.normalise(); light->setDirection(dir); light->setDiffuseColour(0.15, 0.65, 0.15); light->setSpecularColour(0.5, 0.5, 0.5); light->setAttenuation(200.0, 1.0, 0.0005, 0.0); BillboardSet* bbs; // Create billboard set. bbs = mSceneMgr->createBillboardSet(); bbs->setMaterialName(""Examples/Flare3""); bbs->createBillboard(200, 100, 0)->setColour(light->getDiffuseColour()); bbs->setCastShadows(false); mPointLightNode->attachObject(bbs); } //----------------------------------------------------------------------- void Sample_ShaderSystem::createSpotLight() { Light* light; Vector3 dir; SceneNode *spotLightNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); light = mSceneMgr->createLight(); light->setName(SPOT_LIGHT_NAME); spotLightNode->attachObject(light); light->setType(Light::LT_SPOTLIGHT); light->setCastShadows(false); dir.x = 0.0; dir.y = 0.0; dir.z = -1.0f; dir.normalise(); light->setSpotlightRange(Degree(20.0), Degree(25.0), 0.95); light->setDirection(dir); light->setDiffuseColour(0.15, 0.15, 0.65); light->setSpecularColour(0.5, 0.5, 0.5); light->setAttenuation(1000.0, 1.0, 0.0005, 0.0); } void Sample_ShaderSystem::addModelToScene(const String & modelName) { mNumberOfModelsAdded++; for(int i = 0 ; i < 8 ; i++) { float scaleFactor = 30; Entity* entity; SceneNode* childNode; entity = mSceneMgr->createEntity(modelName); mLotsOfModelsEntities.push_back(entity); childNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); mLotsOfModelsNodes.push_back(childNode); childNode->setPosition(mNumberOfModelsAdded * scaleFactor, 15, i * scaleFactor); childNode->attachObject(entity); MeshPtr modelMesh = MeshManager::getSingleton().getByName(modelName); Vector3 modelSize = modelMesh->getBounds().getSize(); childNode->scale(1 / modelSize.x * scaleFactor, 1 / modelSize.y * scaleFactor, 1 / modelSize.z * scaleFactor ); } } void Sample_ShaderSystem::updateAddLotsOfModels(bool addThem) { if (mAddedLotsOfModels != addThem) { mAddedLotsOfModels = addThem; if(mNumberOfModelsAdded == 0) { addModelToScene(""Barrel.mesh""); addModelToScene(""facial.mesh""); addModelToScene(""fish.mesh""); addModelToScene(""ninja.mesh""); addModelToScene(""penguin.mesh""); addModelToScene(""razor.mesh""); addModelToScene(""RZR-002.mesh""); addModelToScene(""tudorhouse.mesh""); addModelToScene(""WoodPallet.mesh""); } for (size_t i = 0 ; i < mLotsOfModelsNodes.size() ; i++) { mLotsOfModelsNodes[i]->setVisible(mAddedLotsOfModels); } } } //----------------------------------------------------------------------- void Sample_ShaderSystem::updateInstancedViewports(bool enabled) { if (mInstancedViewportsEnable != enabled) { mInstancedViewportsEnable = enabled; if (mInstancedViewportsEnable) { mCamera->setCullingFrustum(&mInfiniteFrustum); // having problems with bb... mDirectionalLightNode->detachObject(mBbsFlare); } else { mCamera->setCullingFrustum(NULL); mDirectionalLightNode->attachObject(mBbsFlare); } if(mInstancedViewportsEnable) { createInstancedViewports(); } else { destroyInstancedViewports(); } } } //----------------------------------------------------------------------- void Sample_ShaderSystem::updateLightState(const String& lightName, bool visible) { if (getLightNamedFromSceneManager(lightName) != NULL) { // Case it is the point light, // toggle its visibility and billboard set visibility. if (lightName == POINT_LIGHT_NAME) { if (visible) { if (mPointLightNode->getParent() != mSceneMgr->getRootSceneNode()) { mSceneMgr->getRootSceneNode()->addChild(mPointLightNode); } } else { if (mPointLightNode->getParent() == mSceneMgr->getRootSceneNode()) { mSceneMgr->getRootSceneNode()->removeChild(mPointLightNode); } } getLightNamedFromSceneManager(lightName)->setVisible(visible); } // Case it is the directional light, // toggle its visibility and billboard set visibility. else if (lightName == DIRECTIONAL_LIGHT_NAME) { SceneNode::ObjectIterator it = mDirectionalLightNode->getAttachedObjectIterator(); while (it.hasMoreElements()) { MovableObject* o = it.getNext(); o->setVisible(visible); } } // Spot light has no scene node representation. else { getLightNamedFromSceneManager(lightName)->setVisible(visible); } RenderState* schemRenderState = mShaderGenerator->getRenderState(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME); int lightCount[3] = {0}; // Update point light count. if (getLightNamedFromSceneManager(POINT_LIGHT_NAME)->isVisible()) { lightCount[0] = 1; } // Update directional light count. if (getLightNamedFromSceneManager(DIRECTIONAL_LIGHT_NAME)->isVisible()) { lightCount[1] = 1; } // Update spot light count. if (getLightNamedFromSceneManager(SPOT_LIGHT_NAME)->isVisible()) { lightCount[2] = 1; } // Update the scheme light count. schemRenderState->setLightCount(lightCount); // Invalidate the scheme in order to re-generate all shaders based technique related to this scheme. mShaderGenerator->invalidateScheme(Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME); } } //----------------------------------------------------------------------- void Sample_ShaderSystem::applyShadowType(int menuIndex) { // Grab the scheme render state. Ogre::RTShader::RenderState* schemRenderState = mShaderGenerator->getRenderState(Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME); // No shadow if (menuIndex == 0) { // mSceneMgr->setShadowTechnique(SHADOWTYPE_NONE); #ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS const Ogre::RTShader::SubRenderStateList& subRenderStateList = schemRenderState->getTemplateSubRenderStateList(); Ogre::RTShader::SubRenderStateListConstIterator it = subRenderStateList.begin(); Ogre::RTShader::SubRenderStateListConstIterator itEnd = subRenderStateList.end(); for (; it != itEnd; ++it) { Ogre::RTShader::SubRenderState* curSubRenderState = *it; // This is the pssm3 sub render state -> remove it. if (curSubRenderState->getType() == Ogre::RTShader::IntegratedPSSM3::Type) { schemRenderState->removeTemplateSubRenderState(*it); break; } } #endif mTrayMgr->moveWidgetToTray(mDirLightCheckBox, TL_TOPLEFT, 1); mTrayMgr->moveWidgetToTray(mPointLightCheckBox, TL_TOPLEFT, 2); mTrayMgr->moveWidgetToTray(mSpotLightCheckBox, TL_TOPLEFT, 3); mDirLightCheckBox->show(); mPointLightCheckBox->show(); mSpotLightCheckBox->show(); } #ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS // Integrated shadow PSSM with 3 splits. else if (menuIndex == 1) { // mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE_INTEGRATED); // // // 3 textures per directional light // mSceneMgr->setShadowTextureCountPerLightType(Ogre::Light::LT_DIRECTIONAL, 3); // mSceneMgr->setShadowTextureSettings(512, 3, PF_FLOAT32_R); // mSceneMgr->setShadowTextureSelfShadow(true); // Leave only directional light. mDirLightCheckBox->setChecked(true); mPointLightCheckBox->setChecked(false); mSpotLightCheckBox->setChecked(false); mTrayMgr->removeWidgetFromTray(mDirLightCheckBox); mTrayMgr->removeWidgetFromTray(mPointLightCheckBox); mTrayMgr->removeWidgetFromTray(mSpotLightCheckBox); mDirLightCheckBox->hide(); mPointLightCheckBox->hide(); mSpotLightCheckBox->hide(); // Set up caster material - this is just a standard depth/shadow map caster mSceneMgr->setShadowTextureCasterMaterial(""PSSM/shadow_caster""); // Disable fog on the caster pass. MaterialPtr passCaterMaterial = MaterialManager::getSingleton().getByName(""PSSM/shadow_caster""); Pass* pssmCasterPass = passCaterMaterial->getTechnique(0)->getPass(0); pssmCasterPass->setFog(true); // shadow camera setup PSSMShadowCameraSetup* pssmSetup = new PSSMShadowCameraSetup(); pssmSetup->calculateSplitPoints(3, 5, 3000); pssmSetup->setSplitPadding(10); pssmSetup->setOptimalAdjustFactor(0, 2); pssmSetup->setOptimalAdjustFactor(1, 1); pssmSetup->setOptimalAdjustFactor(2, 0.5); // mSceneMgr->setShadowCameraSetup(ShadowCameraSetupPtr(pssmSetup)); Ogre::RTShader::SubRenderState* subRenderState = mShaderGenerator->createSubRenderState(Ogre::RTShader::IntegratedPSSM3::Type); Ogre::RTShader::IntegratedPSSM3* pssm3SubRenderState = static_cast(subRenderState); const PSSMShadowCameraSetup::SplitPointList& srcSplitPoints = pssmSetup->getSplitPoints(); Ogre::RTShader::IntegratedPSSM3::SplitPointList dstSplitPoints; for (unsigned int i=0; i < srcSplitPoints.size(); ++i) { dstSplitPoints.push_back(srcSplitPoints[i]); } pssm3SubRenderState->setSplitPoints(dstSplitPoints); schemRenderState->addTemplateSubRenderState(subRenderState); } #endif // Invalidate the scheme in order to re-generate all shaders based technique related to this scheme. mShaderGenerator->invalidateScheme(Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME); } //----------------------------------------------------------------------- void Sample_ShaderSystem::exportRTShaderSystemMaterial(const String& fileName, const String& materialName) { // Grab material pointer. MaterialPtr materialPtr = MaterialManager::getSingleton().getByName(materialName); // Create shader based technique. bool success = mShaderGenerator->createShaderBasedTechnique(materialName, MaterialManager::DEFAULT_SCHEME_NAME, RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME); // Case creation of shader based technique succeeded. if (success) { // Force shader generation of the given material. RTShader::ShaderGenerator::getSingleton().validateMaterial(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME, materialName); // Grab the RTSS material serializer listener. MaterialSerializer::Listener* matRTSSListener = RTShader::ShaderGenerator::getSingleton().getMaterialSerializerListener(); MaterialSerializer matSer; // Add the custom RTSS listener to the serializer. // It will make sure that every custom parameter needed by the RTSS // will be added to the exported material script. matSer.addListener(matRTSSListener); // Simply export the material. matSer.exportMaterial(materialPtr, fileName, false, false, """", materialPtr->getName() + ""_RTSS_Export""); } } //----------------------------------------------------------------------- Ogre::StringVector Sample_ShaderSystem::getRequiredPlugins() { StringVector names; if (!GpuProgramManager::getSingleton().isSyntaxSupported(""glsles"") && !GpuProgramManager::getSingleton().isSyntaxSupported(""glsl"")) names.push_back(""Cg Program Manager""); return names; } //----------------------------------------------------------------------- void Sample_ShaderSystem::testCapabilities( const RenderSystemCapabilities* caps ) { if (!caps->hasCapability(RSC_VERTEX_PROGRAM) || !(caps->hasCapability(RSC_FRAGMENT_PROGRAM))) { OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, ""Your graphics card does not support vertex and fragment programs, "" ""so you cannot run this sample. Sorry!"", ""Sample_ShaderSystem::testCapabilities""); } // Check if D3D10 shader is supported - is so - then we are OK. if (GpuProgramManager::getSingleton().isSyntaxSupported(""ps_4_0"")) { return; } // Check if GLSL type shaders are supported - is so - then we are OK. if (GpuProgramManager::getSingleton().isSyntaxSupported(""glsles"") || GpuProgramManager::getSingleton().isSyntaxSupported(""glsl"")) { return; } if (!GpuProgramManager::getSingleton().isSyntaxSupported(""arbfp1"") && !GpuProgramManager::getSingleton().isSyntaxSupported(""ps_2_0"")) { OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, ""Your card does not support shader model 2, "" ""so you cannot run this sample. Sorry!"", ""Sample_ShaderSystem::testCapabilities""); } } //----------------------------------------------------------------------- void Sample_ShaderSystem::loadResources() { // Create and add the custom reflection map shader extension factory to the shader generator. mReflectionMapFactory = OGRE_NEW ShaderExReflectionMapFactory; mShaderGenerator->addSubRenderStateFactory(mReflectionMapFactory); createPrivateResourceGroup(); } //----------------------------------------------------------------------- void Sample_ShaderSystem::createPrivateResourceGroup() { // Create the resource group of the RT Shader System Sample. ResourceGroupManager& rgm = ResourceGroupManager::getSingleton(); mExportMaterialPath = ""C:/""; rgm.createResourceGroup(SAMPLE_MATERIAL_GROUP, false); rgm.addResourceLocation(mExportMaterialPath, ""FileSystem"", SAMPLE_MATERIAL_GROUP); rgm.initialiseResourceGroup(SAMPLE_MATERIAL_GROUP); rgm.loadResourceGroup(SAMPLE_MATERIAL_GROUP, true); } //----------------------------------------------------------------------- void Sample_ShaderSystem::unloadResources() { destroyPrivateResourceGroup(); mShaderGenerator->removeAllShaderBasedTechniques(""Panels""); mShaderGenerator->removeAllShaderBasedTechniques(""Panels_RTSS_Export""); if (mReflectionMapFactory != NULL) { mShaderGenerator->removeSubRenderStateFactory(mReflectionMapFactory); OGRE_DELETE mReflectionMapFactory; mReflectionMapFactory = NULL; } } //----------------------------------------------------------------------- void Sample_ShaderSystem::destroyPrivateResourceGroup() { // Destroy the resource group of the RT Shader System ResourceGroupManager& rgm = ResourceGroupManager::getSingleton(); rgm.destroyResourceGroup(SAMPLE_MATERIAL_GROUP); } //----------------------------------------------------------------------- void Sample_ShaderSystem::pickTargetObject( const OIS::PointerEvent &evt ) { #ifdef ENABLE_INCOMPATIBLE_OGRE_2_0 int xPos = evt.state.X.abs; int yPos = evt.state.Y.abs; int width = evt.state.width; int height = evt.state.height; Ray mouseRay = mCamera->getCameraToViewportRay(xPos / float(width), yPos/float(height)); mRayQuery->setRay(mouseRay); RaySceneQueryResult &result = mRayQuery->execute(); RaySceneQueryResult::iterator it = result.begin(); RaySceneQueryResult::iterator itEnd = result.end(); for (; it != itEnd; ++it) { RaySceneQueryResultEntry& curEntry = *it; if (mTargetObj != NULL) { mTargetObj->getParentSceneNode()->showBoundingBox(false); } mTargetObj = curEntry.movable; mTargetObj ->getParentSceneNode()->showBoundingBox(true); } #endif } //----------------------------------------------------------------------- void Sample_ShaderSystem::updateTargetObjInfo() { if (mTargetObj == NULL) return; String targetObjMaterialName; if (mTargetObj->getMovableType() == ""Entity"") { Entity* targetEnt = static_cast(mTargetObj); targetObjMaterialName = targetEnt->getSubEntity(0)->getMaterialName(); } mTargetObjMatName->setCaption(targetObjMaterialName); if (mCamera->getLastViewport()->getMaterialScheme() == RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME) { MaterialPtr matMainEnt = MaterialManager::getSingleton().getByName(targetObjMaterialName); if (matMainEnt.isNull() == false) { Technique* shaderGeneratedTech = NULL; for (unsigned int i=0; i < matMainEnt->getNumTechniques(); ++i) { Technique* curTech = matMainEnt->getTechnique(i); if (curTech->getSchemeName() == RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME) { shaderGeneratedTech = curTech; break; } } if (shaderGeneratedTech != NULL) { mTargetObjVS->setCaption(""VS: "" + shaderGeneratedTech->getPass(0)->getVertexProgramName()); mTargetObjFS->setCaption(""FS: "" + shaderGeneratedTech->getPass(0)->getFragmentProgramName()); } } } else { mTargetObjVS->setCaption(""VS: N/A""); mTargetObjFS->setCaption(""FS: N/A""); } } //----------------------------------------------------------------------- void Sample_ShaderSystem::changeTextureLayerBlendMode() { LayeredBlending::BlendMode curBlendMode = mLayerBlendSubRS->getBlendMode(1); LayeredBlending::BlendMode nextBlendMode; // Update the next blend layer mode. if (curBlendMode == LayeredBlending::LB_BlendLuminosity) { nextBlendMode = LayeredBlending::LB_FFPBlend; } else { nextBlendMode = (LayeredBlending::BlendMode)(curBlendMode + 1); } mLayerBlendSubRS->setBlendMode(1, nextBlendMode); mShaderGenerator->invalidateMaterial(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME, ""RTSS/LayeredBlending""); // Update the caption. updateLayerBlendingCaption(nextBlendMode); } //----------------------------------------------------------------------- void Sample_ShaderSystem::updateLayerBlendingCaption( LayeredBlending::BlendMode nextBlendMode ) { switch (nextBlendMode) { case LayeredBlending::LB_FFPBlend: mLayerBlendLabel->setCaption(""FFP Blend""); break; case LayeredBlending::LB_BlendNormal: mLayerBlendLabel->setCaption(""Normal""); break; case LayeredBlending::LB_BlendLighten: mLayerBlendLabel->setCaption(""Lighten""); break; case LayeredBlending::LB_BlendDarken: mLayerBlendLabel->setCaption(""Darken""); break; case LayeredBlending::LB_BlendMultiply: mLayerBlendLabel->setCaption(""Multiply""); break; case LayeredBlending::LB_BlendAverage: mLayerBlendLabel->setCaption(""Average""); break; case LayeredBlending::LB_BlendAdd: mLayerBlendLabel->setCaption(""Add""); break; case LayeredBlending::LB_BlendSubtract: mLayerBlendLabel->setCaption(""Subtract""); break; case LayeredBlending::LB_BlendDifference: mLayerBlendLabel->setCaption(""Difference""); break; case LayeredBlending::LB_BlendNegation: mLayerBlendLabel->setCaption(""Negation""); break; case LayeredBlending::LB_BlendExclusion: mLayerBlendLabel->setCaption(""Exclusion""); break; case LayeredBlending::LB_BlendScreen: mLayerBlendLabel->setCaption(""Screen""); break; case LayeredBlending::LB_BlendOverlay: mLayerBlendLabel->setCaption(""Overlay""); break; case LayeredBlending::LB_BlendSoftLight: mLayerBlendLabel->setCaption(""SoftLight""); break; case LayeredBlending::LB_BlendHardLight: mLayerBlendLabel->setCaption(""HardLight""); break; case LayeredBlending::LB_BlendColorDodge: mLayerBlendLabel->setCaption(""ColorDodge""); break; case LayeredBlending::LB_BlendColorBurn: mLayerBlendLabel->setCaption(""ColorBurn""); break; case LayeredBlending::LB_BlendLinearDodge: mLayerBlendLabel->setCaption(""LinearDodge""); break; case LayeredBlending::LB_BlendLinearBurn: mLayerBlendLabel->setCaption(""LinearBurn""); break; case LayeredBlending::LB_BlendLinearLight: mLayerBlendLabel->setCaption(""LinearLight""); break; case LayeredBlending::LB_BlendVividLight: mLayerBlendLabel->setCaption(""VividLight""); break; case LayeredBlending::LB_BlendPinLight: mLayerBlendLabel->setCaption(""PinLight""); break; case LayeredBlending::LB_BlendHardMix: mLayerBlendLabel->setCaption(""HardMix""); break; case LayeredBlending::LB_BlendReflect: mLayerBlendLabel->setCaption(""Reflect""); break; case LayeredBlending::LB_BlendGlow: mLayerBlendLabel->setCaption(""Glow""); break; case LayeredBlending::LB_BlendPhoenix: mLayerBlendLabel->setCaption(""Phoenix""); break; case LayeredBlending::LB_BlendSaturation: mLayerBlendLabel->setCaption(""Saturation""); break; case LayeredBlending::LB_BlendColor: mLayerBlendLabel->setCaption(""Color""); break; case LayeredBlending::LB_BlendLuminosity: mLayerBlendLabel->setCaption(""Luminosity""); break; default: break; } } //----------------------------------------------------------------------- bool Sample_ShaderSystem::pointerPressed( const OIS::PointerEvent& evt, OIS::MouseButtonID id ) { if (mTrayMgr->injectPointerDown(evt, id)) return true; if (id == OIS::MB_Left) mTrayMgr->hideCursor(); // hide the cursor if user left-clicks in the scene if (id == OIS::MB_Right) pickTargetObject(evt); return true; } //----------------------------------------------------------------------- bool Sample_ShaderSystem::pointerReleased( const OIS::PointerEvent& evt, OIS::MouseButtonID id ) { if (mTrayMgr->injectPointerUp(evt, id)) return true; if (id == OIS::MB_Left) mTrayMgr->showCursor(); // unhide the cursor if user lets go of LMB return true; } //----------------------------------------------------------------------- bool Sample_ShaderSystem::pointerMoved( const OIS::PointerEvent& evt ) { // only rotate the camera if cursor is hidden if (mTrayMgr->isCursorVisible()) mTrayMgr->injectPointerMove(evt); else mCameraMan->injectPointerMove(evt); return true; } //----------------------------------------------------------------------- void Sample_ShaderSystem::destroyInstancedViewports() { if (mInstancedViewportsSubRenderState) { Ogre::RTShader::RenderState* renderState = mShaderGenerator->getRenderState(Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME); renderState->removeTemplateSubRenderState(mInstancedViewportsSubRenderState); mInstancedViewportsSubRenderState = NULL; } if (mRoot->getRenderSystem()->getGlobalInstanceVertexBufferVertexDeclaration() != NULL) { Ogre::HardwareBufferManager::getSingleton().destroyVertexDeclaration( mRoot->getRenderSystem()->getGlobalInstanceVertexBufferVertexDeclaration()); mRoot->getRenderSystem()->setGlobalInstanceVertexBufferVertexDeclaration(NULL); } mRoot->getRenderSystem()->setGlobalNumberOfInstances(1); mRoot->getRenderSystem()->setGlobalInstanceVertexBuffer(Ogre::HardwareVertexBufferSharedPtr() ); mShaderGenerator->invalidateScheme(Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME); mShaderGenerator->validateScheme(Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME); destroyInstancedViewportsFactory(); } //----------------------------------------------------------------------- void Sample_ShaderSystem::destroyInstancedViewportsFactory() { if (mInstancedViewportsFactory != NULL) { mInstancedViewportsFactory->destroyAllInstances(); mShaderGenerator->removeSubRenderStateFactory(mInstancedViewportsFactory); delete mInstancedViewportsFactory; mInstancedViewportsFactory = NULL; } } //----------------------------------------------------------------------- void Sample_ShaderSystem::createInstancedViewports() { if (mInstancedViewportsFactory == NULL) { mInstancedViewportsFactory = OGRE_NEW ShaderExInstancedViewportsFactory; mShaderGenerator->addSubRenderStateFactory(mInstancedViewportsFactory); } Ogre::Vector2 monitorCount(2.0, 2.0); mInstancedViewportsSubRenderState = mShaderGenerator->createSubRenderState(Ogre::RTShader::ShaderExInstancedViewports::Type); Ogre::RTShader::ShaderExInstancedViewports* shaderExInstancedViewports = static_cast(mInstancedViewportsSubRenderState); shaderExInstancedViewports->setMonitorsCount(monitorCount); Ogre::RTShader::RenderState* renderState = mShaderGenerator->getRenderState(Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME); renderState->addTemplateSubRenderState(mInstancedViewportsSubRenderState); Ogre::VertexDeclaration* vertexDeclaration = Ogre::HardwareBufferManager::getSingleton().createVertexDeclaration(); size_t offset = 0; offset = vertexDeclaration->getVertexSize(0); vertexDeclaration->addElement(0, offset, Ogre::VET_FLOAT4, Ogre::VES_TEXTURE_COORDINATES, 3); offset = vertexDeclaration->getVertexSize(0); vertexDeclaration->addElement(0, offset, Ogre::VET_FLOAT4, Ogre::VES_TEXTURE_COORDINATES, 4); offset = vertexDeclaration->getVertexSize(0); vertexDeclaration->addElement(0, offset, Ogre::VET_FLOAT4, Ogre::VES_TEXTURE_COORDINATES, 5); offset = vertexDeclaration->getVertexSize(0); vertexDeclaration->addElement(0, offset, Ogre::VET_FLOAT4, Ogre::VES_TEXTURE_COORDINATES, 6); offset = vertexDeclaration->getVertexSize(0); vertexDeclaration->addElement(0, offset, Ogre::VET_FLOAT4, Ogre::VES_TEXTURE_COORDINATES, 7); Ogre::HardwareVertexBufferSharedPtr vbuf = Ogre::HardwareBufferManager::getSingleton().createVertexBuffer( vertexDeclaration->getVertexSize(0), monitorCount.x * monitorCount.y, Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY); vbuf->setInstanceDataStepRate(1); vbuf->setIsInstanceData(true); float * buf = (float *)vbuf->lock(Ogre::HardwareBuffer::HBL_DISCARD); for (float x = 0 ; x < monitorCount.x ; x++) for (float y = 0 ; y < monitorCount.y ; y++) { *buf = x; buf++; *buf = y; buf++; *buf = 0; buf++; *buf = 0; buf++; Ogre::Quaternion q; Ogre::Radian angle = Ogre::Degree(90 / ( monitorCount.x * monitorCount.y) * (x + y * monitorCount.x) ); q.FromAngleAxis(angle,Ogre::Vector3::UNIT_Y); q.normalise(); Ogre::Matrix3 rotMat; q.ToRotationMatrix(rotMat); *buf = rotMat.GetColumn(0).x; buf++; *buf = rotMat.GetColumn(0).y; buf++; *buf = rotMat.GetColumn(0).z; buf++; *buf = x * -20; buf++; *buf = rotMat.GetColumn(1).x; buf++; *buf = rotMat.GetColumn(1).y; buf++; *buf = rotMat.GetColumn(1).z; buf++; *buf = 0; buf++; *buf = rotMat.GetColumn(2).x; buf++; *buf = rotMat.GetColumn(2).y; buf++; *buf = rotMat.GetColumn(2).z; buf++; *buf = y * 20; buf++; *buf = 0; buf++; *buf = 0; buf++; *buf = 0; buf++; *buf = 1; buf++; } vbuf->unlock(); mRoot->getRenderSystem()->setGlobalInstanceVertexBuffer(vbuf); mRoot->getRenderSystem()->setGlobalInstanceVertexBufferVertexDeclaration(vertexDeclaration); mRoot->getRenderSystem()->setGlobalNumberOfInstances(monitorCount.x * monitorCount.y); // Invalidate the scheme in order to re-generate all shaders based technique related to this scheme. mShaderGenerator->invalidateScheme(Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME); mShaderGenerator->validateScheme(Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME); } void Sample_ShaderSystem::createMaterialForTexture( const String & texName, bool isTextureAtlasTexture ) { MaterialManager * matMgr = MaterialManager::getSingletonPtr(); if ( matMgr->resourceExists(texName) == false ) { MaterialPtr newMat = matMgr->create(texName, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); newMat->getTechnique(0)->getPass(0)->setLightingEnabled(false); TextureUnitState* pState = newMat->getTechnique(0)->getPass(0)->createTextureUnitState(texName); if(isTextureAtlasTexture) { // to solve wrap edge bleed pState->setTextureFiltering(TFO_TRILINEAR); } } } ManualObject* Sample_ShaderSystem::createTextureAtlasObject() { TextureAtlasSamplerFactory * textureAtlasSamplerFactory = static_cast(mShaderGenerator->getSubRenderStateFactory(TextureAtlasSampler::Type)); TextureAtlasTablePtr textureAtlasTable(new TextureAtlasTable); DataStreamPtr taiFile = Ogre::ResourceGroupManager::getSingleton().openResource(""TextureAtlasSampleWrap.tai""); textureAtlasSamplerFactory->addTexutreAtlasDefinition(taiFile, textureAtlasTable); //Generate the geometry that will seed the particle system ManualObject* textureAtlasObject = mSceneMgr->createManualObject(); textureAtlasObject->setName(""TextureAtlasObject""); int sliceSize = 30.0; int wrapSize = 5.0; String curMatName; // create original texture geometry for( size_t i = 0 ; i < textureAtlasTable->size() ; i++ ) { bool changeMat = (curMatName != (*textureAtlasTable)[i].atlasTextureName); if (changeMat) { if (curMatName.empty() == false) // we don't want to end before we begin { textureAtlasObject->end(); } curMatName = (*textureAtlasTable)[i].originalTextureName; createMaterialForTexture(curMatName, false); textureAtlasObject->begin(curMatName, RenderOperation::OT_TRIANGLE_LIST); } // triangle 0 textureAtlasObject->position(i * sliceSize, 0, 0); //Position textureAtlasObject->textureCoord(0,0); //UV textureAtlasObject->position(i * sliceSize, 0, sliceSize); //Position textureAtlasObject->textureCoord(0,wrapSize); //UV textureAtlasObject->position((i + 1) * sliceSize, 0 , sliceSize); //Position textureAtlasObject->textureCoord(wrapSize,wrapSize); //UV // triangle 1 textureAtlasObject->position(i * sliceSize, 0, 0); //Position textureAtlasObject->textureCoord(0,0); //UV textureAtlasObject->position((i + 1) * sliceSize, 0, sliceSize); //Position textureAtlasObject->textureCoord(wrapSize,wrapSize); //UV textureAtlasObject->position((i + 1) * sliceSize, 0, 0); //Position textureAtlasObject->textureCoord(wrapSize, 0); //UV } // create texture atlas geometry for( size_t i = 0 ; i < (*textureAtlasTable).size() ; i++ ) { bool changeMat = (curMatName != (*textureAtlasTable)[i].atlasTextureName); if (changeMat) { if (curMatName.empty() == false) // we don't want to end before we begin { textureAtlasObject->end(); } curMatName = (*textureAtlasTable)[i].atlasTextureName; createMaterialForTexture(curMatName, true); textureAtlasObject->begin(curMatName, RenderOperation::OT_TRIANGLE_LIST); } // triangle 0 textureAtlasObject->position(i * sliceSize, 0, sliceSize); //Position textureAtlasObject->textureCoord(0,0); //UV textureAtlasObject->textureCoord((*textureAtlasTable)[i].indexInAtlas); //Texture ID textureAtlasObject->position(i * sliceSize, 0, sliceSize * 2); //Position textureAtlasObject->textureCoord(0,wrapSize); //UV textureAtlasObject->textureCoord((*textureAtlasTable)[i].indexInAtlas); //Texture ID textureAtlasObject->position((i + 1) * sliceSize, 0 , sliceSize * 2); //Position textureAtlasObject->textureCoord(wrapSize,wrapSize); //UV textureAtlasObject->textureCoord((*textureAtlasTable)[i].indexInAtlas); //Texture ID // triangle 1 textureAtlasObject->position(i * sliceSize, 0, sliceSize); //Position textureAtlasObject->textureCoord(0,0); //UV textureAtlasObject->textureCoord((*textureAtlasTable)[i].indexInAtlas); //Texture ID textureAtlasObject->position((i + 1) * sliceSize, 0, sliceSize * 2); //Position textureAtlasObject->textureCoord(wrapSize,wrapSize); //UV textureAtlasObject->textureCoord((*textureAtlasTable)[i].indexInAtlas); //Texture ID textureAtlasObject->position((i + 1) * sliceSize, 0, sliceSize); //Position textureAtlasObject->textureCoord(wrapSize, 0); //UV textureAtlasObject->textureCoord((*textureAtlasTable)[i].indexInAtlas); //Texture ID } textureAtlasObject->end(); return textureAtlasObject; } ",16219,True,2932.911273719779,median "CLASS /dmo/cl_flight_legacy15 DEFINITION PUBLIC FINAL CREATE PRIVATE GLOBAL FRIENDS /dmo/cl_flight_data_generat_15. PUBLIC SECTION. INTERFACES /dmo/if_flight_legacy15. TYPES: BEGIN OF ENUM ty_change_mode STRUCTURE change_mode,"" Key checks are done separately create, update,"" Only fields that have been changed need to be checked END OF ENUM ty_change_mode STRUCTURE change_mode. CLASS-METHODS: get_instance RETURNING VALUE(ro_instance) TYPE REF TO /dmo/cl_flight_legacy15. "" With respect to the same method call of create/update/delete_travel() we have All or Nothing. "" I.e. when one of the levels contains an error, the complete call is refused. "" However, the buffer is not cleared in case of an error. "" I.e. when the caller wants to start over, he needs to call Initialize() explicitly. METHODS set_status_to_booked IMPORTING iv_travel_id TYPE /dmo/travel_id15 EXPORTING et_messages TYPE /dmo/if_flight_legacy15=>tt_if_t100_message. METHODS create_travel IMPORTING is_travel TYPE /dmo/if_flight_legacy15=>ts_travel_in it_booking TYPE /dmo/if_flight_legacy15=>tt_booking_in OPTIONAL it_booking_supplement TYPE /dmo/if_flight_legacy15=>tt_booking_supplement_in OPTIONAL EXPORTING es_travel TYPE /dmo/travel15 et_booking TYPE /dmo/if_flight_legacy15=>tt_booking et_booking_supplement TYPE /dmo/if_flight_legacy15=>tt_booking_supplement et_messages TYPE /dmo/if_flight_legacy15=>tt_if_t100_message. METHODS update_travel IMPORTING is_travel TYPE /dmo/if_flight_legacy15=>ts_travel_in is_travelx TYPE /dmo/if_flight_legacy15=>ts_travel_inx it_booking TYPE /dmo/if_flight_legacy15=>tt_booking_in OPTIONAL it_bookingx TYPE /dmo/if_flight_legacy15=>tt_booking_inx OPTIONAL it_booking_supplement TYPE /dmo/if_flight_legacy15=>tt_booking_supplement_in OPTIONAL it_booking_supplementx TYPE /dmo/if_flight_legacy15=>tt_booking_supplement_inx OPTIONAL EXPORTING es_travel TYPE /dmo/travel15 et_booking TYPE /dmo/if_flight_legacy15=>tt_booking et_booking_supplement TYPE /dmo/if_flight_legacy15=>tt_booking_supplement et_messages TYPE /dmo/if_flight_legacy15=>tt_if_t100_message. METHODS delete_travel IMPORTING iv_travel_id TYPE /dmo/travel_id15 EXPORTING et_messages TYPE /dmo/if_flight_legacy15=>tt_if_t100_message. METHODS get_travel IMPORTING iv_travel_id TYPE /dmo/travel_id15 iv_include_buffer TYPE abap_boolean iv_include_temp_buffer TYPE abap_boolean OPTIONAL EXPORTING es_travel TYPE /dmo/travel15 et_booking TYPE /dmo/if_flight_legacy15=>tt_booking et_booking_supplement TYPE /dmo/if_flight_legacy15=>tt_booking_supplement et_messages TYPE /dmo/if_flight_legacy15=>tt_if_t100_message. METHODS save. METHODS initialize. METHODS convert_messages IMPORTING it_messages TYPE /dmo/if_flight_legacy15=>tt_if_t100_message EXPORTING et_messages TYPE /dmo/if_flight_legacy15=>tt_message. PROTECTED SECTION. PRIVATE SECTION. CLASS-DATA go_instance TYPE REF TO /dmo/cl_flight_legacy15. CLASS-METHODS: ""! Calculation of Price
""!
""! Price will be calculated using distance multiplied and occupied seats.
""! Depending on how many seats in percentage are occupied the formula
""! 3/400·x² + 25
""! will be applied.
""! 0% seats occupied leads to 25% of distance as price.
""! 75% seats occupied leads to 50% of distance as price.
""! 100% seats occupied leads to 100% of distance as price.
""! @parameter iv_seats_occupied_percent | occupied seats ""! @parameter iv_flight_distance | flight distance in kilometer ""! @parameter rv_price | calculated flight price calculate_flight_price IMPORTING iv_seats_occupied_percent TYPE /dmo/plane_seats_occupied15 iv_flight_distance TYPE i RETURNING VALUE(rv_price) TYPE /dmo/flight_price15 ##RELAX. METHODS lock_travel IMPORTING iv_lock TYPE abap_bool RAISING /dmo/cx_flight_legacy15 ##RELAX ##NEEDED. METHODS _resolve_attribute IMPORTING iv_attrname TYPE scx_attrname ix TYPE REF TO /dmo/cx_flight_legacy15 RETURNING VALUE(rv_symsgv) TYPE symsgv. ""! Final determinations / derivations after all levels have been prepared, e.g. bottom-up derivations METHODS _determine EXPORTING et_messages TYPE /dmo/if_flight_legacy15=>tt_if_t100_message CHANGING cs_travel TYPE /dmo/travel15 ct_booking TYPE /dmo/if_flight_legacy15=>tt_booking ct_booking_supplement TYPE /dmo/if_flight_legacy15=>tt_booking_supplement. METHODS _determine_travel_total_price CHANGING cs_travel TYPE /dmo/travel15 ct_booking TYPE /dmo/if_flight_legacy15=>tt_booking ct_booking_supplement TYPE /dmo/if_flight_legacy15=>tt_booking_supplement ct_messages TYPE /dmo/if_flight_legacy15=>tt_if_t100_message ##NEEDED. METHODS _convert_currency IMPORTING iv_currency_code_source TYPE /dmo/currency_code15 iv_currency_code_target TYPE /dmo/currency_code15 iv_amount TYPE /dmo/total_price15 RETURNING VALUE(rv_amount) TYPE /dmo/total_price15. ENDCLASS. CLASS /dmo/cl_flight_legacy15 IMPLEMENTATION. METHOD calculate_flight_price. DATA: lv_percentage_of_max_price TYPE i. lv_percentage_of_max_price = ( 3 * iv_seats_occupied_percent ** 2 DIV 400 ) + 25 ##OPERATOR[**]. rv_price = lv_percentage_of_max_price * iv_flight_distance DIV 100. ENDMETHOD. METHOD convert_messages. CLEAR et_messages. DATA ls_message TYPE symsg. LOOP AT it_messages INTO DATA(lr_error) ##INTO_OK. ls_message-msgty = 'E'. ls_message-msgid = lr_error->t100key-msgid. ls_message-msgno = lr_error->t100key-msgno. IF lr_error IS INSTANCE OF /dmo/cx_flight_legacy15. DATA(lx) = CAST /dmo/cx_flight_legacy15( lr_error ). ls_message-msgv1 = _resolve_attribute( iv_attrname = lr_error->t100key-attr1 ix = lx ). ls_message-msgv2 = _resolve_attribute( iv_attrname = lr_error->t100key-attr2 ix = lx ). ls_message-msgv3 = _resolve_attribute( iv_attrname = lr_error->t100key-attr3 ix = lx ). ls_message-msgv4 = _resolve_attribute( iv_attrname = lr_error->t100key-attr4 ix = lx ). ENDIF. APPEND ls_message TO et_messages. ENDLOOP. ENDMETHOD. METHOD create_travel. CLEAR: es_travel, et_booking, et_booking_supplement, et_messages. "" Travel lcl_travel_buffer=>get_instance( )->cud_prep( EXPORTING it_travel = VALUE #( ( CORRESPONDING #( is_travel ) ) ) it_travelx = VALUE #( ( travel_id = is_travel-travel_id action_code = /dmo/if_flight_legacy15=>action_code-create ) ) IMPORTING et_travel = DATA(lt_travel) et_messages = et_messages ). IF et_messages IS INITIAL. ASSERT lines( lt_travel ) = 1. es_travel = lt_travel[ 1 ]. ENDIF. "" Bookings IF et_messages IS INITIAL. DATA lt_booking TYPE /dmo/if_flight_legacy15=>tt_booking. DATA lt_bookingx TYPE /dmo/if_flight_legacy15=>tt_bookingx. LOOP AT it_booking INTO DATA(ls_booking_in). DATA ls_booking TYPE /dmo/booking15. ls_booking = CORRESPONDING #( ls_booking_in ). ls_booking-travel_id = es_travel-travel_id. INSERT ls_booking INTO TABLE lt_booking. INSERT VALUE #( travel_id = ls_booking-travel_id booking_id = ls_booking-booking_id action_code = /dmo/if_flight_legacy15=>action_code-create ) INTO TABLE lt_bookingx. ENDLOOP. lcl_booking_buffer=>get_instance( )->cud_prep( EXPORTING it_booking = lt_booking it_bookingx = lt_bookingx IMPORTING et_booking = et_booking et_messages = DATA(lt_messages) ). APPEND LINES OF lt_messages TO et_messages. ENDIF. "" Booking Supplements IF et_messages IS INITIAL. DATA lt_booking_supplement TYPE /dmo/if_flight_legacy15=>tt_booking_supplement. DATA lt_booking_supplementx TYPE /dmo/if_flight_legacy15=>tt_booking_supplementx. LOOP AT it_booking_supplement INTO DATA(ls_booking_supplement_in). DATA ls_booking_supplement TYPE /dmo/book_sup_15. ls_booking_supplement = CORRESPONDING #( ls_booking_supplement_in ). ls_booking_supplement-travel_id = es_travel-travel_id. IF lcl_booking_buffer=>get_instance( )->check_booking_id( EXPORTING iv_travel_id = ls_booking_supplement-travel_id iv_booking_id = ls_booking_supplement-booking_id CHANGING ct_messages = et_messages ) = abap_false. EXIT. ENDIF. INSERT ls_booking_supplement INTO TABLE lt_booking_supplement. INSERT VALUE #( travel_id = ls_booking_supplement-travel_id booking_id = ls_booking_supplement-booking_id booking_supplement_id = ls_booking_supplement-booking_supplement_id action_code = /dmo/if_flight_legacy15=>action_code-create ) INTO TABLE lt_booking_supplementx. ENDLOOP. IF et_messages IS INITIAL. lcl_booking_supplement_buffer=>get_instance( )->cud_prep( EXPORTING it_booking_supplement = lt_booking_supplement it_booking_supplementx = lt_booking_supplementx IMPORTING et_booking_supplement = et_booking_supplement et_messages = lt_messages ). APPEND LINES OF lt_messages TO et_messages. ENDIF. ENDIF. "" Now do any derivations that require the whole business object (not only a single node), but which may in principle result in an error IF et_messages IS INITIAL. _determine( IMPORTING et_messages = et_messages CHANGING cs_travel = es_travel ct_booking = et_booking ct_booking_supplement = et_booking_supplement ). ENDIF. IF et_messages IS INITIAL. lcl_travel_buffer=>get_instance( )->cud_copy( ). lcl_booking_buffer=>get_instance( )->cud_copy( ). lcl_booking_supplement_buffer=>get_instance( )->cud_copy( ). ELSE. CLEAR: es_travel, et_booking, et_booking_supplement. lcl_travel_buffer=>get_instance( )->cud_disc( ). lcl_booking_buffer=>get_instance( )->cud_disc( ). lcl_booking_supplement_buffer=>get_instance( )->cud_disc( ). ENDIF. ENDMETHOD. METHOD delete_travel. CLEAR et_messages. get_travel( EXPORTING iv_travel_id = iv_travel_id iv_include_buffer = abap_true iv_include_temp_buffer = abap_true IMPORTING et_booking = DATA(lt_booking) et_booking_supplement = DATA(lt_booking_supplement) et_messages = et_messages ). IF et_messages IS INITIAL. lcl_booking_supplement_buffer=>get_instance( )->cud_prep( EXPORTING it_booking_supplement = CORRESPONDING #( lt_booking_supplement MAPPING travel_id = travel_id booking_id = booking_id booking_supplement_id = booking_supplement_id EXCEPT * ) it_booking_supplementx = VALUE #( FOR ls_bs IN lt_booking_supplement ( action_code = /dmo/if_flight_legacy15=>action_code-delete travel_id = ls_bs-travel_id booking_id = ls_bs-booking_id booking_supplement_id = ls_bs-booking_supplement_id ) ) iv_no_delete_check = abap_true "" No existence check required IMPORTING et_messages = DATA(lt_messages) ). APPEND LINES OF lt_messages TO et_messages. ENDIF. IF et_messages IS INITIAL. lcl_booking_buffer=>get_instance( )->cud_prep( EXPORTING it_booking = CORRESPONDING #( lt_booking MAPPING travel_id = travel_id booking_id = booking_id EXCEPT * ) it_bookingx = VALUE #( FOR ls_b IN lt_booking ( action_code = /dmo/if_flight_legacy15=>action_code-delete travel_id = ls_b-travel_id booking_id = ls_b-booking_id ) ) iv_no_delete_check = abap_true "" No existence check required IMPORTING et_messages = lt_messages ). APPEND LINES OF lt_messages TO et_messages. ENDIF. IF et_messages IS INITIAL. lcl_travel_buffer=>get_instance( )->cud_prep( EXPORTING it_travel = VALUE #( ( travel_id = iv_travel_id ) ) it_travelx = VALUE #( ( travel_id = iv_travel_id action_code = /dmo/if_flight_legacy15=>action_code-delete ) ) iv_no_delete_check = abap_true "" No existence check required IMPORTING et_messages = lt_messages ). APPEND LINES OF lt_messages TO et_messages. ENDIF. IF et_messages IS INITIAL. lcl_travel_buffer=>get_instance( )->cud_copy( ). lcl_booking_buffer=>get_instance( )->cud_copy( ). lcl_booking_supplement_buffer=>get_instance( )->cud_copy( ). ELSE. lcl_travel_buffer=>get_instance( )->cud_disc( ). lcl_booking_buffer=>get_instance( )->cud_disc( ). lcl_booking_supplement_buffer=>get_instance( )->cud_disc( ). ENDIF. ENDMETHOD. METHOD get_instance. go_instance = COND #( WHEN go_instance IS BOUND THEN go_instance ELSE NEW #( ) ). ro_instance = go_instance. ENDMETHOD. METHOD get_travel. CLEAR: es_travel, et_booking, et_booking_supplement, et_messages. IF iv_travel_id IS INITIAL. APPEND NEW /dmo/cx_flight_legacy15( textid = /dmo/cx_flight_legacy15=>travel_no_key ) TO et_messages. RETURN. ENDIF. lcl_travel_buffer=>get_instance( )->get( EXPORTING it_travel = VALUE #( ( travel_id = iv_travel_id ) ) iv_include_buffer = iv_include_buffer iv_include_temp_buffer = iv_include_temp_buffer IMPORTING et_travel = DATA(lt_travel) ). IF lt_travel IS INITIAL. APPEND NEW /dmo/cx_flight_legacy15( textid = /dmo/cx_flight_legacy15=>travel_unknown travel_id = iv_travel_id ) TO et_messages. RETURN. ENDIF. ASSERT lines( lt_travel ) = 1. es_travel = lt_travel[ 1 ]. lcl_booking_buffer=>get_instance( )->get( EXPORTING it_booking = VALUE #( ( travel_id = iv_travel_id ) ) iv_include_buffer = iv_include_buffer iv_include_temp_buffer = iv_include_temp_buffer IMPORTING et_booking = et_booking ). lcl_booking_supplement_buffer=>get_instance( )->get( EXPORTING it_booking_supplement = CORRESPONDING #( et_booking MAPPING travel_id = travel_id booking_id = booking_id EXCEPT * ) iv_include_buffer = iv_include_buffer iv_include_temp_buffer = iv_include_temp_buffer IMPORTING et_booking_supplement = et_booking_supplement ). ENDMETHOD. METHOD initialize. lcl_travel_buffer=>get_instance( )->initialize( ). lcl_booking_buffer=>get_instance( )->initialize( ). lcl_booking_supplement_buffer=>get_instance( )->initialize( ). ENDMETHOD. METHOD lock_travel ##NEEDED. * IF iv_lock = abap_true. * CALL FUNCTION 'ENQUEUE_/DMO/ETRAVEL15' * EXCEPTIONS * foreign_lock = 1 * system_failure = 2 * OTHERS = 3. * IF sy-subrc <> 0. * RAISE EXCEPTION TYPE /dmo/cx_flight_legacy15 * EXPORTING * textid = /dmo/cx_flight_legacy15=>travel_lock. * ENDIF. * ELSE. * CALL FUNCTION 'DEQUEUE_/DMO/ETRAVEL15'. * ENDIF. ENDMETHOD. METHOD save. lcl_travel_buffer=>get_instance( )->save( ). lcl_booking_buffer=>get_instance( )->save( ). lcl_booking_supplement_buffer=>get_instance( )->save( ). initialize( ). ENDMETHOD. METHOD set_status_to_booked. lcl_travel_buffer=>get_instance( )->set_status_to_booked( EXPORTING iv_travel_id = iv_travel_id IMPORTING et_messages = et_messages ). ENDMETHOD. METHOD update_travel. CLEAR es_travel. CLEAR et_booking. CLEAR et_booking_supplement. CLEAR et_messages. "" Travel IF is_travel-travel_id IS INITIAL. APPEND NEW /dmo/cx_flight_legacy15( textid = /dmo/cx_flight_legacy15=>travel_no_key ) TO et_messages. RETURN. ENDIF. DATA ls_travelx TYPE /dmo/if_flight_legacy15=>ts_travelx. ls_travelx = CORRESPONDING #( is_travelx ). ls_travelx-action_code = /dmo/if_flight_legacy15=>action_code-update. lcl_travel_buffer=>get_instance( )->cud_prep( EXPORTING it_travel = VALUE #( ( CORRESPONDING #( is_travel ) ) ) it_travelx = VALUE #( ( ls_travelx ) ) IMPORTING et_travel = DATA(lt_travel) et_messages = et_messages ). "" We may need to delete Booking Supplements of deleted Bookings "" Read all Booking Supplements before any Bookings are deleted get_travel( EXPORTING iv_travel_id = is_travel-travel_id iv_include_buffer = abap_true iv_include_temp_buffer = abap_true IMPORTING et_booking_supplement = DATA(lt_booking_supplement_del) ). "" Bookings IF et_messages IS INITIAL. "" Ignore provided Travel ID of subnode tables DATA lt_booking TYPE /dmo/if_flight_legacy15=>tt_booking. DATA lt_bookingx TYPE /dmo/if_flight_legacy15=>tt_bookingx. LOOP AT it_booking INTO DATA(ls_booking_in). DATA ls_booking TYPE /dmo/booking15. ls_booking = CORRESPONDING #( ls_booking_in ). ls_booking-travel_id = is_travel-travel_id. INSERT ls_booking INTO TABLE lt_booking. ENDLOOP. LOOP AT it_bookingx INTO DATA(ls_booking_inx). DATA ls_bookingx TYPE /dmo/if_flight_legacy15=>ts_bookingx. ls_bookingx = CORRESPONDING #( ls_booking_inx ). ls_bookingx-travel_id = is_travel-travel_id. INSERT ls_bookingx INTO TABLE lt_bookingx. ENDLOOP. lcl_booking_buffer=>get_instance( )->cud_prep( EXPORTING it_booking = lt_booking it_bookingx = lt_bookingx IMPORTING et_booking = et_booking et_messages = DATA(lt_messages) ). APPEND LINES OF lt_messages TO et_messages. ENDIF. "" Booking Supplements IF et_messages IS INITIAL. "" Ignore provided Travel ID of subnode tables DATA lt_booking_supplement TYPE /dmo/if_flight_legacy15=>tt_booking_supplement. DATA lt_booking_supplementx TYPE /dmo/if_flight_legacy15=>tt_booking_supplementx. LOOP AT it_booking_supplement INTO DATA(ls_booking_supplement_in). DATA ls_booking_supplement TYPE /dmo/book_sup_15. ls_booking_supplement = CORRESPONDING #( ls_booking_supplement_in ). ls_booking_supplement-travel_id = is_travel-travel_id. IF lcl_booking_buffer=>get_instance( )->check_booking_id( EXPORTING iv_travel_id = ls_booking_supplement-travel_id iv_booking_id = ls_booking_supplement-booking_id CHANGING ct_messages = et_messages ) = abap_false. EXIT. ENDIF. INSERT ls_booking_supplement INTO TABLE lt_booking_supplement. ENDLOOP. IF et_messages IS INITIAL. LOOP AT it_booking_supplementx INTO DATA(ls_booking_supplement_inx). DATA ls_booking_supplementx TYPE /dmo/if_flight_legacy15=>ts_booking_supplementx. ls_booking_supplementx = CORRESPONDING #( ls_booking_supplement_inx ). ls_booking_supplementx-travel_id = is_travel-travel_id. INSERT ls_booking_supplementx INTO TABLE lt_booking_supplementx. ENDLOOP. lcl_booking_supplement_buffer=>get_instance( )->cud_prep( EXPORTING it_booking_supplement = lt_booking_supplement it_booking_supplementx = lt_booking_supplementx IMPORTING et_booking_supplement = et_booking_supplement et_messages = lt_messages ). APPEND LINES OF lt_messages TO et_messages. ENDIF. ENDIF. "" For Bookings to be deleted we also need to delete the Booking Supplements IF et_messages IS INITIAL AND lt_booking_supplement_del IS NOT INITIAL AND line_exists( lt_bookingx[ action_code = CONV /dmo/action_code15( /dmo/if_flight_legacy15=>action_code-delete ) ] ). "" Remove any Bookings from internal table that must not be deleted LOOP AT lt_booking_supplement_del ASSIGNING FIELD-SYMBOL(). READ TABLE lt_bookingx TRANSPORTING NO FIELDS WITH KEY action_code = CONV /dmo/action_code15( /dmo/if_flight_legacy15=>action_code-delete ) travel_id = -travel_id booking_id = -booking_id. IF sy-subrc <> 0. DELETE lt_booking_supplement_del. ENDIF. ENDLOOP. lcl_booking_supplement_buffer=>get_instance( )->cud_prep( EXPORTING it_booking_supplement = CORRESPONDING #( lt_booking_supplement_del MAPPING travel_id = travel_id booking_id = booking_id booking_supplement_id = booking_supplement_id EXCEPT * ) it_booking_supplementx = VALUE #( FOR ls_bs IN lt_booking_supplement_del ( action_code = /dmo/if_flight_legacy15=>action_code-delete travel_id = ls_bs-travel_id booking_id = ls_bs-booking_id booking_supplement_id = ls_bs-booking_supplement_id ) ) iv_no_delete_check = abap_true "" No existence check required IMPORTING et_messages = et_messages ). ENDIF. IF et_messages IS INITIAL. ASSERT lines( lt_travel ) = 1. "" Now do any derivations that require the whole business object (not only a single node), but which may in principle result in an error "" The derivation may need the complete Business Object, i.e. including unchanged subnodes get_travel( EXPORTING iv_travel_id = lt_travel[ 1 ]-travel_id iv_include_buffer = abap_true iv_include_temp_buffer = abap_true IMPORTING es_travel = es_travel et_booking = et_booking et_booking_supplement = et_booking_supplement et_messages = et_messages ). ASSERT et_messages IS INITIAL. _determine( IMPORTING et_messages = et_messages CHANGING cs_travel = es_travel ct_booking = et_booking ct_booking_supplement = et_booking_supplement ). IF et_messages IS INITIAL. "" We do not want to return all subnodes, but only those that have been created or changed. "" So currently it is not implemented that a determination of a booking changes another booking as the other booking cannot be properly returned. LOOP AT et_booking ASSIGNING FIELD-SYMBOL(). LOOP AT it_bookingx TRANSPORTING NO FIELDS WHERE booking_id = -booking_id AND ( action_code = CONV /dmo/action_code15( /dmo/if_flight_legacy15=>action_code-create ) OR action_code = CONV /dmo/action_code15( /dmo/if_flight_legacy15=>action_code-update ) ). EXIT. ENDLOOP. IF sy-subrc <> 0. DELETE et_booking. ENDIF. ENDLOOP. LOOP AT et_booking_supplement ASSIGNING FIELD-SYMBOL(). LOOP AT it_booking_supplementx TRANSPORTING NO FIELDS WHERE booking_id = -booking_id AND booking_supplement_id = -booking_supplement_id AND ( action_code = CONV /dmo/action_code15( /dmo/if_flight_legacy15=>action_code-create ) OR action_code = CONV /dmo/action_code15( /dmo/if_flight_legacy15=>action_code-update ) ). EXIT. ENDLOOP. IF sy-subrc <> 0. DELETE et_booking_supplement. ENDIF. ENDLOOP. ENDIF. ENDIF. IF et_messages IS INITIAL. lcl_travel_buffer=>get_instance( )->cud_copy( ). lcl_booking_buffer=>get_instance( )->cud_copy( ). lcl_booking_supplement_buffer=>get_instance( )->cud_copy( ). ELSE. CLEAR: es_travel, et_booking, et_booking_supplement. lcl_travel_buffer=>get_instance( )->cud_disc( ). lcl_booking_buffer=>get_instance( )->cud_disc( ). lcl_booking_supplement_buffer=>get_instance( )->cud_disc( ). ENDIF. ENDMETHOD. METHOD _convert_currency. DATA(lv_exchange_rate_date) = cl_abap_context_info=>get_system_date( )."" Do not buffer: Current date may change during lifetime of session /dmo/cl_flight_amdp15=>convert_currency( EXPORTING iv_amount = iv_amount iv_currency_code_source = iv_currency_code_source iv_currency_code_target = iv_currency_code_target iv_exchange_rate_date = lv_exchange_rate_date IMPORTING ev_amount = rv_amount ). ENDMETHOD. METHOD _determine. ASSERT cs_travel-travel_id IS NOT INITIAL. LOOP AT ct_booking TRANSPORTING NO FIELDS WHERE travel_id <> cs_travel-travel_id. EXIT. ENDLOOP. ASSERT sy-subrc = 4. LOOP AT ct_booking_supplement TRANSPORTING NO FIELDS WHERE travel_id <> cs_travel-travel_id. EXIT. ENDLOOP. ASSERT sy-subrc = 4. CLEAR et_messages. _determine_travel_total_price( CHANGING cs_travel = cs_travel ct_booking = ct_booking ct_booking_supplement = ct_booking_supplement ct_messages = et_messages ). ENDMETHOD. METHOD _determine_travel_total_price. DATA lv_add TYPE /dmo/total_price15. DATA(lv_currency_code_target) = cs_travel-currency_code. "" If we do not have a Travel Currency Code yet, "" we may derive it when all the subnodes have the same non-initial Currency Code IF lv_currency_code_target IS INITIAL. DATA lv_ok TYPE abap_bool. lv_ok = abap_true. LOOP AT ct_booking ASSIGNING FIELD-SYMBOL(). IF sy-tabix = 1. lv_currency_code_target = -currency_code. ENDIF. IF -currency_code IS INITIAL. lv_ok = abap_false. EXIT. ENDIF. IF lv_currency_code_target <> -currency_code. lv_ok = abap_false. EXIT. ENDIF. ENDLOOP. IF lv_ok = abap_true. LOOP AT ct_booking_supplement ASSIGNING FIELD-SYMBOL(). IF -currency_code IS INITIAL. lv_ok = abap_false. EXIT. ENDIF. IF lv_currency_code_target <> -currency_code. lv_ok = abap_false. EXIT. ENDIF. ENDLOOP. ENDIF. ENDIF. IF lv_currency_code_target IS NOT INITIAL. "" Total Price = Booking Fee + Booking Flight Prices + Booking Supplement Prices cs_travel-total_price = cs_travel-booking_fee. cs_travel-currency_code = lv_currency_code_target. LOOP AT ct_booking ASSIGNING GROUP BY -currency_code INTO DATA(booking_currency_code). lv_add = REDUCE #( INIT sum = 0 FOR b IN GROUP booking_currency_code NEXT sum = sum + b-flight_price ). IF booking_currency_code <> lv_currency_code_target. lv_add = _convert_currency( iv_currency_code_source = booking_currency_code iv_currency_code_target = lv_currency_code_target iv_amount = lv_add ). ENDIF. cs_travel-total_price = cs_travel-total_price + lv_add. ENDLOOP. LOOP AT ct_booking_supplement ASSIGNING GROUP BY -currency_code INTO DATA(supplement_currency_code). lv_add = REDUCE #( INIT sum = 0 FOR s IN GROUP supplement_currency_code NEXT sum = sum + s-price ). IF supplement_currency_code <> lv_currency_code_target. lv_add = _convert_currency( iv_currency_code_source = supplement_currency_code iv_currency_code_target = lv_currency_code_target iv_amount = lv_add ). ENDIF. cs_travel-total_price = cs_travel-total_price + lv_add. ENDLOOP. lcl_travel_buffer=>get_instance( )->cud_prep( EXPORTING it_travel = VALUE #( ( travel_id = cs_travel-travel_id total_price = cs_travel-total_price currency_code = cs_travel-currency_code ) ) it_travelx = VALUE #( ( action_code = /dmo/if_flight_legacy15=>action_code-update travel_id = cs_travel-travel_id total_price = abap_true currency_code = abap_true ) ) IMPORTING et_messages = DATA(lt_messages) ). ASSERT lt_messages IS INITIAL. ENDIF. ENDMETHOD. METHOD _resolve_attribute. CLEAR rv_symsgv. CASE iv_attrname. WHEN ''. rv_symsgv = ''. WHEN 'MV_TRAVEL_ID'. rv_symsgv = |{ ix->mv_travel_id ALPHA = OUT }|. WHEN 'MV_BOOKING_ID'. rv_symsgv = |{ ix->mv_booking_id ALPHA = OUT }|. WHEN 'MV_BOOKING_SUPPLEMENT_ID'. rv_symsgv = |{ ix->mv_booking_supplement_id ALPHA = OUT }|. WHEN 'MV_AGENCY_ID'. rv_symsgv = |{ ix->mv_agency_id ALPHA = OUT }|. WHEN 'MV_CUSTOMER_ID'. rv_symsgv = |{ ix->mv_customer_id ALPHA = OUT }|. WHEN 'MV_CARRIER_ID'. rv_symsgv = |{ ix->mv_carrier_id ALPHA = OUT }|. WHEN 'MV_CONNECTION_ID'. rv_symsgv = |{ ix->mv_connection_id ALPHA = OUT }|. WHEN 'MV_SUPPLEMENT_ID'. rv_symsgv = ix->mv_supplement_id. WHEN 'MV_BEGIN_DATE'. rv_symsgv = |{ ix->mv_begin_date DATE = USER }|. WHEN 'MV_END_DATE'. rv_symsgv = |{ ix->mv_end_date DATE = USER }|. WHEN 'MV_BOOKING_DATE'. rv_symsgv = |{ ix->mv_booking_date DATE = USER }|. WHEN 'MV_FLIGHT_DATE'. rv_symsgv = |{ ix->mv_flight_date DATE = USER }|. WHEN 'MV_STATUS'. rv_symsgv = ix->mv_status. WHEN 'MV_CURRENCY_CODE'. rv_symsgv = ix->mv_currency_code. WHEN 'MV_UNAME'. rv_symsgv = ix->mv_uname. WHEN OTHERS. ASSERT 1 = 2. ENDCASE. ENDMETHOD. ENDCLASS. ",7461,False,1556.6094573883104,median """!

Converter for JavaScript Literals

CLASS /gal/javascript_converter DEFINITION PUBLIC FINAL CREATE PUBLIC. PUBLIC SECTION. TYPE-POOLS: abap. DATA: ""!

String delimiter

string_delimiter TYPE c VALUE '""'. ""#EC NOTEXT METHODS: ""!

Conversion: Boolean -> JavaScript

""! ""! @parameter input |

Value to convert

""! @parameter output |

Converted value

boolean_to_javascript IMPORTING !input TYPE abap_bool RETURNING VALUE(output) TYPE string, ""!

Conversion: Date -> JavaScript

""! ""! @parameter input |

Value to convert

""! @parameter output |

Converted value

date_to_javascript IMPORTING !input TYPE d RETURNING VALUE(output) TYPE string, ""!

Conversion: JavaScript -> Boolean

""! ""! @parameter input |

Value to convert

""! @parameter output |

Converted value

javascript_to_boolean IMPORTING !input TYPE string RETURNING VALUE(output) TYPE abap_bool, ""!

Conversion: JavaScript -> Date

""! ""! @parameter input |

Value to convert

""! @parameter output |

Converted value

""! @raising /gal/cx_json_exception |

Conversion error

javascript_to_date IMPORTING !input TYPE string RETURNING VALUE(output) TYPE d RAISING /gal/cx_json_exception, ""!

Conversion: JavaScript -> Number

""! ""! @parameter input |

Value to convert

""! @parameter output |

Converted value

javascript_to_number IMPORTING !input TYPE string RETURNING VALUE(output) TYPE /gal/javascript_number, ""!

Conversion: JavaScript -> String

""! ""! @parameter input |

Value to convert

""! @parameter output |

Converted value

javascript_to_string IMPORTING !input TYPE string RETURNING VALUE(output) TYPE string, ""!

Conversion: JavaScript -> Time

""! ""! @parameter input |

Value to convert

""! @parameter output |

Converted value

""! @raising /gal/cx_json_exception |

Conversion error

javascript_to_time IMPORTING !input TYPE string RETURNING VALUE(output) TYPE t RAISING /gal/cx_json_exception, ""!

Conversion: JavaScript -> Timestamp

""! ""! @parameter input |

Value to convert

""! @parameter output |

Converted value

""! @raising /gal/cx_json_exception |

Conversion error

javascript_to_timestamp IMPORTING !input TYPE string RETURNING VALUE(output) TYPE timestampl RAISING /gal/cx_json_exception, ""!

Conversion: Integer -> JavaScript

""! ""! @parameter input |

Value to convert

""! @parameter output |

Converted value

number_to_javascript IMPORTING !input TYPE numeric RETURNING VALUE(output) TYPE string, ""!

Conversion: String -> JavaScript

""! ""! @parameter input |

Value to convert

""! @parameter output |

Converted value

string_to_javascript IMPORTING !input TYPE csequence RETURNING VALUE(output) TYPE string, ""!

Conversion: Time -> JavaScript

""! ""! @parameter input |

Value to convert

""! @parameter output |

Converted value

time_to_javascript IMPORTING !input TYPE t RETURNING VALUE(output) TYPE string, ""!

Conversion: Timestamp -> JavaScript

""! ""! @parameter input |

Value to convert

""! @parameter output |

Converted value

timestamp_to_javascript IMPORTING !input TYPE numeric RETURNING VALUE(output) TYPE string. PROTECTED SECTION. PRIVATE SECTION. ENDCLASS. CLASS /GAL/JAVASCRIPT_CONVERTER IMPLEMENTATION. METHOD boolean_to_javascript. IF input CA 'XYJ1'. output = /gal/javascript_constants=>true. ELSE. output = /gal/javascript_constants=>false. ENDIF. ENDMETHOD. METHOD date_to_javascript. CONCATENATE string_delimiter input(4) '-' input+4(2) '-' input+6(2) string_delimiter INTO output. ENDMETHOD. METHOD javascript_to_boolean. IF input = /gal/javascript_constants=>true. output = abap_true. ELSE. output = abap_false. ENDIF. ENDMETHOD. METHOD javascript_to_date. DATA: l_length TYPE i, l_input TYPE string. l_length = strlen( input ). IF l_length > 2 AND input(1) CA '''""'. l_input = javascript_to_string( input ). l_length = strlen( l_input ). ELSE. l_input = input. ENDIF. IF l_length = 10 AND l_input+4(1) = '-' AND l_input+7(1) = '-' AND l_input(4) CO '0123456789' AND l_input+5(2) CO '0123456789' AND l_input+8(2) CO '0123456789'. output(4) = l_input(4). output+4(2) = l_input+5(2). output+6(2) = l_input+8(2). CALL FUNCTION 'DATE_CHECK_PLAUSIBILITY' EXPORTING date = output EXCEPTIONS OTHERS = 1. IF sy-subrc = 0. RETURN. ENDIF. ENDIF. RAISE EXCEPTION TYPE /gal/cx_json_exception EXPORTING textid = /gal/cx_json_exception=>conv_format_error_date var1 = input. ENDMETHOD. METHOD javascript_to_number. output = input. ENDMETHOD. METHOD javascript_to_string. CONSTANTS lc_hex_chars TYPE string VALUE `0123456789abcdefABCDEF`. ""#EC NOTEXT CONSTANTS lc_oct_chars TYPE string VALUE `01234567`. ""#EC NOTEXT DATA l_offset TYPE i. DATA l_length TYPE i. DATA l_temp_offset TYPE i. DATA l_unicode_i TYPE i. DATA l_unicode_hex_c(4) TYPE c. DATA l_unicode_hex_x(2) TYPE x. DATA l_unicode_char TYPE c. DATA l_unicode_oct_c(3) TYPE c. * Check if there is something to convert IF input IS INITIAL. RETURN. ENDIF. * Remove quotes l_offset = strlen( input ) - 1. IF l_offset > 0 AND input(1) CA `'""` AND input+l_offset(1) = input(1). l_offset = 1. l_length = strlen( input ) - 2. ELSE. l_offset = 0. l_length = strlen( input ). ENDIF. * Replace special characters WHILE l_length > 1 AND input+l_offset CA '\\'. CONCATENATE output input+l_offset(sy-fdpos) INTO output RESPECTING BLANKS. l_offset = l_offset + sy-fdpos. l_length = l_length - sy-fdpos. CASE input+l_offset(2). WHEN '\\\\' OR '\\""' OR '\\'''. l_offset = l_offset + 1. CONCATENATE output input+l_offset(1) INTO output RESPECTING BLANKS. l_offset = l_offset + 1. l_length = l_length - 2. WHEN '\\v'. CONCATENATE output cl_abap_char_utilities=>vertical_tab INTO output RESPECTING BLANKS. l_offset = l_offset + 2. l_length = l_length - 2. WHEN '\\r'. CONCATENATE output cl_abap_char_utilities=>cr_lf(1) INTO output RESPECTING BLANKS. l_offset = l_offset + 2. l_length = l_length - 2. WHEN '\\t'. CONCATENATE output cl_abap_char_utilities=>horizontal_tab INTO output RESPECTING BLANKS. l_offset = l_offset + 2. l_length = l_length - 2. WHEN '\\n'. CONCATENATE output cl_abap_char_utilities=>newline INTO output RESPECTING BLANKS. l_offset = l_offset + 2. l_length = l_length - 2. WHEN '\\f'. CONCATENATE output cl_abap_char_utilities=>form_feed INTO output RESPECTING BLANKS. l_offset = l_offset + 2. l_length = l_length - 2. WHEN '\\b'. CONCATENATE output cl_abap_char_utilities=>backspace INTO output RESPECTING BLANKS. l_offset = l_offset + 2. l_length = l_length - 2. WHEN '\\u'. l_temp_offset = l_offset + 2. IF l_length >= 6 AND input+l_temp_offset(4) CO lc_hex_chars. l_unicode_hex_c = input+l_temp_offset(4). TRANSLATE l_unicode_hex_c TO UPPER CASE. l_unicode_hex_x = l_unicode_hex_c. l_unicode_char = cl_abap_conv_in_ce=>uccp( l_unicode_hex_x ). CONCATENATE output l_unicode_char INTO output RESPECTING BLANKS. l_offset = l_offset + 6. l_length = l_length - 6. ELSE. CONCATENATE output input+l_offset(2) INTO output RESPECTING BLANKS. l_offset = l_offset + 2. l_length = l_length - 2. ENDIF. WHEN '\\x'. l_temp_offset = l_offset + 2. IF l_length >= 4 AND input+l_temp_offset(2) CO lc_hex_chars. CONCATENATE '00' input+l_temp_offset(2) INTO l_unicode_hex_c. TRANSLATE l_unicode_hex_c TO UPPER CASE. l_unicode_hex_x = l_unicode_hex_c. l_unicode_char = cl_abap_conv_in_ce=>uccp( l_unicode_hex_x ). CONCATENATE output l_unicode_char INTO output RESPECTING BLANKS. l_offset = l_offset + 4. l_length = l_length - 4. ELSE. CONCATENATE output input+l_offset(2) INTO output RESPECTING BLANKS. l_offset = l_offset + 2. l_length = l_length - 2. ENDIF. WHEN '\\0' OR '\\1' OR '\\2' OR '\\3' OR '\\4' OR '\\5' OR '\\6' OR '\\7'. l_temp_offset = l_offset + 1. IF l_length >= 4 AND input+l_temp_offset(3) CO lc_oct_chars AND input+l_temp_offset(3) <= '377'. l_unicode_oct_c = input+l_temp_offset(3). l_unicode_i = l_unicode_oct_c(1) * 64 + l_unicode_oct_c+1(1) * 8 + l_unicode_oct_c+2(1). l_unicode_hex_x = l_unicode_i. l_unicode_char = cl_abap_conv_in_ce=>uccp( l_unicode_hex_x ). CONCATENATE output l_unicode_char INTO output RESPECTING BLANKS. l_offset = l_offset + 4. l_length = l_length - 4. ELSEIF l_length >= 3 AND input+l_temp_offset(2) CO lc_oct_chars. l_unicode_oct_c = input+l_temp_offset(2). l_unicode_i = l_unicode_oct_c(1) * 8 + l_unicode_oct_c+1(1). l_unicode_hex_x = l_unicode_i. l_unicode_char = cl_abap_conv_in_ce=>uccp( l_unicode_hex_x ). CONCATENATE output l_unicode_char INTO output RESPECTING BLANKS. l_offset = l_offset + 3. l_length = l_length - 3. ELSEIF l_length >= 2 AND input+l_temp_offset(1) CO lc_oct_chars. l_unicode_oct_c = input+l_temp_offset(1). l_unicode_i = l_unicode_oct_c(1). l_unicode_hex_x = l_unicode_i. l_unicode_char = cl_abap_conv_in_ce=>uccp( l_unicode_hex_x ). CONCATENATE output l_unicode_char INTO output RESPECTING BLANKS. l_offset = l_offset + 2. l_length = l_length - 2. ELSE. CONCATENATE output input+l_offset(2) INTO output RESPECTING BLANKS. l_offset = l_offset + 2. l_length = l_length - 2. ENDIF. WHEN OTHERS. CONCATENATE output input+l_offset(2) INTO output RESPECTING BLANKS. l_offset = l_offset + 2. l_length = l_length - 2. ENDCASE. ENDWHILE. * Add Remaining part of string to output IF l_length > 0. CONCATENATE output input+l_offset(l_length) INTO output RESPECTING BLANKS. ENDIF. ENDMETHOD. METHOD javascript_to_time. DATA: l_length TYPE i, l_input TYPE string, l_hours(2) TYPE n, l_minutes(2) TYPE n, l_seconds(2) TYPE n. l_length = strlen( input ). IF l_length > 2 AND input(1) CA '''""'. l_input = javascript_to_string( input ). l_length = strlen( l_input ). ELSE. l_input = input. ENDIF. IF l_length = 8 AND l_input+2(1) = ':' AND l_input+5(1) = ':' AND l_input(2) CO '0123456789' AND l_input+3(2) CO '0123456789' AND l_input+6(2) CO '0123456789'. l_hours = l_input(2). l_minutes = l_input+3(2). l_seconds = l_input+6(2). IF l_hours < '24' AND l_minutes < '60' AND l_seconds < '60'. output(2) = l_hours. output+2(2) = l_minutes. output+4(2) = l_seconds. RETURN. ENDIF. ENDIF. RAISE EXCEPTION TYPE /gal/cx_json_exception EXPORTING textid = /gal/cx_json_exception=>conv_format_error_time var1 = input. ENDMETHOD. METHOD javascript_to_timestamp. DATA: l_length TYPE i, l_offset TYPE i, l_input TYPE string, l_date_str TYPE string, l_date TYPE d, l_time_str TYPE string, l_time TYPE t, l_fract_str TYPE string, l_fract TYPE timestampl, l_tzone_str TYPE string, l_offset_hours TYPE i, l_offset_minutes TYPE i, l_offset_seconds TYPE i, l_timestamp TYPE timestampl, l_timestamp_obj TYPE REF TO /gal/timestamp_long, l_js_time TYPE string, l_dummy TYPE string. ""#EC NEEDED * Get string length and content l_length = strlen( input ). IF l_length > 2 AND input(1) CA '''""'. l_input = javascript_to_string( input ). l_length = strlen( l_input ). ELSE. l_input = input. ENDIF. IF l_length >= 19 AND ""#EC NUMBER_OK l_input+4(1) = '-' AND l_input+7(1) = '-' AND l_input+10(1) = 'T' AND l_input+13(1) = ':' AND l_input+16(1) = ':' AND l_input(4) CO '0123456789' AND l_input+5(2) CO '0123456789' AND l_input+8(2) CO '0123456789' AND l_input+11(2) CO '0123456789' AND l_input+14(2) CO '0123456789' AND l_input+17(2) CO '0123456789'. l_date_str = l_input(10). l_date = javascript_to_date( l_date_str ). l_time_str = l_input+11(8). l_time = javascript_to_time( l_time_str ). IF l_length > 20 AND l_input+19(1) CA '.,' AND l_input+20(1) CO '0123456789'. ""#EC NUMBER_OK IF l_input+20 CN '0123456789'. l_offset = 20 + sy-fdpos. ""#EC NUMBER_OK l_fract_str = l_input+20(sy-fdpos). l_tzone_str = l_input+l_offset. ELSE. l_fract_str = l_input+20. ENDIF. CONCATENATE '0.' l_fract_str INTO l_fract_str. l_fract = l_fract_str. ENDIF. ELSEIF l_input CP 'DATE(+*)' OR l_input CP '/DATE(+*)/' OR l_input CP '\\/DATE(+*)\\/' OR l_input CP 'NEW DATE(+*)'. SPLIT l_input AT '(' INTO l_dummy l_js_time. SPLIT l_js_time AT ')' INTO l_js_time l_dummy. IF l_js_time CN '0123456789' AND sy-fdpos > 0. l_tzone_str = l_js_time+sy-fdpos. l_js_time = l_js_time(sy-fdpos). ENDIF. IF l_js_time CO '0123456789'. l_date = '19700101'. l_time = '000000'. l_fract = frac( l_js_time / 1000 ). l_offset_seconds = trunc( l_js_time / 1000 ). ELSE. RAISE EXCEPTION TYPE /gal/cx_json_exception EXPORTING textid = /gal/cx_json_exception=>conv_format_error_timestamp var1 = input. ENDIF. ENDIF. * Convert date, time and time zone to timestamp IF l_date IS NOT INITIAL. CONVERT DATE l_date TIME l_time INTO TIME STAMP l_timestamp TIME ZONE /gal/timestamp_base=>time_zone_utc. l_timestamp = l_timestamp + l_fract. * Parse time zone offset IF l_tzone_str IS NOT INITIAL AND l_tzone_str <> `Z`. IF l_tzone_str(1) CA '+-' AND l_tzone_str CP '+++' AND l_tzone_str+1(2) CO '0123456789'. l_offset_hours = l_tzone_str+1(2). ELSEIF l_tzone_str(1) CA '+-' AND l_tzone_str CP '+++:++' AND l_tzone_str+1(2) CO '0123456789' AND l_tzone_str+4(2) CO '0123456789'. l_offset_hours = l_tzone_str+1(2). l_offset_minutes = l_tzone_str+4(2). ELSE. RAISE EXCEPTION TYPE /gal/cx_json_exception EXPORTING textid = /gal/cx_json_exception=>conv_format_error_timestamp var1 = input. ENDIF. IF l_tzone_str(1) = '+'. l_offset_hours = - l_offset_hours. l_offset_minutes = - l_offset_minutes. ENDIF. ENDIF. * Apply offset to timestamp IF l_offset_hours <> 0 OR l_offset_minutes <> 0 OR l_offset_seconds <> 0. CREATE OBJECT l_timestamp_obj EXPORTING value = l_timestamp. l_timestamp_obj->add_interval( hours = l_offset_hours minutes = l_offset_minutes seconds = l_offset_seconds ). output = l_timestamp_obj->value. ELSE. output = l_timestamp. ENDIF. RETURN. ENDIF. * Format is not supported RAISE EXCEPTION TYPE /gal/cx_json_exception EXPORTING textid = /gal/cx_json_exception=>conv_format_error_timestamp var1 = input. ENDMETHOD. METHOD number_to_javascript. DATA: l_sign TYPE string, l_abs_value TYPE /gal/javascript_number, l_digits(31) TYPE c. * Get sign and absolute value IF input < 0. l_sign = `-`. l_abs_value = - input. ELSE. l_abs_value = input. ENDIF. * Convert to decimal number UNPACK l_abs_value TO l_digits. CONCATENATE l_digits(17) l_digits+17 INTO output SEPARATED BY '.'. * Remove leading and trailing zeros SHIFT output LEFT DELETING LEADING '0'. SHIFT output RIGHT DELETING TRAILING '0'. SHIFT output LEFT DELETING LEADING space. * Format number for JSON SHIFT output RIGHT DELETING TRAILING '.'. SHIFT output LEFT DELETING LEADING space. IF output IS INITIAL OR output(1) = '.'. CONCATENATE l_sign '0' output INTO output. ELSE. CONCATENATE l_sign output INTO output. ENDIF. ENDMETHOD. METHOD string_to_javascript. DATA: l_escaped_delimiter(2) TYPE c. l_escaped_delimiter+0(1) = '\\'. l_escaped_delimiter+1(1) = string_delimiter. output = input. REPLACE ALL OCCURRENCES OF '\\' IN output WITH '\\\\'. REPLACE ALL OCCURRENCES OF cl_abap_char_utilities=>backspace IN output WITH '\\b'. REPLACE ALL OCCURRENCES OF cl_abap_char_utilities=>form_feed IN output WITH '\\f'. REPLACE ALL OCCURRENCES OF cl_abap_char_utilities=>newline IN output WITH '\\n'. REPLACE ALL OCCURRENCES OF cl_abap_char_utilities=>cr_lf(1) IN output WITH '\\r'. REPLACE ALL OCCURRENCES OF cl_abap_char_utilities=>horizontal_tab IN output WITH '\\t'. REPLACE ALL OCCURRENCES OF cl_abap_char_utilities=>vertical_tab IN output WITH '\\v'. REPLACE ALL OCCURRENCES OF string_delimiter IN output WITH l_escaped_delimiter. CONCATENATE string_delimiter output string_delimiter INTO output RESPECTING BLANKS. ENDMETHOD. METHOD timestamp_to_javascript. DATA: l_timestamp TYPE timestampl, l_digits(21) TYPE c. l_timestamp = input. UNPACK l_timestamp TO l_digits. CONCATENATE string_delimiter l_digits+0(4) '-' l_digits+4(2) '-' l_digits+6(2) 'T' l_digits+8(2) ':' l_digits+10(2) ':' l_digits+12(2) '.' l_digits+14(3) 'Z' string_delimiter INTO output. ENDMETHOD. METHOD time_to_javascript. CONCATENATE string_delimiter input(2) ':' input+2(2) ':' input+4(2) string_delimiter INTO output. ENDMETHOD. ENDCLASS. ",6005,False,1083.9243898711993,median "/******************************************************* * FILE NAME: inetc.cpp * * Copyright (c) 2004-2015 Takhir Bedertdinov and NSIS contributors * * PURPOSE: * ftp/http file download plug-in * on the base of MS Inet API * 4 GB limit (http support?) * * CHANGE HISTORY * * Author Date Modifications * Takhir Bedertdinov * Nov 11, 2004 Original * Dec 17, 2004 Embedded edition - * NSISdl GUI style as default * (nsisdl.cpp code was partly used) * Dec 17, 2004 MSI Banner style * Feb 20, 2005 Resume download * feature for big files and bad connections * Mar 05, 2005 Proxy authentication * and /POPUP caption prefix option * Mar 25, 2005 Connect timeout option * and FTP switched to passive mode * Apr 18, 2005 Crack URL buffer size * bug fixed (256->string_size) * HTTP POST added * Jun 06, 2005 IDOK on ""Enter"" key locked * POST HTTP header added * Jun 22, 2005 non-interaptable mode /nocancel * and direct connect /noproxy * Jun 29, 2005 post.php written and tested * Jul 05, 2005 60 sec delay on WinInet detach problem * solved (not fine, but works including * installer exit and system reboot) * Jul 08, 2005 'set foreground' finally removed * Jul 26, 2005 POPUP translate option * Aug 23, 2005 https service type in InternetConnect * and ""ignore certificate"" flags * Sep 30, 2005 https with bad certificate from old OS; * Forbidden handling * Dec 23, 2005 'put' entry point, new names, 12003 * ftp error handling (on ftp write permission) * 405 http error (method not allowed) * Mar 12, 2006 Internal authorization via InternetErrorDlg() * and Unauthorized (401) handling. * Jun 10, 2006 Caption text option for Resume download * MessageBox * Jun 24, 2006 HEAD method, silent mode clean up * Sep 05, 2006 Center dialog code from Backland * Sep 07, 2006 NSISdl crash fix /Backland idea/ * Sep 08, 2006 POST as dll entry point. * Sep 21, 2006 parent dlg progr.bar style and font, * nocancel via ws_sysmenu * Sep 22, 2006 current lang IDCANCEL text, /canceltext * and /useragent options * Sep 24, 2006 .onInit improvements and defaults * Nov 11, 2006 FTP path creation, root|current dir mgmt * Jan 01, 2007 Global char[] cleanup, GetLastError() to * status string on ERR_DIALOG, few MSVCRT replaces * Jan 13, 2007 /HEADER option added * Jan 28, 2007 _open -> CreateFile and related * Feb 18, 2007 Speed calculating improved (pauses), * /popup text parameter to hide URL * Jun 07, 2007 Local file truncation added for download * (CREATE_ALWAYS) * Jun 11, 2007 FTP download permitted even if server rejects * SIZE request (ProFTPD). * Aug 11, 2007 Backland' fix for progress bar redraw/style * issue in NSISdl display mode. * Jan 09, 2008 {_trueparuex^}' fix - InternetSetFilePointer() * returns -1 on error. * /question option added for cancel question. * Feb 15, 2008 PUT content-length file size fix * Feb 17, 2008 char -> TCHAR replace for UNICODE option * Feb 19, 2008 janekschwarz fix for HTTP PUT with auth * CreateFile INVALID_HANDLE_VALUE on error fix * Feb 20, 2008 base64 encoder update for unicode * Feb 27, 2008 Unicode configurations added to VS 6 dsp * Mar 20, 2008 HTTP PUT with proxy auth finally fixed * FTP errors handling improved. * HEAD bug fixed * Mar 27, 2008 Details window hide/show in NSISdl mode * Apr 10, 2008 Auth test method changed to HEAD for * old proxy's * Apr 30, 2008 InternetErrorDlg() ERROR_SUCESS on cancel * click patched * 3xx errors added to status list. * May 20, 2008 InternetReadFile on cable disconnect patched * May 20, 2008 Reply status ""0"" patch (name resolution?) * Jul 15, 2008 HTTP 304 parsing. Incorrect size reported fix. * Aug 21, 2009 Escape sequence convertion removed (caused * error in signature with %2b requests) * Marqueue progess bar style for unknown file size. * Feb 04, 2010 Unicode POST patch - body converted to multibyte * Jul 11, 2010 /FILE POST option added * Nov 04, 2010 Disabled cookies and cache for cleanliness * Feb 14, 2011 Fixed reget bug introduced in previous commit * Feb 18, 2011 /NOCOOKIES option added * Mar 02, 2011 User-agent buffer increased. Small memory leak fix * Mar 23, 2011 Use caption on embedded progressbar - zenpoy * Apr 05, 2011 reget fix - INTERNET_FLAG_RELOAD for first connect only * Apr 27, 2011 /receivetimeout option added for big files and antivirus * Jun 15, 2011 Stack clean up fix on cancel - zenpoy * Oct 19, 2011 FTP PUT error parsing fix - tperquin * Aug 19, 2013 Fix focus stealing when in silent - negativesir, JohnTHaller * Jul 20, 2014 - 1.0.4.4 - Stuart 'Afrow UK' Welch * /tostack & /tostackconv added * Version information resource added * Updated to NSIS 3.0 plugin API * Upgraded to Visual Studio 2012 * 64-bit build added * MSVCRT dependency removed * Sep 04, 2015 - 1.0.5.0 - anders_k * HTTPS connections are more secure by default * Added /weaksecurity switch, reverts to old cert. security checks * Sep 06, 2015 - 1.0.5.1 - anders_k * Don't allow infinite FtpCreateDirectory tries * Use memset intrinsic when possible to avoid VC code generation bug * Oct 17, 2015 - 1.0.5.2 - anders_k * Tries to set FTP mode to binary before querying the size. * Calls FtpGetFileSize if it exists. *******************************************************/ #define _WIN32_WINNT 0x0500 #include //#include #include #include #include ""pluginapi.h"" #include ""resource.h"" #include // strstr etc #ifndef PBM_SETMARQUEE #define PBM_SETMARQUEE (WM_USER + 10) #define PBS_MARQUEE 0x08 #endif #ifndef HTTP_QUERY_PROXY_AUTHORIZATION #define HTTP_QUERY_PROXY_AUTHORIZATION 61 #endif #ifndef SECURITY_FLAG_IGNORE_REVOCATION #define SECURITY_FLAG_IGNORE_REVOCATION 0x00000080 #endif #ifndef SECURITY_FLAG_IGNORE_UNKNOWN_CA #define SECURITY_FLAG_IGNORE_UNKNOWN_CA 0x00000100 #endif // IE 4 safety and VS 6 compatibility typedef BOOL (__stdcall *FTP_CMD)(HINTERNET,BOOL,DWORD,LPCTSTR,DWORD,HINTERNET *); FTP_CMD myFtpCommand; #define PLUGIN_NAME TEXT(""Inetc plug-in"") #define INETC_USERAGENT TEXT(""NSIS_Inetc (Mozilla)"") #define PB_RANGE 400 // progress bar values range #define PAUSE1_SEC 2 // transfer error indication time, for reget only #define PAUSE2_SEC 3 // paused state time, increase this if need (60?) #define PAUSE3_SEC 1 // pause after resume button pressed #define NOT_AVAILABLE 0xffffffff #define POST_HEADER TEXT(""Content-Type: application/x-www-form-urlencoded"") #define PUT_HEADER TEXT(""Content-Type: octet-stream\\nContent-Length: %d"") #define INTERNAL_OK 0xFFEE #define PROGRESS_MS 1000 // screen values update interval #define DEF_QUESTION TEXT(""Are you sure that you want to stop download?"") #define HOST_AUTH_HDR TEXT(""Authorization: basic %s"") #define PROXY_AUTH_HDR TEXT(""Proxy-authorization: basic %s"") //#define MY_WEAKSECURITY_CERT_FLAGS SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_REVOCATION | SECURITY_FLAG_IGNORE_CERT_DATE_INVALID | SECURITY_FLAG_IGNORE_CERT_CN_INVALID #define MY_WEAKSECURITY_CERT_FLAGS SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_REVOCATION #define MY_REDIR_FLAGS INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP | INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS #define MY_HTTPS_FLAGS (MY_REDIR_FLAGS | INTERNET_FLAG_SECURE) enum STATUS_CODES { ST_OK = 0, ST_CONNECTING, ST_DOWNLOAD, ST_CANCELLED, ST_URLOPEN, // ST_OPENING, ST_PAUSE, ERR_TERMINATED, ERR_DIALOG, ERR_INETOPEN, ERR_URLOPEN, ERR_TRANSFER, ERR_FILEOPEN, ERR_FILEWRITE, ERR_FILEREAD, ERR_REGET, ERR_CONNECT, ERR_OPENREQUEST, ERR_SENDREQUEST, ERR_CRACKURL, ERR_NOTFOUND, ERR_THREAD, ERR_PROXY, ERR_FORBIDDEN, ERR_NOTALLOWED, ERR_REQUEST, ERR_SERVER, ERR_AUTH, ERR_CREATEDIR, ERR_PATH, ERR_NOTMODIFIED, ERR_REDIRECTION }; static TCHAR szStatus[][32] = { TEXT(""OK""),TEXT(""Connecting""),TEXT(""Downloading""),TEXT(""Cancelled""),TEXT(""Connecting""), //TEXT(""Opening URL"")), TEXT(""Reconnect Pause""),TEXT(""Terminated""),TEXT(""Dialog Error""),TEXT(""Open Internet Error""), TEXT(""Open URL Error""),TEXT(""Transfer Error""),TEXT(""File Open Error""),TEXT(""File Write Error""),TEXT(""File Read Error""), TEXT(""Reget Error""),TEXT(""Connection Error""),TEXT(""OpenRequest Error""),TEXT(""SendRequest Error""), TEXT(""URL Parts Error""),TEXT(""File Not Found (404)""),TEXT(""CreateThread Error""),TEXT(""Proxy Error (407)""), TEXT(""Access Forbidden (403)""),TEXT(""Not Allowed (405)""),TEXT(""Request Error""),TEXT(""Server Error""), TEXT(""Unauthorized (401)""),TEXT(""FtpCreateDir failed (550)""),TEXT(""Error FTP path (550)""),TEXT(""Not Modified""), TEXT(""Redirection"") }; HINSTANCE g_hInstance; TCHAR fn[MAX_PATH]=TEXT(""""), *url = NULL, *szAlias = NULL, *szProxy = NULL, *szHeader = NULL, *szBanner = NULL, *szQuestion = NULL, szCancel[64]=TEXT(""""), szCaption[128]=TEXT(""""), szUserAgent[256]=TEXT(""""), szResume[256] = TEXT(""Your internet connection seems to be not permitted or dropped out!\\nPlease reconnect and click Retry to resume installation.""); CHAR *szPost = NULL, post_fname[MAX_PATH] = """"; DWORD fSize = 0; TCHAR *szToStack = NULL; int status; DWORD cnt = 0, cntToStack = 0, fs = 0, timeout = 0, receivetimeout = 0; DWORD startTime, transfStart, openType; bool silent, popup, resume, nocancel, noproxy, nocookies, convToStack, g_ignorecertissues; HWND childwnd; HWND hDlg; bool fput = false, fhead = false; #define Option_IgnoreCertIssues() ( g_ignorecertissues ) static FARPROC GetWininetProcAddress(LPCSTR Name) { return GetProcAddress(LoadLibraryA(""WININET""), Name); } /***************************************************** * FUNCTION NAME: sf(HWND) * PURPOSE: * moves HWND to top and activates it * SPECIAL CONSIDERATIONS: * commented because annoying *****************************************************/ /* void sf(HWND hw) { DWORD ctid = GetCurrentThreadId(); DWORD ftid = GetWindowThreadProcessId(GetForegroundWindow(), NULL); AttachThreadInput(ftid, ctid, TRUE); SetForegroundWindow(hw); AttachThreadInput(ftid, ctid, FALSE); } */ static TCHAR szUrl[64] = TEXT(""""); static TCHAR szDownloading[64] = TEXT(""Downloading %s""); static TCHAR szConnecting[64] = TEXT(""Connecting ...""); static TCHAR szSecond[64] = TEXT(""second""); static TCHAR szMinute[32] = TEXT(""minute""); static TCHAR szHour[32] = TEXT(""hour""); static TCHAR szPlural[32] = TEXT(""s""); static TCHAR szProgress[128] = TEXT(""%dkB (%d%%) of %dkB @ %d.%01dkB/s""); static TCHAR szRemaining[64] = TEXT("" (%d %s%s remaining)""); static TCHAR szBasic[128] = TEXT(""""); static TCHAR szAuth[128] = TEXT(""""); // is it possible to make it working with unicode strings? /* Base64 encode one byte */ static TCHAR encode(unsigned char u) { if(u < 26) return TEXT('A')+u; if(u < 52) return TEXT('a')+(u-26); if(u < 62) return TEXT('0')+(u-52); if(u == 62) return TEXT('+'); return TEXT('/'); } TCHAR *encode_base64(int size, TCHAR *src, TCHAR *dst) { int i; TCHAR *p; if(!src) return NULL; if(!size) size= lstrlen(src); p = dst; for(i=0; i>2; b5= ((b1&0x3)<<4)|(b2>>4); b6= ((b2&0xf)<<2)|(b3>>6); b7= b3&0x3f; *p++= encode(b4); *p++= encode(b5); if(i+1 0) { dw = data_buf; if(!InternetWriteFile(hFile, dw, bytesDone, &rslt) || rslt == 0) { status = ERR_TRANSFER; break; } dw += rslt; cnt += rslt; bytesDone -= rslt; } } else { if(!InternetReadFile(hFile, data_buf, sizeof(data_buf), &rslt)) { status = ERR_TRANSFER; break; } if(rslt == 0) // EOF reached or cable disconnect { // on cable disconnect returns TRUE and 0 bytes. is cnt == 0 OK (zero file size)? // cannot check this if reply is chunked (no content-length, http 1.1) status = (fs != NOT_AVAILABLE && cnt < fs) ? ERR_TRANSFER : ST_OK; break; } if(szToStack) { for (DWORD i = 0; cntToStack < g_stringsize && i < rslt; i++, cntToStack++) *(szToStack + cntToStack) = data_buf[i]; } else if(!WriteFile(localFile, data_buf, rslt, &bytesDone, NULL) || rslt != bytesDone) { status = ERR_FILEWRITE; break; } cnt += rslt; } } } /***************************************************** * FUNCTION NAME: mySendRequest() * PURPOSE: * HttpSendRequestEx() sends headers only - for PUT * We also can use InetWriteFile for POST body I guess * SPECIAL CONSIDERATIONS: * *****************************************************/ int mySendRequest(HINTERNET hFile) { INTERNET_BUFFERS BufferIn = {0}; if(fput) { BufferIn.dwStructSize = sizeof( INTERNET_BUFFERS ); BufferIn.dwBufferTotal = fs; return HttpSendRequestEx( hFile, &BufferIn, NULL, HSR_INITIATE, 0); } return HttpSendRequest(hFile, NULL, 0, szPost, fSize); } /***************************************************** * FUNCTION NAME: queryStatus() * PURPOSE: * http status code comes before download (get) and * after upload (put), so this is called from 2 places * SPECIAL CONSIDERATIONS: * *****************************************************/ bool queryStatus(HINTERNET hFile) { TCHAR buf[256] = TEXT(""""); DWORD rslt; if(HttpQueryInfo(hFile, HTTP_QUERY_STATUS_CODE, buf, &(rslt = sizeof(buf)), NULL)) { buf[3] = 0; if(lstrcmp(buf, TEXT(""0"")) == 0 || *buf == 0) status = ERR_SENDREQUEST; else if(lstrcmp(buf, TEXT(""401"")) == 0) status = ERR_AUTH; else if(lstrcmp(buf, TEXT(""403"")) == 0) status = ERR_FORBIDDEN; else if(lstrcmp(buf, TEXT(""404"")) == 0) status = ERR_NOTFOUND; else if(lstrcmp(buf, TEXT(""407"")) == 0) status = ERR_PROXY; else if(lstrcmp(buf, TEXT(""405"")) == 0) status = ERR_NOTALLOWED; else if(lstrcmp(buf, TEXT(""304"")) == 0) status = ERR_NOTMODIFIED; else if(*buf == TEXT('3')) { status = ERR_REDIRECTION; wsprintf(szStatus[status] + lstrlen(szStatus[status]), TEXT("" (%s)""), buf); } else if(*buf == TEXT('4')) { status = ERR_REQUEST; wsprintf(szStatus[status] + lstrlen(szStatus[status]), TEXT("" (%s)""), buf); } else if(*buf == TEXT('5')) { status = ERR_SERVER; wsprintf(szStatus[status] + lstrlen(szStatus[status]), TEXT("" (%s)""), buf); } return true; } return false; } /***************************************************** * FUNCTION NAME: openFtpFile() * PURPOSE: * control connection, size request, re-get lseek * SPECIAL CONSIDERATIONS: * *****************************************************/ HINTERNET openFtpFile(HINTERNET hConn, TCHAR *path) { TCHAR buf[256] = TEXT(""""), *movp; HINTERNET hFile; DWORD rslt, err, gle; bool https_req_ok = false; /* reads connection / auth responce info and cleares 'control' buffer this way */ InternetGetLastResponseInfo(&err, buf, &(rslt = sizeof(buf))); if(cnt == 0) { if(!fput) // we know local file size already { if (myFtpCommand) { /* Try to set the REPRESENTATION TYPE to I[mage] (Binary) because some servers don't accept the SIZE command in ASCII mode */ myFtpCommand(hConn, false, FTP_TRANSFER_TYPE_ASCII, TEXT(""TYPE I""), 0, &hFile); } /* too clever myFtpCommand returnes false on the valid TEXT(""550 Not found/Not permitted"" server answer, to read answer I had to ignory returned false (!= 999999) :-( GetLastError also possible, but MSDN description of codes is very limited */ wsprintf(buf, TEXT(""SIZE %s""), path + 1); if(myFtpCommand != NULL && myFtpCommand(hConn, false, FTP_TRANSFER_TYPE_ASCII, buf, 0, &hFile) != 9999 && memset(buf, 0, sizeof(buf)) != NULL && InternetGetLastResponseInfo(&err, buf, &(rslt = sizeof(buf)))) { if(_tcsstr(buf, TEXT(""213 ""))) { fs = myatou(_tcschr(buf, TEXT(' ')) + 1); } /* stupid ProFTPD returns error on SIZE request. let's continue without size. But IE knows some trick to get size from ProFTPD...... else if(mystrstr(buf, TEXT(""550 TEXT("")) { status = ERR_SIZE_NOT_PERMITTED; return NULL; } */ } if(fs == 0) { fs = NOT_AVAILABLE; } } } else { wsprintf(buf, TEXT(""REST %d""), cnt); if(myFtpCommand == NULL || !myFtpCommand(hConn, false, FTP_TRANSFER_TYPE_BINARY, buf, 0, &hFile) || memset(buf, 0, sizeof(buf)) == NULL || !InternetGetLastResponseInfo(&err, buf, &(rslt = sizeof(buf))) || (_tcsstr(buf, TEXT(""350"")) == NULL && _tcsstr(buf, TEXT(""110"")) == NULL)) { status = ERR_REGET; return NULL; } } if((hFile = FtpOpenFile(hConn, path + 1, fput ? GENERIC_WRITE : GENERIC_READ, FTP_TRANSFER_TYPE_BINARY|INTERNET_FLAG_RELOAD,0)) == NULL) { gle = GetLastError(); *buf = 0; InternetGetLastResponseInfo(&err, buf, &(rslt = sizeof(buf))); // wrong path - dir may not exist or upload may be not allowed // we use ftp://host//path (double /) to define path from FS root if(fput && (_tcsstr(buf, TEXT(""550"")) != NULL || _tcsstr(buf, TEXT(""553"")) != NULL)) { movp = path + 1; if(*movp == TEXT('/')) movp++; // don't need to create root for (UINT8 escapehatch = 0; ++escapehatch;) // Weak workaround for http://forums.winamp.com/showpost.php?p=3031692&postcount=513 bug { TCHAR *pbs = _tcschr(movp, TEXT('/')); if (!pbs) break; *pbs = TEXT('\\0'); FtpCreateDirectory(hConn, path + 1); InternetGetLastResponseInfo(&err, buf, &(rslt = sizeof(buf))); *(movp + lstrlen(movp)) = TEXT('/'); movp = _tcschr(movp, TEXT('/')) + 1; } if(status != ERR_CREATEDIR && (hFile = FtpOpenFile(hConn, path + 1, GENERIC_WRITE, FTP_TRANSFER_TYPE_BINARY|INTERNET_FLAG_RELOAD,0)) == NULL) { status = ERR_PATH; if(InternetGetLastResponseInfo(&err, buf, &(rslt = sizeof(buf)))) lstrcpyn(szStatus[status], _tcsstr(buf, TEXT(""550"")), sizeof(szStatus[0]) / sizeof(TCHAR)); } } // may be firewall related error, let's give user time to disable it else if(gle == 12003) // ERROR_INTERNET_EXTENDED_ERROR { if(_tcsstr(buf, TEXT(""550""))) { status = ERR_NOTFOUND; lstrcpyn(szStatus[status], _tcsstr(buf, TEXT(""550"")), sizeof(szStatus[0]) / sizeof(TCHAR)); } else { lstrcpyn(szStatus[status], buf, sizeof(szStatus[0]) / sizeof(TCHAR)); } } // timeout (firewall or dropped connection problem) else if(gle == 12002) // ERROR_INTERNET_TIMEOUT { if(!silent) resume = true; status = ERR_URLOPEN; } } else InternetGetLastResponseInfo(&err, buf, &(rslt = sizeof(buf))); if (hFile && NOT_AVAILABLE == fs) { FARPROC ftpgfs = GetWininetProcAddress(""FtpGetFileSize""); // IE5+ if (ftpgfs) { DWORD shi, slo = ((DWORD(WINAPI*)(HINTERNET,DWORD*))ftpgfs)(hFile, &shi); if (slo != -1 && !shi) fs = slo; } } return hFile; } /***************************************************** * FUNCTION NAME: openHttpFile() * PURPOSE: * file open, size request, re-get lseek * SPECIAL CONSIDERATIONS: * *****************************************************/ HINTERNET openHttpFile(HINTERNET hConn, INTERNET_SCHEME nScheme, TCHAR *path) { TCHAR buf[256] = TEXT(""""); HINTERNET hFile; DWORD rslt, err; bool first_attempt = true;; // test connection for PUT, the only way to do this before sending data // OPTIONS fails on HttpOpenRequest step for HTTPS // but works for HEAD I guess if(fput)// && nScheme != INTERNET_SCHEME_HTTPS) { // old proxy's may not support OPTIONS request, so changed to HEAD.... if((hFile = HttpOpenRequest(hConn, TEXT(""HEAD""), path, NULL, NULL, NULL, // if((hFile = HttpOpenRequest(hConn, TEXT(""OPTIONS""), path, NULL, NULL, NULL, INTERNET_FLAG_RELOAD | INTERNET_FLAG_KEEP_CONNECTION | (nocookies ? (INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES) : 0), 0)) != NULL) { if(*szAuth) { wsprintf(buf, PROXY_AUTH_HDR, szAuth); HttpAddRequestHeaders(hFile, buf, -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); } resend_proxy1: if(*szBasic) { wsprintf(buf, HOST_AUTH_HDR, szBasic); HttpAddRequestHeaders(hFile, buf, -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); } resend_auth1: if(HttpSendRequest(hFile, NULL, 0, NULL, 0)) { queryStatus(hFile); // may be don't need to read all from socket, but this looks safer while(InternetReadFile(hFile, buf, sizeof(buf), &rslt) && rslt > 0) {} if(!silent && (status == ERR_PROXY || status == ERR_AUTH))// || status == ERR_FORBIDDEN)) { rslt = InternetErrorDlg(hDlg, hFile, ERROR_INTERNET_INCORRECT_PASSWORD, FLAGS_ERROR_UI_FILTER_FOR_ERRORS | FLAGS_ERROR_UI_FLAGS_GENERATE_DATA | FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS, NULL); if (rslt == ERROR_INTERNET_FORCE_RETRY) { status = ST_URLOPEN; if(status == ERR_PROXY) goto resend_proxy1; else goto resend_auth1; } else { status = ST_CANCELLED; } } // no such file is OK for PUT. server first checks authentication if(status == ERR_NOTFOUND || status == ERR_FORBIDDEN || status == ERR_NOTALLOWED) { // MessageBox(childwnd, TEXT(""NOT_FOUND""), """", 0); status = ST_URLOPEN; } // parameters might be updated during dialog popup if(status == ST_URLOPEN) { *buf = 0; if(HttpQueryInfo(hFile, HTTP_QUERY_AUTHORIZATION, buf, &(rslt = sizeof(buf)), NULL) && *buf) lstrcpyn(szBasic, buf, rslt); *buf = 0; if(HttpQueryInfo(hFile, HTTP_QUERY_PROXY_AUTHORIZATION, buf, &(rslt = sizeof(buf)), NULL) && *buf) lstrcpyn(szAuth, buf, rslt); } } else status = ERR_SENDREQUEST; InternetCloseHandle(hFile); } else status = ERR_OPENREQUEST; } // request itself if(status == ST_URLOPEN) { DWORD secflags = nScheme == INTERNET_SCHEME_HTTPS ? MY_HTTPS_FLAGS : 0; if (Option_IgnoreCertIssues()) secflags |= MY_WEAKSECURITY_CERT_FLAGS; DWORD cokflags = nocookies ? (INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES) : 0; if((hFile = HttpOpenRequest(hConn, fput ? TEXT(""PUT"") : (fhead ? TEXT(""HEAD"") : (szPost ? TEXT(""POST"") : NULL)), path, NULL, NULL, NULL, // INTERNET_FLAG_RELOAD conflicts with reget - hidden re-read from beginning has place // INTERNET_FLAG_RESYNCHRONIZE // note - sync may not work with some http servers // reload on first connect (and any req. except GET), just continue on resume. // HTTP Proxy still is a problem for reget (cnt ? 0 : INTERNET_FLAG_RELOAD) | INTERNET_FLAG_KEEP_CONNECTION | cokflags | secflags, 0)) != NULL) { if(*szAuth) { wsprintf(buf, PROXY_AUTH_HDR, szAuth); HttpAddRequestHeaders(hFile, buf, -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); } resend_proxy2: if(szPost != NULL) HttpAddRequestHeaders(hFile, POST_HEADER, -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); if(*post_fname) HttpAddRequestHeadersA(hFile, post_fname, -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); if(szHeader != NULL) HttpAddRequestHeaders(hFile, szHeader, -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); if(*szBasic) { wsprintf(buf, HOST_AUTH_HDR, szBasic); HttpAddRequestHeaders(hFile, buf, -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); } if(fput) { wsprintf(buf, PUT_HEADER, fs); HttpAddRequestHeaders(hFile, buf, -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); } resend_auth2: first_attempt = true; if(nScheme == INTERNET_SCHEME_HTTPS) { if(!mySendRequest(hFile)) { InternetQueryOption (hFile, INTERNET_OPTION_SECURITY_FLAGS, (LPVOID)&rslt, &(err = sizeof(rslt))); rslt |= Option_IgnoreCertIssues() ? MY_WEAKSECURITY_CERT_FLAGS : 0; InternetSetOption (hFile, INTERNET_OPTION_SECURITY_FLAGS, &rslt, sizeof(rslt) ); } else first_attempt = false; } // https Request answer may be after optional second Send only on Win98 if(!first_attempt || mySendRequest(hFile)) { // no status for PUT - headers were sent only. And not need to get size / set position if(!fput) { queryStatus(hFile); if(!silent && (status == ERR_PROXY || status == ERR_AUTH)) { rslt = InternetErrorDlg(hDlg, hFile, ERROR_INTERNET_INCORRECT_PASSWORD, FLAGS_ERROR_UI_FILTER_FOR_ERRORS | FLAGS_ERROR_UI_FLAGS_GENERATE_DATA | FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS, NULL); if (rslt == ERROR_INTERNET_FORCE_RETRY) { status = ST_URLOPEN; if(status == ERR_PROXY) goto resend_proxy2; else goto resend_auth2; } else status = ST_CANCELLED; } // get size / set position if(status == ST_URLOPEN) { if(cnt == 0) { if(HttpQueryInfo(hFile, HTTP_QUERY_CONTENT_LENGTH, buf, &(rslt = sizeof(buf)), NULL)) fs = myatou(buf); else fs = NOT_AVAILABLE; } else { if((int)InternetSetFilePointer(hFile, cnt, NULL, FILE_BEGIN, 0) == -1) status = ERR_REGET; } } } } else { if(!queryStatus(hFile)) status = ERR_SENDREQUEST; } } else status = ERR_OPENREQUEST; } return hFile; } /***************************************************** * FUNCTION NAME: inetTransfer() * PURPOSE: * http/ftp file transfer * SPECIAL CONSIDERATIONS: * *****************************************************/ DWORD __stdcall inetTransfer(void *hw) { HINTERNET hSes, hConn, hFile; HANDLE localFile = NULL; HWND hDlg = (HWND)hw; DWORD lastCnt, rslt, err; static TCHAR hdr[2048]; TCHAR *host = (TCHAR*)LocalAlloc(LPTR, g_stringsize * sizeof(TCHAR)), *path = (TCHAR*)LocalAlloc(LPTR, g_stringsize * sizeof(TCHAR)), *params = (TCHAR*)LocalAlloc(LPTR, g_stringsize * sizeof(TCHAR)), *user = (TCHAR*)LocalAlloc(LPTR, g_stringsize * sizeof(TCHAR)), *passwd = (TCHAR*)LocalAlloc(LPTR, g_stringsize * sizeof(TCHAR)); URL_COMPONENTS uc = {sizeof(URL_COMPONENTS), NULL, 0, (INTERNET_SCHEME)0, host, g_stringsize, 0 , user, g_stringsize, passwd, g_stringsize, path, g_stringsize, params, g_stringsize}; if((hSes = InternetOpen(szUserAgent, openType, szProxy, NULL, 0)) != NULL) { if(InternetQueryOption(hSes, INTERNET_OPTION_CONNECTED_STATE, &(rslt=0), &(lastCnt=sizeof(DWORD))) && (rslt & INTERNET_STATE_DISCONNECTED_BY_USER)) { INTERNET_CONNECTED_INFO ci = {INTERNET_STATE_CONNECTED, 0}; InternetSetOption(hSes, INTERNET_OPTION_CONNECTED_STATE, &ci, sizeof(ci)); } if(timeout > 0) lastCnt = InternetSetOption(hSes, INTERNET_OPTION_CONNECT_TIMEOUT, &timeout, sizeof(timeout)); if(receivetimeout > 0) InternetSetOption(hSes, INTERNET_OPTION_RECEIVE_TIMEOUT, &receivetimeout, sizeof(receivetimeout)); // 60 sec WinInet.dll detach delay on socket time_wait fix myFtpCommand = (FTP_CMD) GetWininetProcAddress( #ifdef UNICODE ""FtpCommandW"" #else ""FtpCommandA"" #endif ); while(!popstring(url) && lstrcmpi(url, TEXT(""/end"")) != 0) { // too many customers requested not to do this // sf(hDlg); if(popstring(fn) != 0 || lstrcmpi(url, TEXT(""/end"")) == 0) break; status = ST_CONNECTING; cnt = fs = *host = *user = *passwd = *path = *params = 0; PostMessage(hDlg, WM_TIMER, 1, 0); // show url & fn, do it sync if(szToStack || (localFile = CreateFile(fn, fput ? GENERIC_READ : GENERIC_WRITE, FILE_SHARE_READ, NULL, fput ? OPEN_EXISTING : CREATE_ALWAYS, 0, NULL)) != INVALID_HANDLE_VALUE) { uc.dwHostNameLength = uc.dwUserNameLength = uc.dwPasswordLength = uc.dwUrlPathLength = uc.dwExtraInfoLength = g_stringsize; if(fput) { fs = GetFileSize(localFile, NULL); } if(InternetCrackUrl(url, 0, 0/*ICU_ESCAPE*/ , &uc)) { // auth headers for HTTP PUT seems to be lost, preparing encoded login:password if(*user && *passwd) { wsprintf(hdr, TEXT(""%s:%s""), user, passwd); // does unicode version of encoding works correct? // are user and passwd ascii only? encode_base64(lstrlen(hdr), hdr, szBasic); *hdr = 0; } lstrcat(path, params); // BUGBUG: Could overflow path? transfStart = GetTickCount(); do { // re-PUT to already deleted tmp file on http server is not possible. // the same with POST - must re-send data to server. for 'resume' loop if((fput && uc.nScheme != INTERNET_SCHEME_FTP) || szPost) { cnt = 0; SetFilePointer(localFile, 0, NULL, FILE_BEGIN); } status = ST_CONNECTING; lastCnt = cnt; if((hConn = InternetConnect(hSes, host, uc.nPort, lstrlen(user) > 0 ? user : NULL, lstrlen(passwd) > 0 ? passwd : NULL, uc.nScheme == INTERNET_SCHEME_FTP ? INTERNET_SERVICE_FTP : INTERNET_SERVICE_HTTP, uc.nScheme == INTERNET_SCHEME_FTP ? INTERNET_FLAG_PASSIVE : 0, 0)) != NULL) { status = ST_URLOPEN; hFile = uc.nScheme == INTERNET_SCHEME_FTP ? openFtpFile(hConn, path) : openHttpFile(hConn, uc.nScheme, path); if(status != ST_URLOPEN && hFile != NULL) { InternetCloseHandle(hFile); hFile = NULL; } if(hFile != NULL) { if(fhead) {// repeating calls clear headers.. if(HttpQueryInfo(hFile, HTTP_QUERY_RAW_HEADERS_CRLF, hdr, &(rslt=2048), NULL)) { if(szToStack) { for (DWORD i = 0; cntToStack < g_stringsize && i < rslt; i++, cntToStack++) *(szToStack + cntToStack) = hdr[i]; } else { WriteFile(localFile, hdr, rslt, &lastCnt, NULL); } } status = ST_OK; } else { HWND hBar = GetDlgItem(hDlg, IDC_PROGRESS1); SendDlgItemMessage(hDlg, IDC_PROGRESS1, PBM_SETPOS, 0, 0); SetWindowText(GetDlgItem(hDlg, IDC_STATIC5), fs == NOT_AVAILABLE ? TEXT(""Not Available"") : TEXT("""")); SetWindowText(GetDlgItem(hDlg, IDC_STATIC4), fs == NOT_AVAILABLE ? TEXT(""Unknown"") : TEXT("""")); SetWindowLong(hBar, GWL_STYLE, fs == NOT_AVAILABLE ? (GetWindowLong(hBar, GWL_STYLE) | PBS_MARQUEE) : (GetWindowLong(hBar, GWL_STYLE) & ~PBS_MARQUEE)); SendDlgItemMessage(hDlg, IDC_PROGRESS1, PBM_SETMARQUEE, (WPARAM)(fs == NOT_AVAILABLE ? 1 : 0), (LPARAM)50 ); fileTransfer(localFile, hFile); if(fput && uc.nScheme != INTERNET_SCHEME_FTP) { rslt = HttpEndRequest(hFile, NULL, 0, 0); queryStatus(hFile); } } InternetCloseHandle(hFile); } InternetCloseHandle(hConn); } else { status = ERR_CONNECT; if(uc.nScheme == INTERNET_SCHEME_FTP && InternetGetLastResponseInfo(&err, hdr, &(rslt = sizeof(hdr))) && _tcsstr(hdr, TEXT(""530""))) { lstrcpyn(szStatus[status], _tcsstr(hdr, TEXT(""530"")), sizeof(szStatus[0]) / sizeof(TCHAR)); } else { rslt = GetLastError(); if((rslt == 12003 || rslt == 12002) && !silent) resume = true; } } } while(((!fput || uc.nScheme == INTERNET_SCHEME_FTP) && cnt > lastCnt && status == ERR_TRANSFER && SleepEx(PAUSE1_SEC * 1000, false) == 0 && (status = ST_PAUSE) != ST_OK && SleepEx(PAUSE2_SEC * 1000, false) == 0) || (resume && status != ST_OK && status != ST_CANCELLED && status != ERR_NOTFOUND && ShowWindow(hDlg, SW_HIDE) != -1 && MessageBox(GetParent(hDlg), szResume, *szCaption ? szCaption : PLUGIN_NAME, MB_RETRYCANCEL|MB_ICONWARNING) == IDRETRY && (status = ST_PAUSE) != ST_OK && ShowWindow(hDlg, silent ? SW_HIDE : SW_SHOW) == false && SleepEx(PAUSE3_SEC * 1000, false) == 0)); } else status = ERR_CRACKURL; CloseHandle(localFile); if(!fput && status != ST_OK && !szToStack) { rslt = DeleteFile(fn); break; } } else status = ERR_FILEOPEN; } InternetCloseHandle(hSes); if (lstrcmpi(url, TEXT(""/end""))==0) pushstring(url); } else status = ERR_INETOPEN; LocalFree(host); LocalFree(path); LocalFree(user); LocalFree(passwd); LocalFree(params); if(IsWindow(hDlg)) PostMessage(hDlg, WM_COMMAND, MAKELONG(IDOK, INTERNAL_OK), 0); return status; } /***************************************************** * FUNCTION NAME: fsFormat() * PURPOSE: * formats DWORD (max 4 GB) file size for dialog, big MB * SPECIAL CONSIDERATIONS: * *****************************************************/ void fsFormat(DWORD bfs, TCHAR *b) { if(bfs == NOT_AVAILABLE) lstrcpy(b, TEXT(""???"")); else if(bfs == 0) lstrcpy(b, TEXT(""0"")); else if(bfs < 10 * 1024) wsprintf(b, TEXT(""%u bytes""), bfs); else if(bfs < 10 * 1024 * 1024) wsprintf(b, TEXT(""%u kB""), bfs / 1024); else wsprintf(b, TEXT(""%u MB""), (bfs / 1024 / 1024)); } /***************************************************** * FUNCTION NAME: progress_callback * PURPOSE: * old-style progress bar text updates * SPECIAL CONSIDERATIONS: * *****************************************************/ void progress_callback(void) { static TCHAR buf[1024] = TEXT(""""), b[1024] = TEXT(""""); int time_sofar = max(1, (GetTickCount() - transfStart) / 1000); int bps = cnt / time_sofar; int remain = (cnt > 0 && fs != NOT_AVAILABLE) ? (MulDiv(time_sofar, fs, cnt) - time_sofar) : 0; TCHAR *rtext=szSecond; if(remain < 0) remain = 0; if (remain >= 60) { remain/=60; rtext=szMinute; if (remain >= 60) { remain/=60; rtext=szHour; } } wsprintf(buf, szProgress, cnt/1024, fs > 0 && fs != NOT_AVAILABLE ? MulDiv(100, cnt, fs) : 0, fs != NOT_AVAILABLE ? fs/1024 : 0, bps/1024,((bps*10)/1024)%10 ); if (remain) wsprintf(buf + lstrlen(buf), szRemaining, remain, rtext, remain==1?TEXT(""""):szPlural ); SetDlgItemText(hDlg, IDC_STATIC1, (cnt == 0 || status == ST_CONNECTING) ? szConnecting : buf); if(fs > 0 && fs != NOT_AVAILABLE) SendMessage(GetDlgItem(hDlg, IDC_PROGRESS1), PBM_SETPOS, MulDiv(cnt, PB_RANGE, fs), 0); if (*szCaption == 0) wsprintf(buf, szDownloading, _tcsrchr(fn, TEXT('\\\\')) ? _tcsrchr(fn, TEXT('\\\\')) + 1 : fn); else wsprintf(buf, TEXT(""%s""),szCaption); HWND hwndS = GetDlgItem(childwnd, 1006); if(!silent && hwndS != NULL && IsWindow(hwndS)) { GetWindowText(hwndS, b, sizeof(b)); if(lstrcmp(b, buf) != 0) SetWindowText(hwndS, buf); } } /***************************************************** * FUNCTION NAME: onTimer() * PURPOSE: * updates text fields every second * SPECIAL CONSIDERATIONS: * *****************************************************/ void onTimer(HWND hDlg) { TCHAR b[128]; DWORD ct = (GetTickCount() - transfStart) / 1000, tt = (GetTickCount() - startTime) / 1000; // dialog window caption wsprintf(b, TEXT(""%s - %s""), *szCaption ? szCaption : PLUGIN_NAME, szStatus[status]); if(fs > 0 && fs != NOT_AVAILABLE && status == ST_DOWNLOAD) { wsprintf(b + lstrlen(b), TEXT("" %d%%""), MulDiv(100, cnt, fs)); } if(szBanner == NULL) SetWindowText(hDlg, b); // current file and url SetDlgItemText(hDlg, IDC_STATIC1, (szAlias && *szAlias) ? szAlias : url); SetDlgItemText(hDlg, IDC_STATIC2, /*_tcsrchr(fn, '\\\\') ? _tcsrchr(fn, '\\\\') + 1 : */fn); // bytes done and rate if(cnt > 0) { fsFormat(cnt, b); if(ct > 1 && status == ST_DOWNLOAD) { lstrcat(b, TEXT("" ( "")); fsFormat(cnt / ct, b + lstrlen(b)); lstrcat(b, TEXT(""/sec )"")); } } else *b = 0; SetDlgItemText(hDlg, IDC_STATIC3, b); // total download time wsprintf(b, TEXT(""%d:%02d:%02d""), tt / 3600, (tt / 60) % 60, tt % 60); SetDlgItemText(hDlg, IDC_STATIC6, b); // file size, time remaining, progress bar if(fs > 0 && fs != NOT_AVAILABLE) { fsFormat(fs, b); SetDlgItemText(hDlg, IDC_STATIC5, b); SendDlgItemMessage(hDlg, IDC_PROGRESS1, PBM_SETPOS, MulDiv(cnt, PB_RANGE, fs), 0); if(cnt > 5000) { ct = MulDiv(fs - cnt, ct, cnt); wsprintf(b, TEXT(""%d:%02d:%02d""), ct / 3600, (ct / 60) % 60, ct % 60); } else *b = 0; SetWindowText(GetDlgItem(hDlg, IDC_STATIC4), b); } } /***************************************************** * FUNCTION NAME: centerDlg() * PURPOSE: * centers dlg on NSIS parent * SPECIAL CONSIDERATIONS: * *****************************************************/ void centerDlg(HWND hDlg) { HWND hwndParent = GetParent(hDlg); RECT nsisRect, dlgRect, waRect; int dlgX, dlgY, dlgWidth, dlgHeight; if(hwndParent == NULL || silent) return; if(popup) GetWindowRect(hwndParent, &nsisRect); else GetClientRect(hwndParent, &nsisRect); GetWindowRect(hDlg, &dlgRect); dlgWidth = dlgRect.right - dlgRect.left; dlgHeight = dlgRect.bottom - dlgRect.top; dlgX = (nsisRect.left + nsisRect.right - dlgWidth) / 2; dlgY = (nsisRect.top + nsisRect.bottom - dlgHeight) / 2; if(popup) { SystemParametersInfo(SPI_GETWORKAREA, 0, &waRect, 0); if(dlgX > waRect.right - dlgWidth) dlgX = waRect.right - dlgWidth; if(dlgX < waRect.left) dlgX = waRect.left; if(dlgY > waRect.bottom - dlgHeight) dlgY = waRect.bottom - dlgHeight; if(dlgY < waRect.top) dlgY = waRect.top; } else dlgY += 20; SetWindowPos(hDlg, HWND_TOP, dlgX, dlgY, 0, 0, SWP_NOSIZE); } /***************************************************** * FUNCTION NAME: onInitDlg() * PURPOSE: * dlg init * SPECIAL CONSIDERATIONS: * *****************************************************/ void onInitDlg(HWND hDlg) { HFONT hFont; HWND hPrbNew; HWND hPrbOld; HWND hCan = GetDlgItem(hDlg, IDCANCEL); if(childwnd) { hPrbNew = GetDlgItem(hDlg, IDC_PROGRESS1); hPrbOld = GetDlgItem(childwnd, 0x3ec); // Backland' fix for progress bar redraw/style issue. // Original bar may be hidden because of interfernce with other plug-ins. LONG prbStyle = WS_VISIBLE | WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN; if(hPrbOld != NULL) { prbStyle |= GetWindowLong(hPrbOld, GWL_STYLE); } SetWindowLong(hPrbNew, GWL_STYLE, prbStyle); if(!popup) { if((hFont = (HFONT)SendMessage(childwnd, WM_GETFONT, 0, 0)) != NULL) { SendDlgItemMessage(hDlg, IDC_STATIC1, WM_SETFONT, (WPARAM)hFont, 0); SendDlgItemMessage(hDlg, IDCANCEL, WM_SETFONT, (WPARAM)hFont, 0); } if(*szCancel == 0) GetWindowText(GetDlgItem(GetParent(childwnd), IDCANCEL), szCancel, sizeof(szCancel)); SetWindowText(hCan, szCancel); SetWindowPos(hPrbNew, HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE); } } if(nocancel) { if(hCan != NULL) ShowWindow(hCan, SW_HIDE); if(popup) SetWindowLong(hDlg, GWL_STYLE, GetWindowLong(hDlg, GWL_STYLE) ^ WS_SYSMENU); } SendDlgItemMessage(hDlg, IDC_PROGRESS1, PBM_SETRANGE, 0, MAKELPARAM(0, PB_RANGE)); if(szBanner != NULL) { SendDlgItemMessage(hDlg, IDC_STATIC13, STM_SETICON, (WPARAM)LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(103)), 0); SetDlgItemText(hDlg, IDC_STATIC12, szBanner); SetWindowText(hDlg, *szCaption ? szCaption : PLUGIN_NAME); } SetTimer(hDlg, 1, 1000, NULL); if(*szUrl != 0) { SetDlgItemText(hDlg, IDC_STATIC20, szUrl); SetDlgItemText(hDlg, IDC_STATIC21, szDownloading); SetDlgItemText(hDlg, IDC_STATIC22, szConnecting); SetDlgItemText(hDlg, IDC_STATIC23, szProgress); SetDlgItemText(hDlg, IDC_STATIC24, szSecond); SetDlgItemText(hDlg, IDC_STATIC25, szRemaining); } } /***************************************************** * FUNCTION NAME: dlgProc() * PURPOSE: * dlg message handling procedure * SPECIAL CONSIDERATIONS: * todo: better dialog design *****************************************************/ INT_PTR CALLBACK dlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam ) { switch(message) { case WM_INITDIALOG: onInitDlg(hDlg); centerDlg(hDlg); return false; case WM_PAINT: // child dialog redraw problem. return false is important RedrawWindow(GetDlgItem(hDlg, IDC_STATIC1), NULL, NULL, RDW_INVALIDATE); RedrawWindow(GetDlgItem(hDlg, IDCANCEL), NULL, NULL, RDW_INVALIDATE); RedrawWindow(GetDlgItem(hDlg, IDC_PROGRESS1), NULL, NULL, RDW_INVALIDATE); UpdateWindow(GetDlgItem(hDlg, IDC_STATIC1)); UpdateWindow(GetDlgItem(hDlg, IDCANCEL)); UpdateWindow(GetDlgItem(hDlg, IDC_PROGRESS1)); return false; case WM_TIMER: if(!silent && IsWindow(hDlg)) { // long connection period and paused state updates if(status != ST_DOWNLOAD && GetTickCount() - transfStart > PROGRESS_MS) transfStart += PROGRESS_MS; if(popup) onTimer(hDlg); else progress_callback(); RedrawWindow(GetDlgItem(hDlg, IDC_STATIC1), NULL, NULL, RDW_INVALIDATE); RedrawWindow(GetDlgItem(hDlg, IDCANCEL), NULL, NULL, RDW_INVALIDATE); RedrawWindow(GetDlgItem(hDlg, IDC_PROGRESS1), NULL, NULL, RDW_INVALIDATE); } break; case WM_COMMAND: switch(LOWORD(wParam)) { case IDCANCEL: if(nocancel) break; if(szQuestion && MessageBox(hDlg, szQuestion, *szCaption ? szCaption : PLUGIN_NAME, MB_ICONWARNING|MB_YESNO) == IDNO) break; status = ST_CANCELLED; // FallThrough case IDOK: if(status != ST_CANCELLED && HIWORD(wParam) != INTERNAL_OK) break; // otherwise in the silent mode next banner windows may go to background // if(silent) sf(hDlg); KillTimer(hDlg, 1); DestroyWindow(hDlg); break; } return false; default: return false; } return true; } /***************************************************** * FUNCTION NAME: get() * PURPOSE: * http/https/ftp file download entry point * SPECIAL CONSIDERATIONS: * *****************************************************/ extern ""C"" void __declspec(dllexport) __cdecl get(HWND hwndParent, int string_size, TCHAR *variables, stack_t **stacktop, extra_parameters *extra ) { HANDLE hThread; DWORD dwThreadId; MSG msg; TCHAR szUsername[64]=TEXT(""""), // proxy params szPassword[64]=TEXT(""""); EXDLL_INIT(); // for repeating /nounload plug-un calls - global vars clean up silent = popup = resume = nocancel = noproxy = nocookies = false; g_ignorecertissues = false; myFtpCommand = NULL; openType = INTERNET_OPEN_TYPE_PRECONFIG; status = ST_CONNECTING; *szCaption = *szCancel = *szUserAgent = *szBasic = *szAuth = 0; url = (TCHAR*)LocalAlloc(LPTR, string_size * sizeof(TCHAR)); if(szPost) { popstring(url); #ifdef UNICODE WideCharToMultiByte(CP_ACP, 0, url, -1, szPost, string_size, NULL, NULL); #else lstrcpy(szPost, url); #endif fSize = (DWORD)lstrlenA(szPost); } // global silent option if(extra->exec_flags->silent != 0) silent = true; // we must take this from stack, or push url back while(!popstring(url) && *url == TEXT('/')) { if(lstrcmpi(url, TEXT(""/silent"")) == 0) silent = true; else if(lstrcmpi(url, TEXT(""/weaksecurity"")) == 0) g_ignorecertissues = true; else if(lstrcmpi(url, TEXT(""/caption"")) == 0) popstring(szCaption); else if(lstrcmpi(url, TEXT(""/username"")) == 0) popstring(szUsername); else if(lstrcmpi(url, TEXT(""/password"")) == 0) popstring(szPassword); else if(lstrcmpi(url, TEXT(""/nocancel"")) == 0) nocancel = true; else if(lstrcmpi(url, TEXT(""/nocookies"")) == 0) nocookies = true; else if(lstrcmpi(url, TEXT(""/noproxy"")) == 0) openType = INTERNET_OPEN_TYPE_DIRECT; else if(lstrcmpi(url, TEXT(""/popup"")) == 0) { popup = true; szAlias = (TCHAR*)LocalAlloc(LPTR, string_size * sizeof(TCHAR)); popstring(szAlias); } else if(lstrcmpi(url, TEXT(""/resume"")) == 0) { popstring(url); if(url[0]) lstrcpy(szResume, url); resume = true; } else if(lstrcmpi(url, TEXT(""/translate"")) == 0) { if(popup) { popstring(szUrl); popstring(szStatus[ST_DOWNLOAD]); // Downloading popstring(szStatus[ST_CONNECTING]); // Connecting lstrcpy(szStatus[ST_URLOPEN], szStatus[ST_CONNECTING]); popstring(szDownloading);// file name popstring(szConnecting);// received popstring(szProgress);// file size popstring(szSecond);// remaining time popstring(szRemaining);// total time } else { popstring(szDownloading); popstring(szConnecting); popstring(szSecond); popstring(szMinute); popstring(szHour); popstring(szPlural); popstring(szProgress); popstring(szRemaining); } } else if(lstrcmpi(url, TEXT(""/banner"")) == 0) { popup = true; szBanner = (TCHAR*)LocalAlloc(LPTR, string_size * sizeof(TCHAR)); popstring(szBanner); } else if(lstrcmpi(url, TEXT(""/canceltext"")) == 0) { popstring(szCancel); } else if(lstrcmpi(url, TEXT(""/question"")) == 0) { szQuestion = (TCHAR*)LocalAlloc(LPTR, string_size * sizeof(TCHAR)); popstring(szQuestion); if(*szQuestion == 0) lstrcpy(szQuestion, DEF_QUESTION); } else if(lstrcmpi(url, TEXT(""/useragent"")) == 0) { popstring(szUserAgent); } else if(lstrcmpi(url, TEXT(""/proxy"")) == 0) { szProxy = (TCHAR*)LocalAlloc(LPTR, string_size * sizeof(TCHAR)); popstring(szProxy); openType = INTERNET_OPEN_TYPE_PROXY; } else if(lstrcmpi(url, TEXT(""/connecttimeout"")) == 0) { popstring(url); timeout = myatou(url) * 1000; } else if(lstrcmpi(url, TEXT(""/receivetimeout"")) == 0) { popstring(url); receivetimeout = myatou(url) * 1000; } else if(lstrcmpi(url, TEXT(""/header"")) == 0) { szHeader = (TCHAR*)LocalAlloc(LPTR, string_size * sizeof(TCHAR)); popstring(szHeader); } else if(!fput && ((convToStack = lstrcmpi(url, TEXT(""/tostackconv"")) == 0) || lstrcmpi(url, TEXT(""/tostack"")) == 0)) { szToStack = (TCHAR*)LocalAlloc(LPTR, string_size * sizeof(TCHAR)); cntToStack = 0; lstrcpy(fn, TEXT(""file"")); } else if(lstrcmpi(url, TEXT(""/file"")) == 0) { HANDLE hFile = CreateFileA(szPost, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); DWORD rslt; if(hFile == INVALID_HANDLE_VALUE) { status = ERR_FILEOPEN; goto cleanup; } if((fSize = GetFileSize(hFile, NULL)) == 0) { CloseHandle(hFile); status = ERR_FILEREAD; goto cleanup; } wsprintfA(post_fname, ""Filename: %s"", strchr(szPost, '\\\\') ? strrchr(szPost, '\\\\') + 1 : szPost); LocalFree(szPost); szPost = (char*)LocalAlloc(LPTR, fSize); if(ReadFile(hFile, szPost, fSize, &rslt, NULL) == 0 || rslt != fSize) { CloseHandle(hFile); status = ERR_FILEREAD; goto cleanup; } CloseHandle(hFile); } } pushstring(url); // if(*szCaption == 0) lstrcpy(szCaption, PLUGIN_NAME); if(*szUserAgent == 0) lstrcpy(szUserAgent, INETC_USERAGENT); if(*szPassword && *szUsername) { wsprintf(url, TEXT(""%s:%s""), szUsername, szPassword); encode_base64(lstrlen(url), url, szAuth); } // may be silent for plug-in, but not so for installer itself - let's try to define 'progress text' if(hwndParent != NULL && (childwnd = FindWindowEx(hwndParent, NULL, TEXT(""#32770""), NULL)) != NULL && !silent) SetDlgItemText(childwnd, 1006, *szCaption ? szCaption : PLUGIN_NAME); else InitCommonControls(); // or NSIS do this before .onInit? // cannot embed child dialog to non-existing parent. Using 'silent' to hide it if(childwnd == NULL && !popup) silent = true; // let's use hidden popup dlg in the silent mode - works both on .onInit and Page if(silent) { resume = false; popup = true; } // google says WS_CLIPSIBLINGS helps to redraw... not in my tests... if(!popup) { unsigned int wstyle = GetWindowLong(childwnd, GWL_STYLE); wstyle |= WS_CLIPSIBLINGS; SetWindowLong(childwnd, GWL_STYLE, wstyle); } startTime = GetTickCount(); if((hDlg = CreateDialog(g_hInstance, MAKEINTRESOURCE(szBanner ? IDD_DIALOG2 : (popup ? IDD_DIALOG1 : IDD_DIALOG3)), (popup ? hwndParent : childwnd), dlgProc)) != NULL) { if((hThread = CreateThread(NULL, 0, inetTransfer, (LPVOID)hDlg, 0, &dwThreadId)) != NULL) { HWND hButton = GetDlgItem(childwnd, 0x403); HWND hList = GetDlgItem(childwnd, 0x3f8); DWORD dwStyleButton = 0; BOOL fVisibleList = false; if(!silent) { ShowWindow(hDlg, SW_NORMAL); if(childwnd && !popup) { if(hButton) { dwStyleButton = GetWindowLong(hButton, GWL_STYLE); EnableWindow(hButton, false); } if(hList) { fVisibleList = IsWindowVisible(hList); ShowWindow(hList, SW_HIDE); } } } while(IsWindow(hDlg) && GetMessage(&msg, NULL, 0, 0) > 0) { if(!IsDialogMessage(hDlg, &msg) && !IsDialogMessage(hwndParent, &msg) && !TranslateMessage(&msg)) DispatchMessage(&msg); } if(WaitForSingleObject(hThread, 3000) == WAIT_TIMEOUT) { TerminateThread(hThread, 1); status = ERR_TERMINATED; } CloseHandle(hThread); if(!silent && childwnd) { SetDlgItemText(childwnd, 1006, TEXT("""")); if(!popup) { if(hButton) SetWindowLong(hButton, GWL_STYLE, dwStyleButton); if(hList && fVisibleList) ShowWindow(hList, SW_SHOW); } // RedrawWindow(childwnd, NULL, NULL, RDW_INVALIDATE|RDW_ERASE); } } else { status = ERR_THREAD; DestroyWindow(hDlg); } } else { status = ERR_DIALOG; wsprintf(szStatus[status] + lstrlen(szStatus[status]), TEXT("" (Err=%d)""), GetLastError()); } cleanup: // we need to clean up stack from remaining url/file pairs. // this multiple files download head pain and may be not safe while(!popstring(url) && lstrcmpi(url, TEXT(""/end"")) != 0) { /* nothing MessageBox(NULL, url, TEXT(""""), 0);*/ } LocalFree(url); if(szAlias) LocalFree(szAlias); if(szBanner) LocalFree(szAlias); if(szQuestion) LocalFree(szQuestion); if(szProxy) LocalFree(szProxy); if(szPost) LocalFree(szPost); if(szHeader) LocalFree(szHeader); url = szProxy = szHeader = szAlias = szQuestion = NULL; szPost = NULL; fput = fhead = false; if(szToStack && status == ST_OK) { if(cntToStack > 0 && convToStack) { #ifdef UNICODE int required = MultiByteToWideChar(CP_ACP, 0, (CHAR*)szToStack, string_size * sizeof(TCHAR), NULL, 0); if(required > 0) { WCHAR* pszToStackNew = (WCHAR*)LocalAlloc(LPTR, sizeof(WCHAR) * (required + 1)); if(pszToStackNew) { if(MultiByteToWideChar(CP_ACP, 0, (CHAR*)szToStack, string_size * sizeof(TCHAR), pszToStackNew, required) > 0) pushstring(pszToStackNew); LocalFree(pszToStackNew); } } #else int required = WideCharToMultiByte(CP_ACP, 0, (WCHAR*)szToStack, -1, NULL, 0, NULL, NULL); if(required > 0) { CHAR* pszToStackNew = (CHAR*)LocalAlloc(LPTR, required + 1); if(pszToStackNew) { if(WideCharToMultiByte(CP_ACP, 0, (WCHAR*)szToStack, -1, pszToStackNew, required, NULL, NULL) > 0) pushstring(pszToStackNew); LocalFree(pszToStackNew); } } #endif } else { pushstring(szToStack); } LocalFree(szToStack); szToStack = NULL; } pushstring(szStatus[status]); } /***************************************************** * FUNCTION NAME: put() * PURPOSE: * http/ftp file upload entry point * SPECIAL CONSIDERATIONS: * re-put not works with http, but ftp REST - may be. *****************************************************/ extern ""C"" void __declspec(dllexport) __cdecl put(HWND hwndParent, int string_size, TCHAR *variables, stack_t **stacktop, extra_parameters *extra ) { fput = true; lstrcpy(szDownloading, TEXT(""Uploading %s"")); lstrcpy(szStatus[2], TEXT(""Uploading"")); get(hwndParent, string_size, variables, stacktop, extra); } /***************************************************** * FUNCTION NAME: post() * PURPOSE: * http post entry point * SPECIAL CONSIDERATIONS: * *****************************************************/ extern ""C"" void __declspec(dllexport) __cdecl post(HWND hwndParent, int string_size, TCHAR *variables, stack_t **stacktop, extra_parameters *extra ) { szPost = (CHAR*)LocalAlloc(LPTR, string_size); get(hwndParent, string_size, variables, stacktop, extra); } /***************************************************** * FUNCTION NAME: head() * PURPOSE: * http/ftp file upload entry point * SPECIAL CONSIDERATIONS: * re-put not works with http, but ftp REST - may be. *****************************************************/ extern ""C"" void __declspec(dllexport) __cdecl head(HWND hwndParent, int string_size, TCHAR *variables, stack_t **stacktop, extra_parameters *extra ) { fhead = true; get(hwndParent, string_size, variables, stacktop, extra); } /***************************************************** * FUNCTION NAME: DllMain() * PURPOSE: * Dll main (initialization) entry point * SPECIAL CONSIDERATIONS: * *****************************************************/ #ifdef _VC_NODEFAULTLIB #define DllMain _DllMainCRTStartup #endif EXTERN_C BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { g_hInstance = hinstDLL; return TRUE; } ",16352,True,2879.4129083902117,median "// Copyright (c) 2013, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. // // Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #include #include #include #include #include #include #include #include #include #include #include ""rocksdb/env.h"" #include ""rocksdb/slice.h"" #include ""port/port.h"" #include ""port/dirent.h"" #include ""port/win/win_logger.h"" #include ""util/random.h"" #include ""util/iostats_context_imp.h"" #include ""util/rate_limiter.h"" #include ""util/sync_point.h"" #include ""util/aligned_buffer.h"" #include ""util/thread_status_updater.h"" #include ""util/thread_status_util.h"" #include // For UUID generation #include namespace rocksdb { std::string GetWindowsErrSz(DWORD err) { LPSTR lpMsgBuf; FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, 0, // Default language reinterpret_cast(&lpMsgBuf), 0, NULL); std::string Err = lpMsgBuf; LocalFree(lpMsgBuf); return Err; } namespace { const size_t c_OneMB = (1 << 20); ThreadStatusUpdater* CreateThreadStatusUpdater() { return new ThreadStatusUpdater(); } inline Status IOErrorFromWindowsError(const std::string& context, DWORD err) { return Status::IOError(context, GetWindowsErrSz(err)); } inline Status IOErrorFromLastWindowsError(const std::string& context) { return IOErrorFromWindowsError(context, GetLastError()); } inline Status IOError(const std::string& context, int err_number) { return Status::IOError(context, strerror(err_number)); } // TODO(sdong): temp logging. Need to help debugging. Remove it when // the feature is proved to be stable. inline void PrintThreadInfo(size_t thread_id, size_t terminatingId) { fprintf(stdout, ""Bg thread %Iu terminates %Iu\\n"", thread_id, terminatingId); } // returns the ID of the current process inline int current_process_id() { return _getpid(); } // RAII helpers for HANDLEs const auto CloseHandleFunc = [](HANDLE h) { ::CloseHandle(h); }; typedef std::unique_ptr UniqueCloseHandlePtr; // We preserve the original name of this interface to denote the original idea // behind it. // All reads happen by a specified offset and pwrite interface does not change // the position of the file pointer. Judging from the man page and errno it does // execute // lseek atomically to return the position of the file back where it was. // WriteFile() does not // have this capability. Therefore, for both pread and pwrite the pointer is // advanced to the next position // which is fine for writes because they are (should be) sequential. // Because all the reads/writes happen by the specified offset, the caller in // theory should not // rely on the current file offset. SSIZE_T pwrite(HANDLE hFile, const char* src, size_t numBytes, uint64_t offset) { assert(numBytes <= std::numeric_limits::max()); OVERLAPPED overlapped = {0}; ULARGE_INTEGER offsetUnion; offsetUnion.QuadPart = offset; overlapped.Offset = offsetUnion.LowPart; overlapped.OffsetHigh = offsetUnion.HighPart; SSIZE_T result = 0; unsigned long bytesWritten = 0; if (FALSE == WriteFile(hFile, src, static_cast(numBytes), &bytesWritten, &overlapped)) { result = -1; } else { result = bytesWritten; } return result; } // See comments for pwrite above SSIZE_T pread(HANDLE hFile, char* src, size_t numBytes, uint64_t offset) { assert(numBytes <= std::numeric_limits::max()); OVERLAPPED overlapped = {0}; ULARGE_INTEGER offsetUnion; offsetUnion.QuadPart = offset; overlapped.Offset = offsetUnion.LowPart; overlapped.OffsetHigh = offsetUnion.HighPart; SSIZE_T result = 0; unsigned long bytesRead = 0; if (FALSE == ReadFile(hFile, src, static_cast(numBytes), &bytesRead, &overlapped)) { return -1; } else { result = bytesRead; } return result; } // Note the below two do not set errno because they are used only here in this // file // on a Windows handle and, therefore, not necessary. Translating GetLastError() // to errno // is a sad business inline int fsync(HANDLE hFile) { if (!FlushFileBuffers(hFile)) { return -1; } return 0; } // SetFileInformationByHandle() is capable of fast pre-allocates. // However, this does not change the file end position unless the file is // truncated and the pre-allocated space is not considered filled with zeros. inline Status fallocate(const std::string& filename, HANDLE hFile, uint64_t to_size) { Status status; FILE_ALLOCATION_INFO alloc_info; alloc_info.AllocationSize.QuadPart = to_size; if (!SetFileInformationByHandle(hFile, FileAllocationInfo, &alloc_info, sizeof(FILE_ALLOCATION_INFO))) { auto lastError = GetLastError(); status = IOErrorFromWindowsError( ""Failed to pre-allocate space: "" + filename, lastError); } return status; } inline Status ftruncate(const std::string& filename, HANDLE hFile, uint64_t toSize) { Status status; FILE_END_OF_FILE_INFO end_of_file; end_of_file.EndOfFile.QuadPart = toSize; if (!SetFileInformationByHandle(hFile, FileEndOfFileInfo, &end_of_file, sizeof(FILE_END_OF_FILE_INFO))) { auto lastError = GetLastError(); status = IOErrorFromWindowsError(""Failed to Set end of file: "" + filename, lastError); } return status; } // mmap() based random-access class WinMmapReadableFile : public RandomAccessFile { const std::string fileName_; HANDLE hFile_; HANDLE hMap_; const void* mapped_region_; const size_t length_; public: // mapped_region_[0,length-1] contains the mmapped contents of the file. WinMmapReadableFile(const std::string& fileName, HANDLE hFile, HANDLE hMap, const void* mapped_region, size_t length) : fileName_(fileName), hFile_(hFile), hMap_(hMap), mapped_region_(mapped_region), length_(length) {} ~WinMmapReadableFile() { BOOL ret = ::UnmapViewOfFile(mapped_region_); assert(ret); ret = ::CloseHandle(hMap_); assert(ret); ret = ::CloseHandle(hFile_); assert(ret); } virtual Status Read(uint64_t offset, size_t n, Slice* result, char* scratch) const override { Status s; if (offset > length_) { *result = Slice(); return IOError(fileName_, EINVAL); } else if (offset + n > length_) { n = length_ - offset; } *result = Slice(reinterpret_cast(mapped_region_) + offset, n); return s; } virtual Status InvalidateCache(size_t offset, size_t length) override { return Status::OK(); } }; // We preallocate up to an extra megabyte and use memcpy to append new // data to the file. This is safe since we either properly close the // file before reading from it, or for log files, the reading code // knows enough to skip zero suffixes. class WinMmapFile : public WritableFile { private: const std::string filename_; HANDLE hFile_; HANDLE hMap_; const size_t page_size_; // We flush the mapping view in page_size // increments. We may decide if this is a memory // page size or SSD page size const size_t allocation_granularity_; // View must start at such a granularity size_t mapping_size_; // We want file mapping to be of a specific size // because then the file is expandable size_t view_size_; // How much memory to map into a view at a time char* mapped_begin_; // Must begin at the file offset that is aligned with // allocation_granularity_ char* mapped_end_; char* dst_; // Where to write next (in range [mapped_begin_,mapped_end_]) char* last_sync_; // Where have we synced up to uint64_t file_offset_; // Offset of mapped_begin_ in file // Do we have unsynced writes? bool pending_sync_; // Can only truncate or reserve to a sector size aligned if // used on files that are opened with Unbuffered I/O Status TruncateFile(uint64_t toSize) { return ftruncate(filename_, hFile_, toSize); } // Can only truncate or reserve to a sector size aligned if // used on files that are opened with Unbuffered I/O // Normally it does not present a problem since in memory mapped files // we do not disable buffering Status ReserveFileSpace(uint64_t toSize) { IOSTATS_TIMER_GUARD(allocate_nanos); return fallocate(filename_, hFile_, toSize); } Status UnmapCurrentRegion() { Status status; if (mapped_begin_ != nullptr) { if (!::UnmapViewOfFile(mapped_begin_)) { status = IOErrorFromWindowsError( ""Failed to unmap file view: "" + filename_, GetLastError()); } // UnmapView automatically sends data to disk but not the metadata // which is good and provides some equivalent of fdatasync() on Linux // therefore, we donot need separate flag for metadata pending_sync_ = false; mapped_begin_ = nullptr; mapped_end_ = nullptr; dst_ = nullptr; last_sync_ = nullptr; // Move on to the next portion of the file file_offset_ += view_size_; // Increase the amount we map the next time, but capped at 1MB view_size_ *= 2; view_size_ = std::min(view_size_, c_OneMB); } return status; } Status MapNewRegion() { Status status; assert(mapped_begin_ == nullptr); size_t minMappingSize = file_offset_ + view_size_; // Check if we need to create a new mapping since we want to write beyond // the current one // If the mapping view is now too short // CreateFileMapping will extend the size of the file automatically if the // mapping size is greater than // the current length of the file, which reserves the space and makes // writing faster, except, windows can not map an empty file. // Thus the first time around we must actually extend the file ourselves if (hMap_ == NULL || minMappingSize > mapping_size_) { if (NULL == hMap_) { // Creating mapping for the first time so reserve the space on disk status = ReserveFileSpace(minMappingSize); if (!status.ok()) { return status; } } if (hMap_) { // Unmap the previous one BOOL ret = ::CloseHandle(hMap_); assert(ret); hMap_ = NULL; } // Calculate the new mapping size which will hopefully reserve space for // several consecutive sliding views // Query preallocation block size if set size_t preallocationBlockSize = 0; size_t lastAllocatedBlockSize = 0; // Not used GetPreallocationStatus(&preallocationBlockSize, &lastAllocatedBlockSize); if (preallocationBlockSize) { preallocationBlockSize = Roundup(preallocationBlockSize, allocation_granularity_); } else { preallocationBlockSize = 2 * view_size_; } mapping_size_ += preallocationBlockSize; ULARGE_INTEGER mappingSize; mappingSize.QuadPart = mapping_size_; hMap_ = CreateFileMappingA( hFile_, NULL, // Security attributes PAGE_READWRITE, // There is not a write only mode for mapping mappingSize.HighPart, // Enable mapping the whole file but the actual // amount mapped is determined by MapViewOfFile mappingSize.LowPart, NULL); // Mapping name if (NULL == hMap_) { return IOErrorFromWindowsError( ""WindowsMmapFile failed to create file mapping for: "" + filename_, GetLastError()); } } ULARGE_INTEGER offset; offset.QuadPart = file_offset_; // View must begin at the granularity aligned offset mapped_begin_ = reinterpret_cast( MapViewOfFileEx(hMap_, FILE_MAP_WRITE, offset.HighPart, offset.LowPart, view_size_, NULL)); if (!mapped_begin_) { status = IOErrorFromWindowsError( ""WindowsMmapFile failed to map file view: "" + filename_, GetLastError()); } else { mapped_end_ = mapped_begin_ + view_size_; dst_ = mapped_begin_; last_sync_ = mapped_begin_; pending_sync_ = false; } return status; } public: WinMmapFile(const std::string& fname, HANDLE hFile, size_t page_size, size_t allocation_granularity, const EnvOptions& options) : filename_(fname), hFile_(hFile), hMap_(NULL), page_size_(page_size), allocation_granularity_(allocation_granularity), mapping_size_(0), view_size_(0), mapped_begin_(nullptr), mapped_end_(nullptr), dst_(nullptr), last_sync_(nullptr), file_offset_(0), pending_sync_(false) { // Allocation granularity must be obtained from GetSystemInfo() and must be // a power of two. assert(allocation_granularity > 0); assert((allocation_granularity & (allocation_granularity - 1)) == 0); assert(page_size > 0); assert((page_size & (page_size - 1)) == 0); // Only for memory mapped writes assert(options.use_mmap_writes); // Make sure buffering is not disabled. It is ignored for mapping // purposes but also imposes restriction on moving file position // it is not a problem so much with reserving space since it is probably a // factor // of allocation_granularity but we also want to truncate the file in // Close() at // arbitrary position so we do not have to feel this with zeros. assert(options.use_os_buffer); // View size must be both the multiple of allocation_granularity AND the // page size if ((allocation_granularity_ % page_size_) == 0) { view_size_ = 2 * allocation_granularity; } else if ((page_size_ % allocation_granularity_) == 0) { view_size_ = 2 * page_size_; } else { // we can multiply them together assert(false); } } ~WinMmapFile() { if (hFile_) { this->Close(); } } virtual Status Append(const Slice& data) override { const char* src = data.data(); size_t left = data.size(); while (left > 0) { assert(mapped_begin_ <= dst_); size_t avail = mapped_end_ - dst_; if (avail == 0) { Status s = UnmapCurrentRegion(); if (s.ok()) { s = MapNewRegion(); } if (!s.ok()) { return s; } } size_t n = std::min(left, avail); memcpy(dst_, src, n); dst_ += n; src += n; left -= n; pending_sync_ = true; } return Status::OK(); } // Means Close() will properly take care of truncate // and it does not need any additional information virtual Status Truncate(uint64_t size) override { return Status::OK(); } virtual Status Close() override { Status s; assert(NULL != hFile_); // We truncate to the precise size so no // uninitialized data at the end. SetEndOfFile // which we use does not write zeros and it is good. uint64_t targetSize = GetFileSize(); s = UnmapCurrentRegion(); if (NULL != hMap_) { BOOL ret = ::CloseHandle(hMap_); if (!ret && s.ok()) { auto lastError = GetLastError(); s = IOErrorFromWindowsError( ""Failed to Close mapping for file: "" + filename_, lastError); } hMap_ = NULL; } TruncateFile(targetSize); BOOL ret = ::CloseHandle(hFile_); hFile_ = NULL; if (!ret && s.ok()) { auto lastError = GetLastError(); s = IOErrorFromWindowsError( ""Failed to close file map handle: "" + filename_, lastError); } return s; } virtual Status Flush() override { return Status::OK(); } // Flush only data virtual Status Sync() override { Status s; // Some writes occurred since last sync if (pending_sync_) { assert(mapped_begin_); assert(dst_); assert(dst_ > mapped_begin_); assert(dst_ < mapped_end_); size_t page_begin = TruncateToPageBoundary(page_size_, last_sync_ - mapped_begin_); size_t page_end = TruncateToPageBoundary(page_size_, dst_ - mapped_begin_ - 1); last_sync_ = dst_; // Flush only the amount of that is a multiple of pages if (!::FlushViewOfFile(mapped_begin_ + page_begin, (page_end - page_begin) + page_size_)) { s = IOErrorFromWindowsError(""Failed to FlushViewOfFile: "" + filename_, GetLastError()); } pending_sync_ = false; } return s; } /** * Flush data as well as metadata to stable storage. */ virtual Status Fsync() override { Status s; // Flush metadata if pending const bool pending = pending_sync_; s = Sync(); // Flush metadata if (s.ok() && pending) { if (!::FlushFileBuffers(hFile_)) { s = IOErrorFromWindowsError(""Failed to FlushFileBuffers: "" + filename_, GetLastError()); } } return s; } /** * Get the size of valid data in the file. This will not match the * size that is returned from the filesystem because we use mmap * to extend file by map_size every time. */ virtual uint64_t GetFileSize() override { size_t used = dst_ - mapped_begin_; return file_offset_ + used; } virtual Status InvalidateCache(size_t offset, size_t length) override { return Status::OK(); } virtual Status Allocate(uint64_t offset, uint64_t len) override { return Status::OK(); } }; class WinSequentialFile : public SequentialFile { private: const std::string filename_; HANDLE file_; // There is no equivalent of advising away buffered pages as in posix. // To implement this flag we would need to do unbuffered reads which // will need to be aligned (not sure there is a guarantee that the buffer // passed in is aligned). // Hence we currently ignore this flag. It is used only in a few cases // which should not be perf critical. // If perf evaluation finds this to be a problem, we can look into // implementing this. bool use_os_buffer_; public: WinSequentialFile(const std::string& fname, HANDLE f, const EnvOptions& options) : filename_(fname), file_(f), use_os_buffer_(options.use_os_buffer) {} virtual ~WinSequentialFile() { assert(file_ != INVALID_HANDLE_VALUE); CloseHandle(file_); } virtual Status Read(size_t n, Slice* result, char* scratch) override { Status s; size_t r = 0; // Windows ReadFile API accepts a DWORD. // While it is possible to read in a loop if n is > UINT_MAX // it is a highly unlikely case. if (n > UINT_MAX) { return IOErrorFromWindowsError(filename_, ERROR_INVALID_PARAMETER); } DWORD bytesToRead = static_cast(n); //cast is safe due to the check above DWORD bytesRead = 0; BOOL ret = ReadFile(file_, scratch, bytesToRead, &bytesRead, NULL); if (ret == TRUE) { r = bytesRead; } else { return IOErrorFromWindowsError(filename_, GetLastError()); } *result = Slice(scratch, r); return s; } virtual Status Skip(uint64_t n) override { // Can't handle more than signed max as SetFilePointerEx accepts a signed 64-bit // integer. As such it is a highly unlikley case to have n so large. if (n > _I64_MAX) { return IOErrorFromWindowsError(filename_, ERROR_INVALID_PARAMETER); } LARGE_INTEGER li; li.QuadPart = static_cast(n); //cast is safe due to the check above BOOL ret = SetFilePointerEx(file_, li, NULL, FILE_CURRENT); if (ret == FALSE) { return IOErrorFromWindowsError(filename_, GetLastError()); } return Status::OK(); } virtual Status InvalidateCache(size_t offset, size_t length) override { return Status::OK(); } }; // pread() based random-access class WinRandomAccessFile : public RandomAccessFile { const std::string filename_; HANDLE hFile_; const bool use_os_buffer_; bool read_ahead_; const size_t compaction_readahead_size_; const size_t random_access_max_buffer_size_; mutable std::mutex buffer_mut_; mutable AlignedBuffer buffer_; mutable uint64_t buffered_start_; // file offset set that is currently buffered /* * The function reads a requested amount of bytes into the specified aligned * buffer Upon success the function sets the length of the buffer to the * amount of bytes actually read even though it might be less than actually * requested. It then copies the amount of bytes requested by the user (left) * to the user supplied buffer (dest) and reduces left by the amount of bytes * copied to the user buffer * * @user_offset [in] - offset on disk where the read was requested by the user * @first_page_start [in] - actual page aligned disk offset that we want to * read from * @bytes_to_read [in] - total amount of bytes that will be read from disk * which is generally greater or equal to the amount * that the user has requested due to the * either alignment requirements or read_ahead in * effect. * @left [in/out] total amount of bytes that needs to be copied to the user * buffer. It is reduced by the amount of bytes that actually * copied * @buffer - buffer to use * @dest - user supplied buffer */ SSIZE_T ReadIntoBuffer(uint64_t user_offset, uint64_t first_page_start, size_t bytes_to_read, size_t& left, AlignedBuffer& buffer, char* dest) const { assert(buffer.CurrentSize() == 0); assert(buffer.Capacity() >= bytes_to_read); SSIZE_T read = pread(hFile_, buffer.Destination(), bytes_to_read, first_page_start); if (read > 0) { buffer.Size(read); // Let's figure out how much we read from the users standpoint if ((first_page_start + buffer.CurrentSize()) > user_offset) { assert(first_page_start <= user_offset); size_t buffer_offset = user_offset - first_page_start; read = buffer.Read(dest, buffer_offset, left); } else { read = 0; } left -= read; } return read; } SSIZE_T ReadIntoOneShotBuffer(uint64_t user_offset, uint64_t first_page_start, size_t bytes_to_read, size_t& left, char* dest) const { AlignedBuffer bigBuffer; bigBuffer.Alignment(buffer_.Alignment()); bigBuffer.AllocateNewBuffer(bytes_to_read); return ReadIntoBuffer(user_offset, first_page_start, bytes_to_read, left, bigBuffer, dest); } SSIZE_T ReadIntoInstanceBuffer(uint64_t user_offset, uint64_t first_page_start, size_t bytes_to_read, size_t& left, char* dest) const { SSIZE_T read = ReadIntoBuffer(user_offset, first_page_start, bytes_to_read, left, buffer_, dest); if (read > 0) { buffered_start_ = first_page_start; } return read; } void CalculateReadParameters(uint64_t offset, size_t bytes_requested, size_t& actual_bytes_toread, uint64_t& first_page_start) const { const size_t alignment = buffer_.Alignment(); first_page_start = TruncateToPageBoundary(alignment, offset); const uint64_t last_page_start = TruncateToPageBoundary(alignment, offset + bytes_requested - 1); actual_bytes_toread = (last_page_start - first_page_start) + alignment; } public: WinRandomAccessFile(const std::string& fname, HANDLE hFile, size_t alignment, const EnvOptions& options) : filename_(fname), hFile_(hFile), use_os_buffer_(options.use_os_buffer), read_ahead_(false), compaction_readahead_size_(options.compaction_readahead_size), random_access_max_buffer_size_(options.random_access_max_buffer_size), buffer_(), buffered_start_(0) { assert(!options.use_mmap_reads); // Unbuffered access, use internal buffer for reads if (!use_os_buffer_) { // Do not allocate the buffer either until the first request or // until there is a call to allocate a read-ahead buffer buffer_.Alignment(alignment); } } virtual ~WinRandomAccessFile() { if (hFile_ != NULL && hFile_ != INVALID_HANDLE_VALUE) { ::CloseHandle(hFile_); } } virtual void EnableReadAhead() override { this->Hint(SEQUENTIAL); } virtual Status Read(uint64_t offset, size_t n, Slice* result, char* scratch) const override { Status s; SSIZE_T r = -1; size_t left = n; char* dest = scratch; if (n == 0) { *result = Slice(scratch, 0); return s; } // When in unbuffered mode we need to do the following changes: // - use our own aligned buffer // - always read at the offset of that is a multiple of alignment if (!use_os_buffer_) { uint64_t first_page_start = 0; size_t actual_bytes_toread = 0; size_t bytes_requested = left; if (!read_ahead_ && random_access_max_buffer_size_ == 0) { CalculateReadParameters(offset, bytes_requested, actual_bytes_toread, first_page_start); assert(actual_bytes_toread > 0); r = ReadIntoOneShotBuffer(offset, first_page_start, actual_bytes_toread, left, dest); } else { std::unique_lock lock(buffer_mut_); // Let's see if at least some of the requested data is already // in the buffer if (offset >= buffered_start_ && offset < (buffered_start_ + buffer_.CurrentSize())) { size_t buffer_offset = offset - buffered_start_; r = buffer_.Read(dest, buffer_offset, left); assert(r >= 0); left -= size_t(r); offset += r; dest += r; } // Still some left or none was buffered if (left > 0) { // Figure out the start/end offset for reading and amount to read bytes_requested = left; if (read_ahead_ && bytes_requested < compaction_readahead_size_) { bytes_requested = compaction_readahead_size_; } CalculateReadParameters(offset, bytes_requested, actual_bytes_toread, first_page_start); assert(actual_bytes_toread > 0); if (buffer_.Capacity() < actual_bytes_toread) { // If we are in read-ahead mode or the requested size // exceeds max buffer size then use one-shot // big buffer otherwise reallocate main buffer if (read_ahead_ || (actual_bytes_toread > random_access_max_buffer_size_)) { // Unlock the mutex since we are not using instance buffer lock.unlock(); r = ReadIntoOneShotBuffer(offset, first_page_start, actual_bytes_toread, left, dest); } else { buffer_.AllocateNewBuffer(actual_bytes_toread); r = ReadIntoInstanceBuffer(offset, first_page_start, actual_bytes_toread, left, dest); } } else { buffer_.Clear(); r = ReadIntoInstanceBuffer(offset, first_page_start, actual_bytes_toread, left, dest); } } } } else { r = pread(hFile_, scratch, left, offset); if (r > 0) { left -= r; } } *result = Slice(scratch, (r < 0) ? 0 : n - left); if (r < 0) { s = IOErrorFromLastWindowsError(filename_); } return s; } virtual bool ShouldForwardRawRequest() const override { return true; } virtual void Hint(AccessPattern pattern) override { if (pattern == SEQUENTIAL && !use_os_buffer_ && compaction_readahead_size_ > 0) { std::lock_guard lg(buffer_mut_); if (!read_ahead_) { read_ahead_ = true; // This would allocate read-ahead size + 2 alignments // - one for memory alignment which added implicitly by AlignedBuffer // - We add one more alignment because we will read one alignment more // from disk buffer_.AllocateNewBuffer(compaction_readahead_size_ + buffer_.Alignment()); } } } virtual Status InvalidateCache(size_t offset, size_t length) override { return Status::OK(); } }; // This is a sequential write class. It has been mimicked (as others) after // the original Posix class. We add support for unbuffered I/O on windows as // well // we utilize the original buffer as an alignment buffer to write directly to // file with no buffering. // No buffering requires that the provided buffer is aligned to the physical // sector size (SSD page size) and // that all SetFilePointer() operations to occur with such an alignment. // We thus always write in sector/page size increments to the drive and leave // the tail for the next write OR for Close() at which point we pad with zeros. // No padding is required for // buffered access. class WinWritableFile : public WritableFile { private: const std::string filename_; HANDLE hFile_; const bool use_os_buffer_; // Used to indicate unbuffered access, the file const uint64_t alignment_; // must be opened as unbuffered if false uint64_t filesize_; // How much data is actually written disk uint64_t reservedsize_; // how far we have reserved space public: WinWritableFile(const std::string& fname, HANDLE hFile, size_t alignment, size_t capacity, const EnvOptions& options) : filename_(fname), hFile_(hFile), use_os_buffer_(options.use_os_buffer), alignment_(alignment), filesize_(0), reservedsize_(0) { assert(!options.use_mmap_writes); } ~WinWritableFile() { if (NULL != hFile_ && INVALID_HANDLE_VALUE != hFile_) { WinWritableFile::Close(); } } // Indicates if the class makes use of unbuffered I/O virtual bool UseOSBuffer() const override { return use_os_buffer_; } virtual size_t GetRequiredBufferAlignment() const override { return alignment_; } virtual Status Append(const Slice& data) override { // Used for buffered access ONLY assert(use_os_buffer_); assert(data.size() < std::numeric_limits::max()); Status s; DWORD bytesWritten = 0; if (!WriteFile(hFile_, data.data(), static_cast(data.size()), &bytesWritten, NULL)) { auto lastError = GetLastError(); s = IOErrorFromWindowsError( ""Failed to WriteFile: "" + filename_, lastError); } else { assert(size_t(bytesWritten) == data.size()); filesize_ += data.size(); } return s; } virtual Status PositionedAppend(const Slice& data, uint64_t offset) override { Status s; SSIZE_T ret = pwrite(hFile_, data.data(), data.size(), offset); // Error break if (ret < 0) { auto lastError = GetLastError(); s = IOErrorFromWindowsError( ""Failed to pwrite for: "" + filename_, lastError); } else { // With positional write it is not clear at all // if this actually extends the filesize assert(size_t(ret) == data.size()); filesize_ += data.size(); } return s; } // Need to implement this so the file is truncated correctly // when buffered and unbuffered mode virtual Status Truncate(uint64_t size) override { Status s = ftruncate(filename_, hFile_, size); if (s.ok()) { filesize_ = size; } return s; } virtual Status Close() override { Status s; assert(INVALID_HANDLE_VALUE != hFile_); if (fsync(hFile_) < 0) { auto lastError = GetLastError(); s = IOErrorFromWindowsError(""fsync failed at Close() for: "" + filename_, lastError); } if (FALSE == ::CloseHandle(hFile_)) { auto lastError = GetLastError(); s = IOErrorFromWindowsError(""CloseHandle failed for: "" + filename_, lastError); } hFile_ = INVALID_HANDLE_VALUE; return s; } // write out the cached data to the OS cache // This is now taken care of the WritableFileWriter virtual Status Flush() override { return Status::OK(); } virtual Status Sync() override { Status s; // Calls flush buffers if (fsync(hFile_) < 0) { auto lastError = GetLastError(); s = IOErrorFromWindowsError(""fsync failed at Sync() for: "" + filename_, lastError); } return s; } virtual Status Fsync() override { return Sync(); } virtual uint64_t GetFileSize() override { // Double accounting now here with WritableFileWriter // and this size will be wrong when unbuffered access is used // but tests implement their own writable files and do not use WritableFileWrapper // so we need to squeeze a square peg through // a round hole here. return filesize_; } virtual Status Allocate(uint64_t offset, uint64_t len) override { Status status; TEST_KILL_RANDOM(""WinWritableFile::Allocate"", rocksdb_kill_odds); // Make sure that we reserve an aligned amount of space // since the reservation block size is driven outside so we want // to check if we are ok with reservation here size_t spaceToReserve = Roundup(offset + len, alignment_); // Nothing to do if (spaceToReserve <= reservedsize_) { return status; } IOSTATS_TIMER_GUARD(allocate_nanos); status = fallocate(filename_, hFile_, spaceToReserve); if (status.ok()) { reservedsize_ = spaceToReserve; } return status; } }; class WinDirectory : public Directory { public: WinDirectory() {} virtual Status Fsync() override { return Status::OK(); } }; class WinFileLock : public FileLock { public: explicit WinFileLock(HANDLE hFile) : hFile_(hFile) { assert(hFile != NULL); assert(hFile != INVALID_HANDLE_VALUE); } ~WinFileLock() { BOOL ret = ::CloseHandle(hFile_); assert(ret); } private: HANDLE hFile_; }; namespace { void WinthreadCall(const char* label, std::error_code result) { if (0 != result.value()) { fprintf(stderr, ""pthread %s: %s\\n"", label, strerror(result.value())); abort(); } } } typedef VOID(WINAPI * FnGetSystemTimePreciseAsFileTime)(LPFILETIME); class WinEnv : public Env { public: WinEnv(); virtual ~WinEnv() { for (auto& th : threads_to_join_) { th.join(); } threads_to_join_.clear(); for (auto& thpool : thread_pools_) { thpool.JoinAllThreads(); } // All threads must be joined before the deletion of // thread_status_updater_. delete thread_status_updater_; } virtual Status DeleteFile(const std::string& fname) override { Status result; if (_unlink(fname.c_str())) { result = IOError(""Failed to delete: "" + fname, errno); } return result; } Status GetCurrentTime(int64_t* unix_time) override { time_t time = std::time(nullptr); if (time == (time_t)(-1)) { return Status::NotSupported(""Failed to get time""); } *unix_time = time; return Status::OK(); } virtual Status NewSequentialFile(const std::string& fname, std::unique_ptr* result, const EnvOptions& options) override { Status s; result->reset(); // Corruption test needs to rename and delete files of these kind // while they are still open with another handle. For that reason we // allow share_write and delete(allows rename). HANDLE hFile = INVALID_HANDLE_VALUE; { IOSTATS_TIMER_GUARD(open_nanos); hFile = CreateFileA( fname.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, // Original fopen mode is ""rb"" FILE_ATTRIBUTE_NORMAL, NULL); } if (INVALID_HANDLE_VALUE == hFile) { auto lastError = GetLastError(); s = IOErrorFromWindowsError(""Failed to open NewSequentialFile"" + fname, lastError); } else { result->reset(new WinSequentialFile(fname, hFile, options)); } return s; } virtual Status NewRandomAccessFile(const std::string& fname, std::unique_ptr* result, const EnvOptions& options) override { result->reset(); Status s; // Open the file for read-only random access // Random access is to disable read-ahead as the system reads too much data DWORD fileFlags = FILE_ATTRIBUTE_READONLY; if (!options.use_os_buffer && !options.use_mmap_reads) { fileFlags |= FILE_FLAG_NO_BUFFERING; } else { fileFlags |= FILE_FLAG_RANDOM_ACCESS; } /// Shared access is necessary for corruption test to pass // almost all tests would work with a possible exception of fault_injection HANDLE hFile = 0; { IOSTATS_TIMER_GUARD(open_nanos); hFile = CreateFileA(fname.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, fileFlags, NULL); } if (INVALID_HANDLE_VALUE == hFile) { auto lastError = GetLastError(); return IOErrorFromWindowsError( ""NewRandomAccessFile failed to Create/Open: "" + fname, lastError); } UniqueCloseHandlePtr fileGuard(hFile, CloseHandleFunc); // CAUTION! This will map the entire file into the process address space if (options.use_mmap_reads && sizeof(void*) >= 8) { // Use mmap when virtual address-space is plentiful. uint64_t fileSize; s = GetFileSize(fname, &fileSize); if (s.ok()) { // Will not map empty files if (fileSize == 0) { return IOError( ""NewRandomAccessFile failed to map empty file: "" + fname, EINVAL); } HANDLE hMap = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, // Whole file at its present length 0, NULL); // Mapping name if (!hMap) { auto lastError = GetLastError(); return IOErrorFromWindowsError( ""Failed to create file mapping for NewRandomAccessFile: "" + fname, lastError); } UniqueCloseHandlePtr mapGuard(hMap, CloseHandleFunc); const void* mapped_region = MapViewOfFileEx(hMap, FILE_MAP_READ, 0, // High DWORD of access start 0, // Low DWORD fileSize, NULL); // Let the OS choose the mapping if (!mapped_region) { auto lastError = GetLastError(); return IOErrorFromWindowsError( ""Failed to MapViewOfFile for NewRandomAccessFile: "" + fname, lastError); } result->reset(new WinMmapReadableFile(fname, hFile, hMap, mapped_region, fileSize)); mapGuard.release(); fileGuard.release(); } } else { result->reset(new WinRandomAccessFile(fname, hFile, page_size_, options)); fileGuard.release(); } return s; } virtual Status NewWritableFile(const std::string& fname, std::unique_ptr* result, const EnvOptions& options) override { const size_t c_BufferCapacity = 64 * 1024; EnvOptions local_options(options); result->reset(); Status s; DWORD fileFlags = FILE_ATTRIBUTE_NORMAL; if (!local_options.use_os_buffer && !local_options.use_mmap_writes) { fileFlags = FILE_FLAG_NO_BUFFERING; } // Desired access. We are want to write only here but if we want to memory // map // the file then there is no write only mode so we have to create it // Read/Write // However, MapViewOfFile specifies only Write only DWORD desired_access = GENERIC_WRITE; DWORD shared_mode = FILE_SHARE_READ; if (local_options.use_mmap_writes) { desired_access |= GENERIC_READ; } else { // Adding this solely for tests to pass (fault_injection_test, // wal_manager_test). shared_mode |= (FILE_SHARE_WRITE | FILE_SHARE_DELETE); } HANDLE hFile = 0; { IOSTATS_TIMER_GUARD(open_nanos); hFile = CreateFileA( fname.c_str(), desired_access, // Access desired shared_mode, NULL, // Security attributes CREATE_ALWAYS, // Posix env says O_CREAT | O_RDWR | O_TRUNC fileFlags, // Flags NULL); // Template File } if (INVALID_HANDLE_VALUE == hFile) { auto lastError = GetLastError(); return IOErrorFromWindowsError( ""Failed to create a NewWriteableFile: "" + fname, lastError); } if (options.use_mmap_writes) { // We usually do not use mmmapping on SSD and thus we pass memory // page_size result->reset(new WinMmapFile(fname, hFile, page_size_, allocation_granularity_, local_options)); } else { // Here we want the buffer allocation to be aligned by the SSD page size // and to be a multiple of it result->reset(new WinWritableFile(fname, hFile, page_size_, c_BufferCapacity, local_options)); } return s; } virtual Status NewDirectory(const std::string& name, std::unique_ptr* result) override { Status s; // Must be nullptr on failure result->reset(); // Must fail if directory does not exist if (!DirExists(name)) { s = IOError(""Directory does not exist: "" + name, EEXIST); } else { IOSTATS_TIMER_GUARD(open_nanos); result->reset(new WinDirectory); } return s; } virtual Status FileExists(const std::string& fname) override { // F_OK == 0 const int F_OK_ = 0; return _access(fname.c_str(), F_OK_) == 0 ? Status::OK() : Status::NotFound(); } virtual Status GetChildren(const std::string& dir, std::vector* result) override { std::vector output; Status status; auto CloseDir = [](DIR* p) { closedir(p); }; std::unique_ptr dirp(opendir(dir.c_str()), CloseDir); if (!dirp) { status = IOError(dir, errno); } else { if (result->capacity() > 0) { output.reserve(result->capacity()); } struct dirent* ent = readdir(dirp.get()); while (ent) { output.push_back(ent->d_name); ent = readdir(dirp.get()); } } output.swap(*result); return status; } virtual Status CreateDir(const std::string& name) override { Status result; if (_mkdir(name.c_str()) != 0) { auto code = errno; result = IOError(""Failed to create dir: "" + name, code); } return result; } virtual Status CreateDirIfMissing(const std::string& name) override { Status result; if (DirExists(name)) { return result; } if (_mkdir(name.c_str()) != 0) { if (errno == EEXIST) { result = Status::IOError(""`"" + name + ""' exists but is not a directory""); } else { auto code = errno; result = IOError(""Failed to create dir: "" + name, code); } } return result; } virtual Status DeleteDir(const std::string& name) override { Status result; if (_rmdir(name.c_str()) != 0) { auto code = errno; result = IOError(""Failed to remove dir: "" + name, code); } return result; } virtual Status GetFileSize(const std::string& fname, uint64_t* size) override { Status s; WIN32_FILE_ATTRIBUTE_DATA attrs; if (GetFileAttributesExA(fname.c_str(), GetFileExInfoStandard, &attrs)) { ULARGE_INTEGER file_size; file_size.HighPart = attrs.nFileSizeHigh; file_size.LowPart = attrs.nFileSizeLow; *size = file_size.QuadPart; } else { auto lastError = GetLastError(); s = IOErrorFromWindowsError(""Can not get size for: "" + fname, lastError); } return s; } static inline uint64_t FileTimeToUnixTime(const FILETIME& ftTime) { const uint64_t c_FileTimePerSecond = 10000000U; // UNIX epoch starts on 1970-01-01T00:00:00Z // Windows FILETIME starts on 1601-01-01T00:00:00Z // Therefore, we need to subtract the below number of seconds from // the seconds that we obtain from FILETIME with an obvious loss of // precision const uint64_t c_SecondBeforeUnixEpoch = 11644473600U; ULARGE_INTEGER li; li.HighPart = ftTime.dwHighDateTime; li.LowPart = ftTime.dwLowDateTime; uint64_t result = (li.QuadPart / c_FileTimePerSecond) - c_SecondBeforeUnixEpoch; return result; } virtual Status GetFileModificationTime(const std::string& fname, uint64_t* file_mtime) override { Status s; WIN32_FILE_ATTRIBUTE_DATA attrs; if (GetFileAttributesExA(fname.c_str(), GetFileExInfoStandard, &attrs)) { *file_mtime = FileTimeToUnixTime(attrs.ftLastWriteTime); } else { auto lastError = GetLastError(); s = IOErrorFromWindowsError( ""Can not get file modification time for: "" + fname, lastError); *file_mtime = 0; } return s; } virtual Status RenameFile(const std::string& src, const std::string& target) override { Status result; // rename() is not capable of replacing the existing file as on Linux // so use OS API directly if (!MoveFileExA(src.c_str(), target.c_str(), MOVEFILE_REPLACE_EXISTING)) { DWORD lastError = GetLastError(); std::string text(""Failed to rename: ""); text.append(src).append("" to: "").append(target); result = IOErrorFromWindowsError(text, lastError); } return result; } virtual Status LinkFile(const std::string& src, const std::string& target) override { Status result; if (!CreateHardLinkA(target.c_str(), src.c_str(), NULL)) { DWORD lastError = GetLastError(); std::string text(""Failed to link: ""); text.append(src).append("" to: "").append(target); result = IOErrorFromWindowsError(text, lastError); } return result; } virtual Status LockFile(const std::string& lockFname, FileLock** lock) override { assert(lock != nullptr); *lock = NULL; Status result; // No-sharing, this is a LOCK file const DWORD ExclusiveAccessON = 0; // Obtain exclusive access to the LOCK file // Previously, instead of NORMAL attr we set DELETE on close and that worked // well except with fault_injection test that insists on deleting it. HANDLE hFile = 0; { IOSTATS_TIMER_GUARD(open_nanos); hFile = CreateFileA(lockFname.c_str(), (GENERIC_READ | GENERIC_WRITE), ExclusiveAccessON, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); } if (INVALID_HANDLE_VALUE == hFile) { auto lastError = GetLastError(); result = IOErrorFromWindowsError( ""Failed to create lock file: "" + lockFname, lastError); } else { *lock = new WinFileLock(hFile); } return result; } virtual Status UnlockFile(FileLock* lock) override { Status result; assert(lock != nullptr); delete lock; return result; } virtual void Schedule(void (*function)(void*), void* arg, Priority pri = LOW, void* tag = nullptr, void (*unschedFunction)(void* arg) = 0) override; virtual int UnSchedule(void* arg, Priority pri) override; virtual void StartThread(void (*function)(void* arg), void* arg) override; virtual void WaitForJoin() override; virtual unsigned int GetThreadPoolQueueLen(Priority pri = LOW) const override; virtual Status GetTestDirectory(std::string* result) override { std::string output; const char* env = getenv(""TEST_TMPDIR""); if (env && env[0] != '\\0') { output = env; CreateDir(output); } else { env = getenv(""TMP""); if (env && env[0] != '\\0') { output = env; } else { output = ""c:\\\\tmp""; } CreateDir(output); } output.append(""\\\\testrocksdb-""); output.append(std::to_string(_getpid())); CreateDir(output); output.swap(*result); return Status::OK(); } virtual Status GetThreadList( std::vector* thread_list) override { assert(thread_status_updater_); return thread_status_updater_->GetThreadList(thread_list); } static uint64_t gettid() { uint64_t thread_id = GetCurrentThreadId(); return thread_id; } virtual uint64_t GetThreadID() const override { return gettid(); } virtual Status NewLogger(const std::string& fname, std::shared_ptr* result) override { Status s; result->reset(); HANDLE hFile = 0; { IOSTATS_TIMER_GUARD(open_nanos); hFile = CreateFileA( fname.c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_DELETE, // In RocksDb log files are // renamed and deleted before // they are closed. This enables // doing so. NULL, CREATE_ALWAYS, // Original fopen mode is ""w"" FILE_ATTRIBUTE_NORMAL, NULL); } if (INVALID_HANDLE_VALUE == hFile) { auto lastError = GetLastError(); s = IOErrorFromWindowsError(""Failed to open LogFile"" + fname, lastError); } else { { // With log files we want to set the true creation time as of now // because the system // for some reason caches the attributes of the previous file that just // been renamed from // this name so auto_roll_logger_test fails FILETIME ft; GetSystemTimeAsFileTime(&ft); // Set creation, last access and last write time to the same value SetFileTime(hFile, &ft, &ft, &ft); } result->reset(new WinLogger(&WinEnv::gettid, this, hFile)); } return s; } virtual uint64_t NowMicros() override { if (GetSystemTimePreciseAsFileTime_ != NULL) { // all std::chrono clocks on windows proved to return // values that may repeat that is not good enough for some uses. const int64_t c_UnixEpochStartTicks = 116444736000000000i64; const int64_t c_FtToMicroSec = 10; // This interface needs to return system time and not // just any microseconds because it is often used as an argument // to TimedWait() on condition variable FILETIME ftSystemTime; GetSystemTimePreciseAsFileTime_(&ftSystemTime); LARGE_INTEGER li; li.LowPart = ftSystemTime.dwLowDateTime; li.HighPart = ftSystemTime.dwHighDateTime; // Subtract unix epoch start li.QuadPart -= c_UnixEpochStartTicks; // Convert to microsecs li.QuadPart /= c_FtToMicroSec; return li.QuadPart; } using namespace std::chrono; return duration_cast(system_clock::now().time_since_epoch()).count(); } virtual uint64_t NowNanos() override { // all std::chrono clocks on windows have the same resolution that is only // good enough for microseconds but not nanoseconds // On Windows 8 and Windows 2012 Server // GetSystemTimePreciseAsFileTime(¤t_time) can be used LARGE_INTEGER li; QueryPerformanceCounter(&li); // Convert to nanoseconds first to avoid loss of precision // and divide by frequency li.QuadPart *= std::nano::den; li.QuadPart /= perf_counter_frequency_; return li.QuadPart; } virtual void SleepForMicroseconds(int micros) override { std::this_thread::sleep_for(std::chrono::microseconds(micros)); } virtual Status GetHostName(char* name, uint64_t len) override { Status s; DWORD nSize = static_cast(std::min(len, std::numeric_limits::max())); if (!::GetComputerNameA(name, &nSize)) { auto lastError = GetLastError(); s = IOErrorFromWindowsError(""GetHostName"", lastError); } else { name[nSize] = 0; } return s; } virtual Status GetCurrTime(int64_t* unix_time) { Status s; time_t ret = time(nullptr); if (ret == (time_t)-1) { *unix_time = 0; s = IOError(""GetCurrTime"", errno); } else { *unix_time = (int64_t)ret; } return s; } virtual Status GetAbsolutePath(const std::string& db_path, std::string* output_path) override { // Check if we already have an absolute path // that starts with non dot and has a semicolon in it if ((!db_path.empty() && (db_path[0] == '/' || db_path[0] == '\\\\')) || (db_path.size() > 2 && db_path[0] != '.' && ((db_path[1] == ':' && db_path[2] == '\\\\') || (db_path[1] == ':' && db_path[2] == '/')))) { *output_path = db_path; return Status::OK(); } std::string result; result.resize(_MAX_PATH); char* ret = _getcwd(&result[0], _MAX_PATH); if (ret == nullptr) { return Status::IOError(""Failed to get current working directory"", strerror(errno)); } result.resize(strlen(result.data())); result.swap(*output_path); return Status::OK(); } // Allow increasing the number of worker threads. virtual void SetBackgroundThreads(int num, Priority pri) override { assert(pri >= Priority::LOW && pri <= Priority::HIGH); thread_pools_[pri].SetBackgroundThreads(num); } virtual void IncBackgroundThreadsIfNeeded(int num, Priority pri) override { assert(pri >= Priority::LOW && pri <= Priority::HIGH); thread_pools_[pri].IncBackgroundThreadsIfNeeded(num); } virtual std::string TimeToString(uint64_t secondsSince1970) override { std::string result; const time_t seconds = secondsSince1970; const int maxsize = 64; struct tm t; errno_t ret = localtime_s(&t, &seconds); if (ret) { result = std::to_string(seconds); } else { result.resize(maxsize); char* p = &result[0]; int len = snprintf(p, maxsize, ""%04d/%02d/%02d-%02d:%02d:%02d "", t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec); assert(len > 0); result.resize(len); } return result; } EnvOptions OptimizeForLogWrite(const EnvOptions& env_options, const DBOptions& db_options) const override { EnvOptions optimized = env_options; optimized.use_mmap_writes = false; optimized.bytes_per_sync = db_options.wal_bytes_per_sync; optimized.use_os_buffer = true; // This is because we flush only whole pages on unbuffered io and // the last records are not guaranteed to be flushed. // TODO(icanadi) it's faster if fallocate_with_keep_size is false, but it // breaks TransactionLogIteratorStallAtLastRecord unit test. Fix the unit // test and make this false optimized.fallocate_with_keep_size = true; return optimized; } EnvOptions OptimizeForManifestWrite( const EnvOptions& env_options) const override { EnvOptions optimized = env_options; optimized.use_mmap_writes = false; optimized.use_os_buffer = true; optimized.fallocate_with_keep_size = true; return optimized; } private: // Returns true iff the named directory exists and is a directory. virtual bool DirExists(const std::string& dname) { WIN32_FILE_ATTRIBUTE_DATA attrs; if (GetFileAttributesExA(dname.c_str(), GetFileExInfoStandard, &attrs)) { return 0 != (attrs.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY); } return false; } bool SupportsFastAllocate(const std::string& /* path */) { return false; } class ThreadPool { public: ThreadPool() : total_threads_limit_(1), bgthreads_(0), queue_(), queue_len_(0U), exit_all_threads_(false), low_io_priority_(false), env_(nullptr) {} ~ThreadPool() { assert(bgthreads_.size() == 0U); } void JoinAllThreads() { { std::lock_guard lock(mu_); assert(!exit_all_threads_); exit_all_threads_ = true; bgsignal_.notify_all(); } for (std::thread& th : bgthreads_) { th.join(); } // Subject to assert in the __dtor bgthreads_.clear(); } void SetHostEnv(Env* env) { env_ = env; } // Return true if there is at least one thread needs to terminate. bool HasExcessiveThread() const { return bgthreads_.size() > total_threads_limit_; } // Return true iff the current thread is the excessive thread to terminate. // Always terminate the running thread that is added last, even if there are // more than one thread to terminate. bool IsLastExcessiveThread(size_t thread_id) const { return HasExcessiveThread() && thread_id == bgthreads_.size() - 1; } // Is one of the threads to terminate. bool IsExcessiveThread(size_t thread_id) const { return thread_id >= total_threads_limit_; } // Return the thread priority. // This would allow its member-thread to know its priority. Env::Priority GetThreadPriority() { return priority_; } // Set the thread priority. void SetThreadPriority(Env::Priority priority) { priority_ = priority; } void BGThread(size_t thread_id) { while (true) { // Wait until there is an item that is ready to run std::unique_lock uniqueLock(mu_); // Stop waiting if the thread needs to do work or needs to terminate. while (!exit_all_threads_ && !IsLastExcessiveThread(thread_id) && (queue_.empty() || IsExcessiveThread(thread_id))) { bgsignal_.wait(uniqueLock); } if (exit_all_threads_) { // mechanism to let BG threads exit safely uniqueLock.unlock(); break; } if (IsLastExcessiveThread(thread_id)) { // Current thread is the last generated one and is excessive. // We always terminate excessive thread in the reverse order of // generation time. std::thread& terminating_thread = bgthreads_.back(); auto tid = terminating_thread.get_id(); // Ensure that that this thread is ours assert(tid == std::this_thread::get_id()); terminating_thread.detach(); bgthreads_.pop_back(); if (HasExcessiveThread()) { // There is still at least more excessive thread to terminate. WakeUpAllThreads(); } uniqueLock.unlock(); PrintThreadInfo(thread_id, gettid()); break; } void (*function)(void*) = queue_.front().function; void* arg = queue_.front().arg; queue_.pop_front(); queue_len_.store(queue_.size(), std::memory_order_relaxed); uniqueLock.unlock(); (*function)(arg); } } // Helper struct for passing arguments when creating threads. struct BGThreadMetadata { ThreadPool* thread_pool_; size_t thread_id_; // Thread count in the thread. BGThreadMetadata(ThreadPool* thread_pool, size_t thread_id) : thread_pool_(thread_pool), thread_id_(thread_id) {} }; static void* BGThreadWrapper(void* arg) { std::unique_ptr meta( reinterpret_cast(arg)); size_t thread_id = meta->thread_id_; ThreadPool* tp = meta->thread_pool_; #if ROCKSDB_USING_THREAD_STATUS // for thread-status ThreadStatusUtil::RegisterThread( tp->env_, (tp->GetThreadPriority() == Env::Priority::HIGH ? ThreadStatus::HIGH_PRIORITY : ThreadStatus::LOW_PRIORITY)); #endif tp->BGThread(thread_id); #if ROCKSDB_USING_THREAD_STATUS ThreadStatusUtil::UnregisterThread(); #endif return nullptr; } void WakeUpAllThreads() { bgsignal_.notify_all(); } void SetBackgroundThreadsInternal(size_t num, bool allow_reduce) { std::lock_guard lg(mu_); if (exit_all_threads_) { return; } if (num > total_threads_limit_ || (num < total_threads_limit_ && allow_reduce)) { total_threads_limit_ = std::max(size_t(1), num); WakeUpAllThreads(); StartBGThreads(); } assert(total_threads_limit_ > 0); } void IncBackgroundThreadsIfNeeded(int num) { SetBackgroundThreadsInternal(num, false); } void SetBackgroundThreads(int num) { SetBackgroundThreadsInternal(num, true); } void StartBGThreads() { // Start background thread if necessary while (bgthreads_.size() < total_threads_limit_) { std::thread p_t(&ThreadPool::BGThreadWrapper, new BGThreadMetadata(this, bgthreads_.size())); bgthreads_.push_back(std::move(p_t)); } } void Schedule(void (*function)(void* arg1), void* arg, void* tag, void (*unschedFunction)(void* arg)) { std::lock_guard lg(mu_); if (exit_all_threads_) { return; } StartBGThreads(); // Add to priority queue queue_.push_back(BGItem()); queue_.back().function = function; queue_.back().arg = arg; queue_.back().tag = tag; queue_.back().unschedFunction = unschedFunction; queue_len_.store(queue_.size(), std::memory_order_relaxed); if (!HasExcessiveThread()) { // Wake up at least one waiting thread. bgsignal_.notify_one(); } else { // Need to wake up all threads to make sure the one woken // up is not the one to terminate. WakeUpAllThreads(); } } int UnSchedule(void* arg) { int count = 0; std::lock_guard lg(mu_); // Remove from priority queue BGQueue::iterator it = queue_.begin(); while (it != queue_.end()) { if (arg == (*it).tag) { void (*unschedFunction)(void*) = (*it).unschedFunction; void* arg1 = (*it).arg; if (unschedFunction != nullptr) { (*unschedFunction)(arg1); } it = queue_.erase(it); count++; } else { ++it; } } queue_len_.store(queue_.size(), std::memory_order_relaxed); return count; } unsigned int GetQueueLen() const { return static_cast( queue_len_.load(std::memory_order_relaxed)); } private: // Entry per Schedule() call struct BGItem { void* arg; void (*function)(void*); void* tag; void (*unschedFunction)(void*); }; typedef std::deque BGQueue; std::mutex mu_; std::condition_variable bgsignal_; size_t total_threads_limit_; std::vector bgthreads_; BGQueue queue_; std::atomic_size_t queue_len_; // Queue length. Used for stats reporting bool exit_all_threads_; bool low_io_priority_; Env::Priority priority_; Env* env_; }; bool checkedDiskForMmap_; bool forceMmapOff; // do we override Env options? size_t page_size_; size_t allocation_granularity_; uint64_t perf_counter_frequency_; std::vector thread_pools_; mutable std::mutex mu_; std::vector threads_to_join_; FnGetSystemTimePreciseAsFileTime GetSystemTimePreciseAsFileTime_; }; WinEnv::WinEnv() : checkedDiskForMmap_(false), forceMmapOff(false), page_size_(4 * 1012), allocation_granularity_(page_size_), perf_counter_frequency_(0), thread_pools_(Priority::TOTAL), GetSystemTimePreciseAsFileTime_(NULL) { HMODULE module = GetModuleHandle(""kernel32.dll""); if (module != NULL) { GetSystemTimePreciseAsFileTime_ = (FnGetSystemTimePreciseAsFileTime)GetProcAddress( module, ""GetSystemTimePreciseAsFileTime""); } SYSTEM_INFO sinfo; GetSystemInfo(&sinfo); page_size_ = sinfo.dwPageSize; allocation_granularity_ = sinfo.dwAllocationGranularity; { LARGE_INTEGER qpf; BOOL ret = QueryPerformanceFrequency(&qpf); assert(ret == TRUE); perf_counter_frequency_ = qpf.QuadPart; } for (int pool_id = 0; pool_id < Env::Priority::TOTAL; ++pool_id) { thread_pools_[pool_id].SetThreadPriority( static_cast(pool_id)); // This allows later initializing the thread-local-env of each thread. thread_pools_[pool_id].SetHostEnv(this); } // Protected member of the base class thread_status_updater_ = CreateThreadStatusUpdater(); } void WinEnv::Schedule(void (*function)(void*), void* arg, Priority pri, void* tag, void (*unschedFunction)(void* arg)) { assert(pri >= Priority::LOW && pri <= Priority::HIGH); thread_pools_[pri].Schedule(function, arg, tag, unschedFunction); } int WinEnv::UnSchedule(void* arg, Priority pri) { return thread_pools_[pri].UnSchedule(arg); } unsigned int WinEnv::GetThreadPoolQueueLen(Priority pri) const { assert(pri >= Priority::LOW && pri <= Priority::HIGH); return thread_pools_[pri].GetQueueLen(); } namespace { struct StartThreadState { void (*user_function)(void*); void* arg; }; } static void* StartThreadWrapper(void* arg) { std::unique_ptr state( reinterpret_cast(arg)); state->user_function(state->arg); return nullptr; } void WinEnv::StartThread(void (*function)(void* arg), void* arg) { StartThreadState* state = new StartThreadState; state->user_function = function; state->arg = arg; try { std::thread th(&StartThreadWrapper, state); std::lock_guard lg(mu_); threads_to_join_.push_back(std::move(th)); } catch (const std::system_error& ex) { WinthreadCall(""start thread"", ex.code()); } } void WinEnv::WaitForJoin() { for (auto& th : threads_to_join_) { th.join(); } threads_to_join_.clear(); } } // namespace std::string Env::GenerateUniqueId() { std::string result; UUID uuid; UuidCreateSequential(&uuid); RPC_CSTR rpc_str; auto status = UuidToStringA(&uuid, &rpc_str); assert(status == RPC_S_OK); result = reinterpret_cast(rpc_str); status = RpcStringFreeA(&rpc_str); assert(status == RPC_S_OK); return result; } // We choose to create this on the heap and using std::once for the following // reasons // 1) Currently available MS compiler does not implement atomic C++11 // initialization of // function local statics // 2) We choose not to destroy the env because joining the threads from the // system loader // which destroys the statics (same as from DLLMain) creates a system loader // dead-lock. // in this manner any remaining threads are terminated OK. namespace { std::once_flag winenv_once_flag; Env* envptr; }; Env* Env::Default() { std::call_once(winenv_once_flag, []() { envptr = new WinEnv(); }); return envptr; } } // namespace rocksdb ",16361,True,2812.4713591967393,median "// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include ""amount.h"" #include ""chain.h"" #include ""chainparams.h"" #include ""checkpoints.h"" #include ""coins.h"" #include ""consensus/validation.h"" #include ""validation.h"" #include ""policy/policy.h"" #include ""primitives/transaction.h"" #include ""rpc/server.h"" #include ""streams.h"" #include ""sync.h"" #include ""txmempool.h"" #include ""util.h"" #include ""utilstrencodings.h"" #include ""hash.h"" #include #include #include // boost::thread::interrupt #include #include using namespace std; struct CUpdatedBlock { uint256 hash; int height; }; static std::mutex cs_blockchange; static std::condition_variable cond_blockchange; static CUpdatedBlock latestblock; extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry); void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex); double GetDifficulty(const CBlockIndex* blockindex) { // Floating point number that is a multiple of the minimum difficulty, // minimum difficulty = 1.0. if (blockindex == NULL) { if (chainActive.Tip() == NULL) return 1.0; else blockindex = chainActive.Tip(); } int nShift = (blockindex->nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff); while (nShift < 29) { dDiff *= 256.0; nShift++; } while (nShift > 29) { dDiff /= 256.0; nShift--; } return dDiff; } UniValue blockheaderToJSON(const CBlockIndex* blockindex) { UniValue result(UniValue::VOBJ); result.push_back(Pair(""hash"", blockindex->GetBlockHash().GetHex())); result.push_back(Pair(""powhash"", blockindex->GetBlockPoWHash().GetHex())); int confirmations = -1; // Only report confirmations if the block is on the main chain if (chainActive.Contains(blockindex)) confirmations = chainActive.Height() - blockindex->nHeight + 1; result.push_back(Pair(""confirmations"", confirmations)); result.push_back(Pair(""height"", blockindex->nHeight)); result.push_back(Pair(""version"", blockindex->nVersion)); result.push_back(Pair(""versionHex"", strprintf(""%08x"", blockindex->nVersion))); result.push_back(Pair(""merkleroot"", blockindex->hashMerkleRoot.GetHex())); result.push_back(Pair(""time"", (int64_t)blockindex->nTime)); result.push_back(Pair(""mediantime"", (int64_t)blockindex->GetMedianTimePast())); result.push_back(Pair(""nonce"", (uint64_t)blockindex->nNonce)); result.push_back(Pair(""bits"", strprintf(""%08x"", blockindex->nBits))); result.push_back(Pair(""difficulty"", GetDifficulty(blockindex))); result.push_back(Pair(""chainwork"", blockindex->nChainWork.GetHex())); if (blockindex->pprev) result.push_back(Pair(""previousblockhash"", blockindex->pprev->GetBlockHash().GetHex())); CBlockIndex *pnext = chainActive.Next(blockindex); if (pnext) result.push_back(Pair(""nextblockhash"", pnext->GetBlockHash().GetHex())); return result; } UniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool txDetails = false) { UniValue result(UniValue::VOBJ); result.push_back(Pair(""hash"", blockindex->GetBlockHash().GetHex())); result.push_back(Pair(""powhash"", block.GetPoWHash(blockindex->nHeight >= Params().GetConsensus().BCDHeight).GetHex())); int confirmations = -1; // Only report confirmations if the block is on the main chain if (chainActive.Contains(blockindex)) confirmations = chainActive.Height() - blockindex->nHeight + 1; result.push_back(Pair(""confirmations"", confirmations)); result.push_back(Pair(""strippedsize"", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS))); result.push_back(Pair(""size"", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION))); result.push_back(Pair(""weight"", (int)::GetBlockWeight(block))); result.push_back(Pair(""height"", blockindex->nHeight)); result.push_back(Pair(""version"", block.nVersion)); result.push_back(Pair(""versionHex"", strprintf(""%08x"", block.nVersion))); result.push_back(Pair(""merkleroot"", block.hashMerkleRoot.GetHex())); UniValue txs(UniValue::VARR); for(const auto& tx : block.vtx) { if(txDetails) { UniValue objTx(UniValue::VOBJ); TxToJSON(*tx, uint256(), objTx); txs.push_back(objTx); } else txs.push_back(tx->GetHash().GetHex()); } result.push_back(Pair(""tx"", txs)); result.push_back(Pair(""time"", block.GetBlockTime())); result.push_back(Pair(""mediantime"", (int64_t)blockindex->GetMedianTimePast())); result.push_back(Pair(""nonce"", (uint64_t)block.nNonce)); result.push_back(Pair(""bits"", strprintf(""%08x"", block.nBits))); result.push_back(Pair(""difficulty"", GetDifficulty(blockindex))); result.push_back(Pair(""chainwork"", blockindex->nChainWork.GetHex())); if (blockindex->pprev) result.push_back(Pair(""previousblockhash"", blockindex->pprev->GetBlockHash().GetHex())); CBlockIndex *pnext = chainActive.Next(blockindex); if (pnext) result.push_back(Pair(""nextblockhash"", pnext->GetBlockHash().GetHex())); return result; } UniValue getblockcount(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw runtime_error( ""getblockcount\\n"" ""\\nReturns the number of blocks in the longest blockchain.\\n"" ""\\nResult:\\n"" ""n (numeric) The current block count\\n"" ""\\nExamples:\\n"" + HelpExampleCli(""getblockcount"", """") + HelpExampleRpc(""getblockcount"", """") ); LOCK(cs_main); return chainActive.Height(); } UniValue getbestblockhash(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw runtime_error( ""getbestblockhash\\n"" ""\\nReturns the hash of the best (tip) block in the longest blockchain.\\n"" ""\\nResult:\\n"" ""\\""hex\\"" (string) the block hash hex encoded\\n"" ""\\nExamples:\\n"" + HelpExampleCli(""getbestblockhash"", """") + HelpExampleRpc(""getbestblockhash"", """") ); LOCK(cs_main); return chainActive.Tip()->GetBlockHash().GetHex(); } void RPCNotifyBlockChange(bool ibd, const CBlockIndex * pindex) { if(pindex) { std::lock_guard lock(cs_blockchange); latestblock.hash = pindex->GetBlockHash(); latestblock.height = pindex->nHeight; } cond_blockchange.notify_all(); } UniValue waitfornewblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() > 1) throw runtime_error( ""waitfornewblock (timeout)\\n"" ""\\nWaits for a specific new block and returns useful info about it.\\n"" ""\\nReturns the current block on timeout or exit.\\n"" ""\\nArguments:\\n"" ""1. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\\n"" ""\\nResult:\\n"" ""{ (json object)\\n"" "" \\""hash\\"" : { (string) The blockhash\\n"" "" \\""height\\"" : { (int) Block height\\n"" ""}\\n"" ""\\nExamples:\\n"" + HelpExampleCli(""waitfornewblock"", ""1000"") + HelpExampleRpc(""waitfornewblock"", ""1000"") ); int timeout = 0; if (request.params.size() > 0) timeout = request.params[0].get_int(); CUpdatedBlock block; { std::unique_lock lock(cs_blockchange); block = latestblock; if(timeout) cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&block]{return latestblock.height != block.height || latestblock.hash != block.hash || !IsRPCRunning(); }); else cond_blockchange.wait(lock, [&block]{return latestblock.height != block.height || latestblock.hash != block.hash || !IsRPCRunning(); }); block = latestblock; } UniValue ret(UniValue::VOBJ); ret.push_back(Pair(""hash"", block.hash.GetHex())); ret.push_back(Pair(""height"", block.height)); return ret; } UniValue waitforblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw runtime_error( ""waitforblock (timeout)\\n"" ""\\nWaits for a specific new block and returns useful info about it.\\n"" ""\\nReturns the current block on timeout or exit.\\n"" ""\\nArguments:\\n"" ""1. \\""blockhash\\"" (required, string) Block hash to wait for.\\n"" ""2. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\\n"" ""\\nResult:\\n"" ""{ (json object)\\n"" "" \\""hash\\"" : { (string) The blockhash\\n"" "" \\""height\\"" : { (int) Block height\\n"" ""}\\n"" ""\\nExamples:\\n"" + HelpExampleCli(""waitforblock"", ""\\""0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\\"", 1000"") + HelpExampleRpc(""waitforblock"", ""\\""0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\\"", 1000"") ); int timeout = 0; uint256 hash = uint256S(request.params[0].get_str()); if (request.params.size() > 1) timeout = request.params[1].get_int(); CUpdatedBlock block; { std::unique_lock lock(cs_blockchange); if(timeout) cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&hash]{return latestblock.hash == hash || !IsRPCRunning();}); else cond_blockchange.wait(lock, [&hash]{return latestblock.hash == hash || !IsRPCRunning(); }); block = latestblock; } UniValue ret(UniValue::VOBJ); ret.push_back(Pair(""hash"", block.hash.GetHex())); ret.push_back(Pair(""height"", block.height)); return ret; } UniValue waitforblockheight(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw runtime_error( ""waitforblockheight (timeout)\\n"" ""\\nWaits for (at least) block height and returns the height and hash\\n"" ""of the current tip.\\n"" ""\\nReturns the current block on timeout or exit.\\n"" ""\\nArguments:\\n"" ""1. height (required, int) Block height to wait for (int)\\n"" ""2. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\\n"" ""\\nResult:\\n"" ""{ (json object)\\n"" "" \\""hash\\"" : { (string) The blockhash\\n"" "" \\""height\\"" : { (int) Block height\\n"" ""}\\n"" ""\\nExamples:\\n"" + HelpExampleCli(""waitforblockheight"", ""\\""100\\"", 1000"") + HelpExampleRpc(""waitforblockheight"", ""\\""100\\"", 1000"") ); int timeout = 0; int height = request.params[0].get_int(); if (request.params.size() > 1) timeout = request.params[1].get_int(); CUpdatedBlock block; { std::unique_lock lock(cs_blockchange); if(timeout) cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&height]{return latestblock.height >= height || !IsRPCRunning();}); else cond_blockchange.wait(lock, [&height]{return latestblock.height >= height || !IsRPCRunning(); }); block = latestblock; } UniValue ret(UniValue::VOBJ); ret.push_back(Pair(""hash"", block.hash.GetHex())); ret.push_back(Pair(""height"", block.height)); return ret; } UniValue getdifficulty(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw runtime_error( ""getdifficulty\\n"" ""\\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\\n"" ""\\nResult:\\n"" ""n.nnn (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty.\\n"" ""\\nExamples:\\n"" + HelpExampleCli(""getdifficulty"", """") + HelpExampleRpc(""getdifficulty"", """") ); LOCK(cs_main); return GetDifficulty(); } std::string EntryDescriptionString() { return "" \\""size\\"" : n, (numeric) virtual transaction size as defined in BIP 141. This is different from actual serialized size for witness transactions as witness data is discounted.\\n"" "" \\""fee\\"" : n, (numeric) transaction fee in "" + CURRENCY_UNIT + ""\\n"" "" \\""modifiedfee\\"" : n, (numeric) transaction fee with fee deltas used for mining priority\\n"" "" \\""time\\"" : n, (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT\\n"" "" \\""height\\"" : n, (numeric) block height when transaction entered pool\\n"" "" \\""startingpriority\\"" : n, (numeric) DEPRECATED. Priority when transaction entered pool\\n"" "" \\""currentpriority\\"" : n, (numeric) DEPRECATED. Transaction priority now\\n"" "" \\""descendantcount\\"" : n, (numeric) number of in-mempool descendant transactions (including this one)\\n"" "" \\""descendantsize\\"" : n, (numeric) virtual transaction size of in-mempool descendants (including this one)\\n"" "" \\""descendantfees\\"" : n, (numeric) modified fees (see above) of in-mempool descendants (including this one)\\n"" "" \\""ancestorcount\\"" : n, (numeric) number of in-mempool ancestor transactions (including this one)\\n"" "" \\""ancestorsize\\"" : n, (numeric) virtual transaction size of in-mempool ancestors (including this one)\\n"" "" \\""ancestorfees\\"" : n, (numeric) modified fees (see above) of in-mempool ancestors (including this one)\\n"" "" \\""depends\\"" : [ (array) unconfirmed transactions used as inputs for this transaction\\n"" "" \\""transactionid\\"", (string) parent transaction id\\n"" "" ... ]\\n""; } void entryToJSON(UniValue &info, const CTxMemPoolEntry &e) { AssertLockHeld(mempool.cs); info.push_back(Pair(""size"", (int)e.GetTxSize())); info.push_back(Pair(""fee"", ValueFromAmount(e.GetFee()))); info.push_back(Pair(""modifiedfee"", ValueFromAmount(e.GetModifiedFee()))); info.push_back(Pair(""time"", e.GetTime())); info.push_back(Pair(""height"", (int)e.GetHeight())); info.push_back(Pair(""startingpriority"", e.GetPriority(e.GetHeight()))); info.push_back(Pair(""currentpriority"", e.GetPriority(chainActive.Height()))); info.push_back(Pair(""descendantcount"", e.GetCountWithDescendants())); info.push_back(Pair(""descendantsize"", e.GetSizeWithDescendants())); info.push_back(Pair(""descendantfees"", e.GetModFeesWithDescendants())); info.push_back(Pair(""ancestorcount"", e.GetCountWithAncestors())); info.push_back(Pair(""ancestorsize"", e.GetSizeWithAncestors())); info.push_back(Pair(""ancestorfees"", e.GetModFeesWithAncestors())); const CTransaction& tx = e.GetTx(); set setDepends; BOOST_FOREACH(const CTxIn& txin, tx.vin) { if (mempool.exists(txin.prevout.hash)) setDepends.insert(txin.prevout.hash.ToString()); } UniValue depends(UniValue::VARR); BOOST_FOREACH(const string& dep, setDepends) { depends.push_back(dep); } info.push_back(Pair(""depends"", depends)); } UniValue mempoolToJSON(bool fVerbose = false) { if (fVerbose) { LOCK(mempool.cs); UniValue o(UniValue::VOBJ); BOOST_FOREACH(const CTxMemPoolEntry& e, mempool.mapTx) { const uint256& hash = e.GetTx().GetHash(); UniValue info(UniValue::VOBJ); entryToJSON(info, e); o.push_back(Pair(hash.ToString(), info)); } return o; } else { vector vtxid; mempool.queryHashes(vtxid); UniValue a(UniValue::VARR); BOOST_FOREACH(const uint256& hash, vtxid) a.push_back(hash.ToString()); return a; } } UniValue getrawmempool(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() > 1) throw runtime_error( ""getrawmempool ( verbose )\\n"" ""\\nReturns all transaction ids in memory pool as a json array of string transaction ids.\\n"" ""\\nHint: use getmempoolentry to fetch a specific transaction from the mempool.\\n"" ""\\nArguments:\\n"" ""1. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\\n"" ""\\nResult: (for verbose = false):\\n"" ""[ (json array of string)\\n"" "" \\""transactionid\\"" (string) The transaction id\\n"" "" ,...\\n"" ""]\\n"" ""\\nResult: (for verbose = true):\\n"" ""{ (json object)\\n"" "" \\""transactionid\\"" : { (json object)\\n"" + EntryDescriptionString() + "" }, ...\\n"" ""}\\n"" ""\\nExamples:\\n"" + HelpExampleCli(""getrawmempool"", ""true"") + HelpExampleRpc(""getrawmempool"", ""true"") ); bool fVerbose = false; if (request.params.size() > 0) fVerbose = request.params[0].get_bool(); return mempoolToJSON(fVerbose); } UniValue getmempoolancestors(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) { throw runtime_error( ""getmempoolancestors txid (verbose)\\n"" ""\\nIf txid is in the mempool, returns all in-mempool ancestors.\\n"" ""\\nArguments:\\n"" ""1. \\""txid\\"" (string, required) The transaction id (must be in mempool)\\n"" ""2. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\\n"" ""\\nResult (for verbose=false):\\n"" ""[ (json array of strings)\\n"" "" \\""transactionid\\"" (string) The transaction id of an in-mempool ancestor transaction\\n"" "" ,...\\n"" ""]\\n"" ""\\nResult (for verbose=true):\\n"" ""{ (json object)\\n"" "" \\""transactionid\\"" : { (json object)\\n"" + EntryDescriptionString() + "" }, ...\\n"" ""}\\n"" ""\\nExamples:\\n"" + HelpExampleCli(""getmempoolancestors"", ""\\""mytxid\\"""") + HelpExampleRpc(""getmempoolancestors"", ""\\""mytxid\\"""") ); } bool fVerbose = false; if (request.params.size() > 1) fVerbose = request.params[1].get_bool(); uint256 hash = ParseHashV(request.params[0], ""parameter 1""); LOCK(mempool.cs); CTxMemPool::txiter it = mempool.mapTx.find(hash); if (it == mempool.mapTx.end()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, ""Transaction not in mempool""); } CTxMemPool::setEntries setAncestors; uint64_t noLimit = std::numeric_limits::max(); std::string dummy; mempool.CalculateMemPoolAncestors(*it, setAncestors, noLimit, noLimit, noLimit, noLimit, dummy, false); if (!fVerbose) { UniValue o(UniValue::VARR); BOOST_FOREACH(CTxMemPool::txiter ancestorIt, setAncestors) { o.push_back(ancestorIt->GetTx().GetHash().ToString()); } return o; } else { UniValue o(UniValue::VOBJ); BOOST_FOREACH(CTxMemPool::txiter ancestorIt, setAncestors) { const CTxMemPoolEntry &e = *ancestorIt; const uint256& _hash = e.GetTx().GetHash(); UniValue info(UniValue::VOBJ); entryToJSON(info, e); o.push_back(Pair(_hash.ToString(), info)); } return o; } } UniValue getmempooldescendants(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) { throw runtime_error( ""getmempooldescendants txid (verbose)\\n"" ""\\nIf txid is in the mempool, returns all in-mempool descendants.\\n"" ""\\nArguments:\\n"" ""1. \\""txid\\"" (string, required) The transaction id (must be in mempool)\\n"" ""2. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\\n"" ""\\nResult (for verbose=false):\\n"" ""[ (json array of strings)\\n"" "" \\""transactionid\\"" (string) The transaction id of an in-mempool descendant transaction\\n"" "" ,...\\n"" ""]\\n"" ""\\nResult (for verbose=true):\\n"" ""{ (json object)\\n"" "" \\""transactionid\\"" : { (json object)\\n"" + EntryDescriptionString() + "" }, ...\\n"" ""}\\n"" ""\\nExamples:\\n"" + HelpExampleCli(""getmempooldescendants"", ""\\""mytxid\\"""") + HelpExampleRpc(""getmempooldescendants"", ""\\""mytxid\\"""") ); } bool fVerbose = false; if (request.params.size() > 1) fVerbose = request.params[1].get_bool(); uint256 hash = ParseHashV(request.params[0], ""parameter 1""); LOCK(mempool.cs); CTxMemPool::txiter it = mempool.mapTx.find(hash); if (it == mempool.mapTx.end()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, ""Transaction not in mempool""); } CTxMemPool::setEntries setDescendants; mempool.CalculateDescendants(it, setDescendants); // CTxMemPool::CalculateDescendants will include the given tx setDescendants.erase(it); if (!fVerbose) { UniValue o(UniValue::VARR); BOOST_FOREACH(CTxMemPool::txiter descendantIt, setDescendants) { o.push_back(descendantIt->GetTx().GetHash().ToString()); } return o; } else { UniValue o(UniValue::VOBJ); BOOST_FOREACH(CTxMemPool::txiter descendantIt, setDescendants) { const CTxMemPoolEntry &e = *descendantIt; const uint256& _hash = e.GetTx().GetHash(); UniValue info(UniValue::VOBJ); entryToJSON(info, e); o.push_back(Pair(_hash.ToString(), info)); } return o; } } UniValue getmempoolentry(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) { throw runtime_error( ""getmempoolentry txid\\n"" ""\\nReturns mempool data for given transaction\\n"" ""\\nArguments:\\n"" ""1. \\""txid\\"" (string, required) The transaction id (must be in mempool)\\n"" ""\\nResult:\\n"" ""{ (json object)\\n"" + EntryDescriptionString() + ""}\\n"" ""\\nExamples:\\n"" + HelpExampleCli(""getmempoolentry"", ""\\""mytxid\\"""") + HelpExampleRpc(""getmempoolentry"", ""\\""mytxid\\"""") ); } uint256 hash = ParseHashV(request.params[0], ""parameter 1""); LOCK(mempool.cs); CTxMemPool::txiter it = mempool.mapTx.find(hash); if (it == mempool.mapTx.end()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, ""Transaction not in mempool""); } const CTxMemPoolEntry &e = *it; UniValue info(UniValue::VOBJ); entryToJSON(info, e); return info; } UniValue getblockhash(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw runtime_error( ""getblockhash height\\n"" ""\\nReturns hash of block in best-block-chain at height provided.\\n"" ""\\nArguments:\\n"" ""1. height (numeric, required) The height index\\n"" ""\\nResult:\\n"" ""\\""hash\\"" (string) The block hash\\n"" ""\\nExamples:\\n"" + HelpExampleCli(""getblockhash"", ""1000"") + HelpExampleRpc(""getblockhash"", ""1000"") ); LOCK(cs_main); int nHeight = request.params[0].get_int(); if (nHeight < 0 || nHeight > chainActive.Height()) throw JSONRPCError(RPC_INVALID_PARAMETER, ""Block height out of range""); CBlockIndex* pblockindex = chainActive[nHeight]; return pblockindex->GetBlockHash().GetHex(); } UniValue getblockheader(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw runtime_error( ""getblockheader \\""hash\\"" ( verbose )\\n"" ""\\nIf verbose is false, returns a string that is serialized, hex-encoded data for blockheader 'hash'.\\n"" ""If verbose is true, returns an Object with information about blockheader .\\n"" ""\\nArguments:\\n"" ""1. \\""hash\\"" (string, required) The block hash\\n"" ""2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\\n"" ""\\nResult (for verbose = true):\\n"" ""{\\n"" "" \\""hash\\"" : \\""hash\\"", (string) the block hash (same as provided)\\n"" "" \\""confirmations\\"" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\\n"" "" \\""height\\"" : n, (numeric) The block height or index\\n"" "" \\""version\\"" : n, (numeric) The block version\\n"" "" \\""versionHex\\"" : \\""00000000\\"", (string) The block version formatted in hexadecimal\\n"" "" \\""merkleroot\\"" : \\""xxxx\\"", (string) The merkle root\\n"" "" \\""time\\"" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\\n"" "" \\""mediantime\\"" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\\n"" "" \\""nonce\\"" : n, (numeric) The nonce\\n"" "" \\""bits\\"" : \\""1d00ffff\\"", (string) The bits\\n"" "" \\""difficulty\\"" : x.xxx, (numeric) The difficulty\\n"" "" \\""chainwork\\"" : \\""0000...1f3\\"" (string) Expected number of hashes required to produce the current chain (in hex)\\n"" "" \\""previousblockhash\\"" : \\""hash\\"", (string) The hash of the previous block\\n"" "" \\""nextblockhash\\"" : \\""hash\\"", (string) The hash of the next block\\n"" ""}\\n"" ""\\nResult (for verbose=false):\\n"" ""\\""data\\"" (string) A string that is serialized, hex-encoded data for block 'hash'.\\n"" ""\\nExamples:\\n"" + HelpExampleCli(""getblockheader"", ""\\""00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\\"""") + HelpExampleRpc(""getblockheader"", ""\\""00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\\"""") ); LOCK(cs_main); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); bool fVerbose = true; if (request.params.size() > 1) fVerbose = request.params[1].get_bool(); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, ""Block not found""); CBlockIndex* pblockindex = mapBlockIndex[hash]; if (!fVerbose) { CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION); ssBlock << pblockindex->GetBlockHeader(); std::string strHex = HexStr(ssBlock.begin(), ssBlock.end()); return strHex; } return blockheaderToJSON(pblockindex); } UniValue getblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw runtime_error( ""getblock \\""blockhash\\"" ( verbose )\\n"" ""\\nIf verbose is false, returns a string that is serialized, hex-encoded data for block 'hash'.\\n"" ""If verbose is true, returns an Object with information about block .\\n"" ""\\nArguments:\\n"" ""1. \\""blockhash\\"" (string, required) The block hash\\n"" ""2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\\n"" ""\\nResult (for verbose = true):\\n"" ""{\\n"" "" \\""hash\\"" : \\""hash\\"", (string) the block hash (same as provided)\\n"" "" \\""confirmations\\"" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\\n"" "" \\""size\\"" : n, (numeric) The block size\\n"" "" \\""strippedsize\\"" : n, (numeric) The block size excluding witness data\\n"" "" \\""weight\\"" : n (numeric) The block weight as defined in BIP 141\\n"" "" \\""height\\"" : n, (numeric) The block height or index\\n"" "" \\""version\\"" : n, (numeric) The block version\\n"" "" \\""versionHex\\"" : \\""00000000\\"", (string) The block version formatted in hexadecimal\\n"" "" \\""merkleroot\\"" : \\""xxxx\\"", (string) The merkle root\\n"" "" \\""tx\\"" : [ (array of string) The transaction ids\\n"" "" \\""transactionid\\"" (string) The transaction id\\n"" "" ,...\\n"" "" ],\\n"" "" \\""time\\"" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\\n"" "" \\""mediantime\\"" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\\n"" "" \\""nonce\\"" : n, (numeric) The nonce\\n"" "" \\""bits\\"" : \\""1d00ffff\\"", (string) The bits\\n"" "" \\""difficulty\\"" : x.xxx, (numeric) The difficulty\\n"" "" \\""chainwork\\"" : \\""xxxx\\"", (string) Expected number of hashes required to produce the chain up to this block (in hex)\\n"" "" \\""previousblockhash\\"" : \\""hash\\"", (string) The hash of the previous block\\n"" "" \\""nextblockhash\\"" : \\""hash\\"" (string) The hash of the next block\\n"" ""}\\n"" ""\\nResult (for verbose=false):\\n"" ""\\""data\\"" (string) A string that is serialized, hex-encoded data for block 'hash'.\\n"" ""\\nExamples:\\n"" + HelpExampleCli(""getblock"", ""\\""00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\\"""") + HelpExampleRpc(""getblock"", ""\\""00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\\"""") ); LOCK(cs_main); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); bool fVerbose = true; if (request.params.size() > 1) fVerbose = request.params[1].get_bool(); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, ""Block not found""); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hash]; if (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0) throw JSONRPCError(RPC_MISC_ERROR, ""Block not available (pruned data)""); if (!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus())) // Block not found on disk. This could be because we have the block // header in our index but don't have the block (for example if a // non-whitelisted node sends us an unrequested long chain of valid // blocks, we add the headers to our index, but don't accept the // block). throw JSONRPCError(RPC_MISC_ERROR, ""Block not found on disk""); if (!fVerbose) { CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags()); ssBlock << block; std::string strHex = HexStr(ssBlock.begin(), ssBlock.end()); return strHex; } return blockToJSON(block, pblockindex); } struct CCoinsStats { int nHeight; uint256 hashBlock; uint64_t nTransactions; uint64_t nTransactionOutputs; uint64_t nSerializedSize; uint256 hashSerialized; CAmount nTotalAmount; CCoinsStats() : nHeight(0), nTransactions(0), nTransactionOutputs(0), nSerializedSize(0), nTotalAmount(0) {} }; //! Calculate statistics about the unspent transaction output set static bool GetUTXOStats(CCoinsView *view, CCoinsStats &stats) { std::unique_ptr pcursor(view->Cursor()); CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); stats.hashBlock = pcursor->GetBestBlock(); { LOCK(cs_main); stats.nHeight = mapBlockIndex.find(stats.hashBlock)->second->nHeight; } ss << stats.hashBlock; CAmount nTotalAmount = 0; while (pcursor->Valid()) { boost::this_thread::interruption_point(); uint256 key; CCoins coins; if (pcursor->GetKey(key) && pcursor->GetValue(coins)) { stats.nTransactions++; ss << key; for (unsigned int i=0; iGetValueSize(); ss << VARINT(0); } else { return error(""%s: unable to read value"", __func__); } pcursor->Next(); } stats.hashSerialized = ss.GetHash(); stats.nTotalAmount = nTotalAmount; return true; } UniValue pruneblockchain(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw runtime_error( ""pruneblockchain\\n"" ""\\nArguments:\\n"" ""1. \\""height\\"" (numeric, required) The block height to prune up to. May be set to a discrete height, or a unix timestamp\\n"" "" to prune blocks whose block time is at least 2 hours older than the provided timestamp.\\n"" ""\\nResult:\\n"" ""n (numeric) Height of the last block pruned.\\n"" ""\\nExamples:\\n"" + HelpExampleCli(""pruneblockchain"", ""1000"") + HelpExampleRpc(""pruneblockchain"", ""1000"")); if (!fPruneMode) throw JSONRPCError(RPC_MISC_ERROR, ""Cannot prune blocks because node is not in prune mode.""); LOCK(cs_main); int heightParam = request.params[0].get_int(); if (heightParam < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, ""Negative block height.""); // Height value more than a billion is too high to be a block height, and // too low to be a block time (corresponds to timestamp from Sep 2001). if (heightParam > 1000000000) { // Add a 2 hour buffer to include blocks which might have had old timestamps CBlockIndex* pindex = chainActive.FindEarliestAtLeast(heightParam - 7200); if (!pindex) { throw JSONRPCError(RPC_INVALID_PARAMETER, ""Could not find block with at least the specified timestamp.""); } heightParam = pindex->nHeight; } unsigned int height = (unsigned int) heightParam; unsigned int chainHeight = (unsigned int) chainActive.Height(); if (chainHeight < Params().PruneAfterHeight()) throw JSONRPCError(RPC_MISC_ERROR, ""Blockchain is too short for pruning.""); else if (height > chainHeight) throw JSONRPCError(RPC_INVALID_PARAMETER, ""Blockchain is shorter than the attempted prune height.""); else if (height > chainHeight - MIN_BLOCKS_TO_KEEP) { LogPrint(""rpc"", ""Attempt to prune blocks close to the tip. Retaining the minimum number of blocks.""); height = chainHeight - MIN_BLOCKS_TO_KEEP; } PruneBlockFilesManual(height); return uint64_t(height); } UniValue gettxoutsetinfo(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw runtime_error( ""gettxoutsetinfo\\n"" ""\\nReturns statistics about the unspent transaction output set.\\n"" ""Note this call may take some time.\\n"" ""\\nResult:\\n"" ""{\\n"" "" \\""height\\"":n, (numeric) The current block height (index)\\n"" "" \\""bestblock\\"": \\""hex\\"", (string) the best block hash hex\\n"" "" \\""transactions\\"": n, (numeric) The number of transactions\\n"" "" \\""txouts\\"": n, (numeric) The number of output transactions\\n"" "" \\""bytes_serialized\\"": n, (numeric) The serialized size\\n"" "" \\""hash_serialized\\"": \\""hash\\"", (string) The serialized hash\\n"" "" \\""total_amount\\"": x.xxx (numeric) The total amount\\n"" ""}\\n"" ""\\nExamples:\\n"" + HelpExampleCli(""gettxoutsetinfo"", """") + HelpExampleRpc(""gettxoutsetinfo"", """") ); UniValue ret(UniValue::VOBJ); CCoinsStats stats; FlushStateToDisk(); if (GetUTXOStats(pcoinsTip, stats)) { ret.push_back(Pair(""height"", (int64_t)stats.nHeight)); ret.push_back(Pair(""bestblock"", stats.hashBlock.GetHex())); ret.push_back(Pair(""transactions"", (int64_t)stats.nTransactions)); ret.push_back(Pair(""txouts"", (int64_t)stats.nTransactionOutputs)); ret.push_back(Pair(""bytes_serialized"", (int64_t)stats.nSerializedSize)); ret.push_back(Pair(""hash_serialized"", stats.hashSerialized.GetHex())); ret.push_back(Pair(""total_amount"", ValueFromAmount(stats.nTotalAmount))); } else { throw JSONRPCError(RPC_INTERNAL_ERROR, ""Unable to read UTXO set""); } return ret; } UniValue gettxout(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 2 || request.params.size() > 3) throw runtime_error( ""gettxout \\""txid\\"" n ( include_mempool )\\n"" ""\\nReturns details about an unspent transaction output.\\n"" ""\\nArguments:\\n"" ""1. \\""txid\\"" (string, required) The transaction id\\n"" ""2. n (numeric, required) vout number\\n"" ""3. include_mempool (boolean, optional) Whether to include the mempool\\n"" ""\\nResult:\\n"" ""{\\n"" "" \\""bestblock\\"" : \\""hash\\"", (string) the block hash\\n"" "" \\""confirmations\\"" : n, (numeric) The number of confirmations\\n"" "" \\""value\\"" : x.xxx, (numeric) The transaction value in "" + CURRENCY_UNIT + ""\\n"" "" \\""scriptPubKey\\"" : { (json object)\\n"" "" \\""asm\\"" : \\""code\\"", (string) \\n"" "" \\""hex\\"" : \\""hex\\"", (string) \\n"" "" \\""reqSigs\\"" : n, (numeric) Number of required signatures\\n"" "" \\""type\\"" : \\""pubkeyhash\\"", (string) The type, eg pubkeyhash\\n"" "" \\""addresses\\"" : [ (array of string) array of bitcoin addresses\\n"" "" \\""address\\"" (string) bitcoin address\\n"" "" ,...\\n"" "" ]\\n"" "" },\\n"" "" \\""version\\"" : n, (numeric) The version\\n"" "" \\""coinbase\\"" : true|false (boolean) Coinbase or not\\n"" ""}\\n"" ""\\nExamples:\\n"" ""\\nGet unspent transactions\\n"" + HelpExampleCli(""listunspent"", """") + ""\\nView the details\\n"" + HelpExampleCli(""gettxout"", ""\\""txid\\"" 1"") + ""\\nAs a json rpc call\\n"" + HelpExampleRpc(""gettxout"", ""\\""txid\\"", 1"") ); LOCK(cs_main); UniValue ret(UniValue::VOBJ); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); int n = request.params[1].get_int(); bool fMempool = true; if (request.params.size() > 2) fMempool = request.params[2].get_bool(); CCoins coins; if (fMempool) { LOCK(mempool.cs); CCoinsViewMemPool view(pcoinsTip, mempool); if (!view.GetCoins(hash, coins)) return NullUniValue; mempool.pruneSpent(hash, coins); // TODO: this should be done by the CCoinsViewMemPool } else { if (!pcoinsTip->GetCoins(hash, coins)) return NullUniValue; } if (n<0 || (unsigned int)n>=coins.vout.size() || coins.vout[n].IsNull()) return NullUniValue; BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock()); CBlockIndex *pindex = it->second; ret.push_back(Pair(""bestblock"", pindex->GetBlockHash().GetHex())); if ((unsigned int)coins.nHeight == MEMPOOL_HEIGHT) ret.push_back(Pair(""confirmations"", 0)); else ret.push_back(Pair(""confirmations"", pindex->nHeight - coins.nHeight + 1)); ret.push_back(Pair(""value"", ValueFromAmount(coins.vout[n].nValue))); UniValue o(UniValue::VOBJ); ScriptPubKeyToJSON(coins.vout[n].scriptPubKey, o, true); ret.push_back(Pair(""scriptPubKey"", o)); ret.push_back(Pair(""version"", coins.nVersion)); ret.push_back(Pair(""coinbase"", coins.fCoinBase)); return ret; } UniValue verifychain(const JSONRPCRequest& request) { int nCheckLevel = GetArg(""-checklevel"", DEFAULT_CHECKLEVEL); int nCheckDepth = GetArg(""-checkblocks"", DEFAULT_CHECKBLOCKS); if (request.fHelp || request.params.size() > 2) throw runtime_error( ""verifychain ( checklevel nblocks )\\n"" ""\\nVerifies blockchain database.\\n"" ""\\nArguments:\\n"" ""1. checklevel (numeric, optional, 0-4, default="" + strprintf(""%d"", nCheckLevel) + "") How thorough the block verification is.\\n"" ""2. nblocks (numeric, optional, default="" + strprintf(""%d"", nCheckDepth) + "", 0=all) The number of blocks to check.\\n"" ""\\nResult:\\n"" ""true|false (boolean) Verified or not\\n"" ""\\nExamples:\\n"" + HelpExampleCli(""verifychain"", """") + HelpExampleRpc(""verifychain"", """") ); LOCK(cs_main); if (request.params.size() > 0) nCheckLevel = request.params[0].get_int(); if (request.params.size() > 1) nCheckDepth = request.params[1].get_int(); return CVerifyDB().VerifyDB(Params(), pcoinsTip, nCheckLevel, nCheckDepth); } /** Implementation of IsSuperMajority with better feedback */ static UniValue SoftForkMajorityDesc(int version, CBlockIndex* pindex, const Consensus::Params& consensusParams) { UniValue rv(UniValue::VOBJ); bool activated = false; switch(version) { case 2: activated = pindex->nHeight >= consensusParams.BIP34Height; break; case 3: activated = pindex->nHeight >= consensusParams.BIP66Height; break; case 4: activated = pindex->nHeight >= consensusParams.BIP65Height; break; } rv.push_back(Pair(""status"", activated)); return rv; } static UniValue SoftForkDesc(const std::string &name, int version, CBlockIndex* pindex, const Consensus::Params& consensusParams) { UniValue rv(UniValue::VOBJ); rv.push_back(Pair(""id"", name)); rv.push_back(Pair(""version"", version)); rv.push_back(Pair(""reject"", SoftForkMajorityDesc(version, pindex, consensusParams))); return rv; } static UniValue BIP9SoftForkDesc(const Consensus::Params& consensusParams, Consensus::DeploymentPos id) { UniValue rv(UniValue::VOBJ); const ThresholdState thresholdState = VersionBitsTipState(consensusParams, id); switch (thresholdState) { case THRESHOLD_DEFINED: rv.push_back(Pair(""status"", ""defined"")); break; case THRESHOLD_STARTED: rv.push_back(Pair(""status"", ""started"")); break; case THRESHOLD_LOCKED_IN: rv.push_back(Pair(""status"", ""locked_in"")); break; case THRESHOLD_ACTIVE: rv.push_back(Pair(""status"", ""active"")); break; case THRESHOLD_FAILED: rv.push_back(Pair(""status"", ""failed"")); break; } if (THRESHOLD_STARTED == thresholdState) { rv.push_back(Pair(""bit"", consensusParams.vDeployments[id].bit)); } rv.push_back(Pair(""startTime"", consensusParams.vDeployments[id].nStartTime)); rv.push_back(Pair(""timeout"", consensusParams.vDeployments[id].nTimeout)); rv.push_back(Pair(""since"", VersionBitsTipStateSinceHeight(consensusParams, id))); return rv; } void BIP9SoftForkDescPushBack(UniValue& bip9_softforks, const std::string &name, const Consensus::Params& consensusParams, Consensus::DeploymentPos id) { // Deployments with timeout value of 0 are hidden. // A timeout value of 0 guarantees a softfork will never be activated. // This is used when softfork codes are merged without specifying the deployment schedule. if (consensusParams.vDeployments[id].nTimeout > 0) bip9_softforks.push_back(Pair(name, BIP9SoftForkDesc(consensusParams, id))); } UniValue getblockchaininfo(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw runtime_error( ""getblockchaininfo\\n"" ""Returns an object containing various state info regarding blockchain processing.\\n"" ""\\nResult:\\n"" ""{\\n"" "" \\""chain\\"": \\""xxxx\\"", (string) current network name as defined in BIP70 (main, test, regtest)\\n"" "" \\""blocks\\"": xxxxxx, (numeric) the current number of blocks processed in the server\\n"" "" \\""headers\\"": xxxxxx, (numeric) the current number of headers we have validated\\n"" "" \\""bestblockhash\\"": \\""...\\"", (string) the hash of the currently best block\\n"" "" \\""difficulty\\"": xxxxxx, (numeric) the current difficulty\\n"" "" \\""mediantime\\"": xxxxxx, (numeric) median time for the current best block\\n"" "" \\""verificationprogress\\"": xxxx, (numeric) estimate of verification progress [0..1]\\n"" "" \\""chainwork\\"": \\""xxxx\\"" (string) total amount of work in active chain, in hexadecimal\\n"" "" \\""pruned\\"": xx, (boolean) if the blocks are subject to pruning\\n"" "" \\""pruneheight\\"": xxxxxx, (numeric) lowest-height complete block stored\\n"" "" \\""softforks\\"": [ (array) status of softforks in progress\\n"" "" {\\n"" "" \\""id\\"": \\""xxxx\\"", (string) name of softfork\\n"" "" \\""version\\"": xx, (numeric) block version\\n"" "" \\""reject\\"": { (object) progress toward rejecting pre-softfork blocks\\n"" "" \\""status\\"": xx, (boolean) true if threshold reached\\n"" "" },\\n"" "" }, ...\\n"" "" ],\\n"" "" \\""bip9_softforks\\"": { (object) status of BIP9 softforks in progress\\n"" "" \\""xxxx\\"" : { (string) name of the softfork\\n"" "" \\""status\\"": \\""xxxx\\"", (string) one of \\""defined\\"", \\""started\\"", \\""locked_in\\"", \\""active\\"", \\""failed\\""\\n"" "" \\""bit\\"": xx, (numeric) the bit (0-28) in the block version field used to signal this softfork (only for \\""started\\"" status)\\n"" "" \\""startTime\\"": xx, (numeric) the minimum median time past of a block at which the bit gains its meaning\\n"" "" \\""timeout\\"": xx, (numeric) the median time past of a block at which the deployment is considered failed if not yet locked in\\n"" "" \\""since\\"": xx (numeric) height of the first block to which the status applies\\n"" "" }\\n"" "" }\\n"" ""}\\n"" ""\\nExamples:\\n"" + HelpExampleCli(""getblockchaininfo"", """") + HelpExampleRpc(""getblockchaininfo"", """") ); LOCK(cs_main); UniValue obj(UniValue::VOBJ); obj.push_back(Pair(""chain"", Params().NetworkIDString())); obj.push_back(Pair(""blocks"", (int)chainActive.Height())); obj.push_back(Pair(""headers"", pindexBestHeader ? pindexBestHeader->nHeight : -1)); obj.push_back(Pair(""bestblockhash"", chainActive.Tip()->GetBlockHash().GetHex())); obj.push_back(Pair(""difficulty"", (double)GetDifficulty())); obj.push_back(Pair(""mediantime"", (int64_t)chainActive.Tip()->GetMedianTimePast())); obj.push_back(Pair(""verificationprogress"", GuessVerificationProgress(Params().TxData(), chainActive.Tip()))); obj.push_back(Pair(""chainwork"", chainActive.Tip()->nChainWork.GetHex())); obj.push_back(Pair(""pruned"", fPruneMode)); const Consensus::Params& consensusParams = Params().GetConsensus(); CBlockIndex* tip = chainActive.Tip(); UniValue softforks(UniValue::VARR); UniValue bip9_softforks(UniValue::VOBJ); softforks.push_back(SoftForkDesc(""bip34"", 2, tip, consensusParams)); softforks.push_back(SoftForkDesc(""bip66"", 3, tip, consensusParams)); softforks.push_back(SoftForkDesc(""bip65"", 4, tip, consensusParams)); BIP9SoftForkDescPushBack(bip9_softforks, ""csv"", consensusParams, Consensus::DEPLOYMENT_CSV); BIP9SoftForkDescPushBack(bip9_softforks, ""segwit"", consensusParams, Consensus::DEPLOYMENT_SEGWIT); obj.push_back(Pair(""softforks"", softforks)); obj.push_back(Pair(""bip9_softforks"", bip9_softforks)); if (fPruneMode) { CBlockIndex *block = chainActive.Tip(); while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA)) block = block->pprev; obj.push_back(Pair(""pruneheight"", block->nHeight)); } return obj; } /** Comparison function for sorting the getchaintips heads. */ struct CompareBlocksByHeight { bool operator()(const CBlockIndex* a, const CBlockIndex* b) const { /* Make sure that unequal blocks with the same height do not compare equal. Use the pointers themselves to make a distinction. */ if (a->nHeight != b->nHeight) return (a->nHeight > b->nHeight); return a < b; } }; UniValue getchaintips(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw runtime_error( ""getchaintips\\n"" ""Return information about all known tips in the block tree,"" "" including the main chain as well as orphaned branches.\\n"" ""\\nResult:\\n"" ""[\\n"" "" {\\n"" "" \\""height\\"": xxxx, (numeric) height of the chain tip\\n"" "" \\""hash\\"": \\""xxxx\\"", (string) block hash of the tip\\n"" "" \\""branchlen\\"": 0 (numeric) zero for main chain\\n"" "" \\""status\\"": \\""active\\"" (string) \\""active\\"" for the main chain\\n"" "" },\\n"" "" {\\n"" "" \\""height\\"": xxxx,\\n"" "" \\""hash\\"": \\""xxxx\\"",\\n"" "" \\""branchlen\\"": 1 (numeric) length of branch connecting the tip to the main chain\\n"" "" \\""status\\"": \\""xxxx\\"" (string) status of the chain (active, valid-fork, valid-headers, headers-only, invalid)\\n"" "" }\\n"" ""]\\n"" ""Possible values for status:\\n"" ""1. \\""invalid\\"" This branch contains at least one invalid block\\n"" ""2. \\""headers-only\\"" Not all blocks for this branch are available, but the headers are valid\\n"" ""3. \\""valid-headers\\"" All blocks are available for this branch, but they were never fully validated\\n"" ""4. \\""valid-fork\\"" This branch is not part of the active chain, but is fully validated\\n"" ""5. \\""active\\"" This is the tip of the active main chain, which is certainly valid\\n"" ""\\nExamples:\\n"" + HelpExampleCli(""getchaintips"", """") + HelpExampleRpc(""getchaintips"", """") ); LOCK(cs_main); /* * Idea: the set of chain tips is chainActive.tip, plus orphan blocks which do not have another orphan building off of them. * Algorithm: * - Make one pass through mapBlockIndex, picking out the orphan blocks, and also storing a set of the orphan block's pprev pointers. * - Iterate through the orphan blocks. If the block isn't pointed to by another orphan, it is a chain tip. * - add chainActive.Tip() */ std::set setTips; std::set setOrphans; std::set setPrevs; BOOST_FOREACH(const PAIRTYPE(const uint256, CBlockIndex*)& item, mapBlockIndex) { if (!chainActive.Contains(item.second)) { setOrphans.insert(item.second); setPrevs.insert(item.second->pprev); } } for (std::set::iterator it = setOrphans.begin(); it != setOrphans.end(); ++it) { if (setPrevs.erase(*it) == 0) { setTips.insert(*it); } } // Always report the currently active tip. setTips.insert(chainActive.Tip()); /* Construct the output array. */ UniValue res(UniValue::VARR); BOOST_FOREACH(const CBlockIndex* block, setTips) { UniValue obj(UniValue::VOBJ); obj.push_back(Pair(""height"", block->nHeight)); obj.push_back(Pair(""hash"", block->phashBlock->GetHex())); const int branchLen = block->nHeight - chainActive.FindFork(block)->nHeight; obj.push_back(Pair(""branchlen"", branchLen)); string status; if (chainActive.Contains(block)) { // This block is part of the currently active chain. status = ""active""; } else if (block->nStatus & BLOCK_FAILED_MASK) { // This block or one of its ancestors is invalid. status = ""invalid""; } else if (block->nChainTx == 0) { // This block cannot be connected because full block data for it or one of its parents is missing. status = ""headers-only""; } else if (block->IsValid(BLOCK_VALID_SCRIPTS)) { // This block is fully validated, but no longer part of the active chain. It was probably the active block once, but was reorganized. status = ""valid-fork""; } else if (block->IsValid(BLOCK_VALID_TREE)) { // The headers for this block are valid, but it has not been validated. It was probably never part of the most-work chain. status = ""valid-headers""; } else { // No clue. status = ""unknown""; } obj.push_back(Pair(""status"", status)); res.push_back(obj); } return res; } UniValue mempoolInfoToJSON() { UniValue ret(UniValue::VOBJ); ret.push_back(Pair(""size"", (int64_t) mempool.size())); ret.push_back(Pair(""bytes"", (int64_t) mempool.GetTotalTxSize())); ret.push_back(Pair(""usage"", (int64_t) mempool.DynamicMemoryUsage())); size_t maxmempool = GetArg(""-maxmempool"", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000; ret.push_back(Pair(""maxmempool"", (int64_t) maxmempool)); ret.push_back(Pair(""mempoolminfee"", ValueFromAmount(mempool.GetMinFee(maxmempool).GetFeePerK()))); return ret; } UniValue getmempoolinfo(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw runtime_error( ""getmempoolinfo\\n"" ""\\nReturns details on the active state of the TX memory pool.\\n"" ""\\nResult:\\n"" ""{\\n"" "" \\""size\\"": xxxxx, (numeric) Current tx count\\n"" "" \\""bytes\\"": xxxxx, (numeric) Sum of all virtual transaction sizes as defined in BIP 141. Differs from actual serialized size because witness data is discounted\\n"" "" \\""usage\\"": xxxxx, (numeric) Total memory usage for the mempool\\n"" "" \\""maxmempool\\"": xxxxx, (numeric) Maximum memory usage for the mempool\\n"" "" \\""mempoolminfee\\"": xxxxx (numeric) Minimum fee for tx to be accepted\\n"" ""}\\n"" ""\\nExamples:\\n"" + HelpExampleCli(""getmempoolinfo"", """") + HelpExampleRpc(""getmempoolinfo"", """") ); return mempoolInfoToJSON(); } UniValue preciousblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw runtime_error( ""preciousblock \\""blockhash\\""\\n"" ""\\nTreats a block as if it were received before others with the same work.\\n"" ""\\nA later preciousblock call can override the effect of an earlier one.\\n"" ""\\nThe effects of preciousblock are not retained across restarts.\\n"" ""\\nArguments:\\n"" ""1. \\""blockhash\\"" (string, required) the hash of the block to mark as precious\\n"" ""\\nResult:\\n"" ""\\nExamples:\\n"" + HelpExampleCli(""preciousblock"", ""\\""blockhash\\"""") + HelpExampleRpc(""preciousblock"", ""\\""blockhash\\"""") ); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); CBlockIndex* pblockindex; { LOCK(cs_main); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, ""Block not found""); pblockindex = mapBlockIndex[hash]; } CValidationState state; PreciousBlock(state, Params(), pblockindex); if (!state.IsValid()) { throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason()); } return NullUniValue; } UniValue invalidateblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw runtime_error( ""invalidateblock \\""blockhash\\""\\n"" ""\\nPermanently marks a block as invalid, as if it violated a consensus rule.\\n"" ""\\nArguments:\\n"" ""1. \\""blockhash\\"" (string, required) the hash of the block to mark as invalid\\n"" ""\\nResult:\\n"" ""\\nExamples:\\n"" + HelpExampleCli(""invalidateblock"", ""\\""blockhash\\"""") + HelpExampleRpc(""invalidateblock"", ""\\""blockhash\\"""") ); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); CValidationState state; { LOCK(cs_main); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, ""Block not found""); CBlockIndex* pblockindex = mapBlockIndex[hash]; InvalidateBlock(state, Params(), pblockindex); } if (state.IsValid()) { ActivateBestChain(state, Params()); } if (!state.IsValid()) { throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason()); } return NullUniValue; } UniValue reconsiderblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw runtime_error( ""reconsiderblock \\""blockhash\\""\\n"" ""\\nRemoves invalidity status of a block and its descendants, reconsider them for activation.\\n"" ""This can be used to undo the effects of invalidateblock.\\n"" ""\\nArguments:\\n"" ""1. \\""blockhash\\"" (string, required) the hash of the block to reconsider\\n"" ""\\nResult:\\n"" ""\\nExamples:\\n"" + HelpExampleCli(""reconsiderblock"", ""\\""blockhash\\"""") + HelpExampleRpc(""reconsiderblock"", ""\\""blockhash\\"""") ); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); { LOCK(cs_main); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, ""Block not found""); CBlockIndex* pblockindex = mapBlockIndex[hash]; ResetBlockFailureFlags(pblockindex); } CValidationState state; ActivateBestChain(state, Params()); if (!state.IsValid()) { throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason()); } return NullUniValue; } static const CRPCCommand commands[] = { // category name actor (function) okSafe argNames // --------------------- ------------------------ ----------------------- ------ ---------- { ""blockchain"", ""getblockchaininfo"", &getblockchaininfo, true, {} }, { ""blockchain"", ""getbestblockhash"", &getbestblockhash, true, {} }, { ""blockchain"", ""getblockcount"", &getblockcount, true, {} }, { ""blockchain"", ""getblock"", &getblock, true, {""blockhash"",""verbose""} }, { ""blockchain"", ""getblockhash"", &getblockhash, true, {""height""} }, { ""blockchain"", ""getblockheader"", &getblockheader, true, {""blockhash"",""verbose""} }, { ""blockchain"", ""getchaintips"", &getchaintips, true, {} }, { ""blockchain"", ""getdifficulty"", &getdifficulty, true, {} }, { ""blockchain"", ""getmempoolancestors"", &getmempoolancestors, true, {""txid"",""verbose""} }, { ""blockchain"", ""getmempooldescendants"", &getmempooldescendants, true, {""txid"",""verbose""} }, { ""blockchain"", ""getmempoolentry"", &getmempoolentry, true, {""txid""} }, { ""blockchain"", ""getmempoolinfo"", &getmempoolinfo, true, {} }, { ""blockchain"", ""getrawmempool"", &getrawmempool, true, {""verbose""} }, { ""blockchain"", ""gettxout"", &gettxout, true, {""txid"",""n"",""include_mempool""} }, { ""blockchain"", ""gettxoutsetinfo"", &gettxoutsetinfo, true, {} }, { ""blockchain"", ""pruneblockchain"", &pruneblockchain, true, {""height""} }, { ""blockchain"", ""verifychain"", &verifychain, true, {""checklevel"",""nblocks""} }, { ""blockchain"", ""preciousblock"", &preciousblock, true, {""blockhash""} }, /* Not shown in help */ { ""hidden"", ""invalidateblock"", &invalidateblock, true, {""blockhash""} }, { ""hidden"", ""reconsiderblock"", &reconsiderblock, true, {""blockhash""} }, { ""hidden"", ""waitfornewblock"", &waitfornewblock, true, {""timeout""} }, { ""hidden"", ""waitforblock"", &waitforblock, true, {""blockhash"",""timeout""} }, { ""hidden"", ""waitforblockheight"", &waitforblockheight, true, {""height"",""timeout""} }, }; void RegisterBlockchainRPCCommands(CRPCTable &t) { for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++) t.appendCommand(commands[vcidx].name, &commands[vcidx]); } ",16202,True,2853.358200782401,median "All notable changes to this project will be documented in this file. This change log follows the conventions of http://keepachangelog.com/[keepachangelog.com]. == Unreleased (dev) == 2.3.2 (2020-10-07) // {{{ === Added * Added clj-kondo analysis support to testing under cursor. ** When the var under the cursor is not a test, use clj-kondo's analysis to find tests referring to this var. === Changed * Updated jumping to definition to support clj-kondo analysis. * Updated hooks to run multiple definitions at a time. * Bumped joker to 0.15.7. === Fixed * https://github.com/liquidz/vim-iced/issues/271[#271]: Fixed `IcedInstantConnect` and `IcedJackIn` to work correctly. // }}} == 2.3.1 (2020-09-23) // {{{ === Fixed * https://github.com/liquidz/vim-iced/issues/269[#269]: Fixed to work even if `clipboard=unnamedplus` is set. // }}} == 2.3.0 (2020-09-22) // {{{ === Added * https://github.com/liquidz/vim-iced/issues/261[#261]: Added `:IcedRenameSymbol` command. * https://github.com/liquidz/vim-iced/issues/265[#265]: Added `g:iced#buffer#document#mods` option. === Changed * Bump zprint to 1.0.1. === Fixed * https://github.com/liquidz/vim-iced/issues/264[#264]: Fixed command palette to show command messages correctly. // }}} == 2.2.0 (2020-09-13) // {{{ === Added * https://github.com/liquidz/vim-iced/issues/207[#207]: Added support for `completions` op in nREPL 0.8. * https://github.com/liquidz/vim-iced/issues/247[#247]: Added support to use clj-kondo analysis. ** Added `g:iced_enable_clj_kondo_analysis` option. ** Added `g:iced_cache_directory` option. === Changed * Bumped nREPL to `0.8.1`. * Bumped iced-nrepl to `1.0.5`. * Update command palette to be able to select commands which arguments. // }}} == 2.1.9 (2020-08-30) // {{{ === Fixed * https://github.com/liquidz/vim-iced/issues/250[#250], https://github.com/liquidz/vim-iced/issues/253[#253]: Fixed figwheel-main to start ClojureScript REPL correctly. // }}} == 2.1.8 (2020-08-24) // {{{ === Changed * Bump jet to 0.0.13. === Fixed * Fixed to avoid `Press ENTER` message on evaluating code especially when `laststatus` is `0`. // }}} == 2.1.7 (2020-08-21) // {{{ === Changed * Updated quickfix list to be able to trace histories. ** Now you can use https://vim-jp.org/vimdoc-en/quickfix.html#:colder[:colder] and https://vim-jp.org/vimdoc-en/quickfix.html#:cnewer[:cnewer] commands. * Bumped kaocha to `1.0.669`. * Bumped kaocha-nrepl to `1.0.3`. === Fixed * Fixed not to show extra message on starting ClojureScript REPL. // }}} == 2.1.6 (2020-08-19) // {{{ === Changed * Bumped kaocha to `1.0.663`. * Bumped kaocha-nrepl to `1.0.2`. === Fixed * Fixed not to throw error on evaluating the code where there is nothing. // }}} == 2.1.5 (2020-08-16) // {{{ === Fixed * https://github.com/liquidz/vim-iced/issues/239[#239]: Fixed to initialize default formatter. // }}} == 2.1.4 (2020-08-15) // {{{ === Changed * Bumped piggieback to 0.5.1. * Changed to be able to use native-image formatters even when not connected. === Fixed * https://github.com/liquidz/vim-iced/issues/239[#239]: Fixed to be able to format the top level map. ** E.g. `deps.edn` file could not be formattable until now. * Fixed validation for `shadow-cljs.edn` to work correctly. ** A bug from ver 2.1.2. * Fixed `bufenter` autocmd to work with https://github.com/babashka/babashka.nrepl[babashka.nrepl]. // }}} == 2.1.3 (2020-08-07) // {{{ === Added * https://github.com/liquidz/vim-iced/issues/242[#242]: Added `g:iced#nrepl#skip_evaluation_when_buffer_size_is_exceeded` option to avoid freezing vim/nvim when too large values are returned from nREPL. === Changed * Bumped joker to 0.15.6. === Fixed * https://github.com/liquidz/vim-iced/issues/242[#242]: Fixed to warn vim/nvim when too large values are returned from nREPL. // }}} == 2.1.2 (2020-08-01) // {{{ === Changed * Bumped cider-nrepl to 0.25.3. === Fixed * https://github.com/liquidz/vim-iced/issues/121[#121]: Added a option to use https://github.com/borkdude/babashka[Babashka] to detect the use of ClojureScript. ** c.f. https://liquidz.github.io/vim-iced/#iced_usage // }}} == 2.1.1 (2020-07-12) // {{{ === Changed * Bump iced-nrepl to 1.0.3. ** Fixed https://github.com/liquidz/vim-iced-fern-debugger[vim-iced-fern-debugger]'s issue: https://github.com/liquidz/vim-iced-fern-debugger/issues/1[#1], https://github.com/liquidz/vim-iced-fern-debugger/issues/2[#2] // }}} == 2.1.0 (2020-07-11) // {{{ === Added * Added `:IcedStopSideloader` command. * https://github.com/liquidz/vim-iced/issues/104[#104]: Added support for http://tonsky.me/blog/clojurefmt/[Tonsky's formatting rule]. ** https://liquidz.github.io/vim-iced/#customizing_tonsky_formatting_rule === Changed * Bump iced-nrepl to 1.0.3. * Bump kaocha-nrepl to 1.0.1. === Fixed * Fixed `:IcedUndef` command to handle not-found error. === Removed * (Breaking) Removed `:IcedToggleSideloaderLookup` command. ** Please use `:IcedStopSideloader` command instead. // }}} == 2.0.1 (2020-07-04) // {{{ === Added * https://github.com/liquidz/vim-iced/issues/229[#229]: Added `g:iced_default_key_mapping_leader` option to be able to change `` in default key mappings. === Fixed * Fixed test integration to show error message if error context does not exist. // }}} == 2.0.0 (2020-06-28) // {{{ === Added * Added support for test integration on plain nREPL with following commands. ** This functionality was sponsored by https://www.clojuriststogether.org[Clojurists Together] as a part of their ""Summer of Bugs"" program. ** `:IcedTestUnderCursor`, `:IcedTestNs`, `:IcedTestAll` ** Now you can run tests on https://github.com/borkdude/babashka/blob/master/doc/repl.md#nrepl[Babashka]! * Added `IcedUnaliasNs` command. * Added `IcedUpdateTool` command. * Added https://github.com/candid82/joker[joker] as a code formatter. === Fixed * Fixed to be able to get var from quoated symbols. * Fixed to be able to detect the namespace name in `in-ns` form. * Fixed to reset supported ops when reconnecting. * Fixed not to display extra messages on starting shadow-cljs REPL. === Removed * https://github.com/liquidz/vim-iced/issues/226[#226]: (Breaking) Removed ClojureScript support for `Nashorn` and `GraalJS`. ** c.f. https://clojurescript.org/news/2020-04-24-release // }}} == 1.5.5 (2020-06-08) // {{{ === Changed * Bump cider-nrepl to 0.25.2. // }}} == 1.5.4 (2020-06-05) // {{{ === Changed * Bump cider-nrepl to 0.25.1. // }}} == 1.5.3 (2020-06-04) // {{{ === Changed * Bump cider-nrepl to 0.25.0. * Bump iced-nrepl to 1.0.2. // }}} == 1.5.2 (2020-05-26) // {{{ === Added * Added support to launch babashka nREPL server. ** Added `g:iced#repl#babashka_repl_type` option. === Fixed * https://github.com/liquidz/vim-iced/issues/220[#220]: Fixed shadow-cljs dependency checking. // }}} == 1.5.1 (2020-05-19) // {{{ === Changed * Bump kaocha-nrepl. === Fixed * Fixed not to work one-line document when not connected. // }}} == 1.5.0 (2020-05-17) // {{{ === Changed * Updated `IcedDocumentOpen` to use simple document by metadata when there is no `info` op. * Bump kaocha. * Bump piggieback. // }}} == 1.4.5 (2020-05-15) // {{{ === Fixed * Fixed completion to work even if no candidate kind is returned. // }}} == 1.4.4 (2020-05-10) // {{{ === Fixed * Fixed inner state initialization more. // }}} == 1.4.3 (2020-05-10) // {{{ === Added * Added tip document for overwriting default key mappings. ** https://liquidz.github.io/vim-iced/#tips_overwriting_mappings === Changed * Changed Socket REPL session to evaluate `require` / `in-ns` when `bufread` / `bufenter` autocmd is fired. * Updated command palette to add run command to cmd history. * Update vital.vim modules to be latest. * Bump github ation workflows. === Fixed * Fixed to initialize inner state when reconnecting. ** e.g. connect -> start cljs REPL -> quit cljs REPL outside vim -> connect *** Since cljs session is left so far, we must initialize this state. // }}} == 1.4.2 (2020-04-24) // {{{ === Changed * Changed auto connection to be able to select project when nREPL and shadow-cljs projects exists. === Fixed * Fixed a code for default completion to work correctly in Socket REPL. // }}} == 1.4.1 (2020-04-18) // {{{ === Changed * Bump iced-nrepl to 1.0.1. === Fixed * Fixed virtual text to show correctly in nested namespaces in Socket REPL. // }}} == 1.4.0 (2020-04-14) // {{{ === Added * Added `:IcedEvalAtMark` command. * Added `:IcedEvalLastOuterTopList` command. ** Added `g:iced#eval#mark_at_last` option to specify which mark to use. * Added `:IcedClearNsCache` command. * Added `g:iced#nrepl#complete#ignore_context` option. === Changed * Changed to cache the namespaces and its aliases for performance improvement. ** `:IcedClearNsCache` will clear this cache. === Fixed * https://github.com/liquidz/vim-iced/issues/202[#202]: Fixed completion to avoid unexpected behavior with https://github.com/neoclide/coc.nvim[coc.nvim]. ** c.f. https://github.com/liquidz/vim-iced-coc-source/issues/1[vim-iced-coc-source#1] // }}} == 1.3.2 (2020-04-05) // {{{ === Fixed * Fixed nREPL manipulation to support https://github.com/borkdude/babashka[babashka]'s nREPL. // }}} == 1.3.1 (2020-03-29) // {{{ === Fixed * https://github.com/liquidz/vim-iced/issues/195[#195]: Fixed `boot repl` option to be able to launch REPL correctly. // }}} == 1.3.0 (2020-03-29) // {{{ === Added * Added a support for sideloader in nREPL 0.7.0. === Changed * Bump nREPL to 0.7.0. * Bump zprint to 0.5.4. === Fixed * Fixed buffer manipulation to ignore following autocmds also. ** `WinLeave`, `BufLeave` // }}} == 1.2.0 (2020-03-21) // {{{ === Added * Added a support https://github.com/borkdude/babashka[Babashka] to launching by `IcedInstantConnect`. === Fixed * Fixed `IcedAddMissing` and `IcedAddNs` commands not to time out. * Fixed `IcedCycleSrcAndTest` command not to time out. // }}} == 1.1.1 (2020-03-15) // {{{ === Fixed * https://github.com/liquidz/vim-iced/issues/191[#191]: Fixed `:IcedSourceShow` and `:IcedSourcePopupShow` to work correctly. * Fixed nrepl testing not to show duplicated results. * Fixed to unplace signs on other buffers correctly. (for testing mainly) // }}} == 1.1.0 (2020-03-12) // {{{ === Added * Added code completion support for Socket REPL and pREPL. ** https://github.com/borkdude/babashka[Babashka] ** https://github.com/candid82/joker[Joker] ** https://github.com/anmonteiro/lumo[Lumo] ** https://github.com/planck-repl/planck[Planck] // }}} == 1.0.3 (2020-03-02) // {{{ === Fixed * https://github.com/liquidz/vim-iced/issues/187[#187]: Fixed to preserve alternative window during scrolling stdout buffer. // }}} == 1.0.2 (2020-03-01) // {{{ === Changed * Bump refactor-nrepl to 2.5.0. * Update `IcedExtractFunction` to show concrete message on error. === Fixed * Fixed `IcedAddNs` to show ns alias candidate correctly in Vim. * Fixed opening buffer / scrolling to bottom manipulation to ignore `WinEnter` and `BufEnter` autocmd. // }}} == 1.0.1 (2020-02-26) // {{{ === Fixed * Fixed to connect to shadow-cljs REPL correctly. // }}} == 1.0.0 (2020-02-24) // {{{ https://insideclojure.org/2020/02/18/lib-version/ === Added * Add support GraalVM powered code formatting tools. ** https://github.com/greglook/cljstyle[cljstyle] ** https://github.com/kkinnear/zprint[zprint] === Changed * Bump cider-nrepl to 0.24.0. * Bump jet to 0.0.12. * Update vital.vim modules to be latest. === Fixed * Fixed debugger to work with latest cider-nrepl. * https://github.com/liquidz/vim-iced/issues/183[#183]: Fixed `:IcedTestNs` not to be ""Interrupted"" in Neovim. // }}} == 0.14.2 (2020-02-11) // {{{ === Added * Add more tests for iced#nrepl#document#open. * Add `iced#nrepl#op#iced#fetch_tapped_children` function. * Add support for referring docstrings in Socket REPL. * Add support for custom debugger. === Changed * Bump iced-nrepl to 0.7.1. === Fixed * Fixed `:IcedCleanNs` and `:IcedCleanAll` command to hold marks and the last visual range. * Fix regexp for detecting Socket REPL prompt. * Fix `eval_outer_top_list` for Socket REPL to be able to evaluate inside comment form. // }}} == 0.14.1 (2020-01-23) // {{{ === Added * https://github.com/liquidz/vim-iced/issues/179[#179]: Added environmental variable to overwrite Clojure CLI command. ** https://liquidz.github.io/vim-iced/#iced_command_advanced * Added cheatshet. ** https://liquidz.github.io/vim-iced/#cheatsheet === Changed * https://github.com/liquidz/vim-iced/issues/175[#175]: Changed `iced` command to use `clj` command for Clojure CLI project. * https://github.com/liquidz/vim-iced/issues/176[#176]: Added a mention for `PlugInstall` to ""Getting started"" document page. * https://github.com/liquidz/vim-iced/issues/177[#177]: Made `set hidden` option unnecessary. === Fixed * https://github.com/liquidz/vim-iced/issues/174[#174]: Fixed to work `(iced_eval_and_print)` correctly. * https://github.com/liquidz/vim-iced/issues/178[#178]: Fixed `:IcedFormatAll` command to hold marks and the last visual range. * Fixed virtual text position for Vim. // }}} == 0.14.0 (2020-01-14) // {{{ === Added * Added document pages. ** https://liquidz.github.io/vim-iced/ ** https://qiita.com/advent-calendar/2019/vim-iced * Added minimal support for socket REPL and pREPL. ** https://liquidz.github.io/vim-iced/#socket_repl * Added enhanced mode for `IcedSourceShow` command. ** Added `g:iced_enable_enhanced_definition_extraction` option. === Changed * (Breaking) Rename following commands. ** `IcedPopupDocumentOpen` -> `IcedDocumentPopupOpen` ** `IcedPopupSourceShow` -> `IcedSourcePopupShow` === Fixed * https://github.com/liquidz/vim-iced/issues/166[#166]: Fixed to show document protocol method correctly. * https://github.com/liquidz/vim-iced/issues/168[#168]: Fixed a bug for adding resolved namespace. * https://github.com/liquidz/vim-iced/issues/171[#171]: Fixed `IcedAddArity` not to break indents. * https://github.com/liquidz/vim-iced/issues/172[#172]: Fixed `IcedFormat` and `IcedFormatAll` to work asynchronously. * Fixed vim's popup window position when a window is thin. // }}} == 0.13.0 (2019-11-29) // {{{ === Added * Add hook for `connected` event. * Add `command` hook reporter to execute a command simply. * Add `IcedInInitNs` instead of `IcedInReplNs`. * Add `IcedUndefAllInNs` command. === Changed * https://github.com/liquidz/vim-iced/issues/158[#158]: Clear test error sign only if the test passes. * (Breaking) Required vim/neovim version is changed. ** Vim `8.1.0614` or later ** Neovim `0.4` or later * Bump iced-nrepl to 0.7.0. * (Breaking) Rename `IcedToggleSrcAndTest` command to `IcedCycleSrcAndTest`. * (Breaking) Integrate `IcedListTapped` command to `IcedBrowseTapped`. ** `IcedListTapped` command is removed. ** If `IcedBrowseTapped` command is executed with no arguments, it works like `IcedListTapped`. ** Add default key map `dbt` for `IcedBrowseTapped`. ** Change default key map `dlt` for `IcedClearTapped`. * Update to require ns automatically if the first ns-name on connecting REPL is not initial ns-name on REPL. === Fixed * Fixed clearing virtual text to work correctly in neovim. * Fixed not to clear quickfix when executing `IcedRequire` command. * Fixed to work auto connection correctly on evaluation. === Removed * (Breaking) https://github.com/liquidz/vim-iced/issues/159[#159]: Remove linting functionality. * (Breaking) Remove `:IcedDefBack` command. ** You can use built-in https://vim-jp.org/vimdoc-en/tagsrch.html#CTRL-T[] key mapping instead. * (Breaking) Remove `:IcedInReplNs` command. * (Breaking) Remove `eval-repl` hook kind. // }}} == 0.12.5 (2019-10-20) // {{{ === Added * Add `g:iced#nrepl#path_translation` option. ** It is useful for translating paths in docker container. ** https://liquidz.github.io/vim-iced/vim-iced.html#vim-iced-install-docker === Fixed * Fixed to process input-request from debugger correctly. * Fixed a bug that candidates gradually decreased with vim-clap. // }}} == 0.12.4 (2019-10-12) // {{{ === Added * Add `g:iced_enable_enhanced_cljs_completion` option. * Add support for https://github.com/liuchengxu/vim-clap[vim-clap] as multiple candidates selector. ** Add `g:iced#clap#options` option. === Changed * Bump cider-nrepl to 0.22.4. * Bump iced-nrepl to 0.6.6. * Update to show see-alsos in document lookup. === Fixed * Fix to show exception error in test to error buffer. // }}} == 0.12.3 (2019-09-21) // {{{ === Added * Add `g:iced#buffer#stdout#file_buffer_size` option. * https://github.com/liquidz/vim-iced/pull/151[#151]: Add `g:iced#popup#neovim#winhighlight` option. * https://github.com/liquidz/vim-iced/pull/151[#151]: Add `g:iced#popup#neovim#style` option. === Changed * Make `iced#buffer#append` to scroll down asynchronously. * Make `iced#buffer#stdout#append` to buffer lines for writing to `g:iced#buffer#stdout#file`. * https://github.com/liquidz/vim-iced/pull/149[#149]: Make buffer initialization silently. * Update `:IcedDocumentOpen` to check session validily. // }}} == 0.12.2 (2019-09-16) // {{{ === Fixed * Fix to show test error correctly in neovim 0.4.0. // }}} == 0.12.1 (2019-09-14) // {{{ === Added * Add `g:iced#buffer#stdout#max_line` option. ** This option is a limit of line count in stdout buffer. * Add `g:iced#buffer#stdout#deleting_line_delay` option. * Add operation to evaluate codes and tap its results. ** `(iced_eval_and_tap)` * Add `:IcedInterruptAll` command. * Add `:IcedJackIn` command. ** Add `g:iced#nrepl#connect#jack_in_command` option. *** This option enables you to customize jack-in command. === Changed * Bump cider-nrepl to 0.22.3. * Bump iced-nrepl to 0.6.4. === Fixed * Fix to extract ns-name correctly. ** Previously it was not working well for ns form with metadata. // }}} == 0.12.0 (2019-09-07) // {{{ === Changed * Bump cider-nrepl to 0.22.2. * Bump iced-nrepl to 0.6.3. * Make `:IcedGrep` async. ** Add `g:iced#grep#prg` option. ** Add `g:iced#grep#format` option. * Change `IcedBrowseReferences` and `:IcedBrowseDependencies` to show results in quickfix. === Fixed * Fix checking shadow-cljs dependency process. * Fix to work `IcedTestUnderCursor` with neovim 0.4.0(nightly). * Fix for rare reading bencode error. * Fix browsing references/dependencies to work. * Fix test error result to show file path correctly. === Removed * (Breaking) Remove `g:iced#grep#target` option. // }}} == 0.11.3 (2019-08-27) // {{{ === Added * https://github.com/liquidz/vim-iced/pull/140[#140]: Add dependencies and middlewares validation for shadow-cljs.edn. ** vim-iced will validate shadow-cljs.edn when you start cljs REPL. === Fixed * https://github.com/liquidz/vim-iced/pull/142[#142]: Fix jumping to all Clojure's Symbols. // }}} == 0.11.2 (2019-08-26) // {{{ === Changed * Bump cider-nrepl to 0.22.0-beta12. ** Fix completion bugs with ClojureScript. // }}} == 0.11.1 (2019-08-24) // {{{ === Added * Add `g:vim_iced_version` variable for detecting the vim-iced version from other plugins. * Add `iced#complete#candidates` function to fetch completions. * Add `:IcedToggleWarnOnReflection` command. * Add `:IcedFormatAll` command. * Add `:IcedCleanAll` command. * Add `:IcedInstantConnect` command. ** Add `--instant` option to `iced repl` sub command. === Changed * https://github.com/liquidz/vim-iced/pull/135[#135]: Update `:IcedDocumentOpen` to work with qualified symbols.. === Fixed * https://github.com/liquidz/vim-iced/pull/134[#134]: Fix to work with nvim 0.4.0(nightly). * https://github.com/liquidz/vim-iced/pull/135[#135]: Fix `:IcedDocumentOpen` to work correctly. * https://github.com/liquidz/vim-iced/pull/139[#139]: Fix jumping to var that includes single quote. * Fix to show documents for special forms such as `try`. * Fix to hide virtual text if the last one has same position. // }}} == 0.11.0 (2019-08-03) // {{{ === Added * Add support vim8's popup window. ** https://github.com/vim/vim/blob/master/runtime/doc/popup.txt ** Enables virtual text for evaluation and floating window for debugging. ** Add `g:iced_enable_popup_document` option. ** Add `g:iced_enable_auto_document` option. ** Add `g:iced_max_distance_for_auto_document` option. *** Enables full/one-line document on popup/floating window. ** Add `IcedPopupDocumentOpen` command. ** Add `IcedPopupSourceShow` command. * Add support cross references ** Add `IcedBrowseReferences` command. ** Add `IcedBrowseDependencies` command. ** Add `IcedBrowseVarDependencies` command. ** Add `IcedUseCaseOpen` command. * Enhance spec supports ** Add `IcedSpecForm` command. ** Add `IcedSpecExample` command. * Support debugging tapped value. ** Add `IcedListTapped` command. ** Add `IcedClearTapped` command. ** Add `IcedBrowseTapped` command. * Integrate with ClojureDocs. ** Add `IcedClojureDocsOpen` command. ** Add `IcedClojureDocsRefresh` command. ** Add `g:iced#clojuredocs#export_edn_url` option. * Misc ** Add `IcedOpenNs` command. ** Add `--with-kaocha` option to `iced` command. === Changed * Bump cider-nrepl to 0.22.0-beta9. * Bump piggieback to 0.4.1. * Bump https://github.com/liquidz/iced-nrepl[iced-nrepl] to 0.6.0. * Update vital.vim to latest. * Update `:IcedToggleSrcAndTest` to confirm opening a new file with a pseudo path if the file does not exist. * (BREAKING) Rename `g:iced#buffer#floating#time` to `g:iced#popup#time`. * (BREAKING) Rename `g:iced#nrepl#sync#timeout_ms` to `g:iced#promise#timeout_ms`. ** Add `cider.nrepl/wrap-xref` to required middlewares. * (BREAKING) Change default `K` mapping to `IcedPopupDocumentOpen` command. * (BREAKING) Change default `hs` mapping to `IcedPopupSourceShow` command. ** Until now it was `IcedDocumentOpen` command. * (BREAKING) Commands/Key mappings maintenance. [title=""Commands""] |=== | Before | After | IcedGotoLet | IcedJumpToLet | IcedRelatedNamespace | IcedBrowseRelatedNamespace | IcedFindVarReferences | IcedBrowseVarReferences |=== [title=""Key mappings""] |=== | Before | After | (iced_related_namespace) | (iced_browse_related_namespace) | (iced_goto_let) | (iced_jump_to_let) | (iced_find_var_references) | (iced_browse_var_references) |=== [title=""Default keys""] |=== | Mapping | Before | After | (iced_browse_related_namespace) | br | bn | (iced_jump_to_let) | gl | jl | (iced_browse_references) | fr | br |=== === Fixed * Fix floating window position on split windows. === Removed * (BREAKING) Remove `IcedFindVarReferences!` command. * (BREAKING) Remove `g:iced#var_references#cache_dir` option. * Remove `iced#nrepl#op#iced#find_var_references` function. * (BREAKING) Remove `IcedGrimoireOpen` command. ** Sadly grimoire is deprecated... *** https://twitter.com/arrdem/status/1144065851370299392 *** Use `:IcedClojureDocsOpen` instead. // }}} == 0.10.5 (2019-06-19) // {{{ === Fixed * https://github.com/liquidz/vim-iced/pull/128[#128]: Fix `:IcedStartCljsRepl shadow-cljs` not to hang with shadow-cljs. // }}} == 0.10.4 (2019-05-14) // {{{ === Added * Add `--without-cljs` option to `iced` command. * Add `--dependencies` option to `iced` command. * Add `--middleware` option to `iced` command. * Add `g:iced#format#does_overwrite_rules` option. * Add CI config for neovim testing. ** Support neovim officially from this version! * Add operation to evaluate codes and print its results. ** `(iced_eval_and_print)` === Changed * Bump https://github.com/liquidz/iced-nrepl[iced-nrepl] to 0.4.3. === Fixed * https://github.com/liquidz/vim-iced/pull/117[#117]: Fix to detect channel disconnection on neovim. * Fix grimoire fetching error with OpenJDK 11. ** See https://github.com/http-kit/http-kit/issues/388 * Fix to work `in-ns` on reading buffer without moving window. // }}} == 0.10.3 (2019-03-25) // {{{ === Added * Add some extra documents. ** https://liquidz.github.io/vim-iced/vim-iced.html === Changed * https://github.com/liquidz/vim-iced/pull/110[#110]: Change `:IcedDocumentOpen` not to move focus if document buffer is already opened. === Fixed * Fix arguments for `nvim_open_win` ** Neovim's https://github.com/neovim/neovim/commit/27c4b6b9bd90fbc3a41945f87ec944bd0ced8228#diff-49e08ed0add04457bc8a43c962736f13L628[API] has changed. * https://github.com/liquidz/vim-iced/pull/105[#105]: Fix shadow-cljs build-id to trim the beginning colon * https://github.com/liquidz/vim-iced/pull/107[#107]: Fix iced command to render color correctly // }}} == 0.10.2 (2019-03-10) // {{{ === Added * https://github.com/liquidz/vim-iced/pull/96[#96]: Add floating window support for neovim. ** You need nightly build(0.4.0) currently. * Add github pages for help file. ** https://liquidz.github.io/vim-iced/vim-iced.html ** powered by https://github.com/liquidz/clj-vimhelp[clj-vimhelp]. === Fixed * https://github.com/liquidz/vim-iced/pull/101[#101]: Fix not to evaluate `in-ns` while appending lines to stdout buffer. // }}} == 0.10.1 (2019-03-05) // {{{ === Added * Add http://shadow-cljs.org[shadow-cljs] as a CLJS environment. ** Now you can start CLJS REPL via `:IcedStartCljsRepl shadow-cljs {build-id}`. ** WARNING: `iced` command does not support shadow-cljs yet. * Add neovim virtual text support. ** Evaluation result and lint warning messages are shown as virtual text. ** WARNING: Neovim only * Add `g:iced#lint#use_virtual_text` option. ** WARNING: Neovim only * https://github.com/liquidz/vim-iced/pull/87[#87]: Add `:IcedEvalVisual` and `:IcedEvalReplVisual` commands to evaluate selected forms. * https://github.com/liquidz/vim-iced/issues/99[#99]: Add `--force-boot` and `--force-clojure-cli` options to `iced` command. === Changed * Update `:IcedEval` not to evaluate `ns` form every evaluation. ** This leads to evaluation performance improvement for CLJS codes. * Update not to switch session unnecessarily at cljs repl startup. * Update echoing eval result to shorten === Fixed * Fix a bug that `:IcedDefJump` fails for protocol fns. * Fix a type checking bug in testing. // }}} == 0.10.0 (2019-02-19) // {{{ === Added * Add support for https://github.com/bhauman/figwheel-main[figwheel-main]. * Add `:IcedCljsRepl` command for general use of starting CLJS REPL. * Add `:IcedCycleSession` command for cycling clj/cljs session. * Add `g:iced#nrepl#auto#does_switch_session` option for switching CLJ/CLJS session automatically. === Changed * (Breaking) Rename `figwheel` CLJS environment to `figwheel-sidecar`. * Bump nrepl to 0.6.0. * Bump cider-nrepl to 0.21.1. * Bump piggieback to 0.4.0. * (Breaking) Change to require neovim 0.3.2 or later. * Change status text to clarify CLJ/CLJS session status. === Removed * (Breaking) Remove `iced#nrepl#cljs#custom` option. ** Instead of this option, `:IcedCljsRepl` command is added. === Fixed * Fix a bug that response to difference IDs cannot be processed correctly. // }}} == 0.9.3 (2019-01-30) // {{{ === Added * Add hooking feature. ** See details `:h vim-iced-customizing-hooks` === Changed * Bump iced-nrepl to 0.4.1. * https://github.com/liquidz/vim-iced/pull/85[#85]: Update sample code for debugging to work correctly. === Removed * Remove `g:iced#lint#message_max_length` option. (https://github.com/liquidz/vim-iced/pull/79[#79]) === Fixed * https://github.com/liquidz/vim-iced/pull/79[#79]: Fix to prevent ""Press ENTER"" prompt on `one_line_doc` and `lint` message. * Fix bug when completing on new file. * Fix bug when slurping on new file. * Fix to apply skeleton without `clojure.data.json` correctly. // }}} == 0.9.2 (2019-01-15) // {{{ === Changed * https://github.com/liquidz/vim-iced/pull/72[#72]: Update `IcedDefJump` to enable jump into JAR file. * https://github.com/liquidz/vim-iced/pull/73[#73]: Update `iced` command to `piggieback` as an option. ** `iced` command will detect use of CLJS automatically, so you won't need to specify this option basically. * https://github.com/liquidz/vim-iced/pull/74[#74]: Update `:IcedReconnect` to work if a connection is not already established. * Bump iced-nrepl to 0.4.0. === Fixed * https://github.com/liquidz/vim-iced/pull/75[#75]: Fix `E158` error on testing. * https://github.com/liquidz/vim-iced/pull/77[#77]: Fix running tests to work correctly in any namespaces. * https://github.com/liquidz/vim-iced/pull/78[#78]: Fix a bug on processing `info` op response from nREPL. * Fix to reset indentation rules when `:IcedReconnect` is executed. // }}} == 0.9.1 (2019-01-01) // {{{ === Changed * Bump cider-nrepl to 0.19.0. // }}} == 0.9.0 (2018-12-27) // {{{ === Added * Add `g:iced#lint#message_max_length` option. === Changed * Bump iced-nrepl to 0.3.0. ** Isolate iced-nrepl depending on libraries by https://github.com/benedekfazekas/mranderson[mranderson]. * Improve switching signs process performance. ** `iced#sign#unplace#_by_name` is updated. === Fixed * Fix auto-indent for `defrecord`. * Fix to show eastwood's warnings correctly. ** iced-nrepl was failed to detect some type of warnings. * Fix not to throw exception when `:wq` is executed. ** Make linting delay to working. // }}} == 0.8.7 (2018-12-20) // {{{ === Added * Add `g:iced_sign` variable to customize signs. === Changed * Bump nrepl to 0.5.3 === Fixed * #64 Fix to work auto-indent with EDN file. * Fix to work auto-indent after moving buffer or window. * Fix to clear error sign before running `:IcedTestRerunLast`. * Fix `:IcedTestRerunLast` to work with any test patterns. * #65 Fix redrawing glitches for neovim 0.3.2-dev ** This is a workaround for https://github.com/neovim/neovim/issues/7756[neovim's #7756]. * #66 Fix to work auto-indent for string literal. // }}} == 0.8.6 (2018-12-11) // {{{ === Added * Add `:IcedFindVarReferences` command. * Support auto indentation. === Changed * Bump nrepl to 0.5.2 * Bump iced-nrepl to 0.2.11 === Fixed * Fix error in debugging if the file is not saved. ** Fix not to execute `:edit` file in debugging if the file is already opened. * Fix evaluation status not to display ""evaluating"" for initializing debugger. // }}} == 0.8.5 (2018-12-05) // {{{ === Changed * Bump nrepl to 0.5.1 * Bump iced-nrepl to 0.2.8 === Fixed * Fix to warn if there are no test vars on testing from source. * Fix to warn if there are no test_vars on browsing tests. * Fix to unplace corresponding signs when linting and testing. * Fix starting trace process to unplace sign if the sign already exists. // }}} == 0.8.4 (2018-11-28) // {{{ === Added * Allow to connect shadow-cljs's nREPL server as ClojureScript session. === Changed * Bump iced-nrepl to 0.2.6 * Update `:IcedRelatedNamespace` command not to load all namespace at first. === Fixed * Fix completion bug immediately after nREPL connection. // }}} == 0.8.3 (2018-11-20) // {{{ === Added * Allowed to run tests on source code. ** In the test namespace corresponding to the current namespace, tests including name of function under the cursor are the target. * Added `:IcedBrowseTestUnderCursor` command. === Changed * Update not to display ""evaluating"" on status line during linter check. === Fixed * Fix `iced#eval_and_read` to work correctly. ** Code skeleton sometimes failed. * Fix `:IcedTestNs` to work correctly. ** In source code, ""Not found"" error is shown before evaluating some codes. // }}} == 0.8.2 (2018-11-15) // {{{ === Changed * Update to load all ns before browsing related ns only for the first time. * Bump cider-nrepl to 0.19.0-SNAPSHOT ** Update `ns-aliases` op in cider-nrepl to fetch namespace aliases. === Fixed * #55: Fix not to expand macro in IcedThreadFirst/Last command. ** via https://github.com/liquidz/iced-nrepl/commit/de329da8c0f7cffb8fdbd20b6baec581ba15ae76[iced-nrepl] * Fix not to expand vector in IcedThreadFirst/Last command. ** Same above * Fix to handle not-found error on jumping to definition // }}} == 0.8.1 (2018-11-08) // {{{ === Added * Add option to restrict value length in debugging. ** `g:iced#debug#value_max_length` * Add option for `:IcedRelatedNamespace` command. ** `g:iced#related_ns#tail_patterns` *** The namespace tailing pattern to decide the namespace is related or not. * Add clojurescript environment for https://github.com/graalvm/graaljs[GraalJS] === Changed * Update referencing document to show with vim's `help` format. * Update testing process to use `test-var-query` op instead of `test`/`test-all` op in cider-nrepl. ** `test` and `test-all` ops are already deprecated. *** https://github.com/clojure-emacs/cider-nrepl/blob/master/CHANGELOG.md#0170-2018-05-07 * Update to connect nREPL automatically when starting `cljs-repl`. === Fixed * Fix bug for echoing document for Java class constructor under cursor. // }}} == 0.8.0 (2018-11-07) // {{{ === Added * Add option for updating document buffer with current form document. ** `g:iced#buffer#document#does_update_automatically` === Changed * Update to use nrepl.cmdline to launch nREPL server for Clojure CLI instead of cider-nrepl.main * *BREAKING*: Change not to update document buffer with current form document when document buffer is visible. ** You can change this behavior with `g:iced#buffer#document#does_update_automatically` option. === Removed * `g:iced#eastwood#linters` option === Fixed * Fix to work document/grimoire reference before evaluation. * Fix `iced#sign` to check file existence before placing it. * Update `iced#nrepl#system` to evaluate with fully qualified name. * ex) error occured when custom `let` is defined. * Update test commands to check nREPL connection before running. // }}} == 0.7.3 (2018-10-31) // {{{ === Added * Add `g:iced#eastwood#option` which allows to set `exclude-linters` === Changed * Bump iced-nrepl version to 0.2.3 === Deprecated * `g:iced#eastwood#linters` option === Fixed * Fix `iced#nrepl#auto#bufread` to check session validity // }}} == 0.7.2 (2018-10-29) // {{{ === Added * Add codecov badge ** for measuring code coverage * Add test codes ** `iced#complete`, `iced#sign` === Fixed * Fix not to split window permanently when debugging // }}} == 0.7.1 (2018-10-25) // {{{ * Fix jumping to definition not to jump into JAR file * Refactor codes // }}} == 0.7.0 (2018-10-23) // {{{ * Update to support Clojure 1.10's error message format * Update to work with Clojure 1.8 ** via updating https://github.com/liquidz/iced-nrepl/commit/3837d103454586d81f36130defa9daf1575adcb5[iced-nrepl] * Bump orchard version to 0.3.3 * Refactor codes === Breaking changes * Update `:IcedCleanNs` command not to rewrite prefix ** Add `g:iced#refactor#prefix_rewriting` option to change behavior. (default value is 'v:false') * Rename options |=== | before | after | g:iced#nrepl#cljs#default_env | g:iced#cljs#default_env | g:iced#nrepl#cljs#custom#start_code | g:iced#cljs#custom#start_code | g:iced#nrepl#cljs#custom#stop_code | g:iced#cljs#custom#stop_code | g:iced#nrepl#eval#inside_comment | g:iced#eval#inside_comment | g:iced#nrepl#ns#refactor#favorites | g:iced#ns#favorites | g:iced#nrepl#op#cider#debug#print_length | g:iced#debug#print_length | g:iced#nrepl#op#cider#debug#print_level | g:iced#debug#print_level | g:iced#nrepl#test#spec_num_tests | g:iced#test#spec_num_tests | g:iced#palette#palette | g:iced#palette | g:iced#lint#linters | g:iced#eastwood#linters |=== // }}} == 0.6.2 (2018-10-19) // {{{ * Fix not to remove blank lines too much in code formatting #49 * Update to interrupt when disconnecting * Update to make spec document more readable // }}} == 0.6.1 (2018-10-19) // {{{ * Fix to work skeleton correctly #47 * Fix ""Argument to in-ns must be a symbol"" error by `IcedInReplNs` command #46 * Support junegunn/fzf as a selector ** https://github.com/junegunn/fzf * Update `iced` command to allow `with-profile` option for leiningen // }}} == 0.6.0 (2018-10-17) // {{{ * Fix code formatting to delete extra empty line * Fix a bug causes evaluation error on stdout buffer * Update to check `set hidden` when connecting to nrepl * Fix a bug causes vim error when closing stdout/repl buffer * Update completion to display correct document in preview window === Breaking changes * Delete `:IcedBrowseFunction` command ** Extracted to https://github.com/liquidz/vim-iced-project-namespaces * Delete `:IcedBrowseNamespace` command ** Extracted to https://github.com/liquidz/vim-iced-function-list // }}} == 0.5.5 (2018-10-13) // {{{ * Update linting not to run when linting is already running * Update to clear signs when linting is disabled * Update to refresh signs when code is formatted * Add python3 code to boost decoding bencode * Fix decoding bencode in vim script to work(detect error) with incorrect character * Fix setting sign to ignore errors that has no line number // }}} == 0.5.4 (2018-10-10) // {{{ * Fixed `IcedPrintLast` to output all results * Fixed a bug that caused an error if javadoc result did not have a `member` key * Add `clojure.spec.test.alpha` as ns favorites for `IcedAddNs` * Add `IcedTestSpecCheck` command // }}} == 0.5.3 (2018-10-09) // {{{ * Fix to use `sockconnect` for nREPL connection #40 * Update debugging highlighting to specify background color * Update to reload all namespaces before running all tests * Add `IcedRelatedNamespaces` command // }}} == 0.5.2 (2018-10-06) // {{{ * Update code formatting to specify `alias-map` for cljfmt * Tweak codes // }}} == 0.5.1 (2018-10-05) // {{{ * Update to show evaluation error when it is clear that current session is invalid from the extension * Update to be able to define custom command in the command palette // }}} == 0.5.0 (2018-10-03) // {{{ * Fix to work completion on the stdout buffer correctly ** https://github.com/liquidz/iced-nrepl/commit/15697d35f6407a1d86d1a9bce68341792a41cbbc * Update to execute corresponding test codes even if test-ns is executed on the src side * Add `IcedTestRerunLast` command * Support neovim EXPERIMENTALLY // }}} ",12399,True,2708.0768489786983,median "// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // FRAMES.CPP #include ""common.h"" #include ""log.h"" #include ""frames.h"" #include ""threads.h"" #include ""object.h"" #include ""method.hpp"" #include ""class.h"" #include ""excep.h"" #include ""stublink.h"" #include ""fieldmarshaler.h"" #include ""siginfo.hpp"" #include ""gcheaputilities.h"" #include ""dllimportcallback.h"" #include ""stackwalk.h"" #include ""dbginterface.h"" #include ""gms.h"" #include ""eeconfig.h"" #include ""ecall.h"" #include ""clsload.hpp"" #include ""cgensys.h"" #include ""virtualcallstub.h"" #include ""dllimport.h"" #include ""gcrefmap.h"" #include ""asmconstants.h"" #ifdef FEATURE_COMINTEROP #include ""comtoclrcall.h"" #endif // FEATURE_COMINTEROP #ifdef FEATURE_INTERPRETER #include ""interpreter.h"" #endif // FEATURE_INTERPRETER #include ""argdestination.h"" #define CHECK_APP_DOMAIN 0 //----------------------------------------------------------------------- #if _DEBUG //----------------------------------------------------------------------- #ifndef DACCESS_COMPILE unsigned dbgStubCtr = 0; unsigned dbgStubTrip = 0xFFFFFFFF; void Frame::Log() { WRAPPER_NO_CONTRACT; if (!LoggingOn(LF_STUBS, LL_INFO1000000)) return; dbgStubCtr++; if (dbgStubCtr > dbgStubTrip) { dbgStubCtr++; // basicly a nop to put a breakpoint on. } MethodDesc* method = GetFunction(); STRESS_LOG3(LF_STUBS, LL_INFO1000000, ""STUBS: In Stub with Frame %p assoc Method %pM FrameType = %pV\\n"", this, method, *((void**) this)); char buff[64]; const char* frameType; if (GetVTablePtr() == PrestubMethodFrame::GetMethodFrameVPtr()) frameType = ""PreStub""; else if (GetVTablePtr() == PInvokeCalliFrame::GetMethodFrameVPtr()) { sprintf_s(buff, ARRAY_SIZE(buff), ""PInvoke CALLI target"" FMT_ADDR, DBG_ADDR(((PInvokeCalliFrame*)this)->GetPInvokeCalliTarget())); frameType = buff; } else if (GetVTablePtr() == StubDispatchFrame::GetMethodFrameVPtr()) frameType = ""StubDispatch""; else if (GetVTablePtr() == ExternalMethodFrame::GetMethodFrameVPtr()) frameType = ""ExternalMethod""; else frameType = ""Unknown""; if (method != 0) LOG((LF_STUBS, LL_INFO1000000, ""IN %s Stub Method = %s::%s SIG %s ESP of return"" FMT_ADDR ""\\n"", frameType, method->m_pszDebugClassName, method->m_pszDebugMethodName, method->m_pszDebugMethodSignature, DBG_ADDR(GetReturnAddressPtr()))); else LOG((LF_STUBS, LL_INFO1000000, ""IN %s Stub Method UNKNOWN ESP of return"" FMT_ADDR ""\\n"", frameType, DBG_ADDR(GetReturnAddressPtr()) )); _ASSERTE(GetThread()->PreemptiveGCDisabled()); } //----------------------------------------------------------------------- // This function is used to log transitions in either direction // between unmanaged code and CLR/managed code. // This is typically done in a stub that sets up a Frame, which is // passed as an argument to this function. void __stdcall Frame::LogTransition(Frame* frame) { CONTRACTL { DEBUG_ONLY; NOTHROW; ENTRY_POINT; GC_NOTRIGGER; } CONTRACTL_END; BEGIN_ENTRYPOINT_VOIDRET; #ifdef TARGET_X86 // On x86, StubLinkerCPU::EmitMethodStubProlog calls Frame::LogTransition // but the caller of EmitMethodStubProlog sets the GSCookie later on. // So the cookie is not initialized by the point we get here. #else _ASSERTE(*frame->GetGSCookiePtr() == GetProcessGSCookie()); #endif if (Frame::ShouldLogTransitions()) frame->Log(); END_ENTRYPOINT_VOIDRET; } // void Frame::Log() #endif // #ifndef DACCESS_COMPILE //----------------------------------------------------------------------- #endif // _DEBUG //----------------------------------------------------------------------- // TODO [DAVBR]: For the full fix for VsWhidbey 450273, all the below // may be uncommented once isLegalManagedCodeCaller works properly // with non-return address inputs, and with non-DEBUG builds #if 0 //----------------------------------------------------------------------- // returns TRUE if retAddr, is a return address that can call managed code bool isLegalManagedCodeCaller(PCODE retAddr) { WRAPPER_NO_CONTRACT; #ifdef TARGET_X86 // we expect to be called from JITTED code or from special code sites inside // mscorwks like callDescr which we have put a NOP (0x90) so we know that they // are specially blessed. if (!ExecutionManager::IsManagedCode(retAddr) && ( #ifdef DACCESS_COMPILE !(PTR_BYTE(retAddr).IsValid()) || #endif ((*PTR_BYTE(retAddr) != 0x90) && (*PTR_BYTE(retAddr) != 0xcc)))) { LOG((LF_GC, LL_INFO10, ""Bad caller to managed code: retAddr=0x%08x, *retAddr=0x%x\\n"", retAddr, *(BYTE*)PTR_BYTE(retAddr))); return false; } // it better be a return address of some kind TADDR dummy; if (isRetAddr(retAddr, &dummy)) return true; #ifndef DACCESS_COMPILE #ifdef DEBUGGING_SUPPORTED // The debugger could have dropped an INT3 on the instruction that made the call // Calls can be 2 to 7 bytes long if (CORDebuggerAttached()) { PTR_BYTE ptr = PTR_BYTE(retAddr); for (int i = -2; i >= -7; --i) if (ptr[i] == 0xCC) return true; return false; } #endif // DEBUGGING_SUPPORTED #endif // #ifndef DACCESS_COMPILE _ASSERTE(!""Bad return address on stack""); return false; #else // TARGET_X86 return true; #endif // TARGET_X86 } #endif //0 //----------------------------------------------------------------------- // Count of the number of frame types const size_t FRAME_TYPES_COUNT = #define FRAME_TYPE_NAME(frameType) +1 #include ""frames.h"" ; #if defined (_DEBUG_IMPL) // _DEBUG and !DAC //----------------------------------------------------------------------- // Implementation of the global table of names. On the DAC side, just the global pointer. // On the runtime side, the array of names. #define FRAME_TYPE_NAME(x) {x::GetMethodFrameVPtr(), #x} , static FrameTypeName FrameTypeNameTable[] = { #include ""frames.h"" }; /* static */ PTR_CSTR Frame::GetFrameTypeName(TADDR vtbl) { LIMITED_METHOD_CONTRACT; for (size_t i=0; iLogFrame(LF, LL); pFrame = pFrame->m_Next; } } // void Frame::LogFrameChain() //----------------------------------------------------------------------- #endif // _DEBUG_IMPL //----------------------------------------------------------------------- #ifndef DACCESS_COMPILE // This hashtable contains the vtable value of every Frame type. static PtrHashMap* s_pFrameVTables = NULL; // static void Frame::Init() { CONTRACTL { THROWS; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; // create a table big enough for all the frame types, not in asynchronous mode, and with no lock owner s_pFrameVTables = ::new PtrHashMap; s_pFrameVTables->Init(2 * FRAME_TYPES_COUNT, FALSE, &g_lockTrustMeIAmThreadSafe); #define FRAME_TYPE_NAME(frameType) \\ s_pFrameVTables->InsertValue(frameType::GetMethodFrameVPtr(), \\ (LPVOID) frameType::GetMethodFrameVPtr()); #include ""frames.h"" } // void Frame::Init() #endif // DACCESS_COMPILE // Returns true if the Frame's VTablePtr is valid // static bool Frame::HasValidVTablePtr(Frame * pFrame) { WRAPPER_NO_CONTRACT; if (pFrame == NULL || pFrame == FRAME_TOP) return false; #ifndef DACCESS_COMPILE TADDR vptr = pFrame->GetVTablePtr(); // // Helper MethodFrame,GCFrame,DebuggerSecurityCodeMarkFrame are the most // common frame types, explicitly check for them. // if (vptr == HelperMethodFrame::GetMethodFrameVPtr()) return true; if (vptr == DebuggerSecurityCodeMarkFrame::GetMethodFrameVPtr()) return true; // // otherwise consult the hashtable // if (s_pFrameVTables->LookupValue(vptr, (LPVOID) vptr) == (LPVOID) INVALIDENTRY) return false; #endif return true; } // Returns the location of the expected GSCookie, // Return NULL if the frame's vtable pointer is corrupt // // Note that Frame::GetGSCookiePtr is a virtual method, // and so it cannot be used without first checking if // the vtable is valid. // static PTR_GSCookie Frame::SafeGetGSCookiePtr(Frame * pFrame) { WRAPPER_NO_CONTRACT; _ASSERTE(pFrame != FRAME_TOP); if (Frame::HasValidVTablePtr(pFrame)) return pFrame->GetGSCookiePtr(); else return NULL; } //----------------------------------------------------------------------- #ifndef DACCESS_COMPILE //----------------------------------------------------------------------- // Link and Unlink this frame. //----------------------------------------------------------------------- VOID Frame::Push() { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; } CONTRACTL_END; Push(GetThread()); } VOID Frame::Push(Thread *pThread) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; } CONTRACTL_END; _ASSERTE(*GetGSCookiePtr() == GetProcessGSCookie()); m_Next = pThread->GetFrame(); // GetOsPageSize() is used to relax the assert for cases where two Frames are // declared in the same source function. We cannot predict the order // in which the C compiler will lay them out in the stack frame. // So GetOsPageSize() is a guess of the maximum stack frame size of any method // with multiple Frames in coreclr.dll _ASSERTE((pThread->IsExecutingOnAltStack() || (m_Next == FRAME_TOP) || (PBYTE(m_Next) + (2 * GetOsPageSize())) > PBYTE(this)) && ""Pushing a frame out of order ?""); _ASSERTE(// If AssertOnFailFast is set, the test expects to do stack overrun // corruptions. In that case, the Frame chain may be corrupted, // and the rest of the assert is not valid. // Note that the corrupted Frame chain will be detected // during stack-walking. !g_pConfig->fAssertOnFailFast() || (m_Next == FRAME_TOP) || (*m_Next->GetGSCookiePtr() == GetProcessGSCookie())); pThread->SetFrame(this); } VOID Frame::Pop() { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; } CONTRACTL_END; Pop(GetThread()); } VOID Frame::Pop(Thread *pThread) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; } CONTRACTL_END; _ASSERTE(pThread->GetFrame() == this && ""Popping a frame out of order ?""); _ASSERTE(*GetGSCookiePtr() == GetProcessGSCookie()); _ASSERTE(// If AssertOnFailFast is set, the test expects to do stack overrun // corruptions. In that case, the Frame chain may be corrupted, // and the rest of the assert is not valid. // Note that the corrupted Frame chain will be detected // during stack-walking. !g_pConfig->fAssertOnFailFast() || (m_Next == FRAME_TOP) || (*m_Next->GetGSCookiePtr() == GetProcessGSCookie())); pThread->SetFrame(m_Next); m_Next = NULL; } #if defined(TARGET_UNIX) && !defined(DACCESS_COMPILE) void Frame::PopIfChained() { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; } CONTRACTL_END; if (m_Next != NULL) { GCX_COOP(); // When the frame is destroyed, make sure it is no longer in the // frame chain managed by the Thread. Pop(); } } #endif // TARGET_UNIX && !DACCESS_COMPILE //----------------------------------------------------------------------- #endif // #ifndef DACCESS_COMPILE //--------------------------------------------------------------- // Get the extra param for shared generic code. //--------------------------------------------------------------- PTR_VOID TransitionFrame::GetParamTypeArg() { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; SUPPORTS_DAC; } CONTRACTL_END; // This gets called while creating stack traces during exception handling. // Using the ArgIterator constructor calls ArgIterator::Init which calls GetInitialOfsAdjust // which calls SizeOfArgStack, which thinks it may load value types. // However all these will have previously been loaded. // // I'm not entirely convinced this is the best places to put this: CrawlFrame::GetExactGenericArgsToken // may be another option. ENABLE_FORBID_GC_LOADER_USE_IN_THIS_SCOPE(); MethodDesc *pFunction = GetFunction(); _ASSERTE (pFunction->RequiresInstArg()); MetaSig msig(pFunction); ArgIterator argit (&msig); INT offs = argit.GetParamTypeArgOffset(); TADDR taParamTypeArg = *PTR_TADDR(GetTransitionBlock() + offs); return PTR_VOID(taParamTypeArg); } TADDR TransitionFrame::GetAddrOfThis() { WRAPPER_NO_CONTRACT; return GetTransitionBlock() + ArgIterator::GetThisOffset(); } VASigCookie * TransitionFrame::GetVASigCookie() { #if defined(TARGET_X86) LIMITED_METHOD_CONTRACT; return dac_cast( *dac_cast(GetTransitionBlock() + sizeof(TransitionBlock))); #else WRAPPER_NO_CONTRACT; MetaSig msig(GetFunction()); ArgIterator argit(&msig); return PTR_VASigCookie( *dac_cast(GetTransitionBlock() + argit.GetVASigCookieOffset())); #endif } #ifndef DACCESS_COMPILE PrestubMethodFrame::PrestubMethodFrame(TransitionBlock * pTransitionBlock, MethodDesc * pMD) : FramedMethodFrame(pTransitionBlock, pMD) { LIMITED_METHOD_CONTRACT; } #endif // #ifndef DACCESS_COMPILE BOOL PrestubMethodFrame::TraceFrame(Thread *thread, BOOL fromPatch, TraceDestination *trace, REGDISPLAY *regs) { WRAPPER_NO_CONTRACT; // // We want to set a frame patch, unless we're already at the // frame patch, in which case we'll trace the method entrypoint. // if (fromPatch) { // In between the time where the Prestub read the method entry point from the slot and the time it reached // ThePrestubPatchLabel, GetMethodEntryPoint() could have been updated due to code versioning. This will result in the // debugger getting some version of the code or the prestub, but not necessarily the exact code pointer that winds up // getting executed. The debugger has code that handles this ambiguity by placing a breakpoint at the start of all // native code versions, even if they aren't the one that was reported by this trace, see // DebuggerController::PatchTrace() under case TRACE_MANAGED. This alleviates the StubManager from having to prevent the // race that occurs here. trace->InitForStub(GetFunction()->GetMethodEntryPoint()); } else { trace->InitForStub(GetPreStubEntryPoint()); } LOG((LF_CORDB, LL_INFO10000, ""PrestubMethodFrame::TraceFrame: ip="" FMT_ADDR ""\\n"", DBG_ADDR(trace->GetAddress()) )); return TRUE; } #ifndef DACCESS_COMPILE //----------------------------------------------------------------------- // A rather specialized routine for the exclusive use of StubDispatch. //----------------------------------------------------------------------- StubDispatchFrame::StubDispatchFrame(TransitionBlock * pTransitionBlock) : FramedMethodFrame(pTransitionBlock, NULL) { LIMITED_METHOD_CONTRACT; m_pRepresentativeMT = NULL; m_representativeSlot = 0; m_pZapModule = NULL; m_pIndirection = NULL; m_pGCRefMap = NULL; } #endif // #ifndef DACCESS_COMPILE MethodDesc* StubDispatchFrame::GetFunction() { CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END; MethodDesc * pMD = m_pMD; if (m_pMD == NULL) { if (m_pRepresentativeMT != NULL) { pMD = m_pRepresentativeMT->GetMethodDescForSlot(m_representativeSlot); #ifndef DACCESS_COMPILE m_pMD = pMD; #endif } } return pMD; } static PTR_BYTE FindGCRefMap(PTR_Module pZapModule, TADDR ptr) { LIMITED_METHOD_DAC_CONTRACT; PEImageLayout *pNativeImage = pZapModule->GetReadyToRunImage(); RVA rva = pNativeImage->GetDataRva(ptr); PTR_READYTORUN_IMPORT_SECTION pImportSection = pZapModule->GetImportSectionForRVA(rva); if (pImportSection == NULL) return NULL; COUNT_T index = (rva - pImportSection->Section.VirtualAddress) / pImportSection->EntrySize; PTR_BYTE pGCRefMap = dac_cast(pNativeImage->GetRvaData(pImportSection->AuxiliaryData)); _ASSERTE(pGCRefMap != NULL); // GCRefMap starts with lookup index to limit size of linear scan that follows. PTR_BYTE p = pGCRefMap + dac_cast(pGCRefMap)[index / GCREFMAP_LOOKUP_STRIDE]; COUNT_T remaining = index % GCREFMAP_LOOKUP_STRIDE; while (remaining > 0) { while ((*p & 0x80) != 0) p++; p++; remaining--; } return p; } PTR_BYTE StubDispatchFrame::GetGCRefMap() { CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END; PTR_BYTE pGCRefMap = m_pGCRefMap; if (pGCRefMap == NULL) { if (m_pIndirection != NULL) { if (m_pZapModule == NULL) { m_pZapModule = ExecutionManager::FindModuleForGCRefMap(m_pIndirection); } if (m_pZapModule != NULL) { pGCRefMap = FindGCRefMap(m_pZapModule, m_pIndirection); } #ifndef DACCESS_COMPILE if (pGCRefMap != NULL) { m_pGCRefMap = pGCRefMap; } else { // Clear the indirection to avoid retrying m_pIndirection = NULL; } #endif } } return pGCRefMap; } void StubDispatchFrame::GcScanRoots(promote_func *fn, ScanContext* sc) { CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END FramedMethodFrame::GcScanRoots(fn, sc); PTR_BYTE pGCRefMap = GetGCRefMap(); if (pGCRefMap != NULL) { PromoteCallerStackUsingGCRefMap(fn, sc, pGCRefMap); } else { PromoteCallerStack(fn, sc); } } BOOL StubDispatchFrame::TraceFrame(Thread *thread, BOOL fromPatch, TraceDestination *trace, REGDISPLAY *regs) { WRAPPER_NO_CONTRACT; // StubDispatchFixupWorker and VSD_ResolveWorker never directly call managed code. Returning false instructs the debugger to // step out of the call that erected this frame and continuing trying to trace execution from there. LOG((LF_CORDB, LL_INFO1000, ""StubDispatchFrame::TraceFrame: return FALSE\\n"")); return FALSE; } Frame::Interception StubDispatchFrame::GetInterception() { LIMITED_METHOD_CONTRACT; return INTERCEPTION_NONE; } #ifndef DACCESS_COMPILE CallCountingHelperFrame::CallCountingHelperFrame(TransitionBlock *pTransitionBlock, MethodDesc *pMD) : FramedMethodFrame(pTransitionBlock, pMD) { WRAPPER_NO_CONTRACT; } #endif void CallCountingHelperFrame::GcScanRoots(promote_func *fn, ScanContext *sc) { WRAPPER_NO_CONTRACT; FramedMethodFrame::GcScanRoots(fn, sc); PromoteCallerStack(fn, sc); } BOOL CallCountingHelperFrame::TraceFrame(Thread *thread, BOOL fromPatch, TraceDestination *trace, REGDISPLAY *regs) { WRAPPER_NO_CONTRACT; // OnCallCountThresholdReached never directly calls managed code. Returning false instructs the debugger to step out of the // call that erected this frame and continuing trying to trace execution from there. LOG((LF_CORDB, LL_INFO1000, ""CallCountingHelperFrame::TraceFrame: return FALSE\\n"")); return FALSE; } #ifndef DACCESS_COMPILE ExternalMethodFrame::ExternalMethodFrame(TransitionBlock * pTransitionBlock) : FramedMethodFrame(pTransitionBlock, NULL) { LIMITED_METHOD_CONTRACT; m_pIndirection = NULL; m_pZapModule = NULL; m_pGCRefMap = NULL; } #endif // !DACCESS_COMPILE void ExternalMethodFrame::GcScanRoots(promote_func *fn, ScanContext* sc) { CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END FramedMethodFrame::GcScanRoots(fn, sc); PromoteCallerStackUsingGCRefMap(fn, sc, GetGCRefMap()); } PTR_BYTE ExternalMethodFrame::GetGCRefMap() { LIMITED_METHOD_DAC_CONTRACT; PTR_BYTE pGCRefMap = m_pGCRefMap; if (pGCRefMap == NULL) { if (m_pIndirection != NULL) { pGCRefMap = FindGCRefMap(m_pZapModule, m_pIndirection); #ifndef DACCESS_COMPILE m_pGCRefMap = pGCRefMap; #endif } } _ASSERTE(pGCRefMap != NULL); return pGCRefMap; } Frame::Interception ExternalMethodFrame::GetInterception() { LIMITED_METHOD_CONTRACT; return INTERCEPTION_NONE; } Frame::Interception PrestubMethodFrame::GetInterception() { LIMITED_METHOD_DAC_CONTRACT; // // The only direct kind of interception done by the prestub // is class initialization. // return INTERCEPTION_PRESTUB; } #ifdef FEATURE_READYTORUN #ifndef DACCESS_COMPILE DynamicHelperFrame::DynamicHelperFrame(TransitionBlock * pTransitionBlock, int dynamicHelperFrameFlags) : FramedMethodFrame(pTransitionBlock, NULL) { LIMITED_METHOD_CONTRACT; m_dynamicHelperFrameFlags = dynamicHelperFrameFlags; } #endif // !DACCESS_COMPILE void DynamicHelperFrame::GcScanRoots(promote_func *fn, ScanContext* sc) { CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END FramedMethodFrame::GcScanRoots(fn, sc); PTR_PTR_Object pArgumentRegisters = dac_cast(GetTransitionBlock() + TransitionBlock::GetOffsetOfArgumentRegisters()); if (m_dynamicHelperFrameFlags & DynamicHelperFrameFlags_ObjectArg) { TADDR pArgument = GetTransitionBlock() + TransitionBlock::GetOffsetOfArgumentRegisters(); #ifdef TARGET_X86 // x86 is special as always pArgument += offsetof(ArgumentRegisters, ECX); #endif (*fn)(dac_cast(pArgument), sc, CHECK_APP_DOMAIN); } if (m_dynamicHelperFrameFlags & DynamicHelperFrameFlags_ObjectArg2) { TADDR pArgument = GetTransitionBlock() + TransitionBlock::GetOffsetOfArgumentRegisters(); #ifdef TARGET_X86 // x86 is special as always pArgument += offsetof(ArgumentRegisters, EDX); #else pArgument += sizeof(TADDR); #endif (*fn)(dac_cast(pArgument), sc, CHECK_APP_DOMAIN); } } #endif // FEATURE_READYTORUN #ifndef DACCESS_COMPILE #ifdef FEATURE_COMINTEROP //----------------------------------------------------------------------- // A rather specialized routine for the exclusive use of the COM PreStub. //----------------------------------------------------------------------- VOID ComPrestubMethodFrame::Init() { WRAPPER_NO_CONTRACT; // Initializes the frame's VPTR. This assumes C++ puts the vptr // at offset 0 for a class not using MI, but this is no different // than the assumption that COM Classic makes. *((TADDR*)this) = GetMethodFrameVPtr(); *GetGSCookiePtr() = GetProcessGSCookie(); } #endif // FEATURE_COMINTEROP //----------------------------------------------------------------------- // GCFrames //----------------------------------------------------------------------- //-------------------------------------------------------------------- // This constructor pushes a new GCFrame on the frame chain. //-------------------------------------------------------------------- GCFrame::GCFrame(Thread *pThread, OBJECTREF *pObjRefs, UINT numObjRefs, BOOL maybeInterior) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; PRECONDITION(pThread != NULL); } CONTRACTL_END; #ifdef USE_CHECKED_OBJECTREFS if (!maybeInterior) { UINT i; for(i = 0; i < numObjRefs; i++) Thread::ObjectRefProtected(&pObjRefs[i]); for (i = 0; i < numObjRefs; i++) { pObjRefs[i].Validate(); } } #if 0 // We'll want to restore this goodness check at some time. For now, the fact that we use // this as temporary backstops in our loader exception conversions means we're highly // exposed to infinite stack recursion should the loader be invoked during a stackwalk. // So we'll do without. if (g_pConfig->GetGCStressLevel() != 0 && IsProtectedByGCFrame(pObjRefs)) { _ASSERTE(!""This objectref is already protected by a GCFrame. Protecting it twice will corrupt the GC.""); } #endif #endif // USE_CHECKED_OBJECTREFS #ifdef _DEBUG m_Next = NULL; m_pCurThread = NULL; #endif // _DEBUG m_pObjRefs = pObjRefs; m_numObjRefs = numObjRefs; m_MaybeInterior = maybeInterior; Push(pThread); } GCFrame::~GCFrame() { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; PRECONDITION(m_pCurThread != NULL); } CONTRACTL_END; // Do a manual switch to the GC cooperative mode instead of using the GCX_COOP_THREAD_EXISTS // macro so that this function isn't slowed down by having to deal with FS:0 chain on x86 Windows. BOOL wasCoop = m_pCurThread->PreemptiveGCDisabled(); if (!wasCoop) { m_pCurThread->DisablePreemptiveGC(); } Pop(); if (!wasCoop) { m_pCurThread->EnablePreemptiveGC(); } } void GCFrame::Push(Thread* pThread) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; PRECONDITION(pThread != NULL); PRECONDITION(m_Next == NULL); PRECONDITION(m_pCurThread == NULL); } CONTRACTL_END; // Push the GC frame to the per-thread list m_Next = pThread->GetGCFrame(); m_pCurThread = pThread; // GetOsPageSize() is used to relax the assert for cases where two Frames are // declared in the same source function. We cannot predict the order // in which the compiler will lay them out in the stack frame. // So GetOsPageSize() is a guess of the maximum stack frame size of any method // with multiple GCFrames in coreclr.dll _ASSERTE(((m_Next == NULL) || (PBYTE(m_Next) + (2 * GetOsPageSize())) > PBYTE(this)) && ""Pushing a GCFrame out of order ?""); pThread->SetGCFrame(this); } void GCFrame::Pop() { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; PRECONDITION(m_pCurThread != NULL); } CONTRACTL_END; // When the frame is destroyed, make sure it is no longer in the // frame chain managed by the Thread. // It also cancels the GC protection provided by the frame. _ASSERTE(m_pCurThread->GetGCFrame() == this && ""Popping a GCFrame out of order ?""); m_pCurThread->SetGCFrame(m_Next); m_Next = NULL; #ifdef _DEBUG m_pCurThread->EnableStressHeap(); for(UINT i = 0; i < m_numObjRefs; i++) Thread::ObjectRefNew(&m_pObjRefs[i]); // Unprotect them #endif } #endif // !DACCESS_COMPILE // // GCFrame Object Scanning // // This handles scanning/promotion of GC objects that were // protected by the programmer explicitly protecting it in a GC Frame // via the GCPROTECTBEGIN / GCPROTECTEND facility... // void GCFrame::GcScanRoots(promote_func *fn, ScanContext* sc) { WRAPPER_NO_CONTRACT; PTR_PTR_Object pRefs = dac_cast(m_pObjRefs); for (UINT i = 0; i < m_numObjRefs; i++) { auto fromAddress = OBJECTREF_TO_UNCHECKED_OBJECTREF(m_pObjRefs[i]); if (m_MaybeInterior) { PromoteCarefully(fn, pRefs + i, sc, GC_CALL_INTERIOR | CHECK_APP_DOMAIN); } else { (*fn)(pRefs + i, sc, 0); } auto toAddress = OBJECTREF_TO_UNCHECKED_OBJECTREF(m_pObjRefs[i]); LOG((LF_GC, INFO3, ""GC Protection Frame promoted"" FMT_ADDR ""to"" FMT_ADDR ""\\n"", DBG_ADDR(fromAddress), DBG_ADDR(toAddress))); } } #ifndef DACCESS_COMPILE #ifdef FEATURE_INTERPRETER // Methods of IntepreterFrame. InterpreterFrame::InterpreterFrame(Interpreter* interp) : Frame(), m_interp(interp) { Push(); } MethodDesc* InterpreterFrame::GetFunction() { return m_interp->GetMethodDesc(); } void InterpreterFrame::GcScanRoots(promote_func *fn, ScanContext* sc) { return m_interp->GCScanRoots(fn, sc); } #endif // FEATURE_INTERPRETER #if defined(_DEBUG) && !defined (DACCESS_COMPILE) struct IsProtectedByGCFrameStruct { OBJECTREF *ppObjectRef; UINT count; }; static StackWalkAction IsProtectedByGCFrameStackWalkFramesCallback( CrawlFrame *pCF, VOID *pData ) { DEBUG_ONLY_FUNCTION; WRAPPER_NO_CONTRACT; IsProtectedByGCFrameStruct *pd = (IsProtectedByGCFrameStruct*)pData; Frame *pFrame = pCF->GetFrame(); if (pFrame) { if (pFrame->Protects(pd->ppObjectRef)) { pd->count++; } } return SWA_CONTINUE; } BOOL IsProtectedByGCFrame(OBJECTREF *ppObjectRef) { DEBUG_ONLY_FUNCTION; WRAPPER_NO_CONTRACT; // Just report TRUE if GCStress is not on. This satisfies the asserts that use this // code without the cost of actually determining it. if (!GCStress::IsEnabled()) return TRUE; if (ppObjectRef == NULL) { return TRUE; } CONTRACT_VIOLATION(ThrowsViolation); ENABLE_FORBID_GC_LOADER_USE_IN_THIS_SCOPE (); IsProtectedByGCFrameStruct d = {ppObjectRef, 0}; GetThread()->StackWalkFrames(IsProtectedByGCFrameStackWalkFramesCallback, &d); GCFrame* pGCFrame = GetThread()->GetGCFrame(); while (pGCFrame != NULL) { if (pGCFrame->Protects(ppObjectRef)) { d.count++; } pGCFrame = pGCFrame->PtrNextFrame(); } if (d.count > 1) { _ASSERTE(!""Multiple GCFrames protecting the same pointer. This will cause GC corruption!""); } return d.count != 0; } #endif // _DEBUG #endif //!DACCESS_COMPILE #ifdef FEATURE_HIJACK void HijackFrame::GcScanRoots(promote_func *fn, ScanContext* sc) { LIMITED_METHOD_CONTRACT; ReturnKind returnKind = m_Thread->GetHijackReturnKind(); _ASSERTE(IsValidReturnKind(returnKind)); int regNo = 0; bool moreRegisters = false; do { ReturnKind r = ExtractRegReturnKind(returnKind, regNo, moreRegisters); PTR_PTR_Object objPtr = dac_cast(&m_Args->ReturnValue[regNo]); switch (r) { #ifdef TARGET_X86 case RT_Float: // Fall through #endif case RT_Scalar: // nothing to report break; case RT_Object: LOG((LF_GC, INFO3, ""Hijack Frame Promoting Object"" FMT_ADDR ""to"", DBG_ADDR(OBJECTREF_TO_UNCHECKED_OBJECTREF(*objPtr)))); (*fn)(objPtr, sc, CHECK_APP_DOMAIN); LOG((LF_GC, INFO3, FMT_ADDR ""\\n"", DBG_ADDR(OBJECTREF_TO_UNCHECKED_OBJECTREF(*objPtr)))); break; case RT_ByRef: LOG((LF_GC, INFO3, ""Hijack Frame Carefully Promoting pointer"" FMT_ADDR ""to"", DBG_ADDR(OBJECTREF_TO_UNCHECKED_OBJECTREF(*objPtr)))); PromoteCarefully(fn, objPtr, sc, GC_CALL_INTERIOR); LOG((LF_GC, INFO3, FMT_ADDR ""\\n"", DBG_ADDR(OBJECTREF_TO_UNCHECKED_OBJECTREF(*objPtr)))); break; default: _ASSERTE(!""Impossible two bit encoding""); } regNo++; } while (moreRegisters); } #endif // FEATURE_HIJACK void ProtectByRefsFrame::GcScanRoots(promote_func *fn, ScanContext *sc) { CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END ByRefInfo *pByRefInfos = m_brInfo; while (pByRefInfos) { if (!CorIsPrimitiveType(pByRefInfos->typ)) { TADDR pData = PTR_HOST_MEMBER_TADDR(ByRefInfo, pByRefInfos, data); if (pByRefInfos->typeHandle.IsValueType()) { ReportPointersFromValueType(fn, sc, pByRefInfos->typeHandle.GetMethodTable(), PTR_VOID(pData)); } else { PTR_PTR_Object ppObject = PTR_PTR_Object(pData); LOG((LF_GC, INFO3, ""ProtectByRefs Frame Promoting"" FMT_ADDR ""to "", DBG_ADDR(*ppObject))); (*fn)(ppObject, sc, CHECK_APP_DOMAIN); LOG((LF_GC, INFO3, FMT_ADDR ""\\n"", DBG_ADDR(*ppObject) )); } } pByRefInfos = pByRefInfos->pNext; } } void ProtectValueClassFrame::GcScanRoots(promote_func *fn, ScanContext *sc) { CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END ValueClassInfo *pVCInfo = m_pVCInfo; while (pVCInfo != NULL) { _ASSERTE(pVCInfo->pMT->IsValueType()); ReportPointersFromValueType(fn, sc, pVCInfo->pMT, pVCInfo->pData); pVCInfo = pVCInfo->pNext; } } // // Promote Caller Stack // // void TransitionFrame::PromoteCallerStack(promote_func* fn, ScanContext* sc) { WRAPPER_NO_CONTRACT; // I believe this is the contract: //CONTRACTL //{ // INSTANCE_CHECK; // NOTHROW; // GC_NOTRIGGER; // FORBID_FAULT; // MODE_ANY; //} //CONTRACTL_END MethodDesc *pFunction; LOG((LF_GC, INFO3, "" Promoting method caller Arguments\\n"" )); // We're going to have to look at the signature to determine // which arguments a are pointers....First we need the function pFunction = GetFunction(); if (pFunction == NULL) return; // Now get the signature... Signature callSignature = pFunction->GetSignature(); if (callSignature.IsEmpty()) { return; } //If not ""vararg"" calling convention, assume ""default"" calling convention if (!MetaSig::IsVarArg(callSignature)) { SigTypeContext typeContext(pFunction); PCCOR_SIGNATURE pSig; DWORD cbSigSize; pFunction->GetSig(&pSig, &cbSigSize); MetaSig msig(pSig, cbSigSize, pFunction->GetModule(), &typeContext); bool fCtorOfVariableSizedObject = msig.HasThis() && (pFunction->GetMethodTable() == g_pStringClass) && pFunction->IsCtor(); if (fCtorOfVariableSizedObject) msig.ClearHasThis(); if (pFunction->RequiresInstArg() && !SuppressParamTypeArg()) msig.SetHasParamTypeArg(); PromoteCallerStackHelper (fn, sc, pFunction, &msig); } else { VASigCookie *varArgSig = GetVASigCookie(); //Note: no instantiations needed for varargs MetaSig msig(varArgSig->signature, varArgSig->pModule, NULL); PromoteCallerStackHelper (fn, sc, pFunction, &msig); } } void TransitionFrame::PromoteCallerStackHelper(promote_func* fn, ScanContext* sc, MethodDesc *pFunction, MetaSig *pmsig) { WRAPPER_NO_CONTRACT; // I believe this is the contract: //CONTRACTL //{ // INSTANCE_CHECK; // NOTHROW; // GC_NOTRIGGER; // FORBID_FAULT; // MODE_ANY; //} //CONTRACTL_END ArgIterator argit(pmsig); TADDR pTransitionBlock = GetTransitionBlock(); // promote 'this' for non-static methods if (argit.HasThis() && pFunction != NULL) { BOOL interior = pFunction->GetMethodTable()->IsValueType() && !pFunction->IsUnboxingStub(); PTR_PTR_VOID pThis = dac_cast(pTransitionBlock + argit.GetThisOffset()); LOG((LF_GC, INFO3, "" 'this' Argument at "" FMT_ADDR ""promoted from"" FMT_ADDR ""\\n"", DBG_ADDR(pThis), DBG_ADDR(*pThis) )); if (interior) PromoteCarefully(fn, PTR_PTR_Object(pThis), sc, GC_CALL_INTERIOR|CHECK_APP_DOMAIN); else (fn)(PTR_PTR_Object(pThis), sc, CHECK_APP_DOMAIN); } if (argit.HasRetBuffArg()) { PTR_PTR_VOID pRetBuffArg = dac_cast(pTransitionBlock + argit.GetRetBuffArgOffset()); LOG((LF_GC, INFO3, "" ret buf Argument promoted from"" FMT_ADDR ""\\n"", DBG_ADDR(*pRetBuffArg) )); PromoteCarefully(fn, PTR_PTR_Object(pRetBuffArg), sc, GC_CALL_INTERIOR|CHECK_APP_DOMAIN); } int argOffset; while ((argOffset = argit.GetNextOffset()) != TransitionBlock::InvalidOffset) { ArgDestination argDest(dac_cast(pTransitionBlock), argOffset, argit.GetArgLocDescForStructInRegs()); pmsig->GcScanRoots(&argDest, fn, sc); } } #ifdef TARGET_X86 UINT TransitionFrame::CbStackPopUsingGCRefMap(PTR_BYTE pGCRefMap) { LIMITED_METHOD_CONTRACT; GCRefMapDecoder decoder(pGCRefMap); return decoder.ReadStackPop() * sizeof(TADDR); } #endif void TransitionFrame::PromoteCallerStackUsingGCRefMap(promote_func* fn, ScanContext* sc, PTR_BYTE pGCRefMap) { WRAPPER_NO_CONTRACT; GCRefMapDecoder decoder(pGCRefMap); #ifdef TARGET_X86 // Skip StackPop decoder.ReadStackPop(); #endif TADDR pTransitionBlock = GetTransitionBlock(); while (!decoder.AtEnd()) { int pos = decoder.CurrentPos(); int token = decoder.ReadToken(); int ofs; #ifdef TARGET_X86 ofs = (pos < NUM_ARGUMENT_REGISTERS) ? (TransitionBlock::GetOffsetOfArgumentRegisters() + ARGUMENTREGISTERS_SIZE - (pos + 1) * sizeof(TADDR)) : (TransitionBlock::GetOffsetOfArgs() + (pos - NUM_ARGUMENT_REGISTERS) * sizeof(TADDR)); #else ofs = TransitionBlock::GetOffsetOfFirstGCRefMapSlot() + pos * sizeof(TADDR); #endif PTR_TADDR ppObj = dac_cast(pTransitionBlock + ofs); switch (token) { case GCREFMAP_SKIP: break; case GCREFMAP_REF: fn(dac_cast(ppObj), sc, CHECK_APP_DOMAIN); break; case GCREFMAP_INTERIOR: PromoteCarefully(fn, dac_cast(ppObj), sc, GC_CALL_INTERIOR); break; case GCREFMAP_METHOD_PARAM: if (sc->promotion) { #ifndef DACCESS_COMPILE MethodDesc *pMDReal = dac_cast(*ppObj); if (pMDReal != NULL) GcReportLoaderAllocator(fn, sc, pMDReal->GetLoaderAllocator()); #endif } break; case GCREFMAP_TYPE_PARAM: if (sc->promotion) { #ifndef DACCESS_COMPILE MethodTable *pMTReal = dac_cast(*ppObj); if (pMTReal != NULL) GcReportLoaderAllocator(fn, sc, pMTReal->GetLoaderAllocator()); #endif } break; case GCREFMAP_VASIG_COOKIE: { VASigCookie *varArgSig = dac_cast(*ppObj); //Note: no instantiations needed for varargs MetaSig msig(varArgSig->signature, varArgSig->pModule, NULL); PromoteCallerStackHelper (fn, sc, NULL, &msig); } break; default: _ASSERTE(!""Unknown GCREFMAP token""); break; } } } void PInvokeCalliFrame::PromoteCallerStack(promote_func* fn, ScanContext* sc) { WRAPPER_NO_CONTRACT; LOG((LF_GC, INFO3, "" Promoting CALLI caller Arguments\\n"" )); // get the signature VASigCookie *varArgSig = GetVASigCookie(); if (varArgSig->signature.IsEmpty()) { return; } // no instantiations needed for varargs MetaSig msig(varArgSig->signature, varArgSig->pModule, NULL); PromoteCallerStackHelper(fn, sc, NULL, &msig); } #ifndef DACCESS_COMPILE PInvokeCalliFrame::PInvokeCalliFrame(TransitionBlock * pTransitionBlock, VASigCookie * pVASigCookie, PCODE pUnmanagedTarget) : FramedMethodFrame(pTransitionBlock, NULL) { LIMITED_METHOD_CONTRACT; m_pVASigCookie = pVASigCookie; m_pUnmanagedTarget = pUnmanagedTarget; } #endif // #ifndef DACCESS_COMPILE #ifdef FEATURE_COMINTEROP #ifndef DACCESS_COMPILE ComPlusMethodFrame::ComPlusMethodFrame(TransitionBlock * pTransitionBlock, MethodDesc * pMD) : FramedMethodFrame(pTransitionBlock, pMD) { LIMITED_METHOD_CONTRACT; } #endif // #ifndef DACCESS_COMPILE //virtual void ComPlusMethodFrame::GcScanRoots(promote_func* fn, ScanContext* sc) { WRAPPER_NO_CONTRACT; // ComPlusMethodFrame is only used in the event call / late bound call code path where we do not have IL stub // so we need to promote the arguments and return value manually. FramedMethodFrame::GcScanRoots(fn, sc); PromoteCallerStack(fn, sc); // Promote the returned object MethodDesc* methodDesc = GetFunction(); ReturnKind returnKind = methodDesc->GetReturnKind(); if (returnKind == RT_Object) { (*fn)(GetReturnObjectPtr(), sc, CHECK_APP_DOMAIN); } else if (returnKind == RT_ByRef) { PromoteCarefully(fn, GetReturnObjectPtr(), sc, GC_CALL_INTERIOR | CHECK_APP_DOMAIN); } else { _ASSERTE_MSG(!IsStructReturnKind(returnKind), ""NYI: We can't promote multiregs struct returns""); _ASSERTE_MSG(IsScalarReturnKind(returnKind), ""Non-scalar types must be promoted.""); } } #endif // FEATURE_COMINTEROP #if defined (_DEBUG) && !defined (DACCESS_COMPILE) // For IsProtectedByGCFrame, we need to know whether a given object ref is protected // by a ComPlusMethodFrame or a ComMethodFrame. Since GCScanRoots for those frames are // quite complicated, we don't want to duplicate their logic so we call GCScanRoots with // IsObjRefProtected (a fake promote function) and an extended ScanContext to do the checking. struct IsObjRefProtectedScanContext : public ScanContext { OBJECTREF * oref_to_check; BOOL oref_protected; IsObjRefProtectedScanContext (OBJECTREF * oref) { thread_under_crawl = GetThread(); promotion = TRUE; oref_to_check = oref; oref_protected = FALSE; } }; void IsObjRefProtected (Object** ppObj, ScanContext* sc, uint32_t) { LIMITED_METHOD_CONTRACT; IsObjRefProtectedScanContext * orefProtectedSc = (IsObjRefProtectedScanContext *)sc; if (ppObj == (Object **)(orefProtectedSc->oref_to_check)) orefProtectedSc->oref_protected = TRUE; } BOOL TransitionFrame::Protects(OBJECTREF * ppORef) { WRAPPER_NO_CONTRACT; IsObjRefProtectedScanContext sc (ppORef); // Set the stack limit for the scan to the SP of the managed frame above the transition frame sc.stack_limit = GetSP(); GcScanRoots (IsObjRefProtected, &sc); return sc.oref_protected; } #endif //defined (_DEBUG) && !defined (DACCESS_COMPILE) //+---------------------------------------------------------------------------- // // Method: TPMethodFrame::GcScanRoots public // // Synopsis: GC protects arguments on the stack // // //+---------------------------------------------------------------------------- #ifdef FEATURE_COMINTEROP #ifdef TARGET_X86 // Return the # of stack bytes pushed by the unmanaged caller. UINT ComMethodFrame::GetNumCallerStackBytes() { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; ComCallMethodDesc* pCMD = PTR_ComCallMethodDesc((TADDR)GetDatum()); PREFIX_ASSUME(pCMD != NULL); // assumes __stdcall // compute the callee pop stack bytes return pCMD->GetNumStackBytes(); } #endif // TARGET_X86 #ifndef DACCESS_COMPILE void ComMethodFrame::DoSecondPassHandlerCleanup(Frame * pCurFrame) { LIMITED_METHOD_CONTRACT; // Find ComMethodFrame while ((pCurFrame != FRAME_TOP) && (pCurFrame->GetVTablePtr() != ComMethodFrame::GetMethodFrameVPtr())) { pCurFrame = pCurFrame->PtrNextFrame(); } if (pCurFrame == FRAME_TOP) return; ComMethodFrame * pComMethodFrame = (ComMethodFrame *)pCurFrame; _ASSERTE(pComMethodFrame != NULL); Thread * pThread = GetThread(); GCX_COOP_THREAD_EXISTS(pThread); // Unwind the frames till the entry frame (which was ComMethodFrame) pCurFrame = pThread->GetFrame(); while ((pCurFrame != NULL) && (pCurFrame <= pComMethodFrame)) { pCurFrame->ExceptionUnwind(); pCurFrame = pCurFrame->PtrNextFrame(); } // At this point, pCurFrame would be the ComMethodFrame's predecessor frame // that we need to reset to. _ASSERTE((pCurFrame != NULL) && (pComMethodFrame->PtrNextFrame() == pCurFrame)); pThread->SetFrame(pCurFrame); } #endif // !DACCESS_COMPILE #endif // FEATURE_COMINTEROP #ifndef DACCESS_COMPILE #if defined(_MSC_VER) && defined(TARGET_X86) #pragma optimize(""y"", on) // Small critical routines, don't put in EBP frame #endif // Initialization of HelperMethodFrame. void HelperMethodFrame::Push() { CONTRACTL { if (m_Attribs & FRAME_ATTR_NO_THREAD_ABORT) NOTHROW; else THROWS; GC_TRIGGERS; MODE_COOPERATIVE; } CONTRACTL_END; // // Finish initialization // // Compiler would not inline GetGSCookiePtr() because of it is virtual method. // Inline it manually and verify that it gives same result. _ASSERTE(GetGSCookiePtr() == (((GSCookie *)(this)) - 1)); *(((GSCookie *)(this)) - 1) = GetProcessGSCookie(); _ASSERTE(!m_MachState.isValid()); Thread * pThread = ::GetThread(); m_pThread = pThread; // Push the frame Frame::Push(pThread); if (!pThread->HasThreadStateOpportunistic(Thread::TS_AbortRequested)) return; // Outline the slow path for better perf PushSlowHelper(); } void HelperMethodFrame::Pop() { CONTRACTL { if (m_Attribs & FRAME_ATTR_NO_THREAD_ABORT) NOTHROW; else THROWS; GC_TRIGGERS; MODE_COOPERATIVE; } CONTRACTL_END; Thread * pThread = m_pThread; if ((m_Attribs & FRAME_ATTR_NO_THREAD_ABORT) || !pThread->HasThreadStateOpportunistic(Thread::TS_AbortInitiated)) { Frame::Pop(pThread); return; } // Outline the slow path for better perf PopSlowHelper(); } #if defined(_MSC_VER) && defined(TARGET_X86) #pragma optimize("""", on) // Go back to command line default optimizations #endif NOINLINE void HelperMethodFrame::PushSlowHelper() { CONTRACTL { if (m_Attribs & FRAME_ATTR_NO_THREAD_ABORT) NOTHROW; else THROWS; GC_TRIGGERS; MODE_COOPERATIVE; } CONTRACTL_END; if (!(m_Attribs & FRAME_ATTR_NO_THREAD_ABORT)) { if (m_pThread->IsAbortRequested()) { m_pThread->HandleThreadAbort(); } } } NOINLINE void HelperMethodFrame::PopSlowHelper() { CONTRACTL { THROWS; GC_TRIGGERS; MODE_COOPERATIVE; } CONTRACTL_END; m_pThread->HandleThreadAbort(); Frame::Pop(m_pThread); } #endif // #ifndef DACCESS_COMPILE MethodDesc* HelperMethodFrame::GetFunction() { WRAPPER_NO_CONTRACT; #ifndef DACCESS_COMPILE InsureInit(false, NULL); return m_pMD; #else if (m_MachState.isValid()) { return m_pMD; } else { return ECall::MapTargetBackToMethod(m_FCallEntry); } #endif } //--------------------------------------------------------------------------------------- // // Ensures the HelperMethodFrame gets initialized, if not already. // // Arguments: // * initialInit - // * true: ensure the simple, first stage of initialization has been completed. // This is used when the HelperMethodFrame is first created. // * false: complete any initialization that was left to do, if any. // * unwindState - [out] DAC builds use this to return the unwound machine state. // * hostCallPreference - (See code:HelperMethodFrame::HostCallPreference.) // // Return Value: // Normally, the function always returns TRUE meaning the initialization succeeded. // // However, if hostCallPreference is NoHostCalls, AND if a callee (like // LazyMachState::unwindLazyState) needed to acquire a JIT reader lock and was unable // to do so (lest it re-enter the host), then InsureInit will abort and return FALSE. // So any callers that specify hostCallPreference = NoHostCalls (which is not the // default), should check for FALSE return, and refuse to use the HMF in that case. // Currently only asynchronous calls made by profilers use that code path. // BOOL HelperMethodFrame::InsureInit(bool initialInit, MachState * unwindState, HostCallPreference hostCallPreference /* = AllowHostCalls */) { CONTRACTL { NOTHROW; GC_NOTRIGGER; if ((hostCallPreference == AllowHostCalls) && !m_MachState.isValid()) { HOST_CALLS; } else { HOST_NOCALLS; } SUPPORTS_DAC; } CONTRACTL_END; if (m_MachState.isValid()) { return TRUE; } _ASSERTE(m_Attribs != 0xCCCCCCCC); #ifndef DACCESS_COMPILE if (!initialInit) { m_pMD = ECall::MapTargetBackToMethod(m_FCallEntry); // if this is an FCall, we should find it _ASSERTE(m_FCallEntry == 0 || m_pMD != 0); } #endif // Because TRUE FCalls can be called from via reflection, com-interop, etc., // we can't rely on the fact that we are called from jitted code to find the // caller of the FCALL. Thus FCalls must erect the frame directly in the // FCall. For JIT helpers, however, we can rely on this, and so they can // be sneakier and defer the HelperMethodFrame setup to a called worker method. // Work with a copy so that we only write the values once. // this avoids race conditions. LazyMachState* lazy = &m_MachState; DWORD threadId = m_pThread->GetOSThreadId(); MachState unwound; if (!initialInit && m_FCallEntry == 0 && !(m_Attribs & Frame::FRAME_ATTR_EXACT_DEPTH)) // Jit Helper { LazyMachState::unwindLazyState( lazy, &unwound, threadId, 0, hostCallPreference); #if !defined(DACCESS_COMPILE) if (!unwound.isValid()) { // This only happens if LazyMachState::unwindLazyState had to abort as a // result of failing to take a reader lock (because we told it not to yield, // but the writer lock was already held). Since we've not yet updated // m_MachState, this HelperMethodFrame will still be considered not fully // initialized (so a future call into InsureInit() will attempt to complete // initialization again). // // Note that, in DAC builds, the contract with LazyMachState::unwindLazyState // is a bit different, and it's expected that LazyMachState::unwindLazyState // will commonly return an unwound state with _pRetAddr==NULL (which counts // as an ""invalid"" MachState). So have DAC builds deliberately fall through // rather than aborting when unwound is invalid. _ASSERTE(hostCallPreference == NoHostCalls); return FALSE; } #endif // !defined(DACCESS_COMPILE) } else if (!initialInit && (m_Attribs & Frame::FRAME_ATTR_CAPTURE_DEPTH_2) != 0) { // explictly told depth LazyMachState::unwindLazyState(lazy, &unwound, threadId, 2); } else { // True FCall LazyMachState::unwindLazyState(lazy, &unwound, threadId, 1); } _ASSERTE(unwound.isValid()); #if !defined(DACCESS_COMPILE) lazy->setLazyStateFromUnwind(&unwound); #else // DACCESS_COMPILE if (unwindState) { *unwindState = unwound; } #endif // DACCESS_COMPILE return TRUE; } #include ""comdelegate.h"" BOOL MulticastFrame::TraceFrame(Thread *thread, BOOL fromPatch, TraceDestination *trace, REGDISPLAY *regs) { CONTRACTL { THROWS; GC_NOTRIGGER; MODE_COOPERATIVE; } CONTRACTL_END; _ASSERTE(!fromPatch); #ifdef DACCESS_COMPILE return FALSE; #else // !DACCESS_COMPILE LOG((LF_CORDB,LL_INFO10000, ""MulticastFrame::TF FromPatch:0x%x, at 0x%x\\n"", fromPatch, GetControlPC(regs))); // At this point we have no way to recover the Stub object from the control pc. We can't use the MD stored // in the MulticastFrame because it points to the dummy Invoke() method, not the method we want to call. BYTE *pbDel = NULL; int delegateCount = 0; #if defined(TARGET_X86) // At this point the counter hasn't been incremented yet. delegateCount = *regs->GetEdiLocation() + 1; pbDel = *(BYTE **)( (size_t)*regs->GetEsiLocation() + GetOffsetOfTransitionBlock() + ArgIterator::GetThisOffset()); #elif defined(TARGET_AMD64) // At this point the counter hasn't been incremented yet. delegateCount = (int)regs->pCurrentContext->Rdi + 1; pbDel = *(BYTE **)( (size_t)(regs->pCurrentContext->Rsi) + GetOffsetOfTransitionBlock() + ArgIterator::GetThisOffset()); #elif defined(TARGET_ARM) // At this point the counter has not yet been incremented. Counter is in R7, frame pointer in R4. delegateCount = regs->pCurrentContext->R7 + 1; pbDel = *(BYTE **)( (size_t)(regs->pCurrentContext->R4) + GetOffsetOfTransitionBlock() + ArgIterator::GetThisOffset()); #else delegateCount = 0; PORTABILITY_ASSERT(""MulticastFrame::TraceFrame (frames.cpp)""); #endif int totalDelegateCount = (int)*(size_t*)(pbDel + DelegateObject::GetOffsetOfInvocationCount()); _ASSERTE( COMDelegate::IsTrueMulticastDelegate( ObjectToOBJECTREF((Object*)pbDel) ) ); if (delegateCount == totalDelegateCount) { LOG((LF_CORDB, LL_INFO1000, ""MF::TF: Executed all stubs, should return\\n"")); // We've executed all the stubs, so we should return return FALSE; } else { // We're going to execute stub delegateCount next, so go and grab it. BYTE *pbDelInvocationList = *(BYTE **)(pbDel + DelegateObject::GetOffsetOfInvocationList()); pbDel = *(BYTE**)( ((ArrayBase *)pbDelInvocationList)->GetDataPtr() + ((ArrayBase *)pbDelInvocationList)->GetComponentSize()*delegateCount); _ASSERTE(pbDel); return DelegateInvokeStubManager::TraceDelegateObject(pbDel, trace); } #endif // !DACCESS_COMPILE } #ifndef DACCESS_COMPILE VOID InlinedCallFrame::Init() { WRAPPER_NO_CONTRACT; *((TADDR *)this) = GetMethodFrameVPtr(); // GetGSCookiePtr contains a virtual call and this is a perf critical method so we don't want to call it in ret builds GSCookie *ptrGS = (GSCookie *)((BYTE *)this - sizeof(GSCookie)); _ASSERTE(ptrGS == GetGSCookiePtr()); *ptrGS = GetProcessGSCookie(); m_Datum = NULL; m_pCallSiteSP = NULL; m_pCallerReturnAddress = NULL; } #ifdef FEATURE_COMINTEROP void UnmanagedToManagedFrame::ExceptionUnwind() { WRAPPER_NO_CONTRACT; AppDomain::ExceptionUnwind(this); } #endif // FEATURE_COMINTEROP #endif // !DACCESS_COMPILE #ifdef FEATURE_COMINTEROP PCODE UnmanagedToManagedFrame::GetReturnAddress() { WRAPPER_NO_CONTRACT; PCODE pRetAddr = Frame::GetReturnAddress(); if (InlinedCallFrame::FrameHasActiveCall(m_Next) && pRetAddr == m_Next->GetReturnAddress()) { // there's actually no unmanaged code involved - we were called directly // from managed code using an InlinedCallFrame return NULL; } else { return pRetAddr; } } #endif // FEATURE_COMINTEROP #ifndef DACCESS_COMPILE //================================================================================= void FakePromote(PTR_PTR_Object ppObj, ScanContext *pSC, uint32_t dwFlags) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; CORCOMPILE_GCREFMAP_TOKENS newToken = (dwFlags & GC_CALL_INTERIOR) ? GCREFMAP_INTERIOR : GCREFMAP_REF; _ASSERTE((*(CORCOMPILE_GCREFMAP_TOKENS *)ppObj == NULL) || (*(CORCOMPILE_GCREFMAP_TOKENS *)ppObj == newToken)); *(CORCOMPILE_GCREFMAP_TOKENS *)ppObj = newToken; } //================================================================================= void FakePromoteCarefully(promote_func *fn, Object **ppObj, ScanContext *pSC, uint32_t dwFlags) { (*fn)(ppObj, pSC, dwFlags); } //================================================================================= void FakeGcScanRoots(MetaSig& msig, ArgIterator& argit, MethodDesc * pMD, BYTE * pFrame) { STANDARD_VM_CONTRACT; ScanContext sc; // Encode generic instantiation arg if (argit.HasParamType()) { // Note that intrinsic array methods have hidden instantiation arg too, but it is not reported to GC if (pMD->RequiresInstMethodDescArg()) *(CORCOMPILE_GCREFMAP_TOKENS *)(pFrame + argit.GetParamTypeArgOffset()) = GCREFMAP_METHOD_PARAM; else if (pMD->RequiresInstMethodTableArg()) *(CORCOMPILE_GCREFMAP_TOKENS *)(pFrame + argit.GetParamTypeArgOffset()) = GCREFMAP_TYPE_PARAM; } // If the function has a this pointer, add it to the mask if (argit.HasThis()) { BOOL interior = pMD->GetMethodTable()->IsValueType() && !pMD->IsUnboxingStub(); FakePromote((Object **)(pFrame + argit.GetThisOffset()), &sc, interior ? GC_CALL_INTERIOR : 0); } if (argit.IsVarArg()) { *(CORCOMPILE_GCREFMAP_TOKENS *)(pFrame + argit.GetVASigCookieOffset()) = GCREFMAP_VASIG_COOKIE; // We are done for varargs - the remaining arguments are reported via vasig cookie return; } // Also if the method has a return buffer, then it is the first argument, and could be an interior ref, // so always promote it. if (argit.HasRetBuffArg()) { FakePromote((Object **)(pFrame + argit.GetRetBuffArgOffset()), &sc, GC_CALL_INTERIOR); } // // Now iterate the arguments // // Cycle through the arguments, and call msig.GcScanRoots for each int argOffset; while ((argOffset = argit.GetNextOffset()) != TransitionBlock::InvalidOffset) { ArgDestination argDest(pFrame, argOffset, argit.GetArgLocDescForStructInRegs()); msig.GcScanRoots(&argDest, &FakePromote, &sc, &FakePromoteCarefully); } } bool CheckGCRefMapEqual(PTR_BYTE pGCRefMap, MethodDesc* pMD, bool isDispatchCell) { #ifdef _DEBUG GCRefMapBuilder gcRefMapNew; ComputeCallRefMap(pMD, &gcRefMapNew, isDispatchCell); DWORD dwFinalLength; PVOID pBlob = gcRefMapNew.GetBlob(&dwFinalLength); UINT nTokensDecoded = 0; GCRefMapDecoder decoderNew((BYTE *)pBlob); GCRefMapDecoder decoderExisting(pGCRefMap); #ifdef TARGET_X86 _ASSERTE(decoderNew.ReadStackPop() == decoderExisting.ReadStackPop()); #endif _ASSERTE(decoderNew.AtEnd() == decoderExisting.AtEnd()); while (!decoderNew.AtEnd()) { _ASSERTE(decoderNew.CurrentPos() == decoderExisting.CurrentPos()); _ASSERTE(decoderNew.ReadToken() == decoderExisting.ReadToken()); _ASSERTE(decoderNew.AtEnd() == decoderExisting.AtEnd()); } #endif return true; } void ComputeCallRefMap(MethodDesc* pMD, GCRefMapBuilder * pBuilder, bool isDispatchCell) { #ifdef _DEBUG DWORD dwInitialLength = pBuilder->GetBlobLength(); UINT nTokensWritten = 0; #endif SigTypeContext typeContext(pMD); PCCOR_SIGNATURE pSig; DWORD cbSigSize; pMD->GetSig(&pSig, &cbSigSize); MetaSig msig(pSig, cbSigSize, pMD->GetModule(), &typeContext); bool fCtorOfVariableSizedObject = msig.HasThis() && (pMD->GetMethodTable() == g_pStringClass) && pMD->IsCtor(); if (fCtorOfVariableSizedObject) { msig.ClearHasThis(); } // // Shared default interface methods (i.e. virtual interface methods with an implementation) require // an instantiation argument. But if we're in a situation where we haven't resolved the method yet // we need to pretent that unresolved default interface methods are like any other interface // methods and don't have an instantiation argument. // See code:CEEInfo::getMethodSigInternal // assert(!isDispatchCell || !pMD->RequiresInstArg() || pMD->GetMethodTable()->IsInterface()); if (pMD->RequiresInstArg() && !isDispatchCell) { msig.SetHasParamTypeArg(); } ArgIterator argit(&msig); UINT nStackBytes = argit.SizeOfFrameArgumentArray(); // Allocate a fake stack CQuickBytes qbFakeStack; qbFakeStack.AllocThrows(sizeof(TransitionBlock) + nStackBytes); memset(qbFakeStack.Ptr(), 0, qbFakeStack.Size()); BYTE * pFrame = (BYTE *)qbFakeStack.Ptr(); // Fill it in FakeGcScanRoots(msig, argit, pMD, pFrame); // // Encode the ref map // UINT nStackSlots; #ifdef TARGET_X86 UINT cbStackPop = argit.CbStackPop(); pBuilder->WriteStackPop(cbStackPop / sizeof(TADDR)); nStackSlots = nStackBytes / sizeof(TADDR) + NUM_ARGUMENT_REGISTERS; #else nStackSlots = (sizeof(TransitionBlock) + nStackBytes - TransitionBlock::GetOffsetOfFirstGCRefMapSlot()) / TARGET_POINTER_SIZE; #endif for (UINT pos = 0; pos < nStackSlots; pos++) { int ofs; #ifdef TARGET_X86 ofs = (pos < NUM_ARGUMENT_REGISTERS) ? (TransitionBlock::GetOffsetOfArgumentRegisters() + ARGUMENTREGISTERS_SIZE - (pos + 1) * sizeof(TADDR)) : (TransitionBlock::GetOffsetOfArgs() + (pos - NUM_ARGUMENT_REGISTERS) * sizeof(TADDR)); #else ofs = TransitionBlock::GetOffsetOfFirstGCRefMapSlot() + pos * TARGET_POINTER_SIZE; #endif CORCOMPILE_GCREFMAP_TOKENS token = *(CORCOMPILE_GCREFMAP_TOKENS *)(pFrame + ofs); if (token != 0) { INDEBUG(nTokensWritten++;) pBuilder->WriteToken(pos, token); } } // We are done pBuilder->Flush(); #ifdef _DEBUG // // Verify that decoder produces what got encoded // DWORD dwFinalLength; PVOID pBlob = pBuilder->GetBlob(&dwFinalLength); UINT nTokensDecoded = 0; GCRefMapDecoder decoder((BYTE *)pBlob + dwInitialLength); #ifdef TARGET_X86 _ASSERTE(decoder.ReadStackPop() * sizeof(TADDR) == cbStackPop); #endif while (!decoder.AtEnd()) { int pos = decoder.CurrentPos(); int token = decoder.ReadToken(); int ofs; #ifdef TARGET_X86 ofs = (pos < NUM_ARGUMENT_REGISTERS) ? (TransitionBlock::GetOffsetOfArgumentRegisters() + ARGUMENTREGISTERS_SIZE - (pos + 1) * sizeof(TADDR)) : (TransitionBlock::GetOffsetOfArgs() + (pos - NUM_ARGUMENT_REGISTERS) * sizeof(TADDR)); #else ofs = TransitionBlock::GetOffsetOfFirstGCRefMapSlot() + pos * TARGET_POINTER_SIZE; #endif if (token != 0) { _ASSERTE(*(CORCOMPILE_GCREFMAP_TOKENS *)(pFrame + ofs) == token); nTokensDecoded++; } } // Verify that all tokens got decoded. _ASSERTE(nTokensWritten == nTokensDecoded); #endif // _DEBUG } #endif // !DACCESS_COMPILE ",16202,True,2932.457132793162,median "[[install-config-router-default-haproxy]] = Using the Default HAProxy Router {product-author} {product-version} :data-uri: :icons: :experimental: :toc: macro :toc-title: :prewrap!: toc::[] == Overview The `oadm router` command is provided with the administrator CLI to simplify the tasks of setting up routers in a new installation. If you followed the xref:../../install_config/install/quick_install.adoc#install-config-install-quick-install[quick installation], then a default router was automatically created for you. The `oadm router` command creates the service and deployment configuration objects. Just about every form of communication between {product-title} components is secured by TLS and uses various certificates and authentication methods. Use the `--service-account` option to specify the service account the router will use to contact the master. [IMPORTANT] ==== Routers directly attach to port 80 and 443 on all interfaces on a host. Restrict routers to hosts where port 80/443 is available and not being consumed by another service, and set this using node selectors and the xref:../../admin_guide/scheduler.adoc#admin-guide-scheduler[scheduler configuration]. As an example, you can achieve this by dedicating infrastructure nodes to run services such as routers. ==== [IMPORTANT] ==== It is recommended to use separate distinct *openshift-router* service account with your router. This can be provided using the `--service-account` flag to the `oadm router` command. ifdef::openshift-enterprise[] ---- $ oadm router --dry-run --service-account=router //<1> ---- endif::[] ifdef::openshift-origin[] ---- $ oadm router --dry-run --service-account=router //<1> ---- endif::[] <1> `--service-account` is the name of a xref:../../admin_guide/service_accounts.adoc#admin-guide-service-accounts[service account] for the *openshift-router*. ifdef::openshift-origin[] It is recommended using an *openshift-router* specific service account with appropriate permissions. endif::[] ==== [IMPORTANT] ==== Router pods created using `oadm router` have default resource requests that a node must satisfy for the router pod to be deployed. In an effort to increase the reliability of infrastructure components, the default resource requests are used to increase the QoS tier of the router pods above pods without resource requests. The default values represent the observed minimum resources required for a basic router to be deployed and can be edited in the routers deployment configuration and you may want to increase them based on the load of the router. ==== [[deploy-router-create-router]] == Creating a Router The xref:../../install_config/install/quick_install.adoc#install-config-install-quick-install[quick installation] process automatically creates a default router. If the router does not exist, run the following to create a router: ifdef::openshift-enterprise[] ---- $ oadm router --replicas= --service-account=router ---- endif::[] ifdef::openshift-origin[] ---- $ oadm router --replicas= --service-account=router ---- endif::[] You can also xref:creating-router-shards[use router shards] to ensure that the router is filtered to specific namespaces or routes, or xref:../../architecture/core_concepts/routes.adoc#env-variables[set any environment variables] after router creation. [[basic-router-commands]] == Other Basic Router Commands [[deploy-router-check-default]] Checking the Default Router:: ifdef::openshift-enterprise[] The default router service account, named *router*, is automatically created during quick and advanced installations. To verify that this account already exists: endif::[] ifdef::openshift-origin[] First, ensure you have xref:../../install_config/router/index.adoc#creating-the-router-service-account[created the router service account] before deploying a router. To check if a default router, named *router*, already exists: endif::[] ifdef::openshift-enterprise[] ---- $ oadm router --dry-run --service-account=router ---- endif::[] ifdef::openshift-origin[] ---- $ oadm router --dry-run --service-account=router ---- endif::[] [[deploy-router-viewing-default]] Viewing the Default Router:: To see what the default router would look like if created: ifdef::openshift-enterprise[] ---- $ oadm router -o yaml --service-account=router ---- endif::[] ifdef::openshift-origin[] ---- $ oadm router -o yaml --service-account=router ---- endif::[] [[deploy-router-to-labeled-nodes]] Deploying the Router to a Labeled Node:: To deploy the router to any node(s) that match a specified xref:../../admin_guide/manage_nodes.adoc#updating-labels-on-nodes[node label]: ifdef::openshift-enterprise[] ---- $ oadm router --replicas= --selector=